multi.c 113 KB

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