2
0

multi.c 119 KB

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