2
0

multi.c 130 KB

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