multi.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include <curl/curl.h>
  26. #include "urldata.h"
  27. #include "transfer.h"
  28. #include "url.h"
  29. #include "cfilters.h"
  30. #include "connect.h"
  31. #include "progress.h"
  32. #include "easyif.h"
  33. #include "share.h"
  34. #include "psl.h"
  35. #include "multiif.h"
  36. #include "sendf.h"
  37. #include "timeval.h"
  38. #include "http.h"
  39. #include "select.h"
  40. #include "warnless.h"
  41. #include "speedcheck.h"
  42. #include "conncache.h"
  43. #include "multihandle.h"
  44. #include "sigpipe.h"
  45. #include "vtls/vtls.h"
  46. #include "http_proxy.h"
  47. #include "http2.h"
  48. #include "socketpair.h"
  49. #include "socks.h"
  50. /* The last 3 #include files should be in this order */
  51. #include "curl_printf.h"
  52. #include "curl_memory.h"
  53. #include "memdebug.h"
  54. #ifdef __APPLE__
  55. #define wakeup_write write
  56. #define wakeup_read read
  57. #define wakeup_close close
  58. #define wakeup_create pipe
  59. #else /* __APPLE__ */
  60. #define wakeup_write swrite
  61. #define wakeup_read sread
  62. #define wakeup_close sclose
  63. #define wakeup_create(p) Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, p)
  64. #endif /* __APPLE__ */
  65. /*
  66. CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
  67. to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
  68. CURL handle takes 45-50 K memory, therefore this 3K are not significant.
  69. */
  70. #ifndef CURL_SOCKET_HASH_TABLE_SIZE
  71. #define CURL_SOCKET_HASH_TABLE_SIZE 911
  72. #endif
  73. #ifndef CURL_CONNECTION_HASH_SIZE
  74. #define CURL_CONNECTION_HASH_SIZE 97
  75. #endif
  76. #ifndef CURL_DNS_HASH_SIZE
  77. #define CURL_DNS_HASH_SIZE 71
  78. #endif
  79. #define CURL_MULTI_HANDLE 0x000bab1e
  80. #ifdef DEBUGBUILD
  81. /* On a debug build, we want to fail hard on multi handles that
  82. * are not NULL, but no longer have the MAGIC touch. This gives
  83. * us early warning on things only discovered by valgrind otherwise. */
  84. #define GOOD_MULTI_HANDLE(x) \
  85. (((x) && (x)->magic == CURL_MULTI_HANDLE)? TRUE: \
  86. (DEBUGASSERT(!(x)), FALSE))
  87. #else
  88. #define GOOD_MULTI_HANDLE(x) \
  89. ((x) && (x)->magic == CURL_MULTI_HANDLE)
  90. #endif
  91. static CURLMcode singlesocket(struct Curl_multi *multi,
  92. struct Curl_easy *data);
  93. static CURLMcode add_next_timeout(struct curltime now,
  94. struct Curl_multi *multi,
  95. struct Curl_easy *d);
  96. static CURLMcode multi_timeout(struct Curl_multi *multi,
  97. long *timeout_ms);
  98. static void process_pending_handles(struct Curl_multi *multi);
  99. #ifdef DEBUGBUILD
  100. static const char * const multi_statename[]={
  101. "INIT",
  102. "PENDING",
  103. "CONNECT",
  104. "RESOLVING",
  105. "CONNECTING",
  106. "TUNNELING",
  107. "PROTOCONNECT",
  108. "PROTOCONNECTING",
  109. "DO",
  110. "DOING",
  111. "DOING_MORE",
  112. "DID",
  113. "PERFORMING",
  114. "RATELIMITING",
  115. "DONE",
  116. "COMPLETED",
  117. "MSGSENT",
  118. };
  119. #endif
  120. /* function pointer called once when switching TO a state */
  121. typedef void (*init_multistate_func)(struct Curl_easy *data);
  122. /* called in DID state, before PERFORMING state */
  123. static void before_perform(struct Curl_easy *data)
  124. {
  125. data->req.chunk = FALSE;
  126. Curl_pgrsTime(data, TIMER_PRETRANSFER);
  127. }
  128. static void init_completed(struct Curl_easy *data)
  129. {
  130. /* this is a completed transfer */
  131. /* Important: reset the conn pointer so that we don't point to memory
  132. that could be freed anytime */
  133. Curl_detach_connection(data);
  134. Curl_expire_clear(data); /* stop all timers */
  135. }
  136. /* always use this function to change state, to make debugging easier */
  137. static void mstate(struct Curl_easy *data, CURLMstate state
  138. #ifdef DEBUGBUILD
  139. , int lineno
  140. #endif
  141. )
  142. {
  143. CURLMstate oldstate = data->mstate;
  144. static const init_multistate_func finit[MSTATE_LAST] = {
  145. NULL, /* INIT */
  146. NULL, /* PENDING */
  147. Curl_init_CONNECT, /* CONNECT */
  148. NULL, /* RESOLVING */
  149. NULL, /* CONNECTING */
  150. NULL, /* TUNNELING */
  151. NULL, /* PROTOCONNECT */
  152. NULL, /* PROTOCONNECTING */
  153. NULL, /* DO */
  154. NULL, /* DOING */
  155. NULL, /* DOING_MORE */
  156. before_perform, /* DID */
  157. NULL, /* PERFORMING */
  158. NULL, /* RATELIMITING */
  159. NULL, /* DONE */
  160. init_completed, /* COMPLETED */
  161. NULL /* MSGSENT */
  162. };
  163. #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
  164. (void) lineno;
  165. #endif
  166. if(oldstate == state)
  167. /* don't bother when the new state is the same as the old state */
  168. return;
  169. data->mstate = state;
  170. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  171. if(data->mstate >= MSTATE_PENDING &&
  172. data->mstate < MSTATE_COMPLETED) {
  173. infof(data,
  174. "STATE: %s => %s handle %p; line %d",
  175. multi_statename[oldstate], multi_statename[data->mstate],
  176. (void *)data, lineno);
  177. }
  178. #endif
  179. if(state == MSTATE_COMPLETED) {
  180. /* changing to COMPLETED means there's one less easy handle 'alive' */
  181. DEBUGASSERT(data->multi->num_alive > 0);
  182. data->multi->num_alive--;
  183. }
  184. /* if this state has an init-function, run it */
  185. if(finit[state])
  186. finit[state](data);
  187. }
  188. #ifndef DEBUGBUILD
  189. #define multistate(x,y) mstate(x,y)
  190. #else
  191. #define multistate(x,y) mstate(x,y, __LINE__)
  192. #endif
  193. /*
  194. * We add one of these structs to the sockhash for each socket
  195. */
  196. struct Curl_sh_entry {
  197. struct Curl_hash transfers; /* hash of transfers using this socket */
  198. unsigned int action; /* what combined action READ/WRITE this socket waits
  199. for */
  200. unsigned int users; /* number of transfers using this */
  201. void *socketp; /* settable by users with curl_multi_assign() */
  202. unsigned int readers; /* this many transfers want to read */
  203. unsigned int writers; /* this many transfers want to write */
  204. };
  205. /* bits for 'action' having no bits means this socket is not expecting any
  206. action */
  207. #define SH_READ 1
  208. #define SH_WRITE 2
  209. /* look up a given socket in the socket hash, skip invalid sockets */
  210. static struct Curl_sh_entry *sh_getentry(struct Curl_hash *sh,
  211. curl_socket_t s)
  212. {
  213. if(s != CURL_SOCKET_BAD) {
  214. /* only look for proper sockets */
  215. return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
  216. }
  217. return NULL;
  218. }
  219. #define TRHASH_SIZE 13
  220. static size_t trhash(void *key, size_t key_length, size_t slots_num)
  221. {
  222. size_t keyval = (size_t)*(struct Curl_easy **)key;
  223. (void) key_length;
  224. return (keyval % slots_num);
  225. }
  226. static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
  227. {
  228. (void)k1_len;
  229. (void)k2_len;
  230. return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2;
  231. }
  232. static void trhash_dtor(void *nada)
  233. {
  234. (void)nada;
  235. }
  236. /*
  237. * The sockhash has its own separate subhash in each entry that need to be
  238. * safely destroyed first.
  239. */
  240. static void sockhash_destroy(struct Curl_hash *h)
  241. {
  242. struct Curl_hash_iterator iter;
  243. struct Curl_hash_element *he;
  244. DEBUGASSERT(h);
  245. Curl_hash_start_iterate(h, &iter);
  246. he = Curl_hash_next_element(&iter);
  247. while(he) {
  248. struct Curl_sh_entry *sh = (struct Curl_sh_entry *)he->ptr;
  249. Curl_hash_destroy(&sh->transfers);
  250. he = Curl_hash_next_element(&iter);
  251. }
  252. Curl_hash_destroy(h);
  253. }
  254. /* make sure this socket is present in the hash for this handle */
  255. static struct Curl_sh_entry *sh_addentry(struct Curl_hash *sh,
  256. curl_socket_t s)
  257. {
  258. struct Curl_sh_entry *there = sh_getentry(sh, s);
  259. struct Curl_sh_entry *check;
  260. if(there) {
  261. /* it is present, return fine */
  262. return there;
  263. }
  264. /* not present, add it */
  265. check = calloc(1, sizeof(struct Curl_sh_entry));
  266. if(!check)
  267. return NULL; /* major failure */
  268. Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash, trhash_compare,
  269. trhash_dtor);
  270. /* make/add new hash entry */
  271. if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
  272. Curl_hash_destroy(&check->transfers);
  273. free(check);
  274. return NULL; /* major failure */
  275. }
  276. return check; /* things are good in sockhash land */
  277. }
  278. /* delete the given socket + handle from the hash */
  279. static void sh_delentry(struct Curl_sh_entry *entry,
  280. struct Curl_hash *sh, curl_socket_t s)
  281. {
  282. Curl_hash_destroy(&entry->transfers);
  283. /* We remove the hash entry. This will end up in a call to
  284. sh_freeentry(). */
  285. Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
  286. }
  287. /*
  288. * free a sockhash entry
  289. */
  290. static void sh_freeentry(void *freethis)
  291. {
  292. struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
  293. free(p);
  294. }
  295. static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
  296. {
  297. (void) k1_len; (void) k2_len;
  298. return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2));
  299. }
  300. static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
  301. {
  302. curl_socket_t fd = *((curl_socket_t *) key);
  303. (void) key_length;
  304. return (fd % slots_num);
  305. }
  306. /*
  307. * sh_init() creates a new socket hash and returns the handle for it.
  308. *
  309. * Quote from README.multi_socket:
  310. *
  311. * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
  312. * is somewhat of a bottle neck. Its current implementation may be a bit too
  313. * limiting. It simply has a fixed-size array, and on each entry in the array
  314. * it has a linked list with entries. So the hash only checks which list to
  315. * scan through. The code I had used so for used a list with merely 7 slots
  316. * (as that is what the DNS hash uses) but with 7000 connections that would
  317. * make an average of 1000 nodes in each list to run through. I upped that to
  318. * 97 slots (I believe a prime is suitable) and noticed a significant speed
  319. * increase. I need to reconsider the hash implementation or use a rather
  320. * large default value like this. At 9000 connections I was still below 10us
  321. * per call."
  322. *
  323. */
  324. static void sh_init(struct Curl_hash *hash, int hashsize)
  325. {
  326. Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
  327. sh_freeentry);
  328. }
  329. /*
  330. * multi_addmsg()
  331. *
  332. * Called when a transfer is completed. Adds the given msg pointer to
  333. * the list kept in the multi handle.
  334. */
  335. static void multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg)
  336. {
  337. Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg,
  338. &msg->list);
  339. }
  340. struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
  341. int chashsize, /* connection hash */
  342. int dnssize) /* dns hash */
  343. {
  344. struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
  345. if(!multi)
  346. return NULL;
  347. multi->magic = CURL_MULTI_HANDLE;
  348. Curl_init_dnscache(&multi->hostcache, dnssize);
  349. sh_init(&multi->sockhash, hashsize);
  350. if(Curl_conncache_init(&multi->conn_cache, chashsize))
  351. goto error;
  352. Curl_llist_init(&multi->msglist, NULL);
  353. Curl_llist_init(&multi->pending, NULL);
  354. Curl_llist_init(&multi->msgsent, NULL);
  355. multi->multiplexing = TRUE;
  356. /* -1 means it not set by user, use the default value */
  357. multi->maxconnects = -1;
  358. multi->max_concurrent_streams = 100;
  359. #ifdef USE_WINSOCK
  360. multi->wsa_event = WSACreateEvent();
  361. if(multi->wsa_event == WSA_INVALID_EVENT)
  362. goto error;
  363. #else
  364. #ifdef ENABLE_WAKEUP
  365. if(wakeup_create(multi->wakeup_pair) < 0) {
  366. multi->wakeup_pair[0] = CURL_SOCKET_BAD;
  367. multi->wakeup_pair[1] = CURL_SOCKET_BAD;
  368. }
  369. else if(curlx_nonblock(multi->wakeup_pair[0], TRUE) < 0 ||
  370. curlx_nonblock(multi->wakeup_pair[1], TRUE) < 0) {
  371. wakeup_close(multi->wakeup_pair[0]);
  372. wakeup_close(multi->wakeup_pair[1]);
  373. multi->wakeup_pair[0] = CURL_SOCKET_BAD;
  374. multi->wakeup_pair[1] = CURL_SOCKET_BAD;
  375. }
  376. #endif
  377. #endif
  378. return multi;
  379. error:
  380. sockhash_destroy(&multi->sockhash);
  381. Curl_hash_destroy(&multi->hostcache);
  382. Curl_conncache_destroy(&multi->conn_cache);
  383. free(multi);
  384. return NULL;
  385. }
  386. struct Curl_multi *curl_multi_init(void)
  387. {
  388. return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
  389. CURL_CONNECTION_HASH_SIZE,
  390. CURL_DNS_HASH_SIZE);
  391. }
  392. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  393. static void multi_warn_debug(struct Curl_multi *multi, struct Curl_easy *data)
  394. {
  395. if(!multi->warned) {
  396. infof(data, "!!! WARNING !!!");
  397. infof(data, "This is a debug build of libcurl, "
  398. "do not use in production.");
  399. multi->warned = true;
  400. }
  401. }
  402. #else
  403. #define multi_warn_debug(x,y) Curl_nop_stmt
  404. #endif
  405. /* returns TRUE if the easy handle is supposed to be present in the main link
  406. list */
  407. static bool in_main_list(struct Curl_easy *data)
  408. {
  409. return ((data->mstate != MSTATE_PENDING) &&
  410. (data->mstate != MSTATE_MSGSENT));
  411. }
  412. static void link_easy(struct Curl_multi *multi,
  413. struct Curl_easy *data)
  414. {
  415. /* We add the new easy entry last in the list. */
  416. data->next = NULL; /* end of the line */
  417. if(multi->easyp) {
  418. struct Curl_easy *last = multi->easylp;
  419. last->next = data;
  420. data->prev = last;
  421. multi->easylp = data; /* the new last node */
  422. }
  423. else {
  424. /* first node, make prev NULL! */
  425. data->prev = NULL;
  426. multi->easylp = multi->easyp = data; /* both first and last */
  427. }
  428. }
  429. /* unlink the given easy handle from the linked list of easy handles */
  430. static void unlink_easy(struct Curl_multi *multi,
  431. struct Curl_easy *data)
  432. {
  433. /* make the previous node point to our next */
  434. if(data->prev)
  435. data->prev->next = data->next;
  436. else
  437. multi->easyp = data->next; /* point to first node */
  438. /* make our next point to our previous node */
  439. if(data->next)
  440. data->next->prev = data->prev;
  441. else
  442. multi->easylp = data->prev; /* point to last node */
  443. data->prev = data->next = NULL;
  444. }
  445. CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
  446. struct Curl_easy *data)
  447. {
  448. CURLMcode rc;
  449. /* First, make some basic checks that the CURLM handle is a good handle */
  450. if(!GOOD_MULTI_HANDLE(multi))
  451. return CURLM_BAD_HANDLE;
  452. /* Verify that we got a somewhat good easy handle too */
  453. if(!GOOD_EASY_HANDLE(data))
  454. return CURLM_BAD_EASY_HANDLE;
  455. /* Prevent users from adding same easy handle more than once and prevent
  456. adding to more than one multi stack */
  457. if(data->multi)
  458. return CURLM_ADDED_ALREADY;
  459. if(multi->in_callback)
  460. return CURLM_RECURSIVE_API_CALL;
  461. if(multi->dead) {
  462. /* a "dead" handle cannot get added transfers while any existing easy
  463. handles are still alive - but if there are none alive anymore, it is
  464. fine to start over and unmark the "deadness" of this handle */
  465. if(multi->num_alive)
  466. return CURLM_ABORTED_BY_CALLBACK;
  467. multi->dead = FALSE;
  468. }
  469. /* Initialize timeout list for this handle */
  470. Curl_llist_init(&data->state.timeoutlist, NULL);
  471. /*
  472. * No failure allowed in this function beyond this point. And no
  473. * modification of easy nor multi handle allowed before this except for
  474. * potential multi's connection cache growing which won't be undone in this
  475. * function no matter what.
  476. */
  477. if(data->set.errorbuffer)
  478. data->set.errorbuffer[0] = 0;
  479. /* make the Curl_easy refer back to this multi handle - before Curl_expire()
  480. is called. */
  481. data->multi = multi;
  482. /* Set the timeout for this handle to expire really soon so that it will
  483. be taken care of even when this handle is added in the midst of operation
  484. when only the curl_multi_socket() API is used. During that flow, only
  485. sockets that time-out or have actions will be dealt with. Since this
  486. handle has no action yet, we make sure it times out to get things to
  487. happen. */
  488. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  489. /* A somewhat crude work-around for a little glitch in Curl_update_timer()
  490. that happens if the lastcall time is set to the same time when the handle
  491. is removed as when the next handle is added, as then the check in
  492. Curl_update_timer() that prevents calling the application multiple times
  493. with the same timer info will not trigger and then the new handle's
  494. timeout will not be notified to the app.
  495. The work-around is thus simply to clear the 'lastcall' variable to force
  496. Curl_update_timer() to always trigger a callback to the app when a new
  497. easy handle is added */
  498. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  499. rc = Curl_update_timer(multi);
  500. if(rc)
  501. return rc;
  502. /* set the easy handle */
  503. multistate(data, MSTATE_INIT);
  504. /* for multi interface connections, we share DNS cache automatically if the
  505. easy handle's one is currently not set. */
  506. if(!data->dns.hostcache ||
  507. (data->dns.hostcachetype == HCACHE_NONE)) {
  508. data->dns.hostcache = &multi->hostcache;
  509. data->dns.hostcachetype = HCACHE_MULTI;
  510. }
  511. /* Point to the shared or multi handle connection cache */
  512. if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT)))
  513. data->state.conn_cache = &data->share->conn_cache;
  514. else
  515. data->state.conn_cache = &multi->conn_cache;
  516. data->state.lastconnect_id = -1;
  517. #ifdef USE_LIBPSL
  518. /* Do the same for PSL. */
  519. if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL)))
  520. data->psl = &data->share->psl;
  521. else
  522. data->psl = &multi->psl;
  523. #endif
  524. link_easy(multi, data);
  525. /* increase the node-counter */
  526. multi->num_easy++;
  527. /* increase the alive-counter */
  528. multi->num_alive++;
  529. CONNCACHE_LOCK(data);
  530. /* The closure handle only ever has default timeouts set. To improve the
  531. state somewhat we clone the timeouts from each added handle so that the
  532. closure handle always has the same timeouts as the most recently added
  533. easy handle. */
  534. data->state.conn_cache->closure_handle->set.timeout = data->set.timeout;
  535. data->state.conn_cache->closure_handle->set.server_response_timeout =
  536. data->set.server_response_timeout;
  537. data->state.conn_cache->closure_handle->set.no_signal =
  538. data->set.no_signal;
  539. data->id = data->state.conn_cache->next_easy_id++;
  540. if(data->state.conn_cache->next_easy_id <= 0)
  541. data->state.conn_cache->next_easy_id = 0;
  542. CONNCACHE_UNLOCK(data);
  543. multi_warn_debug(multi, data);
  544. return CURLM_OK;
  545. }
  546. #if 0
  547. /* Debug-function, used like this:
  548. *
  549. * Curl_hash_print(&multi->sockhash, debug_print_sock_hash);
  550. *
  551. * Enable the hash print function first by editing hash.c
  552. */
  553. static void debug_print_sock_hash(void *p)
  554. {
  555. struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
  556. fprintf(stderr, " [readers %u][writers %u]",
  557. sh->readers, sh->writers);
  558. }
  559. #endif
  560. static CURLcode multi_done(struct Curl_easy *data,
  561. CURLcode status, /* an error if this is called
  562. after an error was detected */
  563. bool premature)
  564. {
  565. CURLcode result;
  566. struct connectdata *conn = data->conn;
  567. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  568. DEBUGF(infof(data, "multi_done[%s]: status: %d prem: %d done: %d",
  569. multi_statename[data->mstate],
  570. (int)status, (int)premature, data->state.done));
  571. #else
  572. DEBUGF(infof(data, "multi_done: status: %d prem: %d done: %d",
  573. (int)status, (int)premature, data->state.done));
  574. #endif
  575. if(data->state.done)
  576. /* Stop if multi_done() has already been called */
  577. return CURLE_OK;
  578. /* Stop the resolver and free its own resources (but not dns_entry yet). */
  579. Curl_resolver_kill(data);
  580. /* Cleanup possible redirect junk */
  581. Curl_safefree(data->req.newurl);
  582. Curl_safefree(data->req.location);
  583. switch(status) {
  584. case CURLE_ABORTED_BY_CALLBACK:
  585. case CURLE_READ_ERROR:
  586. case CURLE_WRITE_ERROR:
  587. /* When we're aborted due to a callback return code it basically have to
  588. be counted as premature as there is trouble ahead if we don't. We have
  589. many callbacks and protocols work differently, we could potentially do
  590. this more fine-grained in the future. */
  591. premature = TRUE;
  592. default:
  593. break;
  594. }
  595. /* this calls the protocol-specific function pointer previously set */
  596. if(conn->handler->done)
  597. result = conn->handler->done(data, status, premature);
  598. else
  599. result = status;
  600. if(CURLE_ABORTED_BY_CALLBACK != result) {
  601. /* avoid this if we already aborted by callback to avoid this calling
  602. another callback */
  603. int rc = Curl_pgrsDone(data);
  604. if(!result && rc)
  605. result = CURLE_ABORTED_BY_CALLBACK;
  606. }
  607. /* Inform connection filters that this transfer is done */
  608. Curl_conn_ev_data_done(data, premature);
  609. process_pending_handles(data->multi); /* connection / multiplex */
  610. Curl_safefree(data->state.ulbuf);
  611. Curl_client_cleanup(data);
  612. CONNCACHE_LOCK(data);
  613. Curl_detach_connection(data);
  614. if(CONN_INUSE(conn)) {
  615. /* Stop if still used. */
  616. CONNCACHE_UNLOCK(data);
  617. DEBUGF(infof(data, "Connection still in use %zu, "
  618. "no more multi_done now!",
  619. conn->easyq.size));
  620. return CURLE_OK;
  621. }
  622. data->state.done = TRUE; /* called just now! */
  623. if(conn->dns_entry) {
  624. Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
  625. conn->dns_entry = NULL;
  626. }
  627. Curl_hostcache_prune(data);
  628. /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
  629. forced us to close this connection. This is ignored for requests taking
  630. place in a NTLM/NEGOTIATE authentication handshake
  631. if conn->bits.close is TRUE, it means that the connection should be
  632. closed in spite of all our efforts to be nice, due to protocol
  633. restrictions in our or the server's end
  634. if premature is TRUE, it means this connection was said to be DONE before
  635. the entire request operation is complete and thus we can't know in what
  636. state it is for reusing, so we're forced to close it. In a perfect world
  637. we can add code that keep track of if we really must close it here or not,
  638. but currently we have no such detail knowledge.
  639. */
  640. data->state.recent_conn_id = conn->connection_id;
  641. if((data->set.reuse_forbid
  642. #if defined(USE_NTLM)
  643. && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 ||
  644. conn->proxy_ntlm_state == NTLMSTATE_TYPE2)
  645. #endif
  646. #if defined(USE_SPNEGO)
  647. && !(conn->http_negotiate_state == GSS_AUTHRECV ||
  648. conn->proxy_negotiate_state == GSS_AUTHRECV)
  649. #endif
  650. ) || conn->bits.close
  651. || (premature && !Curl_conn_is_multiplex(conn, FIRSTSOCKET))) {
  652. DEBUGF(infof(data, "multi_done, not reusing connection=%"
  653. CURL_FORMAT_CURL_OFF_T ", forbid=%d"
  654. ", close=%d, premature=%d, conn_multiplex=%d",
  655. conn->connection_id,
  656. data->set.reuse_forbid, conn->bits.close, premature,
  657. Curl_conn_is_multiplex(conn, FIRSTSOCKET)));
  658. connclose(conn, "disconnecting");
  659. Curl_conncache_remove_conn(data, conn, FALSE);
  660. CONNCACHE_UNLOCK(data);
  661. Curl_disconnect(data, conn, premature);
  662. }
  663. else {
  664. char buffer[256];
  665. const char *host =
  666. #ifndef CURL_DISABLE_PROXY
  667. conn->bits.socksproxy ?
  668. conn->socks_proxy.host.dispname :
  669. conn->bits.httpproxy ? conn->http_proxy.host.dispname :
  670. #endif
  671. conn->bits.conn_to_host ? conn->conn_to_host.dispname :
  672. conn->host.dispname;
  673. /* create string before returning the connection */
  674. curl_off_t connection_id = conn->connection_id;
  675. msnprintf(buffer, sizeof(buffer),
  676. "Connection #%" CURL_FORMAT_CURL_OFF_T " to host %s left intact",
  677. connection_id, host);
  678. /* the connection is no longer in use by this transfer */
  679. CONNCACHE_UNLOCK(data);
  680. if(Curl_conncache_return_conn(data, conn)) {
  681. /* remember the most recently used connection */
  682. data->state.lastconnect_id = connection_id;
  683. data->state.recent_conn_id = connection_id;
  684. infof(data, "%s", buffer);
  685. }
  686. else
  687. data->state.lastconnect_id = -1;
  688. }
  689. Curl_safefree(data->state.buffer);
  690. return result;
  691. }
  692. static int close_connect_only(struct Curl_easy *data,
  693. struct connectdata *conn, void *param)
  694. {
  695. (void)param;
  696. if(data->state.lastconnect_id != conn->connection_id)
  697. return 0;
  698. if(!conn->connect_only)
  699. return 1;
  700. connclose(conn, "Removing connect-only easy handle");
  701. return 1;
  702. }
  703. CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
  704. struct Curl_easy *data)
  705. {
  706. struct Curl_easy *easy = data;
  707. bool premature;
  708. struct Curl_llist_element *e;
  709. CURLMcode rc;
  710. /* First, make some basic checks that the CURLM handle is a good handle */
  711. if(!GOOD_MULTI_HANDLE(multi))
  712. return CURLM_BAD_HANDLE;
  713. /* Verify that we got a somewhat good easy handle too */
  714. if(!GOOD_EASY_HANDLE(data))
  715. return CURLM_BAD_EASY_HANDLE;
  716. /* Prevent users from trying to remove same easy handle more than once */
  717. if(!data->multi)
  718. return CURLM_OK; /* it is already removed so let's say it is fine! */
  719. /* Prevent users from trying to remove an easy handle from the wrong multi */
  720. if(data->multi != multi)
  721. return CURLM_BAD_EASY_HANDLE;
  722. if(multi->in_callback)
  723. return CURLM_RECURSIVE_API_CALL;
  724. premature = (data->mstate < MSTATE_COMPLETED) ? TRUE : FALSE;
  725. /* If the 'state' is not INIT or COMPLETED, we might need to do something
  726. nice to put the easy_handle in a good known state when this returns. */
  727. if(premature) {
  728. /* this handle is "alive" so we need to count down the total number of
  729. alive connections when this is removed */
  730. multi->num_alive--;
  731. }
  732. if(data->conn &&
  733. data->mstate > MSTATE_DO &&
  734. data->mstate < MSTATE_COMPLETED) {
  735. /* Set connection owner so that the DONE function closes it. We can
  736. safely do this here since connection is killed. */
  737. streamclose(data->conn, "Removed with partial response");
  738. }
  739. if(data->conn) {
  740. /* multi_done() clears the association between the easy handle and the
  741. connection.
  742. Note that this ignores the return code simply because there's
  743. nothing really useful to do with it anyway! */
  744. (void)multi_done(data, data->result, premature);
  745. }
  746. /* The timer must be shut down before data->multi is set to NULL, else the
  747. timenode will remain in the splay tree after curl_easy_cleanup is
  748. called. Do it after multi_done() in case that sets another time! */
  749. Curl_expire_clear(data);
  750. if(data->connect_queue.ptr) {
  751. /* the handle is in the pending or msgsent lists, so go ahead and remove
  752. it */
  753. if(data->mstate == MSTATE_PENDING)
  754. Curl_llist_remove(&multi->pending, &data->connect_queue, NULL);
  755. else
  756. Curl_llist_remove(&multi->msgsent, &data->connect_queue, NULL);
  757. }
  758. if(in_main_list(data))
  759. unlink_easy(multi, data);
  760. if(data->dns.hostcachetype == HCACHE_MULTI) {
  761. /* stop using the multi handle's DNS cache, *after* the possible
  762. multi_done() call above */
  763. data->dns.hostcache = NULL;
  764. data->dns.hostcachetype = HCACHE_NONE;
  765. }
  766. Curl_wildcard_dtor(&data->wildcard);
  767. /* change state without using multistate(), only to make singlesocket() do
  768. what we want */
  769. data->mstate = MSTATE_COMPLETED;
  770. /* This ignores the return code even in case of problems because there's
  771. nothing more to do about that, here */
  772. (void)singlesocket(multi, easy); /* to let the application know what sockets
  773. that vanish with this handle */
  774. /* Remove the association between the connection and the handle */
  775. Curl_detach_connection(data);
  776. if(data->set.connect_only && !data->multi_easy) {
  777. /* This removes a handle that was part the multi interface that used
  778. CONNECT_ONLY, that connection is now left alive but since this handle
  779. has bits.close set nothing can use that transfer anymore and it is
  780. forbidden from reuse. And this easy handle cannot find the connection
  781. anymore once removed from the multi handle
  782. Better close the connection here, at once.
  783. */
  784. struct connectdata *c;
  785. curl_socket_t s;
  786. s = Curl_getconnectinfo(data, &c);
  787. if((s != CURL_SOCKET_BAD) && c) {
  788. Curl_conncache_remove_conn(data, c, TRUE);
  789. Curl_disconnect(data, c, TRUE);
  790. }
  791. }
  792. if(data->state.lastconnect_id != -1) {
  793. /* Mark any connect-only connection for closure */
  794. Curl_conncache_foreach(data, data->state.conn_cache,
  795. NULL, close_connect_only);
  796. }
  797. #ifdef USE_LIBPSL
  798. /* Remove the PSL association. */
  799. if(data->psl == &multi->psl)
  800. data->psl = NULL;
  801. #endif
  802. /* as this was using a shared connection cache we clear the pointer to that
  803. since we're not part of that multi handle anymore */
  804. data->state.conn_cache = NULL;
  805. data->multi = NULL; /* clear the association to this multi handle */
  806. /* make sure there's no pending message in the queue sent from this easy
  807. handle */
  808. for(e = multi->msglist.head; e; e = e->next) {
  809. struct Curl_message *msg = e->ptr;
  810. if(msg->extmsg.easy_handle == easy) {
  811. Curl_llist_remove(&multi->msglist, e, NULL);
  812. /* there can only be one from this specific handle */
  813. break;
  814. }
  815. }
  816. /* NOTE NOTE NOTE
  817. We do not touch the easy handle here! */
  818. multi->num_easy--; /* one less to care about now */
  819. process_pending_handles(multi);
  820. rc = Curl_update_timer(multi);
  821. if(rc)
  822. return rc;
  823. return CURLM_OK;
  824. }
  825. /* Return TRUE if the application asked for multiplexing */
  826. bool Curl_multiplex_wanted(const struct Curl_multi *multi)
  827. {
  828. return (multi && (multi->multiplexing));
  829. }
  830. /*
  831. * Curl_detach_connection() removes the given transfer from the connection.
  832. *
  833. * This is the only function that should clear data->conn. This will
  834. * occasionally be called with the data->conn pointer already cleared.
  835. */
  836. void Curl_detach_connection(struct Curl_easy *data)
  837. {
  838. struct connectdata *conn = data->conn;
  839. if(conn) {
  840. Curl_conn_ev_data_detach(conn, data);
  841. Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL);
  842. }
  843. data->conn = NULL;
  844. }
  845. /*
  846. * Curl_attach_connection() attaches this transfer to this connection.
  847. *
  848. * This is the only function that should assign data->conn
  849. */
  850. void Curl_attach_connection(struct Curl_easy *data,
  851. struct connectdata *conn)
  852. {
  853. DEBUGASSERT(!data->conn);
  854. DEBUGASSERT(conn);
  855. data->conn = conn;
  856. Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data,
  857. &data->conn_queue);
  858. if(conn->handler && conn->handler->attach)
  859. conn->handler->attach(data, conn);
  860. Curl_conn_ev_data_attach(conn, data);
  861. }
  862. static int domore_getsock(struct Curl_easy *data,
  863. struct connectdata *conn,
  864. curl_socket_t *socks)
  865. {
  866. if(conn && conn->handler->domore_getsock)
  867. return conn->handler->domore_getsock(data, conn, socks);
  868. return GETSOCK_BLANK;
  869. }
  870. static int doing_getsock(struct Curl_easy *data,
  871. struct connectdata *conn,
  872. curl_socket_t *socks)
  873. {
  874. if(conn && conn->handler->doing_getsock)
  875. return conn->handler->doing_getsock(data, conn, socks);
  876. return GETSOCK_BLANK;
  877. }
  878. static int protocol_getsock(struct Curl_easy *data,
  879. struct connectdata *conn,
  880. curl_socket_t *socks)
  881. {
  882. if(conn->handler->proto_getsock)
  883. return conn->handler->proto_getsock(data, conn, socks);
  884. return Curl_conn_get_select_socks(data, FIRSTSOCKET, socks);
  885. }
  886. /* returns bitmapped flags for this handle and its sockets. The 'socks[]'
  887. array contains MAX_SOCKSPEREASYHANDLE entries. */
  888. static int multi_getsock(struct Curl_easy *data,
  889. curl_socket_t *socks)
  890. {
  891. struct connectdata *conn = data->conn;
  892. /* The no connection case can happen when this is called from
  893. curl_multi_remove_handle() => singlesocket() => multi_getsock().
  894. */
  895. if(!conn)
  896. return 0;
  897. switch(data->mstate) {
  898. default:
  899. return 0;
  900. case MSTATE_RESOLVING:
  901. return Curl_resolv_getsock(data, socks);
  902. case MSTATE_PROTOCONNECTING:
  903. case MSTATE_PROTOCONNECT:
  904. return protocol_getsock(data, conn, socks);
  905. case MSTATE_DO:
  906. case MSTATE_DOING:
  907. return doing_getsock(data, conn, socks);
  908. case MSTATE_TUNNELING:
  909. case MSTATE_CONNECTING:
  910. return Curl_conn_get_select_socks(data, FIRSTSOCKET, socks);
  911. case MSTATE_DOING_MORE:
  912. return domore_getsock(data, conn, socks);
  913. case MSTATE_DID: /* since is set after DO is completed, we switch to
  914. waiting for the same as the PERFORMING state */
  915. case MSTATE_PERFORMING:
  916. return Curl_single_getsock(data, conn, socks);
  917. }
  918. }
  919. CURLMcode curl_multi_fdset(struct Curl_multi *multi,
  920. fd_set *read_fd_set, fd_set *write_fd_set,
  921. fd_set *exc_fd_set, int *max_fd)
  922. {
  923. /* Scan through all the easy handles to get the file descriptors set.
  924. Some easy handles may not have connected to the remote host yet,
  925. and then we must make sure that is done. */
  926. struct Curl_easy *data;
  927. int this_max_fd = -1;
  928. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  929. int i;
  930. (void)exc_fd_set; /* not used */
  931. if(!GOOD_MULTI_HANDLE(multi))
  932. return CURLM_BAD_HANDLE;
  933. if(multi->in_callback)
  934. return CURLM_RECURSIVE_API_CALL;
  935. for(data = multi->easyp; data; data = data->next) {
  936. int bitmap;
  937. #ifdef __clang_analyzer_
  938. /* to prevent "The left operand of '>=' is a garbage value" warnings */
  939. memset(sockbunch, 0, sizeof(sockbunch));
  940. #endif
  941. bitmap = multi_getsock(data, sockbunch);
  942. for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  943. if((bitmap & GETSOCK_MASK_RW(i)) && VALID_SOCK((sockbunch[i]))) {
  944. if(!FDSET_SOCK(sockbunch[i]))
  945. /* pretend it doesn't exist */
  946. continue;
  947. if(bitmap & GETSOCK_READSOCK(i))
  948. FD_SET(sockbunch[i], read_fd_set);
  949. if(bitmap & GETSOCK_WRITESOCK(i))
  950. FD_SET(sockbunch[i], write_fd_set);
  951. if((int)sockbunch[i] > this_max_fd)
  952. this_max_fd = (int)sockbunch[i];
  953. }
  954. else {
  955. break;
  956. }
  957. }
  958. }
  959. *max_fd = this_max_fd;
  960. return CURLM_OK;
  961. }
  962. #ifdef USE_WINSOCK
  963. /* Reset FD_WRITE for TCP sockets. Nothing is actually sent. UDP sockets can't
  964. * be reset this way because an empty datagram would be sent. #9203
  965. *
  966. * "On Windows the internal state of FD_WRITE as returned from
  967. * WSAEnumNetworkEvents is only reset after successful send()."
  968. */
  969. static void reset_socket_fdwrite(curl_socket_t s)
  970. {
  971. int t;
  972. int l = (int)sizeof(t);
  973. if(!getsockopt(s, SOL_SOCKET, SO_TYPE, (char *)&t, &l) && t == SOCK_STREAM)
  974. send(s, NULL, 0, 0);
  975. }
  976. #endif
  977. #define NUM_POLLS_ON_STACK 10
  978. static CURLMcode multi_wait(struct Curl_multi *multi,
  979. struct curl_waitfd extra_fds[],
  980. unsigned int extra_nfds,
  981. int timeout_ms,
  982. int *ret,
  983. bool extrawait, /* when no socket, wait */
  984. bool use_wakeup)
  985. {
  986. struct Curl_easy *data;
  987. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  988. int bitmap;
  989. unsigned int i;
  990. unsigned int nfds = 0;
  991. unsigned int curlfds;
  992. long timeout_internal;
  993. int retcode = 0;
  994. struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
  995. struct pollfd *ufds = &a_few_on_stack[0];
  996. bool ufds_malloc = FALSE;
  997. #ifdef USE_WINSOCK
  998. WSANETWORKEVENTS wsa_events;
  999. DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT);
  1000. #endif
  1001. #ifndef ENABLE_WAKEUP
  1002. (void)use_wakeup;
  1003. #endif
  1004. if(!GOOD_MULTI_HANDLE(multi))
  1005. return CURLM_BAD_HANDLE;
  1006. if(multi->in_callback)
  1007. return CURLM_RECURSIVE_API_CALL;
  1008. if(timeout_ms < 0)
  1009. return CURLM_BAD_FUNCTION_ARGUMENT;
  1010. /* Count up how many fds we have from the multi handle */
  1011. for(data = multi->easyp; data; data = data->next) {
  1012. bitmap = multi_getsock(data, sockbunch);
  1013. for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
  1014. if((bitmap & GETSOCK_MASK_RW(i)) && VALID_SOCK((sockbunch[i]))) {
  1015. ++nfds;
  1016. }
  1017. else {
  1018. break;
  1019. }
  1020. }
  1021. }
  1022. /* If the internally desired timeout is actually shorter than requested from
  1023. the outside, then use the shorter time! But only if the internal timer
  1024. is actually larger than -1! */
  1025. (void)multi_timeout(multi, &timeout_internal);
  1026. if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
  1027. timeout_ms = (int)timeout_internal;
  1028. curlfds = nfds; /* number of internal file descriptors */
  1029. nfds += extra_nfds; /* add the externally provided ones */
  1030. #ifdef ENABLE_WAKEUP
  1031. #ifdef USE_WINSOCK
  1032. if(use_wakeup) {
  1033. #else
  1034. if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
  1035. #endif
  1036. ++nfds;
  1037. }
  1038. #endif
  1039. if(nfds > NUM_POLLS_ON_STACK) {
  1040. /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes
  1041. big, so at 2^29 sockets this value might wrap. When a process gets
  1042. the capability to actually handle over 500 million sockets this
  1043. calculation needs a integer overflow check. */
  1044. ufds = malloc(nfds * sizeof(struct pollfd));
  1045. if(!ufds)
  1046. return CURLM_OUT_OF_MEMORY;
  1047. ufds_malloc = TRUE;
  1048. }
  1049. nfds = 0;
  1050. /* only do the second loop if we found descriptors in the first stage run
  1051. above */
  1052. if(curlfds) {
  1053. /* Add the curl handles to our pollfds first */
  1054. for(data = multi->easyp; data; data = data->next) {
  1055. bitmap = multi_getsock(data, sockbunch);
  1056. for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
  1057. if((bitmap & GETSOCK_MASK_RW(i)) && VALID_SOCK((sockbunch[i]))) {
  1058. struct pollfd *ufd = &ufds[nfds++];
  1059. #ifdef USE_WINSOCK
  1060. long mask = 0;
  1061. #endif
  1062. ufd->fd = sockbunch[i];
  1063. ufd->events = 0;
  1064. if(bitmap & GETSOCK_READSOCK(i)) {
  1065. #ifdef USE_WINSOCK
  1066. mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
  1067. #endif
  1068. ufd->events |= POLLIN;
  1069. }
  1070. if(bitmap & GETSOCK_WRITESOCK(i)) {
  1071. #ifdef USE_WINSOCK
  1072. mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
  1073. reset_socket_fdwrite(sockbunch[i]);
  1074. #endif
  1075. ufd->events |= POLLOUT;
  1076. }
  1077. #ifdef USE_WINSOCK
  1078. if(WSAEventSelect(sockbunch[i], multi->wsa_event, mask) != 0) {
  1079. if(ufds_malloc)
  1080. free(ufds);
  1081. return CURLM_INTERNAL_ERROR;
  1082. }
  1083. #endif
  1084. }
  1085. else {
  1086. break;
  1087. }
  1088. }
  1089. }
  1090. }
  1091. /* Add external file descriptions from poll-like struct curl_waitfd */
  1092. for(i = 0; i < extra_nfds; i++) {
  1093. #ifdef USE_WINSOCK
  1094. long mask = 0;
  1095. if(extra_fds[i].events & CURL_WAIT_POLLIN)
  1096. mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
  1097. if(extra_fds[i].events & CURL_WAIT_POLLPRI)
  1098. mask |= FD_OOB;
  1099. if(extra_fds[i].events & CURL_WAIT_POLLOUT) {
  1100. mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
  1101. reset_socket_fdwrite(extra_fds[i].fd);
  1102. }
  1103. if(WSAEventSelect(extra_fds[i].fd, multi->wsa_event, mask) != 0) {
  1104. if(ufds_malloc)
  1105. free(ufds);
  1106. return CURLM_INTERNAL_ERROR;
  1107. }
  1108. #endif
  1109. ufds[nfds].fd = extra_fds[i].fd;
  1110. ufds[nfds].events = 0;
  1111. if(extra_fds[i].events & CURL_WAIT_POLLIN)
  1112. ufds[nfds].events |= POLLIN;
  1113. if(extra_fds[i].events & CURL_WAIT_POLLPRI)
  1114. ufds[nfds].events |= POLLPRI;
  1115. if(extra_fds[i].events & CURL_WAIT_POLLOUT)
  1116. ufds[nfds].events |= POLLOUT;
  1117. ++nfds;
  1118. }
  1119. #ifdef ENABLE_WAKEUP
  1120. #ifndef USE_WINSOCK
  1121. if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
  1122. ufds[nfds].fd = multi->wakeup_pair[0];
  1123. ufds[nfds].events = POLLIN;
  1124. ++nfds;
  1125. }
  1126. #endif
  1127. #endif
  1128. #if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
  1129. if(nfds || use_wakeup) {
  1130. #else
  1131. if(nfds) {
  1132. #endif
  1133. int pollrc;
  1134. #ifdef USE_WINSOCK
  1135. if(nfds)
  1136. pollrc = Curl_poll(ufds, nfds, 0); /* just pre-check with WinSock */
  1137. else
  1138. pollrc = 0;
  1139. #else
  1140. pollrc = Curl_poll(ufds, nfds, timeout_ms); /* wait... */
  1141. #endif
  1142. if(pollrc < 0)
  1143. return CURLM_UNRECOVERABLE_POLL;
  1144. if(pollrc > 0) {
  1145. retcode = pollrc;
  1146. #ifdef USE_WINSOCK
  1147. }
  1148. else { /* now wait... if not ready during the pre-check (pollrc == 0) */
  1149. WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, timeout_ms, FALSE);
  1150. }
  1151. /* With WinSock, we have to run the following section unconditionally
  1152. to call WSAEventSelect(fd, event, 0) on all the sockets */
  1153. {
  1154. #endif
  1155. /* copy revents results from the poll to the curl_multi_wait poll
  1156. struct, the bit values of the actual underlying poll() implementation
  1157. may not be the same as the ones in the public libcurl API! */
  1158. for(i = 0; i < extra_nfds; i++) {
  1159. unsigned r = ufds[curlfds + i].revents;
  1160. unsigned short mask = 0;
  1161. #ifdef USE_WINSOCK
  1162. curl_socket_t s = extra_fds[i].fd;
  1163. wsa_events.lNetworkEvents = 0;
  1164. if(WSAEnumNetworkEvents(s, NULL, &wsa_events) == 0) {
  1165. if(wsa_events.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))
  1166. mask |= CURL_WAIT_POLLIN;
  1167. if(wsa_events.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))
  1168. mask |= CURL_WAIT_POLLOUT;
  1169. if(wsa_events.lNetworkEvents & FD_OOB)
  1170. mask |= CURL_WAIT_POLLPRI;
  1171. if(ret && !pollrc && wsa_events.lNetworkEvents)
  1172. retcode++;
  1173. }
  1174. WSAEventSelect(s, multi->wsa_event, 0);
  1175. if(!pollrc) {
  1176. extra_fds[i].revents = mask;
  1177. continue;
  1178. }
  1179. #endif
  1180. if(r & POLLIN)
  1181. mask |= CURL_WAIT_POLLIN;
  1182. if(r & POLLOUT)
  1183. mask |= CURL_WAIT_POLLOUT;
  1184. if(r & POLLPRI)
  1185. mask |= CURL_WAIT_POLLPRI;
  1186. extra_fds[i].revents = mask;
  1187. }
  1188. #ifdef USE_WINSOCK
  1189. /* Count up all our own sockets that had activity,
  1190. and remove them from the event. */
  1191. if(curlfds) {
  1192. for(data = multi->easyp; data; data = data->next) {
  1193. bitmap = multi_getsock(data, sockbunch);
  1194. for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
  1195. if(bitmap & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))) {
  1196. wsa_events.lNetworkEvents = 0;
  1197. if(WSAEnumNetworkEvents(sockbunch[i], NULL, &wsa_events) == 0) {
  1198. if(ret && !pollrc && wsa_events.lNetworkEvents)
  1199. retcode++;
  1200. }
  1201. WSAEventSelect(sockbunch[i], multi->wsa_event, 0);
  1202. }
  1203. else {
  1204. /* break on entry not checked for being readable or writable */
  1205. break;
  1206. }
  1207. }
  1208. }
  1209. }
  1210. WSAResetEvent(multi->wsa_event);
  1211. #else
  1212. #ifdef ENABLE_WAKEUP
  1213. if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
  1214. if(ufds[curlfds + extra_nfds].revents & POLLIN) {
  1215. char buf[64];
  1216. ssize_t nread;
  1217. while(1) {
  1218. /* the reading socket is non-blocking, try to read
  1219. data from it until it receives an error (except EINTR).
  1220. In normal cases it will get EAGAIN or EWOULDBLOCK
  1221. when there is no more data, breaking the loop. */
  1222. nread = wakeup_read(multi->wakeup_pair[0], buf, sizeof(buf));
  1223. if(nread <= 0) {
  1224. if(nread < 0 && EINTR == SOCKERRNO)
  1225. continue;
  1226. break;
  1227. }
  1228. }
  1229. /* do not count the wakeup socket into the returned value */
  1230. retcode--;
  1231. }
  1232. }
  1233. #endif
  1234. #endif
  1235. }
  1236. }
  1237. if(ufds_malloc)
  1238. free(ufds);
  1239. if(ret)
  1240. *ret = retcode;
  1241. #if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
  1242. if(extrawait && !nfds && !use_wakeup) {
  1243. #else
  1244. if(extrawait && !nfds) {
  1245. #endif
  1246. long sleep_ms = 0;
  1247. /* Avoid busy-looping when there's nothing particular to wait for */
  1248. if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) {
  1249. if(sleep_ms > timeout_ms)
  1250. sleep_ms = timeout_ms;
  1251. /* when there are no easy handles in the multi, this holds a -1
  1252. timeout */
  1253. else if(sleep_ms < 0)
  1254. sleep_ms = timeout_ms;
  1255. Curl_wait_ms(sleep_ms);
  1256. }
  1257. }
  1258. return CURLM_OK;
  1259. }
  1260. CURLMcode curl_multi_wait(struct Curl_multi *multi,
  1261. struct curl_waitfd extra_fds[],
  1262. unsigned int extra_nfds,
  1263. int timeout_ms,
  1264. int *ret)
  1265. {
  1266. return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE,
  1267. FALSE);
  1268. }
  1269. CURLMcode curl_multi_poll(struct Curl_multi *multi,
  1270. struct curl_waitfd extra_fds[],
  1271. unsigned int extra_nfds,
  1272. int timeout_ms,
  1273. int *ret)
  1274. {
  1275. return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE,
  1276. TRUE);
  1277. }
  1278. CURLMcode curl_multi_wakeup(struct Curl_multi *multi)
  1279. {
  1280. /* this function is usually called from another thread,
  1281. it has to be careful only to access parts of the
  1282. Curl_multi struct that are constant */
  1283. /* GOOD_MULTI_HANDLE can be safely called */
  1284. if(!GOOD_MULTI_HANDLE(multi))
  1285. return CURLM_BAD_HANDLE;
  1286. #ifdef ENABLE_WAKEUP
  1287. #ifdef USE_WINSOCK
  1288. if(WSASetEvent(multi->wsa_event))
  1289. return CURLM_OK;
  1290. #else
  1291. /* the wakeup_pair variable is only written during init and cleanup,
  1292. making it safe to access from another thread after the init part
  1293. and before cleanup */
  1294. if(multi->wakeup_pair[1] != CURL_SOCKET_BAD) {
  1295. char buf[1];
  1296. buf[0] = 1;
  1297. while(1) {
  1298. /* swrite() is not thread-safe in general, because concurrent calls
  1299. can have their messages interleaved, but in this case the content
  1300. of the messages does not matter, which makes it ok to call.
  1301. The write socket is set to non-blocking, this way this function
  1302. cannot block, making it safe to call even from the same thread
  1303. that will call curl_multi_wait(). If swrite() returns that it
  1304. would block, it's considered successful because it means that
  1305. previous calls to this function will wake up the poll(). */
  1306. if(wakeup_write(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) {
  1307. int err = SOCKERRNO;
  1308. int return_success;
  1309. #ifdef USE_WINSOCK
  1310. return_success = WSAEWOULDBLOCK == err;
  1311. #else
  1312. if(EINTR == err)
  1313. continue;
  1314. return_success = EWOULDBLOCK == err || EAGAIN == err;
  1315. #endif
  1316. if(!return_success)
  1317. return CURLM_WAKEUP_FAILURE;
  1318. }
  1319. return CURLM_OK;
  1320. }
  1321. }
  1322. #endif
  1323. #endif
  1324. return CURLM_WAKEUP_FAILURE;
  1325. }
  1326. /*
  1327. * multi_ischanged() is called
  1328. *
  1329. * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
  1330. * => CONNECT action.
  1331. *
  1332. * Set 'clear' to TRUE to have it also clear the state variable.
  1333. */
  1334. static bool multi_ischanged(struct Curl_multi *multi, bool clear)
  1335. {
  1336. bool retval = multi->recheckstate;
  1337. if(clear)
  1338. multi->recheckstate = FALSE;
  1339. return retval;
  1340. }
  1341. /*
  1342. * Curl_multi_connchanged() is called to tell that there is a connection in
  1343. * this multi handle that has changed state (multiplexing become possible, the
  1344. * number of allowed streams changed or similar), and a subsequent use of this
  1345. * multi handle should move CONNECT_PEND handles back to CONNECT to have them
  1346. * retry.
  1347. */
  1348. void Curl_multi_connchanged(struct Curl_multi *multi)
  1349. {
  1350. multi->recheckstate = TRUE;
  1351. }
  1352. CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
  1353. struct Curl_easy *data,
  1354. struct connectdata *conn)
  1355. {
  1356. CURLMcode rc;
  1357. if(multi->in_callback)
  1358. return CURLM_RECURSIVE_API_CALL;
  1359. rc = curl_multi_add_handle(multi, data);
  1360. if(!rc) {
  1361. struct SingleRequest *k = &data->req;
  1362. /* pass in NULL for 'conn' here since we don't want to init the
  1363. connection, only this transfer */
  1364. Curl_init_do(data, NULL);
  1365. /* take this handle to the perform state right away */
  1366. multistate(data, MSTATE_PERFORMING);
  1367. Curl_attach_connection(data, conn);
  1368. k->keepon |= KEEP_RECV; /* setup to receive! */
  1369. }
  1370. return rc;
  1371. }
  1372. static CURLcode multi_do(struct Curl_easy *data, bool *done)
  1373. {
  1374. CURLcode result = CURLE_OK;
  1375. struct connectdata *conn = data->conn;
  1376. DEBUGASSERT(conn);
  1377. DEBUGASSERT(conn->handler);
  1378. if(conn->handler->do_it)
  1379. result = conn->handler->do_it(data, done);
  1380. return result;
  1381. }
  1382. /*
  1383. * multi_do_more() is called during the DO_MORE multi state. It is basically a
  1384. * second stage DO state which (wrongly) was introduced to support FTP's
  1385. * second connection.
  1386. *
  1387. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
  1388. * DOING state there's more work to do!
  1389. */
  1390. static CURLcode multi_do_more(struct Curl_easy *data, int *complete)
  1391. {
  1392. CURLcode result = CURLE_OK;
  1393. struct connectdata *conn = data->conn;
  1394. *complete = 0;
  1395. if(conn->handler->do_more)
  1396. result = conn->handler->do_more(data, complete);
  1397. return result;
  1398. }
  1399. /*
  1400. * Check whether a timeout occurred, and handle it if it did
  1401. */
  1402. static bool multi_handle_timeout(struct Curl_easy *data,
  1403. struct curltime *now,
  1404. bool *stream_error,
  1405. CURLcode *result,
  1406. bool connect_timeout)
  1407. {
  1408. timediff_t timeout_ms;
  1409. timeout_ms = Curl_timeleft(data, now, connect_timeout);
  1410. if(timeout_ms < 0) {
  1411. /* Handle timed out */
  1412. if(data->mstate == MSTATE_RESOLVING)
  1413. failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T
  1414. " milliseconds",
  1415. Curl_timediff(*now, data->progress.t_startsingle));
  1416. else if(data->mstate == MSTATE_CONNECTING)
  1417. failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T
  1418. " milliseconds",
  1419. Curl_timediff(*now, data->progress.t_startsingle));
  1420. else {
  1421. struct SingleRequest *k = &data->req;
  1422. if(k->size != -1) {
  1423. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1424. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
  1425. CURL_FORMAT_CURL_OFF_T " bytes received",
  1426. Curl_timediff(*now, data->progress.t_startsingle),
  1427. k->bytecount, k->size);
  1428. }
  1429. else {
  1430. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1431. " milliseconds with %" CURL_FORMAT_CURL_OFF_T
  1432. " bytes received",
  1433. Curl_timediff(*now, data->progress.t_startsingle),
  1434. k->bytecount);
  1435. }
  1436. }
  1437. /* Force connection closed if the connection has indeed been used */
  1438. if(data->mstate > MSTATE_DO) {
  1439. streamclose(data->conn, "Disconnected with pending data");
  1440. *stream_error = TRUE;
  1441. }
  1442. *result = CURLE_OPERATION_TIMEDOUT;
  1443. (void)multi_done(data, *result, TRUE);
  1444. }
  1445. return (timeout_ms < 0);
  1446. }
  1447. /*
  1448. * We are doing protocol-specific connecting and this is being called over and
  1449. * over from the multi interface until the connection phase is done on
  1450. * protocol layer.
  1451. */
  1452. static CURLcode protocol_connecting(struct Curl_easy *data, bool *done)
  1453. {
  1454. CURLcode result = CURLE_OK;
  1455. struct connectdata *conn = data->conn;
  1456. if(conn && conn->handler->connecting) {
  1457. *done = FALSE;
  1458. result = conn->handler->connecting(data, done);
  1459. }
  1460. else
  1461. *done = TRUE;
  1462. return result;
  1463. }
  1464. /*
  1465. * We are DOING this is being called over and over from the multi interface
  1466. * until the DOING phase is done on protocol layer.
  1467. */
  1468. static CURLcode protocol_doing(struct Curl_easy *data, bool *done)
  1469. {
  1470. CURLcode result = CURLE_OK;
  1471. struct connectdata *conn = data->conn;
  1472. if(conn && conn->handler->doing) {
  1473. *done = FALSE;
  1474. result = conn->handler->doing(data, done);
  1475. }
  1476. else
  1477. *done = TRUE;
  1478. return result;
  1479. }
  1480. /*
  1481. * We have discovered that the TCP connection has been successful, we can now
  1482. * proceed with some action.
  1483. *
  1484. */
  1485. static CURLcode protocol_connect(struct Curl_easy *data,
  1486. bool *protocol_done)
  1487. {
  1488. CURLcode result = CURLE_OK;
  1489. struct connectdata *conn = data->conn;
  1490. DEBUGASSERT(conn);
  1491. DEBUGASSERT(protocol_done);
  1492. *protocol_done = FALSE;
  1493. if(Curl_conn_is_connected(conn, FIRSTSOCKET)
  1494. && conn->bits.protoconnstart) {
  1495. /* We already are connected, get back. This may happen when the connect
  1496. worked fine in the first call, like when we connect to a local server
  1497. or proxy. Note that we don't know if the protocol is actually done.
  1498. Unless this protocol doesn't have any protocol-connect callback, as
  1499. then we know we're done. */
  1500. if(!conn->handler->connecting)
  1501. *protocol_done = TRUE;
  1502. return CURLE_OK;
  1503. }
  1504. if(!conn->bits.protoconnstart) {
  1505. if(conn->handler->connect_it) {
  1506. /* is there a protocol-specific connect() procedure? */
  1507. /* Call the protocol-specific connect function */
  1508. result = conn->handler->connect_it(data, protocol_done);
  1509. }
  1510. else
  1511. *protocol_done = TRUE;
  1512. /* it has started, possibly even completed but that knowledge isn't stored
  1513. in this bit! */
  1514. if(!result)
  1515. conn->bits.protoconnstart = TRUE;
  1516. }
  1517. return result; /* pass back status */
  1518. }
  1519. /*
  1520. * readrewind() rewinds the read stream. This is typically used for HTTP
  1521. * POST/PUT with multi-pass authentication when a sending was denied and a
  1522. * resend is necessary.
  1523. */
  1524. static CURLcode readrewind(struct Curl_easy *data)
  1525. {
  1526. curl_mimepart *mimepart = &data->set.mimepost;
  1527. DEBUGASSERT(data->conn);
  1528. data->state.rewindbeforesend = FALSE; /* we rewind now */
  1529. /* explicitly switch off sending data on this connection now since we are
  1530. about to restart a new transfer and thus we want to avoid inadvertently
  1531. sending more data on the existing connection until the next transfer
  1532. starts */
  1533. data->req.keepon &= ~KEEP_SEND;
  1534. /* We have sent away data. If not using CURLOPT_POSTFIELDS or
  1535. CURLOPT_HTTPPOST, call app to rewind
  1536. */
  1537. #ifndef CURL_DISABLE_HTTP
  1538. if(data->conn->handler->protocol & PROTO_FAMILY_HTTP) {
  1539. if(data->state.mimepost)
  1540. mimepart = data->state.mimepost;
  1541. }
  1542. #endif
  1543. if(data->set.postfields ||
  1544. (data->state.httpreq == HTTPREQ_GET) ||
  1545. (data->state.httpreq == HTTPREQ_HEAD))
  1546. ; /* no need to rewind */
  1547. else if(data->state.httpreq == HTTPREQ_POST_MIME ||
  1548. data->state.httpreq == HTTPREQ_POST_FORM) {
  1549. CURLcode result = Curl_mime_rewind(mimepart);
  1550. if(result) {
  1551. failf(data, "Cannot rewind mime/post data");
  1552. return result;
  1553. }
  1554. }
  1555. else {
  1556. if(data->set.seek_func) {
  1557. int err;
  1558. Curl_set_in_callback(data, true);
  1559. err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
  1560. Curl_set_in_callback(data, false);
  1561. if(err) {
  1562. failf(data, "seek callback returned error %d", (int)err);
  1563. return CURLE_SEND_FAIL_REWIND;
  1564. }
  1565. }
  1566. else if(data->set.ioctl_func) {
  1567. curlioerr err;
  1568. Curl_set_in_callback(data, true);
  1569. err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
  1570. data->set.ioctl_client);
  1571. Curl_set_in_callback(data, false);
  1572. infof(data, "the ioctl callback returned %d", (int)err);
  1573. if(err) {
  1574. failf(data, "ioctl callback returned error %d", (int)err);
  1575. return CURLE_SEND_FAIL_REWIND;
  1576. }
  1577. }
  1578. else {
  1579. /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
  1580. given FILE * stream and we can actually attempt to rewind that
  1581. ourselves with fseek() */
  1582. if(data->state.fread_func == (curl_read_callback)fread) {
  1583. if(-1 != fseek(data->state.in, 0, SEEK_SET))
  1584. /* successful rewind */
  1585. return CURLE_OK;
  1586. }
  1587. /* no callback set or failure above, makes us fail at once */
  1588. failf(data, "necessary data rewind wasn't possible");
  1589. return CURLE_SEND_FAIL_REWIND;
  1590. }
  1591. }
  1592. return CURLE_OK;
  1593. }
  1594. /*
  1595. * Curl_preconnect() is called immediately before a connect starts. When a
  1596. * redirect is followed, this is then called multiple times during a single
  1597. * transfer.
  1598. */
  1599. CURLcode Curl_preconnect(struct Curl_easy *data)
  1600. {
  1601. if(!data->state.buffer) {
  1602. data->state.buffer = malloc(data->set.buffer_size + 1);
  1603. if(!data->state.buffer)
  1604. return CURLE_OUT_OF_MEMORY;
  1605. }
  1606. return CURLE_OK;
  1607. }
  1608. static void set_in_callback(struct Curl_multi *multi, bool value)
  1609. {
  1610. multi->in_callback = value;
  1611. }
  1612. static CURLMcode multi_runsingle(struct Curl_multi *multi,
  1613. struct curltime *nowp,
  1614. struct Curl_easy *data)
  1615. {
  1616. struct Curl_message *msg = NULL;
  1617. bool connected;
  1618. bool async;
  1619. bool protocol_connected = FALSE;
  1620. bool dophase_done = FALSE;
  1621. bool done = FALSE;
  1622. CURLMcode rc;
  1623. CURLcode result = CURLE_OK;
  1624. timediff_t recv_timeout_ms;
  1625. timediff_t send_timeout_ms;
  1626. int control;
  1627. if(!GOOD_EASY_HANDLE(data))
  1628. return CURLM_BAD_EASY_HANDLE;
  1629. if(multi->dead) {
  1630. /* a multi-level callback returned error before, meaning every individual
  1631. transfer now has failed */
  1632. result = CURLE_ABORTED_BY_CALLBACK;
  1633. Curl_posttransfer(data);
  1634. multi_done(data, result, FALSE);
  1635. multistate(data, MSTATE_COMPLETED);
  1636. }
  1637. multi_warn_debug(multi, data);
  1638. do {
  1639. /* A "stream" here is a logical stream if the protocol can handle that
  1640. (HTTP/2), or the full connection for older protocols */
  1641. bool stream_error = FALSE;
  1642. rc = CURLM_OK;
  1643. if(multi_ischanged(multi, TRUE)) {
  1644. DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue"));
  1645. process_pending_handles(multi); /* multiplexed */
  1646. }
  1647. if(data->mstate > MSTATE_CONNECT &&
  1648. data->mstate < MSTATE_COMPLETED) {
  1649. /* Make sure we set the connection's current owner */
  1650. DEBUGASSERT(data->conn);
  1651. if(!data->conn)
  1652. return CURLM_INTERNAL_ERROR;
  1653. }
  1654. if(data->conn &&
  1655. (data->mstate >= MSTATE_CONNECT) &&
  1656. (data->mstate < MSTATE_COMPLETED)) {
  1657. /* Check for overall operation timeout here but defer handling the
  1658. * connection timeout to later, to allow for a connection to be set up
  1659. * in the window since we last checked timeout. This prevents us
  1660. * tearing down a completed connection in the case where we were slow
  1661. * to check the timeout (e.g. process descheduled during this loop).
  1662. * We set connect_timeout=FALSE to do this. */
  1663. /* we need to wait for the connect state as only then is the start time
  1664. stored, but we must not check already completed handles */
  1665. if(multi_handle_timeout(data, nowp, &stream_error, &result, FALSE)) {
  1666. /* Skip the statemachine and go directly to error handling section. */
  1667. goto statemachine_end;
  1668. }
  1669. }
  1670. switch(data->mstate) {
  1671. case MSTATE_INIT:
  1672. /* init this transfer. */
  1673. result = Curl_pretransfer(data);
  1674. if(!result) {
  1675. /* after init, go CONNECT */
  1676. multistate(data, MSTATE_CONNECT);
  1677. *nowp = Curl_pgrsTime(data, TIMER_STARTOP);
  1678. rc = CURLM_CALL_MULTI_PERFORM;
  1679. }
  1680. break;
  1681. case MSTATE_CONNECT:
  1682. /* Connect. We want to get a connection identifier filled in. */
  1683. /* init this transfer. */
  1684. result = Curl_preconnect(data);
  1685. if(result)
  1686. break;
  1687. *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE);
  1688. if(data->set.timeout)
  1689. Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT);
  1690. if(data->set.connecttimeout)
  1691. Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT);
  1692. result = Curl_connect(data, &async, &connected);
  1693. if(CURLE_NO_CONNECTION_AVAILABLE == result) {
  1694. /* There was no connection available. We will go to the pending
  1695. state and wait for an available connection. */
  1696. multistate(data, MSTATE_PENDING);
  1697. /* add this handle to the list of connect-pending handles */
  1698. Curl_llist_insert_next(&multi->pending, multi->pending.tail, data,
  1699. &data->connect_queue);
  1700. /* unlink from the main list */
  1701. unlink_easy(multi, data);
  1702. result = CURLE_OK;
  1703. break;
  1704. }
  1705. else if(data->state.previouslypending) {
  1706. /* this transfer comes from the pending queue so try move another */
  1707. infof(data, "Transfer was pending, now try another");
  1708. process_pending_handles(data->multi);
  1709. }
  1710. if(!result) {
  1711. if(async)
  1712. /* We're now waiting for an asynchronous name lookup */
  1713. multistate(data, MSTATE_RESOLVING);
  1714. else {
  1715. /* after the connect has been sent off, go WAITCONNECT unless the
  1716. protocol connect is already done and we can go directly to
  1717. WAITDO or DO! */
  1718. rc = CURLM_CALL_MULTI_PERFORM;
  1719. if(connected)
  1720. multistate(data, MSTATE_PROTOCONNECT);
  1721. else {
  1722. multistate(data, MSTATE_CONNECTING);
  1723. }
  1724. }
  1725. }
  1726. break;
  1727. case MSTATE_RESOLVING:
  1728. /* awaiting an asynch name resolve to complete */
  1729. {
  1730. struct Curl_dns_entry *dns = NULL;
  1731. struct connectdata *conn = data->conn;
  1732. const char *hostname;
  1733. DEBUGASSERT(conn);
  1734. #ifndef CURL_DISABLE_PROXY
  1735. if(conn->bits.httpproxy)
  1736. hostname = conn->http_proxy.host.name;
  1737. else
  1738. #endif
  1739. if(conn->bits.conn_to_host)
  1740. hostname = conn->conn_to_host.name;
  1741. else
  1742. hostname = conn->host.name;
  1743. /* check if we have the name resolved by now */
  1744. dns = Curl_fetch_addr(data, hostname, (int)conn->port);
  1745. if(dns) {
  1746. #ifdef CURLRES_ASYNCH
  1747. data->state.async.dns = dns;
  1748. data->state.async.done = TRUE;
  1749. #endif
  1750. result = CURLE_OK;
  1751. infof(data, "Hostname '%s' was found in DNS cache", hostname);
  1752. }
  1753. if(!dns)
  1754. result = Curl_resolv_check(data, &dns);
  1755. /* Update sockets here, because the socket(s) may have been
  1756. closed and the application thus needs to be told, even if it
  1757. is likely that the same socket(s) will again be used further
  1758. down. If the name has not yet been resolved, it is likely
  1759. that new sockets have been opened in an attempt to contact
  1760. another resolver. */
  1761. rc = singlesocket(multi, data);
  1762. if(rc)
  1763. return rc;
  1764. if(dns) {
  1765. /* Perform the next step in the connection phase, and then move on
  1766. to the WAITCONNECT state */
  1767. result = Curl_once_resolved(data, &connected);
  1768. if(result)
  1769. /* if Curl_once_resolved() returns failure, the connection struct
  1770. is already freed and gone */
  1771. data->conn = NULL; /* no more connection */
  1772. else {
  1773. /* call again please so that we get the next socket setup */
  1774. rc = CURLM_CALL_MULTI_PERFORM;
  1775. if(connected)
  1776. multistate(data, MSTATE_PROTOCONNECT);
  1777. else {
  1778. multistate(data, MSTATE_CONNECTING);
  1779. }
  1780. }
  1781. }
  1782. if(result) {
  1783. /* failure detected */
  1784. stream_error = TRUE;
  1785. break;
  1786. }
  1787. }
  1788. break;
  1789. #ifndef CURL_DISABLE_HTTP
  1790. case MSTATE_TUNNELING:
  1791. /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
  1792. DEBUGASSERT(data->conn);
  1793. result = Curl_http_connect(data, &protocol_connected);
  1794. #ifndef CURL_DISABLE_PROXY
  1795. if(data->conn->bits.proxy_connect_closed) {
  1796. rc = CURLM_CALL_MULTI_PERFORM;
  1797. /* connect back to proxy again */
  1798. result = CURLE_OK;
  1799. multi_done(data, CURLE_OK, FALSE);
  1800. multistate(data, MSTATE_CONNECT);
  1801. }
  1802. else
  1803. #endif
  1804. if(!result) {
  1805. rc = CURLM_CALL_MULTI_PERFORM;
  1806. /* initiate protocol connect phase */
  1807. multistate(data, MSTATE_PROTOCONNECT);
  1808. }
  1809. else
  1810. stream_error = TRUE;
  1811. break;
  1812. #endif
  1813. case MSTATE_CONNECTING:
  1814. /* awaiting a completion of an asynch TCP connect */
  1815. DEBUGASSERT(data->conn);
  1816. result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected);
  1817. if(connected && !result) {
  1818. rc = CURLM_CALL_MULTI_PERFORM;
  1819. multistate(data, MSTATE_PROTOCONNECT);
  1820. }
  1821. else if(result) {
  1822. /* failure detected */
  1823. Curl_posttransfer(data);
  1824. multi_done(data, result, TRUE);
  1825. stream_error = TRUE;
  1826. break;
  1827. }
  1828. break;
  1829. case MSTATE_PROTOCONNECT:
  1830. if(data->state.rewindbeforesend)
  1831. result = readrewind(data);
  1832. if(!result && data->conn->bits.reuse) {
  1833. /* ftp seems to hang when protoconnect on reused connection
  1834. * since we handle PROTOCONNECT in general inside the filers, it
  1835. * seems wrong to restart this on a reused connection. */
  1836. multistate(data, MSTATE_DO);
  1837. rc = CURLM_CALL_MULTI_PERFORM;
  1838. break;
  1839. }
  1840. if(!result)
  1841. result = protocol_connect(data, &protocol_connected);
  1842. if(!result && !protocol_connected)
  1843. /* switch to waiting state */
  1844. multistate(data, MSTATE_PROTOCONNECTING);
  1845. else if(!result) {
  1846. /* protocol connect has completed, go WAITDO or DO */
  1847. multistate(data, MSTATE_DO);
  1848. rc = CURLM_CALL_MULTI_PERFORM;
  1849. }
  1850. else {
  1851. /* failure detected */
  1852. Curl_posttransfer(data);
  1853. multi_done(data, result, TRUE);
  1854. stream_error = TRUE;
  1855. }
  1856. break;
  1857. case MSTATE_PROTOCONNECTING:
  1858. /* protocol-specific connect phase */
  1859. result = protocol_connecting(data, &protocol_connected);
  1860. if(!result && protocol_connected) {
  1861. /* after the connect has completed, go WAITDO or DO */
  1862. multistate(data, MSTATE_DO);
  1863. rc = CURLM_CALL_MULTI_PERFORM;
  1864. }
  1865. else if(result) {
  1866. /* failure detected */
  1867. Curl_posttransfer(data);
  1868. multi_done(data, result, TRUE);
  1869. stream_error = TRUE;
  1870. }
  1871. break;
  1872. case MSTATE_DO:
  1873. if(data->set.fprereq) {
  1874. int prereq_rc;
  1875. /* call the prerequest callback function */
  1876. Curl_set_in_callback(data, true);
  1877. prereq_rc = data->set.fprereq(data->set.prereq_userp,
  1878. data->info.conn_primary_ip,
  1879. data->info.conn_local_ip,
  1880. data->info.conn_primary_port,
  1881. data->info.conn_local_port);
  1882. Curl_set_in_callback(data, false);
  1883. if(prereq_rc != CURL_PREREQFUNC_OK) {
  1884. failf(data, "operation aborted by pre-request callback");
  1885. /* failure in pre-request callback - don't do any other processing */
  1886. result = CURLE_ABORTED_BY_CALLBACK;
  1887. Curl_posttransfer(data);
  1888. multi_done(data, result, FALSE);
  1889. stream_error = TRUE;
  1890. break;
  1891. }
  1892. }
  1893. if(data->set.connect_only == 1) {
  1894. /* keep connection open for application to use the socket */
  1895. connkeep(data->conn, "CONNECT_ONLY");
  1896. multistate(data, MSTATE_DONE);
  1897. result = CURLE_OK;
  1898. rc = CURLM_CALL_MULTI_PERFORM;
  1899. }
  1900. else {
  1901. /* Perform the protocol's DO action */
  1902. result = multi_do(data, &dophase_done);
  1903. /* When multi_do() returns failure, data->conn might be NULL! */
  1904. if(!result) {
  1905. if(!dophase_done) {
  1906. #ifndef CURL_DISABLE_FTP
  1907. /* some steps needed for wildcard matching */
  1908. if(data->state.wildcardmatch) {
  1909. struct WildcardData *wc = data->wildcard;
  1910. if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
  1911. /* skip some states if it is important */
  1912. multi_done(data, CURLE_OK, FALSE);
  1913. /* if there's no connection left, skip the DONE state */
  1914. multistate(data, data->conn ?
  1915. MSTATE_DONE : MSTATE_COMPLETED);
  1916. rc = CURLM_CALL_MULTI_PERFORM;
  1917. break;
  1918. }
  1919. }
  1920. #endif
  1921. /* DO was not completed in one function call, we must continue
  1922. DOING... */
  1923. multistate(data, MSTATE_DOING);
  1924. }
  1925. /* after DO, go DO_DONE... or DO_MORE */
  1926. else if(data->conn->bits.do_more) {
  1927. /* we're supposed to do more, but we need to sit down, relax
  1928. and wait a little while first */
  1929. multistate(data, MSTATE_DOING_MORE);
  1930. }
  1931. else {
  1932. /* we're done with the DO, now DID */
  1933. multistate(data, MSTATE_DID);
  1934. rc = CURLM_CALL_MULTI_PERFORM;
  1935. }
  1936. }
  1937. else if((CURLE_SEND_ERROR == result) &&
  1938. data->conn->bits.reuse) {
  1939. /*
  1940. * In this situation, a connection that we were trying to use
  1941. * may have unexpectedly died. If possible, send the connection
  1942. * back to the CONNECT phase so we can try again.
  1943. */
  1944. char *newurl = NULL;
  1945. followtype follow = FOLLOW_NONE;
  1946. CURLcode drc;
  1947. drc = Curl_retry_request(data, &newurl);
  1948. if(drc) {
  1949. /* a failure here pretty much implies an out of memory */
  1950. result = drc;
  1951. stream_error = TRUE;
  1952. }
  1953. Curl_posttransfer(data);
  1954. drc = multi_done(data, result, FALSE);
  1955. /* When set to retry the connection, we must go back to the CONNECT
  1956. * state */
  1957. if(newurl) {
  1958. if(!drc || (drc == CURLE_SEND_ERROR)) {
  1959. follow = FOLLOW_RETRY;
  1960. drc = Curl_follow(data, newurl, follow);
  1961. if(!drc) {
  1962. multistate(data, MSTATE_CONNECT);
  1963. rc = CURLM_CALL_MULTI_PERFORM;
  1964. result = CURLE_OK;
  1965. }
  1966. else {
  1967. /* Follow failed */
  1968. result = drc;
  1969. }
  1970. }
  1971. else {
  1972. /* done didn't return OK or SEND_ERROR */
  1973. result = drc;
  1974. }
  1975. }
  1976. else {
  1977. /* Have error handler disconnect conn if we can't retry */
  1978. stream_error = TRUE;
  1979. }
  1980. free(newurl);
  1981. }
  1982. else {
  1983. /* failure detected */
  1984. Curl_posttransfer(data);
  1985. if(data->conn)
  1986. multi_done(data, result, FALSE);
  1987. stream_error = TRUE;
  1988. }
  1989. }
  1990. break;
  1991. case MSTATE_DOING:
  1992. /* we continue DOING until the DO phase is complete */
  1993. DEBUGASSERT(data->conn);
  1994. result = protocol_doing(data, &dophase_done);
  1995. if(!result) {
  1996. if(dophase_done) {
  1997. /* after DO, go DO_DONE or DO_MORE */
  1998. multistate(data, data->conn->bits.do_more?
  1999. MSTATE_DOING_MORE : MSTATE_DID);
  2000. rc = CURLM_CALL_MULTI_PERFORM;
  2001. } /* dophase_done */
  2002. }
  2003. else {
  2004. /* failure detected */
  2005. Curl_posttransfer(data);
  2006. multi_done(data, result, FALSE);
  2007. stream_error = TRUE;
  2008. }
  2009. break;
  2010. case MSTATE_DOING_MORE:
  2011. /*
  2012. * When we are connected, DOING MORE and then go DID
  2013. */
  2014. DEBUGASSERT(data->conn);
  2015. result = multi_do_more(data, &control);
  2016. if(!result) {
  2017. if(control) {
  2018. /* if positive, advance to DO_DONE
  2019. if negative, go back to DOING */
  2020. multistate(data, control == 1?
  2021. MSTATE_DID : MSTATE_DOING);
  2022. rc = CURLM_CALL_MULTI_PERFORM;
  2023. }
  2024. /* else
  2025. stay in DO_MORE */
  2026. }
  2027. else {
  2028. /* failure detected */
  2029. Curl_posttransfer(data);
  2030. multi_done(data, result, FALSE);
  2031. stream_error = TRUE;
  2032. }
  2033. break;
  2034. case MSTATE_DID:
  2035. DEBUGASSERT(data->conn);
  2036. if(data->conn->bits.multiplex)
  2037. /* Check if we can move pending requests to send pipe */
  2038. process_pending_handles(multi); /* multiplexed */
  2039. /* Only perform the transfer if there's a good socket to work with.
  2040. Having both BAD is a signal to skip immediately to DONE */
  2041. if((data->conn->sockfd != CURL_SOCKET_BAD) ||
  2042. (data->conn->writesockfd != CURL_SOCKET_BAD))
  2043. multistate(data, MSTATE_PERFORMING);
  2044. else {
  2045. #ifndef CURL_DISABLE_FTP
  2046. if(data->state.wildcardmatch &&
  2047. ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
  2048. data->wildcard->state = CURLWC_DONE;
  2049. }
  2050. #endif
  2051. multistate(data, MSTATE_DONE);
  2052. }
  2053. rc = CURLM_CALL_MULTI_PERFORM;
  2054. break;
  2055. case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */
  2056. DEBUGASSERT(data->conn);
  2057. /* if both rates are within spec, resume transfer */
  2058. if(Curl_pgrsUpdate(data))
  2059. result = CURLE_ABORTED_BY_CALLBACK;
  2060. else
  2061. result = Curl_speedcheck(data, *nowp);
  2062. if(result) {
  2063. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  2064. result != CURLE_HTTP2_STREAM)
  2065. streamclose(data->conn, "Transfer returned error");
  2066. Curl_posttransfer(data);
  2067. multi_done(data, result, TRUE);
  2068. }
  2069. else {
  2070. send_timeout_ms = 0;
  2071. if(data->set.max_send_speed)
  2072. send_timeout_ms =
  2073. Curl_pgrsLimitWaitTime(data->progress.uploaded,
  2074. data->progress.ul_limit_size,
  2075. data->set.max_send_speed,
  2076. data->progress.ul_limit_start,
  2077. *nowp);
  2078. recv_timeout_ms = 0;
  2079. if(data->set.max_recv_speed)
  2080. recv_timeout_ms =
  2081. Curl_pgrsLimitWaitTime(data->progress.downloaded,
  2082. data->progress.dl_limit_size,
  2083. data->set.max_recv_speed,
  2084. data->progress.dl_limit_start,
  2085. *nowp);
  2086. if(!send_timeout_ms && !recv_timeout_ms) {
  2087. multistate(data, MSTATE_PERFORMING);
  2088. Curl_ratelimit(data, *nowp);
  2089. }
  2090. else if(send_timeout_ms >= recv_timeout_ms)
  2091. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  2092. else
  2093. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  2094. }
  2095. break;
  2096. case MSTATE_PERFORMING:
  2097. {
  2098. char *newurl = NULL;
  2099. bool retry = FALSE;
  2100. bool comeback = FALSE;
  2101. DEBUGASSERT(data->state.buffer);
  2102. /* check if over send speed */
  2103. send_timeout_ms = 0;
  2104. if(data->set.max_send_speed)
  2105. send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
  2106. data->progress.ul_limit_size,
  2107. data->set.max_send_speed,
  2108. data->progress.ul_limit_start,
  2109. *nowp);
  2110. /* check if over recv speed */
  2111. recv_timeout_ms = 0;
  2112. if(data->set.max_recv_speed)
  2113. recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
  2114. data->progress.dl_limit_size,
  2115. data->set.max_recv_speed,
  2116. data->progress.dl_limit_start,
  2117. *nowp);
  2118. if(send_timeout_ms || recv_timeout_ms) {
  2119. Curl_ratelimit(data, *nowp);
  2120. multistate(data, MSTATE_RATELIMITING);
  2121. if(send_timeout_ms >= recv_timeout_ms)
  2122. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  2123. else
  2124. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  2125. break;
  2126. }
  2127. /* read/write data if it is ready to do so */
  2128. result = Curl_readwrite(data->conn, data, &done, &comeback);
  2129. if(done || (result == CURLE_RECV_ERROR)) {
  2130. /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
  2131. * condition and the server closed the reused connection exactly when
  2132. * we wanted to use it, so figure out if that is indeed the case.
  2133. */
  2134. CURLcode ret = Curl_retry_request(data, &newurl);
  2135. if(!ret)
  2136. retry = (newurl)?TRUE:FALSE;
  2137. else if(!result)
  2138. result = ret;
  2139. if(retry) {
  2140. /* if we are to retry, set the result to OK and consider the
  2141. request as done */
  2142. result = CURLE_OK;
  2143. done = TRUE;
  2144. }
  2145. }
  2146. else if((CURLE_HTTP2_STREAM == result) &&
  2147. Curl_h2_http_1_1_error(data)) {
  2148. CURLcode ret = Curl_retry_request(data, &newurl);
  2149. if(!ret) {
  2150. infof(data, "Downgrades to HTTP/1.1");
  2151. streamclose(data->conn, "Disconnect HTTP/2 for HTTP/1");
  2152. data->state.httpwant = CURL_HTTP_VERSION_1_1;
  2153. /* clear the error message bit too as we ignore the one we got */
  2154. data->state.errorbuf = FALSE;
  2155. if(!newurl)
  2156. /* typically for HTTP_1_1_REQUIRED error on first flight */
  2157. newurl = strdup(data->state.url);
  2158. /* if we are to retry, set the result to OK and consider the request
  2159. as done */
  2160. retry = TRUE;
  2161. result = CURLE_OK;
  2162. done = TRUE;
  2163. }
  2164. else
  2165. result = ret;
  2166. }
  2167. if(result) {
  2168. /*
  2169. * The transfer phase returned error, we mark the connection to get
  2170. * closed to prevent being reused. This is because we can't possibly
  2171. * know if the connection is in a good shape or not now. Unless it is
  2172. * a protocol which uses two "channels" like FTP, as then the error
  2173. * happened in the data connection.
  2174. */
  2175. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  2176. result != CURLE_HTTP2_STREAM)
  2177. streamclose(data->conn, "Transfer returned error");
  2178. Curl_posttransfer(data);
  2179. multi_done(data, result, TRUE);
  2180. }
  2181. else if(done) {
  2182. /* call this even if the readwrite function returned error */
  2183. Curl_posttransfer(data);
  2184. /* When we follow redirects or is set to retry the connection, we must
  2185. to go back to the CONNECT state */
  2186. if(data->req.newurl || retry) {
  2187. followtype follow = FOLLOW_NONE;
  2188. if(!retry) {
  2189. /* if the URL is a follow-location and not just a retried request
  2190. then figure out the URL here */
  2191. free(newurl);
  2192. newurl = data->req.newurl;
  2193. data->req.newurl = NULL;
  2194. follow = FOLLOW_REDIR;
  2195. }
  2196. else
  2197. follow = FOLLOW_RETRY;
  2198. (void)multi_done(data, CURLE_OK, FALSE);
  2199. /* multi_done() might return CURLE_GOT_NOTHING */
  2200. result = Curl_follow(data, newurl, follow);
  2201. if(!result) {
  2202. multistate(data, MSTATE_CONNECT);
  2203. rc = CURLM_CALL_MULTI_PERFORM;
  2204. }
  2205. free(newurl);
  2206. }
  2207. else {
  2208. /* after the transfer is done, go DONE */
  2209. /* but first check to see if we got a location info even though we're
  2210. not following redirects */
  2211. if(data->req.location) {
  2212. free(newurl);
  2213. newurl = data->req.location;
  2214. data->req.location = NULL;
  2215. result = Curl_follow(data, newurl, FOLLOW_FAKE);
  2216. free(newurl);
  2217. if(result) {
  2218. stream_error = TRUE;
  2219. result = multi_done(data, result, TRUE);
  2220. }
  2221. }
  2222. if(!result) {
  2223. multistate(data, MSTATE_DONE);
  2224. rc = CURLM_CALL_MULTI_PERFORM;
  2225. }
  2226. }
  2227. }
  2228. else if(comeback) {
  2229. /* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer
  2230. won't get stuck on this transfer at the expense of other concurrent
  2231. transfers */
  2232. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2233. }
  2234. break;
  2235. }
  2236. case MSTATE_DONE:
  2237. /* this state is highly transient, so run another loop after this */
  2238. rc = CURLM_CALL_MULTI_PERFORM;
  2239. if(data->conn) {
  2240. CURLcode res;
  2241. if(data->conn->bits.multiplex)
  2242. /* Check if we can move pending requests to connection */
  2243. process_pending_handles(multi); /* multiplexing */
  2244. /* post-transfer command */
  2245. res = multi_done(data, result, FALSE);
  2246. /* allow a previously set error code take precedence */
  2247. if(!result)
  2248. result = res;
  2249. }
  2250. #ifndef CURL_DISABLE_FTP
  2251. if(data->state.wildcardmatch) {
  2252. if(data->wildcard->state != CURLWC_DONE) {
  2253. /* if a wildcard is set and we are not ending -> lets start again
  2254. with MSTATE_INIT */
  2255. multistate(data, MSTATE_INIT);
  2256. break;
  2257. }
  2258. }
  2259. #endif
  2260. /* after we have DONE what we're supposed to do, go COMPLETED, and
  2261. it doesn't matter what the multi_done() returned! */
  2262. multistate(data, MSTATE_COMPLETED);
  2263. break;
  2264. case MSTATE_COMPLETED:
  2265. break;
  2266. case MSTATE_PENDING:
  2267. case MSTATE_MSGSENT:
  2268. /* handles in these states should NOT be in this list */
  2269. DEBUGASSERT(0);
  2270. break;
  2271. default:
  2272. return CURLM_INTERNAL_ERROR;
  2273. }
  2274. if(data->conn &&
  2275. data->mstate >= MSTATE_CONNECT &&
  2276. data->mstate < MSTATE_DO &&
  2277. rc != CURLM_CALL_MULTI_PERFORM &&
  2278. !multi_ischanged(multi, false)) {
  2279. /* We now handle stream timeouts if and only if this will be the last
  2280. * loop iteration. We only check this on the last iteration to ensure
  2281. * that if we know we have additional work to do immediately
  2282. * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before
  2283. * declaring the connection timed out as we may almost have a completed
  2284. * connection. */
  2285. multi_handle_timeout(data, nowp, &stream_error, &result, TRUE);
  2286. }
  2287. statemachine_end:
  2288. if(data->mstate < MSTATE_COMPLETED) {
  2289. if(result) {
  2290. /*
  2291. * If an error was returned, and we aren't in completed state now,
  2292. * then we go to completed and consider this transfer aborted.
  2293. */
  2294. /* NOTE: no attempt to disconnect connections must be made
  2295. in the case blocks above - cleanup happens only here */
  2296. /* Check if we can move pending requests to send pipe */
  2297. process_pending_handles(multi); /* connection */
  2298. if(data->conn) {
  2299. if(stream_error) {
  2300. /* Don't attempt to send data over a connection that timed out */
  2301. bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
  2302. struct connectdata *conn = data->conn;
  2303. /* This is where we make sure that the conn pointer is reset.
  2304. We don't have to do this in every case block above where a
  2305. failure is detected */
  2306. Curl_detach_connection(data);
  2307. /* remove connection from cache */
  2308. Curl_conncache_remove_conn(data, conn, TRUE);
  2309. /* disconnect properly */
  2310. Curl_disconnect(data, conn, dead_connection);
  2311. }
  2312. }
  2313. else if(data->mstate == MSTATE_CONNECT) {
  2314. /* Curl_connect() failed */
  2315. (void)Curl_posttransfer(data);
  2316. }
  2317. multistate(data, MSTATE_COMPLETED);
  2318. rc = CURLM_CALL_MULTI_PERFORM;
  2319. }
  2320. /* if there's still a connection to use, call the progress function */
  2321. else if(data->conn && Curl_pgrsUpdate(data)) {
  2322. /* aborted due to progress callback return code must close the
  2323. connection */
  2324. result = CURLE_ABORTED_BY_CALLBACK;
  2325. streamclose(data->conn, "Aborted by callback");
  2326. /* if not yet in DONE state, go there, otherwise COMPLETED */
  2327. multistate(data, (data->mstate < MSTATE_DONE)?
  2328. MSTATE_DONE: MSTATE_COMPLETED);
  2329. rc = CURLM_CALL_MULTI_PERFORM;
  2330. }
  2331. }
  2332. if(MSTATE_COMPLETED == data->mstate) {
  2333. if(data->set.fmultidone) {
  2334. /* signal via callback instead */
  2335. data->set.fmultidone(data, result);
  2336. }
  2337. else {
  2338. /* now fill in the Curl_message with this info */
  2339. msg = &data->msg;
  2340. msg->extmsg.msg = CURLMSG_DONE;
  2341. msg->extmsg.easy_handle = data;
  2342. msg->extmsg.data.result = result;
  2343. multi_addmsg(multi, msg);
  2344. DEBUGASSERT(!data->conn);
  2345. }
  2346. multistate(data, MSTATE_MSGSENT);
  2347. /* add this handle to the list of msgsent handles */
  2348. Curl_llist_insert_next(&multi->msgsent, multi->msgsent.tail, data,
  2349. &data->connect_queue);
  2350. /* unlink from the main list */
  2351. unlink_easy(multi, data);
  2352. return CURLM_OK;
  2353. }
  2354. } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
  2355. data->result = result;
  2356. return rc;
  2357. }
  2358. CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
  2359. {
  2360. struct Curl_easy *data;
  2361. CURLMcode returncode = CURLM_OK;
  2362. struct Curl_tree *t;
  2363. struct curltime now = Curl_now();
  2364. if(!GOOD_MULTI_HANDLE(multi))
  2365. return CURLM_BAD_HANDLE;
  2366. if(multi->in_callback)
  2367. return CURLM_RECURSIVE_API_CALL;
  2368. data = multi->easyp;
  2369. if(data) {
  2370. CURLMcode result;
  2371. bool nosig = data->set.no_signal;
  2372. SIGPIPE_VARIABLE(pipe_st);
  2373. sigpipe_ignore(data, &pipe_st);
  2374. /* Do the loop and only alter the signal ignore state if the next handle
  2375. has a different NO_SIGNAL state than the previous */
  2376. do {
  2377. /* the current node might be unlinked in multi_runsingle(), get the next
  2378. pointer now */
  2379. struct Curl_easy *datanext = data->next;
  2380. if(data->set.no_signal != nosig) {
  2381. sigpipe_restore(&pipe_st);
  2382. sigpipe_ignore(data, &pipe_st);
  2383. nosig = data->set.no_signal;
  2384. }
  2385. result = multi_runsingle(multi, &now, data);
  2386. if(result)
  2387. returncode = result;
  2388. data = datanext; /* operate on next handle */
  2389. } while(data);
  2390. sigpipe_restore(&pipe_st);
  2391. }
  2392. /*
  2393. * Simply remove all expired timers from the splay since handles are dealt
  2394. * with unconditionally by this function and curl_multi_timeout() requires
  2395. * that already passed/handled expire times are removed from the splay.
  2396. *
  2397. * It is important that the 'now' value is set at the entry of this function
  2398. * and not for the current time as it may have ticked a little while since
  2399. * then and then we risk this loop to remove timers that actually have not
  2400. * been handled!
  2401. */
  2402. do {
  2403. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  2404. if(t)
  2405. /* the removed may have another timeout in queue */
  2406. (void)add_next_timeout(now, multi, t->payload);
  2407. } while(t);
  2408. *running_handles = multi->num_alive;
  2409. if(CURLM_OK >= returncode)
  2410. returncode = Curl_update_timer(multi);
  2411. return returncode;
  2412. }
  2413. /* unlink_all_msgsent_handles() detaches all those easy handles from this
  2414. multi handle */
  2415. static void unlink_all_msgsent_handles(struct Curl_multi *multi)
  2416. {
  2417. struct Curl_llist_element *e = multi->msgsent.head;
  2418. if(e) {
  2419. struct Curl_easy *data = e->ptr;
  2420. DEBUGASSERT(data->mstate == MSTATE_MSGSENT);
  2421. data->multi = NULL;
  2422. }
  2423. }
  2424. CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
  2425. {
  2426. struct Curl_easy *data;
  2427. struct Curl_easy *nextdata;
  2428. if(GOOD_MULTI_HANDLE(multi)) {
  2429. if(multi->in_callback)
  2430. return CURLM_RECURSIVE_API_CALL;
  2431. multi->magic = 0; /* not good anymore */
  2432. unlink_all_msgsent_handles(multi);
  2433. process_pending_handles(multi);
  2434. /* First remove all remaining easy handles */
  2435. data = multi->easyp;
  2436. while(data) {
  2437. nextdata = data->next;
  2438. if(!data->state.done && data->conn)
  2439. /* if DONE was never called for this handle */
  2440. (void)multi_done(data, CURLE_OK, TRUE);
  2441. if(data->dns.hostcachetype == HCACHE_MULTI) {
  2442. /* clear out the usage of the shared DNS cache */
  2443. Curl_hostcache_clean(data, data->dns.hostcache);
  2444. data->dns.hostcache = NULL;
  2445. data->dns.hostcachetype = HCACHE_NONE;
  2446. }
  2447. /* Clear the pointer to the connection cache */
  2448. data->state.conn_cache = NULL;
  2449. data->multi = NULL; /* clear the association */
  2450. #ifdef USE_LIBPSL
  2451. if(data->psl == &multi->psl)
  2452. data->psl = NULL;
  2453. #endif
  2454. data = nextdata;
  2455. }
  2456. /* Close all the connections in the connection cache */
  2457. Curl_conncache_close_all_connections(&multi->conn_cache);
  2458. sockhash_destroy(&multi->sockhash);
  2459. Curl_conncache_destroy(&multi->conn_cache);
  2460. Curl_hash_destroy(&multi->hostcache);
  2461. Curl_psl_destroy(&multi->psl);
  2462. #ifdef USE_WINSOCK
  2463. WSACloseEvent(multi->wsa_event);
  2464. #else
  2465. #ifdef ENABLE_WAKEUP
  2466. wakeup_close(multi->wakeup_pair[0]);
  2467. wakeup_close(multi->wakeup_pair[1]);
  2468. #endif
  2469. #endif
  2470. #ifdef USE_SSL
  2471. Curl_free_multi_ssl_backend_data(multi->ssl_backend_data);
  2472. #endif
  2473. free(multi);
  2474. return CURLM_OK;
  2475. }
  2476. return CURLM_BAD_HANDLE;
  2477. }
  2478. /*
  2479. * curl_multi_info_read()
  2480. *
  2481. * This function is the primary way for a multi/multi_socket application to
  2482. * figure out if a transfer has ended. We MUST make this function as fast as
  2483. * possible as it will be polled frequently and we MUST NOT scan any lists in
  2484. * here to figure out things. We must scale fine to thousands of handles and
  2485. * beyond. The current design is fully O(1).
  2486. */
  2487. CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
  2488. {
  2489. struct Curl_message *msg;
  2490. *msgs_in_queue = 0; /* default to none */
  2491. if(GOOD_MULTI_HANDLE(multi) &&
  2492. !multi->in_callback &&
  2493. Curl_llist_count(&multi->msglist)) {
  2494. /* there is one or more messages in the list */
  2495. struct Curl_llist_element *e;
  2496. /* extract the head of the list to return */
  2497. e = multi->msglist.head;
  2498. msg = e->ptr;
  2499. /* remove the extracted entry */
  2500. Curl_llist_remove(&multi->msglist, e, NULL);
  2501. *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
  2502. return &msg->extmsg;
  2503. }
  2504. return NULL;
  2505. }
  2506. /*
  2507. * singlesocket() checks what sockets we deal with and their "action state"
  2508. * and if we have a different state in any of those sockets from last time we
  2509. * call the callback accordingly.
  2510. */
  2511. static CURLMcode singlesocket(struct Curl_multi *multi,
  2512. struct Curl_easy *data)
  2513. {
  2514. curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
  2515. int i;
  2516. struct Curl_sh_entry *entry;
  2517. curl_socket_t s;
  2518. int num;
  2519. unsigned int curraction;
  2520. unsigned char actions[MAX_SOCKSPEREASYHANDLE];
  2521. int rc;
  2522. for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
  2523. socks[i] = CURL_SOCKET_BAD;
  2524. /* Fill in the 'current' struct with the state as it is now: what sockets to
  2525. supervise and for what actions */
  2526. curraction = multi_getsock(data, socks);
  2527. /* We have 0 .. N sockets already and we get to know about the 0 .. M
  2528. sockets we should have from now on. Detect the differences, remove no
  2529. longer supervised ones and add new ones */
  2530. /* walk over the sockets we got right now */
  2531. for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
  2532. (curraction & GETSOCK_MASK_RW(i));
  2533. i++) {
  2534. unsigned char action = CURL_POLL_NONE;
  2535. unsigned char prevaction = 0;
  2536. int comboaction;
  2537. bool sincebefore = FALSE;
  2538. s = socks[i];
  2539. /* get it from the hash */
  2540. entry = sh_getentry(&multi->sockhash, s);
  2541. if(curraction & GETSOCK_READSOCK(i))
  2542. action |= CURL_POLL_IN;
  2543. if(curraction & GETSOCK_WRITESOCK(i))
  2544. action |= CURL_POLL_OUT;
  2545. actions[i] = action;
  2546. if(entry) {
  2547. /* check if new for this transfer */
  2548. int j;
  2549. for(j = 0; j< data->numsocks; j++) {
  2550. if(s == data->sockets[j]) {
  2551. prevaction = data->actions[j];
  2552. sincebefore = TRUE;
  2553. break;
  2554. }
  2555. }
  2556. }
  2557. else {
  2558. /* this is a socket we didn't have before, add it to the hash! */
  2559. entry = sh_addentry(&multi->sockhash, s);
  2560. if(!entry)
  2561. /* fatal */
  2562. return CURLM_OUT_OF_MEMORY;
  2563. }
  2564. if(sincebefore && (prevaction != action)) {
  2565. /* Socket was used already, but different action now */
  2566. if(prevaction & CURL_POLL_IN)
  2567. entry->readers--;
  2568. if(prevaction & CURL_POLL_OUT)
  2569. entry->writers--;
  2570. if(action & CURL_POLL_IN)
  2571. entry->readers++;
  2572. if(action & CURL_POLL_OUT)
  2573. entry->writers++;
  2574. }
  2575. else if(!sincebefore) {
  2576. /* a new user */
  2577. entry->users++;
  2578. if(action & CURL_POLL_IN)
  2579. entry->readers++;
  2580. if(action & CURL_POLL_OUT)
  2581. entry->writers++;
  2582. /* add 'data' to the transfer hash on this socket! */
  2583. if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */
  2584. sizeof(struct Curl_easy *), data)) {
  2585. Curl_hash_destroy(&entry->transfers);
  2586. return CURLM_OUT_OF_MEMORY;
  2587. }
  2588. }
  2589. comboaction = (entry->writers? CURL_POLL_OUT : 0) |
  2590. (entry->readers ? CURL_POLL_IN : 0);
  2591. /* socket existed before and has the same action set as before */
  2592. if(sincebefore && ((int)entry->action == comboaction))
  2593. /* same, continue */
  2594. continue;
  2595. if(multi->socket_cb) {
  2596. set_in_callback(multi, TRUE);
  2597. rc = multi->socket_cb(data, s, comboaction, multi->socket_userp,
  2598. entry->socketp);
  2599. set_in_callback(multi, FALSE);
  2600. if(rc == -1) {
  2601. multi->dead = TRUE;
  2602. return CURLM_ABORTED_BY_CALLBACK;
  2603. }
  2604. }
  2605. entry->action = comboaction; /* store the current action state */
  2606. }
  2607. num = i; /* number of sockets */
  2608. /* when we've walked over all the sockets we should have right now, we must
  2609. make sure to detect sockets that are removed */
  2610. for(i = 0; i< data->numsocks; i++) {
  2611. int j;
  2612. bool stillused = FALSE;
  2613. s = data->sockets[i];
  2614. for(j = 0; j < num; j++) {
  2615. if(s == socks[j]) {
  2616. /* this is still supervised */
  2617. stillused = TRUE;
  2618. break;
  2619. }
  2620. }
  2621. if(stillused)
  2622. continue;
  2623. entry = sh_getentry(&multi->sockhash, s);
  2624. /* if this is NULL here, the socket has been closed and notified so
  2625. already by Curl_multi_closed() */
  2626. if(entry) {
  2627. unsigned char oldactions = data->actions[i];
  2628. /* this socket has been removed. Decrease user count */
  2629. entry->users--;
  2630. if(oldactions & CURL_POLL_OUT)
  2631. entry->writers--;
  2632. if(oldactions & CURL_POLL_IN)
  2633. entry->readers--;
  2634. if(!entry->users) {
  2635. if(multi->socket_cb) {
  2636. set_in_callback(multi, TRUE);
  2637. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2638. multi->socket_userp, entry->socketp);
  2639. set_in_callback(multi, FALSE);
  2640. if(rc == -1) {
  2641. multi->dead = TRUE;
  2642. return CURLM_ABORTED_BY_CALLBACK;
  2643. }
  2644. }
  2645. sh_delentry(entry, &multi->sockhash, s);
  2646. }
  2647. else {
  2648. /* still users, but remove this handle as a user of this socket */
  2649. if(Curl_hash_delete(&entry->transfers, (char *)&data,
  2650. sizeof(struct Curl_easy *))) {
  2651. DEBUGASSERT(NULL);
  2652. }
  2653. }
  2654. }
  2655. } /* for loop over numsocks */
  2656. memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
  2657. memcpy(data->actions, actions, num*sizeof(char));
  2658. data->numsocks = num;
  2659. return CURLM_OK;
  2660. }
  2661. CURLcode Curl_updatesocket(struct Curl_easy *data)
  2662. {
  2663. if(singlesocket(data->multi, data))
  2664. return CURLE_ABORTED_BY_CALLBACK;
  2665. return CURLE_OK;
  2666. }
  2667. /*
  2668. * Curl_multi_closed()
  2669. *
  2670. * Used by the connect code to tell the multi_socket code that one of the
  2671. * sockets we were using is about to be closed. This function will then
  2672. * remove it from the sockethash for this handle to make the multi_socket API
  2673. * behave properly, especially for the case when libcurl will create another
  2674. * socket again and it gets the same file descriptor number.
  2675. */
  2676. void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
  2677. {
  2678. if(data) {
  2679. /* if there's still an easy handle associated with this connection */
  2680. struct Curl_multi *multi = data->multi;
  2681. if(multi) {
  2682. /* this is set if this connection is part of a handle that is added to
  2683. a multi handle, and only then this is necessary */
  2684. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  2685. if(entry) {
  2686. int rc = 0;
  2687. if(multi->socket_cb) {
  2688. set_in_callback(multi, TRUE);
  2689. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2690. multi->socket_userp, entry->socketp);
  2691. set_in_callback(multi, FALSE);
  2692. }
  2693. /* now remove it from the socket hash */
  2694. sh_delentry(entry, &multi->sockhash, s);
  2695. if(rc == -1)
  2696. /* This just marks the multi handle as "dead" without returning an
  2697. error code primarily because this function is used from many
  2698. places where propagating an error back is tricky. */
  2699. multi->dead = TRUE;
  2700. }
  2701. }
  2702. }
  2703. }
  2704. /*
  2705. * add_next_timeout()
  2706. *
  2707. * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
  2708. * when it has just been removed from the splay tree because the timeout has
  2709. * expired. This function is then to advance in the list to pick the next
  2710. * timeout to use (skip the already expired ones) and add this node back to
  2711. * the splay tree again.
  2712. *
  2713. * The splay tree only has each sessionhandle as a single node and the nearest
  2714. * timeout is used to sort it on.
  2715. */
  2716. static CURLMcode add_next_timeout(struct curltime now,
  2717. struct Curl_multi *multi,
  2718. struct Curl_easy *d)
  2719. {
  2720. struct curltime *tv = &d->state.expiretime;
  2721. struct Curl_llist *list = &d->state.timeoutlist;
  2722. struct Curl_llist_element *e;
  2723. struct time_node *node = NULL;
  2724. /* move over the timeout list for this specific handle and remove all
  2725. timeouts that are now passed tense and store the next pending
  2726. timeout in *tv */
  2727. for(e = list->head; e;) {
  2728. struct Curl_llist_element *n = e->next;
  2729. timediff_t diff;
  2730. node = (struct time_node *)e->ptr;
  2731. diff = Curl_timediff_us(node->time, now);
  2732. if(diff <= 0)
  2733. /* remove outdated entry */
  2734. Curl_llist_remove(list, e, NULL);
  2735. else
  2736. /* the list is sorted so get out on the first mismatch */
  2737. break;
  2738. e = n;
  2739. }
  2740. e = list->head;
  2741. if(!e) {
  2742. /* clear the expire times within the handles that we remove from the
  2743. splay tree */
  2744. tv->tv_sec = 0;
  2745. tv->tv_usec = 0;
  2746. }
  2747. else {
  2748. /* copy the first entry to 'tv' */
  2749. memcpy(tv, &node->time, sizeof(*tv));
  2750. /* Insert this node again into the splay. Keep the timer in the list in
  2751. case we need to recompute future timers. */
  2752. multi->timetree = Curl_splayinsert(*tv, multi->timetree,
  2753. &d->state.timenode);
  2754. }
  2755. return CURLM_OK;
  2756. }
  2757. static CURLMcode multi_socket(struct Curl_multi *multi,
  2758. bool checkall,
  2759. curl_socket_t s,
  2760. int ev_bitmask,
  2761. int *running_handles)
  2762. {
  2763. CURLMcode result = CURLM_OK;
  2764. struct Curl_easy *data = NULL;
  2765. struct Curl_tree *t;
  2766. struct curltime now = Curl_now();
  2767. bool first = FALSE;
  2768. bool nosig = FALSE;
  2769. SIGPIPE_VARIABLE(pipe_st);
  2770. if(checkall) {
  2771. /* *perform() deals with running_handles on its own */
  2772. result = curl_multi_perform(multi, running_handles);
  2773. /* walk through each easy handle and do the socket state change magic
  2774. and callbacks */
  2775. if(result != CURLM_BAD_HANDLE) {
  2776. data = multi->easyp;
  2777. while(data && !result) {
  2778. result = singlesocket(multi, data);
  2779. data = data->next;
  2780. }
  2781. }
  2782. /* or should we fall-through and do the timer-based stuff? */
  2783. return result;
  2784. }
  2785. if(s != CURL_SOCKET_TIMEOUT) {
  2786. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  2787. if(!entry)
  2788. /* Unmatched socket, we can't act on it but we ignore this fact. In
  2789. real-world tests it has been proved that libevent can in fact give
  2790. the application actions even though the socket was just previously
  2791. asked to get removed, so thus we better survive stray socket actions
  2792. and just move on. */
  2793. ;
  2794. else {
  2795. struct Curl_hash_iterator iter;
  2796. struct Curl_hash_element *he;
  2797. /* the socket can be shared by many transfers, iterate */
  2798. Curl_hash_start_iterate(&entry->transfers, &iter);
  2799. for(he = Curl_hash_next_element(&iter); he;
  2800. he = Curl_hash_next_element(&iter)) {
  2801. data = (struct Curl_easy *)he->ptr;
  2802. DEBUGASSERT(data);
  2803. DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER);
  2804. if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK))
  2805. /* set socket event bitmask if they're not locked */
  2806. data->conn->cselect_bits = (unsigned char)ev_bitmask;
  2807. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2808. }
  2809. /* Now we fall-through and do the timer-based stuff, since we don't want
  2810. to force the user to have to deal with timeouts as long as at least
  2811. one connection in fact has traffic. */
  2812. data = NULL; /* set data to NULL again to avoid calling
  2813. multi_runsingle() in case there's no need to */
  2814. now = Curl_now(); /* get a newer time since the multi_runsingle() loop
  2815. may have taken some time */
  2816. }
  2817. }
  2818. else {
  2819. /* Asked to run due to time-out. Clear the 'lastcall' variable to force
  2820. Curl_update_timer() to trigger a callback to the app again even if the
  2821. same timeout is still the one to run after this call. That handles the
  2822. case when the application asks libcurl to run the timeout
  2823. prematurely. */
  2824. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  2825. }
  2826. /*
  2827. * The loop following here will go on as long as there are expire-times left
  2828. * to process in the splay and 'data' will be re-assigned for every expired
  2829. * handle we deal with.
  2830. */
  2831. do {
  2832. /* the first loop lap 'data' can be NULL */
  2833. if(data) {
  2834. if(!first) {
  2835. first = TRUE;
  2836. nosig = data->set.no_signal; /* initial state */
  2837. sigpipe_ignore(data, &pipe_st);
  2838. }
  2839. else if(data->set.no_signal != nosig) {
  2840. sigpipe_restore(&pipe_st);
  2841. sigpipe_ignore(data, &pipe_st);
  2842. nosig = data->set.no_signal; /* remember new state */
  2843. }
  2844. result = multi_runsingle(multi, &now, data);
  2845. if(CURLM_OK >= result) {
  2846. /* get the socket(s) and check if the state has been changed since
  2847. last */
  2848. result = singlesocket(multi, data);
  2849. if(result)
  2850. break;
  2851. }
  2852. }
  2853. /* Check if there's one (more) expired timer to deal with! This function
  2854. extracts a matching node if there is one */
  2855. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  2856. if(t) {
  2857. data = t->payload; /* assign this for next loop */
  2858. (void)add_next_timeout(now, multi, t->payload);
  2859. }
  2860. } while(t);
  2861. if(first)
  2862. sigpipe_restore(&pipe_st);
  2863. *running_handles = multi->num_alive;
  2864. return result;
  2865. }
  2866. #undef curl_multi_setopt
  2867. CURLMcode curl_multi_setopt(struct Curl_multi *multi,
  2868. CURLMoption option, ...)
  2869. {
  2870. CURLMcode res = CURLM_OK;
  2871. va_list param;
  2872. if(!GOOD_MULTI_HANDLE(multi))
  2873. return CURLM_BAD_HANDLE;
  2874. if(multi->in_callback)
  2875. return CURLM_RECURSIVE_API_CALL;
  2876. va_start(param, option);
  2877. switch(option) {
  2878. case CURLMOPT_SOCKETFUNCTION:
  2879. multi->socket_cb = va_arg(param, curl_socket_callback);
  2880. break;
  2881. case CURLMOPT_SOCKETDATA:
  2882. multi->socket_userp = va_arg(param, void *);
  2883. break;
  2884. case CURLMOPT_PUSHFUNCTION:
  2885. multi->push_cb = va_arg(param, curl_push_callback);
  2886. break;
  2887. case CURLMOPT_PUSHDATA:
  2888. multi->push_userp = va_arg(param, void *);
  2889. break;
  2890. case CURLMOPT_PIPELINING:
  2891. multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0;
  2892. break;
  2893. case CURLMOPT_TIMERFUNCTION:
  2894. multi->timer_cb = va_arg(param, curl_multi_timer_callback);
  2895. break;
  2896. case CURLMOPT_TIMERDATA:
  2897. multi->timer_userp = va_arg(param, void *);
  2898. break;
  2899. case CURLMOPT_MAXCONNECTS:
  2900. multi->maxconnects = va_arg(param, long);
  2901. break;
  2902. case CURLMOPT_MAX_HOST_CONNECTIONS:
  2903. multi->max_host_connections = va_arg(param, long);
  2904. break;
  2905. case CURLMOPT_MAX_TOTAL_CONNECTIONS:
  2906. multi->max_total_connections = va_arg(param, long);
  2907. break;
  2908. /* options formerly used for pipelining */
  2909. case CURLMOPT_MAX_PIPELINE_LENGTH:
  2910. break;
  2911. case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
  2912. break;
  2913. case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
  2914. break;
  2915. case CURLMOPT_PIPELINING_SITE_BL:
  2916. break;
  2917. case CURLMOPT_PIPELINING_SERVER_BL:
  2918. break;
  2919. case CURLMOPT_MAX_CONCURRENT_STREAMS:
  2920. {
  2921. long streams = va_arg(param, long);
  2922. if(streams < 1)
  2923. streams = 100;
  2924. multi->max_concurrent_streams = curlx_sltoui(streams);
  2925. }
  2926. break;
  2927. default:
  2928. res = CURLM_UNKNOWN_OPTION;
  2929. break;
  2930. }
  2931. va_end(param);
  2932. return res;
  2933. }
  2934. /* we define curl_multi_socket() in the public multi.h header */
  2935. #undef curl_multi_socket
  2936. CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
  2937. int *running_handles)
  2938. {
  2939. CURLMcode result;
  2940. if(multi->in_callback)
  2941. return CURLM_RECURSIVE_API_CALL;
  2942. result = multi_socket(multi, FALSE, s, 0, running_handles);
  2943. if(CURLM_OK >= result)
  2944. result = Curl_update_timer(multi);
  2945. return result;
  2946. }
  2947. CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
  2948. int ev_bitmask, int *running_handles)
  2949. {
  2950. CURLMcode result;
  2951. if(multi->in_callback)
  2952. return CURLM_RECURSIVE_API_CALL;
  2953. result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
  2954. if(CURLM_OK >= result)
  2955. result = Curl_update_timer(multi);
  2956. return result;
  2957. }
  2958. CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
  2959. {
  2960. CURLMcode result;
  2961. if(multi->in_callback)
  2962. return CURLM_RECURSIVE_API_CALL;
  2963. result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
  2964. if(CURLM_OK >= result)
  2965. result = Curl_update_timer(multi);
  2966. return result;
  2967. }
  2968. static CURLMcode multi_timeout(struct Curl_multi *multi,
  2969. long *timeout_ms)
  2970. {
  2971. static const struct curltime tv_zero = {0, 0};
  2972. if(multi->dead) {
  2973. *timeout_ms = 0;
  2974. return CURLM_OK;
  2975. }
  2976. if(multi->timetree) {
  2977. /* we have a tree of expire times */
  2978. struct curltime now = Curl_now();
  2979. /* splay the lowest to the bottom */
  2980. multi->timetree = Curl_splay(tv_zero, multi->timetree);
  2981. if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
  2982. /* some time left before expiration */
  2983. timediff_t diff = Curl_timediff_ceil(multi->timetree->key, now);
  2984. /* this should be safe even on 32 bit archs, as we don't use that
  2985. overly long timeouts */
  2986. *timeout_ms = (long)diff;
  2987. }
  2988. else
  2989. /* 0 means immediately */
  2990. *timeout_ms = 0;
  2991. }
  2992. else
  2993. *timeout_ms = -1;
  2994. return CURLM_OK;
  2995. }
  2996. CURLMcode curl_multi_timeout(struct Curl_multi *multi,
  2997. long *timeout_ms)
  2998. {
  2999. /* First, make some basic checks that the CURLM handle is a good handle */
  3000. if(!GOOD_MULTI_HANDLE(multi))
  3001. return CURLM_BAD_HANDLE;
  3002. if(multi->in_callback)
  3003. return CURLM_RECURSIVE_API_CALL;
  3004. return multi_timeout(multi, timeout_ms);
  3005. }
  3006. /*
  3007. * Tell the application it should update its timers, if it subscribes to the
  3008. * update timer callback.
  3009. */
  3010. CURLMcode Curl_update_timer(struct Curl_multi *multi)
  3011. {
  3012. long timeout_ms;
  3013. int rc;
  3014. if(!multi->timer_cb || multi->dead)
  3015. return CURLM_OK;
  3016. if(multi_timeout(multi, &timeout_ms)) {
  3017. return CURLM_OK;
  3018. }
  3019. if(timeout_ms < 0) {
  3020. static const struct curltime none = {0, 0};
  3021. if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
  3022. multi->timer_lastcall = none;
  3023. /* there's no timeout now but there was one previously, tell the app to
  3024. disable it */
  3025. set_in_callback(multi, TRUE);
  3026. rc = multi->timer_cb(multi, -1, multi->timer_userp);
  3027. set_in_callback(multi, FALSE);
  3028. if(rc == -1) {
  3029. multi->dead = TRUE;
  3030. return CURLM_ABORTED_BY_CALLBACK;
  3031. }
  3032. return CURLM_OK;
  3033. }
  3034. return CURLM_OK;
  3035. }
  3036. /* When multi_timeout() is done, multi->timetree points to the node with the
  3037. * timeout we got the (relative) time-out time for. We can thus easily check
  3038. * if this is the same (fixed) time as we got in a previous call and then
  3039. * avoid calling the callback again. */
  3040. if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
  3041. return CURLM_OK;
  3042. multi->timer_lastcall = multi->timetree->key;
  3043. set_in_callback(multi, TRUE);
  3044. rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp);
  3045. set_in_callback(multi, FALSE);
  3046. if(rc == -1) {
  3047. multi->dead = TRUE;
  3048. return CURLM_ABORTED_BY_CALLBACK;
  3049. }
  3050. return CURLM_OK;
  3051. }
  3052. /*
  3053. * multi_deltimeout()
  3054. *
  3055. * Remove a given timestamp from the list of timeouts.
  3056. */
  3057. static void
  3058. multi_deltimeout(struct Curl_easy *data, expire_id eid)
  3059. {
  3060. struct Curl_llist_element *e;
  3061. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3062. /* find and remove the specific node from the list */
  3063. for(e = timeoutlist->head; e; e = e->next) {
  3064. struct time_node *n = (struct time_node *)e->ptr;
  3065. if(n->eid == eid) {
  3066. Curl_llist_remove(timeoutlist, e, NULL);
  3067. return;
  3068. }
  3069. }
  3070. }
  3071. /*
  3072. * multi_addtimeout()
  3073. *
  3074. * Add a timestamp to the list of timeouts. Keep the list sorted so that head
  3075. * of list is always the timeout nearest in time.
  3076. *
  3077. */
  3078. static CURLMcode
  3079. multi_addtimeout(struct Curl_easy *data,
  3080. struct curltime *stamp,
  3081. expire_id eid)
  3082. {
  3083. struct Curl_llist_element *e;
  3084. struct time_node *node;
  3085. struct Curl_llist_element *prev = NULL;
  3086. size_t n;
  3087. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3088. node = &data->state.expires[eid];
  3089. /* copy the timestamp and id */
  3090. memcpy(&node->time, stamp, sizeof(*stamp));
  3091. node->eid = eid; /* also marks it as in use */
  3092. n = Curl_llist_count(timeoutlist);
  3093. if(n) {
  3094. /* find the correct spot in the list */
  3095. for(e = timeoutlist->head; e; e = e->next) {
  3096. struct time_node *check = (struct time_node *)e->ptr;
  3097. timediff_t diff = Curl_timediff(check->time, node->time);
  3098. if(diff > 0)
  3099. break;
  3100. prev = e;
  3101. }
  3102. }
  3103. /* else
  3104. this is the first timeout on the list */
  3105. Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
  3106. return CURLM_OK;
  3107. }
  3108. /*
  3109. * Curl_expire()
  3110. *
  3111. * given a number of milliseconds from now to use to set the 'act before
  3112. * this'-time for the transfer, to be extracted by curl_multi_timeout()
  3113. *
  3114. * The timeout will be added to a queue of timeouts if it defines a moment in
  3115. * time that is later than the current head of queue.
  3116. *
  3117. * Expire replaces a former timeout using the same id if already set.
  3118. */
  3119. void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
  3120. {
  3121. struct Curl_multi *multi = data->multi;
  3122. struct curltime *nowp = &data->state.expiretime;
  3123. struct curltime set;
  3124. /* this is only interesting while there is still an associated multi struct
  3125. remaining! */
  3126. if(!multi)
  3127. return;
  3128. DEBUGASSERT(id < EXPIRE_LAST);
  3129. set = Curl_now();
  3130. set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */
  3131. set.tv_usec += (unsigned int)(milli%1000)*1000;
  3132. if(set.tv_usec >= 1000000) {
  3133. set.tv_sec++;
  3134. set.tv_usec -= 1000000;
  3135. }
  3136. /* Remove any timer with the same id just in case. */
  3137. multi_deltimeout(data, id);
  3138. /* Add it to the timer list. It must stay in the list until it has expired
  3139. in case we need to recompute the minimum timer later. */
  3140. multi_addtimeout(data, &set, id);
  3141. if(nowp->tv_sec || nowp->tv_usec) {
  3142. /* This means that the struct is added as a node in the splay tree.
  3143. Compare if the new time is earlier, and only remove-old/add-new if it
  3144. is. */
  3145. timediff_t diff = Curl_timediff(set, *nowp);
  3146. int rc;
  3147. if(diff > 0) {
  3148. /* The current splay tree entry is sooner than this new expiry time.
  3149. We don't need to update our splay tree entry. */
  3150. return;
  3151. }
  3152. /* Since this is an updated time, we must remove the previous entry from
  3153. the splay tree first and then re-add the new value */
  3154. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3155. &multi->timetree);
  3156. if(rc)
  3157. infof(data, "Internal error removing splay node = %d", rc);
  3158. }
  3159. /* Indicate that we are in the splay tree and insert the new timer expiry
  3160. value since it is our local minimum. */
  3161. *nowp = set;
  3162. data->state.timenode.payload = data;
  3163. multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
  3164. &data->state.timenode);
  3165. }
  3166. /*
  3167. * Curl_expire_done()
  3168. *
  3169. * Removes the expire timer. Marks it as done.
  3170. *
  3171. */
  3172. void Curl_expire_done(struct Curl_easy *data, expire_id id)
  3173. {
  3174. /* remove the timer, if there */
  3175. multi_deltimeout(data, id);
  3176. }
  3177. /*
  3178. * Curl_expire_clear()
  3179. *
  3180. * Clear ALL timeout values for this handle.
  3181. */
  3182. void Curl_expire_clear(struct Curl_easy *data)
  3183. {
  3184. struct Curl_multi *multi = data->multi;
  3185. struct curltime *nowp = &data->state.expiretime;
  3186. /* this is only interesting while there is still an associated multi struct
  3187. remaining! */
  3188. if(!multi)
  3189. return;
  3190. if(nowp->tv_sec || nowp->tv_usec) {
  3191. /* Since this is an cleared time, we must remove the previous entry from
  3192. the splay tree */
  3193. struct Curl_llist *list = &data->state.timeoutlist;
  3194. int rc;
  3195. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3196. &multi->timetree);
  3197. if(rc)
  3198. infof(data, "Internal error clearing splay node = %d", rc);
  3199. /* flush the timeout list too */
  3200. while(list->size > 0) {
  3201. Curl_llist_remove(list, list->tail, NULL);
  3202. }
  3203. #ifdef DEBUGBUILD
  3204. infof(data, "Expire cleared");
  3205. #endif
  3206. nowp->tv_sec = 0;
  3207. nowp->tv_usec = 0;
  3208. }
  3209. }
  3210. CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
  3211. void *hashp)
  3212. {
  3213. struct Curl_sh_entry *there = NULL;
  3214. there = sh_getentry(&multi->sockhash, s);
  3215. if(!there)
  3216. return CURLM_BAD_SOCKET;
  3217. there->socketp = hashp;
  3218. return CURLM_OK;
  3219. }
  3220. size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
  3221. {
  3222. return multi ? multi->max_host_connections : 0;
  3223. }
  3224. size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
  3225. {
  3226. return multi ? multi->max_total_connections : 0;
  3227. }
  3228. /*
  3229. * When information about a connection has appeared, call this!
  3230. */
  3231. void Curl_multiuse_state(struct Curl_easy *data,
  3232. int bundlestate) /* use BUNDLE_* defines */
  3233. {
  3234. struct connectdata *conn;
  3235. DEBUGASSERT(data);
  3236. DEBUGASSERT(data->multi);
  3237. conn = data->conn;
  3238. DEBUGASSERT(conn);
  3239. DEBUGASSERT(conn->bundle);
  3240. conn->bundle->multiuse = bundlestate;
  3241. process_pending_handles(data->multi);
  3242. }
  3243. /* process_pending_handles() moves all handles from PENDING
  3244. back into the main list and change state to CONNECT */
  3245. static void process_pending_handles(struct Curl_multi *multi)
  3246. {
  3247. struct Curl_llist_element *e = multi->pending.head;
  3248. if(e) {
  3249. struct Curl_easy *data = e->ptr;
  3250. DEBUGASSERT(data->mstate == MSTATE_PENDING);
  3251. /* put it back into the main list */
  3252. link_easy(multi, data);
  3253. multistate(data, MSTATE_CONNECT);
  3254. /* Remove this node from the list */
  3255. Curl_llist_remove(&multi->pending, e, NULL);
  3256. /* Make sure that the handle will be processed soonish. */
  3257. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  3258. /* mark this as having been in the pending queue */
  3259. data->state.previouslypending = TRUE;
  3260. }
  3261. }
  3262. void Curl_set_in_callback(struct Curl_easy *data, bool value)
  3263. {
  3264. /* might get called when there is no data pointer! */
  3265. if(data) {
  3266. if(data->multi_easy)
  3267. data->multi_easy->in_callback = value;
  3268. else if(data->multi)
  3269. data->multi->in_callback = value;
  3270. }
  3271. }
  3272. bool Curl_is_in_callback(struct Curl_easy *easy)
  3273. {
  3274. return ((easy->multi && easy->multi->in_callback) ||
  3275. (easy->multi_easy && easy->multi_easy->in_callback));
  3276. }
  3277. unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
  3278. {
  3279. DEBUGASSERT(multi);
  3280. return multi->max_concurrent_streams;
  3281. }
  3282. struct Curl_easy **curl_multi_get_handles(struct Curl_multi *multi)
  3283. {
  3284. struct Curl_easy **a = malloc(sizeof(struct Curl_easy *) *
  3285. (multi->num_easy + 1));
  3286. if(a) {
  3287. int i = 0;
  3288. struct Curl_easy *e = multi->easyp;
  3289. while(e) {
  3290. DEBUGASSERT(i < multi->num_easy);
  3291. if(!e->internal)
  3292. a[i++] = e;
  3293. e = e->next;
  3294. }
  3295. a[i] = NULL; /* last entry is a NULL */
  3296. }
  3297. return a;
  3298. }