multi.c 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861
  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, 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->conn);
  862. DEBUGASSERT(conn);
  863. data->conn = conn;
  864. Curl_llist_append(&conn->easyq, data, &data->conn_queue);
  865. if(conn->handler && conn->handler->attach)
  866. conn->handler->attach(data, conn);
  867. Curl_conn_ev_data_attach(conn, data);
  868. }
  869. static int connecting_getsock(struct Curl_easy *data, curl_socket_t *socks)
  870. {
  871. struct connectdata *conn = data->conn;
  872. (void)socks;
  873. /* Not using `conn->sockfd` as `Curl_xfer_setup()` initializes
  874. * that *after* the connect. */
  875. if(conn && conn->sock[FIRSTSOCKET] != CURL_SOCKET_BAD) {
  876. /* Default is to wait to something from the server */
  877. socks[0] = conn->sock[FIRSTSOCKET];
  878. return GETSOCK_READSOCK(0);
  879. }
  880. return GETSOCK_BLANK;
  881. }
  882. static int protocol_getsock(struct Curl_easy *data, curl_socket_t *socks)
  883. {
  884. struct connectdata *conn = data->conn;
  885. if(conn && conn->handler->proto_getsock)
  886. return conn->handler->proto_getsock(data, conn, socks);
  887. else if(conn && conn->sockfd != CURL_SOCKET_BAD) {
  888. /* Default is to wait to something from the server */
  889. socks[0] = conn->sockfd;
  890. return GETSOCK_READSOCK(0);
  891. }
  892. return GETSOCK_BLANK;
  893. }
  894. static int domore_getsock(struct Curl_easy *data, curl_socket_t *socks)
  895. {
  896. struct connectdata *conn = data->conn;
  897. if(conn && conn->handler->domore_getsock)
  898. return conn->handler->domore_getsock(data, conn, socks);
  899. else if(conn && conn->sockfd != CURL_SOCKET_BAD) {
  900. /* Default is that we want to send something to the server */
  901. socks[0] = conn->sockfd;
  902. return GETSOCK_WRITESOCK(0);
  903. }
  904. return GETSOCK_BLANK;
  905. }
  906. static int doing_getsock(struct Curl_easy *data, curl_socket_t *socks)
  907. {
  908. struct connectdata *conn = data->conn;
  909. if(conn && conn->handler->doing_getsock)
  910. return conn->handler->doing_getsock(data, conn, socks);
  911. else if(conn && conn->sockfd != CURL_SOCKET_BAD) {
  912. /* Default is that we want to send something to the server */
  913. socks[0] = conn->sockfd;
  914. return GETSOCK_WRITESOCK(0);
  915. }
  916. return GETSOCK_BLANK;
  917. }
  918. static int perform_getsock(struct Curl_easy *data, curl_socket_t *sock)
  919. {
  920. struct connectdata *conn = data->conn;
  921. if(!conn)
  922. return GETSOCK_BLANK;
  923. else if(conn->handler->perform_getsock)
  924. return conn->handler->perform_getsock(data, conn, sock);
  925. else {
  926. /* Default is to obey the data->req.keepon flags for send/recv */
  927. int bitmap = GETSOCK_BLANK;
  928. unsigned sockindex = 0;
  929. if(CURL_WANT_RECV(data)) {
  930. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  931. bitmap |= GETSOCK_READSOCK(sockindex);
  932. sock[sockindex] = conn->sockfd;
  933. }
  934. if(CURL_WANT_SEND(data)) {
  935. if((conn->sockfd != conn->writesockfd) ||
  936. bitmap == GETSOCK_BLANK) {
  937. /* only if they are not the same socket and we have a readable
  938. one, we increase index */
  939. if(bitmap != GETSOCK_BLANK)
  940. sockindex++; /* increase index if we need two entries */
  941. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  942. sock[sockindex] = conn->writesockfd;
  943. }
  944. bitmap |= GETSOCK_WRITESOCK(sockindex);
  945. }
  946. return bitmap;
  947. }
  948. }
  949. /* Initializes `poll_set` with the current socket poll actions needed
  950. * for transfer `data`. */
  951. static void multi_getsock(struct Curl_easy *data,
  952. struct easy_pollset *ps)
  953. {
  954. /* The no connection case can happen when this is called from
  955. curl_multi_remove_handle() => singlesocket() => multi_getsock().
  956. */
  957. Curl_pollset_reset(data, ps);
  958. if(!data->conn)
  959. return;
  960. switch(data->mstate) {
  961. case MSTATE_INIT:
  962. case MSTATE_PENDING:
  963. case MSTATE_SETUP:
  964. case MSTATE_CONNECT:
  965. /* nothing to poll for yet */
  966. break;
  967. case MSTATE_RESOLVING:
  968. Curl_pollset_add_socks(data, ps, Curl_resolv_getsock);
  969. /* connection filters are not involved in this phase */
  970. break;
  971. case MSTATE_CONNECTING:
  972. case MSTATE_TUNNELING:
  973. Curl_pollset_add_socks(data, ps, connecting_getsock);
  974. Curl_conn_adjust_pollset(data, ps);
  975. break;
  976. case MSTATE_PROTOCONNECT:
  977. case MSTATE_PROTOCONNECTING:
  978. Curl_pollset_add_socks(data, ps, protocol_getsock);
  979. Curl_conn_adjust_pollset(data, ps);
  980. break;
  981. case MSTATE_DO:
  982. case MSTATE_DOING:
  983. Curl_pollset_add_socks(data, ps, doing_getsock);
  984. Curl_conn_adjust_pollset(data, ps);
  985. break;
  986. case MSTATE_DOING_MORE:
  987. Curl_pollset_add_socks(data, ps, domore_getsock);
  988. Curl_conn_adjust_pollset(data, ps);
  989. break;
  990. case MSTATE_DID: /* same as PERFORMING in regard to polling */
  991. case MSTATE_PERFORMING:
  992. Curl_pollset_add_socks(data, ps, perform_getsock);
  993. Curl_conn_adjust_pollset(data, ps);
  994. break;
  995. case MSTATE_RATELIMITING:
  996. /* we need to let time pass, ignore socket(s) */
  997. break;
  998. case MSTATE_DONE:
  999. case MSTATE_COMPLETED:
  1000. case MSTATE_MSGSENT:
  1001. /* nothing more to poll for */
  1002. break;
  1003. default:
  1004. failf(data, "multi_getsock: unexpected multi state %d", data->mstate);
  1005. DEBUGASSERT(0);
  1006. break;
  1007. }
  1008. }
  1009. CURLMcode curl_multi_fdset(struct Curl_multi *multi,
  1010. fd_set *read_fd_set, fd_set *write_fd_set,
  1011. fd_set *exc_fd_set, int *max_fd)
  1012. {
  1013. /* Scan through all the easy handles to get the file descriptors set.
  1014. Some easy handles may not have connected to the remote host yet,
  1015. and then we must make sure that is done. */
  1016. struct Curl_easy *data;
  1017. int this_max_fd = -1;
  1018. struct easy_pollset ps;
  1019. unsigned int i;
  1020. (void)exc_fd_set; /* not used */
  1021. if(!GOOD_MULTI_HANDLE(multi))
  1022. return CURLM_BAD_HANDLE;
  1023. if(multi->in_callback)
  1024. return CURLM_RECURSIVE_API_CALL;
  1025. memset(&ps, 0, sizeof(ps));
  1026. for(data = multi->easyp; data; data = data->next) {
  1027. multi_getsock(data, &ps);
  1028. for(i = 0; i < ps.num; i++) {
  1029. if(!FDSET_SOCK(ps.sockets[i]))
  1030. /* pretend it doesn't exist */
  1031. continue;
  1032. if(ps.actions[i] & CURL_POLL_IN)
  1033. FD_SET(ps.sockets[i], read_fd_set);
  1034. if(ps.actions[i] & CURL_POLL_OUT)
  1035. FD_SET(ps.sockets[i], write_fd_set);
  1036. if((int)ps.sockets[i] > this_max_fd)
  1037. this_max_fd = (int)ps.sockets[i];
  1038. }
  1039. }
  1040. *max_fd = this_max_fd;
  1041. return CURLM_OK;
  1042. }
  1043. CURLMcode curl_multi_waitfds(struct Curl_multi *multi,
  1044. struct curl_waitfd *ufds,
  1045. unsigned int size,
  1046. unsigned int *fd_count)
  1047. {
  1048. struct Curl_easy *data;
  1049. struct curl_waitfds cwfds;
  1050. struct easy_pollset ps;
  1051. if(!ufds)
  1052. return CURLM_BAD_FUNCTION_ARGUMENT;
  1053. if(!GOOD_MULTI_HANDLE(multi))
  1054. return CURLM_BAD_HANDLE;
  1055. if(multi->in_callback)
  1056. return CURLM_RECURSIVE_API_CALL;
  1057. Curl_waitfds_init(&cwfds, ufds, size);
  1058. memset(&ps, 0, sizeof(ps));
  1059. for(data = multi->easyp; data; data = data->next) {
  1060. multi_getsock(data, &ps);
  1061. if(Curl_waitfds_add_ps(&cwfds, &ps))
  1062. return CURLM_OUT_OF_MEMORY;
  1063. }
  1064. if(fd_count)
  1065. *fd_count = cwfds.n;
  1066. return CURLM_OK;
  1067. }
  1068. #ifdef USE_WINSOCK
  1069. /* Reset FD_WRITE for TCP sockets. Nothing is actually sent. UDP sockets can't
  1070. * be reset this way because an empty datagram would be sent. #9203
  1071. *
  1072. * "On Windows the internal state of FD_WRITE as returned from
  1073. * WSAEnumNetworkEvents is only reset after successful send()."
  1074. */
  1075. static void reset_socket_fdwrite(curl_socket_t s)
  1076. {
  1077. int t;
  1078. int l = (int)sizeof(t);
  1079. if(!getsockopt(s, SOL_SOCKET, SO_TYPE, (char *)&t, &l) && t == SOCK_STREAM)
  1080. send(s, NULL, 0, 0);
  1081. }
  1082. #endif
  1083. #define NUM_POLLS_ON_STACK 10
  1084. static CURLMcode multi_wait(struct Curl_multi *multi,
  1085. struct curl_waitfd extra_fds[],
  1086. unsigned int extra_nfds,
  1087. int timeout_ms,
  1088. int *ret,
  1089. bool extrawait, /* when no socket, wait */
  1090. bool use_wakeup)
  1091. {
  1092. struct Curl_easy *data;
  1093. struct easy_pollset ps;
  1094. size_t i;
  1095. long timeout_internal;
  1096. int retcode = 0;
  1097. struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
  1098. struct curl_pollfds cpfds;
  1099. unsigned int curl_nfds = 0; /* how many pfds are for curl transfers */
  1100. #ifdef USE_WINSOCK
  1101. WSANETWORKEVENTS wsa_events;
  1102. DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT);
  1103. #endif
  1104. #ifndef ENABLE_WAKEUP
  1105. (void)use_wakeup;
  1106. #endif
  1107. if(!GOOD_MULTI_HANDLE(multi))
  1108. return CURLM_BAD_HANDLE;
  1109. if(multi->in_callback)
  1110. return CURLM_RECURSIVE_API_CALL;
  1111. if(timeout_ms < 0)
  1112. return CURLM_BAD_FUNCTION_ARGUMENT;
  1113. Curl_pollfds_init(&cpfds, a_few_on_stack, NUM_POLLS_ON_STACK);
  1114. memset(&ps, 0, sizeof(ps));
  1115. /* Add the curl handles to our pollfds first */
  1116. for(data = multi->easyp; data; data = data->next) {
  1117. multi_getsock(data, &ps);
  1118. if(Curl_pollfds_add_ps(&cpfds, &ps)) {
  1119. Curl_pollfds_cleanup(&cpfds);
  1120. return CURLM_OUT_OF_MEMORY;
  1121. }
  1122. }
  1123. curl_nfds = cpfds.n; /* what curl internally uses in cpfds */
  1124. /* Add external file descriptions from poll-like struct curl_waitfd */
  1125. for(i = 0; i < extra_nfds; i++) {
  1126. unsigned short events = 0;
  1127. if(extra_fds[i].events & CURL_WAIT_POLLIN)
  1128. events |= POLLIN;
  1129. if(extra_fds[i].events & CURL_WAIT_POLLPRI)
  1130. events |= POLLPRI;
  1131. if(extra_fds[i].events & CURL_WAIT_POLLOUT)
  1132. events |= POLLOUT;
  1133. if(Curl_pollfds_add_sock(&cpfds, extra_fds[i].fd, events)) {
  1134. Curl_pollfds_cleanup(&cpfds);
  1135. return CURLM_OUT_OF_MEMORY;
  1136. }
  1137. }
  1138. #ifdef USE_WINSOCK
  1139. /* Set the WSA events based on the collected pollds */
  1140. for(i = 0; i < cpfds.n; i++) {
  1141. long mask = 0;
  1142. if(cpfds.pfds[i].events & POLLIN)
  1143. mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
  1144. if(cpfds.pfds[i].events & POLLPRI)
  1145. mask |= FD_OOB;
  1146. if(cpfds.pfds[i].events & POLLOUT) {
  1147. mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
  1148. reset_socket_fdwrite(cpfds.pfds[i].fd);
  1149. }
  1150. if(mask) {
  1151. if(WSAEventSelect(cpfds.pfds[i].fd, multi->wsa_event, mask) != 0) {
  1152. Curl_pollfds_cleanup(&cpfds);
  1153. return CURLM_INTERNAL_ERROR;
  1154. }
  1155. }
  1156. }
  1157. #endif
  1158. #ifdef ENABLE_WAKEUP
  1159. #ifndef USE_WINSOCK
  1160. if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
  1161. if(Curl_pollfds_add_sock(&cpfds, multi->wakeup_pair[0], POLLIN)) {
  1162. Curl_pollfds_cleanup(&cpfds);
  1163. return CURLM_OUT_OF_MEMORY;
  1164. }
  1165. }
  1166. #endif
  1167. #endif
  1168. /* We check the internal timeout *AFTER* we collected all sockets to
  1169. * poll. Collecting the sockets may install new timers by protocols
  1170. * and connection filters.
  1171. * Use the shorter one of the internal and the caller requested timeout. */
  1172. (void)multi_timeout(multi, &timeout_internal);
  1173. if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
  1174. timeout_ms = (int)timeout_internal;
  1175. #if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
  1176. if(cpfds.n || use_wakeup) {
  1177. #else
  1178. if(cpfds.n) {
  1179. #endif
  1180. int pollrc;
  1181. #ifdef USE_WINSOCK
  1182. if(cpfds.n) /* just pre-check with WinSock */
  1183. pollrc = Curl_poll(cpfds.pfds, cpfds.n, 0);
  1184. else
  1185. pollrc = 0;
  1186. #else
  1187. pollrc = Curl_poll(cpfds.pfds, cpfds.n, timeout_ms); /* wait... */
  1188. #endif
  1189. if(pollrc < 0) {
  1190. Curl_pollfds_cleanup(&cpfds);
  1191. return CURLM_UNRECOVERABLE_POLL;
  1192. }
  1193. if(pollrc > 0) {
  1194. retcode = pollrc;
  1195. #ifdef USE_WINSOCK
  1196. }
  1197. else { /* now wait... if not ready during the pre-check (pollrc == 0) */
  1198. WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, (DWORD)timeout_ms,
  1199. FALSE);
  1200. }
  1201. /* With WinSock, we have to run the following section unconditionally
  1202. to call WSAEventSelect(fd, event, 0) on all the sockets */
  1203. {
  1204. #endif
  1205. /* copy revents results from the poll to the curl_multi_wait poll
  1206. struct, the bit values of the actual underlying poll() implementation
  1207. may not be the same as the ones in the public libcurl API! */
  1208. for(i = 0; i < extra_nfds; i++) {
  1209. unsigned r = (unsigned)cpfds.pfds[curl_nfds + i].revents;
  1210. unsigned short mask = 0;
  1211. #ifdef USE_WINSOCK
  1212. curl_socket_t s = extra_fds[i].fd;
  1213. wsa_events.lNetworkEvents = 0;
  1214. if(WSAEnumNetworkEvents(s, NULL, &wsa_events) == 0) {
  1215. if(wsa_events.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))
  1216. mask |= CURL_WAIT_POLLIN;
  1217. if(wsa_events.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))
  1218. mask |= CURL_WAIT_POLLOUT;
  1219. if(wsa_events.lNetworkEvents & FD_OOB)
  1220. mask |= CURL_WAIT_POLLPRI;
  1221. if(ret && !pollrc && wsa_events.lNetworkEvents)
  1222. retcode++;
  1223. }
  1224. WSAEventSelect(s, multi->wsa_event, 0);
  1225. if(!pollrc) {
  1226. extra_fds[i].revents = (short)mask;
  1227. continue;
  1228. }
  1229. #endif
  1230. if(r & POLLIN)
  1231. mask |= CURL_WAIT_POLLIN;
  1232. if(r & POLLOUT)
  1233. mask |= CURL_WAIT_POLLOUT;
  1234. if(r & POLLPRI)
  1235. mask |= CURL_WAIT_POLLPRI;
  1236. extra_fds[i].revents = (short)mask;
  1237. }
  1238. #ifdef USE_WINSOCK
  1239. /* Count up all our own sockets that had activity,
  1240. and remove them from the event. */
  1241. if(curl_nfds) {
  1242. for(data = multi->easyp; data; data = data->next) {
  1243. multi_getsock(data, &ps);
  1244. for(i = 0; i < ps.num; i++) {
  1245. wsa_events.lNetworkEvents = 0;
  1246. if(WSAEnumNetworkEvents(ps.sockets[i], NULL,
  1247. &wsa_events) == 0) {
  1248. if(ret && !pollrc && wsa_events.lNetworkEvents)
  1249. retcode++;
  1250. }
  1251. WSAEventSelect(ps.sockets[i], multi->wsa_event, 0);
  1252. }
  1253. }
  1254. }
  1255. WSAResetEvent(multi->wsa_event);
  1256. #else
  1257. #ifdef ENABLE_WAKEUP
  1258. if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
  1259. if(cpfds.pfds[curl_nfds + extra_nfds].revents & POLLIN) {
  1260. char buf[64];
  1261. ssize_t nread;
  1262. while(1) {
  1263. /* the reading socket is non-blocking, try to read
  1264. data from it until it receives an error (except EINTR).
  1265. In normal cases it will get EAGAIN or EWOULDBLOCK
  1266. when there is no more data, breaking the loop. */
  1267. nread = wakeup_read(multi->wakeup_pair[0], buf, sizeof(buf));
  1268. if(nread <= 0) {
  1269. if(nread < 0 && EINTR == SOCKERRNO)
  1270. continue;
  1271. break;
  1272. }
  1273. }
  1274. /* do not count the wakeup socket into the returned value */
  1275. retcode--;
  1276. }
  1277. }
  1278. #endif
  1279. #endif
  1280. }
  1281. }
  1282. if(ret)
  1283. *ret = retcode;
  1284. #if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
  1285. if(extrawait && !cpfds.n && !use_wakeup) {
  1286. #else
  1287. if(extrawait && !cpfds.n) {
  1288. #endif
  1289. long sleep_ms = 0;
  1290. /* Avoid busy-looping when there's nothing particular to wait for */
  1291. if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) {
  1292. if(sleep_ms > timeout_ms)
  1293. sleep_ms = timeout_ms;
  1294. /* when there are no easy handles in the multi, this holds a -1
  1295. timeout */
  1296. else if(sleep_ms < 0)
  1297. sleep_ms = timeout_ms;
  1298. Curl_wait_ms(sleep_ms);
  1299. }
  1300. }
  1301. Curl_pollfds_cleanup(&cpfds);
  1302. return CURLM_OK;
  1303. }
  1304. CURLMcode curl_multi_wait(struct Curl_multi *multi,
  1305. struct curl_waitfd extra_fds[],
  1306. unsigned int extra_nfds,
  1307. int timeout_ms,
  1308. int *ret)
  1309. {
  1310. return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE,
  1311. FALSE);
  1312. }
  1313. CURLMcode curl_multi_poll(struct Curl_multi *multi,
  1314. struct curl_waitfd extra_fds[],
  1315. unsigned int extra_nfds,
  1316. int timeout_ms,
  1317. int *ret)
  1318. {
  1319. return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE,
  1320. TRUE);
  1321. }
  1322. CURLMcode curl_multi_wakeup(struct Curl_multi *multi)
  1323. {
  1324. /* this function is usually called from another thread,
  1325. it has to be careful only to access parts of the
  1326. Curl_multi struct that are constant */
  1327. #if defined(ENABLE_WAKEUP) && !defined(USE_WINSOCK)
  1328. #ifdef USE_EVENTFD
  1329. const void *buf;
  1330. const uint64_t val = 1;
  1331. #else
  1332. char buf[1];
  1333. #endif
  1334. #endif
  1335. /* GOOD_MULTI_HANDLE can be safely called */
  1336. if(!GOOD_MULTI_HANDLE(multi))
  1337. return CURLM_BAD_HANDLE;
  1338. #ifdef ENABLE_WAKEUP
  1339. #ifdef USE_WINSOCK
  1340. if(WSASetEvent(multi->wsa_event))
  1341. return CURLM_OK;
  1342. #else
  1343. /* the wakeup_pair variable is only written during init and cleanup,
  1344. making it safe to access from another thread after the init part
  1345. and before cleanup */
  1346. if(multi->wakeup_pair[1] != CURL_SOCKET_BAD) {
  1347. #ifdef USE_EVENTFD
  1348. buf = &val;
  1349. #else
  1350. buf[0] = 1;
  1351. #endif
  1352. while(1) {
  1353. /* swrite() is not thread-safe in general, because concurrent calls
  1354. can have their messages interleaved, but in this case the content
  1355. of the messages does not matter, which makes it ok to call.
  1356. The write socket is set to non-blocking, this way this function
  1357. cannot block, making it safe to call even from the same thread
  1358. that will call curl_multi_wait(). If swrite() returns that it
  1359. would block, it's considered successful because it means that
  1360. previous calls to this function will wake up the poll(). */
  1361. if(wakeup_write(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) {
  1362. int err = SOCKERRNO;
  1363. int return_success;
  1364. #ifdef USE_WINSOCK
  1365. return_success = WSAEWOULDBLOCK == err;
  1366. #else
  1367. if(EINTR == err)
  1368. continue;
  1369. return_success = EWOULDBLOCK == err || EAGAIN == err;
  1370. #endif
  1371. if(!return_success)
  1372. return CURLM_WAKEUP_FAILURE;
  1373. }
  1374. return CURLM_OK;
  1375. }
  1376. }
  1377. #endif
  1378. #endif
  1379. return CURLM_WAKEUP_FAILURE;
  1380. }
  1381. /*
  1382. * multi_ischanged() is called
  1383. *
  1384. * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
  1385. * => CONNECT action.
  1386. *
  1387. * Set 'clear' to TRUE to have it also clear the state variable.
  1388. */
  1389. static bool multi_ischanged(struct Curl_multi *multi, bool clear)
  1390. {
  1391. bool retval = multi->recheckstate;
  1392. if(clear)
  1393. multi->recheckstate = FALSE;
  1394. return retval;
  1395. }
  1396. /*
  1397. * Curl_multi_connchanged() is called to tell that there is a connection in
  1398. * this multi handle that has changed state (multiplexing become possible, the
  1399. * number of allowed streams changed or similar), and a subsequent use of this
  1400. * multi handle should move CONNECT_PEND handles back to CONNECT to have them
  1401. * retry.
  1402. */
  1403. void Curl_multi_connchanged(struct Curl_multi *multi)
  1404. {
  1405. multi->recheckstate = TRUE;
  1406. }
  1407. CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
  1408. struct Curl_easy *data,
  1409. struct connectdata *conn)
  1410. {
  1411. CURLMcode rc;
  1412. if(multi->in_callback)
  1413. return CURLM_RECURSIVE_API_CALL;
  1414. rc = curl_multi_add_handle(multi, data);
  1415. if(!rc) {
  1416. struct SingleRequest *k = &data->req;
  1417. /* pass in NULL for 'conn' here since we don't want to init the
  1418. connection, only this transfer */
  1419. Curl_init_do(data, NULL);
  1420. /* take this handle to the perform state right away */
  1421. multistate(data, MSTATE_PERFORMING);
  1422. Curl_attach_connection(data, conn);
  1423. k->keepon |= KEEP_RECV; /* setup to receive! */
  1424. }
  1425. return rc;
  1426. }
  1427. static CURLcode multi_do(struct Curl_easy *data, bool *done)
  1428. {
  1429. CURLcode result = CURLE_OK;
  1430. struct connectdata *conn = data->conn;
  1431. DEBUGASSERT(conn);
  1432. DEBUGASSERT(conn->handler);
  1433. if(conn->handler->do_it)
  1434. result = conn->handler->do_it(data, done);
  1435. return result;
  1436. }
  1437. /*
  1438. * multi_do_more() is called during the DO_MORE multi state. It is basically a
  1439. * second stage DO state which (wrongly) was introduced to support FTP's
  1440. * second connection.
  1441. *
  1442. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
  1443. * DOING state there's more work to do!
  1444. */
  1445. static CURLcode multi_do_more(struct Curl_easy *data, int *complete)
  1446. {
  1447. CURLcode result = CURLE_OK;
  1448. struct connectdata *conn = data->conn;
  1449. *complete = 0;
  1450. if(conn->handler->do_more)
  1451. result = conn->handler->do_more(data, complete);
  1452. return result;
  1453. }
  1454. /*
  1455. * Check whether a timeout occurred, and handle it if it did
  1456. */
  1457. static bool multi_handle_timeout(struct Curl_easy *data,
  1458. struct curltime *now,
  1459. bool *stream_error,
  1460. CURLcode *result,
  1461. bool connect_timeout)
  1462. {
  1463. timediff_t timeout_ms = Curl_timeleft(data, now, connect_timeout);
  1464. if(timeout_ms < 0) {
  1465. /* Handle timed out */
  1466. struct curltime since;
  1467. if(connect_timeout)
  1468. since = data->progress.t_startsingle;
  1469. else
  1470. since = data->progress.t_startop;
  1471. if(data->mstate == MSTATE_RESOLVING)
  1472. failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T
  1473. " milliseconds", Curl_timediff(*now, since));
  1474. else if(data->mstate == MSTATE_CONNECTING)
  1475. failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T
  1476. " milliseconds", Curl_timediff(*now, since));
  1477. else {
  1478. struct SingleRequest *k = &data->req;
  1479. if(k->size != -1) {
  1480. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1481. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
  1482. CURL_FORMAT_CURL_OFF_T " bytes received",
  1483. Curl_timediff(*now, since), k->bytecount, k->size);
  1484. }
  1485. else {
  1486. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1487. " milliseconds with %" CURL_FORMAT_CURL_OFF_T
  1488. " bytes received", Curl_timediff(*now, since), k->bytecount);
  1489. }
  1490. }
  1491. *result = CURLE_OPERATION_TIMEDOUT;
  1492. if(data->conn) {
  1493. /* Force connection closed if the connection has indeed been used */
  1494. if(data->mstate > MSTATE_DO) {
  1495. streamclose(data->conn, "Disconnect due to timeout");
  1496. *stream_error = TRUE;
  1497. }
  1498. (void)multi_done(data, *result, TRUE);
  1499. }
  1500. return TRUE;
  1501. }
  1502. return FALSE;
  1503. }
  1504. /*
  1505. * We are doing protocol-specific connecting and this is being called over and
  1506. * over from the multi interface until the connection phase is done on
  1507. * protocol layer.
  1508. */
  1509. static CURLcode protocol_connecting(struct Curl_easy *data, bool *done)
  1510. {
  1511. CURLcode result = CURLE_OK;
  1512. struct connectdata *conn = data->conn;
  1513. if(conn && conn->handler->connecting) {
  1514. *done = FALSE;
  1515. result = conn->handler->connecting(data, done);
  1516. }
  1517. else
  1518. *done = TRUE;
  1519. return result;
  1520. }
  1521. /*
  1522. * We are DOING this is being called over and over from the multi interface
  1523. * until the DOING phase is done on protocol layer.
  1524. */
  1525. static CURLcode protocol_doing(struct Curl_easy *data, bool *done)
  1526. {
  1527. CURLcode result = CURLE_OK;
  1528. struct connectdata *conn = data->conn;
  1529. if(conn && conn->handler->doing) {
  1530. *done = FALSE;
  1531. result = conn->handler->doing(data, done);
  1532. }
  1533. else
  1534. *done = TRUE;
  1535. return result;
  1536. }
  1537. /*
  1538. * We have discovered that the TCP connection has been successful, we can now
  1539. * proceed with some action.
  1540. *
  1541. */
  1542. static CURLcode protocol_connect(struct Curl_easy *data,
  1543. bool *protocol_done)
  1544. {
  1545. CURLcode result = CURLE_OK;
  1546. struct connectdata *conn = data->conn;
  1547. DEBUGASSERT(conn);
  1548. DEBUGASSERT(protocol_done);
  1549. *protocol_done = FALSE;
  1550. if(Curl_conn_is_connected(conn, FIRSTSOCKET)
  1551. && conn->bits.protoconnstart) {
  1552. /* We already are connected, get back. This may happen when the connect
  1553. worked fine in the first call, like when we connect to a local server
  1554. or proxy. Note that we don't know if the protocol is actually done.
  1555. Unless this protocol doesn't have any protocol-connect callback, as
  1556. then we know we're done. */
  1557. if(!conn->handler->connecting)
  1558. *protocol_done = TRUE;
  1559. return CURLE_OK;
  1560. }
  1561. if(!conn->bits.protoconnstart) {
  1562. if(conn->handler->connect_it) {
  1563. /* is there a protocol-specific connect() procedure? */
  1564. /* Call the protocol-specific connect function */
  1565. result = conn->handler->connect_it(data, protocol_done);
  1566. }
  1567. else
  1568. *protocol_done = TRUE;
  1569. /* it has started, possibly even completed but that knowledge isn't stored
  1570. in this bit! */
  1571. if(!result)
  1572. conn->bits.protoconnstart = TRUE;
  1573. }
  1574. return result; /* pass back status */
  1575. }
  1576. static void set_in_callback(struct Curl_multi *multi, bool value)
  1577. {
  1578. multi->in_callback = value;
  1579. }
  1580. static CURLMcode multi_runsingle(struct Curl_multi *multi,
  1581. struct curltime *nowp,
  1582. struct Curl_easy *data)
  1583. {
  1584. struct Curl_message *msg = NULL;
  1585. bool connected;
  1586. bool async;
  1587. bool protocol_connected = FALSE;
  1588. bool dophase_done = FALSE;
  1589. CURLMcode rc;
  1590. CURLcode result = CURLE_OK;
  1591. timediff_t recv_timeout_ms;
  1592. timediff_t send_timeout_ms;
  1593. int control;
  1594. if(!GOOD_EASY_HANDLE(data))
  1595. return CURLM_BAD_EASY_HANDLE;
  1596. if(multi->dead) {
  1597. /* a multi-level callback returned error before, meaning every individual
  1598. transfer now has failed */
  1599. result = CURLE_ABORTED_BY_CALLBACK;
  1600. Curl_posttransfer(data);
  1601. multi_done(data, result, FALSE);
  1602. multistate(data, MSTATE_COMPLETED);
  1603. }
  1604. multi_warn_debug(multi, data);
  1605. do {
  1606. /* A "stream" here is a logical stream if the protocol can handle that
  1607. (HTTP/2), or the full connection for older protocols */
  1608. bool stream_error = FALSE;
  1609. rc = CURLM_OK;
  1610. if(multi_ischanged(multi, TRUE)) {
  1611. DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue"));
  1612. process_pending_handles(multi); /* multiplexed */
  1613. }
  1614. if(data->mstate > MSTATE_CONNECT &&
  1615. data->mstate < MSTATE_COMPLETED) {
  1616. /* Make sure we set the connection's current owner */
  1617. DEBUGASSERT(data->conn);
  1618. if(!data->conn)
  1619. return CURLM_INTERNAL_ERROR;
  1620. }
  1621. /* Wait for the connect state as only then is the start time stored, but
  1622. we must not check already completed handles */
  1623. if((data->mstate >= MSTATE_CONNECT) && (data->mstate < MSTATE_COMPLETED) &&
  1624. multi_handle_timeout(data, nowp, &stream_error, &result, FALSE))
  1625. /* Skip the statemachine and go directly to error handling section. */
  1626. goto statemachine_end;
  1627. switch(data->mstate) {
  1628. case MSTATE_INIT:
  1629. /* Transitional state. init this transfer. A handle never comes
  1630. back to this state. */
  1631. result = Curl_pretransfer(data);
  1632. if(result)
  1633. break;
  1634. /* after init, go SETUP */
  1635. multistate(data, MSTATE_SETUP);
  1636. (void)Curl_pgrsTime(data, TIMER_STARTOP);
  1637. FALLTHROUGH();
  1638. case MSTATE_SETUP:
  1639. /* Transitional state. Setup things for a new transfer. The handle
  1640. can come back to this state on a redirect. */
  1641. *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE);
  1642. if(data->set.timeout)
  1643. Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT);
  1644. if(data->set.connecttimeout)
  1645. /* Since a connection might go to pending and back to CONNECT several
  1646. times before it actually takes off, we need to set the timeout once
  1647. in SETUP before we enter CONNECT the first time. */
  1648. Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT);
  1649. multistate(data, MSTATE_CONNECT);
  1650. FALLTHROUGH();
  1651. case MSTATE_CONNECT:
  1652. /* Connect. We want to get a connection identifier filled in. This state
  1653. can be entered from SETUP and from PENDING. */
  1654. result = Curl_connect(data, &async, &connected);
  1655. if(CURLE_NO_CONNECTION_AVAILABLE == result) {
  1656. /* There was no connection available. We will go to the pending
  1657. state and wait for an available connection. */
  1658. multistate(data, MSTATE_PENDING);
  1659. /* add this handle to the list of connect-pending handles */
  1660. Curl_llist_append(&multi->pending, data, &data->connect_queue);
  1661. /* unlink from the main list */
  1662. unlink_easy(multi, data);
  1663. result = CURLE_OK;
  1664. break;
  1665. }
  1666. else
  1667. process_pending_handles(data->multi);
  1668. if(!result) {
  1669. *nowp = Curl_pgrsTime(data, TIMER_POSTQUEUE);
  1670. if(async)
  1671. /* We're now waiting for an asynchronous name lookup */
  1672. multistate(data, MSTATE_RESOLVING);
  1673. else {
  1674. /* after the connect has been sent off, go WAITCONNECT unless the
  1675. protocol connect is already done and we can go directly to
  1676. WAITDO or DO! */
  1677. rc = CURLM_CALL_MULTI_PERFORM;
  1678. if(connected)
  1679. multistate(data, MSTATE_PROTOCONNECT);
  1680. else {
  1681. multistate(data, MSTATE_CONNECTING);
  1682. }
  1683. }
  1684. }
  1685. break;
  1686. case MSTATE_RESOLVING:
  1687. /* awaiting an asynch name resolve to complete */
  1688. {
  1689. struct Curl_dns_entry *dns = NULL;
  1690. struct connectdata *conn = data->conn;
  1691. const char *hostname;
  1692. DEBUGASSERT(conn);
  1693. #ifndef CURL_DISABLE_PROXY
  1694. if(conn->bits.httpproxy)
  1695. hostname = conn->http_proxy.host.name;
  1696. else
  1697. #endif
  1698. if(conn->bits.conn_to_host)
  1699. hostname = conn->conn_to_host.name;
  1700. else
  1701. hostname = conn->host.name;
  1702. /* check if we have the name resolved by now */
  1703. dns = Curl_fetch_addr(data, hostname, conn->primary.remote_port);
  1704. if(dns) {
  1705. #ifdef CURLRES_ASYNCH
  1706. data->state.async.dns = dns;
  1707. data->state.async.done = TRUE;
  1708. #endif
  1709. result = CURLE_OK;
  1710. infof(data, "Hostname '%s' was found in DNS cache", hostname);
  1711. }
  1712. if(!dns)
  1713. result = Curl_resolv_check(data, &dns);
  1714. /* Update sockets here, because the socket(s) may have been
  1715. closed and the application thus needs to be told, even if it
  1716. is likely that the same socket(s) will again be used further
  1717. down. If the name has not yet been resolved, it is likely
  1718. that new sockets have been opened in an attempt to contact
  1719. another resolver. */
  1720. rc = singlesocket(multi, data);
  1721. if(rc)
  1722. return rc;
  1723. if(dns) {
  1724. /* Perform the next step in the connection phase, and then move on
  1725. to the WAITCONNECT state */
  1726. result = Curl_once_resolved(data, &connected);
  1727. if(result)
  1728. /* if Curl_once_resolved() returns failure, the connection struct
  1729. is already freed and gone */
  1730. data->conn = NULL; /* no more connection */
  1731. else {
  1732. /* call again please so that we get the next socket setup */
  1733. rc = CURLM_CALL_MULTI_PERFORM;
  1734. if(connected)
  1735. multistate(data, MSTATE_PROTOCONNECT);
  1736. else {
  1737. multistate(data, MSTATE_CONNECTING);
  1738. }
  1739. }
  1740. }
  1741. if(result) {
  1742. /* failure detected */
  1743. stream_error = TRUE;
  1744. break;
  1745. }
  1746. }
  1747. break;
  1748. #ifndef CURL_DISABLE_HTTP
  1749. case MSTATE_TUNNELING:
  1750. /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
  1751. DEBUGASSERT(data->conn);
  1752. result = Curl_http_connect(data, &protocol_connected);
  1753. #ifndef CURL_DISABLE_PROXY
  1754. if(data->conn->bits.proxy_connect_closed) {
  1755. rc = CURLM_CALL_MULTI_PERFORM;
  1756. /* connect back to proxy again */
  1757. result = CURLE_OK;
  1758. multi_done(data, CURLE_OK, FALSE);
  1759. multistate(data, MSTATE_CONNECT);
  1760. }
  1761. else
  1762. #endif
  1763. if(!result) {
  1764. rc = CURLM_CALL_MULTI_PERFORM;
  1765. /* initiate protocol connect phase */
  1766. multistate(data, MSTATE_PROTOCONNECT);
  1767. }
  1768. else
  1769. stream_error = TRUE;
  1770. break;
  1771. #endif
  1772. case MSTATE_CONNECTING:
  1773. /* awaiting a completion of an asynch TCP connect */
  1774. DEBUGASSERT(data->conn);
  1775. result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected);
  1776. if(connected && !result) {
  1777. rc = CURLM_CALL_MULTI_PERFORM;
  1778. multistate(data, MSTATE_PROTOCONNECT);
  1779. }
  1780. else if(result) {
  1781. /* failure detected */
  1782. Curl_posttransfer(data);
  1783. multi_done(data, result, TRUE);
  1784. stream_error = TRUE;
  1785. break;
  1786. }
  1787. break;
  1788. case MSTATE_PROTOCONNECT:
  1789. if(!result && data->conn->bits.reuse) {
  1790. /* ftp seems to hang when protoconnect on reused connection
  1791. * since we handle PROTOCONNECT in general inside the filers, it
  1792. * seems wrong to restart this on a reused connection. */
  1793. multistate(data, MSTATE_DO);
  1794. rc = CURLM_CALL_MULTI_PERFORM;
  1795. break;
  1796. }
  1797. if(!result)
  1798. result = protocol_connect(data, &protocol_connected);
  1799. if(!result && !protocol_connected) {
  1800. /* switch to waiting state */
  1801. multistate(data, MSTATE_PROTOCONNECTING);
  1802. rc = CURLM_CALL_MULTI_PERFORM;
  1803. }
  1804. else if(!result) {
  1805. /* protocol connect has completed, go WAITDO or DO */
  1806. multistate(data, MSTATE_DO);
  1807. rc = CURLM_CALL_MULTI_PERFORM;
  1808. }
  1809. else {
  1810. /* failure detected */
  1811. Curl_posttransfer(data);
  1812. multi_done(data, result, TRUE);
  1813. stream_error = TRUE;
  1814. }
  1815. break;
  1816. case MSTATE_PROTOCONNECTING:
  1817. /* protocol-specific connect phase */
  1818. result = protocol_connecting(data, &protocol_connected);
  1819. if(!result && protocol_connected) {
  1820. /* after the connect has completed, go WAITDO or DO */
  1821. multistate(data, MSTATE_DO);
  1822. rc = CURLM_CALL_MULTI_PERFORM;
  1823. }
  1824. else if(result) {
  1825. /* failure detected */
  1826. Curl_posttransfer(data);
  1827. multi_done(data, result, TRUE);
  1828. stream_error = TRUE;
  1829. }
  1830. break;
  1831. case MSTATE_DO:
  1832. if(data->set.fprereq) {
  1833. int prereq_rc;
  1834. /* call the prerequest callback function */
  1835. Curl_set_in_callback(data, true);
  1836. prereq_rc = data->set.fprereq(data->set.prereq_userp,
  1837. data->info.primary.remote_ip,
  1838. data->info.primary.local_ip,
  1839. data->info.primary.remote_port,
  1840. data->info.primary.local_port);
  1841. Curl_set_in_callback(data, false);
  1842. if(prereq_rc != CURL_PREREQFUNC_OK) {
  1843. failf(data, "operation aborted by pre-request callback");
  1844. /* failure in pre-request callback - don't do any other processing */
  1845. result = CURLE_ABORTED_BY_CALLBACK;
  1846. Curl_posttransfer(data);
  1847. multi_done(data, result, FALSE);
  1848. stream_error = TRUE;
  1849. break;
  1850. }
  1851. }
  1852. if(data->set.connect_only == 1) {
  1853. /* keep connection open for application to use the socket */
  1854. connkeep(data->conn, "CONNECT_ONLY");
  1855. multistate(data, MSTATE_DONE);
  1856. result = CURLE_OK;
  1857. rc = CURLM_CALL_MULTI_PERFORM;
  1858. }
  1859. else {
  1860. /* Perform the protocol's DO action */
  1861. result = multi_do(data, &dophase_done);
  1862. /* When multi_do() returns failure, data->conn might be NULL! */
  1863. if(!result) {
  1864. if(!dophase_done) {
  1865. #ifndef CURL_DISABLE_FTP
  1866. /* some steps needed for wildcard matching */
  1867. if(data->state.wildcardmatch) {
  1868. struct WildcardData *wc = data->wildcard;
  1869. if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
  1870. /* skip some states if it is important */
  1871. multi_done(data, CURLE_OK, FALSE);
  1872. /* if there's no connection left, skip the DONE state */
  1873. multistate(data, data->conn ?
  1874. MSTATE_DONE : MSTATE_COMPLETED);
  1875. rc = CURLM_CALL_MULTI_PERFORM;
  1876. break;
  1877. }
  1878. }
  1879. #endif
  1880. /* DO was not completed in one function call, we must continue
  1881. DOING... */
  1882. multistate(data, MSTATE_DOING);
  1883. rc = CURLM_CALL_MULTI_PERFORM;
  1884. }
  1885. /* after DO, go DO_DONE... or DO_MORE */
  1886. else if(data->conn->bits.do_more) {
  1887. /* we're supposed to do more, but we need to sit down, relax
  1888. and wait a little while first */
  1889. multistate(data, MSTATE_DOING_MORE);
  1890. rc = CURLM_CALL_MULTI_PERFORM;
  1891. }
  1892. else {
  1893. /* we're done with the DO, now DID */
  1894. multistate(data, MSTATE_DID);
  1895. rc = CURLM_CALL_MULTI_PERFORM;
  1896. }
  1897. }
  1898. else if((CURLE_SEND_ERROR == result) &&
  1899. data->conn->bits.reuse) {
  1900. /*
  1901. * In this situation, a connection that we were trying to use
  1902. * may have unexpectedly died. If possible, send the connection
  1903. * back to the CONNECT phase so we can try again.
  1904. */
  1905. char *newurl = NULL;
  1906. followtype follow = FOLLOW_NONE;
  1907. CURLcode drc;
  1908. drc = Curl_retry_request(data, &newurl);
  1909. if(drc) {
  1910. /* a failure here pretty much implies an out of memory */
  1911. result = drc;
  1912. stream_error = TRUE;
  1913. }
  1914. Curl_posttransfer(data);
  1915. drc = multi_done(data, result, FALSE);
  1916. /* When set to retry the connection, we must go back to the CONNECT
  1917. * state */
  1918. if(newurl) {
  1919. if(!drc || (drc == CURLE_SEND_ERROR)) {
  1920. follow = FOLLOW_RETRY;
  1921. drc = Curl_follow(data, newurl, follow);
  1922. if(!drc) {
  1923. multistate(data, MSTATE_SETUP);
  1924. rc = CURLM_CALL_MULTI_PERFORM;
  1925. result = CURLE_OK;
  1926. }
  1927. else {
  1928. /* Follow failed */
  1929. result = drc;
  1930. }
  1931. }
  1932. else {
  1933. /* done didn't return OK or SEND_ERROR */
  1934. result = drc;
  1935. }
  1936. }
  1937. else {
  1938. /* Have error handler disconnect conn if we can't retry */
  1939. stream_error = TRUE;
  1940. }
  1941. free(newurl);
  1942. }
  1943. else {
  1944. /* failure detected */
  1945. Curl_posttransfer(data);
  1946. if(data->conn)
  1947. multi_done(data, result, FALSE);
  1948. stream_error = TRUE;
  1949. }
  1950. }
  1951. break;
  1952. case MSTATE_DOING:
  1953. /* we continue DOING until the DO phase is complete */
  1954. DEBUGASSERT(data->conn);
  1955. result = protocol_doing(data, &dophase_done);
  1956. if(!result) {
  1957. if(dophase_done) {
  1958. /* after DO, go DO_DONE or DO_MORE */
  1959. multistate(data, data->conn->bits.do_more?
  1960. MSTATE_DOING_MORE : MSTATE_DID);
  1961. rc = CURLM_CALL_MULTI_PERFORM;
  1962. } /* dophase_done */
  1963. }
  1964. else {
  1965. /* failure detected */
  1966. Curl_posttransfer(data);
  1967. multi_done(data, result, FALSE);
  1968. stream_error = TRUE;
  1969. }
  1970. break;
  1971. case MSTATE_DOING_MORE:
  1972. /*
  1973. * When we are connected, DOING MORE and then go DID
  1974. */
  1975. DEBUGASSERT(data->conn);
  1976. result = multi_do_more(data, &control);
  1977. if(!result) {
  1978. if(control) {
  1979. /* if positive, advance to DO_DONE
  1980. if negative, go back to DOING */
  1981. multistate(data, control == 1?
  1982. MSTATE_DID : MSTATE_DOING);
  1983. rc = CURLM_CALL_MULTI_PERFORM;
  1984. }
  1985. /* else
  1986. stay in DO_MORE */
  1987. }
  1988. else {
  1989. /* failure detected */
  1990. Curl_posttransfer(data);
  1991. multi_done(data, result, FALSE);
  1992. stream_error = TRUE;
  1993. }
  1994. break;
  1995. case MSTATE_DID:
  1996. DEBUGASSERT(data->conn);
  1997. if(data->conn->bits.multiplex)
  1998. /* Check if we can move pending requests to send pipe */
  1999. process_pending_handles(multi); /* multiplexed */
  2000. /* Only perform the transfer if there's a good socket to work with.
  2001. Having both BAD is a signal to skip immediately to DONE */
  2002. if((data->conn->sockfd != CURL_SOCKET_BAD) ||
  2003. (data->conn->writesockfd != CURL_SOCKET_BAD))
  2004. multistate(data, MSTATE_PERFORMING);
  2005. else {
  2006. #ifndef CURL_DISABLE_FTP
  2007. if(data->state.wildcardmatch &&
  2008. ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
  2009. data->wildcard->state = CURLWC_DONE;
  2010. }
  2011. #endif
  2012. multistate(data, MSTATE_DONE);
  2013. }
  2014. rc = CURLM_CALL_MULTI_PERFORM;
  2015. break;
  2016. case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */
  2017. DEBUGASSERT(data->conn);
  2018. /* if both rates are within spec, resume transfer */
  2019. if(Curl_pgrsUpdate(data))
  2020. result = CURLE_ABORTED_BY_CALLBACK;
  2021. else
  2022. result = Curl_speedcheck(data, *nowp);
  2023. if(result) {
  2024. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  2025. result != CURLE_HTTP2_STREAM)
  2026. streamclose(data->conn, "Transfer returned error");
  2027. Curl_posttransfer(data);
  2028. multi_done(data, result, TRUE);
  2029. }
  2030. else {
  2031. send_timeout_ms = 0;
  2032. if(data->set.max_send_speed)
  2033. send_timeout_ms =
  2034. Curl_pgrsLimitWaitTime(data->progress.uploaded,
  2035. data->progress.ul_limit_size,
  2036. data->set.max_send_speed,
  2037. data->progress.ul_limit_start,
  2038. *nowp);
  2039. recv_timeout_ms = 0;
  2040. if(data->set.max_recv_speed)
  2041. recv_timeout_ms =
  2042. Curl_pgrsLimitWaitTime(data->progress.downloaded,
  2043. data->progress.dl_limit_size,
  2044. data->set.max_recv_speed,
  2045. data->progress.dl_limit_start,
  2046. *nowp);
  2047. if(!send_timeout_ms && !recv_timeout_ms) {
  2048. multistate(data, MSTATE_PERFORMING);
  2049. Curl_ratelimit(data, *nowp);
  2050. }
  2051. else if(send_timeout_ms >= recv_timeout_ms)
  2052. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  2053. else
  2054. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  2055. }
  2056. break;
  2057. case MSTATE_PERFORMING:
  2058. {
  2059. char *newurl = NULL;
  2060. bool retry = FALSE;
  2061. /* check if over send speed */
  2062. send_timeout_ms = 0;
  2063. if(data->set.max_send_speed)
  2064. send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
  2065. data->progress.ul_limit_size,
  2066. data->set.max_send_speed,
  2067. data->progress.ul_limit_start,
  2068. *nowp);
  2069. /* check if over recv speed */
  2070. recv_timeout_ms = 0;
  2071. if(data->set.max_recv_speed)
  2072. recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
  2073. data->progress.dl_limit_size,
  2074. data->set.max_recv_speed,
  2075. data->progress.dl_limit_start,
  2076. *nowp);
  2077. if(send_timeout_ms || recv_timeout_ms) {
  2078. Curl_ratelimit(data, *nowp);
  2079. multistate(data, MSTATE_RATELIMITING);
  2080. if(send_timeout_ms >= recv_timeout_ms)
  2081. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  2082. else
  2083. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  2084. break;
  2085. }
  2086. /* read/write data if it is ready to do so */
  2087. result = Curl_readwrite(data);
  2088. if(data->req.done || (result == CURLE_RECV_ERROR)) {
  2089. /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
  2090. * condition and the server closed the reused connection exactly when
  2091. * we wanted to use it, so figure out if that is indeed the case.
  2092. */
  2093. CURLcode ret = Curl_retry_request(data, &newurl);
  2094. if(!ret)
  2095. retry = (newurl)?TRUE:FALSE;
  2096. else if(!result)
  2097. result = ret;
  2098. if(retry) {
  2099. /* if we are to retry, set the result to OK and consider the
  2100. request as done */
  2101. result = CURLE_OK;
  2102. data->req.done = TRUE;
  2103. }
  2104. }
  2105. else if((CURLE_HTTP2_STREAM == result) &&
  2106. Curl_h2_http_1_1_error(data)) {
  2107. CURLcode ret = Curl_retry_request(data, &newurl);
  2108. if(!ret) {
  2109. infof(data, "Downgrades to HTTP/1.1");
  2110. streamclose(data->conn, "Disconnect HTTP/2 for HTTP/1");
  2111. data->state.httpwant = CURL_HTTP_VERSION_1_1;
  2112. /* clear the error message bit too as we ignore the one we got */
  2113. data->state.errorbuf = FALSE;
  2114. if(!newurl)
  2115. /* typically for HTTP_1_1_REQUIRED error on first flight */
  2116. newurl = strdup(data->state.url);
  2117. /* if we are to retry, set the result to OK and consider the request
  2118. as done */
  2119. retry = TRUE;
  2120. result = CURLE_OK;
  2121. data->req.done = TRUE;
  2122. }
  2123. else
  2124. result = ret;
  2125. }
  2126. if(result) {
  2127. /*
  2128. * The transfer phase returned error, we mark the connection to get
  2129. * closed to prevent being reused. This is because we can't possibly
  2130. * know if the connection is in a good shape or not now. Unless it is
  2131. * a protocol which uses two "channels" like FTP, as then the error
  2132. * happened in the data connection.
  2133. */
  2134. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  2135. result != CURLE_HTTP2_STREAM)
  2136. streamclose(data->conn, "Transfer returned error");
  2137. Curl_posttransfer(data);
  2138. multi_done(data, result, TRUE);
  2139. }
  2140. else if(data->req.done && !Curl_cwriter_is_paused(data)) {
  2141. /* call this even if the readwrite function returned error */
  2142. Curl_posttransfer(data);
  2143. /* When we follow redirects or is set to retry the connection, we must
  2144. to go back to the CONNECT state */
  2145. if(data->req.newurl || retry) {
  2146. followtype follow = FOLLOW_NONE;
  2147. if(!retry) {
  2148. /* if the URL is a follow-location and not just a retried request
  2149. then figure out the URL here */
  2150. free(newurl);
  2151. newurl = data->req.newurl;
  2152. data->req.newurl = NULL;
  2153. follow = FOLLOW_REDIR;
  2154. }
  2155. else
  2156. follow = FOLLOW_RETRY;
  2157. (void)multi_done(data, CURLE_OK, FALSE);
  2158. /* multi_done() might return CURLE_GOT_NOTHING */
  2159. result = Curl_follow(data, newurl, follow);
  2160. if(!result) {
  2161. multistate(data, MSTATE_SETUP);
  2162. rc = CURLM_CALL_MULTI_PERFORM;
  2163. }
  2164. }
  2165. else {
  2166. /* after the transfer is done, go DONE */
  2167. /* but first check to see if we got a location info even though we're
  2168. not following redirects */
  2169. if(data->req.location) {
  2170. free(newurl);
  2171. newurl = data->req.location;
  2172. data->req.location = NULL;
  2173. result = Curl_follow(data, newurl, FOLLOW_FAKE);
  2174. if(result) {
  2175. stream_error = TRUE;
  2176. result = multi_done(data, result, TRUE);
  2177. }
  2178. }
  2179. if(!result) {
  2180. multistate(data, MSTATE_DONE);
  2181. rc = CURLM_CALL_MULTI_PERFORM;
  2182. }
  2183. }
  2184. }
  2185. else if(data->state.select_bits && !Curl_xfer_is_blocked(data)) {
  2186. /* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer
  2187. won't get stuck on this transfer at the expense of other concurrent
  2188. transfers */
  2189. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2190. }
  2191. free(newurl);
  2192. break;
  2193. }
  2194. case MSTATE_DONE:
  2195. /* this state is highly transient, so run another loop after this */
  2196. rc = CURLM_CALL_MULTI_PERFORM;
  2197. if(data->conn) {
  2198. CURLcode res;
  2199. if(data->conn->bits.multiplex)
  2200. /* Check if we can move pending requests to connection */
  2201. process_pending_handles(multi); /* multiplexing */
  2202. /* post-transfer command */
  2203. res = multi_done(data, result, FALSE);
  2204. /* allow a previously set error code take precedence */
  2205. if(!result)
  2206. result = res;
  2207. }
  2208. #ifndef CURL_DISABLE_FTP
  2209. if(data->state.wildcardmatch) {
  2210. if(data->wildcard->state != CURLWC_DONE) {
  2211. /* if a wildcard is set and we are not ending -> lets start again
  2212. with MSTATE_INIT */
  2213. multistate(data, MSTATE_INIT);
  2214. break;
  2215. }
  2216. }
  2217. #endif
  2218. /* after we have DONE what we're supposed to do, go COMPLETED, and
  2219. it doesn't matter what the multi_done() returned! */
  2220. multistate(data, MSTATE_COMPLETED);
  2221. break;
  2222. case MSTATE_COMPLETED:
  2223. break;
  2224. case MSTATE_PENDING:
  2225. case MSTATE_MSGSENT:
  2226. /* handles in these states should NOT be in this list */
  2227. DEBUGASSERT(0);
  2228. break;
  2229. default:
  2230. return CURLM_INTERNAL_ERROR;
  2231. }
  2232. if(data->mstate >= MSTATE_CONNECT &&
  2233. data->mstate < MSTATE_DO &&
  2234. rc != CURLM_CALL_MULTI_PERFORM &&
  2235. !multi_ischanged(multi, false)) {
  2236. /* We now handle stream timeouts if and only if this will be the last
  2237. * loop iteration. We only check this on the last iteration to ensure
  2238. * that if we know we have additional work to do immediately
  2239. * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before
  2240. * declaring the connection timed out as we may almost have a completed
  2241. * connection. */
  2242. multi_handle_timeout(data, nowp, &stream_error, &result, FALSE);
  2243. }
  2244. statemachine_end:
  2245. if(data->mstate < MSTATE_COMPLETED) {
  2246. if(result) {
  2247. /*
  2248. * If an error was returned, and we aren't in completed state now,
  2249. * then we go to completed and consider this transfer aborted.
  2250. */
  2251. /* NOTE: no attempt to disconnect connections must be made
  2252. in the case blocks above - cleanup happens only here */
  2253. /* Check if we can move pending requests to send pipe */
  2254. process_pending_handles(multi); /* connection */
  2255. if(data->conn) {
  2256. if(stream_error) {
  2257. /* Don't attempt to send data over a connection that timed out */
  2258. bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
  2259. struct connectdata *conn = data->conn;
  2260. /* This is where we make sure that the conn pointer is reset.
  2261. We don't have to do this in every case block above where a
  2262. failure is detected */
  2263. Curl_detach_connection(data);
  2264. /* remove connection from cache */
  2265. Curl_conncache_remove_conn(data, conn, TRUE);
  2266. /* disconnect properly */
  2267. Curl_disconnect(data, conn, dead_connection);
  2268. }
  2269. }
  2270. else if(data->mstate == MSTATE_CONNECT) {
  2271. /* Curl_connect() failed */
  2272. (void)Curl_posttransfer(data);
  2273. }
  2274. multistate(data, MSTATE_COMPLETED);
  2275. rc = CURLM_CALL_MULTI_PERFORM;
  2276. }
  2277. /* if there's still a connection to use, call the progress function */
  2278. else if(data->conn && Curl_pgrsUpdate(data)) {
  2279. /* aborted due to progress callback return code must close the
  2280. connection */
  2281. result = CURLE_ABORTED_BY_CALLBACK;
  2282. streamclose(data->conn, "Aborted by callback");
  2283. /* if not yet in DONE state, go there, otherwise COMPLETED */
  2284. multistate(data, (data->mstate < MSTATE_DONE)?
  2285. MSTATE_DONE: MSTATE_COMPLETED);
  2286. rc = CURLM_CALL_MULTI_PERFORM;
  2287. }
  2288. }
  2289. if(MSTATE_COMPLETED == data->mstate) {
  2290. if(data->set.fmultidone) {
  2291. /* signal via callback instead */
  2292. data->set.fmultidone(data, result);
  2293. }
  2294. else {
  2295. /* now fill in the Curl_message with this info */
  2296. msg = &data->msg;
  2297. msg->extmsg.msg = CURLMSG_DONE;
  2298. msg->extmsg.easy_handle = data;
  2299. msg->extmsg.data.result = result;
  2300. multi_addmsg(multi, msg);
  2301. DEBUGASSERT(!data->conn);
  2302. }
  2303. multistate(data, MSTATE_MSGSENT);
  2304. /* add this handle to the list of msgsent handles */
  2305. Curl_llist_append(&multi->msgsent, data, &data->connect_queue);
  2306. /* unlink from the main list */
  2307. unlink_easy(multi, data);
  2308. return CURLM_OK;
  2309. }
  2310. } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
  2311. data->result = result;
  2312. return rc;
  2313. }
  2314. CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
  2315. {
  2316. struct Curl_easy *data;
  2317. CURLMcode returncode = CURLM_OK;
  2318. struct Curl_tree *t;
  2319. struct curltime now = Curl_now();
  2320. if(!GOOD_MULTI_HANDLE(multi))
  2321. return CURLM_BAD_HANDLE;
  2322. if(multi->in_callback)
  2323. return CURLM_RECURSIVE_API_CALL;
  2324. data = multi->easyp;
  2325. if(data) {
  2326. CURLMcode result;
  2327. bool nosig = data->set.no_signal;
  2328. SIGPIPE_VARIABLE(pipe_st);
  2329. sigpipe_ignore(data, &pipe_st);
  2330. /* Do the loop and only alter the signal ignore state if the next handle
  2331. has a different NO_SIGNAL state than the previous */
  2332. do {
  2333. /* the current node might be unlinked in multi_runsingle(), get the next
  2334. pointer now */
  2335. struct Curl_easy *datanext = data->next;
  2336. if(data->set.no_signal != nosig) {
  2337. sigpipe_restore(&pipe_st);
  2338. sigpipe_ignore(data, &pipe_st);
  2339. nosig = data->set.no_signal;
  2340. }
  2341. result = multi_runsingle(multi, &now, data);
  2342. if(result)
  2343. returncode = result;
  2344. data = datanext; /* operate on next handle */
  2345. } while(data);
  2346. sigpipe_restore(&pipe_st);
  2347. }
  2348. /*
  2349. * Simply remove all expired timers from the splay since handles are dealt
  2350. * with unconditionally by this function and curl_multi_timeout() requires
  2351. * that already passed/handled expire times are removed from the splay.
  2352. *
  2353. * It is important that the 'now' value is set at the entry of this function
  2354. * and not for the current time as it may have ticked a little while since
  2355. * then and then we risk this loop to remove timers that actually have not
  2356. * been handled!
  2357. */
  2358. do {
  2359. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  2360. if(t) {
  2361. /* the removed may have another timeout in queue */
  2362. data = t->payload;
  2363. if(data->mstate == MSTATE_PENDING) {
  2364. bool stream_unused;
  2365. CURLcode result_unused;
  2366. if(multi_handle_timeout(data, &now, &stream_unused, &result_unused,
  2367. FALSE)) {
  2368. infof(data, "PENDING handle timeout");
  2369. move_pending_to_connect(multi, data);
  2370. }
  2371. }
  2372. (void)add_next_timeout(now, multi, t->payload);
  2373. }
  2374. } while(t);
  2375. *running_handles = (int)multi->num_alive;
  2376. if(CURLM_OK >= returncode)
  2377. returncode = Curl_update_timer(multi);
  2378. return returncode;
  2379. }
  2380. /* unlink_all_msgsent_handles() detaches all those easy handles from this
  2381. multi handle */
  2382. static void unlink_all_msgsent_handles(struct Curl_multi *multi)
  2383. {
  2384. struct Curl_llist_element *e = multi->msgsent.head;
  2385. if(e) {
  2386. struct Curl_easy *data = e->ptr;
  2387. DEBUGASSERT(data->mstate == MSTATE_MSGSENT);
  2388. data->multi = NULL;
  2389. }
  2390. }
  2391. CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
  2392. {
  2393. struct Curl_easy *data;
  2394. struct Curl_easy *nextdata;
  2395. if(GOOD_MULTI_HANDLE(multi)) {
  2396. if(multi->in_callback)
  2397. return CURLM_RECURSIVE_API_CALL;
  2398. multi->magic = 0; /* not good anymore */
  2399. unlink_all_msgsent_handles(multi);
  2400. process_pending_handles(multi);
  2401. /* First remove all remaining easy handles */
  2402. data = multi->easyp;
  2403. while(data) {
  2404. nextdata = data->next;
  2405. if(!data->state.done && data->conn)
  2406. /* if DONE was never called for this handle */
  2407. (void)multi_done(data, CURLE_OK, TRUE);
  2408. if(data->dns.hostcachetype == HCACHE_MULTI) {
  2409. /* clear out the usage of the shared DNS cache */
  2410. Curl_hostcache_clean(data, data->dns.hostcache);
  2411. data->dns.hostcache = NULL;
  2412. data->dns.hostcachetype = HCACHE_NONE;
  2413. }
  2414. /* Clear the pointer to the connection cache */
  2415. data->state.conn_cache = NULL;
  2416. data->multi = NULL; /* clear the association */
  2417. #ifdef USE_LIBPSL
  2418. if(data->psl == &multi->psl)
  2419. data->psl = NULL;
  2420. #endif
  2421. data = nextdata;
  2422. }
  2423. /* Close all the connections in the connection cache */
  2424. Curl_conncache_close_all_connections(&multi->conn_cache);
  2425. sockhash_destroy(&multi->sockhash);
  2426. Curl_hash_destroy(&multi->proto_hash);
  2427. Curl_conncache_destroy(&multi->conn_cache);
  2428. Curl_hash_destroy(&multi->hostcache);
  2429. Curl_psl_destroy(&multi->psl);
  2430. #ifdef USE_WINSOCK
  2431. WSACloseEvent(multi->wsa_event);
  2432. #else
  2433. #ifdef ENABLE_WAKEUP
  2434. wakeup_close(multi->wakeup_pair[0]);
  2435. #ifndef USE_EVENTFD
  2436. wakeup_close(multi->wakeup_pair[1]);
  2437. #endif
  2438. #endif
  2439. #endif
  2440. multi_xfer_bufs_free(multi);
  2441. free(multi);
  2442. return CURLM_OK;
  2443. }
  2444. return CURLM_BAD_HANDLE;
  2445. }
  2446. /*
  2447. * curl_multi_info_read()
  2448. *
  2449. * This function is the primary way for a multi/multi_socket application to
  2450. * figure out if a transfer has ended. We MUST make this function as fast as
  2451. * possible as it will be polled frequently and we MUST NOT scan any lists in
  2452. * here to figure out things. We must scale fine to thousands of handles and
  2453. * beyond. The current design is fully O(1).
  2454. */
  2455. CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
  2456. {
  2457. struct Curl_message *msg;
  2458. *msgs_in_queue = 0; /* default to none */
  2459. if(GOOD_MULTI_HANDLE(multi) &&
  2460. !multi->in_callback &&
  2461. Curl_llist_count(&multi->msglist)) {
  2462. /* there is one or more messages in the list */
  2463. struct Curl_llist_element *e;
  2464. /* extract the head of the list to return */
  2465. e = multi->msglist.head;
  2466. msg = e->ptr;
  2467. /* remove the extracted entry */
  2468. Curl_llist_remove(&multi->msglist, e, NULL);
  2469. *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
  2470. return &msg->extmsg;
  2471. }
  2472. return NULL;
  2473. }
  2474. /*
  2475. * singlesocket() checks what sockets we deal with and their "action state"
  2476. * and if we have a different state in any of those sockets from last time we
  2477. * call the callback accordingly.
  2478. */
  2479. static CURLMcode singlesocket(struct Curl_multi *multi,
  2480. struct Curl_easy *data)
  2481. {
  2482. struct easy_pollset cur_poll;
  2483. unsigned int i;
  2484. struct Curl_sh_entry *entry;
  2485. curl_socket_t s;
  2486. int rc;
  2487. /* Fill in the 'current' struct with the state as it is now: what sockets to
  2488. supervise and for what actions */
  2489. multi_getsock(data, &cur_poll);
  2490. /* We have 0 .. N sockets already and we get to know about the 0 .. M
  2491. sockets we should have from now on. Detect the differences, remove no
  2492. longer supervised ones and add new ones */
  2493. /* walk over the sockets we got right now */
  2494. for(i = 0; i < cur_poll.num; i++) {
  2495. unsigned char cur_action = cur_poll.actions[i];
  2496. unsigned char last_action = 0;
  2497. int comboaction;
  2498. s = cur_poll.sockets[i];
  2499. /* get it from the hash */
  2500. entry = sh_getentry(&multi->sockhash, s);
  2501. if(entry) {
  2502. /* check if new for this transfer */
  2503. unsigned int j;
  2504. for(j = 0; j< data->last_poll.num; j++) {
  2505. if(s == data->last_poll.sockets[j]) {
  2506. last_action = data->last_poll.actions[j];
  2507. break;
  2508. }
  2509. }
  2510. }
  2511. else {
  2512. /* this is a socket we didn't have before, add it to the hash! */
  2513. entry = sh_addentry(&multi->sockhash, s);
  2514. if(!entry)
  2515. /* fatal */
  2516. return CURLM_OUT_OF_MEMORY;
  2517. }
  2518. if(last_action && (last_action != cur_action)) {
  2519. /* Socket was used already, but different action now */
  2520. if(last_action & CURL_POLL_IN)
  2521. entry->readers--;
  2522. if(last_action & CURL_POLL_OUT)
  2523. entry->writers--;
  2524. if(cur_action & CURL_POLL_IN)
  2525. entry->readers++;
  2526. if(cur_action & CURL_POLL_OUT)
  2527. entry->writers++;
  2528. }
  2529. else if(!last_action) {
  2530. /* a new transfer using this socket */
  2531. entry->users++;
  2532. if(cur_action & CURL_POLL_IN)
  2533. entry->readers++;
  2534. if(cur_action & CURL_POLL_OUT)
  2535. entry->writers++;
  2536. /* add 'data' to the transfer hash on this socket! */
  2537. if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */
  2538. sizeof(struct Curl_easy *), data)) {
  2539. Curl_hash_destroy(&entry->transfers);
  2540. return CURLM_OUT_OF_MEMORY;
  2541. }
  2542. }
  2543. comboaction = (entry->writers ? CURL_POLL_OUT : 0) |
  2544. (entry->readers ? CURL_POLL_IN : 0);
  2545. /* socket existed before and has the same action set as before */
  2546. if(last_action && ((int)entry->action == comboaction))
  2547. /* same, continue */
  2548. continue;
  2549. if(multi->socket_cb) {
  2550. set_in_callback(multi, TRUE);
  2551. rc = multi->socket_cb(data, s, comboaction, multi->socket_userp,
  2552. entry->socketp);
  2553. set_in_callback(multi, FALSE);
  2554. if(rc == -1) {
  2555. multi->dead = TRUE;
  2556. return CURLM_ABORTED_BY_CALLBACK;
  2557. }
  2558. }
  2559. /* store the current action state */
  2560. entry->action = (unsigned int)comboaction;
  2561. }
  2562. /* Check for last_poll.sockets that no longer appear in cur_poll.sockets.
  2563. * Need to remove the easy handle from the multi->sockhash->transfers and
  2564. * remove multi->sockhash entry when this was the last transfer */
  2565. for(i = 0; i< data->last_poll.num; i++) {
  2566. unsigned int j;
  2567. bool stillused = FALSE;
  2568. s = data->last_poll.sockets[i];
  2569. for(j = 0; j < cur_poll.num; j++) {
  2570. if(s == cur_poll.sockets[j]) {
  2571. /* this is still supervised */
  2572. stillused = TRUE;
  2573. break;
  2574. }
  2575. }
  2576. if(stillused)
  2577. continue;
  2578. entry = sh_getentry(&multi->sockhash, s);
  2579. /* if this is NULL here, the socket has been closed and notified so
  2580. already by Curl_multi_closed() */
  2581. if(entry) {
  2582. unsigned char oldactions = data->last_poll.actions[i];
  2583. /* this socket has been removed. Decrease user count */
  2584. entry->users--;
  2585. if(oldactions & CURL_POLL_OUT)
  2586. entry->writers--;
  2587. if(oldactions & CURL_POLL_IN)
  2588. entry->readers--;
  2589. if(!entry->users) {
  2590. if(multi->socket_cb) {
  2591. set_in_callback(multi, TRUE);
  2592. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2593. multi->socket_userp, entry->socketp);
  2594. set_in_callback(multi, FALSE);
  2595. if(rc == -1) {
  2596. multi->dead = TRUE;
  2597. return CURLM_ABORTED_BY_CALLBACK;
  2598. }
  2599. }
  2600. sh_delentry(entry, &multi->sockhash, s);
  2601. }
  2602. else {
  2603. /* still users, but remove this handle as a user of this socket */
  2604. if(Curl_hash_delete(&entry->transfers, (char *)&data,
  2605. sizeof(struct Curl_easy *))) {
  2606. DEBUGASSERT(NULL);
  2607. }
  2608. }
  2609. }
  2610. } /* for loop over num */
  2611. /* Remember for next time */
  2612. memcpy(&data->last_poll, &cur_poll, sizeof(data->last_poll));
  2613. return CURLM_OK;
  2614. }
  2615. CURLcode Curl_updatesocket(struct Curl_easy *data)
  2616. {
  2617. if(singlesocket(data->multi, data))
  2618. return CURLE_ABORTED_BY_CALLBACK;
  2619. return CURLE_OK;
  2620. }
  2621. /*
  2622. * Curl_multi_closed()
  2623. *
  2624. * Used by the connect code to tell the multi_socket code that one of the
  2625. * sockets we were using is about to be closed. This function will then
  2626. * remove it from the sockethash for this handle to make the multi_socket API
  2627. * behave properly, especially for the case when libcurl will create another
  2628. * socket again and it gets the same file descriptor number.
  2629. */
  2630. void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
  2631. {
  2632. if(data) {
  2633. /* if there's still an easy handle associated with this connection */
  2634. struct Curl_multi *multi = data->multi;
  2635. if(multi) {
  2636. /* this is set if this connection is part of a handle that is added to
  2637. a multi handle, and only then this is necessary */
  2638. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  2639. if(entry) {
  2640. int rc = 0;
  2641. if(multi->socket_cb) {
  2642. set_in_callback(multi, TRUE);
  2643. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2644. multi->socket_userp, entry->socketp);
  2645. set_in_callback(multi, FALSE);
  2646. }
  2647. /* now remove it from the socket hash */
  2648. sh_delentry(entry, &multi->sockhash, s);
  2649. if(rc == -1)
  2650. /* This just marks the multi handle as "dead" without returning an
  2651. error code primarily because this function is used from many
  2652. places where propagating an error back is tricky. */
  2653. multi->dead = TRUE;
  2654. }
  2655. }
  2656. }
  2657. }
  2658. /*
  2659. * add_next_timeout()
  2660. *
  2661. * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
  2662. * when it has just been removed from the splay tree because the timeout has
  2663. * expired. This function is then to advance in the list to pick the next
  2664. * timeout to use (skip the already expired ones) and add this node back to
  2665. * the splay tree again.
  2666. *
  2667. * The splay tree only has each sessionhandle as a single node and the nearest
  2668. * timeout is used to sort it on.
  2669. */
  2670. static CURLMcode add_next_timeout(struct curltime now,
  2671. struct Curl_multi *multi,
  2672. struct Curl_easy *d)
  2673. {
  2674. struct curltime *tv = &d->state.expiretime;
  2675. struct Curl_llist *list = &d->state.timeoutlist;
  2676. struct Curl_llist_element *e;
  2677. struct time_node *node = NULL;
  2678. /* move over the timeout list for this specific handle and remove all
  2679. timeouts that are now passed tense and store the next pending
  2680. timeout in *tv */
  2681. for(e = list->head; e;) {
  2682. struct Curl_llist_element *n = e->next;
  2683. timediff_t diff;
  2684. node = (struct time_node *)e->ptr;
  2685. diff = Curl_timediff_us(node->time, now);
  2686. if(diff <= 0)
  2687. /* remove outdated entry */
  2688. Curl_llist_remove(list, e, NULL);
  2689. else
  2690. /* the list is sorted so get out on the first mismatch */
  2691. break;
  2692. e = n;
  2693. }
  2694. e = list->head;
  2695. if(!e) {
  2696. /* clear the expire times within the handles that we remove from the
  2697. splay tree */
  2698. tv->tv_sec = 0;
  2699. tv->tv_usec = 0;
  2700. }
  2701. else {
  2702. /* copy the first entry to 'tv' */
  2703. memcpy(tv, &node->time, sizeof(*tv));
  2704. /* Insert this node again into the splay. Keep the timer in the list in
  2705. case we need to recompute future timers. */
  2706. multi->timetree = Curl_splayinsert(*tv, multi->timetree,
  2707. &d->state.timenode);
  2708. }
  2709. return CURLM_OK;
  2710. }
  2711. static CURLMcode multi_socket(struct Curl_multi *multi,
  2712. bool checkall,
  2713. curl_socket_t s,
  2714. int ev_bitmask,
  2715. int *running_handles)
  2716. {
  2717. CURLMcode result = CURLM_OK;
  2718. struct Curl_easy *data = NULL;
  2719. struct Curl_tree *t;
  2720. struct curltime now = Curl_now();
  2721. bool first = FALSE;
  2722. bool nosig = FALSE;
  2723. SIGPIPE_VARIABLE(pipe_st);
  2724. if(checkall) {
  2725. /* *perform() deals with running_handles on its own */
  2726. result = curl_multi_perform(multi, running_handles);
  2727. /* walk through each easy handle and do the socket state change magic
  2728. and callbacks */
  2729. if(result != CURLM_BAD_HANDLE) {
  2730. data = multi->easyp;
  2731. while(data && !result) {
  2732. result = singlesocket(multi, data);
  2733. data = data->next;
  2734. }
  2735. }
  2736. /* or should we fall-through and do the timer-based stuff? */
  2737. return result;
  2738. }
  2739. if(s != CURL_SOCKET_TIMEOUT) {
  2740. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  2741. if(!entry)
  2742. /* Unmatched socket, we can't act on it but we ignore this fact. In
  2743. real-world tests it has been proved that libevent can in fact give
  2744. the application actions even though the socket was just previously
  2745. asked to get removed, so thus we better survive stray socket actions
  2746. and just move on. */
  2747. ;
  2748. else {
  2749. struct Curl_hash_iterator iter;
  2750. struct Curl_hash_element *he;
  2751. /* the socket can be shared by many transfers, iterate */
  2752. Curl_hash_start_iterate(&entry->transfers, &iter);
  2753. for(he = Curl_hash_next_element(&iter); he;
  2754. he = Curl_hash_next_element(&iter)) {
  2755. data = (struct Curl_easy *)he->ptr;
  2756. DEBUGASSERT(data);
  2757. DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER);
  2758. if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK))
  2759. /* set socket event bitmask if they're not locked */
  2760. data->state.select_bits |= (unsigned char)ev_bitmask;
  2761. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2762. }
  2763. /* Now we fall-through and do the timer-based stuff, since we don't want
  2764. to force the user to have to deal with timeouts as long as at least
  2765. one connection in fact has traffic. */
  2766. data = NULL; /* set data to NULL again to avoid calling
  2767. multi_runsingle() in case there's no need to */
  2768. now = Curl_now(); /* get a newer time since the multi_runsingle() loop
  2769. may have taken some time */
  2770. }
  2771. }
  2772. else {
  2773. /* Asked to run due to time-out. Clear the 'lastcall' variable to force
  2774. Curl_update_timer() to trigger a callback to the app again even if the
  2775. same timeout is still the one to run after this call. That handles the
  2776. case when the application asks libcurl to run the timeout
  2777. prematurely. */
  2778. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  2779. }
  2780. /*
  2781. * The loop following here will go on as long as there are expire-times left
  2782. * to process in the splay and 'data' will be re-assigned for every expired
  2783. * handle we deal with.
  2784. */
  2785. do {
  2786. /* the first loop lap 'data' can be NULL */
  2787. if(data) {
  2788. if(!first) {
  2789. first = TRUE;
  2790. nosig = data->set.no_signal; /* initial state */
  2791. sigpipe_ignore(data, &pipe_st);
  2792. }
  2793. else if(data->set.no_signal != nosig) {
  2794. sigpipe_restore(&pipe_st);
  2795. sigpipe_ignore(data, &pipe_st);
  2796. nosig = data->set.no_signal; /* remember new state */
  2797. }
  2798. result = multi_runsingle(multi, &now, data);
  2799. if(CURLM_OK >= result) {
  2800. /* get the socket(s) and check if the state has been changed since
  2801. last */
  2802. result = singlesocket(multi, data);
  2803. if(result)
  2804. break;
  2805. }
  2806. }
  2807. /* Check if there's one (more) expired timer to deal with! This function
  2808. extracts a matching node if there is one */
  2809. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  2810. if(t) {
  2811. data = t->payload; /* assign this for next loop */
  2812. (void)add_next_timeout(now, multi, t->payload);
  2813. }
  2814. } while(t);
  2815. if(first)
  2816. sigpipe_restore(&pipe_st);
  2817. *running_handles = (int)multi->num_alive;
  2818. return result;
  2819. }
  2820. #undef curl_multi_setopt
  2821. CURLMcode curl_multi_setopt(struct Curl_multi *multi,
  2822. CURLMoption option, ...)
  2823. {
  2824. CURLMcode res = CURLM_OK;
  2825. va_list param;
  2826. unsigned long uarg;
  2827. if(!GOOD_MULTI_HANDLE(multi))
  2828. return CURLM_BAD_HANDLE;
  2829. if(multi->in_callback)
  2830. return CURLM_RECURSIVE_API_CALL;
  2831. va_start(param, option);
  2832. switch(option) {
  2833. case CURLMOPT_SOCKETFUNCTION:
  2834. multi->socket_cb = va_arg(param, curl_socket_callback);
  2835. break;
  2836. case CURLMOPT_SOCKETDATA:
  2837. multi->socket_userp = va_arg(param, void *);
  2838. break;
  2839. case CURLMOPT_PUSHFUNCTION:
  2840. multi->push_cb = va_arg(param, curl_push_callback);
  2841. break;
  2842. case CURLMOPT_PUSHDATA:
  2843. multi->push_userp = va_arg(param, void *);
  2844. break;
  2845. case CURLMOPT_PIPELINING:
  2846. multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0;
  2847. break;
  2848. case CURLMOPT_TIMERFUNCTION:
  2849. multi->timer_cb = va_arg(param, curl_multi_timer_callback);
  2850. break;
  2851. case CURLMOPT_TIMERDATA:
  2852. multi->timer_userp = va_arg(param, void *);
  2853. break;
  2854. case CURLMOPT_MAXCONNECTS:
  2855. uarg = va_arg(param, unsigned long);
  2856. if(uarg <= UINT_MAX)
  2857. multi->maxconnects = (unsigned int)uarg;
  2858. break;
  2859. case CURLMOPT_MAX_HOST_CONNECTIONS:
  2860. multi->max_host_connections = va_arg(param, long);
  2861. break;
  2862. case CURLMOPT_MAX_TOTAL_CONNECTIONS:
  2863. multi->max_total_connections = va_arg(param, long);
  2864. break;
  2865. /* options formerly used for pipelining */
  2866. case CURLMOPT_MAX_PIPELINE_LENGTH:
  2867. break;
  2868. case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
  2869. break;
  2870. case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
  2871. break;
  2872. case CURLMOPT_PIPELINING_SITE_BL:
  2873. break;
  2874. case CURLMOPT_PIPELINING_SERVER_BL:
  2875. break;
  2876. case CURLMOPT_MAX_CONCURRENT_STREAMS:
  2877. {
  2878. long streams = va_arg(param, long);
  2879. if((streams < 1) || (streams > INT_MAX))
  2880. streams = 100;
  2881. multi->max_concurrent_streams = (unsigned int)streams;
  2882. }
  2883. break;
  2884. default:
  2885. res = CURLM_UNKNOWN_OPTION;
  2886. break;
  2887. }
  2888. va_end(param);
  2889. return res;
  2890. }
  2891. /* we define curl_multi_socket() in the public multi.h header */
  2892. #undef curl_multi_socket
  2893. CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
  2894. int *running_handles)
  2895. {
  2896. CURLMcode result;
  2897. if(multi->in_callback)
  2898. return CURLM_RECURSIVE_API_CALL;
  2899. result = multi_socket(multi, FALSE, s, 0, running_handles);
  2900. if(CURLM_OK >= result)
  2901. result = Curl_update_timer(multi);
  2902. return result;
  2903. }
  2904. CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
  2905. int ev_bitmask, int *running_handles)
  2906. {
  2907. CURLMcode result;
  2908. if(multi->in_callback)
  2909. return CURLM_RECURSIVE_API_CALL;
  2910. result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
  2911. if(CURLM_OK >= result)
  2912. result = Curl_update_timer(multi);
  2913. return result;
  2914. }
  2915. CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
  2916. {
  2917. CURLMcode result;
  2918. if(multi->in_callback)
  2919. return CURLM_RECURSIVE_API_CALL;
  2920. result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
  2921. if(CURLM_OK >= result)
  2922. result = Curl_update_timer(multi);
  2923. return result;
  2924. }
  2925. static CURLMcode multi_timeout(struct Curl_multi *multi,
  2926. long *timeout_ms)
  2927. {
  2928. static const struct curltime tv_zero = {0, 0};
  2929. if(multi->dead) {
  2930. *timeout_ms = 0;
  2931. return CURLM_OK;
  2932. }
  2933. if(multi->timetree) {
  2934. /* we have a tree of expire times */
  2935. struct curltime now = Curl_now();
  2936. /* splay the lowest to the bottom */
  2937. multi->timetree = Curl_splay(tv_zero, multi->timetree);
  2938. if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
  2939. /* some time left before expiration */
  2940. timediff_t diff = Curl_timediff_ceil(multi->timetree->key, now);
  2941. /* this should be safe even on 32 bit archs, as we don't use that
  2942. overly long timeouts */
  2943. *timeout_ms = (long)diff;
  2944. }
  2945. else
  2946. /* 0 means immediately */
  2947. *timeout_ms = 0;
  2948. }
  2949. else
  2950. *timeout_ms = -1;
  2951. return CURLM_OK;
  2952. }
  2953. CURLMcode curl_multi_timeout(struct Curl_multi *multi,
  2954. long *timeout_ms)
  2955. {
  2956. /* First, make some basic checks that the CURLM handle is a good handle */
  2957. if(!GOOD_MULTI_HANDLE(multi))
  2958. return CURLM_BAD_HANDLE;
  2959. if(multi->in_callback)
  2960. return CURLM_RECURSIVE_API_CALL;
  2961. return multi_timeout(multi, timeout_ms);
  2962. }
  2963. /*
  2964. * Tell the application it should update its timers, if it subscribes to the
  2965. * update timer callback.
  2966. */
  2967. CURLMcode Curl_update_timer(struct Curl_multi *multi)
  2968. {
  2969. long timeout_ms;
  2970. int rc;
  2971. if(!multi->timer_cb || multi->dead)
  2972. return CURLM_OK;
  2973. if(multi_timeout(multi, &timeout_ms)) {
  2974. return CURLM_OK;
  2975. }
  2976. if(timeout_ms < 0) {
  2977. static const struct curltime none = {0, 0};
  2978. if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
  2979. multi->timer_lastcall = none;
  2980. /* there's no timeout now but there was one previously, tell the app to
  2981. disable it */
  2982. set_in_callback(multi, TRUE);
  2983. rc = multi->timer_cb(multi, -1, multi->timer_userp);
  2984. set_in_callback(multi, FALSE);
  2985. if(rc == -1) {
  2986. multi->dead = TRUE;
  2987. return CURLM_ABORTED_BY_CALLBACK;
  2988. }
  2989. return CURLM_OK;
  2990. }
  2991. return CURLM_OK;
  2992. }
  2993. /* When multi_timeout() is done, multi->timetree points to the node with the
  2994. * timeout we got the (relative) time-out time for. We can thus easily check
  2995. * if this is the same (fixed) time as we got in a previous call and then
  2996. * avoid calling the callback again. */
  2997. if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
  2998. return CURLM_OK;
  2999. multi->timer_lastcall = multi->timetree->key;
  3000. set_in_callback(multi, TRUE);
  3001. rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp);
  3002. set_in_callback(multi, FALSE);
  3003. if(rc == -1) {
  3004. multi->dead = TRUE;
  3005. return CURLM_ABORTED_BY_CALLBACK;
  3006. }
  3007. return CURLM_OK;
  3008. }
  3009. /*
  3010. * multi_deltimeout()
  3011. *
  3012. * Remove a given timestamp from the list of timeouts.
  3013. */
  3014. static void
  3015. multi_deltimeout(struct Curl_easy *data, expire_id eid)
  3016. {
  3017. struct Curl_llist_element *e;
  3018. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3019. /* find and remove the specific node from the list */
  3020. for(e = timeoutlist->head; e; e = e->next) {
  3021. struct time_node *n = (struct time_node *)e->ptr;
  3022. if(n->eid == eid) {
  3023. Curl_llist_remove(timeoutlist, e, NULL);
  3024. return;
  3025. }
  3026. }
  3027. }
  3028. /*
  3029. * multi_addtimeout()
  3030. *
  3031. * Add a timestamp to the list of timeouts. Keep the list sorted so that head
  3032. * of list is always the timeout nearest in time.
  3033. *
  3034. */
  3035. static CURLMcode
  3036. multi_addtimeout(struct Curl_easy *data,
  3037. struct curltime *stamp,
  3038. expire_id eid)
  3039. {
  3040. struct Curl_llist_element *e;
  3041. struct time_node *node;
  3042. struct Curl_llist_element *prev = NULL;
  3043. size_t n;
  3044. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3045. node = &data->state.expires[eid];
  3046. /* copy the timestamp and id */
  3047. memcpy(&node->time, stamp, sizeof(*stamp));
  3048. node->eid = eid; /* also marks it as in use */
  3049. n = Curl_llist_count(timeoutlist);
  3050. if(n) {
  3051. /* find the correct spot in the list */
  3052. for(e = timeoutlist->head; e; e = e->next) {
  3053. struct time_node *check = (struct time_node *)e->ptr;
  3054. timediff_t diff = Curl_timediff(check->time, node->time);
  3055. if(diff > 0)
  3056. break;
  3057. prev = e;
  3058. }
  3059. }
  3060. /* else
  3061. this is the first timeout on the list */
  3062. Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
  3063. return CURLM_OK;
  3064. }
  3065. /*
  3066. * Curl_expire()
  3067. *
  3068. * given a number of milliseconds from now to use to set the 'act before
  3069. * this'-time for the transfer, to be extracted by curl_multi_timeout()
  3070. *
  3071. * The timeout will be added to a queue of timeouts if it defines a moment in
  3072. * time that is later than the current head of queue.
  3073. *
  3074. * Expire replaces a former timeout using the same id if already set.
  3075. */
  3076. void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
  3077. {
  3078. struct Curl_multi *multi = data->multi;
  3079. struct curltime *nowp = &data->state.expiretime;
  3080. struct curltime set;
  3081. /* this is only interesting while there is still an associated multi struct
  3082. remaining! */
  3083. if(!multi)
  3084. return;
  3085. DEBUGASSERT(id < EXPIRE_LAST);
  3086. set = Curl_now();
  3087. set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */
  3088. set.tv_usec += (int)(milli%1000)*1000;
  3089. if(set.tv_usec >= 1000000) {
  3090. set.tv_sec++;
  3091. set.tv_usec -= 1000000;
  3092. }
  3093. /* Remove any timer with the same id just in case. */
  3094. multi_deltimeout(data, id);
  3095. /* Add it to the timer list. It must stay in the list until it has expired
  3096. in case we need to recompute the minimum timer later. */
  3097. multi_addtimeout(data, &set, id);
  3098. if(nowp->tv_sec || nowp->tv_usec) {
  3099. /* This means that the struct is added as a node in the splay tree.
  3100. Compare if the new time is earlier, and only remove-old/add-new if it
  3101. is. */
  3102. timediff_t diff = Curl_timediff(set, *nowp);
  3103. int rc;
  3104. if(diff > 0) {
  3105. /* The current splay tree entry is sooner than this new expiry time.
  3106. We don't need to update our splay tree entry. */
  3107. return;
  3108. }
  3109. /* Since this is an updated time, we must remove the previous entry from
  3110. the splay tree first and then re-add the new value */
  3111. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3112. &multi->timetree);
  3113. if(rc)
  3114. infof(data, "Internal error removing splay node = %d", rc);
  3115. }
  3116. /* Indicate that we are in the splay tree and insert the new timer expiry
  3117. value since it is our local minimum. */
  3118. *nowp = set;
  3119. data->state.timenode.payload = data;
  3120. multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
  3121. &data->state.timenode);
  3122. }
  3123. /*
  3124. * Curl_expire_done()
  3125. *
  3126. * Removes the expire timer. Marks it as done.
  3127. *
  3128. */
  3129. void Curl_expire_done(struct Curl_easy *data, expire_id id)
  3130. {
  3131. /* remove the timer, if there */
  3132. multi_deltimeout(data, id);
  3133. }
  3134. /*
  3135. * Curl_expire_clear()
  3136. *
  3137. * Clear ALL timeout values for this handle.
  3138. */
  3139. void Curl_expire_clear(struct Curl_easy *data)
  3140. {
  3141. struct Curl_multi *multi = data->multi;
  3142. struct curltime *nowp = &data->state.expiretime;
  3143. /* this is only interesting while there is still an associated multi struct
  3144. remaining! */
  3145. if(!multi)
  3146. return;
  3147. if(nowp->tv_sec || nowp->tv_usec) {
  3148. /* Since this is an cleared time, we must remove the previous entry from
  3149. the splay tree */
  3150. struct Curl_llist *list = &data->state.timeoutlist;
  3151. int rc;
  3152. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3153. &multi->timetree);
  3154. if(rc)
  3155. infof(data, "Internal error clearing splay node = %d", rc);
  3156. /* flush the timeout list too */
  3157. while(list->size > 0) {
  3158. Curl_llist_remove(list, list->tail, NULL);
  3159. }
  3160. #ifdef DEBUGBUILD
  3161. infof(data, "Expire cleared");
  3162. #endif
  3163. nowp->tv_sec = 0;
  3164. nowp->tv_usec = 0;
  3165. }
  3166. }
  3167. CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
  3168. void *hashp)
  3169. {
  3170. struct Curl_sh_entry *there = NULL;
  3171. there = sh_getentry(&multi->sockhash, s);
  3172. if(!there)
  3173. return CURLM_BAD_SOCKET;
  3174. there->socketp = hashp;
  3175. return CURLM_OK;
  3176. }
  3177. size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
  3178. {
  3179. return multi ? (size_t)multi->max_host_connections : 0;
  3180. }
  3181. size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
  3182. {
  3183. return multi ? (size_t)multi->max_total_connections : 0;
  3184. }
  3185. /*
  3186. * When information about a connection has appeared, call this!
  3187. */
  3188. void Curl_multiuse_state(struct Curl_easy *data,
  3189. int bundlestate) /* use BUNDLE_* defines */
  3190. {
  3191. struct connectdata *conn;
  3192. DEBUGASSERT(data);
  3193. DEBUGASSERT(data->multi);
  3194. conn = data->conn;
  3195. DEBUGASSERT(conn);
  3196. DEBUGASSERT(conn->bundle);
  3197. conn->bundle->multiuse = bundlestate;
  3198. process_pending_handles(data->multi);
  3199. }
  3200. static void move_pending_to_connect(struct Curl_multi *multi,
  3201. struct Curl_easy *data)
  3202. {
  3203. DEBUGASSERT(data->mstate == MSTATE_PENDING);
  3204. /* put it back into the main list */
  3205. link_easy(multi, data);
  3206. multistate(data, MSTATE_CONNECT);
  3207. /* Remove this node from the pending list */
  3208. Curl_llist_remove(&multi->pending, &data->connect_queue, NULL);
  3209. /* Make sure that the handle will be processed soonish. */
  3210. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  3211. }
  3212. /* process_pending_handles() moves a handle from PENDING back into the main
  3213. list and change state to CONNECT.
  3214. We do not move all transfers because that can be a significant amount.
  3215. Since this is tried every now and then doing too many too often becomes a
  3216. performance problem.
  3217. When there is a change for connection limits like max host connections etc,
  3218. this likely only allows one new transfer. When there is a pipewait change,
  3219. it can potentially allow hundreds of new transfers.
  3220. We could consider an improvement where we store the queue reason and allow
  3221. more pipewait rechecks than others.
  3222. */
  3223. static void process_pending_handles(struct Curl_multi *multi)
  3224. {
  3225. struct Curl_llist_element *e = multi->pending.head;
  3226. if(e) {
  3227. struct Curl_easy *data = e->ptr;
  3228. move_pending_to_connect(multi, data);
  3229. }
  3230. }
  3231. void Curl_set_in_callback(struct Curl_easy *data, bool value)
  3232. {
  3233. if(data && data->multi)
  3234. data->multi->in_callback = value;
  3235. }
  3236. bool Curl_is_in_callback(struct Curl_easy *data)
  3237. {
  3238. return (data && data->multi && data->multi->in_callback);
  3239. }
  3240. unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
  3241. {
  3242. DEBUGASSERT(multi);
  3243. return multi->max_concurrent_streams;
  3244. }
  3245. struct Curl_easy **curl_multi_get_handles(struct Curl_multi *multi)
  3246. {
  3247. struct Curl_easy **a = malloc(sizeof(struct Curl_easy *) *
  3248. (multi->num_easy + 1));
  3249. if(a) {
  3250. unsigned int i = 0;
  3251. struct Curl_easy *e = multi->easyp;
  3252. while(e) {
  3253. DEBUGASSERT(i < multi->num_easy);
  3254. if(!e->state.internal)
  3255. a[i++] = e;
  3256. e = e->next;
  3257. }
  3258. a[i] = NULL; /* last entry is a NULL */
  3259. }
  3260. return a;
  3261. }
  3262. CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data,
  3263. char **pbuf, size_t *pbuflen)
  3264. {
  3265. DEBUGASSERT(data);
  3266. DEBUGASSERT(data->multi);
  3267. *pbuf = NULL;
  3268. *pbuflen = 0;
  3269. if(!data->multi) {
  3270. failf(data, "transfer has no multi handle");
  3271. return CURLE_FAILED_INIT;
  3272. }
  3273. if(!data->set.buffer_size) {
  3274. failf(data, "transfer buffer size is 0");
  3275. return CURLE_FAILED_INIT;
  3276. }
  3277. if(data->multi->xfer_buf_borrowed) {
  3278. failf(data, "attempt to borrow xfer_buf when already borrowed");
  3279. return CURLE_AGAIN;
  3280. }
  3281. if(data->multi->xfer_buf &&
  3282. data->set.buffer_size > data->multi->xfer_buf_len) {
  3283. /* not large enough, get a new one */
  3284. free(data->multi->xfer_buf);
  3285. data->multi->xfer_buf = NULL;
  3286. data->multi->xfer_buf_len = 0;
  3287. }
  3288. if(!data->multi->xfer_buf) {
  3289. data->multi->xfer_buf = malloc((size_t)data->set.buffer_size);
  3290. if(!data->multi->xfer_buf) {
  3291. failf(data, "could not allocate xfer_buf of %zu bytes",
  3292. (size_t)data->set.buffer_size);
  3293. return CURLE_OUT_OF_MEMORY;
  3294. }
  3295. data->multi->xfer_buf_len = data->set.buffer_size;
  3296. }
  3297. data->multi->xfer_buf_borrowed = TRUE;
  3298. *pbuf = data->multi->xfer_buf;
  3299. *pbuflen = data->multi->xfer_buf_len;
  3300. return CURLE_OK;
  3301. }
  3302. void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf)
  3303. {
  3304. (void)buf;
  3305. DEBUGASSERT(data);
  3306. DEBUGASSERT(data->multi);
  3307. DEBUGASSERT(!buf || data->multi->xfer_buf == buf);
  3308. data->multi->xfer_buf_borrowed = FALSE;
  3309. }
  3310. CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data,
  3311. char **pbuf, size_t *pbuflen)
  3312. {
  3313. DEBUGASSERT(data);
  3314. DEBUGASSERT(data->multi);
  3315. *pbuf = NULL;
  3316. *pbuflen = 0;
  3317. if(!data->multi) {
  3318. failf(data, "transfer has no multi handle");
  3319. return CURLE_FAILED_INIT;
  3320. }
  3321. if(!data->set.upload_buffer_size) {
  3322. failf(data, "transfer upload buffer size is 0");
  3323. return CURLE_FAILED_INIT;
  3324. }
  3325. if(data->multi->xfer_ulbuf_borrowed) {
  3326. failf(data, "attempt to borrow xfer_ulbuf when already borrowed");
  3327. return CURLE_AGAIN;
  3328. }
  3329. if(data->multi->xfer_ulbuf &&
  3330. data->set.upload_buffer_size > data->multi->xfer_ulbuf_len) {
  3331. /* not large enough, get a new one */
  3332. free(data->multi->xfer_ulbuf);
  3333. data->multi->xfer_ulbuf = NULL;
  3334. data->multi->xfer_ulbuf_len = 0;
  3335. }
  3336. if(!data->multi->xfer_ulbuf) {
  3337. data->multi->xfer_ulbuf = malloc((size_t)data->set.upload_buffer_size);
  3338. if(!data->multi->xfer_ulbuf) {
  3339. failf(data, "could not allocate xfer_ulbuf of %zu bytes",
  3340. (size_t)data->set.upload_buffer_size);
  3341. return CURLE_OUT_OF_MEMORY;
  3342. }
  3343. data->multi->xfer_ulbuf_len = data->set.upload_buffer_size;
  3344. }
  3345. data->multi->xfer_ulbuf_borrowed = TRUE;
  3346. *pbuf = data->multi->xfer_ulbuf;
  3347. *pbuflen = data->multi->xfer_ulbuf_len;
  3348. return CURLE_OK;
  3349. }
  3350. void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf)
  3351. {
  3352. (void)buf;
  3353. DEBUGASSERT(data);
  3354. DEBUGASSERT(data->multi);
  3355. DEBUGASSERT(!buf || data->multi->xfer_ulbuf == buf);
  3356. data->multi->xfer_ulbuf_borrowed = FALSE;
  3357. }
  3358. static void multi_xfer_bufs_free(struct Curl_multi *multi)
  3359. {
  3360. DEBUGASSERT(multi);
  3361. Curl_safefree(multi->xfer_buf);
  3362. multi->xfer_buf_len = 0;
  3363. multi->xfer_buf_borrowed = FALSE;
  3364. Curl_safefree(multi->xfer_ulbuf);
  3365. multi->xfer_ulbuf_len = 0;
  3366. multi->xfer_ulbuf_borrowed = FALSE;
  3367. }