multi.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2015, 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 http://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 "multiif.h"
  32. #include "sendf.h"
  33. #include "timeval.h"
  34. #include "http.h"
  35. #include "select.h"
  36. #include "warnless.h"
  37. #include "speedcheck.h"
  38. #include "conncache.h"
  39. #include "bundles.h"
  40. #include "multihandle.h"
  41. #include "pipeline.h"
  42. #include "sigpipe.h"
  43. #define _MPRINTF_REPLACE /* use our functions only */
  44. #include <curl/mprintf.h>
  45. #include "curl_memory.h"
  46. /* The last #include file should be: */
  47. #include "memdebug.h"
  48. /*
  49. CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
  50. to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
  51. CURL handle takes 45-50 K memory, therefore this 3K are not significant.
  52. */
  53. #ifndef CURL_SOCKET_HASH_TABLE_SIZE
  54. #define CURL_SOCKET_HASH_TABLE_SIZE 911
  55. #endif
  56. #define CURL_CONNECTION_HASH_SIZE 97
  57. #define CURL_MULTI_HANDLE 0x000bab1e
  58. #define GOOD_MULTI_HANDLE(x) \
  59. ((x) && (((struct Curl_multi *)(x))->type == CURL_MULTI_HANDLE))
  60. #define GOOD_EASY_HANDLE(x) \
  61. ((x) && (((struct SessionHandle *)(x))->magic == CURLEASY_MAGIC_NUMBER))
  62. static void singlesocket(struct Curl_multi *multi,
  63. struct SessionHandle *data);
  64. static int update_timer(struct Curl_multi *multi);
  65. static bool isHandleAtHead(struct SessionHandle *handle,
  66. struct curl_llist *pipeline);
  67. static CURLMcode add_next_timeout(struct timeval now,
  68. struct Curl_multi *multi,
  69. struct SessionHandle *d);
  70. static CURLMcode multi_timeout(struct Curl_multi *multi,
  71. long *timeout_ms);
  72. #ifdef DEBUGBUILD
  73. static const char * const statename[]={
  74. "INIT",
  75. "CONNECT_PEND",
  76. "CONNECT",
  77. "WAITRESOLVE",
  78. "WAITCONNECT",
  79. "WAITPROXYCONNECT",
  80. "PROTOCONNECT",
  81. "WAITDO",
  82. "DO",
  83. "DOING",
  84. "DO_MORE",
  85. "DO_DONE",
  86. "WAITPERFORM",
  87. "PERFORM",
  88. "TOOFAST",
  89. "DONE",
  90. "COMPLETED",
  91. "MSGSENT",
  92. };
  93. #endif
  94. static void multi_freetimeout(void *a, void *b);
  95. /* always use this function to change state, to make debugging easier */
  96. static void mstate(struct SessionHandle *data, CURLMstate state
  97. #ifdef DEBUGBUILD
  98. , int lineno
  99. #endif
  100. )
  101. {
  102. CURLMstate oldstate = data->mstate;
  103. #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
  104. (void) lineno;
  105. #endif
  106. if(oldstate == state)
  107. /* don't bother when the new state is the same as the old state */
  108. return;
  109. data->mstate = state;
  110. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  111. if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
  112. data->mstate < CURLM_STATE_COMPLETED) {
  113. long connection_id = -5000;
  114. if(data->easy_conn)
  115. connection_id = data->easy_conn->connection_id;
  116. infof(data,
  117. "STATE: %s => %s handle %p; line %d (connection #%ld) \n",
  118. statename[oldstate], statename[data->mstate],
  119. (void *)data, lineno, connection_id);
  120. }
  121. #endif
  122. if(state == CURLM_STATE_COMPLETED)
  123. /* changing to COMPLETED means there's one less easy handle 'alive' */
  124. data->multi->num_alive--;
  125. }
  126. #ifndef DEBUGBUILD
  127. #define multistate(x,y) mstate(x,y)
  128. #else
  129. #define multistate(x,y) mstate(x,y, __LINE__)
  130. #endif
  131. /*
  132. * We add one of these structs to the sockhash for a particular socket
  133. */
  134. struct Curl_sh_entry {
  135. struct SessionHandle *easy;
  136. time_t timestamp;
  137. int action; /* what action READ/WRITE this socket waits for */
  138. curl_socket_t socket; /* mainly to ease debugging */
  139. void *socketp; /* settable by users with curl_multi_assign() */
  140. };
  141. /* bits for 'action' having no bits means this socket is not expecting any
  142. action */
  143. #define SH_READ 1
  144. #define SH_WRITE 2
  145. /* make sure this socket is present in the hash for this handle */
  146. static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh,
  147. curl_socket_t s,
  148. struct SessionHandle *data)
  149. {
  150. struct Curl_sh_entry *there =
  151. Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
  152. struct Curl_sh_entry *check;
  153. if(there)
  154. /* it is present, return fine */
  155. return there;
  156. /* not present, add it */
  157. check = calloc(1, sizeof(struct Curl_sh_entry));
  158. if(!check)
  159. return NULL; /* major failure */
  160. check->easy = data;
  161. check->socket = s;
  162. /* make/add new hash entry */
  163. if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
  164. free(check);
  165. return NULL; /* major failure */
  166. }
  167. return check; /* things are good in sockhash land */
  168. }
  169. /* delete the given socket + handle from the hash */
  170. static void sh_delentry(struct curl_hash *sh, curl_socket_t s)
  171. {
  172. struct Curl_sh_entry *there =
  173. Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
  174. if(there) {
  175. /* this socket is in the hash */
  176. /* We remove the hash entry. (This'll end up in a call to
  177. sh_freeentry().) */
  178. Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
  179. }
  180. }
  181. /*
  182. * free a sockhash entry
  183. */
  184. static void sh_freeentry(void *freethis)
  185. {
  186. struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
  187. if(p)
  188. free(p);
  189. }
  190. static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
  191. {
  192. (void) k1_len; (void) k2_len;
  193. return (*((int *) k1)) == (*((int *) k2));
  194. }
  195. static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
  196. {
  197. int fd = *((int *) key);
  198. (void) key_length;
  199. return (fd % (int)slots_num);
  200. }
  201. /*
  202. * sh_init() creates a new socket hash and returns the handle for it.
  203. *
  204. * Quote from README.multi_socket:
  205. *
  206. * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
  207. * is somewhat of a bottle neck. Its current implementation may be a bit too
  208. * limiting. It simply has a fixed-size array, and on each entry in the array
  209. * it has a linked list with entries. So the hash only checks which list to
  210. * scan through. The code I had used so for used a list with merely 7 slots
  211. * (as that is what the DNS hash uses) but with 7000 connections that would
  212. * make an average of 1000 nodes in each list to run through. I upped that to
  213. * 97 slots (I believe a prime is suitable) and noticed a significant speed
  214. * increase. I need to reconsider the hash implementation or use a rather
  215. * large default value like this. At 9000 connections I was still below 10us
  216. * per call."
  217. *
  218. */
  219. static struct curl_hash *sh_init(int hashsize)
  220. {
  221. return Curl_hash_alloc(hashsize, hash_fd, fd_key_compare,
  222. sh_freeentry);
  223. }
  224. /*
  225. * multi_addmsg()
  226. *
  227. * Called when a transfer is completed. Adds the given msg pointer to
  228. * the list kept in the multi handle.
  229. */
  230. static CURLMcode multi_addmsg(struct Curl_multi *multi,
  231. struct Curl_message *msg)
  232. {
  233. if(!Curl_llist_insert_next(multi->msglist, multi->msglist->tail, msg))
  234. return CURLM_OUT_OF_MEMORY;
  235. return CURLM_OK;
  236. }
  237. /*
  238. * multi_freeamsg()
  239. *
  240. * Callback used by the llist system when a single list entry is destroyed.
  241. */
  242. static void multi_freeamsg(void *a, void *b)
  243. {
  244. (void)a;
  245. (void)b;
  246. }
  247. struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
  248. int chashsize) /* connection hash */
  249. {
  250. struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
  251. if(!multi)
  252. return NULL;
  253. multi->type = CURL_MULTI_HANDLE;
  254. multi->hostcache = Curl_mk_dnscache();
  255. if(!multi->hostcache)
  256. goto error;
  257. multi->sockhash = sh_init(hashsize);
  258. if(!multi->sockhash)
  259. goto error;
  260. multi->conn_cache = Curl_conncache_init(chashsize);
  261. if(!multi->conn_cache)
  262. goto error;
  263. multi->msglist = Curl_llist_alloc(multi_freeamsg);
  264. if(!multi->msglist)
  265. goto error;
  266. multi->pending = Curl_llist_alloc(multi_freeamsg);
  267. if(!multi->pending)
  268. goto error;
  269. /* allocate a new easy handle to use when closing cached connections */
  270. multi->closure_handle = curl_easy_init();
  271. if(!multi->closure_handle)
  272. goto error;
  273. multi->closure_handle->multi = multi;
  274. multi->closure_handle->state.conn_cache = multi->conn_cache;
  275. multi->max_pipeline_length = 5;
  276. /* -1 means it not set by user, use the default value */
  277. multi->maxconnects = -1;
  278. return (CURLM *) multi;
  279. error:
  280. Curl_hash_destroy(multi->sockhash);
  281. multi->sockhash = NULL;
  282. Curl_hash_destroy(multi->hostcache);
  283. multi->hostcache = NULL;
  284. Curl_conncache_destroy(multi->conn_cache);
  285. multi->conn_cache = NULL;
  286. Curl_close(multi->closure_handle);
  287. multi->closure_handle = NULL;
  288. Curl_llist_destroy(multi->msglist, NULL);
  289. Curl_llist_destroy(multi->pending, NULL);
  290. free(multi);
  291. return NULL;
  292. }
  293. CURLM *curl_multi_init(void)
  294. {
  295. return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
  296. CURL_CONNECTION_HASH_SIZE);
  297. }
  298. CURLMcode curl_multi_add_handle(CURLM *multi_handle,
  299. CURL *easy_handle)
  300. {
  301. struct curl_llist *timeoutlist;
  302. struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
  303. struct SessionHandle *data = (struct SessionHandle *)easy_handle;
  304. /* First, make some basic checks that the CURLM handle is a good handle */
  305. if(!GOOD_MULTI_HANDLE(multi))
  306. return CURLM_BAD_HANDLE;
  307. /* Verify that we got a somewhat good easy handle too */
  308. if(!GOOD_EASY_HANDLE(easy_handle))
  309. return CURLM_BAD_EASY_HANDLE;
  310. /* Prevent users from adding same easy handle more than once and prevent
  311. adding to more than one multi stack */
  312. if(data->multi)
  313. return CURLM_ADDED_ALREADY;
  314. /* Allocate and initialize timeout list for easy handle */
  315. timeoutlist = Curl_llist_alloc(multi_freetimeout);
  316. if(!timeoutlist)
  317. return CURLM_OUT_OF_MEMORY;
  318. /*
  319. * No failure allowed in this function beyond this point. And no
  320. * modification of easy nor multi handle allowed before this except for
  321. * potential multi's connection cache growing which won't be undone in this
  322. * function no matter what.
  323. */
  324. /* Make easy handle use timeout list initialized above */
  325. data->state.timeoutlist = timeoutlist;
  326. timeoutlist = NULL;
  327. /* set the easy handle */
  328. multistate(data, CURLM_STATE_INIT);
  329. if((data->set.global_dns_cache) &&
  330. (data->dns.hostcachetype != HCACHE_GLOBAL)) {
  331. /* global dns cache was requested but still isn't */
  332. struct curl_hash *global = Curl_global_host_cache_init();
  333. if(global) {
  334. /* only do this if the global cache init works */
  335. data->dns.hostcache = global;
  336. data->dns.hostcachetype = HCACHE_GLOBAL;
  337. }
  338. }
  339. /* for multi interface connections, we share DNS cache automatically if the
  340. easy handle's one is currently not set. */
  341. else if(!data->dns.hostcache ||
  342. (data->dns.hostcachetype == HCACHE_NONE)) {
  343. data->dns.hostcache = multi->hostcache;
  344. data->dns.hostcachetype = HCACHE_MULTI;
  345. }
  346. /* Point to the multi's connection cache */
  347. data->state.conn_cache = multi->conn_cache;
  348. data->state.infilesize = data->set.filesize;
  349. /* This adds the new entry at the 'end' of the doubly-linked circular
  350. list of SessionHandle structs to try and maintain a FIFO queue so
  351. the pipelined requests are in order. */
  352. /* We add this new entry last in the list. */
  353. data->next = NULL; /* end of the line */
  354. if(multi->easyp) {
  355. struct SessionHandle *last = multi->easylp;
  356. last->next = data;
  357. data->prev = last;
  358. multi->easylp = data; /* the new last node */
  359. }
  360. else {
  361. /* first node, make both prev and next be NULL! */
  362. data->next = NULL;
  363. data->prev = NULL;
  364. multi->easylp = multi->easyp = data; /* both first and last */
  365. }
  366. /* make the SessionHandle refer back to this multi handle */
  367. data->multi = multi_handle;
  368. /* Set the timeout for this handle to expire really soon so that it will
  369. be taken care of even when this handle is added in the midst of operation
  370. when only the curl_multi_socket() API is used. During that flow, only
  371. sockets that time-out or have actions will be dealt with. Since this
  372. handle has no action yet, we make sure it times out to get things to
  373. happen. */
  374. Curl_expire(data, 1);
  375. /* increase the node-counter */
  376. multi->num_easy++;
  377. /* increase the alive-counter */
  378. multi->num_alive++;
  379. /* A somewhat crude work-around for a little glitch in update_timer() that
  380. happens if the lastcall time is set to the same time when the handle is
  381. removed as when the next handle is added, as then the check in
  382. update_timer() that prevents calling the application multiple times with
  383. the same timer infor will not trigger and then the new handle's timeout
  384. will not be notified to the app.
  385. The work-around is thus simply to clear the 'lastcall' variable to force
  386. update_timer() to always trigger a callback to the app when a new easy
  387. handle is added */
  388. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  389. update_timer(multi);
  390. return CURLM_OK;
  391. }
  392. #if 0
  393. /* Debug-function, used like this:
  394. *
  395. * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
  396. *
  397. * Enable the hash print function first by editing hash.c
  398. */
  399. static void debug_print_sock_hash(void *p)
  400. {
  401. struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
  402. fprintf(stderr, " [easy %p/magic %x/socket %d]",
  403. (void *)sh->data, sh->data->magic, (int)sh->socket);
  404. }
  405. #endif
  406. CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
  407. CURL *curl_handle)
  408. {
  409. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  410. struct SessionHandle *easy = curl_handle;
  411. struct SessionHandle *data = easy;
  412. bool premature;
  413. bool easy_owns_conn;
  414. struct curl_llist_element *e;
  415. /* First, make some basic checks that the CURLM handle is a good handle */
  416. if(!GOOD_MULTI_HANDLE(multi))
  417. return CURLM_BAD_HANDLE;
  418. /* Verify that we got a somewhat good easy handle too */
  419. if(!GOOD_EASY_HANDLE(curl_handle))
  420. return CURLM_BAD_EASY_HANDLE;
  421. /* Prevent users from trying to remove same easy handle more than once */
  422. if(!data->multi)
  423. return CURLM_OK; /* it is already removed so let's say it is fine! */
  424. premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
  425. easy_owns_conn = (data->easy_conn && (data->easy_conn->data == easy)) ?
  426. TRUE : FALSE;
  427. /* If the 'state' is not INIT or COMPLETED, we might need to do something
  428. nice to put the easy_handle in a good known state when this returns. */
  429. if(premature)
  430. /* this handle is "alive" so we need to count down the total number of
  431. alive connections when this is removed */
  432. multi->num_alive--;
  433. if(data->easy_conn &&
  434. data->mstate > CURLM_STATE_DO &&
  435. data->mstate < CURLM_STATE_COMPLETED) {
  436. /* If the handle is in a pipeline and has started sending off its
  437. request but not received its response yet, we need to close
  438. connection. */
  439. connclose(data->easy_conn, "Removed with partial response");
  440. /* Set connection owner so that Curl_done() closes it.
  441. We can safely do this here since connection is killed. */
  442. data->easy_conn->data = easy;
  443. easy_owns_conn = TRUE;
  444. }
  445. /* The timer must be shut down before data->multi is set to NULL,
  446. else the timenode will remain in the splay tree after
  447. curl_easy_cleanup is called. */
  448. Curl_expire(data, 0);
  449. /* destroy the timeout list that is held in the easy handle */
  450. if(data->state.timeoutlist) {
  451. Curl_llist_destroy(data->state.timeoutlist, NULL);
  452. data->state.timeoutlist = NULL;
  453. }
  454. if(data->dns.hostcachetype == HCACHE_MULTI) {
  455. /* stop using the multi handle's DNS cache */
  456. data->dns.hostcache = NULL;
  457. data->dns.hostcachetype = HCACHE_NONE;
  458. }
  459. if(data->easy_conn) {
  460. /* we must call Curl_done() here (if we still "own it") so that we don't
  461. leave a half-baked one around */
  462. if(easy_owns_conn) {
  463. /* Curl_done() clears the conn->data field to lose the association
  464. between the easy handle and the connection
  465. Note that this ignores the return code simply because there's
  466. nothing really useful to do with it anyway! */
  467. (void)Curl_done(&data->easy_conn, data->result, premature);
  468. }
  469. else
  470. /* Clear connection pipelines, if Curl_done above was not called */
  471. Curl_getoff_all_pipelines(data, data->easy_conn);
  472. }
  473. Curl_wildcard_dtor(&data->wildcard);
  474. /* as this was using a shared connection cache we clear the pointer to that
  475. since we're not part of that multi handle anymore */
  476. data->state.conn_cache = NULL;
  477. /* change state without using multistate(), only to make singlesocket() do
  478. what we want */
  479. data->mstate = CURLM_STATE_COMPLETED;
  480. singlesocket(multi, easy); /* to let the application know what sockets that
  481. vanish with this handle */
  482. /* Remove the association between the connection and the handle */
  483. if(data->easy_conn) {
  484. data->easy_conn->data = NULL;
  485. data->easy_conn = NULL;
  486. }
  487. data->multi = NULL; /* clear the association to this multi handle */
  488. /* make sure there's no pending message in the queue sent from this easy
  489. handle */
  490. for(e = multi->msglist->head; e; e = e->next) {
  491. struct Curl_message *msg = e->ptr;
  492. if(msg->extmsg.easy_handle == easy) {
  493. Curl_llist_remove(multi->msglist, e, NULL);
  494. /* there can only be one from this specific handle */
  495. break;
  496. }
  497. }
  498. /* make the previous node point to our next */
  499. if(data->prev)
  500. data->prev->next = data->next;
  501. else
  502. multi->easyp = data->next; /* point to first node */
  503. /* make our next point to our previous node */
  504. if(data->next)
  505. data->next->prev = data->prev;
  506. else
  507. multi->easylp = data->prev; /* point to last node */
  508. /* NOTE NOTE NOTE
  509. We do not touch the easy handle here! */
  510. multi->num_easy--; /* one less to care about now */
  511. update_timer(multi);
  512. return CURLM_OK;
  513. }
  514. bool Curl_multi_pipeline_enabled(const struct Curl_multi *multi)
  515. {
  516. return (multi && multi->pipelining_enabled) ? TRUE : FALSE;
  517. }
  518. void Curl_multi_handlePipeBreak(struct SessionHandle *data)
  519. {
  520. data->easy_conn = NULL;
  521. }
  522. static int waitconnect_getsock(struct connectdata *conn,
  523. curl_socket_t *sock,
  524. int numsocks)
  525. {
  526. int i;
  527. int s=0;
  528. int rc=0;
  529. if(!numsocks)
  530. return GETSOCK_BLANK;
  531. for(i=0; i<2; i++) {
  532. if(conn->tempsock[i] != CURL_SOCKET_BAD) {
  533. sock[s] = conn->tempsock[i];
  534. rc |= GETSOCK_WRITESOCK(s++);
  535. }
  536. }
  537. /* when we've sent a CONNECT to a proxy, we should rather wait for the
  538. socket to become readable to be able to get the response headers */
  539. if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT) {
  540. sock[0] = conn->sock[FIRSTSOCKET];
  541. rc = GETSOCK_READSOCK(0);
  542. }
  543. return rc;
  544. }
  545. static int domore_getsock(struct connectdata *conn,
  546. curl_socket_t *socks,
  547. int numsocks)
  548. {
  549. if(conn && conn->handler->domore_getsock)
  550. return conn->handler->domore_getsock(conn, socks, numsocks);
  551. return GETSOCK_BLANK;
  552. }
  553. /* returns bitmapped flags for this handle and its sockets */
  554. static int multi_getsock(struct SessionHandle *data,
  555. curl_socket_t *socks, /* points to numsocks number
  556. of sockets */
  557. int numsocks)
  558. {
  559. /* If the pipe broke, or if there's no connection left for this easy handle,
  560. then we MUST bail out now with no bitmask set. The no connection case can
  561. happen when this is called from curl_multi_remove_handle() =>
  562. singlesocket() => multi_getsock().
  563. */
  564. if(data->state.pipe_broke || !data->easy_conn)
  565. return 0;
  566. if(data->mstate > CURLM_STATE_CONNECT &&
  567. data->mstate < CURLM_STATE_COMPLETED) {
  568. /* Set up ownership correctly */
  569. data->easy_conn->data = data;
  570. }
  571. switch(data->mstate) {
  572. default:
  573. #if 0 /* switch back on these cases to get the compiler to check for all enums
  574. to be present */
  575. case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */
  576. case CURLM_STATE_COMPLETED:
  577. case CURLM_STATE_MSGSENT:
  578. case CURLM_STATE_INIT:
  579. case CURLM_STATE_CONNECT:
  580. case CURLM_STATE_WAITDO:
  581. case CURLM_STATE_DONE:
  582. case CURLM_STATE_LAST:
  583. /* this will get called with CURLM_STATE_COMPLETED when a handle is
  584. removed */
  585. #endif
  586. return 0;
  587. case CURLM_STATE_WAITRESOLVE:
  588. return Curl_resolver_getsock(data->easy_conn, socks, numsocks);
  589. case CURLM_STATE_PROTOCONNECT:
  590. return Curl_protocol_getsock(data->easy_conn, socks, numsocks);
  591. case CURLM_STATE_DO:
  592. case CURLM_STATE_DOING:
  593. return Curl_doing_getsock(data->easy_conn, socks, numsocks);
  594. case CURLM_STATE_WAITPROXYCONNECT:
  595. case CURLM_STATE_WAITCONNECT:
  596. return waitconnect_getsock(data->easy_conn, socks, numsocks);
  597. case CURLM_STATE_DO_MORE:
  598. return domore_getsock(data->easy_conn, socks, numsocks);
  599. case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
  600. to waiting for the same as the *PERFORM
  601. states */
  602. case CURLM_STATE_PERFORM:
  603. case CURLM_STATE_WAITPERFORM:
  604. return Curl_single_getsock(data->easy_conn, socks, numsocks);
  605. }
  606. }
  607. CURLMcode curl_multi_fdset(CURLM *multi_handle,
  608. fd_set *read_fd_set, fd_set *write_fd_set,
  609. fd_set *exc_fd_set, int *max_fd)
  610. {
  611. /* Scan through all the easy handles to get the file descriptors set.
  612. Some easy handles may not have connected to the remote host yet,
  613. and then we must make sure that is done. */
  614. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  615. struct SessionHandle *data;
  616. int this_max_fd=-1;
  617. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  618. int bitmap;
  619. int i;
  620. (void)exc_fd_set; /* not used */
  621. if(!GOOD_MULTI_HANDLE(multi))
  622. return CURLM_BAD_HANDLE;
  623. data=multi->easyp;
  624. while(data) {
  625. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  626. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  627. curl_socket_t s = CURL_SOCKET_BAD;
  628. if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
  629. FD_SET(sockbunch[i], read_fd_set);
  630. s = sockbunch[i];
  631. }
  632. if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
  633. FD_SET(sockbunch[i], write_fd_set);
  634. s = sockbunch[i];
  635. }
  636. if(s == CURL_SOCKET_BAD)
  637. /* this socket is unused, break out of loop */
  638. break;
  639. else {
  640. if((int)s > this_max_fd)
  641. this_max_fd = (int)s;
  642. }
  643. }
  644. data = data->next; /* check next handle */
  645. }
  646. *max_fd = this_max_fd;
  647. return CURLM_OK;
  648. }
  649. CURLMcode curl_multi_wait(CURLM *multi_handle,
  650. struct curl_waitfd extra_fds[],
  651. unsigned int extra_nfds,
  652. int timeout_ms,
  653. int *ret)
  654. {
  655. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  656. struct SessionHandle *data;
  657. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  658. int bitmap;
  659. unsigned int i;
  660. unsigned int nfds = 0;
  661. unsigned int curlfds;
  662. struct pollfd *ufds = NULL;
  663. long timeout_internal;
  664. if(!GOOD_MULTI_HANDLE(multi))
  665. return CURLM_BAD_HANDLE;
  666. /* If the internally desired timeout is actually shorter than requested from
  667. the outside, then use the shorter time! But only if the internal timer
  668. is actually larger than -1! */
  669. (void)multi_timeout(multi, &timeout_internal);
  670. if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
  671. timeout_ms = (int)timeout_internal;
  672. /* Count up how many fds we have from the multi handle */
  673. data=multi->easyp;
  674. while(data) {
  675. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  676. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  677. curl_socket_t s = CURL_SOCKET_BAD;
  678. if(bitmap & GETSOCK_READSOCK(i)) {
  679. ++nfds;
  680. s = sockbunch[i];
  681. }
  682. if(bitmap & GETSOCK_WRITESOCK(i)) {
  683. ++nfds;
  684. s = sockbunch[i];
  685. }
  686. if(s == CURL_SOCKET_BAD) {
  687. break;
  688. }
  689. }
  690. data = data->next; /* check next handle */
  691. }
  692. curlfds = nfds; /* number of internal file descriptors */
  693. nfds += extra_nfds; /* add the externally provided ones */
  694. if(nfds || extra_nfds) {
  695. ufds = malloc(nfds * sizeof(struct pollfd));
  696. if(!ufds)
  697. return CURLM_OUT_OF_MEMORY;
  698. }
  699. nfds = 0;
  700. /* only do the second loop if we found descriptors in the first stage run
  701. above */
  702. if(curlfds) {
  703. /* Add the curl handles to our pollfds first */
  704. data=multi->easyp;
  705. while(data) {
  706. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  707. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  708. curl_socket_t s = CURL_SOCKET_BAD;
  709. if(bitmap & GETSOCK_READSOCK(i)) {
  710. ufds[nfds].fd = sockbunch[i];
  711. ufds[nfds].events = POLLIN;
  712. ++nfds;
  713. s = sockbunch[i];
  714. }
  715. if(bitmap & GETSOCK_WRITESOCK(i)) {
  716. ufds[nfds].fd = sockbunch[i];
  717. ufds[nfds].events = POLLOUT;
  718. ++nfds;
  719. s = sockbunch[i];
  720. }
  721. if(s == CURL_SOCKET_BAD) {
  722. break;
  723. }
  724. }
  725. data = data->next; /* check next handle */
  726. }
  727. }
  728. /* Add external file descriptions from poll-like struct curl_waitfd */
  729. for(i = 0; i < extra_nfds; i++) {
  730. ufds[nfds].fd = extra_fds[i].fd;
  731. ufds[nfds].events = 0;
  732. if(extra_fds[i].events & CURL_WAIT_POLLIN)
  733. ufds[nfds].events |= POLLIN;
  734. if(extra_fds[i].events & CURL_WAIT_POLLPRI)
  735. ufds[nfds].events |= POLLPRI;
  736. if(extra_fds[i].events & CURL_WAIT_POLLOUT)
  737. ufds[nfds].events |= POLLOUT;
  738. ++nfds;
  739. }
  740. if(nfds) {
  741. /* wait... */
  742. infof(data, "Curl_poll(%d ds, %d ms)\n", nfds, timeout_ms);
  743. i = Curl_poll(ufds, nfds, timeout_ms);
  744. if(i) {
  745. unsigned int j;
  746. /* copy revents results from the poll to the curl_multi_wait poll
  747. struct, the bit values of the actual underlying poll() implementation
  748. may not be the same as the ones in the public libcurl API! */
  749. for(j = 0; j < extra_nfds; j++) {
  750. unsigned short mask = 0;
  751. unsigned r = ufds[curlfds + j].revents;
  752. if(r & POLLIN)
  753. mask |= CURL_WAIT_POLLIN;
  754. if(r & POLLOUT)
  755. mask |= CURL_WAIT_POLLOUT;
  756. if(r & POLLPRI)
  757. mask |= CURL_WAIT_POLLPRI;
  758. extra_fds[j].revents = mask;
  759. }
  760. }
  761. }
  762. else
  763. i = 0;
  764. Curl_safefree(ufds);
  765. if(ret)
  766. *ret = i;
  767. return CURLM_OK;
  768. }
  769. static CURLMcode multi_runsingle(struct Curl_multi *multi,
  770. struct timeval now,
  771. struct SessionHandle *data)
  772. {
  773. struct Curl_message *msg = NULL;
  774. bool connected;
  775. bool async;
  776. bool protocol_connect = FALSE;
  777. bool dophase_done = FALSE;
  778. bool done = FALSE;
  779. CURLMcode rc;
  780. CURLcode result = CURLE_OK;
  781. struct SingleRequest *k;
  782. long timeout_ms;
  783. int control;
  784. if(!GOOD_EASY_HANDLE(data))
  785. return CURLM_BAD_EASY_HANDLE;
  786. do {
  787. bool disconnect_conn = FALSE;
  788. rc = CURLM_OK;
  789. /* Handle the case when the pipe breaks, i.e., the connection
  790. we're using gets cleaned up and we're left with nothing. */
  791. if(data->state.pipe_broke) {
  792. infof(data, "Pipe broke: handle %p, url = %s\n",
  793. (void *)data, data->state.path);
  794. if(data->mstate < CURLM_STATE_COMPLETED) {
  795. /* Head back to the CONNECT state */
  796. multistate(data, CURLM_STATE_CONNECT);
  797. rc = CURLM_CALL_MULTI_PERFORM;
  798. result = CURLE_OK;
  799. }
  800. data->state.pipe_broke = FALSE;
  801. data->easy_conn = NULL;
  802. continue;
  803. }
  804. if(!data->easy_conn &&
  805. data->mstate > CURLM_STATE_CONNECT &&
  806. data->mstate < CURLM_STATE_DONE) {
  807. /* In all these states, the code will blindly access 'data->easy_conn'
  808. so this is precaution that it isn't NULL. And it silences static
  809. analyzers. */
  810. failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
  811. return CURLM_INTERNAL_ERROR;
  812. }
  813. if(data->easy_conn && data->mstate > CURLM_STATE_CONNECT &&
  814. data->mstate < CURLM_STATE_COMPLETED)
  815. /* Make sure we set the connection's current owner */
  816. data->easy_conn->data = data;
  817. if(data->easy_conn &&
  818. (data->mstate >= CURLM_STATE_CONNECT) &&
  819. (data->mstate < CURLM_STATE_COMPLETED)) {
  820. /* we need to wait for the connect state as only then is the start time
  821. stored, but we must not check already completed handles */
  822. timeout_ms = Curl_timeleft(data, &now,
  823. (data->mstate <= CURLM_STATE_WAITDO)?
  824. TRUE:FALSE);
  825. if(timeout_ms < 0) {
  826. /* Handle timed out */
  827. if(data->mstate == CURLM_STATE_WAITRESOLVE)
  828. failf(data, "Resolving timed out after %ld milliseconds",
  829. Curl_tvdiff(now, data->progress.t_startsingle));
  830. else if(data->mstate == CURLM_STATE_WAITCONNECT)
  831. failf(data, "Connection timed out after %ld milliseconds",
  832. Curl_tvdiff(now, data->progress.t_startsingle));
  833. else {
  834. k = &data->req;
  835. if(k->size != -1) {
  836. failf(data, "Operation timed out after %ld milliseconds with %"
  837. CURL_FORMAT_CURL_OFF_T " out of %"
  838. CURL_FORMAT_CURL_OFF_T " bytes received",
  839. Curl_tvdiff(k->now, data->progress.t_startsingle),
  840. k->bytecount, k->size);
  841. }
  842. else {
  843. failf(data, "Operation timed out after %ld milliseconds with %"
  844. CURL_FORMAT_CURL_OFF_T " bytes received",
  845. Curl_tvdiff(now, data->progress.t_startsingle),
  846. k->bytecount);
  847. }
  848. }
  849. /* Force connection closed if the connection has indeed been used */
  850. if(data->mstate > CURLM_STATE_DO) {
  851. connclose(data->easy_conn, "Disconnected with pending data");
  852. disconnect_conn = TRUE;
  853. }
  854. result = CURLE_OPERATION_TIMEDOUT;
  855. /* Skip the statemachine and go directly to error handling section. */
  856. goto statemachine_end;
  857. }
  858. }
  859. switch(data->mstate) {
  860. case CURLM_STATE_INIT:
  861. /* init this transfer. */
  862. result=Curl_pretransfer(data);
  863. if(!result) {
  864. /* after init, go CONNECT */
  865. multistate(data, CURLM_STATE_CONNECT);
  866. Curl_pgrsTime(data, TIMER_STARTOP);
  867. rc = CURLM_CALL_MULTI_PERFORM;
  868. }
  869. break;
  870. case CURLM_STATE_CONNECT_PEND:
  871. /* We will stay here until there is a connection available. Then
  872. we try again in the CURLM_STATE_CONNECT state. */
  873. break;
  874. case CURLM_STATE_CONNECT:
  875. /* Connect. We want to get a connection identifier filled in. */
  876. Curl_pgrsTime(data, TIMER_STARTSINGLE);
  877. result = Curl_connect(data, &data->easy_conn,
  878. &async, &protocol_connect);
  879. if(CURLE_NO_CONNECTION_AVAILABLE == result) {
  880. /* There was no connection available. We will go to the pending
  881. state and wait for an available connection. */
  882. multistate(data, CURLM_STATE_CONNECT_PEND);
  883. /* add this handle to the list of connect-pending handles */
  884. if(!Curl_llist_insert_next(multi->pending, multi->pending->tail, data))
  885. result = CURLE_OUT_OF_MEMORY;
  886. else
  887. result = CURLE_OK;
  888. break;
  889. }
  890. if(!result) {
  891. /* Add this handle to the send or pend pipeline */
  892. result = Curl_add_handle_to_pipeline(data, data->easy_conn);
  893. if(result)
  894. disconnect_conn = TRUE;
  895. else {
  896. if(async)
  897. /* We're now waiting for an asynchronous name lookup */
  898. multistate(data, CURLM_STATE_WAITRESOLVE);
  899. else {
  900. /* after the connect has been sent off, go WAITCONNECT unless the
  901. protocol connect is already done and we can go directly to
  902. WAITDO or DO! */
  903. rc = CURLM_CALL_MULTI_PERFORM;
  904. if(protocol_connect)
  905. multistate(data, multi->pipelining_enabled?
  906. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  907. else {
  908. #ifndef CURL_DISABLE_HTTP
  909. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  910. multistate(data, CURLM_STATE_WAITPROXYCONNECT);
  911. else
  912. #endif
  913. multistate(data, CURLM_STATE_WAITCONNECT);
  914. }
  915. }
  916. }
  917. }
  918. break;
  919. case CURLM_STATE_WAITRESOLVE:
  920. /* awaiting an asynch name resolve to complete */
  921. {
  922. struct Curl_dns_entry *dns = NULL;
  923. struct connectdata *conn = data->easy_conn;
  924. /* check if we have the name resolved by now */
  925. if(data->share)
  926. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  927. dns = Curl_fetch_addr(conn, conn->host.name, (int)conn->port);
  928. if(dns) {
  929. dns->inuse++; /* we use it! */
  930. #ifdef CURLRES_ASYNCH
  931. conn->async.dns = dns;
  932. conn->async.done = TRUE;
  933. #endif
  934. result = CURLE_OK;
  935. infof(data, "Hostname was found in DNS cache\n");
  936. }
  937. if(data->share)
  938. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  939. if(!dns)
  940. result = Curl_resolver_is_resolved(data->easy_conn, &dns);
  941. /* Update sockets here, because the socket(s) may have been
  942. closed and the application thus needs to be told, even if it
  943. is likely that the same socket(s) will again be used further
  944. down. If the name has not yet been resolved, it is likely
  945. that new sockets have been opened in an attempt to contact
  946. another resolver. */
  947. singlesocket(multi, data);
  948. if(dns) {
  949. /* Perform the next step in the connection phase, and then move on
  950. to the WAITCONNECT state */
  951. result = Curl_async_resolved(data->easy_conn, &protocol_connect);
  952. if(result)
  953. /* if Curl_async_resolved() returns failure, the connection struct
  954. is already freed and gone */
  955. data->easy_conn = NULL; /* no more connection */
  956. else {
  957. /* call again please so that we get the next socket setup */
  958. rc = CURLM_CALL_MULTI_PERFORM;
  959. if(protocol_connect)
  960. multistate(data, multi->pipelining_enabled?
  961. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  962. else {
  963. #ifndef CURL_DISABLE_HTTP
  964. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  965. multistate(data, CURLM_STATE_WAITPROXYCONNECT);
  966. else
  967. #endif
  968. multistate(data, CURLM_STATE_WAITCONNECT);
  969. }
  970. }
  971. }
  972. if(result) {
  973. /* failure detected */
  974. disconnect_conn = TRUE;
  975. break;
  976. }
  977. }
  978. break;
  979. #ifndef CURL_DISABLE_HTTP
  980. case CURLM_STATE_WAITPROXYCONNECT:
  981. /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
  982. result = Curl_http_connect(data->easy_conn, &protocol_connect);
  983. if(data->easy_conn->bits.proxy_connect_closed) {
  984. /* connect back to proxy again */
  985. result = CURLE_OK;
  986. rc = CURLM_CALL_MULTI_PERFORM;
  987. multistate(data, CURLM_STATE_CONNECT);
  988. }
  989. else if(!result) {
  990. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE)
  991. multistate(data, CURLM_STATE_WAITCONNECT);
  992. }
  993. break;
  994. #endif
  995. case CURLM_STATE_WAITCONNECT:
  996. /* awaiting a completion of an asynch connect */
  997. result = Curl_is_connected(data->easy_conn,
  998. FIRSTSOCKET,
  999. &connected);
  1000. if(connected) {
  1001. if(!result)
  1002. /* if everything is still fine we do the protocol-specific connect
  1003. setup */
  1004. result = Curl_protocol_connect(data->easy_conn,
  1005. &protocol_connect);
  1006. }
  1007. if(data->easy_conn->bits.proxy_connect_closed) {
  1008. /* connect back to proxy again since it was closed in a proxy CONNECT
  1009. setup */
  1010. result = CURLE_OK;
  1011. rc = CURLM_CALL_MULTI_PERFORM;
  1012. multistate(data, CURLM_STATE_CONNECT);
  1013. break;
  1014. }
  1015. else if(result) {
  1016. /* failure detected */
  1017. /* Just break, the cleaning up is handled all in one place */
  1018. disconnect_conn = TRUE;
  1019. break;
  1020. }
  1021. if(connected) {
  1022. if(!protocol_connect) {
  1023. /* We have a TCP connection, but 'protocol_connect' may be false
  1024. and then we continue to 'STATE_PROTOCONNECT'. If protocol
  1025. connect is TRUE, we move on to STATE_DO.
  1026. BUT if we are using a proxy we must change to WAITPROXYCONNECT
  1027. */
  1028. #ifndef CURL_DISABLE_HTTP
  1029. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  1030. multistate(data, CURLM_STATE_WAITPROXYCONNECT);
  1031. else
  1032. #endif
  1033. multistate(data, CURLM_STATE_PROTOCONNECT);
  1034. }
  1035. else
  1036. /* after the connect has completed, go WAITDO or DO */
  1037. multistate(data, multi->pipelining_enabled?
  1038. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  1039. rc = CURLM_CALL_MULTI_PERFORM;
  1040. }
  1041. break;
  1042. case CURLM_STATE_PROTOCONNECT:
  1043. /* protocol-specific connect phase */
  1044. result = Curl_protocol_connecting(data->easy_conn, &protocol_connect);
  1045. if(!result && protocol_connect) {
  1046. /* after the connect has completed, go WAITDO or DO */
  1047. multistate(data, multi->pipelining_enabled?
  1048. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  1049. rc = CURLM_CALL_MULTI_PERFORM;
  1050. }
  1051. else if(result) {
  1052. /* failure detected */
  1053. Curl_posttransfer(data);
  1054. Curl_done(&data->easy_conn, result, TRUE);
  1055. disconnect_conn = TRUE;
  1056. }
  1057. break;
  1058. case CURLM_STATE_WAITDO:
  1059. /* Wait for our turn to DO when we're pipelining requests */
  1060. #ifdef DEBUGBUILD
  1061. infof(data, "WAITDO: Conn %ld send pipe %zu inuse %s athead %s\n",
  1062. data->easy_conn->connection_id,
  1063. data->easy_conn->send_pipe->size,
  1064. data->easy_conn->writechannel_inuse?"TRUE":"FALSE",
  1065. isHandleAtHead(data,
  1066. data->easy_conn->send_pipe)?"TRUE":"FALSE");
  1067. #endif
  1068. if(!data->easy_conn->writechannel_inuse &&
  1069. isHandleAtHead(data,
  1070. data->easy_conn->send_pipe)) {
  1071. /* Grab the channel */
  1072. data->easy_conn->writechannel_inuse = TRUE;
  1073. multistate(data, CURLM_STATE_DO);
  1074. rc = CURLM_CALL_MULTI_PERFORM;
  1075. }
  1076. break;
  1077. case CURLM_STATE_DO:
  1078. if(data->set.connect_only) {
  1079. /* keep connection open for application to use the socket */
  1080. connkeep(data->easy_conn, "CONNECT_ONLY");
  1081. multistate(data, CURLM_STATE_DONE);
  1082. result = CURLE_OK;
  1083. rc = CURLM_CALL_MULTI_PERFORM;
  1084. }
  1085. else {
  1086. /* Perform the protocol's DO action */
  1087. result = Curl_do(&data->easy_conn, &dophase_done);
  1088. /* When Curl_do() returns failure, data->easy_conn might be NULL! */
  1089. if(!result) {
  1090. if(!dophase_done) {
  1091. /* some steps needed for wildcard matching */
  1092. if(data->set.wildcardmatch) {
  1093. struct WildcardData *wc = &data->wildcard;
  1094. if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
  1095. /* skip some states if it is important */
  1096. Curl_done(&data->easy_conn, CURLE_OK, FALSE);
  1097. multistate(data, CURLM_STATE_DONE);
  1098. rc = CURLM_CALL_MULTI_PERFORM;
  1099. break;
  1100. }
  1101. }
  1102. /* DO was not completed in one function call, we must continue
  1103. DOING... */
  1104. multistate(data, CURLM_STATE_DOING);
  1105. rc = CURLM_OK;
  1106. }
  1107. /* after DO, go DO_DONE... or DO_MORE */
  1108. else if(data->easy_conn->bits.do_more) {
  1109. /* we're supposed to do more, but we need to sit down, relax
  1110. and wait a little while first */
  1111. multistate(data, CURLM_STATE_DO_MORE);
  1112. rc = CURLM_OK;
  1113. }
  1114. else {
  1115. /* we're done with the DO, now DO_DONE */
  1116. multistate(data, CURLM_STATE_DO_DONE);
  1117. rc = CURLM_CALL_MULTI_PERFORM;
  1118. }
  1119. }
  1120. else if((CURLE_SEND_ERROR == result) &&
  1121. data->easy_conn->bits.reuse) {
  1122. /*
  1123. * In this situation, a connection that we were trying to use
  1124. * may have unexpectedly died. If possible, send the connection
  1125. * back to the CONNECT phase so we can try again.
  1126. */
  1127. char *newurl = NULL;
  1128. followtype follow=FOLLOW_NONE;
  1129. CURLcode drc;
  1130. bool retry = FALSE;
  1131. drc = Curl_retry_request(data->easy_conn, &newurl);
  1132. if(drc) {
  1133. /* a failure here pretty much implies an out of memory */
  1134. result = drc;
  1135. disconnect_conn = TRUE;
  1136. }
  1137. else
  1138. retry = (newurl)?TRUE:FALSE;
  1139. Curl_posttransfer(data);
  1140. drc = Curl_done(&data->easy_conn, result, FALSE);
  1141. /* When set to retry the connection, we must to go back to
  1142. * the CONNECT state */
  1143. if(retry) {
  1144. if(!drc || (drc == CURLE_SEND_ERROR)) {
  1145. follow = FOLLOW_RETRY;
  1146. drc = Curl_follow(data, newurl, follow);
  1147. if(!drc) {
  1148. multistate(data, CURLM_STATE_CONNECT);
  1149. rc = CURLM_CALL_MULTI_PERFORM;
  1150. result = CURLE_OK;
  1151. }
  1152. else {
  1153. /* Follow failed */
  1154. result = drc;
  1155. free(newurl);
  1156. }
  1157. }
  1158. else {
  1159. /* done didn't return OK or SEND_ERROR */
  1160. result = drc;
  1161. free(newurl);
  1162. }
  1163. }
  1164. else {
  1165. /* Have error handler disconnect conn if we can't retry */
  1166. disconnect_conn = TRUE;
  1167. free(newurl);
  1168. }
  1169. }
  1170. else {
  1171. /* failure detected */
  1172. Curl_posttransfer(data);
  1173. if(data->easy_conn)
  1174. Curl_done(&data->easy_conn, result, FALSE);
  1175. disconnect_conn = TRUE;
  1176. }
  1177. }
  1178. break;
  1179. case CURLM_STATE_DOING:
  1180. /* we continue DOING until the DO phase is complete */
  1181. result = Curl_protocol_doing(data->easy_conn,
  1182. &dophase_done);
  1183. if(!result) {
  1184. if(dophase_done) {
  1185. /* after DO, go DO_DONE or DO_MORE */
  1186. multistate(data, data->easy_conn->bits.do_more?
  1187. CURLM_STATE_DO_MORE:
  1188. CURLM_STATE_DO_DONE);
  1189. rc = CURLM_CALL_MULTI_PERFORM;
  1190. } /* dophase_done */
  1191. }
  1192. else {
  1193. /* failure detected */
  1194. Curl_posttransfer(data);
  1195. Curl_done(&data->easy_conn, result, FALSE);
  1196. disconnect_conn = TRUE;
  1197. }
  1198. break;
  1199. case CURLM_STATE_DO_MORE:
  1200. /*
  1201. * When we are connected, DO MORE and then go DO_DONE
  1202. */
  1203. result = Curl_do_more(data->easy_conn, &control);
  1204. /* No need to remove this handle from the send pipeline here since that
  1205. is done in Curl_done() */
  1206. if(!result) {
  1207. if(control) {
  1208. /* if positive, advance to DO_DONE
  1209. if negative, go back to DOING */
  1210. multistate(data, control==1?
  1211. CURLM_STATE_DO_DONE:
  1212. CURLM_STATE_DOING);
  1213. rc = CURLM_CALL_MULTI_PERFORM;
  1214. }
  1215. else
  1216. /* stay in DO_MORE */
  1217. rc = CURLM_OK;
  1218. }
  1219. else {
  1220. /* failure detected */
  1221. Curl_posttransfer(data);
  1222. Curl_done(&data->easy_conn, result, FALSE);
  1223. disconnect_conn = TRUE;
  1224. }
  1225. break;
  1226. case CURLM_STATE_DO_DONE:
  1227. /* Move ourselves from the send to recv pipeline */
  1228. Curl_move_handle_from_send_to_recv_pipe(data, data->easy_conn);
  1229. /* Check if we can move pending requests to send pipe */
  1230. Curl_multi_process_pending_handles(multi);
  1231. /* Only perform the transfer if there's a good socket to work with.
  1232. Having both BAD is a signal to skip immediately to DONE */
  1233. if((data->easy_conn->sockfd != CURL_SOCKET_BAD) ||
  1234. (data->easy_conn->writesockfd != CURL_SOCKET_BAD))
  1235. multistate(data, CURLM_STATE_WAITPERFORM);
  1236. else
  1237. multistate(data, CURLM_STATE_DONE);
  1238. rc = CURLM_CALL_MULTI_PERFORM;
  1239. break;
  1240. case CURLM_STATE_WAITPERFORM:
  1241. /* Wait for our turn to PERFORM */
  1242. if(!data->easy_conn->readchannel_inuse &&
  1243. isHandleAtHead(data,
  1244. data->easy_conn->recv_pipe)) {
  1245. /* Grab the channel */
  1246. data->easy_conn->readchannel_inuse = TRUE;
  1247. multistate(data, CURLM_STATE_PERFORM);
  1248. rc = CURLM_CALL_MULTI_PERFORM;
  1249. }
  1250. #ifdef DEBUGBUILD
  1251. else {
  1252. infof(data, "WAITPERFORM: Conn %ld recv pipe %zu inuse %s athead %s\n",
  1253. data->easy_conn->connection_id,
  1254. data->easy_conn->recv_pipe->size,
  1255. data->easy_conn->readchannel_inuse?"TRUE":"FALSE",
  1256. isHandleAtHead(data,
  1257. data->easy_conn->recv_pipe)?"TRUE":"FALSE");
  1258. }
  1259. #endif
  1260. break;
  1261. case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
  1262. /* if both rates are within spec, resume transfer */
  1263. if(Curl_pgrsUpdate(data->easy_conn))
  1264. result = CURLE_ABORTED_BY_CALLBACK;
  1265. else
  1266. result = Curl_speedcheck(data, now);
  1267. if(( (data->set.max_send_speed == 0) ||
  1268. (data->progress.ulspeed < data->set.max_send_speed )) &&
  1269. ( (data->set.max_recv_speed == 0) ||
  1270. (data->progress.dlspeed < data->set.max_recv_speed)))
  1271. multistate(data, CURLM_STATE_PERFORM);
  1272. break;
  1273. case CURLM_STATE_PERFORM:
  1274. {
  1275. char *newurl = NULL;
  1276. bool retry = FALSE;
  1277. /* check if over send speed */
  1278. if((data->set.max_send_speed > 0) &&
  1279. (data->progress.ulspeed > data->set.max_send_speed)) {
  1280. int buffersize;
  1281. multistate(data, CURLM_STATE_TOOFAST);
  1282. /* calculate upload rate-limitation timeout. */
  1283. buffersize = (int)(data->set.buffer_size ?
  1284. data->set.buffer_size : BUFSIZE);
  1285. timeout_ms = Curl_sleep_time(data->set.max_send_speed,
  1286. data->progress.ulspeed, buffersize);
  1287. Curl_expire_latest(data, timeout_ms);
  1288. break;
  1289. }
  1290. /* check if over recv speed */
  1291. if((data->set.max_recv_speed > 0) &&
  1292. (data->progress.dlspeed > data->set.max_recv_speed)) {
  1293. int buffersize;
  1294. multistate(data, CURLM_STATE_TOOFAST);
  1295. /* Calculate download rate-limitation timeout. */
  1296. buffersize = (int)(data->set.buffer_size ?
  1297. data->set.buffer_size : BUFSIZE);
  1298. timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
  1299. data->progress.dlspeed, buffersize);
  1300. Curl_expire_latest(data, timeout_ms);
  1301. break;
  1302. }
  1303. /* read/write data if it is ready to do so */
  1304. result = Curl_readwrite(data->easy_conn, &done);
  1305. k = &data->req;
  1306. if(!(k->keepon & KEEP_RECV)) {
  1307. /* We're done receiving */
  1308. data->easy_conn->readchannel_inuse = FALSE;
  1309. }
  1310. if(!(k->keepon & KEEP_SEND)) {
  1311. /* We're done sending */
  1312. data->easy_conn->writechannel_inuse = FALSE;
  1313. }
  1314. if(done || (result == CURLE_RECV_ERROR)) {
  1315. /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
  1316. * condition and the server closed the re-used connection exactly when
  1317. * we wanted to use it, so figure out if that is indeed the case.
  1318. */
  1319. CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
  1320. if(!ret)
  1321. retry = (newurl)?TRUE:FALSE;
  1322. if(retry) {
  1323. /* if we are to retry, set the result to OK and consider the
  1324. request as done */
  1325. result = CURLE_OK;
  1326. done = TRUE;
  1327. }
  1328. }
  1329. if(result) {
  1330. /*
  1331. * The transfer phase returned error, we mark the connection to get
  1332. * closed to prevent being re-used. This is because we can't possibly
  1333. * know if the connection is in a good shape or not now. Unless it is
  1334. * a protocol which uses two "channels" like FTP, as then the error
  1335. * happened in the data connection.
  1336. */
  1337. if(!(data->easy_conn->handler->flags & PROTOPT_DUAL))
  1338. connclose(data->easy_conn, "Transfer returned error");
  1339. Curl_posttransfer(data);
  1340. Curl_done(&data->easy_conn, result, FALSE);
  1341. }
  1342. else if(done) {
  1343. followtype follow=FOLLOW_NONE;
  1344. /* call this even if the readwrite function returned error */
  1345. Curl_posttransfer(data);
  1346. /* we're no longer receiving */
  1347. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1348. /* expire the new receiving pipeline head */
  1349. if(data->easy_conn->recv_pipe->head)
  1350. Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 1);
  1351. /* Check if we can move pending requests to send pipe */
  1352. Curl_multi_process_pending_handles(multi);
  1353. /* When we follow redirects or is set to retry the connection, we must
  1354. to go back to the CONNECT state */
  1355. if(data->req.newurl || retry) {
  1356. if(!retry) {
  1357. /* if the URL is a follow-location and not just a retried request
  1358. then figure out the URL here */
  1359. if(newurl)
  1360. free(newurl);
  1361. newurl = data->req.newurl;
  1362. data->req.newurl = NULL;
  1363. follow = FOLLOW_REDIR;
  1364. }
  1365. else
  1366. follow = FOLLOW_RETRY;
  1367. result = Curl_done(&data->easy_conn, CURLE_OK, FALSE);
  1368. if(!result) {
  1369. result = Curl_follow(data, newurl, follow);
  1370. if(!result) {
  1371. multistate(data, CURLM_STATE_CONNECT);
  1372. rc = CURLM_CALL_MULTI_PERFORM;
  1373. newurl = NULL; /* handed over the memory ownership to
  1374. Curl_follow(), make sure we don't free() it
  1375. here */
  1376. }
  1377. }
  1378. }
  1379. else {
  1380. /* after the transfer is done, go DONE */
  1381. /* but first check to see if we got a location info even though we're
  1382. not following redirects */
  1383. if(data->req.location) {
  1384. if(newurl)
  1385. free(newurl);
  1386. newurl = data->req.location;
  1387. data->req.location = NULL;
  1388. result = Curl_follow(data, newurl, FOLLOW_FAKE);
  1389. if(!result)
  1390. newurl = NULL; /* allocation was handed over Curl_follow() */
  1391. else
  1392. disconnect_conn = TRUE;
  1393. }
  1394. multistate(data, CURLM_STATE_DONE);
  1395. rc = CURLM_CALL_MULTI_PERFORM;
  1396. }
  1397. }
  1398. if(newurl)
  1399. free(newurl);
  1400. break;
  1401. }
  1402. case CURLM_STATE_DONE:
  1403. /* this state is highly transient, so run another loop after this */
  1404. rc = CURLM_CALL_MULTI_PERFORM;
  1405. if(data->easy_conn) {
  1406. CURLcode res;
  1407. /* Remove ourselves from the receive pipeline, if we are there. */
  1408. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1409. /* Check if we can move pending requests to send pipe */
  1410. Curl_multi_process_pending_handles(multi);
  1411. /* post-transfer command */
  1412. res = Curl_done(&data->easy_conn, result, FALSE);
  1413. /* allow a previously set error code take precedence */
  1414. if(!result)
  1415. result = res;
  1416. /*
  1417. * If there are other handles on the pipeline, Curl_done won't set
  1418. * easy_conn to NULL. In such a case, curl_multi_remove_handle() can
  1419. * access free'd data, if the connection is free'd and the handle
  1420. * removed before we perform the processing in CURLM_STATE_COMPLETED
  1421. */
  1422. if(data->easy_conn)
  1423. data->easy_conn = NULL;
  1424. }
  1425. if(data->set.wildcardmatch) {
  1426. if(data->wildcard.state != CURLWC_DONE) {
  1427. /* if a wildcard is set and we are not ending -> lets start again
  1428. with CURLM_STATE_INIT */
  1429. multistate(data, CURLM_STATE_INIT);
  1430. break;
  1431. }
  1432. }
  1433. /* after we have DONE what we're supposed to do, go COMPLETED, and
  1434. it doesn't matter what the Curl_done() returned! */
  1435. multistate(data, CURLM_STATE_COMPLETED);
  1436. break;
  1437. case CURLM_STATE_COMPLETED:
  1438. /* this is a completed transfer, it is likely to still be connected */
  1439. /* This node should be delinked from the list now and we should post
  1440. an information message that we are complete. */
  1441. /* Important: reset the conn pointer so that we don't point to memory
  1442. that could be freed anytime */
  1443. data->easy_conn = NULL;
  1444. Curl_expire(data, 0); /* stop all timers */
  1445. break;
  1446. case CURLM_STATE_MSGSENT:
  1447. data->result = result;
  1448. return CURLM_OK; /* do nothing */
  1449. default:
  1450. return CURLM_INTERNAL_ERROR;
  1451. }
  1452. statemachine_end:
  1453. if(data->mstate < CURLM_STATE_COMPLETED) {
  1454. if(result) {
  1455. /*
  1456. * If an error was returned, and we aren't in completed state now,
  1457. * then we go to completed and consider this transfer aborted.
  1458. */
  1459. /* NOTE: no attempt to disconnect connections must be made
  1460. in the case blocks above - cleanup happens only here */
  1461. data->state.pipe_broke = FALSE;
  1462. if(data->easy_conn) {
  1463. /* if this has a connection, unsubscribe from the pipelines */
  1464. data->easy_conn->writechannel_inuse = FALSE;
  1465. data->easy_conn->readchannel_inuse = FALSE;
  1466. Curl_removeHandleFromPipeline(data, data->easy_conn->send_pipe);
  1467. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1468. /* Check if we can move pending requests to send pipe */
  1469. Curl_multi_process_pending_handles(multi);
  1470. if(disconnect_conn) {
  1471. /* Don't attempt to send data over a connection that timed out */
  1472. bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
  1473. /* disconnect properly */
  1474. Curl_disconnect(data->easy_conn, dead_connection);
  1475. /* This is where we make sure that the easy_conn pointer is reset.
  1476. We don't have to do this in every case block above where a
  1477. failure is detected */
  1478. data->easy_conn = NULL;
  1479. }
  1480. }
  1481. else if(data->mstate == CURLM_STATE_CONNECT) {
  1482. /* Curl_connect() failed */
  1483. (void)Curl_posttransfer(data);
  1484. }
  1485. multistate(data, CURLM_STATE_COMPLETED);
  1486. }
  1487. /* if there's still a connection to use, call the progress function */
  1488. else if(data->easy_conn && Curl_pgrsUpdate(data->easy_conn)) {
  1489. /* aborted due to progress callback return code must close the
  1490. connection */
  1491. result = CURLE_ABORTED_BY_CALLBACK;
  1492. connclose(data->easy_conn, "Aborted by callback");
  1493. /* if not yet in DONE state, go there, otherwise COMPLETED */
  1494. multistate(data, (data->mstate < CURLM_STATE_DONE)?
  1495. CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
  1496. rc = CURLM_CALL_MULTI_PERFORM;
  1497. }
  1498. }
  1499. if(CURLM_STATE_COMPLETED == data->mstate) {
  1500. /* now fill in the Curl_message with this info */
  1501. msg = &data->msg;
  1502. msg->extmsg.msg = CURLMSG_DONE;
  1503. msg->extmsg.easy_handle = data;
  1504. msg->extmsg.data.result = result;
  1505. rc = multi_addmsg(multi, msg);
  1506. multistate(data, CURLM_STATE_MSGSENT);
  1507. }
  1508. } while(rc == CURLM_CALL_MULTI_PERFORM);
  1509. data->result = result;
  1510. return rc;
  1511. }
  1512. CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles)
  1513. {
  1514. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1515. struct SessionHandle *data;
  1516. CURLMcode returncode=CURLM_OK;
  1517. struct Curl_tree *t;
  1518. struct timeval now = Curl_tvnow();
  1519. if(!GOOD_MULTI_HANDLE(multi))
  1520. return CURLM_BAD_HANDLE;
  1521. data=multi->easyp;
  1522. while(data) {
  1523. CURLMcode result;
  1524. struct WildcardData *wc = &data->wildcard;
  1525. SIGPIPE_VARIABLE(pipe_st);
  1526. if(data->set.wildcardmatch) {
  1527. if(!wc->filelist) {
  1528. CURLcode ret = Curl_wildcard_init(wc); /* init wildcard structures */
  1529. if(ret)
  1530. return CURLM_OUT_OF_MEMORY;
  1531. }
  1532. }
  1533. sigpipe_ignore(data, &pipe_st);
  1534. result = multi_runsingle(multi, now, data);
  1535. sigpipe_restore(&pipe_st);
  1536. if(data->set.wildcardmatch) {
  1537. /* destruct wildcard structures if it is needed */
  1538. if(wc->state == CURLWC_DONE || result)
  1539. Curl_wildcard_dtor(wc);
  1540. }
  1541. if(result)
  1542. returncode = result;
  1543. data = data->next; /* operate on next handle */
  1544. }
  1545. /*
  1546. * Simply remove all expired timers from the splay since handles are dealt
  1547. * with unconditionally by this function and curl_multi_timeout() requires
  1548. * that already passed/handled expire times are removed from the splay.
  1549. *
  1550. * It is important that the 'now' value is set at the entry of this function
  1551. * and not for the current time as it may have ticked a little while since
  1552. * then and then we risk this loop to remove timers that actually have not
  1553. * been handled!
  1554. */
  1555. do {
  1556. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  1557. if(t)
  1558. /* the removed may have another timeout in queue */
  1559. (void)add_next_timeout(now, multi, t->payload);
  1560. } while(t);
  1561. *running_handles = multi->num_alive;
  1562. if(CURLM_OK >= returncode)
  1563. update_timer(multi);
  1564. return returncode;
  1565. }
  1566. static void close_all_connections(struct Curl_multi *multi)
  1567. {
  1568. struct connectdata *conn;
  1569. conn = Curl_conncache_find_first_connection(multi->conn_cache);
  1570. while(conn) {
  1571. SIGPIPE_VARIABLE(pipe_st);
  1572. conn->data = multi->closure_handle;
  1573. sigpipe_ignore(conn->data, &pipe_st);
  1574. /* This will remove the connection from the cache */
  1575. (void)Curl_disconnect(conn, FALSE);
  1576. sigpipe_restore(&pipe_st);
  1577. conn = Curl_conncache_find_first_connection(multi->conn_cache);
  1578. }
  1579. }
  1580. CURLMcode curl_multi_cleanup(CURLM *multi_handle)
  1581. {
  1582. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1583. struct SessionHandle *data;
  1584. struct SessionHandle *nextdata;
  1585. if(GOOD_MULTI_HANDLE(multi)) {
  1586. bool restore_pipe = FALSE;
  1587. SIGPIPE_VARIABLE(pipe_st);
  1588. multi->type = 0; /* not good anymore */
  1589. /* Close all the connections in the connection cache */
  1590. close_all_connections(multi);
  1591. if(multi->closure_handle) {
  1592. sigpipe_ignore(multi->closure_handle, &pipe_st);
  1593. restore_pipe = TRUE;
  1594. multi->closure_handle->dns.hostcache = multi->hostcache;
  1595. Curl_hostcache_clean(multi->closure_handle,
  1596. multi->closure_handle->dns.hostcache);
  1597. Curl_close(multi->closure_handle);
  1598. }
  1599. Curl_hash_destroy(multi->sockhash);
  1600. Curl_conncache_destroy(multi->conn_cache);
  1601. Curl_llist_destroy(multi->msglist, NULL);
  1602. Curl_llist_destroy(multi->pending, NULL);
  1603. /* remove all easy handles */
  1604. data = multi->easyp;
  1605. while(data) {
  1606. nextdata=data->next;
  1607. if(data->dns.hostcachetype == HCACHE_MULTI) {
  1608. /* clear out the usage of the shared DNS cache */
  1609. Curl_hostcache_clean(data, data->dns.hostcache);
  1610. data->dns.hostcache = NULL;
  1611. data->dns.hostcachetype = HCACHE_NONE;
  1612. }
  1613. /* Clear the pointer to the connection cache */
  1614. data->state.conn_cache = NULL;
  1615. data->multi = NULL; /* clear the association */
  1616. data = nextdata;
  1617. }
  1618. Curl_hash_destroy(multi->hostcache);
  1619. /* Free the blacklists by setting them to NULL */
  1620. Curl_pipeline_set_site_blacklist(NULL, &multi->pipelining_site_bl);
  1621. Curl_pipeline_set_server_blacklist(NULL, &multi->pipelining_server_bl);
  1622. free(multi);
  1623. if(restore_pipe)
  1624. sigpipe_restore(&pipe_st);
  1625. return CURLM_OK;
  1626. }
  1627. else
  1628. return CURLM_BAD_HANDLE;
  1629. }
  1630. /*
  1631. * curl_multi_info_read()
  1632. *
  1633. * This function is the primary way for a multi/multi_socket application to
  1634. * figure out if a transfer has ended. We MUST make this function as fast as
  1635. * possible as it will be polled frequently and we MUST NOT scan any lists in
  1636. * here to figure out things. We must scale fine to thousands of handles and
  1637. * beyond. The current design is fully O(1).
  1638. */
  1639. CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue)
  1640. {
  1641. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1642. struct Curl_message *msg;
  1643. *msgs_in_queue = 0; /* default to none */
  1644. if(GOOD_MULTI_HANDLE(multi) && Curl_llist_count(multi->msglist)) {
  1645. /* there is one or more messages in the list */
  1646. struct curl_llist_element *e;
  1647. /* extract the head of the list to return */
  1648. e = multi->msglist->head;
  1649. msg = e->ptr;
  1650. /* remove the extracted entry */
  1651. Curl_llist_remove(multi->msglist, e, NULL);
  1652. *msgs_in_queue = curlx_uztosi(Curl_llist_count(multi->msglist));
  1653. return &msg->extmsg;
  1654. }
  1655. else
  1656. return NULL;
  1657. }
  1658. /*
  1659. * singlesocket() checks what sockets we deal with and their "action state"
  1660. * and if we have a different state in any of those sockets from last time we
  1661. * call the callback accordingly.
  1662. */
  1663. static void singlesocket(struct Curl_multi *multi,
  1664. struct SessionHandle *data)
  1665. {
  1666. curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
  1667. int i;
  1668. struct Curl_sh_entry *entry;
  1669. curl_socket_t s;
  1670. int num;
  1671. unsigned int curraction;
  1672. bool remove_sock_from_hash;
  1673. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++)
  1674. socks[i] = CURL_SOCKET_BAD;
  1675. /* Fill in the 'current' struct with the state as it is now: what sockets to
  1676. supervise and for what actions */
  1677. curraction = multi_getsock(data, socks, MAX_SOCKSPEREASYHANDLE);
  1678. /* We have 0 .. N sockets already and we get to know about the 0 .. M
  1679. sockets we should have from now on. Detect the differences, remove no
  1680. longer supervised ones and add new ones */
  1681. /* walk over the sockets we got right now */
  1682. for(i=0; (i< MAX_SOCKSPEREASYHANDLE) &&
  1683. (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
  1684. i++) {
  1685. int action = CURL_POLL_NONE;
  1686. s = socks[i];
  1687. /* get it from the hash */
  1688. entry = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
  1689. if(curraction & GETSOCK_READSOCK(i))
  1690. action |= CURL_POLL_IN;
  1691. if(curraction & GETSOCK_WRITESOCK(i))
  1692. action |= CURL_POLL_OUT;
  1693. if(entry) {
  1694. /* yeps, already present so check if it has the same action set */
  1695. if(entry->action == action)
  1696. /* same, continue */
  1697. continue;
  1698. }
  1699. else {
  1700. /* this is a socket we didn't have before, add it! */
  1701. entry = sh_addentry(multi->sockhash, s, data);
  1702. if(!entry)
  1703. /* fatal */
  1704. return;
  1705. }
  1706. /* we know (entry != NULL) at this point, see the logic above */
  1707. if(multi->socket_cb)
  1708. multi->socket_cb(data,
  1709. s,
  1710. action,
  1711. multi->socket_userp,
  1712. entry->socketp);
  1713. entry->action = action; /* store the current action state */
  1714. }
  1715. num = i; /* number of sockets */
  1716. /* when we've walked over all the sockets we should have right now, we must
  1717. make sure to detect sockets that are removed */
  1718. for(i=0; i< data->numsocks; i++) {
  1719. int j;
  1720. s = data->sockets[i];
  1721. for(j=0; j<num; j++) {
  1722. if(s == socks[j]) {
  1723. /* this is still supervised */
  1724. s = CURL_SOCKET_BAD;
  1725. break;
  1726. }
  1727. }
  1728. if(s != CURL_SOCKET_BAD) {
  1729. /* this socket has been removed. Tell the app to remove it */
  1730. remove_sock_from_hash = TRUE;
  1731. entry = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
  1732. if(entry) {
  1733. /* check if the socket to be removed serves a connection which has
  1734. other easy-s in a pipeline. In this case the socket should not be
  1735. removed. */
  1736. struct connectdata *easy_conn = data->easy_conn;
  1737. if(easy_conn) {
  1738. if(easy_conn->recv_pipe && easy_conn->recv_pipe->size > 1) {
  1739. /* the handle should not be removed from the pipe yet */
  1740. remove_sock_from_hash = FALSE;
  1741. /* Update the sockhash entry to instead point to the next in line
  1742. for the recv_pipe, or the first (in case this particular easy
  1743. isn't already) */
  1744. if(entry->easy == data) {
  1745. if(isHandleAtHead(data, easy_conn->recv_pipe))
  1746. entry->easy = easy_conn->recv_pipe->head->next->ptr;
  1747. else
  1748. entry->easy = easy_conn->recv_pipe->head->ptr;
  1749. }
  1750. }
  1751. if(easy_conn->send_pipe && easy_conn->send_pipe->size > 1) {
  1752. /* the handle should not be removed from the pipe yet */
  1753. remove_sock_from_hash = FALSE;
  1754. /* Update the sockhash entry to instead point to the next in line
  1755. for the send_pipe, or the first (in case this particular easy
  1756. isn't already) */
  1757. if(entry->easy == data) {
  1758. if(isHandleAtHead(data, easy_conn->send_pipe))
  1759. entry->easy = easy_conn->send_pipe->head->next->ptr;
  1760. else
  1761. entry->easy = easy_conn->send_pipe->head->ptr;
  1762. }
  1763. }
  1764. /* Don't worry about overwriting recv_pipe head with send_pipe_head,
  1765. when action will be asked on the socket (see multi_socket()), the
  1766. head of the correct pipe will be taken according to the
  1767. action. */
  1768. }
  1769. }
  1770. else
  1771. /* just a precaution, this socket really SHOULD be in the hash already
  1772. but in case it isn't, we don't have to tell the app to remove it
  1773. either since it never got to know about it */
  1774. remove_sock_from_hash = FALSE;
  1775. if(remove_sock_from_hash) {
  1776. /* in this case 'entry' is always non-NULL */
  1777. if(multi->socket_cb)
  1778. multi->socket_cb(data,
  1779. s,
  1780. CURL_POLL_REMOVE,
  1781. multi->socket_userp,
  1782. entry->socketp);
  1783. sh_delentry(multi->sockhash, s);
  1784. }
  1785. }
  1786. }
  1787. memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
  1788. data->numsocks = num;
  1789. }
  1790. /*
  1791. * Curl_multi_closed()
  1792. *
  1793. * Used by the connect code to tell the multi_socket code that one of the
  1794. * sockets we were using is about to be closed. This function will then
  1795. * remove it from the sockethash for this handle to make the multi_socket API
  1796. * behave properly, especially for the case when libcurl will create another
  1797. * socket again and it gets the same file descriptor number.
  1798. */
  1799. void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
  1800. {
  1801. struct Curl_multi *multi = conn->data->multi;
  1802. if(multi) {
  1803. /* this is set if this connection is part of a handle that is added to
  1804. a multi handle, and only then this is necessary */
  1805. struct Curl_sh_entry *entry =
  1806. Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
  1807. if(entry) {
  1808. if(multi->socket_cb)
  1809. multi->socket_cb(conn->data, s, CURL_POLL_REMOVE,
  1810. multi->socket_userp,
  1811. entry->socketp);
  1812. /* now remove it from the socket hash */
  1813. sh_delentry(multi->sockhash, s);
  1814. }
  1815. }
  1816. }
  1817. /*
  1818. * add_next_timeout()
  1819. *
  1820. * Each SessionHandle has a list of timeouts. The add_next_timeout() is called
  1821. * when it has just been removed from the splay tree because the timeout has
  1822. * expired. This function is then to advance in the list to pick the next
  1823. * timeout to use (skip the already expired ones) and add this node back to
  1824. * the splay tree again.
  1825. *
  1826. * The splay tree only has each sessionhandle as a single node and the nearest
  1827. * timeout is used to sort it on.
  1828. */
  1829. static CURLMcode add_next_timeout(struct timeval now,
  1830. struct Curl_multi *multi,
  1831. struct SessionHandle *d)
  1832. {
  1833. struct timeval *tv = &d->state.expiretime;
  1834. struct curl_llist *list = d->state.timeoutlist;
  1835. struct curl_llist_element *e;
  1836. /* move over the timeout list for this specific handle and remove all
  1837. timeouts that are now passed tense and store the next pending
  1838. timeout in *tv */
  1839. for(e = list->head; e; ) {
  1840. struct curl_llist_element *n = e->next;
  1841. long diff = curlx_tvdiff(*(struct timeval *)e->ptr, now);
  1842. if(diff <= 0)
  1843. /* remove outdated entry */
  1844. Curl_llist_remove(list, e, NULL);
  1845. else
  1846. /* the list is sorted so get out on the first mismatch */
  1847. break;
  1848. e = n;
  1849. }
  1850. e = list->head;
  1851. if(!e) {
  1852. /* clear the expire times within the handles that we remove from the
  1853. splay tree */
  1854. tv->tv_sec = 0;
  1855. tv->tv_usec = 0;
  1856. }
  1857. else {
  1858. /* copy the first entry to 'tv' */
  1859. memcpy(tv, e->ptr, sizeof(*tv));
  1860. /* remove first entry from list */
  1861. Curl_llist_remove(list, e, NULL);
  1862. /* insert this node again into the splay */
  1863. multi->timetree = Curl_splayinsert(*tv, multi->timetree,
  1864. &d->state.timenode);
  1865. }
  1866. return CURLM_OK;
  1867. }
  1868. static CURLMcode multi_socket(struct Curl_multi *multi,
  1869. bool checkall,
  1870. curl_socket_t s,
  1871. int ev_bitmask,
  1872. int *running_handles)
  1873. {
  1874. CURLMcode result = CURLM_OK;
  1875. struct SessionHandle *data = NULL;
  1876. struct Curl_tree *t;
  1877. struct timeval now = Curl_tvnow();
  1878. if(checkall) {
  1879. /* *perform() deals with running_handles on its own */
  1880. result = curl_multi_perform(multi, running_handles);
  1881. /* walk through each easy handle and do the socket state change magic
  1882. and callbacks */
  1883. if(result != CURLM_BAD_HANDLE) {
  1884. data=multi->easyp;
  1885. while(data) {
  1886. singlesocket(multi, data);
  1887. data = data->next;
  1888. }
  1889. }
  1890. /* or should we fall-through and do the timer-based stuff? */
  1891. return result;
  1892. }
  1893. else if(s != CURL_SOCKET_TIMEOUT) {
  1894. struct Curl_sh_entry *entry =
  1895. Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
  1896. if(!entry)
  1897. /* Unmatched socket, we can't act on it but we ignore this fact. In
  1898. real-world tests it has been proved that libevent can in fact give
  1899. the application actions even though the socket was just previously
  1900. asked to get removed, so thus we better survive stray socket actions
  1901. and just move on. */
  1902. ;
  1903. else {
  1904. SIGPIPE_VARIABLE(pipe_st);
  1905. data = entry->easy;
  1906. if(data->magic != CURLEASY_MAGIC_NUMBER)
  1907. /* bad bad bad bad bad bad bad */
  1908. return CURLM_INTERNAL_ERROR;
  1909. /* If the pipeline is enabled, take the handle which is in the head of
  1910. the pipeline. If we should write into the socket, take the send_pipe
  1911. head. If we should read from the socket, take the recv_pipe head. */
  1912. if(data->easy_conn) {
  1913. if((ev_bitmask & CURL_POLL_OUT) &&
  1914. data->easy_conn->send_pipe &&
  1915. data->easy_conn->send_pipe->head)
  1916. data = data->easy_conn->send_pipe->head->ptr;
  1917. else if((ev_bitmask & CURL_POLL_IN) &&
  1918. data->easy_conn->recv_pipe &&
  1919. data->easy_conn->recv_pipe->head)
  1920. data = data->easy_conn->recv_pipe->head->ptr;
  1921. }
  1922. if(data->easy_conn &&
  1923. !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
  1924. /* set socket event bitmask if they're not locked */
  1925. data->easy_conn->cselect_bits = ev_bitmask;
  1926. sigpipe_ignore(data, &pipe_st);
  1927. result = multi_runsingle(multi, now, data);
  1928. sigpipe_restore(&pipe_st);
  1929. if(data->easy_conn &&
  1930. !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
  1931. /* clear the bitmask only if not locked */
  1932. data->easy_conn->cselect_bits = 0;
  1933. if(CURLM_OK >= result)
  1934. /* get the socket(s) and check if the state has been changed since
  1935. last */
  1936. singlesocket(multi, data);
  1937. /* Now we fall-through and do the timer-based stuff, since we don't want
  1938. to force the user to have to deal with timeouts as long as at least
  1939. one connection in fact has traffic. */
  1940. data = NULL; /* set data to NULL again to avoid calling
  1941. multi_runsingle() in case there's no need to */
  1942. now = Curl_tvnow(); /* get a newer time since the multi_runsingle() loop
  1943. may have taken some time */
  1944. }
  1945. }
  1946. else {
  1947. /* Asked to run due to time-out. Clear the 'lastcall' variable to force
  1948. update_timer() to trigger a callback to the app again even if the same
  1949. timeout is still the one to run after this call. That handles the case
  1950. when the application asks libcurl to run the timeout prematurely. */
  1951. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  1952. }
  1953. /*
  1954. * The loop following here will go on as long as there are expire-times left
  1955. * to process in the splay and 'data' will be re-assigned for every expired
  1956. * handle we deal with.
  1957. */
  1958. do {
  1959. /* the first loop lap 'data' can be NULL */
  1960. if(data) {
  1961. SIGPIPE_VARIABLE(pipe_st);
  1962. sigpipe_ignore(data, &pipe_st);
  1963. result = multi_runsingle(multi, now, data);
  1964. sigpipe_restore(&pipe_st);
  1965. if(CURLM_OK >= result)
  1966. /* get the socket(s) and check if the state has been changed since
  1967. last */
  1968. singlesocket(multi, data);
  1969. }
  1970. /* Check if there's one (more) expired timer to deal with! This function
  1971. extracts a matching node if there is one */
  1972. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  1973. if(t) {
  1974. data = t->payload; /* assign this for next loop */
  1975. (void)add_next_timeout(now, multi, t->payload);
  1976. }
  1977. } while(t);
  1978. *running_handles = multi->num_alive;
  1979. return result;
  1980. }
  1981. #undef curl_multi_setopt
  1982. CURLMcode curl_multi_setopt(CURLM *multi_handle,
  1983. CURLMoption option, ...)
  1984. {
  1985. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1986. CURLMcode res = CURLM_OK;
  1987. va_list param;
  1988. if(!GOOD_MULTI_HANDLE(multi))
  1989. return CURLM_BAD_HANDLE;
  1990. va_start(param, option);
  1991. switch(option) {
  1992. case CURLMOPT_SOCKETFUNCTION:
  1993. multi->socket_cb = va_arg(param, curl_socket_callback);
  1994. break;
  1995. case CURLMOPT_SOCKETDATA:
  1996. multi->socket_userp = va_arg(param, void *);
  1997. break;
  1998. case CURLMOPT_PIPELINING:
  1999. multi->pipelining_enabled = (0 != va_arg(param, long)) ? TRUE : FALSE;
  2000. break;
  2001. case CURLMOPT_TIMERFUNCTION:
  2002. multi->timer_cb = va_arg(param, curl_multi_timer_callback);
  2003. break;
  2004. case CURLMOPT_TIMERDATA:
  2005. multi->timer_userp = va_arg(param, void *);
  2006. break;
  2007. case CURLMOPT_MAXCONNECTS:
  2008. multi->maxconnects = va_arg(param, long);
  2009. break;
  2010. case CURLMOPT_MAX_HOST_CONNECTIONS:
  2011. multi->max_host_connections = va_arg(param, long);
  2012. break;
  2013. case CURLMOPT_MAX_PIPELINE_LENGTH:
  2014. multi->max_pipeline_length = va_arg(param, long);
  2015. break;
  2016. case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
  2017. multi->content_length_penalty_size = va_arg(param, long);
  2018. break;
  2019. case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
  2020. multi->chunk_length_penalty_size = va_arg(param, long);
  2021. break;
  2022. case CURLMOPT_PIPELINING_SITE_BL:
  2023. res = Curl_pipeline_set_site_blacklist(va_arg(param, char **),
  2024. &multi->pipelining_site_bl);
  2025. break;
  2026. case CURLMOPT_PIPELINING_SERVER_BL:
  2027. res = Curl_pipeline_set_server_blacklist(va_arg(param, char **),
  2028. &multi->pipelining_server_bl);
  2029. break;
  2030. case CURLMOPT_MAX_TOTAL_CONNECTIONS:
  2031. multi->max_total_connections = va_arg(param, long);
  2032. break;
  2033. default:
  2034. res = CURLM_UNKNOWN_OPTION;
  2035. break;
  2036. }
  2037. va_end(param);
  2038. return res;
  2039. }
  2040. /* we define curl_multi_socket() in the public multi.h header */
  2041. #undef curl_multi_socket
  2042. CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
  2043. int *running_handles)
  2044. {
  2045. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
  2046. 0, running_handles);
  2047. if(CURLM_OK >= result)
  2048. update_timer((struct Curl_multi *)multi_handle);
  2049. return result;
  2050. }
  2051. CURLMcode curl_multi_socket_action(CURLM *multi_handle, curl_socket_t s,
  2052. int ev_bitmask, int *running_handles)
  2053. {
  2054. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
  2055. ev_bitmask, running_handles);
  2056. if(CURLM_OK >= result)
  2057. update_timer((struct Curl_multi *)multi_handle);
  2058. return result;
  2059. }
  2060. CURLMcode curl_multi_socket_all(CURLM *multi_handle, int *running_handles)
  2061. {
  2062. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle,
  2063. TRUE, CURL_SOCKET_BAD, 0, running_handles);
  2064. if(CURLM_OK >= result)
  2065. update_timer((struct Curl_multi *)multi_handle);
  2066. return result;
  2067. }
  2068. static CURLMcode multi_timeout(struct Curl_multi *multi,
  2069. long *timeout_ms)
  2070. {
  2071. static struct timeval tv_zero = {0,0};
  2072. if(multi->timetree) {
  2073. /* we have a tree of expire times */
  2074. struct timeval now = Curl_tvnow();
  2075. /* splay the lowest to the bottom */
  2076. multi->timetree = Curl_splay(tv_zero, multi->timetree);
  2077. if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
  2078. /* some time left before expiration */
  2079. *timeout_ms = curlx_tvdiff(multi->timetree->key, now);
  2080. if(!*timeout_ms)
  2081. /*
  2082. * Since we only provide millisecond resolution on the returned value
  2083. * and the diff might be less than one millisecond here, we don't
  2084. * return zero as that may cause short bursts of busyloops on fast
  2085. * processors while the diff is still present but less than one
  2086. * millisecond! instead we return 1 until the time is ripe.
  2087. */
  2088. *timeout_ms=1;
  2089. }
  2090. else
  2091. /* 0 means immediately */
  2092. *timeout_ms = 0;
  2093. }
  2094. else
  2095. *timeout_ms = -1;
  2096. return CURLM_OK;
  2097. }
  2098. CURLMcode curl_multi_timeout(CURLM *multi_handle,
  2099. long *timeout_ms)
  2100. {
  2101. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  2102. /* First, make some basic checks that the CURLM handle is a good handle */
  2103. if(!GOOD_MULTI_HANDLE(multi))
  2104. return CURLM_BAD_HANDLE;
  2105. return multi_timeout(multi, timeout_ms);
  2106. }
  2107. /*
  2108. * Tell the application it should update its timers, if it subscribes to the
  2109. * update timer callback.
  2110. */
  2111. static int update_timer(struct Curl_multi *multi)
  2112. {
  2113. long timeout_ms;
  2114. if(!multi->timer_cb)
  2115. return 0;
  2116. if(multi_timeout(multi, &timeout_ms)) {
  2117. return -1;
  2118. }
  2119. if(timeout_ms < 0) {
  2120. static const struct timeval none={0,0};
  2121. if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
  2122. multi->timer_lastcall = none;
  2123. /* there's no timeout now but there was one previously, tell the app to
  2124. disable it */
  2125. return multi->timer_cb((CURLM*)multi, -1, multi->timer_userp);
  2126. }
  2127. return 0;
  2128. }
  2129. /* When multi_timeout() is done, multi->timetree points to the node with the
  2130. * timeout we got the (relative) time-out time for. We can thus easily check
  2131. * if this is the same (fixed) time as we got in a previous call and then
  2132. * avoid calling the callback again. */
  2133. if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
  2134. return 0;
  2135. multi->timer_lastcall = multi->timetree->key;
  2136. return multi->timer_cb((CURLM*)multi, timeout_ms, multi->timer_userp);
  2137. }
  2138. static bool isHandleAtHead(struct SessionHandle *handle,
  2139. struct curl_llist *pipeline)
  2140. {
  2141. struct curl_llist_element *curr = pipeline->head;
  2142. if(curr)
  2143. return (curr->ptr == handle) ? TRUE : FALSE;
  2144. return FALSE;
  2145. }
  2146. /*
  2147. * multi_freetimeout()
  2148. *
  2149. * Callback used by the llist system when a single timeout list entry is
  2150. * destroyed.
  2151. */
  2152. static void multi_freetimeout(void *user, void *entryptr)
  2153. {
  2154. (void)user;
  2155. /* the entry was plain malloc()'ed */
  2156. free(entryptr);
  2157. }
  2158. /*
  2159. * multi_addtimeout()
  2160. *
  2161. * Add a timestamp to the list of timeouts. Keep the list sorted so that head
  2162. * of list is always the timeout nearest in time.
  2163. *
  2164. */
  2165. static CURLMcode
  2166. multi_addtimeout(struct curl_llist *timeoutlist,
  2167. struct timeval *stamp)
  2168. {
  2169. struct curl_llist_element *e;
  2170. struct timeval *timedup;
  2171. struct curl_llist_element *prev = NULL;
  2172. timedup = malloc(sizeof(*timedup));
  2173. if(!timedup)
  2174. return CURLM_OUT_OF_MEMORY;
  2175. /* copy the timestamp */
  2176. memcpy(timedup, stamp, sizeof(*timedup));
  2177. if(Curl_llist_count(timeoutlist)) {
  2178. /* find the correct spot in the list */
  2179. for(e = timeoutlist->head; e; e = e->next) {
  2180. struct timeval *checktime = e->ptr;
  2181. long diff = curlx_tvdiff(*checktime, *timedup);
  2182. if(diff > 0)
  2183. break;
  2184. prev = e;
  2185. }
  2186. }
  2187. /* else
  2188. this is the first timeout on the list */
  2189. if(!Curl_llist_insert_next(timeoutlist, prev, timedup)) {
  2190. free(timedup);
  2191. return CURLM_OUT_OF_MEMORY;
  2192. }
  2193. return CURLM_OK;
  2194. }
  2195. /*
  2196. * Curl_expire()
  2197. *
  2198. * given a number of milliseconds from now to use to set the 'act before
  2199. * this'-time for the transfer, to be extracted by curl_multi_timeout()
  2200. *
  2201. * Note that the timeout will be added to a queue of timeouts if it defines a
  2202. * moment in time that is later than the current head of queue.
  2203. *
  2204. * Pass zero to clear all timeout values for this handle.
  2205. */
  2206. void Curl_expire(struct SessionHandle *data, long milli)
  2207. {
  2208. struct Curl_multi *multi = data->multi;
  2209. struct timeval *nowp = &data->state.expiretime;
  2210. int rc;
  2211. /* this is only interesting while there is still an associated multi struct
  2212. remaining! */
  2213. if(!multi)
  2214. return;
  2215. if(!milli) {
  2216. /* No timeout, clear the time data. */
  2217. if(nowp->tv_sec || nowp->tv_usec) {
  2218. /* Since this is an cleared time, we must remove the previous entry from
  2219. the splay tree */
  2220. struct curl_llist *list = data->state.timeoutlist;
  2221. rc = Curl_splayremovebyaddr(multi->timetree,
  2222. &data->state.timenode,
  2223. &multi->timetree);
  2224. if(rc)
  2225. infof(data, "Internal error clearing splay node = %d\n", rc);
  2226. /* flush the timeout list too */
  2227. while(list->size > 0)
  2228. Curl_llist_remove(list, list->tail, NULL);
  2229. #ifdef DEBUGBUILD
  2230. infof(data, "Expire cleared\n");
  2231. #endif
  2232. nowp->tv_sec = 0;
  2233. nowp->tv_usec = 0;
  2234. }
  2235. }
  2236. else {
  2237. struct timeval set;
  2238. set = Curl_tvnow();
  2239. set.tv_sec += milli/1000;
  2240. set.tv_usec += (milli%1000)*1000;
  2241. if(set.tv_usec >= 1000000) {
  2242. set.tv_sec++;
  2243. set.tv_usec -= 1000000;
  2244. }
  2245. if(nowp->tv_sec || nowp->tv_usec) {
  2246. /* This means that the struct is added as a node in the splay tree.
  2247. Compare if the new time is earlier, and only remove-old/add-new if it
  2248. is. */
  2249. long diff = curlx_tvdiff(set, *nowp);
  2250. if(diff > 0) {
  2251. /* the new expire time was later so just add it to the queue
  2252. and get out */
  2253. multi_addtimeout(data->state.timeoutlist, &set);
  2254. return;
  2255. }
  2256. /* the new time is newer than the presently set one, so add the current
  2257. to the queue and update the head */
  2258. multi_addtimeout(data->state.timeoutlist, nowp);
  2259. /* Since this is an updated time, we must remove the previous entry from
  2260. the splay tree first and then re-add the new value */
  2261. rc = Curl_splayremovebyaddr(multi->timetree,
  2262. &data->state.timenode,
  2263. &multi->timetree);
  2264. if(rc)
  2265. infof(data, "Internal error removing splay node = %d\n", rc);
  2266. }
  2267. *nowp = set;
  2268. data->state.timenode.payload = data;
  2269. multi->timetree = Curl_splayinsert(*nowp,
  2270. multi->timetree,
  2271. &data->state.timenode);
  2272. }
  2273. #if 0
  2274. Curl_splayprint(multi->timetree, 0, TRUE);
  2275. #endif
  2276. }
  2277. /*
  2278. * Curl_expire_latest()
  2279. *
  2280. * This is like Curl_expire() but will only add a timeout node to the list of
  2281. * timers if there is no timeout that will expire before the given time.
  2282. *
  2283. * Use this function if the code logic risks calling this function many times
  2284. * or if there's no particular conditional wait in the code for this specific
  2285. * time-out period to expire.
  2286. *
  2287. */
  2288. void Curl_expire_latest(struct SessionHandle *data, long milli)
  2289. {
  2290. struct timeval *expire = &data->state.expiretime;
  2291. struct timeval set;
  2292. set = Curl_tvnow();
  2293. set.tv_sec += milli / 1000;
  2294. set.tv_usec += (milli % 1000) * 1000;
  2295. if(set.tv_usec >= 1000000) {
  2296. set.tv_sec++;
  2297. set.tv_usec -= 1000000;
  2298. }
  2299. if(expire->tv_sec || expire->tv_usec) {
  2300. /* This means that the struct is added as a node in the splay tree.
  2301. Compare if the new time is earlier, and only remove-old/add-new if it
  2302. is. */
  2303. long diff = curlx_tvdiff(set, *expire);
  2304. if(diff > 0)
  2305. /* the new expire time was later than the top time, so just skip this */
  2306. return;
  2307. }
  2308. /* Just add the timeout like normal */
  2309. Curl_expire(data, milli);
  2310. }
  2311. CURLMcode curl_multi_assign(CURLM *multi_handle,
  2312. curl_socket_t s, void *hashp)
  2313. {
  2314. struct Curl_sh_entry *there = NULL;
  2315. struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
  2316. if(s != CURL_SOCKET_BAD)
  2317. there = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(curl_socket_t));
  2318. if(!there)
  2319. return CURLM_BAD_SOCKET;
  2320. there->socketp = hashp;
  2321. return CURLM_OK;
  2322. }
  2323. size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
  2324. {
  2325. return multi ? multi->max_host_connections : 0;
  2326. }
  2327. size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
  2328. {
  2329. return multi ? multi->max_total_connections : 0;
  2330. }
  2331. size_t Curl_multi_max_pipeline_length(struct Curl_multi *multi)
  2332. {
  2333. return multi ? multi->max_pipeline_length : 0;
  2334. }
  2335. curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi)
  2336. {
  2337. return multi ? multi->content_length_penalty_size : 0;
  2338. }
  2339. curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi)
  2340. {
  2341. return multi ? multi->chunk_length_penalty_size : 0;
  2342. }
  2343. struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi)
  2344. {
  2345. return multi->pipelining_site_bl;
  2346. }
  2347. struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi)
  2348. {
  2349. return multi->pipelining_server_bl;
  2350. }
  2351. void Curl_multi_process_pending_handles(struct Curl_multi *multi)
  2352. {
  2353. struct curl_llist_element *e = multi->pending->head;
  2354. while(e) {
  2355. struct SessionHandle *data = e->ptr;
  2356. struct curl_llist_element *next = e->next;
  2357. if(data->mstate == CURLM_STATE_CONNECT_PEND) {
  2358. multistate(data, CURLM_STATE_CONNECT);
  2359. /* Remove this node from the list */
  2360. Curl_llist_remove(multi->pending, e, NULL);
  2361. /* Make sure that the handle will be processed soonish. */
  2362. Curl_expire_latest(data, 1);
  2363. }
  2364. e = next; /* operate on next handle */
  2365. }
  2366. }
  2367. #ifdef DEBUGBUILD
  2368. void Curl_multi_dump(const struct Curl_multi *multi_handle)
  2369. {
  2370. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  2371. struct SessionHandle *data;
  2372. int i;
  2373. fprintf(stderr, "* Multi status: %d handles, %d alive\n",
  2374. multi->num_easy, multi->num_alive);
  2375. for(data=multi->easyp; data; data = data->next) {
  2376. if(data->mstate < CURLM_STATE_COMPLETED) {
  2377. /* only display handles that are not completed */
  2378. fprintf(stderr, "handle %p, state %s, %d sockets\n",
  2379. (void *)data,
  2380. statename[data->mstate], data->numsocks);
  2381. for(i=0; i < data->numsocks; i++) {
  2382. curl_socket_t s = data->sockets[i];
  2383. struct Curl_sh_entry *entry =
  2384. Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
  2385. fprintf(stderr, "%d ", (int)s);
  2386. if(!entry) {
  2387. fprintf(stderr, "INTERNAL CONFUSION\n");
  2388. continue;
  2389. }
  2390. fprintf(stderr, "[%s %s] ",
  2391. entry->action&CURL_POLL_IN?"RECVING":"",
  2392. entry->action&CURL_POLL_OUT?"SENDING":"");
  2393. }
  2394. if(data->numsocks)
  2395. fprintf(stderr, "\n");
  2396. }
  2397. }
  2398. }
  2399. #endif