multi.c 118 KB

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