multi.c 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2015, 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.haxx.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. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #include <curl/curl.h>
  24. #include "urldata.h"
  25. #include "transfer.h"
  26. #include "url.h"
  27. #include "connect.h"
  28. #include "progress.h"
  29. #include "easyif.h"
  30. #include "share.h"
  31. #include "multiif.h"
  32. #include "sendf.h"
  33. #include "timeval.h"
  34. #include "http.h"
  35. #include "select.h"
  36. #include "warnless.h"
  37. #include "speedcheck.h"
  38. #include "conncache.h"
  39. #include "multihandle.h"
  40. #include "pipeline.h"
  41. #include "sigpipe.h"
  42. #include "curl_printf.h"
  43. #include "curl_memory.h"
  44. /* The last #include file should be: */
  45. #include "memdebug.h"
  46. /*
  47. CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
  48. to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
  49. CURL handle takes 45-50 K memory, therefore this 3K are not significant.
  50. */
  51. #ifndef CURL_SOCKET_HASH_TABLE_SIZE
  52. #define CURL_SOCKET_HASH_TABLE_SIZE 911
  53. #endif
  54. #define CURL_CONNECTION_HASH_SIZE 97
  55. #define CURL_MULTI_HANDLE 0x000bab1e
  56. #define GOOD_MULTI_HANDLE(x) \
  57. ((x) && (((struct Curl_multi *)(x))->type == CURL_MULTI_HANDLE))
  58. static void singlesocket(struct Curl_multi *multi,
  59. struct SessionHandle *data);
  60. static int update_timer(struct Curl_multi *multi);
  61. static CURLMcode add_next_timeout(struct timeval now,
  62. struct Curl_multi *multi,
  63. struct SessionHandle *d);
  64. static CURLMcode multi_timeout(struct Curl_multi *multi,
  65. long *timeout_ms);
  66. #ifdef DEBUGBUILD
  67. static const char * const statename[]={
  68. "INIT",
  69. "CONNECT_PEND",
  70. "CONNECT",
  71. "WAITRESOLVE",
  72. "WAITCONNECT",
  73. "WAITPROXYCONNECT",
  74. "SENDPROTOCONNECT",
  75. "PROTOCONNECT",
  76. "WAITDO",
  77. "DO",
  78. "DOING",
  79. "DO_MORE",
  80. "DO_DONE",
  81. "WAITPERFORM",
  82. "PERFORM",
  83. "TOOFAST",
  84. "DONE",
  85. "COMPLETED",
  86. "MSGSENT",
  87. };
  88. #endif
  89. static void multi_freetimeout(void *a, void *b);
  90. /* function pointer called once when switching TO a state */
  91. typedef void (*init_multistate_func)(struct SessionHandle *data);
  92. /* always use this function to change state, to make debugging easier */
  93. static void mstate(struct SessionHandle *data, CURLMstate state
  94. #ifdef DEBUGBUILD
  95. , int lineno
  96. #endif
  97. )
  98. {
  99. CURLMstate oldstate = data->mstate;
  100. static const init_multistate_func finit[CURLM_STATE_LAST] = {
  101. NULL,
  102. NULL,
  103. Curl_init_CONNECT, /* CONNECT */
  104. /* the rest is NULL too */
  105. };
  106. #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
  107. (void) lineno;
  108. #endif
  109. if(oldstate == state)
  110. /* don't bother when the new state is the same as the old state */
  111. return;
  112. data->mstate = state;
  113. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  114. if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
  115. data->mstate < CURLM_STATE_COMPLETED) {
  116. long connection_id = -5000;
  117. if(data->easy_conn)
  118. connection_id = data->easy_conn->connection_id;
  119. infof(data,
  120. "STATE: %s => %s handle %p; line %d (connection #%ld) \n",
  121. statename[oldstate], statename[data->mstate],
  122. (void *)data, lineno, connection_id);
  123. }
  124. #endif
  125. if(state == CURLM_STATE_COMPLETED)
  126. /* changing to COMPLETED means there's one less easy handle 'alive' */
  127. data->multi->num_alive--;
  128. /* if this state has an init-function, run it */
  129. if(finit[state])
  130. finit[state](data);
  131. }
  132. #ifndef DEBUGBUILD
  133. #define multistate(x,y) mstate(x,y)
  134. #else
  135. #define multistate(x,y) mstate(x,y, __LINE__)
  136. #endif
  137. /*
  138. * We add one of these structs to the sockhash for a particular socket
  139. */
  140. struct Curl_sh_entry {
  141. struct SessionHandle *easy;
  142. int action; /* what action READ/WRITE this socket waits for */
  143. curl_socket_t socket; /* mainly to ease debugging */
  144. void *socketp; /* settable by users with curl_multi_assign() */
  145. };
  146. /* bits for 'action' having no bits means this socket is not expecting any
  147. action */
  148. #define SH_READ 1
  149. #define SH_WRITE 2
  150. /* make sure this socket is present in the hash for this handle */
  151. static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh,
  152. curl_socket_t s,
  153. struct SessionHandle *data)
  154. {
  155. struct Curl_sh_entry *there =
  156. Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
  157. struct Curl_sh_entry *check;
  158. if(there)
  159. /* it is present, return fine */
  160. return there;
  161. /* not present, add it */
  162. check = calloc(1, sizeof(struct Curl_sh_entry));
  163. if(!check)
  164. return NULL; /* major failure */
  165. check->easy = data;
  166. check->socket = s;
  167. /* make/add new hash entry */
  168. if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
  169. free(check);
  170. return NULL; /* major failure */
  171. }
  172. return check; /* things are good in sockhash land */
  173. }
  174. /* delete the given socket + handle from the hash */
  175. static void sh_delentry(struct curl_hash *sh, curl_socket_t s)
  176. {
  177. struct Curl_sh_entry *there =
  178. Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
  179. if(there) {
  180. /* this socket is in the hash */
  181. /* We remove the hash entry. (This'll end up in a call to
  182. sh_freeentry().) */
  183. Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
  184. }
  185. }
  186. /*
  187. * free a sockhash entry
  188. */
  189. static void sh_freeentry(void *freethis)
  190. {
  191. struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
  192. free(p);
  193. }
  194. static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
  195. {
  196. (void) k1_len; (void) k2_len;
  197. return (*((int *) k1)) == (*((int *) k2));
  198. }
  199. static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
  200. {
  201. int fd = *((int *) key);
  202. (void) key_length;
  203. return (fd % (int)slots_num);
  204. }
  205. /*
  206. * sh_init() creates a new socket hash and returns the handle for it.
  207. *
  208. * Quote from README.multi_socket:
  209. *
  210. * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
  211. * is somewhat of a bottle neck. Its current implementation may be a bit too
  212. * limiting. It simply has a fixed-size array, and on each entry in the array
  213. * it has a linked list with entries. So the hash only checks which list to
  214. * scan through. The code I had used so for used a list with merely 7 slots
  215. * (as that is what the DNS hash uses) but with 7000 connections that would
  216. * make an average of 1000 nodes in each list to run through. I upped that to
  217. * 97 slots (I believe a prime is suitable) and noticed a significant speed
  218. * increase. I need to reconsider the hash implementation or use a rather
  219. * large default value like this. At 9000 connections I was still below 10us
  220. * per call."
  221. *
  222. */
  223. static int sh_init(struct curl_hash *hash, int hashsize)
  224. {
  225. return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
  226. sh_freeentry);
  227. }
  228. /*
  229. * multi_addmsg()
  230. *
  231. * Called when a transfer is completed. Adds the given msg pointer to
  232. * the list kept in the multi handle.
  233. */
  234. static CURLMcode multi_addmsg(struct Curl_multi *multi,
  235. struct Curl_message *msg)
  236. {
  237. if(!Curl_llist_insert_next(multi->msglist, multi->msglist->tail, msg))
  238. return CURLM_OUT_OF_MEMORY;
  239. return CURLM_OK;
  240. }
  241. /*
  242. * multi_freeamsg()
  243. *
  244. * Callback used by the llist system when a single list entry is destroyed.
  245. */
  246. static void multi_freeamsg(void *a, void *b)
  247. {
  248. (void)a;
  249. (void)b;
  250. }
  251. struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
  252. int chashsize) /* connection hash */
  253. {
  254. struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
  255. if(!multi)
  256. return NULL;
  257. multi->type = CURL_MULTI_HANDLE;
  258. if(Curl_mk_dnscache(&multi->hostcache))
  259. goto error;
  260. if(sh_init(&multi->sockhash, hashsize))
  261. goto error;
  262. if(Curl_conncache_init(&multi->conn_cache, chashsize))
  263. goto error;
  264. multi->msglist = Curl_llist_alloc(multi_freeamsg);
  265. if(!multi->msglist)
  266. goto error;
  267. multi->pending = Curl_llist_alloc(multi_freeamsg);
  268. if(!multi->pending)
  269. goto error;
  270. /* allocate a new easy handle to use when closing cached connections */
  271. multi->closure_handle = curl_easy_init();
  272. if(!multi->closure_handle)
  273. goto error;
  274. multi->closure_handle->multi = multi;
  275. multi->closure_handle->state.conn_cache = &multi->conn_cache;
  276. multi->max_pipeline_length = 5;
  277. /* -1 means it not set by user, use the default value */
  278. multi->maxconnects = -1;
  279. return (CURLM *) multi;
  280. error:
  281. Curl_hash_destroy(&multi->sockhash);
  282. Curl_hash_destroy(&multi->hostcache);
  283. Curl_conncache_destroy(&multi->conn_cache);
  284. Curl_close(multi->closure_handle);
  285. multi->closure_handle = NULL;
  286. Curl_llist_destroy(multi->msglist, NULL);
  287. Curl_llist_destroy(multi->pending, NULL);
  288. free(multi);
  289. return NULL;
  290. }
  291. CURLM *curl_multi_init(void)
  292. {
  293. return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
  294. CURL_CONNECTION_HASH_SIZE);
  295. }
  296. CURLMcode curl_multi_add_handle(CURLM *multi_handle,
  297. CURL *easy_handle)
  298. {
  299. struct curl_llist *timeoutlist;
  300. struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
  301. struct SessionHandle *data = (struct SessionHandle *)easy_handle;
  302. /* First, make some basic checks that the CURLM handle is a good handle */
  303. if(!GOOD_MULTI_HANDLE(multi))
  304. return CURLM_BAD_HANDLE;
  305. /* Verify that we got a somewhat good easy handle too */
  306. if(!GOOD_EASY_HANDLE(easy_handle))
  307. return CURLM_BAD_EASY_HANDLE;
  308. /* Prevent users from adding same easy handle more than once and prevent
  309. adding to more than one multi stack */
  310. if(data->multi)
  311. return CURLM_ADDED_ALREADY;
  312. /* Allocate and initialize timeout list for easy handle */
  313. timeoutlist = Curl_llist_alloc(multi_freetimeout);
  314. if(!timeoutlist)
  315. return CURLM_OUT_OF_MEMORY;
  316. /*
  317. * No failure allowed in this function beyond this point. And no
  318. * modification of easy nor multi handle allowed before this except for
  319. * potential multi's connection cache growing which won't be undone in this
  320. * function no matter what.
  321. */
  322. /* Make easy handle use timeout list initialized above */
  323. data->state.timeoutlist = timeoutlist;
  324. timeoutlist = NULL;
  325. /* set the easy handle */
  326. multistate(data, CURLM_STATE_INIT);
  327. if((data->set.global_dns_cache) &&
  328. (data->dns.hostcachetype != HCACHE_GLOBAL)) {
  329. /* global dns cache was requested but still isn't */
  330. struct curl_hash *global = Curl_global_host_cache_init();
  331. if(global) {
  332. /* only do this if the global cache init works */
  333. data->dns.hostcache = global;
  334. data->dns.hostcachetype = HCACHE_GLOBAL;
  335. }
  336. }
  337. /* for multi interface connections, we share DNS cache automatically if the
  338. easy handle's one is currently not set. */
  339. else if(!data->dns.hostcache ||
  340. (data->dns.hostcachetype == HCACHE_NONE)) {
  341. data->dns.hostcache = &multi->hostcache;
  342. data->dns.hostcachetype = HCACHE_MULTI;
  343. }
  344. /* Point to the multi's connection cache */
  345. data->state.conn_cache = &multi->conn_cache;
  346. /* This adds the new entry at the 'end' of the doubly-linked circular
  347. list of SessionHandle structs to try and maintain a FIFO queue so
  348. the pipelined requests are in order. */
  349. /* We add this new entry last in the list. */
  350. data->next = NULL; /* end of the line */
  351. if(multi->easyp) {
  352. struct SessionHandle *last = multi->easylp;
  353. last->next = data;
  354. data->prev = last;
  355. multi->easylp = data; /* the new last node */
  356. }
  357. else {
  358. /* first node, make prev NULL! */
  359. data->prev = NULL;
  360. multi->easylp = multi->easyp = data; /* both first and last */
  361. }
  362. /* make the SessionHandle refer back to this multi handle */
  363. data->multi = multi_handle;
  364. /* Set the timeout for this handle to expire really soon so that it will
  365. be taken care of even when this handle is added in the midst of operation
  366. when only the curl_multi_socket() API is used. During that flow, only
  367. sockets that time-out or have actions will be dealt with. Since this
  368. handle has no action yet, we make sure it times out to get things to
  369. happen. */
  370. Curl_expire(data, 1);
  371. /* increase the node-counter */
  372. multi->num_easy++;
  373. /* increase the alive-counter */
  374. multi->num_alive++;
  375. /* A somewhat crude work-around for a little glitch in update_timer() that
  376. happens if the lastcall time is set to the same time when the handle is
  377. removed as when the next handle is added, as then the check in
  378. update_timer() that prevents calling the application multiple times with
  379. the same timer infor will not trigger and then the new handle's timeout
  380. will not be notified to the app.
  381. The work-around is thus simply to clear the 'lastcall' variable to force
  382. update_timer() to always trigger a callback to the app when a new easy
  383. handle is added */
  384. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  385. update_timer(multi);
  386. return CURLM_OK;
  387. }
  388. #if 0
  389. /* Debug-function, used like this:
  390. *
  391. * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
  392. *
  393. * Enable the hash print function first by editing hash.c
  394. */
  395. static void debug_print_sock_hash(void *p)
  396. {
  397. struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
  398. fprintf(stderr, " [easy %p/magic %x/socket %d]",
  399. (void *)sh->data, sh->data->magic, (int)sh->socket);
  400. }
  401. #endif
  402. CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
  403. CURL *curl_handle)
  404. {
  405. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  406. struct SessionHandle *easy = curl_handle;
  407. struct SessionHandle *data = easy;
  408. bool premature;
  409. bool easy_owns_conn;
  410. struct curl_llist_element *e;
  411. /* First, make some basic checks that the CURLM handle is a good handle */
  412. if(!GOOD_MULTI_HANDLE(multi))
  413. return CURLM_BAD_HANDLE;
  414. /* Verify that we got a somewhat good easy handle too */
  415. if(!GOOD_EASY_HANDLE(curl_handle))
  416. return CURLM_BAD_EASY_HANDLE;
  417. /* Prevent users from trying to remove same easy handle more than once */
  418. if(!data->multi)
  419. return CURLM_OK; /* it is already removed so let's say it is fine! */
  420. premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
  421. easy_owns_conn = (data->easy_conn && (data->easy_conn->data == easy)) ?
  422. TRUE : FALSE;
  423. /* If the 'state' is not INIT or COMPLETED, we might need to do something
  424. nice to put the easy_handle in a good known state when this returns. */
  425. if(premature) {
  426. /* this handle is "alive" so we need to count down the total number of
  427. alive connections when this is removed */
  428. multi->num_alive--;
  429. /* When this handle gets removed, other handles may be able to get the
  430. connection */
  431. Curl_multi_process_pending_handles(multi);
  432. }
  433. if(data->easy_conn &&
  434. data->mstate > CURLM_STATE_DO &&
  435. data->mstate < CURLM_STATE_COMPLETED) {
  436. /* If the handle is in a pipeline and has started sending off its
  437. request but not received its response yet, we need to close
  438. connection. */
  439. connclose(data->easy_conn, "Removed with partial response");
  440. /* Set connection owner so that Curl_done() closes it.
  441. We can safely do this here since connection is killed. */
  442. data->easy_conn->data = easy;
  443. easy_owns_conn = TRUE;
  444. }
  445. /* The timer must be shut down before data->multi is set to NULL,
  446. else the timenode will remain in the splay tree after
  447. curl_easy_cleanup is called. */
  448. Curl_expire(data, 0);
  449. /* destroy the timeout list that is held in the easy handle */
  450. if(data->state.timeoutlist) {
  451. Curl_llist_destroy(data->state.timeoutlist, NULL);
  452. data->state.timeoutlist = NULL;
  453. }
  454. if(data->dns.hostcachetype == HCACHE_MULTI) {
  455. /* stop using the multi handle's DNS cache */
  456. data->dns.hostcache = NULL;
  457. data->dns.hostcachetype = HCACHE_NONE;
  458. }
  459. if(data->easy_conn) {
  460. /* we must call Curl_done() here (if we still "own it") so that we don't
  461. leave a half-baked one around */
  462. if(easy_owns_conn) {
  463. /* Curl_done() clears the conn->data field to lose the association
  464. between the easy handle and the connection
  465. Note that this ignores the return code simply because there's
  466. nothing really useful to do with it anyway! */
  467. (void)Curl_done(&data->easy_conn, data->result, premature);
  468. }
  469. else
  470. /* Clear connection pipelines, if Curl_done above was not called */
  471. Curl_getoff_all_pipelines(data, data->easy_conn);
  472. }
  473. Curl_wildcard_dtor(&data->wildcard);
  474. /* as this was using a shared connection cache we clear the pointer to that
  475. since we're not part of that multi handle anymore */
  476. data->state.conn_cache = NULL;
  477. /* change state without using multistate(), only to make singlesocket() do
  478. what we want */
  479. data->mstate = CURLM_STATE_COMPLETED;
  480. singlesocket(multi, easy); /* to let the application know what sockets that
  481. vanish with this handle */
  482. /* Remove the association between the connection and the handle */
  483. if(data->easy_conn) {
  484. data->easy_conn->data = NULL;
  485. data->easy_conn = NULL;
  486. }
  487. data->multi = NULL; /* clear the association to this multi handle */
  488. /* make sure there's no pending message in the queue sent from this easy
  489. handle */
  490. for(e = multi->msglist->head; e; e = e->next) {
  491. struct Curl_message *msg = e->ptr;
  492. if(msg->extmsg.easy_handle == easy) {
  493. Curl_llist_remove(multi->msglist, e, NULL);
  494. /* there can only be one from this specific handle */
  495. break;
  496. }
  497. }
  498. /* make the previous node point to our next */
  499. if(data->prev)
  500. data->prev->next = data->next;
  501. else
  502. multi->easyp = data->next; /* point to first node */
  503. /* make our next point to our previous node */
  504. if(data->next)
  505. data->next->prev = data->prev;
  506. else
  507. multi->easylp = data->prev; /* point to last node */
  508. /* NOTE NOTE NOTE
  509. We do not touch the easy handle here! */
  510. multi->num_easy--; /* one less to care about now */
  511. update_timer(multi);
  512. return CURLM_OK;
  513. }
  514. /* Return TRUE if the application asked for a certain set of pipelining */
  515. bool Curl_pipeline_wanted(const struct Curl_multi *multi, int bits)
  516. {
  517. return (multi && (multi->pipelining & bits)) ? TRUE : FALSE;
  518. }
  519. void Curl_multi_handlePipeBreak(struct SessionHandle *data)
  520. {
  521. data->easy_conn = NULL;
  522. }
  523. static int waitconnect_getsock(struct connectdata *conn,
  524. curl_socket_t *sock,
  525. int numsocks)
  526. {
  527. int i;
  528. int s=0;
  529. int rc=0;
  530. if(!numsocks)
  531. return GETSOCK_BLANK;
  532. for(i=0; i<2; i++) {
  533. if(conn->tempsock[i] != CURL_SOCKET_BAD) {
  534. sock[s] = conn->tempsock[i];
  535. rc |= GETSOCK_WRITESOCK(s++);
  536. }
  537. }
  538. return rc;
  539. }
  540. static int waitproxyconnect_getsock(struct connectdata *conn,
  541. curl_socket_t *sock,
  542. int numsocks)
  543. {
  544. if(!numsocks)
  545. return GETSOCK_BLANK;
  546. sock[0] = conn->sock[FIRSTSOCKET];
  547. /* when we've sent a CONNECT to a proxy, we should rather wait for the
  548. socket to become readable to be able to get the response headers */
  549. if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  550. return GETSOCK_READSOCK(0);
  551. return GETSOCK_WRITESOCK(0);
  552. }
  553. static int domore_getsock(struct connectdata *conn,
  554. curl_socket_t *socks,
  555. int numsocks)
  556. {
  557. if(conn && conn->handler->domore_getsock)
  558. return conn->handler->domore_getsock(conn, socks, numsocks);
  559. return GETSOCK_BLANK;
  560. }
  561. /* returns bitmapped flags for this handle and its sockets */
  562. static int multi_getsock(struct SessionHandle *data,
  563. curl_socket_t *socks, /* points to numsocks number
  564. of sockets */
  565. int numsocks)
  566. {
  567. /* If the pipe broke, or if there's no connection left for this easy handle,
  568. then we MUST bail out now with no bitmask set. The no connection case can
  569. happen when this is called from curl_multi_remove_handle() =>
  570. singlesocket() => multi_getsock().
  571. */
  572. if(data->state.pipe_broke || !data->easy_conn)
  573. return 0;
  574. if(data->mstate > CURLM_STATE_CONNECT &&
  575. data->mstate < CURLM_STATE_COMPLETED) {
  576. /* Set up ownership correctly */
  577. data->easy_conn->data = data;
  578. }
  579. switch(data->mstate) {
  580. default:
  581. #if 0 /* switch back on these cases to get the compiler to check for all enums
  582. to be present */
  583. case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */
  584. case CURLM_STATE_COMPLETED:
  585. case CURLM_STATE_MSGSENT:
  586. case CURLM_STATE_INIT:
  587. case CURLM_STATE_CONNECT:
  588. case CURLM_STATE_WAITDO:
  589. case CURLM_STATE_DONE:
  590. case CURLM_STATE_LAST:
  591. /* this will get called with CURLM_STATE_COMPLETED when a handle is
  592. removed */
  593. #endif
  594. return 0;
  595. case CURLM_STATE_WAITRESOLVE:
  596. return Curl_resolver_getsock(data->easy_conn, socks, numsocks);
  597. case CURLM_STATE_PROTOCONNECT:
  598. case CURLM_STATE_SENDPROTOCONNECT:
  599. return Curl_protocol_getsock(data->easy_conn, socks, numsocks);
  600. case CURLM_STATE_DO:
  601. case CURLM_STATE_DOING:
  602. return Curl_doing_getsock(data->easy_conn, socks, numsocks);
  603. case CURLM_STATE_WAITPROXYCONNECT:
  604. return waitproxyconnect_getsock(data->easy_conn, socks, numsocks);
  605. case CURLM_STATE_WAITCONNECT:
  606. return waitconnect_getsock(data->easy_conn, socks, numsocks);
  607. case CURLM_STATE_DO_MORE:
  608. return domore_getsock(data->easy_conn, socks, numsocks);
  609. case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
  610. to waiting for the same as the *PERFORM
  611. states */
  612. case CURLM_STATE_PERFORM:
  613. case CURLM_STATE_WAITPERFORM:
  614. return Curl_single_getsock(data->easy_conn, socks, numsocks);
  615. }
  616. }
  617. CURLMcode curl_multi_fdset(CURLM *multi_handle,
  618. fd_set *read_fd_set, fd_set *write_fd_set,
  619. fd_set *exc_fd_set, int *max_fd)
  620. {
  621. /* Scan through all the easy handles to get the file descriptors set.
  622. Some easy handles may not have connected to the remote host yet,
  623. and then we must make sure that is done. */
  624. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  625. struct SessionHandle *data;
  626. int this_max_fd=-1;
  627. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  628. int bitmap;
  629. int i;
  630. (void)exc_fd_set; /* not used */
  631. if(!GOOD_MULTI_HANDLE(multi))
  632. return CURLM_BAD_HANDLE;
  633. data=multi->easyp;
  634. while(data) {
  635. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  636. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  637. curl_socket_t s = CURL_SOCKET_BAD;
  638. if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
  639. FD_SET(sockbunch[i], read_fd_set);
  640. s = sockbunch[i];
  641. }
  642. if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
  643. FD_SET(sockbunch[i], write_fd_set);
  644. s = sockbunch[i];
  645. }
  646. if(s == CURL_SOCKET_BAD)
  647. /* this socket is unused, break out of loop */
  648. break;
  649. else {
  650. if((int)s > this_max_fd)
  651. this_max_fd = (int)s;
  652. }
  653. }
  654. data = data->next; /* check next handle */
  655. }
  656. *max_fd = this_max_fd;
  657. return CURLM_OK;
  658. }
  659. CURLMcode curl_multi_wait(CURLM *multi_handle,
  660. struct curl_waitfd extra_fds[],
  661. unsigned int extra_nfds,
  662. int timeout_ms,
  663. int *ret)
  664. {
  665. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  666. struct SessionHandle *data;
  667. curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
  668. int bitmap;
  669. unsigned int i;
  670. unsigned int nfds = 0;
  671. unsigned int curlfds;
  672. struct pollfd *ufds = NULL;
  673. long timeout_internal;
  674. if(!GOOD_MULTI_HANDLE(multi))
  675. return CURLM_BAD_HANDLE;
  676. /* If the internally desired timeout is actually shorter than requested from
  677. the outside, then use the shorter time! But only if the internal timer
  678. is actually larger than -1! */
  679. (void)multi_timeout(multi, &timeout_internal);
  680. if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
  681. timeout_ms = (int)timeout_internal;
  682. /* Count up how many fds we have from the multi handle */
  683. data=multi->easyp;
  684. while(data) {
  685. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  686. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  687. curl_socket_t s = CURL_SOCKET_BAD;
  688. if(bitmap & GETSOCK_READSOCK(i)) {
  689. ++nfds;
  690. s = sockbunch[i];
  691. }
  692. if(bitmap & GETSOCK_WRITESOCK(i)) {
  693. ++nfds;
  694. s = sockbunch[i];
  695. }
  696. if(s == CURL_SOCKET_BAD) {
  697. break;
  698. }
  699. }
  700. data = data->next; /* check next handle */
  701. }
  702. curlfds = nfds; /* number of internal file descriptors */
  703. nfds += extra_nfds; /* add the externally provided ones */
  704. if(nfds || extra_nfds) {
  705. ufds = malloc(nfds * sizeof(struct pollfd));
  706. if(!ufds)
  707. return CURLM_OUT_OF_MEMORY;
  708. }
  709. nfds = 0;
  710. /* only do the second loop if we found descriptors in the first stage run
  711. above */
  712. if(curlfds) {
  713. /* Add the curl handles to our pollfds first */
  714. data=multi->easyp;
  715. while(data) {
  716. bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
  717. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
  718. curl_socket_t s = CURL_SOCKET_BAD;
  719. if(bitmap & GETSOCK_READSOCK(i)) {
  720. ufds[nfds].fd = sockbunch[i];
  721. ufds[nfds].events = POLLIN;
  722. ++nfds;
  723. s = sockbunch[i];
  724. }
  725. if(bitmap & GETSOCK_WRITESOCK(i)) {
  726. ufds[nfds].fd = sockbunch[i];
  727. ufds[nfds].events = POLLOUT;
  728. ++nfds;
  729. s = sockbunch[i];
  730. }
  731. if(s == CURL_SOCKET_BAD) {
  732. break;
  733. }
  734. }
  735. data = data->next; /* check next handle */
  736. }
  737. }
  738. /* Add external file descriptions from poll-like struct curl_waitfd */
  739. for(i = 0; i < extra_nfds; i++) {
  740. ufds[nfds].fd = extra_fds[i].fd;
  741. ufds[nfds].events = 0;
  742. if(extra_fds[i].events & CURL_WAIT_POLLIN)
  743. ufds[nfds].events |= POLLIN;
  744. if(extra_fds[i].events & CURL_WAIT_POLLPRI)
  745. ufds[nfds].events |= POLLPRI;
  746. if(extra_fds[i].events & CURL_WAIT_POLLOUT)
  747. ufds[nfds].events |= POLLOUT;
  748. ++nfds;
  749. }
  750. if(nfds) {
  751. /* wait... */
  752. infof(data, "Curl_poll(%d ds, %d ms)\n", nfds, timeout_ms);
  753. i = Curl_poll(ufds, nfds, timeout_ms);
  754. if(i) {
  755. unsigned int j;
  756. /* copy revents results from the poll to the curl_multi_wait poll
  757. struct, the bit values of the actual underlying poll() implementation
  758. may not be the same as the ones in the public libcurl API! */
  759. for(j = 0; j < extra_nfds; j++) {
  760. unsigned short mask = 0;
  761. unsigned r = ufds[curlfds + j].revents;
  762. if(r & POLLIN)
  763. mask |= CURL_WAIT_POLLIN;
  764. if(r & POLLOUT)
  765. mask |= CURL_WAIT_POLLOUT;
  766. if(r & POLLPRI)
  767. mask |= CURL_WAIT_POLLPRI;
  768. extra_fds[j].revents = mask;
  769. }
  770. }
  771. }
  772. else
  773. i = 0;
  774. free(ufds);
  775. if(ret)
  776. *ret = i;
  777. return CURLM_OK;
  778. }
  779. /*
  780. * Curl_multi_connchanged() is called to tell that there is a connection in
  781. * this multi handle that has changed state (pipelining become possible, the
  782. * number of allowed streams changed or similar), and a subsequent use of this
  783. * multi handle should move CONNECT_PEND handles back to CONNECT to have them
  784. * retry.
  785. */
  786. void Curl_multi_connchanged(struct Curl_multi *multi)
  787. {
  788. multi->recheckstate = TRUE;
  789. }
  790. /*
  791. * multi_ischanged() is called
  792. *
  793. * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
  794. * => CONNECT action.
  795. *
  796. * Set 'clear' to TRUE to have it also clear the state variable.
  797. */
  798. static bool multi_ischanged(struct Curl_multi *multi, bool clear)
  799. {
  800. bool retval = multi->recheckstate;
  801. if(clear)
  802. multi->recheckstate = FALSE;
  803. return retval;
  804. }
  805. CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
  806. struct SessionHandle *data,
  807. struct connectdata *conn)
  808. {
  809. CURLMcode rc;
  810. rc = curl_multi_add_handle(multi, data);
  811. if(!rc) {
  812. struct SingleRequest *k = &data->req;
  813. /* pass in NULL for 'conn' here since we don't want to init the
  814. connection, only this transfer */
  815. Curl_init_do(data, NULL);
  816. /* take this handle to the perform state right away */
  817. multistate(data, CURLM_STATE_PERFORM);
  818. data->easy_conn = conn;
  819. k->keepon |= KEEP_RECV; /* setup to receive! */
  820. }
  821. return rc;
  822. }
  823. static CURLMcode multi_runsingle(struct Curl_multi *multi,
  824. struct timeval now,
  825. struct SessionHandle *data)
  826. {
  827. struct Curl_message *msg = NULL;
  828. bool connected;
  829. bool async;
  830. bool protocol_connect = FALSE;
  831. bool dophase_done = FALSE;
  832. bool done = FALSE;
  833. CURLMcode rc;
  834. CURLcode result = CURLE_OK;
  835. struct SingleRequest *k;
  836. long timeout_ms;
  837. int control;
  838. if(!GOOD_EASY_HANDLE(data))
  839. return CURLM_BAD_EASY_HANDLE;
  840. do {
  841. bool disconnect_conn = FALSE;
  842. rc = CURLM_OK;
  843. /* Handle the case when the pipe breaks, i.e., the connection
  844. we're using gets cleaned up and we're left with nothing. */
  845. if(data->state.pipe_broke) {
  846. infof(data, "Pipe broke: handle %p, url = %s\n",
  847. (void *)data, data->state.path);
  848. if(data->mstate < CURLM_STATE_COMPLETED) {
  849. /* Head back to the CONNECT state */
  850. multistate(data, CURLM_STATE_CONNECT);
  851. rc = CURLM_CALL_MULTI_PERFORM;
  852. result = CURLE_OK;
  853. }
  854. data->state.pipe_broke = FALSE;
  855. data->easy_conn = NULL;
  856. continue;
  857. }
  858. if(!data->easy_conn &&
  859. data->mstate > CURLM_STATE_CONNECT &&
  860. data->mstate < CURLM_STATE_DONE) {
  861. /* In all these states, the code will blindly access 'data->easy_conn'
  862. so this is precaution that it isn't NULL. And it silences static
  863. analyzers. */
  864. failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
  865. return CURLM_INTERNAL_ERROR;
  866. }
  867. if(multi_ischanged(multi, TRUE)) {
  868. DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n"));
  869. Curl_multi_process_pending_handles(multi);
  870. }
  871. if(data->easy_conn && data->mstate > CURLM_STATE_CONNECT &&
  872. data->mstate < CURLM_STATE_COMPLETED)
  873. /* Make sure we set the connection's current owner */
  874. data->easy_conn->data = data;
  875. if(data->easy_conn &&
  876. (data->mstate >= CURLM_STATE_CONNECT) &&
  877. (data->mstate < CURLM_STATE_COMPLETED)) {
  878. /* we need to wait for the connect state as only then is the start time
  879. stored, but we must not check already completed handles */
  880. timeout_ms = Curl_timeleft(data, &now,
  881. (data->mstate <= CURLM_STATE_WAITDO)?
  882. TRUE:FALSE);
  883. if(timeout_ms < 0) {
  884. /* Handle timed out */
  885. if(data->mstate == CURLM_STATE_WAITRESOLVE)
  886. failf(data, "Resolving timed out after %ld milliseconds",
  887. Curl_tvdiff(now, data->progress.t_startsingle));
  888. else if(data->mstate == CURLM_STATE_WAITCONNECT)
  889. failf(data, "Connection timed out after %ld milliseconds",
  890. Curl_tvdiff(now, data->progress.t_startsingle));
  891. else {
  892. k = &data->req;
  893. if(k->size != -1) {
  894. failf(data, "Operation timed out after %ld milliseconds with %"
  895. CURL_FORMAT_CURL_OFF_T " out of %"
  896. CURL_FORMAT_CURL_OFF_T " bytes received",
  897. Curl_tvdiff(k->now, data->progress.t_startsingle),
  898. k->bytecount, k->size);
  899. }
  900. else {
  901. failf(data, "Operation timed out after %ld milliseconds with %"
  902. CURL_FORMAT_CURL_OFF_T " bytes received",
  903. Curl_tvdiff(now, data->progress.t_startsingle),
  904. k->bytecount);
  905. }
  906. }
  907. /* Force connection closed if the connection has indeed been used */
  908. if(data->mstate > CURLM_STATE_DO) {
  909. connclose(data->easy_conn, "Disconnected with pending data");
  910. disconnect_conn = TRUE;
  911. }
  912. result = CURLE_OPERATION_TIMEDOUT;
  913. (void)Curl_done(&data->easy_conn, result, TRUE);
  914. /* Skip the statemachine and go directly to error handling section. */
  915. goto statemachine_end;
  916. }
  917. }
  918. switch(data->mstate) {
  919. case CURLM_STATE_INIT:
  920. /* init this transfer. */
  921. result=Curl_pretransfer(data);
  922. if(!result) {
  923. /* after init, go CONNECT */
  924. multistate(data, CURLM_STATE_CONNECT);
  925. Curl_pgrsTime(data, TIMER_STARTOP);
  926. rc = CURLM_CALL_MULTI_PERFORM;
  927. }
  928. break;
  929. case CURLM_STATE_CONNECT_PEND:
  930. /* We will stay here until there is a connection available. Then
  931. we try again in the CURLM_STATE_CONNECT state. */
  932. break;
  933. case CURLM_STATE_CONNECT:
  934. /* Connect. We want to get a connection identifier filled in. */
  935. Curl_pgrsTime(data, TIMER_STARTSINGLE);
  936. result = Curl_connect(data, &data->easy_conn,
  937. &async, &protocol_connect);
  938. if(CURLE_NO_CONNECTION_AVAILABLE == result) {
  939. /* There was no connection available. We will go to the pending
  940. state and wait for an available connection. */
  941. multistate(data, CURLM_STATE_CONNECT_PEND);
  942. /* add this handle to the list of connect-pending handles */
  943. if(!Curl_llist_insert_next(multi->pending, multi->pending->tail, data))
  944. result = CURLE_OUT_OF_MEMORY;
  945. else
  946. result = CURLE_OK;
  947. break;
  948. }
  949. if(!result) {
  950. /* Add this handle to the send or pend pipeline */
  951. result = Curl_add_handle_to_pipeline(data, data->easy_conn);
  952. if(result)
  953. disconnect_conn = TRUE;
  954. else {
  955. if(async)
  956. /* We're now waiting for an asynchronous name lookup */
  957. multistate(data, CURLM_STATE_WAITRESOLVE);
  958. else {
  959. /* after the connect has been sent off, go WAITCONNECT unless the
  960. protocol connect is already done and we can go directly to
  961. WAITDO or DO! */
  962. rc = CURLM_CALL_MULTI_PERFORM;
  963. if(protocol_connect)
  964. multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
  965. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  966. else {
  967. #ifndef CURL_DISABLE_HTTP
  968. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  969. multistate(data, CURLM_STATE_WAITPROXYCONNECT);
  970. else
  971. #endif
  972. multistate(data, CURLM_STATE_WAITCONNECT);
  973. }
  974. }
  975. }
  976. }
  977. break;
  978. case CURLM_STATE_WAITRESOLVE:
  979. /* awaiting an asynch name resolve to complete */
  980. {
  981. struct Curl_dns_entry *dns = NULL;
  982. struct connectdata *conn = data->easy_conn;
  983. /* check if we have the name resolved by now */
  984. dns = Curl_fetch_addr(conn, conn->host.name, (int)conn->port);
  985. if(dns) {
  986. #ifdef CURLRES_ASYNCH
  987. conn->async.dns = dns;
  988. conn->async.done = TRUE;
  989. #endif
  990. result = CURLE_OK;
  991. infof(data, "Hostname was found in DNS cache\n");
  992. }
  993. if(!dns)
  994. result = Curl_resolver_is_resolved(data->easy_conn, &dns);
  995. /* Update sockets here, because the socket(s) may have been
  996. closed and the application thus needs to be told, even if it
  997. is likely that the same socket(s) will again be used further
  998. down. If the name has not yet been resolved, it is likely
  999. that new sockets have been opened in an attempt to contact
  1000. another resolver. */
  1001. singlesocket(multi, data);
  1002. if(dns) {
  1003. /* Perform the next step in the connection phase, and then move on
  1004. to the WAITCONNECT state */
  1005. result = Curl_async_resolved(data->easy_conn, &protocol_connect);
  1006. if(result)
  1007. /* if Curl_async_resolved() returns failure, the connection struct
  1008. is already freed and gone */
  1009. data->easy_conn = NULL; /* no more connection */
  1010. else {
  1011. /* call again please so that we get the next socket setup */
  1012. rc = CURLM_CALL_MULTI_PERFORM;
  1013. if(protocol_connect)
  1014. multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
  1015. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  1016. else {
  1017. #ifndef CURL_DISABLE_HTTP
  1018. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  1019. multistate(data, CURLM_STATE_WAITPROXYCONNECT);
  1020. else
  1021. #endif
  1022. multistate(data, CURLM_STATE_WAITCONNECT);
  1023. }
  1024. }
  1025. }
  1026. if(result) {
  1027. /* failure detected */
  1028. disconnect_conn = TRUE;
  1029. break;
  1030. }
  1031. }
  1032. break;
  1033. #ifndef CURL_DISABLE_HTTP
  1034. case CURLM_STATE_WAITPROXYCONNECT:
  1035. /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
  1036. result = Curl_http_connect(data->easy_conn, &protocol_connect);
  1037. rc = CURLM_CALL_MULTI_PERFORM;
  1038. if(data->easy_conn->bits.proxy_connect_closed) {
  1039. /* connect back to proxy again */
  1040. result = CURLE_OK;
  1041. Curl_done(&data->easy_conn, CURLE_OK, FALSE);
  1042. multistate(data, CURLM_STATE_CONNECT);
  1043. }
  1044. else if(!result) {
  1045. if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE)
  1046. /* initiate protocol connect phase */
  1047. multistate(data, CURLM_STATE_SENDPROTOCONNECT);
  1048. }
  1049. break;
  1050. #endif
  1051. case CURLM_STATE_WAITCONNECT:
  1052. /* awaiting a completion of an asynch TCP connect */
  1053. result = Curl_is_connected(data->easy_conn, FIRSTSOCKET, &connected);
  1054. if(connected && !result) {
  1055. rc = CURLM_CALL_MULTI_PERFORM;
  1056. multistate(data, data->easy_conn->bits.tunnel_proxy?
  1057. CURLM_STATE_WAITPROXYCONNECT:
  1058. CURLM_STATE_SENDPROTOCONNECT);
  1059. }
  1060. else if(result) {
  1061. /* failure detected */
  1062. /* Just break, the cleaning up is handled all in one place */
  1063. disconnect_conn = TRUE;
  1064. break;
  1065. }
  1066. break;
  1067. case CURLM_STATE_SENDPROTOCONNECT:
  1068. result = Curl_protocol_connect(data->easy_conn, &protocol_connect);
  1069. if(!protocol_connect)
  1070. /* switch to waiting state */
  1071. multistate(data, CURLM_STATE_PROTOCONNECT);
  1072. else if(!result) {
  1073. /* protocol connect has completed, go WAITDO or DO */
  1074. multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
  1075. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  1076. rc = CURLM_CALL_MULTI_PERFORM;
  1077. }
  1078. else if(result) {
  1079. /* failure detected */
  1080. Curl_posttransfer(data);
  1081. Curl_done(&data->easy_conn, result, TRUE);
  1082. disconnect_conn = TRUE;
  1083. }
  1084. break;
  1085. case CURLM_STATE_PROTOCONNECT:
  1086. /* protocol-specific connect phase */
  1087. result = Curl_protocol_connecting(data->easy_conn, &protocol_connect);
  1088. if(!result && protocol_connect) {
  1089. /* after the connect has completed, go WAITDO or DO */
  1090. multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
  1091. CURLM_STATE_WAITDO:CURLM_STATE_DO);
  1092. rc = CURLM_CALL_MULTI_PERFORM;
  1093. }
  1094. else if(result) {
  1095. /* failure detected */
  1096. Curl_posttransfer(data);
  1097. Curl_done(&data->easy_conn, result, TRUE);
  1098. disconnect_conn = TRUE;
  1099. }
  1100. break;
  1101. case CURLM_STATE_WAITDO:
  1102. /* Wait for our turn to DO when we're pipelining requests */
  1103. if(Curl_pipeline_checkget_write(data, data->easy_conn)) {
  1104. /* Grabbed the channel */
  1105. multistate(data, CURLM_STATE_DO);
  1106. rc = CURLM_CALL_MULTI_PERFORM;
  1107. }
  1108. break;
  1109. case CURLM_STATE_DO:
  1110. if(data->set.connect_only) {
  1111. /* keep connection open for application to use the socket */
  1112. connkeep(data->easy_conn, "CONNECT_ONLY");
  1113. multistate(data, CURLM_STATE_DONE);
  1114. result = CURLE_OK;
  1115. rc = CURLM_CALL_MULTI_PERFORM;
  1116. }
  1117. else {
  1118. /* Perform the protocol's DO action */
  1119. result = Curl_do(&data->easy_conn, &dophase_done);
  1120. /* When Curl_do() returns failure, data->easy_conn might be NULL! */
  1121. if(!result) {
  1122. if(!dophase_done) {
  1123. /* some steps needed for wildcard matching */
  1124. if(data->set.wildcardmatch) {
  1125. struct WildcardData *wc = &data->wildcard;
  1126. if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
  1127. /* skip some states if it is important */
  1128. Curl_done(&data->easy_conn, CURLE_OK, FALSE);
  1129. multistate(data, CURLM_STATE_DONE);
  1130. rc = CURLM_CALL_MULTI_PERFORM;
  1131. break;
  1132. }
  1133. }
  1134. /* DO was not completed in one function call, we must continue
  1135. DOING... */
  1136. multistate(data, CURLM_STATE_DOING);
  1137. rc = CURLM_OK;
  1138. }
  1139. /* after DO, go DO_DONE... or DO_MORE */
  1140. else if(data->easy_conn->bits.do_more) {
  1141. /* we're supposed to do more, but we need to sit down, relax
  1142. and wait a little while first */
  1143. multistate(data, CURLM_STATE_DO_MORE);
  1144. rc = CURLM_OK;
  1145. }
  1146. else {
  1147. /* we're done with the DO, now DO_DONE */
  1148. multistate(data, CURLM_STATE_DO_DONE);
  1149. rc = CURLM_CALL_MULTI_PERFORM;
  1150. }
  1151. }
  1152. else if((CURLE_SEND_ERROR == result) &&
  1153. data->easy_conn->bits.reuse) {
  1154. /*
  1155. * In this situation, a connection that we were trying to use
  1156. * may have unexpectedly died. If possible, send the connection
  1157. * back to the CONNECT phase so we can try again.
  1158. */
  1159. char *newurl = NULL;
  1160. followtype follow=FOLLOW_NONE;
  1161. CURLcode drc;
  1162. bool retry = FALSE;
  1163. drc = Curl_retry_request(data->easy_conn, &newurl);
  1164. if(drc) {
  1165. /* a failure here pretty much implies an out of memory */
  1166. result = drc;
  1167. disconnect_conn = TRUE;
  1168. }
  1169. else
  1170. retry = (newurl)?TRUE:FALSE;
  1171. Curl_posttransfer(data);
  1172. drc = Curl_done(&data->easy_conn, result, FALSE);
  1173. /* When set to retry the connection, we must to go back to
  1174. * the CONNECT state */
  1175. if(retry) {
  1176. if(!drc || (drc == CURLE_SEND_ERROR)) {
  1177. follow = FOLLOW_RETRY;
  1178. drc = Curl_follow(data, newurl, follow);
  1179. if(!drc) {
  1180. multistate(data, CURLM_STATE_CONNECT);
  1181. rc = CURLM_CALL_MULTI_PERFORM;
  1182. result = CURLE_OK;
  1183. }
  1184. else {
  1185. /* Follow failed */
  1186. result = drc;
  1187. free(newurl);
  1188. }
  1189. }
  1190. else {
  1191. /* done didn't return OK or SEND_ERROR */
  1192. result = drc;
  1193. free(newurl);
  1194. }
  1195. }
  1196. else {
  1197. /* Have error handler disconnect conn if we can't retry */
  1198. disconnect_conn = TRUE;
  1199. free(newurl);
  1200. }
  1201. }
  1202. else {
  1203. /* failure detected */
  1204. Curl_posttransfer(data);
  1205. if(data->easy_conn)
  1206. Curl_done(&data->easy_conn, result, FALSE);
  1207. disconnect_conn = TRUE;
  1208. }
  1209. }
  1210. break;
  1211. case CURLM_STATE_DOING:
  1212. /* we continue DOING until the DO phase is complete */
  1213. result = Curl_protocol_doing(data->easy_conn,
  1214. &dophase_done);
  1215. if(!result) {
  1216. if(dophase_done) {
  1217. /* after DO, go DO_DONE or DO_MORE */
  1218. multistate(data, data->easy_conn->bits.do_more?
  1219. CURLM_STATE_DO_MORE:
  1220. CURLM_STATE_DO_DONE);
  1221. rc = CURLM_CALL_MULTI_PERFORM;
  1222. } /* dophase_done */
  1223. }
  1224. else {
  1225. /* failure detected */
  1226. Curl_posttransfer(data);
  1227. Curl_done(&data->easy_conn, result, FALSE);
  1228. disconnect_conn = TRUE;
  1229. }
  1230. break;
  1231. case CURLM_STATE_DO_MORE:
  1232. /*
  1233. * When we are connected, DO MORE and then go DO_DONE
  1234. */
  1235. result = Curl_do_more(data->easy_conn, &control);
  1236. /* No need to remove this handle from the send pipeline here since that
  1237. is done in Curl_done() */
  1238. if(!result) {
  1239. if(control) {
  1240. /* if positive, advance to DO_DONE
  1241. if negative, go back to DOING */
  1242. multistate(data, control==1?
  1243. CURLM_STATE_DO_DONE:
  1244. CURLM_STATE_DOING);
  1245. rc = CURLM_CALL_MULTI_PERFORM;
  1246. }
  1247. else
  1248. /* stay in DO_MORE */
  1249. rc = CURLM_OK;
  1250. }
  1251. else {
  1252. /* failure detected */
  1253. Curl_posttransfer(data);
  1254. Curl_done(&data->easy_conn, result, FALSE);
  1255. disconnect_conn = TRUE;
  1256. }
  1257. break;
  1258. case CURLM_STATE_DO_DONE:
  1259. /* Move ourselves from the send to recv pipeline */
  1260. Curl_move_handle_from_send_to_recv_pipe(data, data->easy_conn);
  1261. /* Check if we can move pending requests to send pipe */
  1262. Curl_multi_process_pending_handles(multi);
  1263. /* Only perform the transfer if there's a good socket to work with.
  1264. Having both BAD is a signal to skip immediately to DONE */
  1265. if((data->easy_conn->sockfd != CURL_SOCKET_BAD) ||
  1266. (data->easy_conn->writesockfd != CURL_SOCKET_BAD))
  1267. multistate(data, CURLM_STATE_WAITPERFORM);
  1268. else
  1269. multistate(data, CURLM_STATE_DONE);
  1270. rc = CURLM_CALL_MULTI_PERFORM;
  1271. break;
  1272. case CURLM_STATE_WAITPERFORM:
  1273. /* Wait for our turn to PERFORM */
  1274. if(Curl_pipeline_checkget_read(data, data->easy_conn)) {
  1275. /* Grabbed the channel */
  1276. multistate(data, CURLM_STATE_PERFORM);
  1277. rc = CURLM_CALL_MULTI_PERFORM;
  1278. }
  1279. break;
  1280. case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
  1281. /* if both rates are within spec, resume transfer */
  1282. if(Curl_pgrsUpdate(data->easy_conn))
  1283. result = CURLE_ABORTED_BY_CALLBACK;
  1284. else
  1285. result = Curl_speedcheck(data, now);
  1286. if(( (data->set.max_send_speed == 0) ||
  1287. (data->progress.ulspeed < data->set.max_send_speed )) &&
  1288. ( (data->set.max_recv_speed == 0) ||
  1289. (data->progress.dlspeed < data->set.max_recv_speed)))
  1290. multistate(data, CURLM_STATE_PERFORM);
  1291. break;
  1292. case CURLM_STATE_PERFORM:
  1293. {
  1294. char *newurl = NULL;
  1295. bool retry = FALSE;
  1296. /* check if over send speed */
  1297. if((data->set.max_send_speed > 0) &&
  1298. (data->progress.ulspeed > data->set.max_send_speed)) {
  1299. int buffersize;
  1300. multistate(data, CURLM_STATE_TOOFAST);
  1301. /* calculate upload rate-limitation timeout. */
  1302. buffersize = (int)(data->set.buffer_size ?
  1303. data->set.buffer_size : BUFSIZE);
  1304. timeout_ms = Curl_sleep_time(data->set.max_send_speed,
  1305. data->progress.ulspeed, buffersize);
  1306. Curl_expire_latest(data, timeout_ms);
  1307. break;
  1308. }
  1309. /* check if over recv speed */
  1310. if((data->set.max_recv_speed > 0) &&
  1311. (data->progress.dlspeed > data->set.max_recv_speed)) {
  1312. int buffersize;
  1313. multistate(data, CURLM_STATE_TOOFAST);
  1314. /* Calculate download rate-limitation timeout. */
  1315. buffersize = (int)(data->set.buffer_size ?
  1316. data->set.buffer_size : BUFSIZE);
  1317. timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
  1318. data->progress.dlspeed, buffersize);
  1319. Curl_expire_latest(data, timeout_ms);
  1320. break;
  1321. }
  1322. /* read/write data if it is ready to do so */
  1323. result = Curl_readwrite(data->easy_conn, data, &done);
  1324. k = &data->req;
  1325. if(!(k->keepon & KEEP_RECV))
  1326. /* We're done receiving */
  1327. Curl_pipeline_leave_read(data->easy_conn);
  1328. if(!(k->keepon & KEEP_SEND))
  1329. /* We're done sending */
  1330. Curl_pipeline_leave_write(data->easy_conn);
  1331. if(done || (result == CURLE_RECV_ERROR)) {
  1332. /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
  1333. * condition and the server closed the re-used connection exactly when
  1334. * we wanted to use it, so figure out if that is indeed the case.
  1335. */
  1336. CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
  1337. if(!ret)
  1338. retry = (newurl)?TRUE:FALSE;
  1339. if(retry) {
  1340. /* if we are to retry, set the result to OK and consider the
  1341. request as done */
  1342. result = CURLE_OK;
  1343. done = TRUE;
  1344. }
  1345. }
  1346. if(result) {
  1347. /*
  1348. * The transfer phase returned error, we mark the connection to get
  1349. * closed to prevent being re-used. This is because we can't possibly
  1350. * know if the connection is in a good shape or not now. Unless it is
  1351. * a protocol which uses two "channels" like FTP, as then the error
  1352. * happened in the data connection.
  1353. */
  1354. if(!(data->easy_conn->handler->flags & PROTOPT_DUAL))
  1355. connclose(data->easy_conn, "Transfer returned error");
  1356. Curl_posttransfer(data);
  1357. Curl_done(&data->easy_conn, result, FALSE);
  1358. }
  1359. else if(done) {
  1360. followtype follow=FOLLOW_NONE;
  1361. /* call this even if the readwrite function returned error */
  1362. Curl_posttransfer(data);
  1363. /* we're no longer receiving */
  1364. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1365. /* expire the new receiving pipeline head */
  1366. if(data->easy_conn->recv_pipe->head)
  1367. Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 1);
  1368. /* Check if we can move pending requests to send pipe */
  1369. Curl_multi_process_pending_handles(multi);
  1370. /* When we follow redirects or is set to retry the connection, we must
  1371. to go back to the CONNECT state */
  1372. if(data->req.newurl || retry) {
  1373. if(!retry) {
  1374. /* if the URL is a follow-location and not just a retried request
  1375. then figure out the URL here */
  1376. free(newurl);
  1377. newurl = data->req.newurl;
  1378. data->req.newurl = NULL;
  1379. follow = FOLLOW_REDIR;
  1380. }
  1381. else
  1382. follow = FOLLOW_RETRY;
  1383. result = Curl_done(&data->easy_conn, CURLE_OK, FALSE);
  1384. if(!result) {
  1385. result = Curl_follow(data, newurl, follow);
  1386. if(!result) {
  1387. multistate(data, CURLM_STATE_CONNECT);
  1388. rc = CURLM_CALL_MULTI_PERFORM;
  1389. newurl = NULL; /* handed over the memory ownership to
  1390. Curl_follow(), make sure we don't free() it
  1391. here */
  1392. }
  1393. }
  1394. }
  1395. else {
  1396. /* after the transfer is done, go DONE */
  1397. /* but first check to see if we got a location info even though we're
  1398. not following redirects */
  1399. if(data->req.location) {
  1400. free(newurl);
  1401. newurl = data->req.location;
  1402. data->req.location = NULL;
  1403. result = Curl_follow(data, newurl, FOLLOW_FAKE);
  1404. if(!result)
  1405. newurl = NULL; /* allocation was handed over Curl_follow() */
  1406. else
  1407. disconnect_conn = TRUE;
  1408. }
  1409. multistate(data, CURLM_STATE_DONE);
  1410. rc = CURLM_CALL_MULTI_PERFORM;
  1411. }
  1412. }
  1413. free(newurl);
  1414. break;
  1415. }
  1416. case CURLM_STATE_DONE:
  1417. /* this state is highly transient, so run another loop after this */
  1418. rc = CURLM_CALL_MULTI_PERFORM;
  1419. if(data->easy_conn) {
  1420. CURLcode res;
  1421. /* Remove ourselves from the receive pipeline, if we are there. */
  1422. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1423. /* Check if we can move pending requests to send pipe */
  1424. Curl_multi_process_pending_handles(multi);
  1425. /* post-transfer command */
  1426. res = Curl_done(&data->easy_conn, result, FALSE);
  1427. /* allow a previously set error code take precedence */
  1428. if(!result)
  1429. result = res;
  1430. /*
  1431. * If there are other handles on the pipeline, Curl_done won't set
  1432. * easy_conn to NULL. In such a case, curl_multi_remove_handle() can
  1433. * access free'd data, if the connection is free'd and the handle
  1434. * removed before we perform the processing in CURLM_STATE_COMPLETED
  1435. */
  1436. if(data->easy_conn)
  1437. data->easy_conn = NULL;
  1438. }
  1439. if(data->set.wildcardmatch) {
  1440. if(data->wildcard.state != CURLWC_DONE) {
  1441. /* if a wildcard is set and we are not ending -> lets start again
  1442. with CURLM_STATE_INIT */
  1443. multistate(data, CURLM_STATE_INIT);
  1444. break;
  1445. }
  1446. }
  1447. /* after we have DONE what we're supposed to do, go COMPLETED, and
  1448. it doesn't matter what the Curl_done() returned! */
  1449. multistate(data, CURLM_STATE_COMPLETED);
  1450. break;
  1451. case CURLM_STATE_COMPLETED:
  1452. /* this is a completed transfer, it is likely to still be connected */
  1453. /* This node should be delinked from the list now and we should post
  1454. an information message that we are complete. */
  1455. /* Important: reset the conn pointer so that we don't point to memory
  1456. that could be freed anytime */
  1457. data->easy_conn = NULL;
  1458. Curl_expire(data, 0); /* stop all timers */
  1459. break;
  1460. case CURLM_STATE_MSGSENT:
  1461. data->result = result;
  1462. return CURLM_OK; /* do nothing */
  1463. default:
  1464. return CURLM_INTERNAL_ERROR;
  1465. }
  1466. statemachine_end:
  1467. if(data->mstate < CURLM_STATE_COMPLETED) {
  1468. if(result) {
  1469. /*
  1470. * If an error was returned, and we aren't in completed state now,
  1471. * then we go to completed and consider this transfer aborted.
  1472. */
  1473. /* NOTE: no attempt to disconnect connections must be made
  1474. in the case blocks above - cleanup happens only here */
  1475. data->state.pipe_broke = FALSE;
  1476. /* Check if we can move pending requests to send pipe */
  1477. Curl_multi_process_pending_handles(multi);
  1478. if(data->easy_conn) {
  1479. /* if this has a connection, unsubscribe from the pipelines */
  1480. Curl_pipeline_leave_write(data->easy_conn);
  1481. Curl_pipeline_leave_read(data->easy_conn);
  1482. Curl_removeHandleFromPipeline(data, data->easy_conn->send_pipe);
  1483. Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
  1484. if(disconnect_conn) {
  1485. /* Don't attempt to send data over a connection that timed out */
  1486. bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
  1487. /* disconnect properly */
  1488. Curl_disconnect(data->easy_conn, dead_connection);
  1489. /* This is where we make sure that the easy_conn pointer is reset.
  1490. We don't have to do this in every case block above where a
  1491. failure is detected */
  1492. data->easy_conn = NULL;
  1493. }
  1494. }
  1495. else if(data->mstate == CURLM_STATE_CONNECT) {
  1496. /* Curl_connect() failed */
  1497. (void)Curl_posttransfer(data);
  1498. }
  1499. multistate(data, CURLM_STATE_COMPLETED);
  1500. }
  1501. /* if there's still a connection to use, call the progress function */
  1502. else if(data->easy_conn && Curl_pgrsUpdate(data->easy_conn)) {
  1503. /* aborted due to progress callback return code must close the
  1504. connection */
  1505. result = CURLE_ABORTED_BY_CALLBACK;
  1506. connclose(data->easy_conn, "Aborted by callback");
  1507. /* if not yet in DONE state, go there, otherwise COMPLETED */
  1508. multistate(data, (data->mstate < CURLM_STATE_DONE)?
  1509. CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
  1510. rc = CURLM_CALL_MULTI_PERFORM;
  1511. }
  1512. }
  1513. if(CURLM_STATE_COMPLETED == data->mstate) {
  1514. /* now fill in the Curl_message with this info */
  1515. msg = &data->msg;
  1516. msg->extmsg.msg = CURLMSG_DONE;
  1517. msg->extmsg.easy_handle = data;
  1518. msg->extmsg.data.result = result;
  1519. rc = multi_addmsg(multi, msg);
  1520. multistate(data, CURLM_STATE_MSGSENT);
  1521. }
  1522. } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
  1523. data->result = result;
  1524. return rc;
  1525. }
  1526. CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles)
  1527. {
  1528. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1529. struct SessionHandle *data;
  1530. CURLMcode returncode=CURLM_OK;
  1531. struct Curl_tree *t;
  1532. struct timeval now = Curl_tvnow();
  1533. if(!GOOD_MULTI_HANDLE(multi))
  1534. return CURLM_BAD_HANDLE;
  1535. data=multi->easyp;
  1536. while(data) {
  1537. CURLMcode result;
  1538. struct WildcardData *wc = &data->wildcard;
  1539. SIGPIPE_VARIABLE(pipe_st);
  1540. if(data->set.wildcardmatch) {
  1541. if(!wc->filelist) {
  1542. CURLcode ret = Curl_wildcard_init(wc); /* init wildcard structures */
  1543. if(ret)
  1544. return CURLM_OUT_OF_MEMORY;
  1545. }
  1546. }
  1547. sigpipe_ignore(data, &pipe_st);
  1548. result = multi_runsingle(multi, now, data);
  1549. sigpipe_restore(&pipe_st);
  1550. if(data->set.wildcardmatch) {
  1551. /* destruct wildcard structures if it is needed */
  1552. if(wc->state == CURLWC_DONE || result)
  1553. Curl_wildcard_dtor(wc);
  1554. }
  1555. if(result)
  1556. returncode = result;
  1557. data = data->next; /* operate on next handle */
  1558. }
  1559. /*
  1560. * Simply remove all expired timers from the splay since handles are dealt
  1561. * with unconditionally by this function and curl_multi_timeout() requires
  1562. * that already passed/handled expire times are removed from the splay.
  1563. *
  1564. * It is important that the 'now' value is set at the entry of this function
  1565. * and not for the current time as it may have ticked a little while since
  1566. * then and then we risk this loop to remove timers that actually have not
  1567. * been handled!
  1568. */
  1569. do {
  1570. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  1571. if(t)
  1572. /* the removed may have another timeout in queue */
  1573. (void)add_next_timeout(now, multi, t->payload);
  1574. } while(t);
  1575. *running_handles = multi->num_alive;
  1576. if(CURLM_OK >= returncode)
  1577. update_timer(multi);
  1578. return returncode;
  1579. }
  1580. static void close_all_connections(struct Curl_multi *multi)
  1581. {
  1582. struct connectdata *conn;
  1583. conn = Curl_conncache_find_first_connection(&multi->conn_cache);
  1584. while(conn) {
  1585. SIGPIPE_VARIABLE(pipe_st);
  1586. conn->data = multi->closure_handle;
  1587. sigpipe_ignore(conn->data, &pipe_st);
  1588. /* This will remove the connection from the cache */
  1589. (void)Curl_disconnect(conn, FALSE);
  1590. sigpipe_restore(&pipe_st);
  1591. conn = Curl_conncache_find_first_connection(&multi->conn_cache);
  1592. }
  1593. }
  1594. CURLMcode curl_multi_cleanup(CURLM *multi_handle)
  1595. {
  1596. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1597. struct SessionHandle *data;
  1598. struct SessionHandle *nextdata;
  1599. if(GOOD_MULTI_HANDLE(multi)) {
  1600. bool restore_pipe = FALSE;
  1601. SIGPIPE_VARIABLE(pipe_st);
  1602. multi->type = 0; /* not good anymore */
  1603. /* Close all the connections in the connection cache */
  1604. close_all_connections(multi);
  1605. if(multi->closure_handle) {
  1606. sigpipe_ignore(multi->closure_handle, &pipe_st);
  1607. restore_pipe = TRUE;
  1608. multi->closure_handle->dns.hostcache = &multi->hostcache;
  1609. Curl_hostcache_clean(multi->closure_handle,
  1610. multi->closure_handle->dns.hostcache);
  1611. Curl_close(multi->closure_handle);
  1612. }
  1613. Curl_hash_destroy(&multi->sockhash);
  1614. Curl_conncache_destroy(&multi->conn_cache);
  1615. Curl_llist_destroy(multi->msglist, NULL);
  1616. Curl_llist_destroy(multi->pending, NULL);
  1617. /* remove all easy handles */
  1618. data = multi->easyp;
  1619. while(data) {
  1620. nextdata=data->next;
  1621. if(data->dns.hostcachetype == HCACHE_MULTI) {
  1622. /* clear out the usage of the shared DNS cache */
  1623. Curl_hostcache_clean(data, data->dns.hostcache);
  1624. data->dns.hostcache = NULL;
  1625. data->dns.hostcachetype = HCACHE_NONE;
  1626. }
  1627. /* Clear the pointer to the connection cache */
  1628. data->state.conn_cache = NULL;
  1629. data->multi = NULL; /* clear the association */
  1630. data = nextdata;
  1631. }
  1632. Curl_hash_destroy(&multi->hostcache);
  1633. /* Free the blacklists by setting them to NULL */
  1634. Curl_pipeline_set_site_blacklist(NULL, &multi->pipelining_site_bl);
  1635. Curl_pipeline_set_server_blacklist(NULL, &multi->pipelining_server_bl);
  1636. free(multi);
  1637. if(restore_pipe)
  1638. sigpipe_restore(&pipe_st);
  1639. return CURLM_OK;
  1640. }
  1641. else
  1642. return CURLM_BAD_HANDLE;
  1643. }
  1644. /*
  1645. * curl_multi_info_read()
  1646. *
  1647. * This function is the primary way for a multi/multi_socket application to
  1648. * figure out if a transfer has ended. We MUST make this function as fast as
  1649. * possible as it will be polled frequently and we MUST NOT scan any lists in
  1650. * here to figure out things. We must scale fine to thousands of handles and
  1651. * beyond. The current design is fully O(1).
  1652. */
  1653. CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue)
  1654. {
  1655. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  1656. struct Curl_message *msg;
  1657. *msgs_in_queue = 0; /* default to none */
  1658. if(GOOD_MULTI_HANDLE(multi) && Curl_llist_count(multi->msglist)) {
  1659. /* there is one or more messages in the list */
  1660. struct curl_llist_element *e;
  1661. /* extract the head of the list to return */
  1662. e = multi->msglist->head;
  1663. msg = e->ptr;
  1664. /* remove the extracted entry */
  1665. Curl_llist_remove(multi->msglist, e, NULL);
  1666. *msgs_in_queue = curlx_uztosi(Curl_llist_count(multi->msglist));
  1667. return &msg->extmsg;
  1668. }
  1669. else
  1670. return NULL;
  1671. }
  1672. /*
  1673. * singlesocket() checks what sockets we deal with and their "action state"
  1674. * and if we have a different state in any of those sockets from last time we
  1675. * call the callback accordingly.
  1676. */
  1677. static void singlesocket(struct Curl_multi *multi,
  1678. struct SessionHandle *data)
  1679. {
  1680. curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
  1681. int i;
  1682. struct Curl_sh_entry *entry;
  1683. curl_socket_t s;
  1684. int num;
  1685. unsigned int curraction;
  1686. bool remove_sock_from_hash;
  1687. for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++)
  1688. socks[i] = CURL_SOCKET_BAD;
  1689. /* Fill in the 'current' struct with the state as it is now: what sockets to
  1690. supervise and for what actions */
  1691. curraction = multi_getsock(data, socks, MAX_SOCKSPEREASYHANDLE);
  1692. /* We have 0 .. N sockets already and we get to know about the 0 .. M
  1693. sockets we should have from now on. Detect the differences, remove no
  1694. longer supervised ones and add new ones */
  1695. /* walk over the sockets we got right now */
  1696. for(i=0; (i< MAX_SOCKSPEREASYHANDLE) &&
  1697. (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
  1698. i++) {
  1699. int action = CURL_POLL_NONE;
  1700. s = socks[i];
  1701. /* get it from the hash */
  1702. entry = Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s));
  1703. if(curraction & GETSOCK_READSOCK(i))
  1704. action |= CURL_POLL_IN;
  1705. if(curraction & GETSOCK_WRITESOCK(i))
  1706. action |= CURL_POLL_OUT;
  1707. if(entry) {
  1708. /* yeps, already present so check if it has the same action set */
  1709. if(entry->action == action)
  1710. /* same, continue */
  1711. continue;
  1712. }
  1713. else {
  1714. /* this is a socket we didn't have before, add it! */
  1715. entry = sh_addentry(&multi->sockhash, s, data);
  1716. if(!entry)
  1717. /* fatal */
  1718. return;
  1719. }
  1720. /* we know (entry != NULL) at this point, see the logic above */
  1721. if(multi->socket_cb)
  1722. multi->socket_cb(data,
  1723. s,
  1724. action,
  1725. multi->socket_userp,
  1726. entry->socketp);
  1727. entry->action = action; /* store the current action state */
  1728. }
  1729. num = i; /* number of sockets */
  1730. /* when we've walked over all the sockets we should have right now, we must
  1731. make sure to detect sockets that are removed */
  1732. for(i=0; i< data->numsocks; i++) {
  1733. int j;
  1734. s = data->sockets[i];
  1735. for(j=0; j<num; j++) {
  1736. if(s == socks[j]) {
  1737. /* this is still supervised */
  1738. s = CURL_SOCKET_BAD;
  1739. break;
  1740. }
  1741. }
  1742. if(s != CURL_SOCKET_BAD) {
  1743. /* this socket has been removed. Tell the app to remove it */
  1744. remove_sock_from_hash = TRUE;
  1745. entry = Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s));
  1746. if(entry) {
  1747. /* check if the socket to be removed serves a connection which has
  1748. other easy-s in a pipeline. In this case the socket should not be
  1749. removed. */
  1750. struct connectdata *easy_conn = data->easy_conn;
  1751. if(easy_conn) {
  1752. if(easy_conn->recv_pipe && easy_conn->recv_pipe->size > 1) {
  1753. /* the handle should not be removed from the pipe yet */
  1754. remove_sock_from_hash = FALSE;
  1755. /* Update the sockhash entry to instead point to the next in line
  1756. for the recv_pipe, or the first (in case this particular easy
  1757. isn't already) */
  1758. if(entry->easy == data) {
  1759. if(Curl_recvpipe_head(data, easy_conn))
  1760. entry->easy = easy_conn->recv_pipe->head->next->ptr;
  1761. else
  1762. entry->easy = easy_conn->recv_pipe->head->ptr;
  1763. }
  1764. }
  1765. if(easy_conn->send_pipe && easy_conn->send_pipe->size > 1) {
  1766. /* the handle should not be removed from the pipe yet */
  1767. remove_sock_from_hash = FALSE;
  1768. /* Update the sockhash entry to instead point to the next in line
  1769. for the send_pipe, or the first (in case this particular easy
  1770. isn't already) */
  1771. if(entry->easy == data) {
  1772. if(Curl_sendpipe_head(data, easy_conn))
  1773. entry->easy = easy_conn->send_pipe->head->next->ptr;
  1774. else
  1775. entry->easy = easy_conn->send_pipe->head->ptr;
  1776. }
  1777. }
  1778. /* Don't worry about overwriting recv_pipe head with send_pipe_head,
  1779. when action will be asked on the socket (see multi_socket()), the
  1780. head of the correct pipe will be taken according to the
  1781. action. */
  1782. }
  1783. }
  1784. else
  1785. /* just a precaution, this socket really SHOULD be in the hash already
  1786. but in case it isn't, we don't have to tell the app to remove it
  1787. either since it never got to know about it */
  1788. remove_sock_from_hash = FALSE;
  1789. if(remove_sock_from_hash) {
  1790. /* in this case 'entry' is always non-NULL */
  1791. if(multi->socket_cb)
  1792. multi->socket_cb(data,
  1793. s,
  1794. CURL_POLL_REMOVE,
  1795. multi->socket_userp,
  1796. entry->socketp);
  1797. sh_delentry(&multi->sockhash, s);
  1798. }
  1799. }
  1800. }
  1801. memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
  1802. data->numsocks = num;
  1803. }
  1804. /*
  1805. * Curl_multi_closed()
  1806. *
  1807. * Used by the connect code to tell the multi_socket code that one of the
  1808. * sockets we were using is about to be closed. This function will then
  1809. * remove it from the sockethash for this handle to make the multi_socket API
  1810. * behave properly, especially for the case when libcurl will create another
  1811. * socket again and it gets the same file descriptor number.
  1812. */
  1813. void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
  1814. {
  1815. struct Curl_multi *multi = conn->data->multi;
  1816. if(multi) {
  1817. /* this is set if this connection is part of a handle that is added to
  1818. a multi handle, and only then this is necessary */
  1819. struct Curl_sh_entry *entry =
  1820. Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s));
  1821. if(entry) {
  1822. if(multi->socket_cb)
  1823. multi->socket_cb(conn->data, s, CURL_POLL_REMOVE,
  1824. multi->socket_userp,
  1825. entry->socketp);
  1826. /* now remove it from the socket hash */
  1827. sh_delentry(&multi->sockhash, s);
  1828. }
  1829. }
  1830. }
  1831. /*
  1832. * add_next_timeout()
  1833. *
  1834. * Each SessionHandle has a list of timeouts. The add_next_timeout() is called
  1835. * when it has just been removed from the splay tree because the timeout has
  1836. * expired. This function is then to advance in the list to pick the next
  1837. * timeout to use (skip the already expired ones) and add this node back to
  1838. * the splay tree again.
  1839. *
  1840. * The splay tree only has each sessionhandle as a single node and the nearest
  1841. * timeout is used to sort it on.
  1842. */
  1843. static CURLMcode add_next_timeout(struct timeval now,
  1844. struct Curl_multi *multi,
  1845. struct SessionHandle *d)
  1846. {
  1847. struct timeval *tv = &d->state.expiretime;
  1848. struct curl_llist *list = d->state.timeoutlist;
  1849. struct curl_llist_element *e;
  1850. /* move over the timeout list for this specific handle and remove all
  1851. timeouts that are now passed tense and store the next pending
  1852. timeout in *tv */
  1853. for(e = list->head; e; ) {
  1854. struct curl_llist_element *n = e->next;
  1855. long diff = curlx_tvdiff(*(struct timeval *)e->ptr, now);
  1856. if(diff <= 0)
  1857. /* remove outdated entry */
  1858. Curl_llist_remove(list, e, NULL);
  1859. else
  1860. /* the list is sorted so get out on the first mismatch */
  1861. break;
  1862. e = n;
  1863. }
  1864. e = list->head;
  1865. if(!e) {
  1866. /* clear the expire times within the handles that we remove from the
  1867. splay tree */
  1868. tv->tv_sec = 0;
  1869. tv->tv_usec = 0;
  1870. }
  1871. else {
  1872. /* copy the first entry to 'tv' */
  1873. memcpy(tv, e->ptr, sizeof(*tv));
  1874. /* remove first entry from list */
  1875. Curl_llist_remove(list, e, NULL);
  1876. /* insert this node again into the splay */
  1877. multi->timetree = Curl_splayinsert(*tv, multi->timetree,
  1878. &d->state.timenode);
  1879. }
  1880. return CURLM_OK;
  1881. }
  1882. static CURLMcode multi_socket(struct Curl_multi *multi,
  1883. bool checkall,
  1884. curl_socket_t s,
  1885. int ev_bitmask,
  1886. int *running_handles)
  1887. {
  1888. CURLMcode result = CURLM_OK;
  1889. struct SessionHandle *data = NULL;
  1890. struct Curl_tree *t;
  1891. struct timeval now = Curl_tvnow();
  1892. if(checkall) {
  1893. /* *perform() deals with running_handles on its own */
  1894. result = curl_multi_perform(multi, running_handles);
  1895. /* walk through each easy handle and do the socket state change magic
  1896. and callbacks */
  1897. if(result != CURLM_BAD_HANDLE) {
  1898. data=multi->easyp;
  1899. while(data) {
  1900. singlesocket(multi, data);
  1901. data = data->next;
  1902. }
  1903. }
  1904. /* or should we fall-through and do the timer-based stuff? */
  1905. return result;
  1906. }
  1907. else if(s != CURL_SOCKET_TIMEOUT) {
  1908. struct Curl_sh_entry *entry =
  1909. Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s));
  1910. if(!entry)
  1911. /* Unmatched socket, we can't act on it but we ignore this fact. In
  1912. real-world tests it has been proved that libevent can in fact give
  1913. the application actions even though the socket was just previously
  1914. asked to get removed, so thus we better survive stray socket actions
  1915. and just move on. */
  1916. ;
  1917. else {
  1918. SIGPIPE_VARIABLE(pipe_st);
  1919. data = entry->easy;
  1920. if(data->magic != CURLEASY_MAGIC_NUMBER)
  1921. /* bad bad bad bad bad bad bad */
  1922. return CURLM_INTERNAL_ERROR;
  1923. /* If the pipeline is enabled, take the handle which is in the head of
  1924. the pipeline. If we should write into the socket, take the send_pipe
  1925. head. If we should read from the socket, take the recv_pipe head. */
  1926. if(data->easy_conn) {
  1927. if((ev_bitmask & CURL_POLL_OUT) &&
  1928. data->easy_conn->send_pipe &&
  1929. data->easy_conn->send_pipe->head)
  1930. data = data->easy_conn->send_pipe->head->ptr;
  1931. else if((ev_bitmask & CURL_POLL_IN) &&
  1932. data->easy_conn->recv_pipe &&
  1933. data->easy_conn->recv_pipe->head)
  1934. data = data->easy_conn->recv_pipe->head->ptr;
  1935. }
  1936. if(data->easy_conn &&
  1937. !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
  1938. /* set socket event bitmask if they're not locked */
  1939. data->easy_conn->cselect_bits = ev_bitmask;
  1940. sigpipe_ignore(data, &pipe_st);
  1941. result = multi_runsingle(multi, now, data);
  1942. sigpipe_restore(&pipe_st);
  1943. if(data->easy_conn &&
  1944. !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
  1945. /* clear the bitmask only if not locked */
  1946. data->easy_conn->cselect_bits = 0;
  1947. if(CURLM_OK >= result)
  1948. /* get the socket(s) and check if the state has been changed since
  1949. last */
  1950. singlesocket(multi, data);
  1951. /* Now we fall-through and do the timer-based stuff, since we don't want
  1952. to force the user to have to deal with timeouts as long as at least
  1953. one connection in fact has traffic. */
  1954. data = NULL; /* set data to NULL again to avoid calling
  1955. multi_runsingle() in case there's no need to */
  1956. now = Curl_tvnow(); /* get a newer time since the multi_runsingle() loop
  1957. may have taken some time */
  1958. }
  1959. }
  1960. else {
  1961. /* Asked to run due to time-out. Clear the 'lastcall' variable to force
  1962. update_timer() to trigger a callback to the app again even if the same
  1963. timeout is still the one to run after this call. That handles the case
  1964. when the application asks libcurl to run the timeout prematurely. */
  1965. memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
  1966. }
  1967. /*
  1968. * The loop following here will go on as long as there are expire-times left
  1969. * to process in the splay and 'data' will be re-assigned for every expired
  1970. * handle we deal with.
  1971. */
  1972. do {
  1973. /* the first loop lap 'data' can be NULL */
  1974. if(data) {
  1975. SIGPIPE_VARIABLE(pipe_st);
  1976. sigpipe_ignore(data, &pipe_st);
  1977. result = multi_runsingle(multi, now, data);
  1978. sigpipe_restore(&pipe_st);
  1979. if(CURLM_OK >= result)
  1980. /* get the socket(s) and check if the state has been changed since
  1981. last */
  1982. singlesocket(multi, data);
  1983. }
  1984. /* Check if there's one (more) expired timer to deal with! This function
  1985. extracts a matching node if there is one */
  1986. multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
  1987. if(t) {
  1988. data = t->payload; /* assign this for next loop */
  1989. (void)add_next_timeout(now, multi, t->payload);
  1990. }
  1991. } while(t);
  1992. *running_handles = multi->num_alive;
  1993. return result;
  1994. }
  1995. #undef curl_multi_setopt
  1996. CURLMcode curl_multi_setopt(CURLM *multi_handle,
  1997. CURLMoption option, ...)
  1998. {
  1999. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  2000. CURLMcode res = CURLM_OK;
  2001. va_list param;
  2002. if(!GOOD_MULTI_HANDLE(multi))
  2003. return CURLM_BAD_HANDLE;
  2004. va_start(param, option);
  2005. switch(option) {
  2006. case CURLMOPT_SOCKETFUNCTION:
  2007. multi->socket_cb = va_arg(param, curl_socket_callback);
  2008. break;
  2009. case CURLMOPT_SOCKETDATA:
  2010. multi->socket_userp = va_arg(param, void *);
  2011. break;
  2012. case CURLMOPT_PUSHFUNCTION:
  2013. multi->push_cb = va_arg(param, curl_push_callback);
  2014. break;
  2015. case CURLMOPT_PUSHDATA:
  2016. multi->push_userp = va_arg(param, void *);
  2017. break;
  2018. case CURLMOPT_PIPELINING:
  2019. multi->pipelining = va_arg(param, long);
  2020. break;
  2021. case CURLMOPT_TIMERFUNCTION:
  2022. multi->timer_cb = va_arg(param, curl_multi_timer_callback);
  2023. break;
  2024. case CURLMOPT_TIMERDATA:
  2025. multi->timer_userp = va_arg(param, void *);
  2026. break;
  2027. case CURLMOPT_MAXCONNECTS:
  2028. multi->maxconnects = va_arg(param, long);
  2029. break;
  2030. case CURLMOPT_MAX_HOST_CONNECTIONS:
  2031. multi->max_host_connections = va_arg(param, long);
  2032. break;
  2033. case CURLMOPT_MAX_PIPELINE_LENGTH:
  2034. multi->max_pipeline_length = va_arg(param, long);
  2035. break;
  2036. case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
  2037. multi->content_length_penalty_size = va_arg(param, long);
  2038. break;
  2039. case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
  2040. multi->chunk_length_penalty_size = va_arg(param, long);
  2041. break;
  2042. case CURLMOPT_PIPELINING_SITE_BL:
  2043. res = Curl_pipeline_set_site_blacklist(va_arg(param, char **),
  2044. &multi->pipelining_site_bl);
  2045. break;
  2046. case CURLMOPT_PIPELINING_SERVER_BL:
  2047. res = Curl_pipeline_set_server_blacklist(va_arg(param, char **),
  2048. &multi->pipelining_server_bl);
  2049. break;
  2050. case CURLMOPT_MAX_TOTAL_CONNECTIONS:
  2051. multi->max_total_connections = va_arg(param, long);
  2052. break;
  2053. default:
  2054. res = CURLM_UNKNOWN_OPTION;
  2055. break;
  2056. }
  2057. va_end(param);
  2058. return res;
  2059. }
  2060. /* we define curl_multi_socket() in the public multi.h header */
  2061. #undef curl_multi_socket
  2062. CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
  2063. int *running_handles)
  2064. {
  2065. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
  2066. 0, running_handles);
  2067. if(CURLM_OK >= result)
  2068. update_timer((struct Curl_multi *)multi_handle);
  2069. return result;
  2070. }
  2071. CURLMcode curl_multi_socket_action(CURLM *multi_handle, curl_socket_t s,
  2072. int ev_bitmask, int *running_handles)
  2073. {
  2074. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
  2075. ev_bitmask, running_handles);
  2076. if(CURLM_OK >= result)
  2077. update_timer((struct Curl_multi *)multi_handle);
  2078. return result;
  2079. }
  2080. CURLMcode curl_multi_socket_all(CURLM *multi_handle, int *running_handles)
  2081. {
  2082. CURLMcode result = multi_socket((struct Curl_multi *)multi_handle,
  2083. TRUE, CURL_SOCKET_BAD, 0, running_handles);
  2084. if(CURLM_OK >= result)
  2085. update_timer((struct Curl_multi *)multi_handle);
  2086. return result;
  2087. }
  2088. static CURLMcode multi_timeout(struct Curl_multi *multi,
  2089. long *timeout_ms)
  2090. {
  2091. static struct timeval tv_zero = {0, 0};
  2092. if(multi->timetree) {
  2093. /* we have a tree of expire times */
  2094. struct timeval now = Curl_tvnow();
  2095. /* splay the lowest to the bottom */
  2096. multi->timetree = Curl_splay(tv_zero, multi->timetree);
  2097. if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
  2098. /* some time left before expiration */
  2099. *timeout_ms = curlx_tvdiff(multi->timetree->key, now);
  2100. if(!*timeout_ms)
  2101. /*
  2102. * Since we only provide millisecond resolution on the returned value
  2103. * and the diff might be less than one millisecond here, we don't
  2104. * return zero as that may cause short bursts of busyloops on fast
  2105. * processors while the diff is still present but less than one
  2106. * millisecond! instead we return 1 until the time is ripe.
  2107. */
  2108. *timeout_ms=1;
  2109. }
  2110. else
  2111. /* 0 means immediately */
  2112. *timeout_ms = 0;
  2113. }
  2114. else
  2115. *timeout_ms = -1;
  2116. return CURLM_OK;
  2117. }
  2118. CURLMcode curl_multi_timeout(CURLM *multi_handle,
  2119. long *timeout_ms)
  2120. {
  2121. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  2122. /* First, make some basic checks that the CURLM handle is a good handle */
  2123. if(!GOOD_MULTI_HANDLE(multi))
  2124. return CURLM_BAD_HANDLE;
  2125. return multi_timeout(multi, timeout_ms);
  2126. }
  2127. /*
  2128. * Tell the application it should update its timers, if it subscribes to the
  2129. * update timer callback.
  2130. */
  2131. static int update_timer(struct Curl_multi *multi)
  2132. {
  2133. long timeout_ms;
  2134. if(!multi->timer_cb)
  2135. return 0;
  2136. if(multi_timeout(multi, &timeout_ms)) {
  2137. return -1;
  2138. }
  2139. if(timeout_ms < 0) {
  2140. static const struct timeval none={0, 0};
  2141. if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
  2142. multi->timer_lastcall = none;
  2143. /* there's no timeout now but there was one previously, tell the app to
  2144. disable it */
  2145. return multi->timer_cb((CURLM*)multi, -1, multi->timer_userp);
  2146. }
  2147. return 0;
  2148. }
  2149. /* When multi_timeout() is done, multi->timetree points to the node with the
  2150. * timeout we got the (relative) time-out time for. We can thus easily check
  2151. * if this is the same (fixed) time as we got in a previous call and then
  2152. * avoid calling the callback again. */
  2153. if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
  2154. return 0;
  2155. multi->timer_lastcall = multi->timetree->key;
  2156. return multi->timer_cb((CURLM*)multi, timeout_ms, multi->timer_userp);
  2157. }
  2158. /*
  2159. * multi_freetimeout()
  2160. *
  2161. * Callback used by the llist system when a single timeout list entry is
  2162. * destroyed.
  2163. */
  2164. static void multi_freetimeout(void *user, void *entryptr)
  2165. {
  2166. (void)user;
  2167. /* the entry was plain malloc()'ed */
  2168. free(entryptr);
  2169. }
  2170. /*
  2171. * multi_addtimeout()
  2172. *
  2173. * Add a timestamp to the list of timeouts. Keep the list sorted so that head
  2174. * of list is always the timeout nearest in time.
  2175. *
  2176. */
  2177. static CURLMcode
  2178. multi_addtimeout(struct curl_llist *timeoutlist,
  2179. struct timeval *stamp)
  2180. {
  2181. struct curl_llist_element *e;
  2182. struct timeval *timedup;
  2183. struct curl_llist_element *prev = NULL;
  2184. timedup = malloc(sizeof(*timedup));
  2185. if(!timedup)
  2186. return CURLM_OUT_OF_MEMORY;
  2187. /* copy the timestamp */
  2188. memcpy(timedup, stamp, sizeof(*timedup));
  2189. if(Curl_llist_count(timeoutlist)) {
  2190. /* find the correct spot in the list */
  2191. for(e = timeoutlist->head; e; e = e->next) {
  2192. struct timeval *checktime = e->ptr;
  2193. long diff = curlx_tvdiff(*checktime, *timedup);
  2194. if(diff > 0)
  2195. break;
  2196. prev = e;
  2197. }
  2198. }
  2199. /* else
  2200. this is the first timeout on the list */
  2201. if(!Curl_llist_insert_next(timeoutlist, prev, timedup)) {
  2202. free(timedup);
  2203. return CURLM_OUT_OF_MEMORY;
  2204. }
  2205. return CURLM_OK;
  2206. }
  2207. /*
  2208. * Curl_expire()
  2209. *
  2210. * given a number of milliseconds from now to use to set the 'act before
  2211. * this'-time for the transfer, to be extracted by curl_multi_timeout()
  2212. *
  2213. * Note that the timeout will be added to a queue of timeouts if it defines a
  2214. * moment in time that is later than the current head of queue.
  2215. *
  2216. * Pass zero to clear all timeout values for this handle.
  2217. */
  2218. void Curl_expire(struct SessionHandle *data, long milli)
  2219. {
  2220. struct Curl_multi *multi = data->multi;
  2221. struct timeval *nowp = &data->state.expiretime;
  2222. int rc;
  2223. /* this is only interesting while there is still an associated multi struct
  2224. remaining! */
  2225. if(!multi)
  2226. return;
  2227. if(!milli) {
  2228. /* No timeout, clear the time data. */
  2229. if(nowp->tv_sec || nowp->tv_usec) {
  2230. /* Since this is an cleared time, we must remove the previous entry from
  2231. the splay tree */
  2232. struct curl_llist *list = data->state.timeoutlist;
  2233. rc = Curl_splayremovebyaddr(multi->timetree,
  2234. &data->state.timenode,
  2235. &multi->timetree);
  2236. if(rc)
  2237. infof(data, "Internal error clearing splay node = %d\n", rc);
  2238. /* flush the timeout list too */
  2239. while(list->size > 0)
  2240. Curl_llist_remove(list, list->tail, NULL);
  2241. #ifdef DEBUGBUILD
  2242. infof(data, "Expire cleared\n");
  2243. #endif
  2244. nowp->tv_sec = 0;
  2245. nowp->tv_usec = 0;
  2246. }
  2247. }
  2248. else {
  2249. struct timeval set;
  2250. set = Curl_tvnow();
  2251. set.tv_sec += milli/1000;
  2252. set.tv_usec += (milli%1000)*1000;
  2253. if(set.tv_usec >= 1000000) {
  2254. set.tv_sec++;
  2255. set.tv_usec -= 1000000;
  2256. }
  2257. if(nowp->tv_sec || nowp->tv_usec) {
  2258. /* This means that the struct is added as a node in the splay tree.
  2259. Compare if the new time is earlier, and only remove-old/add-new if it
  2260. is. */
  2261. long diff = curlx_tvdiff(set, *nowp);
  2262. if(diff > 0) {
  2263. /* the new expire time was later so just add it to the queue
  2264. and get out */
  2265. multi_addtimeout(data->state.timeoutlist, &set);
  2266. return;
  2267. }
  2268. /* the new time is newer than the presently set one, so add the current
  2269. to the queue and update the head */
  2270. multi_addtimeout(data->state.timeoutlist, nowp);
  2271. /* Since this is an updated time, we must remove the previous entry from
  2272. the splay tree first and then re-add the new value */
  2273. rc = Curl_splayremovebyaddr(multi->timetree,
  2274. &data->state.timenode,
  2275. &multi->timetree);
  2276. if(rc)
  2277. infof(data, "Internal error removing splay node = %d\n", rc);
  2278. }
  2279. *nowp = set;
  2280. data->state.timenode.payload = data;
  2281. multi->timetree = Curl_splayinsert(*nowp,
  2282. multi->timetree,
  2283. &data->state.timenode);
  2284. }
  2285. #if 0
  2286. Curl_splayprint(multi->timetree, 0, TRUE);
  2287. #endif
  2288. }
  2289. /*
  2290. * Curl_expire_latest()
  2291. *
  2292. * This is like Curl_expire() but will only add a timeout node to the list of
  2293. * timers if there is no timeout that will expire before the given time.
  2294. *
  2295. * Use this function if the code logic risks calling this function many times
  2296. * or if there's no particular conditional wait in the code for this specific
  2297. * time-out period to expire.
  2298. *
  2299. */
  2300. void Curl_expire_latest(struct SessionHandle *data, long milli)
  2301. {
  2302. struct timeval *expire = &data->state.expiretime;
  2303. struct timeval set;
  2304. set = Curl_tvnow();
  2305. set.tv_sec += milli / 1000;
  2306. set.tv_usec += (milli % 1000) * 1000;
  2307. if(set.tv_usec >= 1000000) {
  2308. set.tv_sec++;
  2309. set.tv_usec -= 1000000;
  2310. }
  2311. if(expire->tv_sec || expire->tv_usec) {
  2312. /* This means that the struct is added as a node in the splay tree.
  2313. Compare if the new time is earlier, and only remove-old/add-new if it
  2314. is. */
  2315. long diff = curlx_tvdiff(set, *expire);
  2316. if(diff > 0)
  2317. /* the new expire time was later than the top time, so just skip this */
  2318. return;
  2319. }
  2320. /* Just add the timeout like normal */
  2321. Curl_expire(data, milli);
  2322. }
  2323. CURLMcode curl_multi_assign(CURLM *multi_handle,
  2324. curl_socket_t s, void *hashp)
  2325. {
  2326. struct Curl_sh_entry *there = NULL;
  2327. struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
  2328. if(s != CURL_SOCKET_BAD)
  2329. there = Curl_hash_pick(&multi->sockhash, (char *)&s,
  2330. sizeof(curl_socket_t));
  2331. if(!there)
  2332. return CURLM_BAD_SOCKET;
  2333. there->socketp = hashp;
  2334. return CURLM_OK;
  2335. }
  2336. size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
  2337. {
  2338. return multi ? multi->max_host_connections : 0;
  2339. }
  2340. size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
  2341. {
  2342. return multi ? multi->max_total_connections : 0;
  2343. }
  2344. curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi)
  2345. {
  2346. return multi ? multi->content_length_penalty_size : 0;
  2347. }
  2348. curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi)
  2349. {
  2350. return multi ? multi->chunk_length_penalty_size : 0;
  2351. }
  2352. struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi)
  2353. {
  2354. return multi->pipelining_site_bl;
  2355. }
  2356. struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi)
  2357. {
  2358. return multi->pipelining_server_bl;
  2359. }
  2360. void Curl_multi_process_pending_handles(struct Curl_multi *multi)
  2361. {
  2362. struct curl_llist_element *e = multi->pending->head;
  2363. while(e) {
  2364. struct SessionHandle *data = e->ptr;
  2365. struct curl_llist_element *next = e->next;
  2366. if(data->mstate == CURLM_STATE_CONNECT_PEND) {
  2367. multistate(data, CURLM_STATE_CONNECT);
  2368. /* Remove this node from the list */
  2369. Curl_llist_remove(multi->pending, e, NULL);
  2370. /* Make sure that the handle will be processed soonish. */
  2371. Curl_expire_latest(data, 1);
  2372. }
  2373. e = next; /* operate on next handle */
  2374. }
  2375. }
  2376. #ifdef DEBUGBUILD
  2377. void Curl_multi_dump(const struct Curl_multi *multi_handle)
  2378. {
  2379. struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
  2380. struct SessionHandle *data;
  2381. int i;
  2382. fprintf(stderr, "* Multi status: %d handles, %d alive\n",
  2383. multi->num_easy, multi->num_alive);
  2384. for(data=multi->easyp; data; data = data->next) {
  2385. if(data->mstate < CURLM_STATE_COMPLETED) {
  2386. /* only display handles that are not completed */
  2387. fprintf(stderr, "handle %p, state %s, %d sockets\n",
  2388. (void *)data,
  2389. statename[data->mstate], data->numsocks);
  2390. for(i=0; i < data->numsocks; i++) {
  2391. curl_socket_t s = data->sockets[i];
  2392. struct Curl_sh_entry *entry =
  2393. Curl_hash_pick(&multi->sockhash, (char *)&s, sizeof(s));
  2394. fprintf(stderr, "%d ", (int)s);
  2395. if(!entry) {
  2396. fprintf(stderr, "INTERNAL CONFUSION\n");
  2397. continue;
  2398. }
  2399. fprintf(stderr, "[%s %s] ",
  2400. entry->action&CURL_POLL_IN?"RECVING":"",
  2401. entry->action&CURL_POLL_OUT?"SENDING":"");
  2402. }
  2403. if(data->numsocks)
  2404. fprintf(stderr, "\n");
  2405. }
  2406. }
  2407. }
  2408. #endif