multi.c 118 KB

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