2
0

multi.c 129 KB

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