multi.c 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337
  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. #else
  1336. buf[0] = 1;
  1337. #endif
  1338. while(1) {
  1339. /* swrite() is not thread-safe in general, because concurrent calls
  1340. can have their messages interleaved, but in this case the content
  1341. of the messages does not matter, which makes it ok to call.
  1342. The write socket is set to non-blocking, this way this function
  1343. cannot block, making it safe to call even from the same thread
  1344. that will call curl_multi_wait(). If swrite() returns that it
  1345. would block, it is considered successful because it means that
  1346. previous calls to this function will wake up the poll(). */
  1347. if(wakeup_write(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) {
  1348. int err = SOCKERRNO;
  1349. int return_success;
  1350. #ifdef USE_WINSOCK
  1351. return_success = WSAEWOULDBLOCK == err;
  1352. #else
  1353. if(EINTR == err)
  1354. continue;
  1355. return_success = EWOULDBLOCK == err || EAGAIN == err;
  1356. #endif
  1357. if(!return_success)
  1358. return CURLM_WAKEUP_FAILURE;
  1359. }
  1360. return CURLM_OK;
  1361. }
  1362. }
  1363. #endif
  1364. #endif
  1365. return CURLM_WAKEUP_FAILURE;
  1366. }
  1367. /*
  1368. * multi_ischanged() is called
  1369. *
  1370. * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
  1371. * => CONNECT action.
  1372. *
  1373. * Set 'clear' to TRUE to have it also clear the state variable.
  1374. */
  1375. static bool multi_ischanged(struct Curl_multi *multi, bool clear)
  1376. {
  1377. bool retval = multi->recheckstate;
  1378. if(clear)
  1379. multi->recheckstate = FALSE;
  1380. return retval;
  1381. }
  1382. /*
  1383. * Curl_multi_connchanged() is called to tell that there is a connection in
  1384. * this multi handle that has changed state (multiplexing become possible, the
  1385. * number of allowed streams changed or similar), and a subsequent use of this
  1386. * multi handle should move CONNECT_PEND handles back to CONNECT to have them
  1387. * retry.
  1388. */
  1389. void Curl_multi_connchanged(struct Curl_multi *multi)
  1390. {
  1391. multi->recheckstate = TRUE;
  1392. }
  1393. CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
  1394. struct Curl_easy *data,
  1395. struct connectdata *conn)
  1396. {
  1397. CURLMcode rc;
  1398. if(multi->in_callback)
  1399. return CURLM_RECURSIVE_API_CALL;
  1400. rc = curl_multi_add_handle(multi, data);
  1401. if(!rc) {
  1402. struct SingleRequest *k = &data->req;
  1403. /* pass in NULL for 'conn' here since we do not want to init the
  1404. connection, only this transfer */
  1405. Curl_init_do(data, NULL);
  1406. /* take this handle to the perform state right away */
  1407. multistate(data, MSTATE_PERFORMING);
  1408. Curl_attach_connection(data, conn);
  1409. k->keepon |= KEEP_RECV; /* setup to receive! */
  1410. }
  1411. return rc;
  1412. }
  1413. static CURLcode multi_do(struct Curl_easy *data, bool *done)
  1414. {
  1415. CURLcode result = CURLE_OK;
  1416. struct connectdata *conn = data->conn;
  1417. DEBUGASSERT(conn);
  1418. DEBUGASSERT(conn->handler);
  1419. if(conn->handler->do_it)
  1420. result = conn->handler->do_it(data, done);
  1421. return result;
  1422. }
  1423. /*
  1424. * multi_do_more() is called during the DO_MORE multi state. It is basically a
  1425. * second stage DO state which (wrongly) was introduced to support FTP's
  1426. * second connection.
  1427. *
  1428. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
  1429. * DOING state there is more work to do!
  1430. */
  1431. static CURLcode multi_do_more(struct Curl_easy *data, int *complete)
  1432. {
  1433. CURLcode result = CURLE_OK;
  1434. struct connectdata *conn = data->conn;
  1435. *complete = 0;
  1436. if(conn->handler->do_more)
  1437. result = conn->handler->do_more(data, complete);
  1438. return result;
  1439. }
  1440. /*
  1441. * Check whether a timeout occurred, and handle it if it did
  1442. */
  1443. static bool multi_handle_timeout(struct Curl_easy *data,
  1444. struct curltime *now,
  1445. bool *stream_error,
  1446. CURLcode *result)
  1447. {
  1448. bool connect_timeout = data->mstate < MSTATE_DO;
  1449. timediff_t timeout_ms = Curl_timeleft(data, now, connect_timeout);
  1450. if(timeout_ms < 0) {
  1451. /* Handle timed out */
  1452. struct curltime since;
  1453. if(connect_timeout)
  1454. since = data->progress.t_startsingle;
  1455. else
  1456. since = data->progress.t_startop;
  1457. if(data->mstate == MSTATE_RESOLVING)
  1458. failf(data, "Resolving timed out after %" FMT_TIMEDIFF_T
  1459. " milliseconds", Curl_timediff(*now, since));
  1460. else if(data->mstate == MSTATE_CONNECTING)
  1461. failf(data, "Connection timed out after %" FMT_TIMEDIFF_T
  1462. " milliseconds", Curl_timediff(*now, since));
  1463. else {
  1464. struct SingleRequest *k = &data->req;
  1465. if(k->size != -1) {
  1466. failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
  1467. " milliseconds with %" FMT_OFF_T " out of %"
  1468. FMT_OFF_T " bytes received",
  1469. Curl_timediff(*now, since), k->bytecount, k->size);
  1470. }
  1471. else {
  1472. failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
  1473. " milliseconds with %" FMT_OFF_T " bytes received",
  1474. Curl_timediff(*now, since), k->bytecount);
  1475. }
  1476. }
  1477. *result = CURLE_OPERATION_TIMEDOUT;
  1478. if(data->conn) {
  1479. /* Force connection closed if the connection has indeed been used */
  1480. if(data->mstate > MSTATE_DO) {
  1481. streamclose(data->conn, "Disconnect due to timeout");
  1482. *stream_error = TRUE;
  1483. }
  1484. (void)multi_done(data, *result, TRUE);
  1485. }
  1486. return TRUE;
  1487. }
  1488. return FALSE;
  1489. }
  1490. /*
  1491. * We are doing protocol-specific connecting and this is being called over and
  1492. * over from the multi interface until the connection phase is done on
  1493. * protocol layer.
  1494. */
  1495. static CURLcode protocol_connecting(struct Curl_easy *data, bool *done)
  1496. {
  1497. CURLcode result = CURLE_OK;
  1498. struct connectdata *conn = data->conn;
  1499. if(conn && conn->handler->connecting) {
  1500. *done = FALSE;
  1501. result = conn->handler->connecting(data, done);
  1502. }
  1503. else
  1504. *done = TRUE;
  1505. return result;
  1506. }
  1507. /*
  1508. * We are DOING this is being called over and over from the multi interface
  1509. * until the DOING phase is done on protocol layer.
  1510. */
  1511. static CURLcode protocol_doing(struct Curl_easy *data, bool *done)
  1512. {
  1513. CURLcode result = CURLE_OK;
  1514. struct connectdata *conn = data->conn;
  1515. if(conn && conn->handler->doing) {
  1516. *done = FALSE;
  1517. result = conn->handler->doing(data, done);
  1518. }
  1519. else
  1520. *done = TRUE;
  1521. return result;
  1522. }
  1523. /*
  1524. * We have discovered that the TCP connection has been successful, we can now
  1525. * proceed with some action.
  1526. *
  1527. */
  1528. static CURLcode protocol_connect(struct Curl_easy *data,
  1529. bool *protocol_done)
  1530. {
  1531. CURLcode result = CURLE_OK;
  1532. struct connectdata *conn = data->conn;
  1533. DEBUGASSERT(conn);
  1534. DEBUGASSERT(protocol_done);
  1535. *protocol_done = FALSE;
  1536. if(Curl_conn_is_connected(conn, FIRSTSOCKET)
  1537. && conn->bits.protoconnstart) {
  1538. /* We already are connected, get back. This may happen when the connect
  1539. worked fine in the first call, like when we connect to a local server
  1540. or proxy. Note that we do not know if the protocol is actually done.
  1541. Unless this protocol does not have any protocol-connect callback, as
  1542. then we know we are done. */
  1543. if(!conn->handler->connecting)
  1544. *protocol_done = TRUE;
  1545. return CURLE_OK;
  1546. }
  1547. if(!conn->bits.protoconnstart) {
  1548. if(conn->handler->connect_it) {
  1549. /* is there a protocol-specific connect() procedure? */
  1550. /* Call the protocol-specific connect function */
  1551. result = conn->handler->connect_it(data, protocol_done);
  1552. }
  1553. else
  1554. *protocol_done = TRUE;
  1555. /* it has started, possibly even completed but that knowledge is not stored
  1556. in this bit! */
  1557. if(!result)
  1558. conn->bits.protoconnstart = TRUE;
  1559. }
  1560. return result; /* pass back status */
  1561. }
  1562. static void set_in_callback(struct Curl_multi *multi, bool value)
  1563. {
  1564. multi->in_callback = value;
  1565. }
  1566. /*
  1567. * posttransfer() is called immediately after a transfer ends
  1568. */
  1569. static void multi_posttransfer(struct Curl_easy *data)
  1570. {
  1571. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1572. /* restore the signal handler for SIGPIPE before we get back */
  1573. if(!data->set.no_signal)
  1574. signal(SIGPIPE, data->state.prev_signal);
  1575. #else
  1576. (void)data; /* unused parameter */
  1577. #endif
  1578. }
  1579. /*
  1580. * multi_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1581. * as given by the remote server and set up the new URL to request.
  1582. *
  1583. * This function DOES NOT FREE the given url.
  1584. */
  1585. static CURLcode multi_follow(struct Curl_easy *data,
  1586. char *newurl, /* the Location: string */
  1587. followtype type) /* see transfer.h */
  1588. {
  1589. #ifdef CURL_DISABLE_HTTP
  1590. (void)data;
  1591. (void)newurl;
  1592. (void)type;
  1593. /* Location: following will not happen when HTTP is disabled */
  1594. return CURLE_TOO_MANY_REDIRECTS;
  1595. #else
  1596. /* Location: redirect */
  1597. bool disallowport = FALSE;
  1598. bool reachedmax = FALSE;
  1599. CURLUcode uc;
  1600. DEBUGASSERT(type != FOLLOW_NONE);
  1601. if(type != FOLLOW_FAKE)
  1602. data->state.requests++; /* count all real follows */
  1603. if(type == FOLLOW_REDIR) {
  1604. if((data->set.maxredirs != -1) &&
  1605. (data->state.followlocation >= data->set.maxredirs)) {
  1606. reachedmax = TRUE;
  1607. type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
  1608. to URL */
  1609. }
  1610. else {
  1611. data->state.followlocation++; /* count redirect-followings, including
  1612. auth reloads */
  1613. if(data->set.http_auto_referer) {
  1614. CURLU *u;
  1615. char *referer = NULL;
  1616. /* We are asked to automatically set the previous URL as the referer
  1617. when we get the next URL. We pick the ->url field, which may or may
  1618. not be 100% correct */
  1619. if(data->state.referer_alloc) {
  1620. Curl_safefree(data->state.referer);
  1621. data->state.referer_alloc = FALSE;
  1622. }
  1623. /* Make a copy of the URL without credentials and fragment */
  1624. u = curl_url();
  1625. if(!u)
  1626. return CURLE_OUT_OF_MEMORY;
  1627. uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
  1628. if(!uc)
  1629. uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
  1630. if(!uc)
  1631. uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
  1632. if(!uc)
  1633. uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
  1634. if(!uc)
  1635. uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
  1636. curl_url_cleanup(u);
  1637. if(uc || !referer)
  1638. return CURLE_OUT_OF_MEMORY;
  1639. data->state.referer = referer;
  1640. data->state.referer_alloc = TRUE; /* yes, free this later */
  1641. }
  1642. }
  1643. }
  1644. if((type != FOLLOW_RETRY) &&
  1645. (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
  1646. Curl_is_absolute_url(newurl, NULL, 0, FALSE)) {
  1647. /* If this is not redirect due to a 401 or 407 response and an absolute
  1648. URL: do not allow a custom port number */
  1649. disallowport = TRUE;
  1650. }
  1651. DEBUGASSERT(data->state.uh);
  1652. uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, (unsigned int)
  1653. ((type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
  1654. ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
  1655. CURLU_ALLOW_SPACE |
  1656. (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)));
  1657. if(uc) {
  1658. if(type != FOLLOW_FAKE) {
  1659. failf(data, "The redirect target URL could not be parsed: %s",
  1660. curl_url_strerror(uc));
  1661. return Curl_uc_to_curlcode(uc);
  1662. }
  1663. /* the URL could not be parsed for some reason, but since this is FAKE
  1664. mode, just duplicate the field as-is */
  1665. newurl = strdup(newurl);
  1666. if(!newurl)
  1667. return CURLE_OUT_OF_MEMORY;
  1668. }
  1669. else {
  1670. uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
  1671. if(uc)
  1672. return Curl_uc_to_curlcode(uc);
  1673. /* Clear auth if this redirects to a different port number or protocol,
  1674. unless permitted */
  1675. if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
  1676. char *portnum;
  1677. int port;
  1678. bool clear = FALSE;
  1679. if(data->set.use_port && data->state.allow_port)
  1680. /* a custom port is used */
  1681. port = (int)data->set.use_port;
  1682. else {
  1683. uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
  1684. CURLU_DEFAULT_PORT);
  1685. if(uc) {
  1686. free(newurl);
  1687. return Curl_uc_to_curlcode(uc);
  1688. }
  1689. port = atoi(portnum);
  1690. free(portnum);
  1691. }
  1692. if(port != data->info.conn_remote_port) {
  1693. infof(data, "Clear auth, redirects to port from %u to %u",
  1694. data->info.conn_remote_port, port);
  1695. clear = TRUE;
  1696. }
  1697. else {
  1698. char *scheme;
  1699. const struct Curl_handler *p;
  1700. uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
  1701. if(uc) {
  1702. free(newurl);
  1703. return Curl_uc_to_curlcode(uc);
  1704. }
  1705. p = Curl_get_scheme_handler(scheme);
  1706. if(p && (p->protocol != data->info.conn_protocol)) {
  1707. infof(data, "Clear auth, redirects scheme from %s to %s",
  1708. data->info.conn_scheme, scheme);
  1709. clear = TRUE;
  1710. }
  1711. free(scheme);
  1712. }
  1713. if(clear) {
  1714. Curl_safefree(data->state.aptr.user);
  1715. Curl_safefree(data->state.aptr.passwd);
  1716. }
  1717. }
  1718. }
  1719. if(type == FOLLOW_FAKE) {
  1720. /* we are only figuring out the new URL if we would have followed locations
  1721. but now we are done so we can get out! */
  1722. data->info.wouldredirect = newurl;
  1723. if(reachedmax) {
  1724. failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
  1725. return CURLE_TOO_MANY_REDIRECTS;
  1726. }
  1727. return CURLE_OK;
  1728. }
  1729. if(disallowport)
  1730. data->state.allow_port = FALSE;
  1731. if(data->state.url_alloc)
  1732. Curl_safefree(data->state.url);
  1733. data->state.url = newurl;
  1734. data->state.url_alloc = TRUE;
  1735. Curl_req_soft_reset(&data->req, data);
  1736. infof(data, "Issue another request to this URL: '%s'", data->state.url);
  1737. /*
  1738. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1739. * differently based on exactly what return code there was.
  1740. *
  1741. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1742. * an HTTP (proxy-) authentication scheme other than Basic.
  1743. */
  1744. switch(data->info.httpcode) {
  1745. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1746. Authorization: XXXX header in the HTTP request code snippet */
  1747. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1748. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1749. /* 300 - Multiple Choices */
  1750. /* 306 - Not used */
  1751. /* 307 - Temporary Redirect */
  1752. default: /* for all above (and the unknown ones) */
  1753. /* Some codes are explicitly mentioned since I have checked RFC2616 and
  1754. * they seem to be OK to POST to.
  1755. */
  1756. break;
  1757. case 301: /* Moved Permanently */
  1758. /* (quote from RFC7231, section 6.4.2)
  1759. *
  1760. * Note: For historical reasons, a user agent MAY change the request
  1761. * method from POST to GET for the subsequent request. If this
  1762. * behavior is undesired, the 307 (Temporary Redirect) status code
  1763. * can be used instead.
  1764. *
  1765. * ----
  1766. *
  1767. * Many webservers expect this, so these servers often answers to a POST
  1768. * request with an error page. To be sure that libcurl gets the page that
  1769. * most user agents would get, libcurl has to force GET.
  1770. *
  1771. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1772. * can be overridden with CURLOPT_POSTREDIR.
  1773. */
  1774. if((data->state.httpreq == HTTPREQ_POST
  1775. || data->state.httpreq == HTTPREQ_POST_FORM
  1776. || data->state.httpreq == HTTPREQ_POST_MIME)
  1777. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1778. infof(data, "Switch from POST to GET");
  1779. data->state.httpreq = HTTPREQ_GET;
  1780. Curl_creader_set_rewind(data, FALSE);
  1781. }
  1782. break;
  1783. case 302: /* Found */
  1784. /* (quote from RFC7231, section 6.4.3)
  1785. *
  1786. * Note: For historical reasons, a user agent MAY change the request
  1787. * method from POST to GET for the subsequent request. If this
  1788. * behavior is undesired, the 307 (Temporary Redirect) status code
  1789. * can be used instead.
  1790. *
  1791. * ----
  1792. *
  1793. * Many webservers expect this, so these servers often answers to a POST
  1794. * request with an error page. To be sure that libcurl gets the page that
  1795. * most user agents would get, libcurl has to force GET.
  1796. *
  1797. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1798. * can be overridden with CURLOPT_POSTREDIR.
  1799. */
  1800. if((data->state.httpreq == HTTPREQ_POST
  1801. || data->state.httpreq == HTTPREQ_POST_FORM
  1802. || data->state.httpreq == HTTPREQ_POST_MIME)
  1803. && !(data->set.keep_post & CURL_REDIR_POST_302)) {
  1804. infof(data, "Switch from POST to GET");
  1805. data->state.httpreq = HTTPREQ_GET;
  1806. Curl_creader_set_rewind(data, FALSE);
  1807. }
  1808. break;
  1809. case 303: /* See Other */
  1810. /* 'See Other' location is not the resource but a substitute for the
  1811. * resource. In this case we switch the method to GET/HEAD, unless the
  1812. * method is POST and the user specified to keep it as POST.
  1813. * https://github.com/curl/curl/issues/5237#issuecomment-614641049
  1814. */
  1815. if(data->state.httpreq != HTTPREQ_GET &&
  1816. ((data->state.httpreq != HTTPREQ_POST &&
  1817. data->state.httpreq != HTTPREQ_POST_FORM &&
  1818. data->state.httpreq != HTTPREQ_POST_MIME) ||
  1819. !(data->set.keep_post & CURL_REDIR_POST_303))) {
  1820. data->state.httpreq = HTTPREQ_GET;
  1821. infof(data, "Switch to %s",
  1822. data->req.no_body ? "HEAD" : "GET");
  1823. }
  1824. break;
  1825. case 304: /* Not Modified */
  1826. /* 304 means we did a conditional request and it was "Not modified".
  1827. * We should not get any Location: header in this response!
  1828. */
  1829. break;
  1830. case 305: /* Use Proxy */
  1831. /* (quote from RFC2616, section 10.3.6):
  1832. * "The requested resource MUST be accessed through the proxy given
  1833. * by the Location field. The Location field gives the URI of the
  1834. * proxy. The recipient is expected to repeat this single request
  1835. * via the proxy. 305 responses MUST only be generated by origin
  1836. * servers."
  1837. */
  1838. break;
  1839. }
  1840. Curl_pgrsTime(data, TIMER_REDIRECT);
  1841. Curl_pgrsResetTransferSizes(data);
  1842. return CURLE_OK;
  1843. #endif /* CURL_DISABLE_HTTP */
  1844. }
  1845. static CURLMcode state_performing(struct Curl_easy *data,
  1846. struct curltime *nowp,
  1847. bool *stream_errorp,
  1848. CURLcode *resultp)
  1849. {
  1850. char *newurl = NULL;
  1851. bool retry = FALSE;
  1852. timediff_t recv_timeout_ms = 0;
  1853. timediff_t send_timeout_ms = 0;
  1854. CURLMcode rc = CURLM_OK;
  1855. CURLcode result = *resultp = CURLE_OK;
  1856. *stream_errorp = FALSE;
  1857. /* check if over send speed */
  1858. if(data->set.max_send_speed)
  1859. send_timeout_ms = Curl_pgrsLimitWaitTime(&data->progress.ul,
  1860. data->set.max_send_speed,
  1861. *nowp);
  1862. /* check if over recv speed */
  1863. if(data->set.max_recv_speed)
  1864. recv_timeout_ms = Curl_pgrsLimitWaitTime(&data->progress.dl,
  1865. data->set.max_recv_speed,
  1866. *nowp);
  1867. if(send_timeout_ms || recv_timeout_ms) {
  1868. Curl_ratelimit(data, *nowp);
  1869. multistate(data, MSTATE_RATELIMITING);
  1870. if(send_timeout_ms >= recv_timeout_ms)
  1871. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  1872. else
  1873. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  1874. return CURLM_OK;
  1875. }
  1876. /* read/write data if it is ready to do so */
  1877. result = Curl_sendrecv(data, nowp);
  1878. if(data->req.done || (result == CURLE_RECV_ERROR)) {
  1879. /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
  1880. * condition and the server closed the reused connection exactly when we
  1881. * wanted to use it, so figure out if that is indeed the case.
  1882. */
  1883. CURLcode ret = Curl_retry_request(data, &newurl);
  1884. if(!ret)
  1885. retry = !!newurl;
  1886. else if(!result)
  1887. result = ret;
  1888. if(retry) {
  1889. /* if we are to retry, set the result to OK and consider the
  1890. request as done */
  1891. result = CURLE_OK;
  1892. data->req.done = TRUE;
  1893. }
  1894. }
  1895. else if((CURLE_HTTP2_STREAM == result) &&
  1896. Curl_h2_http_1_1_error(data)) {
  1897. CURLcode ret = Curl_retry_request(data, &newurl);
  1898. if(!ret) {
  1899. infof(data, "Downgrades to HTTP/1.1");
  1900. streamclose(data->conn, "Disconnect HTTP/2 for HTTP/1");
  1901. data->state.httpwant = CURL_HTTP_VERSION_1_1;
  1902. /* clear the error message bit too as we ignore the one we got */
  1903. data->state.errorbuf = FALSE;
  1904. if(!newurl)
  1905. /* typically for HTTP_1_1_REQUIRED error on first flight */
  1906. newurl = strdup(data->state.url);
  1907. /* if we are to retry, set the result to OK and consider the request
  1908. as done */
  1909. retry = TRUE;
  1910. result = CURLE_OK;
  1911. data->req.done = TRUE;
  1912. }
  1913. else
  1914. result = ret;
  1915. }
  1916. if(result) {
  1917. /*
  1918. * The transfer phase returned error, we mark the connection to get closed
  1919. * to prevent being reused. This is because we cannot possibly know if the
  1920. * connection is in a good shape or not now. Unless it is a protocol which
  1921. * uses two "channels" like FTP, as then the error happened in the data
  1922. * connection.
  1923. */
  1924. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  1925. result != CURLE_HTTP2_STREAM)
  1926. streamclose(data->conn, "Transfer returned error");
  1927. multi_posttransfer(data);
  1928. multi_done(data, result, TRUE);
  1929. }
  1930. else if(data->req.done && !Curl_cwriter_is_paused(data)) {
  1931. /* call this even if the readwrite function returned error */
  1932. multi_posttransfer(data);
  1933. /* When we follow redirects or is set to retry the connection, we must to
  1934. go back to the CONNECT state */
  1935. if(data->req.newurl || retry) {
  1936. followtype follow = FOLLOW_NONE;
  1937. if(!retry) {
  1938. /* if the URL is a follow-location and not just a retried request then
  1939. figure out the URL here */
  1940. free(newurl);
  1941. newurl = data->req.newurl;
  1942. data->req.newurl = NULL;
  1943. follow = FOLLOW_REDIR;
  1944. }
  1945. else
  1946. follow = FOLLOW_RETRY;
  1947. (void)multi_done(data, CURLE_OK, FALSE);
  1948. /* multi_done() might return CURLE_GOT_NOTHING */
  1949. result = multi_follow(data, newurl, follow);
  1950. if(!result) {
  1951. multistate(data, MSTATE_SETUP);
  1952. rc = CURLM_CALL_MULTI_PERFORM;
  1953. }
  1954. }
  1955. else {
  1956. /* after the transfer is done, go DONE */
  1957. /* but first check to see if we got a location info even though we are
  1958. not following redirects */
  1959. if(data->req.location) {
  1960. free(newurl);
  1961. newurl = data->req.location;
  1962. data->req.location = NULL;
  1963. result = multi_follow(data, newurl, FOLLOW_FAKE);
  1964. if(result) {
  1965. *stream_errorp = TRUE;
  1966. result = multi_done(data, result, TRUE);
  1967. }
  1968. }
  1969. if(!result) {
  1970. multistate(data, MSTATE_DONE);
  1971. rc = CURLM_CALL_MULTI_PERFORM;
  1972. }
  1973. }
  1974. }
  1975. else if(data->state.select_bits && !Curl_xfer_is_blocked(data)) {
  1976. /* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer does
  1977. not get stuck on this transfer at the expense of other concurrent
  1978. transfers */
  1979. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  1980. }
  1981. free(newurl);
  1982. *resultp = result;
  1983. return rc;
  1984. }
  1985. static CURLMcode state_do(struct Curl_easy *data,
  1986. bool *stream_errorp,
  1987. CURLcode *resultp)
  1988. {
  1989. CURLMcode rc = CURLM_OK;
  1990. CURLcode result = CURLE_OK;
  1991. if(data->set.fprereq) {
  1992. int prereq_rc;
  1993. /* call the prerequest callback function */
  1994. Curl_set_in_callback(data, TRUE);
  1995. prereq_rc = data->set.fprereq(data->set.prereq_userp,
  1996. data->info.primary.remote_ip,
  1997. data->info.primary.local_ip,
  1998. data->info.primary.remote_port,
  1999. data->info.primary.local_port);
  2000. Curl_set_in_callback(data, FALSE);
  2001. if(prereq_rc != CURL_PREREQFUNC_OK) {
  2002. failf(data, "operation aborted by pre-request callback");
  2003. /* failure in pre-request callback - do not do any other processing */
  2004. result = CURLE_ABORTED_BY_CALLBACK;
  2005. multi_posttransfer(data);
  2006. multi_done(data, result, FALSE);
  2007. *stream_errorp = TRUE;
  2008. goto end;
  2009. }
  2010. }
  2011. if(data->set.connect_only == 1) {
  2012. /* keep connection open for application to use the socket */
  2013. connkeep(data->conn, "CONNECT_ONLY");
  2014. multistate(data, MSTATE_DONE);
  2015. rc = CURLM_CALL_MULTI_PERFORM;
  2016. }
  2017. else {
  2018. bool dophase_done = FALSE;
  2019. /* Perform the protocol's DO action */
  2020. result = multi_do(data, &dophase_done);
  2021. /* When multi_do() returns failure, data->conn might be NULL! */
  2022. if(!result) {
  2023. if(!dophase_done) {
  2024. #ifndef CURL_DISABLE_FTP
  2025. /* some steps needed for wildcard matching */
  2026. if(data->state.wildcardmatch) {
  2027. struct WildcardData *wc = data->wildcard;
  2028. if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
  2029. /* skip some states if it is important */
  2030. multi_done(data, CURLE_OK, FALSE);
  2031. /* if there is no connection left, skip the DONE state */
  2032. multistate(data, data->conn ?
  2033. MSTATE_DONE : MSTATE_COMPLETED);
  2034. rc = CURLM_CALL_MULTI_PERFORM;
  2035. goto end;
  2036. }
  2037. }
  2038. #endif
  2039. /* DO was not completed in one function call, we must continue
  2040. DOING... */
  2041. multistate(data, MSTATE_DOING);
  2042. rc = CURLM_CALL_MULTI_PERFORM;
  2043. }
  2044. /* after DO, go DO_DONE... or DO_MORE */
  2045. else if(data->conn->bits.do_more) {
  2046. /* we are supposed to do more, but we need to sit down, relax and wait
  2047. a little while first */
  2048. multistate(data, MSTATE_DOING_MORE);
  2049. rc = CURLM_CALL_MULTI_PERFORM;
  2050. }
  2051. else {
  2052. /* we are done with the DO, now DID */
  2053. multistate(data, MSTATE_DID);
  2054. rc = CURLM_CALL_MULTI_PERFORM;
  2055. }
  2056. }
  2057. else if((CURLE_SEND_ERROR == result) &&
  2058. data->conn->bits.reuse) {
  2059. /*
  2060. * In this situation, a connection that we were trying to use may have
  2061. * unexpectedly died. If possible, send the connection back to the
  2062. * CONNECT phase so we can try again.
  2063. */
  2064. char *newurl = NULL;
  2065. followtype follow = FOLLOW_NONE;
  2066. CURLcode drc;
  2067. drc = Curl_retry_request(data, &newurl);
  2068. if(drc) {
  2069. /* a failure here pretty much implies an out of memory */
  2070. result = drc;
  2071. *stream_errorp = TRUE;
  2072. }
  2073. multi_posttransfer(data);
  2074. drc = multi_done(data, result, FALSE);
  2075. /* When set to retry the connection, we must go back to the CONNECT
  2076. * state */
  2077. if(newurl) {
  2078. if(!drc || (drc == CURLE_SEND_ERROR)) {
  2079. follow = FOLLOW_RETRY;
  2080. drc = multi_follow(data, newurl, follow);
  2081. if(!drc) {
  2082. multistate(data, MSTATE_SETUP);
  2083. rc = CURLM_CALL_MULTI_PERFORM;
  2084. result = CURLE_OK;
  2085. }
  2086. else {
  2087. /* Follow failed */
  2088. result = drc;
  2089. }
  2090. }
  2091. else {
  2092. /* done did not return OK or SEND_ERROR */
  2093. result = drc;
  2094. }
  2095. }
  2096. else {
  2097. /* Have error handler disconnect conn if we cannot retry */
  2098. *stream_errorp = TRUE;
  2099. }
  2100. free(newurl);
  2101. }
  2102. else {
  2103. /* failure detected */
  2104. multi_posttransfer(data);
  2105. if(data->conn)
  2106. multi_done(data, result, FALSE);
  2107. *stream_errorp = TRUE;
  2108. }
  2109. }
  2110. end:
  2111. *resultp = result;
  2112. return rc;
  2113. }
  2114. static CURLMcode state_ratelimiting(struct Curl_easy *data,
  2115. struct curltime *nowp,
  2116. CURLcode *resultp)
  2117. {
  2118. CURLcode result = CURLE_OK;
  2119. CURLMcode rc = CURLM_OK;
  2120. DEBUGASSERT(data->conn);
  2121. /* if both rates are within spec, resume transfer */
  2122. if(Curl_pgrsUpdate(data))
  2123. result = CURLE_ABORTED_BY_CALLBACK;
  2124. else
  2125. result = Curl_speedcheck(data, *nowp);
  2126. if(result) {
  2127. if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
  2128. result != CURLE_HTTP2_STREAM)
  2129. streamclose(data->conn, "Transfer returned error");
  2130. multi_posttransfer(data);
  2131. multi_done(data, result, TRUE);
  2132. }
  2133. else {
  2134. timediff_t recv_timeout_ms = 0;
  2135. timediff_t send_timeout_ms = 0;
  2136. if(data->set.max_send_speed)
  2137. send_timeout_ms =
  2138. Curl_pgrsLimitWaitTime(&data->progress.ul,
  2139. data->set.max_send_speed,
  2140. *nowp);
  2141. if(data->set.max_recv_speed)
  2142. recv_timeout_ms =
  2143. Curl_pgrsLimitWaitTime(&data->progress.dl,
  2144. data->set.max_recv_speed,
  2145. *nowp);
  2146. if(!send_timeout_ms && !recv_timeout_ms) {
  2147. multistate(data, MSTATE_PERFORMING);
  2148. Curl_ratelimit(data, *nowp);
  2149. /* start performing again right away */
  2150. rc = CURLM_CALL_MULTI_PERFORM;
  2151. }
  2152. else if(send_timeout_ms >= recv_timeout_ms)
  2153. Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
  2154. else
  2155. Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
  2156. }
  2157. *resultp = result;
  2158. return rc;
  2159. }
  2160. static CURLMcode state_resolving(struct Curl_multi *multi,
  2161. struct Curl_easy *data,
  2162. bool *stream_errorp,
  2163. CURLcode *resultp)
  2164. {
  2165. struct Curl_dns_entry *dns = NULL;
  2166. struct connectdata *conn = data->conn;
  2167. const char *hostname;
  2168. CURLcode result = CURLE_OK;
  2169. CURLMcode rc = CURLM_OK;
  2170. DEBUGASSERT(conn);
  2171. #ifndef CURL_DISABLE_PROXY
  2172. if(conn->bits.httpproxy)
  2173. hostname = conn->http_proxy.host.name;
  2174. else
  2175. #endif
  2176. if(conn->bits.conn_to_host)
  2177. hostname = conn->conn_to_host.name;
  2178. else
  2179. hostname = conn->host.name;
  2180. /* check if we have the name resolved by now */
  2181. dns = Curl_fetch_addr(data, hostname, conn->primary.remote_port);
  2182. if(dns) {
  2183. #ifdef CURLRES_ASYNCH
  2184. data->state.async.dns = dns;
  2185. data->state.async.done = TRUE;
  2186. #endif
  2187. result = CURLE_OK;
  2188. infof(data, "Hostname '%s' was found in DNS cache", hostname);
  2189. }
  2190. if(!dns)
  2191. result = Curl_resolv_check(data, &dns);
  2192. /* Update sockets here, because the socket(s) may have been closed and the
  2193. application thus needs to be told, even if it is likely that the same
  2194. socket(s) will again be used further down. If the name has not yet been
  2195. resolved, it is likely that new sockets have been opened in an attempt to
  2196. contact another resolver. */
  2197. rc = singlesocket(multi, data);
  2198. if(rc)
  2199. return rc;
  2200. if(dns) {
  2201. bool connected;
  2202. /* Perform the next step in the connection phase, and then move on to the
  2203. WAITCONNECT state */
  2204. result = Curl_once_resolved(data, &connected);
  2205. if(result)
  2206. /* if Curl_once_resolved() returns failure, the connection struct is
  2207. already freed and gone */
  2208. data->conn = NULL; /* no more connection */
  2209. else {
  2210. /* call again please so that we get the next socket setup */
  2211. rc = CURLM_CALL_MULTI_PERFORM;
  2212. if(connected)
  2213. multistate(data, MSTATE_PROTOCONNECT);
  2214. else {
  2215. multistate(data, MSTATE_CONNECTING);
  2216. }
  2217. }
  2218. }
  2219. if(result)
  2220. /* failure detected */
  2221. *stream_errorp = TRUE;
  2222. *resultp = result;
  2223. return rc;
  2224. }
  2225. static CURLMcode state_connect(struct Curl_multi *multi,
  2226. struct Curl_easy *data,
  2227. struct curltime *nowp,
  2228. CURLcode *resultp)
  2229. {
  2230. /* Connect. We want to get a connection identifier filled in. This state can
  2231. be entered from SETUP and from PENDING. */
  2232. bool connected;
  2233. bool async;
  2234. CURLMcode rc = CURLM_OK;
  2235. CURLcode result = Curl_connect(data, &async, &connected);
  2236. if(CURLE_NO_CONNECTION_AVAILABLE == result) {
  2237. /* There was no connection available. We will go to the pending state and
  2238. wait for an available connection. */
  2239. multistate(data, MSTATE_PENDING);
  2240. /* unlink from process list */
  2241. Curl_node_remove(&data->multi_queue);
  2242. /* add handle to pending list */
  2243. Curl_llist_append(&multi->pending, data, &data->multi_queue);
  2244. *resultp = CURLE_OK;
  2245. return rc;
  2246. }
  2247. else
  2248. process_pending_handles(data->multi);
  2249. if(!result) {
  2250. *nowp = Curl_pgrsTime(data, TIMER_POSTQUEUE);
  2251. if(async)
  2252. /* We are now waiting for an asynchronous name lookup */
  2253. multistate(data, MSTATE_RESOLVING);
  2254. else {
  2255. /* after the connect has been sent off, go WAITCONNECT unless the
  2256. protocol connect is already done and we can go directly to WAITDO or
  2257. DO! */
  2258. rc = CURLM_CALL_MULTI_PERFORM;
  2259. if(connected) {
  2260. if(!data->conn->bits.reuse &&
  2261. Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) {
  2262. /* new connection, can multiplex, wake pending handles */
  2263. process_pending_handles(data->multi);
  2264. }
  2265. multistate(data, MSTATE_PROTOCONNECT);
  2266. }
  2267. else {
  2268. multistate(data, MSTATE_CONNECTING);
  2269. }
  2270. }
  2271. }
  2272. *resultp = result;
  2273. return rc;
  2274. }
  2275. static CURLMcode multi_runsingle(struct Curl_multi *multi,
  2276. struct curltime *nowp,
  2277. struct Curl_easy *data)
  2278. {
  2279. struct Curl_message *msg = NULL;
  2280. bool connected;
  2281. bool protocol_connected = FALSE;
  2282. bool dophase_done = FALSE;
  2283. CURLMcode rc;
  2284. CURLcode result = CURLE_OK;
  2285. int control;
  2286. if(!GOOD_EASY_HANDLE(data))
  2287. return CURLM_BAD_EASY_HANDLE;
  2288. if(multi->dead) {
  2289. /* a multi-level callback returned error before, meaning every individual
  2290. transfer now has failed */
  2291. result = CURLE_ABORTED_BY_CALLBACK;
  2292. multi_posttransfer(data);
  2293. multi_done(data, result, FALSE);
  2294. multistate(data, MSTATE_COMPLETED);
  2295. }
  2296. multi_warn_debug(multi, data);
  2297. do {
  2298. /* A "stream" here is a logical stream if the protocol can handle that
  2299. (HTTP/2), or the full connection for older protocols */
  2300. bool stream_error = FALSE;
  2301. rc = CURLM_OK;
  2302. if(multi_ischanged(multi, TRUE)) {
  2303. DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue"));
  2304. process_pending_handles(multi); /* multiplexed */
  2305. }
  2306. if(data->mstate > MSTATE_CONNECT &&
  2307. data->mstate < MSTATE_COMPLETED) {
  2308. /* Make sure we set the connection's current owner */
  2309. DEBUGASSERT(data->conn);
  2310. if(!data->conn)
  2311. return CURLM_INTERNAL_ERROR;
  2312. }
  2313. /* Wait for the connect state as only then is the start time stored, but
  2314. we must not check already completed handles */
  2315. if((data->mstate >= MSTATE_CONNECT) && (data->mstate < MSTATE_COMPLETED) &&
  2316. multi_handle_timeout(data, nowp, &stream_error, &result))
  2317. /* Skip the statemachine and go directly to error handling section. */
  2318. goto statemachine_end;
  2319. switch(data->mstate) {
  2320. case MSTATE_INIT:
  2321. /* Transitional state. init this transfer. A handle never comes back to
  2322. this state. */
  2323. result = Curl_pretransfer(data);
  2324. if(result)
  2325. break;
  2326. /* after init, go SETUP */
  2327. multistate(data, MSTATE_SETUP);
  2328. (void)Curl_pgrsTime(data, TIMER_STARTOP);
  2329. FALLTHROUGH();
  2330. case MSTATE_SETUP:
  2331. /* Transitional state. Setup things for a new transfer. The handle
  2332. can come back to this state on a redirect. */
  2333. *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE);
  2334. if(data->set.timeout)
  2335. Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT);
  2336. if(data->set.connecttimeout)
  2337. /* Since a connection might go to pending and back to CONNECT several
  2338. times before it actually takes off, we need to set the timeout once
  2339. in SETUP before we enter CONNECT the first time. */
  2340. Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT);
  2341. multistate(data, MSTATE_CONNECT);
  2342. FALLTHROUGH();
  2343. case MSTATE_CONNECT:
  2344. rc = state_connect(multi, data, nowp, &result);
  2345. break;
  2346. case MSTATE_RESOLVING:
  2347. /* awaiting an asynch name resolve to complete */
  2348. rc = state_resolving(multi, data, &stream_error, &result);
  2349. break;
  2350. #ifndef CURL_DISABLE_HTTP
  2351. case MSTATE_TUNNELING:
  2352. /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
  2353. DEBUGASSERT(data->conn);
  2354. result = Curl_http_connect(data, &protocol_connected);
  2355. if(!result) {
  2356. rc = CURLM_CALL_MULTI_PERFORM;
  2357. /* initiate protocol connect phase */
  2358. multistate(data, MSTATE_PROTOCONNECT);
  2359. }
  2360. else
  2361. stream_error = TRUE;
  2362. break;
  2363. #endif
  2364. case MSTATE_CONNECTING:
  2365. /* awaiting a completion of an asynch TCP connect */
  2366. DEBUGASSERT(data->conn);
  2367. result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected);
  2368. if(connected && !result) {
  2369. if(!data->conn->bits.reuse &&
  2370. Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) {
  2371. /* new connection, can multiplex, wake pending handles */
  2372. process_pending_handles(data->multi);
  2373. }
  2374. rc = CURLM_CALL_MULTI_PERFORM;
  2375. multistate(data, MSTATE_PROTOCONNECT);
  2376. }
  2377. else if(result) {
  2378. /* failure detected */
  2379. multi_posttransfer(data);
  2380. multi_done(data, result, TRUE);
  2381. stream_error = TRUE;
  2382. break;
  2383. }
  2384. break;
  2385. case MSTATE_PROTOCONNECT:
  2386. if(!result && data->conn->bits.reuse) {
  2387. /* ftp seems to hang when protoconnect on reused connection since we
  2388. * handle PROTOCONNECT in general inside the filers, it seems wrong to
  2389. * restart this on a reused connection.
  2390. */
  2391. multistate(data, MSTATE_DO);
  2392. rc = CURLM_CALL_MULTI_PERFORM;
  2393. break;
  2394. }
  2395. if(!result)
  2396. result = protocol_connect(data, &protocol_connected);
  2397. if(!result && !protocol_connected) {
  2398. /* switch to waiting state */
  2399. multistate(data, MSTATE_PROTOCONNECTING);
  2400. rc = CURLM_CALL_MULTI_PERFORM;
  2401. }
  2402. else if(!result) {
  2403. /* protocol connect has completed, go WAITDO or DO */
  2404. multistate(data, MSTATE_DO);
  2405. rc = CURLM_CALL_MULTI_PERFORM;
  2406. }
  2407. else {
  2408. /* failure detected */
  2409. multi_posttransfer(data);
  2410. multi_done(data, result, TRUE);
  2411. stream_error = TRUE;
  2412. }
  2413. break;
  2414. case MSTATE_PROTOCONNECTING:
  2415. /* protocol-specific connect phase */
  2416. result = protocol_connecting(data, &protocol_connected);
  2417. if(!result && protocol_connected) {
  2418. /* after the connect has completed, go WAITDO or DO */
  2419. multistate(data, MSTATE_DO);
  2420. rc = CURLM_CALL_MULTI_PERFORM;
  2421. }
  2422. else if(result) {
  2423. /* failure detected */
  2424. multi_posttransfer(data);
  2425. multi_done(data, result, TRUE);
  2426. stream_error = TRUE;
  2427. }
  2428. break;
  2429. case MSTATE_DO:
  2430. rc = state_do(data, &stream_error, &result);
  2431. break;
  2432. case MSTATE_DOING:
  2433. /* we continue DOING until the DO phase is complete */
  2434. DEBUGASSERT(data->conn);
  2435. result = protocol_doing(data, &dophase_done);
  2436. if(!result) {
  2437. if(dophase_done) {
  2438. /* after DO, go DO_DONE or DO_MORE */
  2439. multistate(data, data->conn->bits.do_more ?
  2440. MSTATE_DOING_MORE : MSTATE_DID);
  2441. rc = CURLM_CALL_MULTI_PERFORM;
  2442. } /* dophase_done */
  2443. }
  2444. else {
  2445. /* failure detected */
  2446. multi_posttransfer(data);
  2447. multi_done(data, result, FALSE);
  2448. stream_error = TRUE;
  2449. }
  2450. break;
  2451. case MSTATE_DOING_MORE:
  2452. /*
  2453. * When we are connected, DOING MORE and then go DID
  2454. */
  2455. DEBUGASSERT(data->conn);
  2456. result = multi_do_more(data, &control);
  2457. if(!result) {
  2458. if(control) {
  2459. /* if positive, advance to DO_DONE
  2460. if negative, go back to DOING */
  2461. multistate(data, control == 1 ?
  2462. MSTATE_DID : MSTATE_DOING);
  2463. rc = CURLM_CALL_MULTI_PERFORM;
  2464. }
  2465. /* else
  2466. stay in DO_MORE */
  2467. }
  2468. else {
  2469. /* failure detected */
  2470. multi_posttransfer(data);
  2471. multi_done(data, result, FALSE);
  2472. stream_error = TRUE;
  2473. }
  2474. break;
  2475. case MSTATE_DID:
  2476. DEBUGASSERT(data->conn);
  2477. if(data->conn->bits.multiplex)
  2478. /* Check if we can move pending requests to send pipe */
  2479. process_pending_handles(multi); /* multiplexed */
  2480. /* Only perform the transfer if there is a good socket to work with.
  2481. Having both BAD is a signal to skip immediately to DONE */
  2482. if((data->conn->sockfd != CURL_SOCKET_BAD) ||
  2483. (data->conn->writesockfd != CURL_SOCKET_BAD))
  2484. multistate(data, MSTATE_PERFORMING);
  2485. else {
  2486. #ifndef CURL_DISABLE_FTP
  2487. if(data->state.wildcardmatch &&
  2488. ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
  2489. data->wildcard->state = CURLWC_DONE;
  2490. }
  2491. #endif
  2492. multistate(data, MSTATE_DONE);
  2493. }
  2494. rc = CURLM_CALL_MULTI_PERFORM;
  2495. break;
  2496. case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */
  2497. rc = state_ratelimiting(data, nowp, &result);
  2498. break;
  2499. case MSTATE_PERFORMING:
  2500. rc = state_performing(data, nowp, &stream_error, &result);
  2501. break;
  2502. case MSTATE_DONE:
  2503. /* this state is highly transient, so run another loop after this */
  2504. rc = CURLM_CALL_MULTI_PERFORM;
  2505. if(data->conn) {
  2506. CURLcode res;
  2507. /* post-transfer command */
  2508. res = multi_done(data, result, FALSE);
  2509. /* allow a previously set error code take precedence */
  2510. if(!result)
  2511. result = res;
  2512. }
  2513. #ifndef CURL_DISABLE_FTP
  2514. if(data->state.wildcardmatch) {
  2515. if(data->wildcard->state != CURLWC_DONE) {
  2516. /* if a wildcard is set and we are not ending -> lets start again
  2517. with MSTATE_INIT */
  2518. multistate(data, MSTATE_INIT);
  2519. break;
  2520. }
  2521. }
  2522. #endif
  2523. /* after we have DONE what we are supposed to do, go COMPLETED, and
  2524. it does not matter what the multi_done() returned! */
  2525. multistate(data, MSTATE_COMPLETED);
  2526. break;
  2527. case MSTATE_COMPLETED:
  2528. break;
  2529. case MSTATE_PENDING:
  2530. case MSTATE_MSGSENT:
  2531. /* handles in these states should NOT be in this list */
  2532. DEBUGASSERT(0);
  2533. break;
  2534. default:
  2535. return CURLM_INTERNAL_ERROR;
  2536. }
  2537. if(data->mstate >= MSTATE_CONNECT &&
  2538. data->mstate < MSTATE_DO &&
  2539. rc != CURLM_CALL_MULTI_PERFORM &&
  2540. !multi_ischanged(multi, FALSE)) {
  2541. /* We now handle stream timeouts if and only if this will be the last
  2542. * loop iteration. We only check this on the last iteration to ensure
  2543. * that if we know we have additional work to do immediately
  2544. * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before
  2545. * declaring the connection timed out as we may almost have a completed
  2546. * connection. */
  2547. multi_handle_timeout(data, nowp, &stream_error, &result);
  2548. }
  2549. statemachine_end:
  2550. if(data->mstate < MSTATE_COMPLETED) {
  2551. if(result) {
  2552. /*
  2553. * If an error was returned, and we are not in completed state now,
  2554. * then we go to completed and consider this transfer aborted.
  2555. */
  2556. /* NOTE: no attempt to disconnect connections must be made
  2557. in the case blocks above - cleanup happens only here */
  2558. /* Check if we can move pending requests to send pipe */
  2559. process_pending_handles(multi); /* connection */
  2560. if(data->conn) {
  2561. if(stream_error) {
  2562. /* Do not attempt to send data over a connection that timed out */
  2563. bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
  2564. struct connectdata *conn = data->conn;
  2565. /* This is where we make sure that the conn pointer is reset.
  2566. We do not have to do this in every case block above where a
  2567. failure is detected */
  2568. Curl_detach_connection(data);
  2569. Curl_cpool_disconnect(data, conn, dead_connection);
  2570. }
  2571. }
  2572. else if(data->mstate == MSTATE_CONNECT) {
  2573. /* Curl_connect() failed */
  2574. multi_posttransfer(data);
  2575. Curl_pgrsUpdate_nometer(data);
  2576. }
  2577. multistate(data, MSTATE_COMPLETED);
  2578. rc = CURLM_CALL_MULTI_PERFORM;
  2579. }
  2580. /* if there is still a connection to use, call the progress function */
  2581. else if(data->conn && Curl_pgrsUpdate(data)) {
  2582. /* aborted due to progress callback return code must close the
  2583. connection */
  2584. result = CURLE_ABORTED_BY_CALLBACK;
  2585. streamclose(data->conn, "Aborted by callback");
  2586. /* if not yet in DONE state, go there, otherwise COMPLETED */
  2587. multistate(data, (data->mstate < MSTATE_DONE) ?
  2588. MSTATE_DONE : MSTATE_COMPLETED);
  2589. rc = CURLM_CALL_MULTI_PERFORM;
  2590. }
  2591. }
  2592. if(MSTATE_COMPLETED == data->mstate) {
  2593. if(data->set.fmultidone) {
  2594. /* signal via callback instead */
  2595. data->set.fmultidone(data, result);
  2596. }
  2597. else {
  2598. /* now fill in the Curl_message with this info */
  2599. msg = &data->msg;
  2600. msg->extmsg.msg = CURLMSG_DONE;
  2601. msg->extmsg.easy_handle = data;
  2602. msg->extmsg.data.result = result;
  2603. multi_addmsg(multi, msg);
  2604. DEBUGASSERT(!data->conn);
  2605. }
  2606. multistate(data, MSTATE_MSGSENT);
  2607. /* unlink from the process list */
  2608. Curl_node_remove(&data->multi_queue);
  2609. /* add this handle msgsent list */
  2610. Curl_llist_append(&multi->msgsent, data, &data->multi_queue);
  2611. return CURLM_OK;
  2612. }
  2613. } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
  2614. data->result = result;
  2615. return rc;
  2616. }
  2617. CURLMcode curl_multi_perform(CURLM *m, int *running_handles)
  2618. {
  2619. CURLMcode returncode = CURLM_OK;
  2620. struct Curl_tree *t = NULL;
  2621. struct curltime now = Curl_now();
  2622. struct Curl_llist_node *e;
  2623. struct Curl_llist_node *n = NULL;
  2624. struct Curl_multi *multi = m;
  2625. SIGPIPE_VARIABLE(pipe_st);
  2626. if(!GOOD_MULTI_HANDLE(multi))
  2627. return CURLM_BAD_HANDLE;
  2628. if(multi->in_callback)
  2629. return CURLM_RECURSIVE_API_CALL;
  2630. sigpipe_init(&pipe_st);
  2631. for(e = Curl_llist_head(&multi->process); e; e = n) {
  2632. struct Curl_easy *data = Curl_node_elem(e);
  2633. CURLMcode result;
  2634. /* Do the loop and only alter the signal ignore state if the next handle
  2635. has a different NO_SIGNAL state than the previous */
  2636. /* the current node might be unlinked in multi_runsingle(), get the next
  2637. pointer now */
  2638. n = Curl_node_next(e);
  2639. if(data != multi->cpool.idata) {
  2640. /* connection pool handle is processed below */
  2641. sigpipe_apply(data, &pipe_st);
  2642. result = multi_runsingle(multi, &now, data);
  2643. if(result)
  2644. returncode = result;
  2645. }
  2646. }
  2647. sigpipe_apply(multi->cpool.idata, &pipe_st);
  2648. Curl_cpool_multi_perform(multi);
  2649. sigpipe_restore(&pipe_st);
  2650. /*
  2651. * Simply remove all expired timers from the splay since handles are dealt
  2652. * with unconditionally by this function and curl_multi_timeout() requires
  2653. * that already passed/handled expire times are removed from the splay.
  2654. *
  2655. * It is important that the 'now' value is set at the entry of this function
  2656. * and not for the current time as it may have ticked a little while since
  2657. * then and then we risk this loop to remove timers that actually have not
  2658. * been handled!
  2659. */
  2660. do {
  2661. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  2662. if(t) {
  2663. /* the removed may have another timeout in queue */
  2664. struct Curl_easy *data = Curl_splayget(t);
  2665. if(data->mstate == MSTATE_PENDING) {
  2666. bool stream_unused;
  2667. CURLcode result_unused;
  2668. if(multi_handle_timeout(data, &now, &stream_unused, &result_unused)) {
  2669. infof(data, "PENDING handle timeout");
  2670. move_pending_to_connect(multi, data);
  2671. }
  2672. }
  2673. (void)add_next_timeout(now, multi, Curl_splayget(t));
  2674. }
  2675. } while(t);
  2676. if(running_handles)
  2677. *running_handles = (int)multi->num_alive;
  2678. if(CURLM_OK >= returncode)
  2679. returncode = Curl_update_timer(multi);
  2680. return returncode;
  2681. }
  2682. /* unlink_all_msgsent_handles() moves all nodes back from the msgsent list to
  2683. the process list */
  2684. static void unlink_all_msgsent_handles(struct Curl_multi *multi)
  2685. {
  2686. struct Curl_llist_node *e;
  2687. for(e = Curl_llist_head(&multi->msgsent); e; e = Curl_node_next(e)) {
  2688. struct Curl_easy *data = Curl_node_elem(e);
  2689. if(data) {
  2690. DEBUGASSERT(data->mstate == MSTATE_MSGSENT);
  2691. Curl_node_remove(&data->multi_queue);
  2692. /* put it into the process list */
  2693. Curl_llist_append(&multi->process, data, &data->multi_queue);
  2694. }
  2695. }
  2696. }
  2697. CURLMcode curl_multi_cleanup(CURLM *m)
  2698. {
  2699. struct Curl_multi *multi = m;
  2700. if(GOOD_MULTI_HANDLE(multi)) {
  2701. struct Curl_llist_node *e;
  2702. struct Curl_llist_node *n;
  2703. if(multi->in_callback)
  2704. return CURLM_RECURSIVE_API_CALL;
  2705. /* move the pending and msgsent entries back to process
  2706. so that there is just one list to iterate over */
  2707. unlink_all_msgsent_handles(multi);
  2708. process_pending_handles(multi);
  2709. /* First remove all remaining easy handles */
  2710. for(e = Curl_llist_head(&multi->process); e; e = n) {
  2711. struct Curl_easy *data = Curl_node_elem(e);
  2712. if(!GOOD_EASY_HANDLE(data))
  2713. return CURLM_BAD_HANDLE;
  2714. n = Curl_node_next(e);
  2715. if(!data->state.done && data->conn)
  2716. /* if DONE was never called for this handle */
  2717. (void)multi_done(data, CURLE_OK, TRUE);
  2718. if(data->dns.hostcachetype == HCACHE_MULTI) {
  2719. /* clear out the usage of the shared DNS cache */
  2720. Curl_hostcache_clean(data, data->dns.hostcache);
  2721. data->dns.hostcache = NULL;
  2722. data->dns.hostcachetype = HCACHE_NONE;
  2723. }
  2724. data->multi = NULL; /* clear the association */
  2725. #ifdef USE_LIBPSL
  2726. if(data->psl == &multi->psl)
  2727. data->psl = NULL;
  2728. #endif
  2729. }
  2730. Curl_cpool_destroy(&multi->cpool);
  2731. multi->magic = 0; /* not good anymore */
  2732. sockhash_destroy(&multi->sockhash);
  2733. Curl_hash_destroy(&multi->proto_hash);
  2734. Curl_hash_destroy(&multi->hostcache);
  2735. Curl_psl_destroy(&multi->psl);
  2736. #ifdef USE_WINSOCK
  2737. WSACloseEvent(multi->wsa_event);
  2738. #else
  2739. #ifdef ENABLE_WAKEUP
  2740. wakeup_close(multi->wakeup_pair[0]);
  2741. #ifndef USE_EVENTFD
  2742. wakeup_close(multi->wakeup_pair[1]);
  2743. #endif
  2744. #endif
  2745. #endif
  2746. multi_xfer_bufs_free(multi);
  2747. free(multi);
  2748. return CURLM_OK;
  2749. }
  2750. return CURLM_BAD_HANDLE;
  2751. }
  2752. /*
  2753. * curl_multi_info_read()
  2754. *
  2755. * This function is the primary way for a multi/multi_socket application to
  2756. * figure out if a transfer has ended. We MUST make this function as fast as
  2757. * possible as it will be polled frequently and we MUST NOT scan any lists in
  2758. * here to figure out things. We must scale fine to thousands of handles and
  2759. * beyond. The current design is fully O(1).
  2760. */
  2761. CURLMsg *curl_multi_info_read(CURLM *m, int *msgs_in_queue)
  2762. {
  2763. struct Curl_message *msg;
  2764. struct Curl_multi *multi = m;
  2765. *msgs_in_queue = 0; /* default to none */
  2766. if(GOOD_MULTI_HANDLE(multi) &&
  2767. !multi->in_callback &&
  2768. Curl_llist_count(&multi->msglist)) {
  2769. /* there is one or more messages in the list */
  2770. struct Curl_llist_node *e;
  2771. /* extract the head of the list to return */
  2772. e = Curl_llist_head(&multi->msglist);
  2773. msg = Curl_node_elem(e);
  2774. /* remove the extracted entry */
  2775. Curl_node_remove(e);
  2776. *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
  2777. return &msg->extmsg;
  2778. }
  2779. return NULL;
  2780. }
  2781. /*
  2782. * singlesocket() checks what sockets we deal with and their "action state"
  2783. * and if we have a different state in any of those sockets from last time we
  2784. * call the callback accordingly.
  2785. */
  2786. static CURLMcode singlesocket(struct Curl_multi *multi,
  2787. struct Curl_easy *data)
  2788. {
  2789. struct easy_pollset cur_poll;
  2790. CURLMcode mresult;
  2791. /* Fill in the 'current' struct with the state as it is now: what sockets to
  2792. supervise and for what actions */
  2793. multi_getsock(data, &cur_poll);
  2794. mresult = Curl_multi_pollset_ev(multi, data, &cur_poll, &data->last_poll);
  2795. if(!mresult) /* Remember for next time */
  2796. memcpy(&data->last_poll, &cur_poll, sizeof(cur_poll));
  2797. return mresult;
  2798. }
  2799. CURLMcode Curl_multi_pollset_ev(struct Curl_multi *multi,
  2800. struct Curl_easy *data,
  2801. struct easy_pollset *ps,
  2802. struct easy_pollset *last_ps)
  2803. {
  2804. unsigned int i;
  2805. struct Curl_sh_entry *entry;
  2806. curl_socket_t s;
  2807. int rc;
  2808. /* We have 0 .. N sockets already and we get to know about the 0 .. M
  2809. sockets we should have from now on. Detect the differences, remove no
  2810. longer supervised ones and add new ones */
  2811. /* walk over the sockets we got right now */
  2812. for(i = 0; i < ps->num; i++) {
  2813. unsigned char cur_action = ps->actions[i];
  2814. unsigned char last_action = 0;
  2815. int comboaction;
  2816. s = ps->sockets[i];
  2817. /* get it from the hash */
  2818. entry = sh_getentry(&multi->sockhash, s);
  2819. if(entry) {
  2820. /* check if new for this transfer */
  2821. unsigned int j;
  2822. for(j = 0; j < last_ps->num; j++) {
  2823. if(s == last_ps->sockets[j]) {
  2824. last_action = last_ps->actions[j];
  2825. break;
  2826. }
  2827. }
  2828. }
  2829. else {
  2830. /* this is a socket we did not have before, add it to the hash! */
  2831. entry = sh_addentry(&multi->sockhash, s);
  2832. if(!entry)
  2833. /* fatal */
  2834. return CURLM_OUT_OF_MEMORY;
  2835. }
  2836. if(last_action && (last_action != cur_action)) {
  2837. /* Socket was used already, but different action now */
  2838. if(last_action & CURL_POLL_IN) {
  2839. DEBUGASSERT(entry->readers);
  2840. entry->readers--;
  2841. }
  2842. if(last_action & CURL_POLL_OUT) {
  2843. DEBUGASSERT(entry->writers);
  2844. entry->writers--;
  2845. }
  2846. if(cur_action & CURL_POLL_IN) {
  2847. entry->readers++;
  2848. }
  2849. if(cur_action & CURL_POLL_OUT)
  2850. entry->writers++;
  2851. }
  2852. else if(!last_action &&
  2853. !Curl_hash_pick(&entry->transfers, (char *)&data, /* hash key */
  2854. sizeof(struct Curl_easy *))) {
  2855. DEBUGASSERT(entry->users < 100000); /* detect weird values */
  2856. /* a new transfer using this socket */
  2857. entry->users++;
  2858. if(cur_action & CURL_POLL_IN)
  2859. entry->readers++;
  2860. if(cur_action & CURL_POLL_OUT)
  2861. entry->writers++;
  2862. /* add 'data' to the transfer hash on this socket! */
  2863. if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */
  2864. sizeof(struct Curl_easy *), data)) {
  2865. Curl_hash_destroy(&entry->transfers);
  2866. return CURLM_OUT_OF_MEMORY;
  2867. }
  2868. }
  2869. comboaction = (entry->writers ? CURL_POLL_OUT : 0) |
  2870. (entry->readers ? CURL_POLL_IN : 0);
  2871. /* socket existed before and has the same action set as before */
  2872. if(last_action && ((int)entry->action == comboaction))
  2873. /* same, continue */
  2874. continue;
  2875. if(multi->socket_cb) {
  2876. set_in_callback(multi, TRUE);
  2877. rc = multi->socket_cb(data, s, comboaction, multi->socket_userp,
  2878. entry->socketp);
  2879. set_in_callback(multi, FALSE);
  2880. if(rc == -1) {
  2881. multi->dead = TRUE;
  2882. return CURLM_ABORTED_BY_CALLBACK;
  2883. }
  2884. }
  2885. /* store the current action state */
  2886. entry->action = (unsigned int)comboaction;
  2887. }
  2888. /* Check for last_poll.sockets that no longer appear in ps->sockets.
  2889. * Need to remove the easy handle from the multi->sockhash->transfers and
  2890. * remove multi->sockhash entry when this was the last transfer */
  2891. for(i = 0; i < last_ps->num; i++) {
  2892. unsigned int j;
  2893. bool stillused = FALSE;
  2894. s = last_ps->sockets[i];
  2895. for(j = 0; j < ps->num; j++) {
  2896. if(s == ps->sockets[j]) {
  2897. /* this is still supervised */
  2898. stillused = TRUE;
  2899. break;
  2900. }
  2901. }
  2902. if(stillused)
  2903. continue;
  2904. entry = sh_getentry(&multi->sockhash, s);
  2905. /* if this is NULL here, the socket has been closed and notified so
  2906. already by Curl_multi_closed() */
  2907. if(entry) {
  2908. unsigned char oldactions = last_ps->actions[i];
  2909. /* this socket has been removed. Decrease user count */
  2910. DEBUGASSERT(entry->users);
  2911. entry->users--;
  2912. if(oldactions & CURL_POLL_OUT)
  2913. entry->writers--;
  2914. if(oldactions & CURL_POLL_IN)
  2915. entry->readers--;
  2916. if(!entry->users) {
  2917. bool dead = FALSE;
  2918. if(multi->socket_cb) {
  2919. set_in_callback(multi, TRUE);
  2920. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2921. multi->socket_userp, entry->socketp);
  2922. set_in_callback(multi, FALSE);
  2923. if(rc == -1)
  2924. dead = TRUE;
  2925. }
  2926. sh_delentry(entry, &multi->sockhash, s);
  2927. if(dead) {
  2928. multi->dead = TRUE;
  2929. return CURLM_ABORTED_BY_CALLBACK;
  2930. }
  2931. }
  2932. else {
  2933. /* still users, but remove this handle as a user of this socket */
  2934. if(Curl_hash_delete(&entry->transfers, (char *)&data,
  2935. sizeof(struct Curl_easy *))) {
  2936. DEBUGASSERT(NULL);
  2937. }
  2938. }
  2939. }
  2940. } /* for loop over num */
  2941. return CURLM_OK;
  2942. }
  2943. CURLcode Curl_updatesocket(struct Curl_easy *data)
  2944. {
  2945. if(singlesocket(data->multi, data))
  2946. return CURLE_ABORTED_BY_CALLBACK;
  2947. return CURLE_OK;
  2948. }
  2949. /*
  2950. * Curl_multi_closed()
  2951. *
  2952. * Used by the connect code to tell the multi_socket code that one of the
  2953. * sockets we were using is about to be closed. This function will then
  2954. * remove it from the sockethash for this handle to make the multi_socket API
  2955. * behave properly, especially for the case when libcurl will create another
  2956. * socket again and it gets the same file descriptor number.
  2957. */
  2958. void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
  2959. {
  2960. if(data) {
  2961. /* if there is still an easy handle associated with this connection */
  2962. struct Curl_multi *multi = data->multi;
  2963. DEBUGF(infof(data, "Curl_multi_closed, fd=%" FMT_SOCKET_T
  2964. " multi is %p", s, (void *)multi));
  2965. if(multi) {
  2966. /* this is set if this connection is part of a handle that is added to
  2967. a multi handle, and only then this is necessary */
  2968. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  2969. DEBUGF(infof(data, "Curl_multi_closed, fd=%" FMT_SOCKET_T
  2970. " entry is %p", s, (void *)entry));
  2971. if(entry) {
  2972. int rc = 0;
  2973. if(multi->socket_cb) {
  2974. set_in_callback(multi, TRUE);
  2975. rc = multi->socket_cb(data, s, CURL_POLL_REMOVE,
  2976. multi->socket_userp, entry->socketp);
  2977. set_in_callback(multi, FALSE);
  2978. }
  2979. /* now remove it from the socket hash */
  2980. sh_delentry(entry, &multi->sockhash, s);
  2981. if(rc == -1)
  2982. /* This just marks the multi handle as "dead" without returning an
  2983. error code primarily because this function is used from many
  2984. places where propagating an error back is tricky. */
  2985. multi->dead = TRUE;
  2986. }
  2987. }
  2988. }
  2989. }
  2990. /*
  2991. * add_next_timeout()
  2992. *
  2993. * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
  2994. * when it has just been removed from the splay tree because the timeout has
  2995. * expired. This function is then to advance in the list to pick the next
  2996. * timeout to use (skip the already expired ones) and add this node back to
  2997. * the splay tree again.
  2998. *
  2999. * The splay tree only has each sessionhandle as a single node and the nearest
  3000. * timeout is used to sort it on.
  3001. */
  3002. static CURLMcode add_next_timeout(struct curltime now,
  3003. struct Curl_multi *multi,
  3004. struct Curl_easy *d)
  3005. {
  3006. struct curltime *tv = &d->state.expiretime;
  3007. struct Curl_llist *list = &d->state.timeoutlist;
  3008. struct Curl_llist_node *e;
  3009. /* move over the timeout list for this specific handle and remove all
  3010. timeouts that are now passed tense and store the next pending
  3011. timeout in *tv */
  3012. for(e = Curl_llist_head(list); e;) {
  3013. struct Curl_llist_node *n = Curl_node_next(e);
  3014. struct time_node *node = Curl_node_elem(e);
  3015. timediff_t diff = Curl_timediff_us(node->time, now);
  3016. if(diff <= 0)
  3017. /* remove outdated entry */
  3018. Curl_node_remove(e);
  3019. else
  3020. /* the list is sorted so get out on the first mismatch */
  3021. break;
  3022. e = n;
  3023. }
  3024. e = Curl_llist_head(list);
  3025. if(!e) {
  3026. /* clear the expire times within the handles that we remove from the
  3027. splay tree */
  3028. tv->tv_sec = 0;
  3029. tv->tv_usec = 0;
  3030. }
  3031. else {
  3032. struct time_node *node = Curl_node_elem(e);
  3033. /* copy the first entry to 'tv' */
  3034. memcpy(tv, &node->time, sizeof(*tv));
  3035. /* Insert this node again into the splay. Keep the timer in the list in
  3036. case we need to recompute future timers. */
  3037. multi->timetree = Curl_splayinsert(*tv, multi->timetree,
  3038. &d->state.timenode);
  3039. }
  3040. return CURLM_OK;
  3041. }
  3042. struct multi_run_ctx {
  3043. struct Curl_multi *multi;
  3044. struct curltime now;
  3045. size_t run_xfers;
  3046. SIGPIPE_MEMBER(pipe_st);
  3047. bool run_cpool;
  3048. };
  3049. static CURLMcode multi_run_expired(struct multi_run_ctx *mrc)
  3050. {
  3051. struct Curl_multi *multi = mrc->multi;
  3052. struct Curl_easy *data = NULL;
  3053. struct Curl_tree *t = NULL;
  3054. CURLMcode result = CURLM_OK;
  3055. /*
  3056. * The loop following here will go on as long as there are expire-times left
  3057. * to process (compared to mrc->now) in the splay and 'data' will be
  3058. * re-assigned for every expired handle we deal with.
  3059. */
  3060. while(1) {
  3061. /* Check if there is one (more) expired timer to deal with! This function
  3062. extracts a matching node if there is one */
  3063. multi->timetree = Curl_splaygetbest(mrc->now, multi->timetree, &t);
  3064. if(!t)
  3065. goto out;
  3066. data = Curl_splayget(t); /* assign this for next loop */
  3067. if(!data)
  3068. continue;
  3069. (void)add_next_timeout(mrc->now, multi, data);
  3070. if(data == multi->cpool.idata) {
  3071. mrc->run_cpool = TRUE;
  3072. continue;
  3073. }
  3074. mrc->run_xfers++;
  3075. sigpipe_apply(data, &mrc->pipe_st);
  3076. result = multi_runsingle(multi, &mrc->now, data);
  3077. if(CURLM_OK >= result) {
  3078. /* get the socket(s) and check if the state has been changed since
  3079. last */
  3080. result = singlesocket(multi, data);
  3081. if(result)
  3082. goto out;
  3083. }
  3084. }
  3085. out:
  3086. return result;
  3087. }
  3088. static CURLMcode multi_socket(struct Curl_multi *multi,
  3089. bool checkall,
  3090. curl_socket_t s,
  3091. int ev_bitmask,
  3092. int *running_handles)
  3093. {
  3094. CURLMcode result = CURLM_OK;
  3095. struct Curl_easy *data = NULL;
  3096. struct multi_run_ctx mrc;
  3097. (void)ev_bitmask;
  3098. memset(&mrc, 0, sizeof(mrc));
  3099. mrc.multi = multi;
  3100. mrc.now = Curl_now();
  3101. sigpipe_init(&mrc.pipe_st);
  3102. if(checkall) {
  3103. struct Curl_llist_node *e;
  3104. /* *perform() deals with running_handles on its own */
  3105. result = curl_multi_perform(multi, running_handles);
  3106. /* walk through each easy handle and do the socket state change magic
  3107. and callbacks */
  3108. if(result != CURLM_BAD_HANDLE) {
  3109. for(e = Curl_llist_head(&multi->process); e && !result;
  3110. e = Curl_node_next(e)) {
  3111. result = singlesocket(multi, Curl_node_elem(e));
  3112. }
  3113. }
  3114. mrc.run_cpool = TRUE;
  3115. goto out;
  3116. }
  3117. if(s != CURL_SOCKET_TIMEOUT) {
  3118. struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
  3119. if(!entry) {
  3120. /* Unmatched socket, we cannot act on it but we ignore this fact. In
  3121. real-world tests it has been proved that libevent can in fact give
  3122. the application actions even though the socket was just previously
  3123. asked to get removed, so thus we better survive stray socket actions
  3124. and just move on. */
  3125. /* The socket might come from a connection that is being shut down
  3126. * by the multi's connection pool. */
  3127. Curl_cpool_multi_socket(multi, s, ev_bitmask);
  3128. }
  3129. else {
  3130. struct Curl_hash_iterator iter;
  3131. struct Curl_hash_element *he;
  3132. /* the socket can be shared by many transfers, iterate */
  3133. Curl_hash_start_iterate(&entry->transfers, &iter);
  3134. for(he = Curl_hash_next_element(&iter); he;
  3135. he = Curl_hash_next_element(&iter)) {
  3136. data = (struct Curl_easy *)he->ptr;
  3137. DEBUGASSERT(data);
  3138. DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER);
  3139. if(data == multi->cpool.idata)
  3140. mrc.run_cpool = TRUE;
  3141. else {
  3142. /* Expire with out current now, so we will get it below when
  3143. * asking the splaytree for expired transfers. */
  3144. expire_ex(data, &mrc.now, 0, EXPIRE_RUN_NOW);
  3145. }
  3146. }
  3147. }
  3148. }
  3149. result = multi_run_expired(&mrc);
  3150. if(result)
  3151. goto out;
  3152. if(mrc.run_xfers) {
  3153. /* Running transfers takes time. With a new timestamp, we might catch
  3154. * other expires which are due now. Instead of telling the application
  3155. * to set a 0 timeout and call us again, we run them here.
  3156. * Do that only once or it might be unfair to transfers on other
  3157. * sockets. */
  3158. mrc.now = Curl_now();
  3159. result = multi_run_expired(&mrc);
  3160. }
  3161. out:
  3162. if(mrc.run_cpool) {
  3163. sigpipe_apply(multi->cpool.idata, &mrc.pipe_st);
  3164. Curl_cpool_multi_perform(multi);
  3165. }
  3166. sigpipe_restore(&mrc.pipe_st);
  3167. if(running_handles)
  3168. *running_handles = (int)multi->num_alive;
  3169. if(CURLM_OK >= result)
  3170. result = Curl_update_timer(multi);
  3171. return result;
  3172. }
  3173. #undef curl_multi_setopt
  3174. CURLMcode curl_multi_setopt(CURLM *m,
  3175. CURLMoption option, ...)
  3176. {
  3177. CURLMcode res = CURLM_OK;
  3178. va_list param;
  3179. unsigned long uarg;
  3180. struct Curl_multi *multi = m;
  3181. if(!GOOD_MULTI_HANDLE(multi))
  3182. return CURLM_BAD_HANDLE;
  3183. if(multi->in_callback)
  3184. return CURLM_RECURSIVE_API_CALL;
  3185. va_start(param, option);
  3186. switch(option) {
  3187. case CURLMOPT_SOCKETFUNCTION:
  3188. multi->socket_cb = va_arg(param, curl_socket_callback);
  3189. break;
  3190. case CURLMOPT_SOCKETDATA:
  3191. multi->socket_userp = va_arg(param, void *);
  3192. break;
  3193. case CURLMOPT_PUSHFUNCTION:
  3194. multi->push_cb = va_arg(param, curl_push_callback);
  3195. break;
  3196. case CURLMOPT_PUSHDATA:
  3197. multi->push_userp = va_arg(param, void *);
  3198. break;
  3199. case CURLMOPT_PIPELINING:
  3200. multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0;
  3201. break;
  3202. case CURLMOPT_TIMERFUNCTION:
  3203. multi->timer_cb = va_arg(param, curl_multi_timer_callback);
  3204. break;
  3205. case CURLMOPT_TIMERDATA:
  3206. multi->timer_userp = va_arg(param, void *);
  3207. break;
  3208. case CURLMOPT_MAXCONNECTS:
  3209. uarg = va_arg(param, unsigned long);
  3210. if(uarg <= UINT_MAX)
  3211. multi->maxconnects = (unsigned int)uarg;
  3212. break;
  3213. case CURLMOPT_MAX_HOST_CONNECTIONS:
  3214. multi->max_host_connections = va_arg(param, long);
  3215. break;
  3216. case CURLMOPT_MAX_TOTAL_CONNECTIONS:
  3217. multi->max_total_connections = va_arg(param, long);
  3218. /* for now, let this also decide the max number of connections
  3219. * in shutdown handling */
  3220. multi->max_shutdown_connections = va_arg(param, long);
  3221. break;
  3222. /* options formerly used for pipelining */
  3223. case CURLMOPT_MAX_PIPELINE_LENGTH:
  3224. break;
  3225. case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
  3226. break;
  3227. case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
  3228. break;
  3229. case CURLMOPT_PIPELINING_SITE_BL:
  3230. break;
  3231. case CURLMOPT_PIPELINING_SERVER_BL:
  3232. break;
  3233. case CURLMOPT_MAX_CONCURRENT_STREAMS:
  3234. {
  3235. long streams = va_arg(param, long);
  3236. if((streams < 1) || (streams > INT_MAX))
  3237. streams = 100;
  3238. multi->max_concurrent_streams = (unsigned int)streams;
  3239. }
  3240. break;
  3241. default:
  3242. res = CURLM_UNKNOWN_OPTION;
  3243. break;
  3244. }
  3245. va_end(param);
  3246. return res;
  3247. }
  3248. /* we define curl_multi_socket() in the public multi.h header */
  3249. #undef curl_multi_socket
  3250. CURLMcode curl_multi_socket(CURLM *m, curl_socket_t s, int *running_handles)
  3251. {
  3252. struct Curl_multi *multi = m;
  3253. if(multi->in_callback)
  3254. return CURLM_RECURSIVE_API_CALL;
  3255. return multi_socket(multi, FALSE, s, 0, running_handles);
  3256. }
  3257. CURLMcode curl_multi_socket_action(CURLM *m, curl_socket_t s,
  3258. int ev_bitmask, int *running_handles)
  3259. {
  3260. struct Curl_multi *multi = m;
  3261. if(multi->in_callback)
  3262. return CURLM_RECURSIVE_API_CALL;
  3263. return multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
  3264. }
  3265. CURLMcode curl_multi_socket_all(CURLM *m, int *running_handles)
  3266. {
  3267. struct Curl_multi *multi = m;
  3268. if(multi->in_callback)
  3269. return CURLM_RECURSIVE_API_CALL;
  3270. return multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
  3271. }
  3272. static CURLMcode multi_timeout(struct Curl_multi *multi,
  3273. struct curltime *expire_time,
  3274. long *timeout_ms)
  3275. {
  3276. static const struct curltime tv_zero = {0, 0};
  3277. if(multi->dead) {
  3278. *timeout_ms = 0;
  3279. return CURLM_OK;
  3280. }
  3281. if(multi->timetree) {
  3282. /* we have a tree of expire times */
  3283. struct curltime now = Curl_now();
  3284. /* splay the lowest to the bottom */
  3285. multi->timetree = Curl_splay(tv_zero, multi->timetree);
  3286. /* this will not return NULL from a non-emtpy tree, but some compilers
  3287. * are not convinced of that. Analyzers are hard. */
  3288. *expire_time = multi->timetree ? multi->timetree->key : tv_zero;
  3289. /* 'multi->timetree' will be non-NULL here but the compilers sometimes
  3290. yell at us if we assume so */
  3291. if(multi->timetree &&
  3292. Curl_timediff_us(multi->timetree->key, now) > 0) {
  3293. /* some time left before expiration */
  3294. timediff_t diff = Curl_timediff_ceil(multi->timetree->key, now);
  3295. /* this should be safe even on 32-bit archs, as we do not use that
  3296. overly long timeouts */
  3297. *timeout_ms = (long)diff;
  3298. }
  3299. else {
  3300. /* 0 means immediately */
  3301. *timeout_ms = 0;
  3302. }
  3303. }
  3304. else {
  3305. *expire_time = tv_zero;
  3306. *timeout_ms = -1;
  3307. }
  3308. return CURLM_OK;
  3309. }
  3310. CURLMcode curl_multi_timeout(CURLM *m,
  3311. long *timeout_ms)
  3312. {
  3313. struct curltime expire_time;
  3314. struct Curl_multi *multi = m;
  3315. /* First, make some basic checks that the CURLM handle is a good handle */
  3316. if(!GOOD_MULTI_HANDLE(multi))
  3317. return CURLM_BAD_HANDLE;
  3318. if(multi->in_callback)
  3319. return CURLM_RECURSIVE_API_CALL;
  3320. return multi_timeout(multi, &expire_time, timeout_ms);
  3321. }
  3322. #define DEBUG_UPDATE_TIMER 0
  3323. /*
  3324. * Tell the application it should update its timers, if it subscribes to the
  3325. * update timer callback.
  3326. */
  3327. CURLMcode Curl_update_timer(struct Curl_multi *multi)
  3328. {
  3329. struct curltime expire_ts;
  3330. long timeout_ms;
  3331. int rc;
  3332. bool set_value = FALSE;
  3333. if(!multi->timer_cb || multi->dead)
  3334. return CURLM_OK;
  3335. if(multi_timeout(multi, &expire_ts, &timeout_ms)) {
  3336. return CURLM_OK;
  3337. }
  3338. if(timeout_ms < 0 && multi->last_timeout_ms < 0) {
  3339. #if DEBUG_UPDATE_TIMER
  3340. fprintf(stderr, "Curl_update_timer(), still no timeout, no change\n");
  3341. #endif
  3342. }
  3343. else if(timeout_ms < 0) {
  3344. /* there is no timeout now but there was one previously */
  3345. #if DEBUG_UPDATE_TIMER
  3346. fprintf(stderr, "Curl_update_timer(), remove timeout, "
  3347. " last_timeout=%ldms\n", multi->last_timeout_ms);
  3348. #endif
  3349. timeout_ms = -1; /* normalize */
  3350. set_value = TRUE;
  3351. }
  3352. else if(multi->last_timeout_ms < 0) {
  3353. #if DEBUG_UPDATE_TIMER
  3354. fprintf(stderr, "Curl_update_timer(), had no timeout, set now\n");
  3355. #endif
  3356. set_value = TRUE;
  3357. }
  3358. else if(Curl_timediff_us(multi->last_expire_ts, expire_ts)) {
  3359. /* We had a timeout before and have one now, the absolute timestamp
  3360. * differs. The relative timeout_ms may be the same, but the starting
  3361. * point differs. Let the application restart its timer. */
  3362. #if DEBUG_UPDATE_TIMER
  3363. fprintf(stderr, "Curl_update_timer(), expire timestamp changed\n");
  3364. #endif
  3365. set_value = TRUE;
  3366. }
  3367. else {
  3368. /* We have same expire time as previously. Our relative 'timeout_ms'
  3369. * may be different now, but the application has the timer running
  3370. * and we do not to tell it to start this again. */
  3371. #if DEBUG_UPDATE_TIMER
  3372. fprintf(stderr, "Curl_update_timer(), same expire timestamp, no change\n");
  3373. #endif
  3374. }
  3375. if(set_value) {
  3376. #if DEBUG_UPDATE_TIMER
  3377. fprintf(stderr, "Curl_update_timer(), set timeout %ldms\n", timeout_ms);
  3378. #endif
  3379. multi->last_expire_ts = expire_ts;
  3380. multi->last_timeout_ms = timeout_ms;
  3381. set_in_callback(multi, TRUE);
  3382. rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp);
  3383. set_in_callback(multi, FALSE);
  3384. if(rc == -1) {
  3385. multi->dead = TRUE;
  3386. return CURLM_ABORTED_BY_CALLBACK;
  3387. }
  3388. }
  3389. return CURLM_OK;
  3390. }
  3391. /*
  3392. * multi_deltimeout()
  3393. *
  3394. * Remove a given timestamp from the list of timeouts.
  3395. */
  3396. static void
  3397. multi_deltimeout(struct Curl_easy *data, expire_id eid)
  3398. {
  3399. struct Curl_llist_node *e;
  3400. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3401. /* find and remove the specific node from the list */
  3402. for(e = Curl_llist_head(timeoutlist); e; e = Curl_node_next(e)) {
  3403. struct time_node *n = Curl_node_elem(e);
  3404. if(n->eid == eid) {
  3405. Curl_node_remove(e);
  3406. return;
  3407. }
  3408. }
  3409. }
  3410. /*
  3411. * multi_addtimeout()
  3412. *
  3413. * Add a timestamp to the list of timeouts. Keep the list sorted so that head
  3414. * of list is always the timeout nearest in time.
  3415. *
  3416. */
  3417. static CURLMcode
  3418. multi_addtimeout(struct Curl_easy *data,
  3419. struct curltime *stamp,
  3420. expire_id eid)
  3421. {
  3422. struct Curl_llist_node *e;
  3423. struct time_node *node;
  3424. struct Curl_llist_node *prev = NULL;
  3425. size_t n;
  3426. struct Curl_llist *timeoutlist = &data->state.timeoutlist;
  3427. node = &data->state.expires[eid];
  3428. /* copy the timestamp and id */
  3429. memcpy(&node->time, stamp, sizeof(*stamp));
  3430. node->eid = eid; /* also marks it as in use */
  3431. n = Curl_llist_count(timeoutlist);
  3432. if(n) {
  3433. /* find the correct spot in the list */
  3434. for(e = Curl_llist_head(timeoutlist); e; e = Curl_node_next(e)) {
  3435. struct time_node *check = Curl_node_elem(e);
  3436. timediff_t diff = Curl_timediff(check->time, node->time);
  3437. if(diff > 0)
  3438. break;
  3439. prev = e;
  3440. }
  3441. }
  3442. /* else
  3443. this is the first timeout on the list */
  3444. Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
  3445. return CURLM_OK;
  3446. }
  3447. static void expire_ex(struct Curl_easy *data,
  3448. const struct curltime *nowp,
  3449. timediff_t milli, expire_id id)
  3450. {
  3451. struct Curl_multi *multi = data->multi;
  3452. struct curltime *curr_expire = &data->state.expiretime;
  3453. struct curltime set;
  3454. /* this is only interesting while there is still an associated multi struct
  3455. remaining! */
  3456. if(!multi)
  3457. return;
  3458. DEBUGASSERT(id < EXPIRE_LAST);
  3459. set = *nowp;
  3460. set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bits conversion */
  3461. set.tv_usec += (int)(milli%1000)*1000;
  3462. if(set.tv_usec >= 1000000) {
  3463. set.tv_sec++;
  3464. set.tv_usec -= 1000000;
  3465. }
  3466. /* Remove any timer with the same id just in case. */
  3467. multi_deltimeout(data, id);
  3468. /* Add it to the timer list. It must stay in the list until it has expired
  3469. in case we need to recompute the minimum timer later. */
  3470. multi_addtimeout(data, &set, id);
  3471. if(curr_expire->tv_sec || curr_expire->tv_usec) {
  3472. /* This means that the struct is added as a node in the splay tree.
  3473. Compare if the new time is earlier, and only remove-old/add-new if it
  3474. is. */
  3475. timediff_t diff = Curl_timediff(set, *curr_expire);
  3476. int rc;
  3477. if(diff > 0) {
  3478. /* The current splay tree entry is sooner than this new expiry time.
  3479. We do not need to update our splay tree entry. */
  3480. return;
  3481. }
  3482. /* Since this is an updated time, we must remove the previous entry from
  3483. the splay tree first and then re-add the new value */
  3484. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3485. &multi->timetree);
  3486. if(rc)
  3487. infof(data, "Internal error removing splay node = %d", rc);
  3488. }
  3489. /* Indicate that we are in the splay tree and insert the new timer expiry
  3490. value since it is our local minimum. */
  3491. *curr_expire = set;
  3492. Curl_splayset(&data->state.timenode, data);
  3493. multi->timetree = Curl_splayinsert(*curr_expire, multi->timetree,
  3494. &data->state.timenode);
  3495. }
  3496. /*
  3497. * Curl_expire()
  3498. *
  3499. * given a number of milliseconds from now to use to set the 'act before
  3500. * this'-time for the transfer, to be extracted by curl_multi_timeout()
  3501. *
  3502. * The timeout will be added to a queue of timeouts if it defines a moment in
  3503. * time that is later than the current head of queue.
  3504. *
  3505. * Expire replaces a former timeout using the same id if already set.
  3506. */
  3507. void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
  3508. {
  3509. struct curltime now = Curl_now();
  3510. expire_ex(data, &now, milli, id);
  3511. }
  3512. /*
  3513. * Curl_expire_done()
  3514. *
  3515. * Removes the expire timer. Marks it as done.
  3516. *
  3517. */
  3518. void Curl_expire_done(struct Curl_easy *data, expire_id id)
  3519. {
  3520. /* remove the timer, if there */
  3521. multi_deltimeout(data, id);
  3522. }
  3523. /*
  3524. * Curl_expire_clear()
  3525. *
  3526. * Clear ALL timeout values for this handle.
  3527. */
  3528. bool Curl_expire_clear(struct Curl_easy *data)
  3529. {
  3530. struct Curl_multi *multi = data->multi;
  3531. struct curltime *nowp = &data->state.expiretime;
  3532. /* this is only interesting while there is still an associated multi struct
  3533. remaining! */
  3534. if(!multi)
  3535. return FALSE;
  3536. if(nowp->tv_sec || nowp->tv_usec) {
  3537. /* Since this is an cleared time, we must remove the previous entry from
  3538. the splay tree */
  3539. struct Curl_llist *list = &data->state.timeoutlist;
  3540. int rc;
  3541. rc = Curl_splayremove(multi->timetree, &data->state.timenode,
  3542. &multi->timetree);
  3543. if(rc)
  3544. infof(data, "Internal error clearing splay node = %d", rc);
  3545. /* clear the timeout list too */
  3546. Curl_llist_destroy(list, NULL);
  3547. #ifdef DEBUGBUILD
  3548. infof(data, "Expire cleared");
  3549. #endif
  3550. nowp->tv_sec = 0;
  3551. nowp->tv_usec = 0;
  3552. return TRUE;
  3553. }
  3554. return FALSE;
  3555. }
  3556. CURLMcode curl_multi_assign(CURLM *m, curl_socket_t s,
  3557. void *hashp)
  3558. {
  3559. struct Curl_sh_entry *there = NULL;
  3560. struct Curl_multi *multi = m;
  3561. if(!GOOD_MULTI_HANDLE(multi))
  3562. return CURLM_BAD_HANDLE;
  3563. there = sh_getentry(&multi->sockhash, s);
  3564. if(!there)
  3565. return CURLM_BAD_SOCKET;
  3566. there->socketp = hashp;
  3567. return CURLM_OK;
  3568. }
  3569. static void move_pending_to_connect(struct Curl_multi *multi,
  3570. struct Curl_easy *data)
  3571. {
  3572. DEBUGASSERT(data->mstate == MSTATE_PENDING);
  3573. /* Remove this node from the pending list */
  3574. Curl_node_remove(&data->multi_queue);
  3575. /* put it into the process list */
  3576. Curl_llist_append(&multi->process, data, &data->multi_queue);
  3577. multistate(data, MSTATE_CONNECT);
  3578. /* Make sure that the handle will be processed soonish. */
  3579. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  3580. }
  3581. /* process_pending_handles() moves a handle from PENDING back into the process
  3582. list and change state to CONNECT.
  3583. We do not move all transfers because that can be a significant amount.
  3584. Since this is tried every now and then doing too many too often becomes a
  3585. performance problem.
  3586. When there is a change for connection limits like max host connections etc,
  3587. this likely only allows one new transfer. When there is a pipewait change,
  3588. it can potentially allow hundreds of new transfers.
  3589. We could consider an improvement where we store the queue reason and allow
  3590. more pipewait rechecks than others.
  3591. */
  3592. static void process_pending_handles(struct Curl_multi *multi)
  3593. {
  3594. struct Curl_llist_node *e = Curl_llist_head(&multi->pending);
  3595. if(e) {
  3596. struct Curl_easy *data = Curl_node_elem(e);
  3597. move_pending_to_connect(multi, data);
  3598. }
  3599. }
  3600. void Curl_set_in_callback(struct Curl_easy *data, bool value)
  3601. {
  3602. if(data && data->multi)
  3603. data->multi->in_callback = value;
  3604. }
  3605. bool Curl_is_in_callback(struct Curl_easy *data)
  3606. {
  3607. return (data && data->multi && data->multi->in_callback);
  3608. }
  3609. unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
  3610. {
  3611. DEBUGASSERT(multi);
  3612. return multi->max_concurrent_streams;
  3613. }
  3614. CURL **curl_multi_get_handles(CURLM *m)
  3615. {
  3616. struct Curl_multi *multi = m;
  3617. CURL **a = malloc(sizeof(struct Curl_easy *) * (multi->num_easy + 1));
  3618. if(a) {
  3619. unsigned int i = 0;
  3620. struct Curl_llist_node *e;
  3621. for(e = Curl_llist_head(&multi->process); e; e = Curl_node_next(e)) {
  3622. struct Curl_easy *data = Curl_node_elem(e);
  3623. DEBUGASSERT(i < multi->num_easy);
  3624. if(!data->state.internal)
  3625. a[i++] = data;
  3626. }
  3627. a[i] = NULL; /* last entry is a NULL */
  3628. }
  3629. return a;
  3630. }
  3631. CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data,
  3632. char **pbuf, size_t *pbuflen)
  3633. {
  3634. DEBUGASSERT(data);
  3635. DEBUGASSERT(data->multi);
  3636. *pbuf = NULL;
  3637. *pbuflen = 0;
  3638. if(!data->multi) {
  3639. failf(data, "transfer has no multi handle");
  3640. return CURLE_FAILED_INIT;
  3641. }
  3642. if(!data->set.buffer_size) {
  3643. failf(data, "transfer buffer size is 0");
  3644. return CURLE_FAILED_INIT;
  3645. }
  3646. if(data->multi->xfer_buf_borrowed) {
  3647. failf(data, "attempt to borrow xfer_buf when already borrowed");
  3648. return CURLE_AGAIN;
  3649. }
  3650. if(data->multi->xfer_buf &&
  3651. data->set.buffer_size > data->multi->xfer_buf_len) {
  3652. /* not large enough, get a new one */
  3653. free(data->multi->xfer_buf);
  3654. data->multi->xfer_buf = NULL;
  3655. data->multi->xfer_buf_len = 0;
  3656. }
  3657. if(!data->multi->xfer_buf) {
  3658. data->multi->xfer_buf = malloc((size_t)data->set.buffer_size);
  3659. if(!data->multi->xfer_buf) {
  3660. failf(data, "could not allocate xfer_buf of %zu bytes",
  3661. (size_t)data->set.buffer_size);
  3662. return CURLE_OUT_OF_MEMORY;
  3663. }
  3664. data->multi->xfer_buf_len = data->set.buffer_size;
  3665. }
  3666. data->multi->xfer_buf_borrowed = TRUE;
  3667. *pbuf = data->multi->xfer_buf;
  3668. *pbuflen = data->multi->xfer_buf_len;
  3669. return CURLE_OK;
  3670. }
  3671. void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf)
  3672. {
  3673. (void)buf;
  3674. DEBUGASSERT(data);
  3675. DEBUGASSERT(data->multi);
  3676. DEBUGASSERT(!buf || data->multi->xfer_buf == buf);
  3677. data->multi->xfer_buf_borrowed = FALSE;
  3678. }
  3679. CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data,
  3680. char **pbuf, size_t *pbuflen)
  3681. {
  3682. DEBUGASSERT(data);
  3683. DEBUGASSERT(data->multi);
  3684. *pbuf = NULL;
  3685. *pbuflen = 0;
  3686. if(!data->multi) {
  3687. failf(data, "transfer has no multi handle");
  3688. return CURLE_FAILED_INIT;
  3689. }
  3690. if(!data->set.upload_buffer_size) {
  3691. failf(data, "transfer upload buffer size is 0");
  3692. return CURLE_FAILED_INIT;
  3693. }
  3694. if(data->multi->xfer_ulbuf_borrowed) {
  3695. failf(data, "attempt to borrow xfer_ulbuf when already borrowed");
  3696. return CURLE_AGAIN;
  3697. }
  3698. if(data->multi->xfer_ulbuf &&
  3699. data->set.upload_buffer_size > data->multi->xfer_ulbuf_len) {
  3700. /* not large enough, get a new one */
  3701. free(data->multi->xfer_ulbuf);
  3702. data->multi->xfer_ulbuf = NULL;
  3703. data->multi->xfer_ulbuf_len = 0;
  3704. }
  3705. if(!data->multi->xfer_ulbuf) {
  3706. data->multi->xfer_ulbuf = malloc((size_t)data->set.upload_buffer_size);
  3707. if(!data->multi->xfer_ulbuf) {
  3708. failf(data, "could not allocate xfer_ulbuf of %zu bytes",
  3709. (size_t)data->set.upload_buffer_size);
  3710. return CURLE_OUT_OF_MEMORY;
  3711. }
  3712. data->multi->xfer_ulbuf_len = data->set.upload_buffer_size;
  3713. }
  3714. data->multi->xfer_ulbuf_borrowed = TRUE;
  3715. *pbuf = data->multi->xfer_ulbuf;
  3716. *pbuflen = data->multi->xfer_ulbuf_len;
  3717. return CURLE_OK;
  3718. }
  3719. void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf)
  3720. {
  3721. (void)buf;
  3722. DEBUGASSERT(data);
  3723. DEBUGASSERT(data->multi);
  3724. DEBUGASSERT(!buf || data->multi->xfer_ulbuf == buf);
  3725. data->multi->xfer_ulbuf_borrowed = FALSE;
  3726. }
  3727. CURLcode Curl_multi_xfer_sockbuf_borrow(struct Curl_easy *data,
  3728. size_t blen, char **pbuf)
  3729. {
  3730. DEBUGASSERT(data);
  3731. DEBUGASSERT(data->multi);
  3732. *pbuf = NULL;
  3733. if(!data->multi) {
  3734. failf(data, "transfer has no multi handle");
  3735. return CURLE_FAILED_INIT;
  3736. }
  3737. if(data->multi->xfer_sockbuf_borrowed) {
  3738. failf(data, "attempt to borrow xfer_sockbuf when already borrowed");
  3739. return CURLE_AGAIN;
  3740. }
  3741. if(data->multi->xfer_sockbuf && blen > data->multi->xfer_sockbuf_len) {
  3742. /* not large enough, get a new one */
  3743. free(data->multi->xfer_sockbuf);
  3744. data->multi->xfer_sockbuf = NULL;
  3745. data->multi->xfer_sockbuf_len = 0;
  3746. }
  3747. if(!data->multi->xfer_sockbuf) {
  3748. data->multi->xfer_sockbuf = malloc(blen);
  3749. if(!data->multi->xfer_sockbuf) {
  3750. failf(data, "could not allocate xfer_sockbuf of %zu bytes", blen);
  3751. return CURLE_OUT_OF_MEMORY;
  3752. }
  3753. data->multi->xfer_sockbuf_len = blen;
  3754. }
  3755. data->multi->xfer_sockbuf_borrowed = TRUE;
  3756. *pbuf = data->multi->xfer_sockbuf;
  3757. return CURLE_OK;
  3758. }
  3759. void Curl_multi_xfer_sockbuf_release(struct Curl_easy *data, char *buf)
  3760. {
  3761. (void)buf;
  3762. DEBUGASSERT(data);
  3763. DEBUGASSERT(data->multi);
  3764. DEBUGASSERT(!buf || data->multi->xfer_sockbuf == buf);
  3765. data->multi->xfer_sockbuf_borrowed = FALSE;
  3766. }
  3767. static void multi_xfer_bufs_free(struct Curl_multi *multi)
  3768. {
  3769. DEBUGASSERT(multi);
  3770. Curl_safefree(multi->xfer_buf);
  3771. multi->xfer_buf_len = 0;
  3772. multi->xfer_buf_borrowed = FALSE;
  3773. Curl_safefree(multi->xfer_ulbuf);
  3774. multi->xfer_ulbuf_len = 0;
  3775. multi->xfer_ulbuf_borrowed = FALSE;
  3776. Curl_safefree(multi->xfer_sockbuf);
  3777. multi->xfer_sockbuf_len = 0;
  3778. multi->xfer_sockbuf_borrowed = FALSE;
  3779. }
  3780. struct Curl_easy *Curl_multi_get_handle(struct Curl_multi *multi,
  3781. curl_off_t mid)
  3782. {
  3783. if(mid >= 0) {
  3784. struct Curl_easy *data;
  3785. struct Curl_llist_node *e;
  3786. for(e = Curl_llist_head(&multi->process); e; e = Curl_node_next(e)) {
  3787. data = Curl_node_elem(e);
  3788. if(data->mid == mid)
  3789. return data;
  3790. }
  3791. /* may be in msgsent queue */
  3792. for(e = Curl_llist_head(&multi->msgsent); e; e = Curl_node_next(e)) {
  3793. data = Curl_node_elem(e);
  3794. if(data->mid == mid)
  3795. return data;
  3796. }
  3797. /* may be in pending queue */
  3798. for(e = Curl_llist_head(&multi->pending); e; e = Curl_node_next(e)) {
  3799. data = Curl_node_elem(e);
  3800. if(data->mid == mid)
  3801. return data;
  3802. }
  3803. }
  3804. return NULL;
  3805. }