2
0

multi.c 88 KB

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