multi.c 103 KB

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