2
0

multi.c 103 KB

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