multi.c 131 KB

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