multi.c 115 KB

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