multi.c 92 KB

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