multi.c 119 KB

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