multi.c 116 KB

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