1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #include <curl/curl.h>
40 #include "speedcheck.h"
41 #include "conncache.h"
42 #include "multihandle.h"
45 #include "vtls/vtls.h"
47 #include "http_proxy.h"
48 /* The last 3 #include files should be in this order */
49 #include "curl_printf.h"
50 #include "curl_memory.h"
54 CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
55 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
56 CURL handle takes 45-50 K memory, therefore this 3K are not significant.
58 #ifndef CURL_SOCKET_HASH_TABLE_SIZE
59 #define CURL_SOCKET_HASH_TABLE_SIZE 911
62 #ifndef CURL_CONNECTION_HASH_SIZE
63 #define CURL_CONNECTION_HASH_SIZE 97
66 #define CURL_MULTI_HANDLE 0x000bab1e
68 #define GOOD_MULTI_HANDLE(x) \
69 ((x) && (x)->type == CURL_MULTI_HANDLE)
71 static void singlesocket(struct Curl_multi *multi,
72 struct Curl_easy *data);
73 static int update_timer(struct Curl_multi *multi);
75 static CURLMcode add_next_timeout(struct curltime now,
76 struct Curl_multi *multi,
78 static CURLMcode multi_timeout(struct Curl_multi *multi,
82 static const char * const statename[]={
105 /* function pointer called once when switching TO a state */
106 typedef void (*init_multistate_func)(struct Curl_easy *data);
108 /* always use this function to change state, to make debugging easier */
109 static void mstate(struct Curl_easy *data, CURLMstate state
115 CURLMstate oldstate = data->mstate;
116 static const init_multistate_func finit[CURLM_STATE_LAST] = {
119 Curl_init_CONNECT, /* CONNECT */
126 Curl_connect_free /* DO */
127 /* the rest is NULL too */
130 #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
134 if(oldstate == state)
135 /* don't bother when the new state is the same as the old state */
138 data->mstate = state;
140 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
141 if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
142 data->mstate < CURLM_STATE_COMPLETED) {
143 long connection_id = -5000;
146 connection_id = data->easy_conn->connection_id;
149 "STATE: %s => %s handle %p; line %d (connection #%ld)\n",
150 statename[oldstate], statename[data->mstate],
151 (void *)data, lineno, connection_id);
155 if(state == CURLM_STATE_COMPLETED)
156 /* changing to COMPLETED means there's one less easy handle 'alive' */
157 data->multi->num_alive--;
159 /* if this state has an init-function, run it */
165 #define multistate(x,y) mstate(x,y)
167 #define multistate(x,y) mstate(x,y, __LINE__)
171 * We add one of these structs to the sockhash for a particular socket
174 struct Curl_sh_entry {
175 struct Curl_easy *easy;
176 int action; /* what action READ/WRITE this socket waits for */
177 curl_socket_t socket; /* mainly to ease debugging */
178 void *socketp; /* settable by users with curl_multi_assign() */
180 /* bits for 'action' having no bits means this socket is not expecting any
185 /* look up a given socket in the socket hash, skip invalid sockets */
186 static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh,
189 if(s != CURL_SOCKET_BAD)
190 /* only look for proper sockets */
191 return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
195 /* make sure this socket is present in the hash for this handle */
196 static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh,
198 struct Curl_easy *data)
200 struct Curl_sh_entry *there = sh_getentry(sh, s);
201 struct Curl_sh_entry *check;
204 /* it is present, return fine */
207 /* not present, add it */
208 check = calloc(1, sizeof(struct Curl_sh_entry));
210 return NULL; /* major failure */
215 /* make/add new hash entry */
216 if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
218 return NULL; /* major failure */
221 return check; /* things are good in sockhash land */
225 /* delete the given socket + handle from the hash */
226 static void sh_delentry(struct curl_hash *sh, curl_socket_t s)
228 /* We remove the hash entry. This will end up in a call to
230 Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
234 * free a sockhash entry
236 static void sh_freeentry(void *freethis)
238 struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
243 static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
245 (void) k1_len; (void) k2_len;
247 return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2));
250 static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
252 curl_socket_t fd = *((curl_socket_t *) key);
255 return (fd % slots_num);
259 * sh_init() creates a new socket hash and returns the handle for it.
261 * Quote from README.multi_socket:
263 * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
264 * is somewhat of a bottle neck. Its current implementation may be a bit too
265 * limiting. It simply has a fixed-size array, and on each entry in the array
266 * it has a linked list with entries. So the hash only checks which list to
267 * scan through. The code I had used so for used a list with merely 7 slots
268 * (as that is what the DNS hash uses) but with 7000 connections that would
269 * make an average of 1000 nodes in each list to run through. I upped that to
270 * 97 slots (I believe a prime is suitable) and noticed a significant speed
271 * increase. I need to reconsider the hash implementation or use a rather
272 * large default value like this. At 9000 connections I was still below 10us
276 static int sh_init(struct curl_hash *hash, int hashsize)
278 return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
285 * Called when a transfer is completed. Adds the given msg pointer to
286 * the list kept in the multi handle.
288 static CURLMcode multi_addmsg(struct Curl_multi *multi,
289 struct Curl_message *msg)
291 Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg,
299 * Callback used by the llist system when a single list entry is destroyed.
301 static void multi_freeamsg(void *a, void *b)
307 struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
308 int chashsize) /* connection hash */
310 struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
315 multi->type = CURL_MULTI_HANDLE;
317 if(Curl_mk_dnscache(&multi->hostcache))
320 if(sh_init(&multi->sockhash, hashsize))
323 if(Curl_conncache_init(&multi->conn_cache, chashsize))
326 Curl_llist_init(&multi->msglist, multi_freeamsg);
327 Curl_llist_init(&multi->pending, multi_freeamsg);
329 multi->max_pipeline_length = 5;
331 /* -1 means it not set by user, use the default value */
332 multi->maxconnects = -1;
337 Curl_hash_destroy(&multi->sockhash);
338 Curl_hash_destroy(&multi->hostcache);
339 Curl_conncache_destroy(&multi->conn_cache);
340 Curl_llist_destroy(&multi->msglist, NULL);
341 Curl_llist_destroy(&multi->pending, NULL);
347 struct Curl_multi *curl_multi_init(void)
349 return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
350 CURL_CONNECTION_HASH_SIZE);
353 CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
354 struct Curl_easy *data)
356 /* First, make some basic checks that the CURLM handle is a good handle */
357 if(!GOOD_MULTI_HANDLE(multi))
358 return CURLM_BAD_HANDLE;
360 /* Verify that we got a somewhat good easy handle too */
361 if(!GOOD_EASY_HANDLE(data))
362 return CURLM_BAD_EASY_HANDLE;
364 /* Prevent users from adding same easy handle more than once and prevent
365 adding to more than one multi stack */
367 return CURLM_ADDED_ALREADY;
369 if(multi->in_callback)
370 return CURLM_RECURSIVE_API_CALL;
372 /* Initialize timeout list for this handle */
373 Curl_llist_init(&data->state.timeoutlist, NULL);
376 * No failure allowed in this function beyond this point. And no
377 * modification of easy nor multi handle allowed before this except for
378 * potential multi's connection cache growing which won't be undone in this
379 * function no matter what.
382 /* set the easy handle */
383 multistate(data, CURLM_STATE_INIT);
385 if((data->set.global_dns_cache) &&
386 (data->dns.hostcachetype != HCACHE_GLOBAL)) {
387 /* global dns cache was requested but still isn't */
388 struct curl_hash *global = Curl_global_host_cache_init();
390 /* only do this if the global cache init works */
391 data->dns.hostcache = global;
392 data->dns.hostcachetype = HCACHE_GLOBAL;
395 /* for multi interface connections, we share DNS cache automatically if the
396 easy handle's one is currently not set. */
397 else if(!data->dns.hostcache ||
398 (data->dns.hostcachetype == HCACHE_NONE)) {
399 data->dns.hostcache = &multi->hostcache;
400 data->dns.hostcachetype = HCACHE_MULTI;
403 /* Point to the shared or multi handle connection cache */
404 if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT)))
405 data->state.conn_cache = &data->share->conn_cache;
407 data->state.conn_cache = &multi->conn_cache;
409 /* This adds the new entry at the 'end' of the doubly-linked circular
410 list of Curl_easy structs to try and maintain a FIFO queue so
411 the pipelined requests are in order. */
413 /* We add this new entry last in the list. */
415 data->next = NULL; /* end of the line */
417 struct Curl_easy *last = multi->easylp;
420 multi->easylp = data; /* the new last node */
423 /* first node, make prev NULL! */
425 multi->easylp = multi->easyp = data; /* both first and last */
428 /* make the Curl_easy refer back to this multi handle */
431 /* Set the timeout for this handle to expire really soon so that it will
432 be taken care of even when this handle is added in the midst of operation
433 when only the curl_multi_socket() API is used. During that flow, only
434 sockets that time-out or have actions will be dealt with. Since this
435 handle has no action yet, we make sure it times out to get things to
437 Curl_expire(data, 0, EXPIRE_RUN_NOW);
439 /* increase the node-counter */
442 /* increase the alive-counter */
445 /* A somewhat crude work-around for a little glitch in update_timer() that
446 happens if the lastcall time is set to the same time when the handle is
447 removed as when the next handle is added, as then the check in
448 update_timer() that prevents calling the application multiple times with
449 the same timer infor will not trigger and then the new handle's timeout
450 will not be notified to the app.
452 The work-around is thus simply to clear the 'lastcall' variable to force
453 update_timer() to always trigger a callback to the app when a new easy
455 memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
457 /* The closure handle only ever has default timeouts set. To improve the
458 state somewhat we clone the timeouts from each added handle so that the
459 closure handle always has the same timeouts as the most recently added
461 data->state.conn_cache->closure_handle->set.timeout = data->set.timeout;
462 data->state.conn_cache->closure_handle->set.server_response_timeout =
463 data->set.server_response_timeout;
470 /* Debug-function, used like this:
472 * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
474 * Enable the hash print function first by editing hash.c
476 static void debug_print_sock_hash(void *p)
478 struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
480 fprintf(stderr, " [easy %p/magic %x/socket %d]",
481 (void *)sh->data, sh->data->magic, (int)sh->socket);
485 static CURLcode multi_done(struct connectdata **connp,
486 CURLcode status, /* an error if this is called
487 after an error was detected */
491 struct connectdata *conn;
492 struct Curl_easy *data;
500 DEBUGF(infof(data, "multi_done\n"));
503 /* Stop if multi_done() has already been called */
506 Curl_getoff_all_pipelines(data, conn);
508 /* Cleanup possible redirect junk */
509 free(data->req.newurl);
510 data->req.newurl = NULL;
511 free(data->req.location);
512 data->req.location = NULL;
515 case CURLE_ABORTED_BY_CALLBACK:
516 case CURLE_READ_ERROR:
517 case CURLE_WRITE_ERROR:
518 /* When we're aborted due to a callback return code it basically have to
519 be counted as premature as there is trouble ahead if we don't. We have
520 many callbacks and protocols work differently, we could potentially do
521 this more fine-grained in the future. */
527 /* this calls the protocol-specific function pointer previously set */
528 if(conn->handler->done)
529 result = conn->handler->done(conn, status, premature);
533 if(CURLE_ABORTED_BY_CALLBACK != result) {
534 /* avoid this if we already aborted by callback to avoid this calling
536 CURLcode rc = Curl_pgrsDone(conn);
538 result = CURLE_ABORTED_BY_CALLBACK;
541 if(conn->send_pipe.size || conn->recv_pipe.size) {
542 /* Stop if pipeline is not empty . */
543 data->easy_conn = NULL;
544 DEBUGF(infof(data, "Connection still in use, no more multi_done now!\n"));
548 data->state.done = TRUE; /* called just now! */
549 Curl_resolver_cancel(conn);
551 if(conn->dns_entry) {
552 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
553 conn->dns_entry = NULL;
555 Curl_hostcache_prune(data);
557 /* if the transfer was completed in a paused state there can be buffered
559 for(i = 0; i < data->state.tempcount; i++) {
560 free(data->state.tempwrite[i].buf);
562 data->state.tempcount = 0;
564 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
565 forced us to close this connection. This is ignored for requests taking
566 place in a NTLM authentication handshake
568 if conn->bits.close is TRUE, it means that the connection should be
569 closed in spite of all our efforts to be nice, due to protocol
570 restrictions in our or the server's end
572 if premature is TRUE, it means this connection was said to be DONE before
573 the entire request operation is complete and thus we can't know in what
574 state it is for re-using, so we're forced to close it. In a perfect world
575 we can add code that keep track of if we really must close it here or not,
576 but currently we have no such detail knowledge.
579 if((data->set.reuse_forbid
580 #if defined(USE_NTLM)
581 && !(conn->ntlm.state == NTLMSTATE_TYPE2 ||
582 conn->proxyntlm.state == NTLMSTATE_TYPE2)
584 ) || conn->bits.close
585 || (premature && !(conn->handler->flags & PROTOPT_STREAM))) {
586 CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
588 /* If we had an error already, make sure we return that one. But
589 if we got a new error, return that. */
595 /* create string before returning the connection */
596 snprintf(buffer, sizeof(buffer),
597 "Connection #%ld to host %s left intact",
599 conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
600 conn->bits.httpproxy ? conn->http_proxy.host.dispname :
601 conn->bits.conn_to_host ? conn->conn_to_host.dispname :
602 conn->host.dispname);
604 /* the connection is no longer in use */
605 if(Curl_conncache_return_conn(conn)) {
606 /* remember the most recently used connection */
607 data->state.lastconnect = conn;
608 infof(data, "%s\n", buffer);
611 data->state.lastconnect = NULL;
614 *connp = NULL; /* to make the caller of this function better detect that
615 this was either closed or handed over to the connection
616 cache here, and therefore cannot be used from this point on
618 Curl_free_request_state(data);
623 CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
624 struct Curl_easy *data)
626 struct Curl_easy *easy = data;
629 struct curl_llist_element *e;
631 /* First, make some basic checks that the CURLM handle is a good handle */
632 if(!GOOD_MULTI_HANDLE(multi))
633 return CURLM_BAD_HANDLE;
635 /* Verify that we got a somewhat good easy handle too */
636 if(!GOOD_EASY_HANDLE(data))
637 return CURLM_BAD_EASY_HANDLE;
639 /* Prevent users from trying to remove same easy handle more than once */
641 return CURLM_OK; /* it is already removed so let's say it is fine! */
643 if(multi->in_callback)
644 return CURLM_RECURSIVE_API_CALL;
646 premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
647 easy_owns_conn = (data->easy_conn && (data->easy_conn->data == easy)) ?
650 /* If the 'state' is not INIT or COMPLETED, we might need to do something
651 nice to put the easy_handle in a good known state when this returns. */
653 /* this handle is "alive" so we need to count down the total number of
654 alive connections when this is removed */
657 /* When this handle gets removed, other handles may be able to get the
659 Curl_multi_process_pending_handles(multi);
662 if(data->easy_conn &&
663 data->mstate > CURLM_STATE_DO &&
664 data->mstate < CURLM_STATE_COMPLETED) {
665 /* Set connection owner so that the DONE function closes it. We can
666 safely do this here since connection is killed. */
667 data->easy_conn->data = easy;
668 /* If the handle is in a pipeline and has started sending off its
669 request but not received its response yet, we need to close
671 streamclose(data->easy_conn, "Removed with partial response");
672 easy_owns_conn = TRUE;
675 /* The timer must be shut down before data->multi is set to NULL,
676 else the timenode will remain in the splay tree after
677 curl_easy_cleanup is called. */
678 Curl_expire_clear(data);
680 if(data->easy_conn) {
682 /* we must call multi_done() here (if we still own the connection) so that
683 we don't leave a half-baked one around */
686 /* multi_done() clears the conn->data field to lose the association
687 between the easy handle and the connection
689 Note that this ignores the return code simply because there's
690 nothing really useful to do with it anyway! */
691 (void)multi_done(&data->easy_conn, data->result, premature);
694 /* Clear connection pipelines, if multi_done above was not called */
695 Curl_getoff_all_pipelines(data, data->easy_conn);
698 if(data->dns.hostcachetype == HCACHE_MULTI) {
699 /* stop using the multi handle's DNS cache, *after* the possible
700 multi_done() call above */
701 data->dns.hostcache = NULL;
702 data->dns.hostcachetype = HCACHE_NONE;
705 Curl_wildcard_dtor(&data->wildcard);
707 /* destroy the timeout list that is held in the easy handle, do this *after*
708 multi_done() as that may actually call Curl_expire that uses this */
709 Curl_llist_destroy(&data->state.timeoutlist, NULL);
711 /* as this was using a shared connection cache we clear the pointer to that
712 since we're not part of that multi handle anymore */
713 data->state.conn_cache = NULL;
715 /* change state without using multistate(), only to make singlesocket() do
717 data->mstate = CURLM_STATE_COMPLETED;
718 singlesocket(multi, easy); /* to let the application know what sockets that
719 vanish with this handle */
721 /* Remove the association between the connection and the handle */
722 if(data->easy_conn) {
723 data->easy_conn->data = NULL;
724 data->easy_conn = NULL;
727 data->multi = NULL; /* clear the association to this multi handle */
729 /* make sure there's no pending message in the queue sent from this easy
732 for(e = multi->msglist.head; e; e = e->next) {
733 struct Curl_message *msg = e->ptr;
735 if(msg->extmsg.easy_handle == easy) {
736 Curl_llist_remove(&multi->msglist, e, NULL);
737 /* there can only be one from this specific handle */
742 /* make the previous node point to our next */
744 data->prev->next = data->next;
746 multi->easyp = data->next; /* point to first node */
748 /* make our next point to our previous node */
750 data->next->prev = data->prev;
752 multi->easylp = data->prev; /* point to last node */
755 We do not touch the easy handle here! */
756 multi->num_easy--; /* one less to care about now */
762 /* Return TRUE if the application asked for a certain set of pipelining */
763 bool Curl_pipeline_wanted(const struct Curl_multi *multi, int bits)
765 return (multi && (multi->pipelining & bits)) ? TRUE : FALSE;
768 void Curl_multi_handlePipeBreak(struct Curl_easy *data)
770 data->easy_conn = NULL;
773 static int waitconnect_getsock(struct connectdata *conn,
782 return GETSOCK_BLANK;
785 if(CONNECT_FIRSTSOCKET_PROXY_SSL())
786 return Curl_ssl_getsock(conn, sock, numsocks);
789 for(i = 0; i<2; i++) {
790 if(conn->tempsock[i] != CURL_SOCKET_BAD) {
791 sock[s] = conn->tempsock[i];
792 rc |= GETSOCK_WRITESOCK(s++);
799 static int waitproxyconnect_getsock(struct connectdata *conn,
804 return GETSOCK_BLANK;
806 sock[0] = conn->sock[FIRSTSOCKET];
808 /* when we've sent a CONNECT to a proxy, we should rather wait for the
809 socket to become readable to be able to get the response headers */
810 if(conn->connect_state)
811 return GETSOCK_READSOCK(0);
813 return GETSOCK_WRITESOCK(0);
816 static int domore_getsock(struct connectdata *conn,
817 curl_socket_t *socks,
820 if(conn && conn->handler->domore_getsock)
821 return conn->handler->domore_getsock(conn, socks, numsocks);
822 return GETSOCK_BLANK;
825 /* returns bitmapped flags for this handle and its sockets */
826 static int multi_getsock(struct Curl_easy *data,
827 curl_socket_t *socks, /* points to numsocks number
831 /* If the pipe broke, or if there's no connection left for this easy handle,
832 then we MUST bail out now with no bitmask set. The no connection case can
833 happen when this is called from curl_multi_remove_handle() =>
834 singlesocket() => multi_getsock().
836 if(data->state.pipe_broke || !data->easy_conn)
839 if(data->mstate > CURLM_STATE_CONNECT &&
840 data->mstate < CURLM_STATE_COMPLETED) {
841 /* Set up ownership correctly */
842 data->easy_conn->data = data;
845 switch(data->mstate) {
847 #if 0 /* switch back on these cases to get the compiler to check for all enums
849 case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */
850 case CURLM_STATE_COMPLETED:
851 case CURLM_STATE_MSGSENT:
852 case CURLM_STATE_INIT:
853 case CURLM_STATE_CONNECT:
854 case CURLM_STATE_WAITDO:
855 case CURLM_STATE_DONE:
856 case CURLM_STATE_LAST:
857 /* this will get called with CURLM_STATE_COMPLETED when a handle is
862 case CURLM_STATE_WAITRESOLVE:
863 return Curl_resolver_getsock(data->easy_conn, socks, numsocks);
865 case CURLM_STATE_PROTOCONNECT:
866 case CURLM_STATE_SENDPROTOCONNECT:
867 return Curl_protocol_getsock(data->easy_conn, socks, numsocks);
870 case CURLM_STATE_DOING:
871 return Curl_doing_getsock(data->easy_conn, socks, numsocks);
873 case CURLM_STATE_WAITPROXYCONNECT:
874 return waitproxyconnect_getsock(data->easy_conn, socks, numsocks);
876 case CURLM_STATE_WAITCONNECT:
877 return waitconnect_getsock(data->easy_conn, socks, numsocks);
879 case CURLM_STATE_DO_MORE:
880 return domore_getsock(data->easy_conn, socks, numsocks);
882 case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
883 to waiting for the same as the *PERFORM
885 case CURLM_STATE_PERFORM:
886 case CURLM_STATE_WAITPERFORM:
887 return Curl_single_getsock(data->easy_conn, socks, numsocks);
892 CURLMcode curl_multi_fdset(struct Curl_multi *multi,
893 fd_set *read_fd_set, fd_set *write_fd_set,
894 fd_set *exc_fd_set, int *max_fd)
896 /* Scan through all the easy handles to get the file descriptors set.
897 Some easy handles may not have connected to the remote host yet,
898 and then we must make sure that is done. */
899 struct Curl_easy *data;
900 int this_max_fd = -1;
901 curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
904 (void)exc_fd_set; /* not used */
906 if(!GOOD_MULTI_HANDLE(multi))
907 return CURLM_BAD_HANDLE;
909 if(multi->in_callback)
910 return CURLM_RECURSIVE_API_CALL;
914 bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
916 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
917 curl_socket_t s = CURL_SOCKET_BAD;
919 if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
920 FD_SET(sockbunch[i], read_fd_set);
923 if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
924 FD_SET(sockbunch[i], write_fd_set);
927 if(s == CURL_SOCKET_BAD)
928 /* this socket is unused, break out of loop */
930 if((int)s > this_max_fd)
931 this_max_fd = (int)s;
934 data = data->next; /* check next handle */
937 *max_fd = this_max_fd;
942 #define NUM_POLLS_ON_STACK 10
944 CURLMcode curl_multi_wait(struct Curl_multi *multi,
945 struct curl_waitfd extra_fds[],
946 unsigned int extra_nfds,
950 struct Curl_easy *data;
951 curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
954 unsigned int nfds = 0;
955 unsigned int curlfds;
956 struct pollfd *ufds = NULL;
957 bool ufds_malloc = FALSE;
958 long timeout_internal;
960 struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
962 if(!GOOD_MULTI_HANDLE(multi))
963 return CURLM_BAD_HANDLE;
965 if(multi->in_callback)
966 return CURLM_RECURSIVE_API_CALL;
968 /* If the internally desired timeout is actually shorter than requested from
969 the outside, then use the shorter time! But only if the internal timer
970 is actually larger than -1! */
971 (void)multi_timeout(multi, &timeout_internal);
972 if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
973 timeout_ms = (int)timeout_internal;
975 /* Count up how many fds we have from the multi handle */
978 bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
980 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
981 curl_socket_t s = CURL_SOCKET_BAD;
983 if(bitmap & GETSOCK_READSOCK(i)) {
987 if(bitmap & GETSOCK_WRITESOCK(i)) {
991 if(s == CURL_SOCKET_BAD) {
996 data = data->next; /* check next handle */
999 curlfds = nfds; /* number of internal file descriptors */
1000 nfds += extra_nfds; /* add the externally provided ones */
1003 if(nfds > NUM_POLLS_ON_STACK) {
1004 /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes
1005 big, so at 2^29 sockets this value might wrap. When a process gets
1006 the capability to actually handle over 500 million sockets this
1007 calculation needs a integer overflow check. */
1008 ufds = malloc(nfds * sizeof(struct pollfd));
1010 return CURLM_OUT_OF_MEMORY;
1014 ufds = &a_few_on_stack[0];
1018 /* only do the second loop if we found descriptors in the first stage run
1022 /* Add the curl handles to our pollfds first */
1023 data = multi->easyp;
1025 bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
1027 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
1028 curl_socket_t s = CURL_SOCKET_BAD;
1030 if(bitmap & GETSOCK_READSOCK(i)) {
1031 ufds[nfds].fd = sockbunch[i];
1032 ufds[nfds].events = POLLIN;
1036 if(bitmap & GETSOCK_WRITESOCK(i)) {
1037 ufds[nfds].fd = sockbunch[i];
1038 ufds[nfds].events = POLLOUT;
1042 if(s == CURL_SOCKET_BAD) {
1047 data = data->next; /* check next handle */
1051 /* Add external file descriptions from poll-like struct curl_waitfd */
1052 for(i = 0; i < extra_nfds; i++) {
1053 ufds[nfds].fd = extra_fds[i].fd;
1054 ufds[nfds].events = 0;
1055 if(extra_fds[i].events & CURL_WAIT_POLLIN)
1056 ufds[nfds].events |= POLLIN;
1057 if(extra_fds[i].events & CURL_WAIT_POLLPRI)
1058 ufds[nfds].events |= POLLPRI;
1059 if(extra_fds[i].events & CURL_WAIT_POLLOUT)
1060 ufds[nfds].events |= POLLOUT;
1067 pollrc = Curl_poll(ufds, nfds, timeout_ms);
1068 DEBUGF(infof(data, "Curl_poll(%d ds, %d ms) == %d\n",
1069 nfds, timeout_ms, pollrc));
1073 /* copy revents results from the poll to the curl_multi_wait poll
1074 struct, the bit values of the actual underlying poll() implementation
1075 may not be the same as the ones in the public libcurl API! */
1076 for(i = 0; i < extra_nfds; i++) {
1077 unsigned short mask = 0;
1078 unsigned r = ufds[curlfds + i].revents;
1081 mask |= CURL_WAIT_POLLIN;
1083 mask |= CURL_WAIT_POLLOUT;
1085 mask |= CURL_WAIT_POLLPRI;
1087 extra_fds[i].revents = mask;
1100 * Curl_multi_connchanged() is called to tell that there is a connection in
1101 * this multi handle that has changed state (pipelining become possible, the
1102 * number of allowed streams changed or similar), and a subsequent use of this
1103 * multi handle should move CONNECT_PEND handles back to CONNECT to have them
1106 void Curl_multi_connchanged(struct Curl_multi *multi)
1108 multi->recheckstate = TRUE;
1112 * multi_ischanged() is called
1114 * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
1115 * => CONNECT action.
1117 * Set 'clear' to TRUE to have it also clear the state variable.
1119 static bool multi_ischanged(struct Curl_multi *multi, bool clear)
1121 bool retval = multi->recheckstate;
1123 multi->recheckstate = FALSE;
1127 CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
1128 struct Curl_easy *data,
1129 struct connectdata *conn)
1133 if(multi->in_callback)
1134 return CURLM_RECURSIVE_API_CALL;
1136 rc = curl_multi_add_handle(multi, data);
1138 struct SingleRequest *k = &data->req;
1140 /* pass in NULL for 'conn' here since we don't want to init the
1141 connection, only this transfer */
1142 Curl_init_do(data, NULL);
1144 /* take this handle to the perform state right away */
1145 multistate(data, CURLM_STATE_PERFORM);
1146 data->easy_conn = conn;
1147 k->keepon |= KEEP_RECV; /* setup to receive! */
1152 static CURLcode multi_reconnect_request(struct connectdata **connp)
1154 CURLcode result = CURLE_OK;
1155 struct connectdata *conn = *connp;
1156 struct Curl_easy *data = conn->data;
1158 /* This was a re-use of a connection and we got a write error in the
1159 * DO-phase. Then we DISCONNECT this connection and have another attempt to
1160 * CONNECT and then DO again! The retry cannot possibly find another
1161 * connection to re-use, since we only keep one possible connection for
1164 infof(data, "Re-used connection seems dead, get a new one\n");
1166 connclose(conn, "Reconnect dead connection"); /* enforce close */
1167 result = multi_done(&conn, result, FALSE); /* we are so done with this */
1169 /* conn may no longer be a good pointer, clear it to avoid mistakes by
1174 * We need to check for CURLE_SEND_ERROR here as well. This could happen
1175 * when the request failed on a FTP connection and thus multi_done() itself
1176 * tried to use the connection (again).
1178 if(!result || (CURLE_SEND_ERROR == result)) {
1180 bool protocol_done = TRUE;
1182 /* Now, redo the connect and get a new connection */
1183 result = Curl_connect(data, connp, &async, &protocol_done);
1185 /* We have connected or sent away a name resolve query fine */
1187 conn = *connp; /* setup conn to again point to something nice */
1189 /* Now, if async is TRUE here, we need to wait for the name
1191 result = Curl_resolver_wait_resolv(conn, NULL);
1195 /* Resolved, continue with the connection */
1196 result = Curl_async_resolved(conn, &protocol_done);
1207 * do_complete is called when the DO actions are complete.
1209 * We init chunking and trailer bits to their default values here immediately
1210 * before receiving any header data for the current request in the pipeline.
1212 static void do_complete(struct connectdata *conn)
1214 conn->data->req.chunk = FALSE;
1215 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
1216 conn->sockfd:conn->writesockfd) + 1;
1217 Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
1220 static CURLcode multi_do(struct connectdata **connp, bool *done)
1222 CURLcode result = CURLE_OK;
1223 struct connectdata *conn = *connp;
1224 struct Curl_easy *data = conn->data;
1226 if(conn->handler->do_it) {
1227 /* generic protocol-specific function pointer set in curl_connect() */
1228 result = conn->handler->do_it(conn, done);
1230 /* This was formerly done in transfer.c, but we better do it here */
1231 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
1233 * If the connection is using an easy handle, call reconnect
1234 * to re-establish the connection. Otherwise, let the multi logic
1235 * figure out how to re-establish the connection.
1238 result = multi_reconnect_request(connp);
1241 /* ... finally back to actually retry the DO phase */
1242 conn = *connp; /* re-assign conn since multi_reconnect_request
1243 creates a new connection */
1244 result = conn->handler->do_it(conn, done);
1251 if(!result && *done)
1252 /* do_complete must be called after the protocol-specific DO function */
1259 * multi_do_more() is called during the DO_MORE multi state. It is basically a
1260 * second stage DO state which (wrongly) was introduced to support FTP's
1261 * second connection.
1263 * TODO: A future libcurl should be able to work away this state.
1265 * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
1266 * DOING state there's more work to do!
1269 static CURLcode multi_do_more(struct connectdata *conn, int *complete)
1271 CURLcode result = CURLE_OK;
1275 if(conn->handler->do_more)
1276 result = conn->handler->do_more(conn, complete);
1278 if(!result && (*complete == 1))
1279 /* do_complete must be called after the protocol-specific DO function */
1285 static CURLMcode multi_runsingle(struct Curl_multi *multi,
1286 struct curltime now,
1287 struct Curl_easy *data)
1289 struct Curl_message *msg = NULL;
1292 bool protocol_connect = FALSE;
1293 bool dophase_done = FALSE;
1296 CURLcode result = CURLE_OK;
1297 struct SingleRequest *k;
1299 time_t recv_timeout_ms;
1300 timediff_t send_timeout_ms;
1303 if(!GOOD_EASY_HANDLE(data))
1304 return CURLM_BAD_EASY_HANDLE;
1307 /* A "stream" here is a logical stream if the protocol can handle that
1308 (HTTP/2), or the full connection for older protocols */
1309 bool stream_error = FALSE;
1312 /* Handle the case when the pipe breaks, i.e., the connection
1313 we're using gets cleaned up and we're left with nothing. */
1314 if(data->state.pipe_broke) {
1315 infof(data, "Pipe broke: handle %p, url = %s\n",
1316 (void *)data, data->state.path);
1318 if(data->mstate < CURLM_STATE_COMPLETED) {
1319 /* Head back to the CONNECT state */
1320 multistate(data, CURLM_STATE_CONNECT);
1321 rc = CURLM_CALL_MULTI_PERFORM;
1325 data->state.pipe_broke = FALSE;
1326 data->easy_conn = NULL;
1330 if(!data->easy_conn &&
1331 data->mstate > CURLM_STATE_CONNECT &&
1332 data->mstate < CURLM_STATE_DONE) {
1333 /* In all these states, the code will blindly access 'data->easy_conn'
1334 so this is precaution that it isn't NULL. And it silences static
1336 failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
1337 return CURLM_INTERNAL_ERROR;
1340 if(multi_ischanged(multi, TRUE)) {
1341 DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n"));
1342 Curl_multi_process_pending_handles(multi);
1345 if(data->easy_conn && data->mstate > CURLM_STATE_CONNECT &&
1346 data->mstate < CURLM_STATE_COMPLETED) {
1347 /* Make sure we set the connection's current owner */
1348 data->easy_conn->data = data;
1351 if(data->easy_conn &&
1352 (data->mstate >= CURLM_STATE_CONNECT) &&
1353 (data->mstate < CURLM_STATE_COMPLETED)) {
1354 /* we need to wait for the connect state as only then is the start time
1355 stored, but we must not check already completed handles */
1356 timeout_ms = Curl_timeleft(data, &now,
1357 (data->mstate <= CURLM_STATE_WAITDO)?
1360 if(timeout_ms < 0) {
1361 /* Handle timed out */
1362 if(data->mstate == CURLM_STATE_WAITRESOLVE)
1363 failf(data, "Resolving timed out after %ld milliseconds",
1364 Curl_timediff(now, data->progress.t_startsingle));
1365 else if(data->mstate == CURLM_STATE_WAITCONNECT)
1366 failf(data, "Connection timed out after %ld milliseconds",
1367 Curl_timediff(now, data->progress.t_startsingle));
1371 failf(data, "Operation timed out after %ld milliseconds with %"
1372 CURL_FORMAT_CURL_OFF_T " out of %"
1373 CURL_FORMAT_CURL_OFF_T " bytes received",
1374 Curl_timediff(now, data->progress.t_startsingle),
1375 k->bytecount, k->size);
1378 failf(data, "Operation timed out after %ld milliseconds with %"
1379 CURL_FORMAT_CURL_OFF_T " bytes received",
1380 Curl_timediff(now, data->progress.t_startsingle),
1385 /* Force connection closed if the connection has indeed been used */
1386 if(data->mstate > CURLM_STATE_DO) {
1387 streamclose(data->easy_conn, "Disconnected with pending data");
1388 stream_error = TRUE;
1390 result = CURLE_OPERATION_TIMEDOUT;
1391 (void)multi_done(&data->easy_conn, result, TRUE);
1392 /* Skip the statemachine and go directly to error handling section. */
1393 goto statemachine_end;
1397 switch(data->mstate) {
1398 case CURLM_STATE_INIT:
1399 /* init this transfer. */
1400 result = Curl_pretransfer(data);
1403 /* after init, go CONNECT */
1404 multistate(data, CURLM_STATE_CONNECT);
1405 Curl_pgrsTime(data, TIMER_STARTOP);
1406 rc = CURLM_CALL_MULTI_PERFORM;
1410 case CURLM_STATE_CONNECT_PEND:
1411 /* We will stay here until there is a connection available. Then
1412 we try again in the CURLM_STATE_CONNECT state. */
1415 case CURLM_STATE_CONNECT:
1416 /* Connect. We want to get a connection identifier filled in. */
1417 Curl_pgrsTime(data, TIMER_STARTSINGLE);
1418 result = Curl_connect(data, &data->easy_conn,
1419 &async, &protocol_connect);
1420 if(CURLE_NO_CONNECTION_AVAILABLE == result) {
1421 /* There was no connection available. We will go to the pending
1422 state and wait for an available connection. */
1423 multistate(data, CURLM_STATE_CONNECT_PEND);
1425 /* add this handle to the list of connect-pending handles */
1426 Curl_llist_insert_next(&multi->pending, multi->pending.tail, data,
1427 &data->connect_queue);
1433 /* Add this handle to the send or pend pipeline */
1434 result = Curl_add_handle_to_pipeline(data, data->easy_conn);
1436 stream_error = TRUE;
1439 /* We're now waiting for an asynchronous name lookup */
1440 multistate(data, CURLM_STATE_WAITRESOLVE);
1442 /* after the connect has been sent off, go WAITCONNECT unless the
1443 protocol connect is already done and we can go directly to
1445 rc = CURLM_CALL_MULTI_PERFORM;
1447 if(protocol_connect)
1448 multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
1449 CURLM_STATE_WAITDO:CURLM_STATE_DO);
1451 #ifndef CURL_DISABLE_HTTP
1452 if(Curl_connect_ongoing(data->easy_conn))
1453 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1456 multistate(data, CURLM_STATE_WAITCONNECT);
1463 case CURLM_STATE_WAITRESOLVE:
1464 /* awaiting an asynch name resolve to complete */
1466 struct Curl_dns_entry *dns = NULL;
1467 struct connectdata *conn = data->easy_conn;
1468 const char *hostname;
1470 if(conn->bits.httpproxy)
1471 hostname = conn->http_proxy.host.name;
1472 else if(conn->bits.conn_to_host)
1473 hostname = conn->conn_to_host.name;
1475 hostname = conn->host.name;
1477 /* check if we have the name resolved by now */
1478 dns = Curl_fetch_addr(conn, hostname, (int)conn->port);
1481 #ifdef CURLRES_ASYNCH
1482 conn->async.dns = dns;
1483 conn->async.done = TRUE;
1486 infof(data, "Hostname '%s' was found in DNS cache\n", hostname);
1490 result = Curl_resolver_is_resolved(data->easy_conn, &dns);
1492 /* Update sockets here, because the socket(s) may have been
1493 closed and the application thus needs to be told, even if it
1494 is likely that the same socket(s) will again be used further
1495 down. If the name has not yet been resolved, it is likely
1496 that new sockets have been opened in an attempt to contact
1497 another resolver. */
1498 singlesocket(multi, data);
1501 /* Perform the next step in the connection phase, and then move on
1502 to the WAITCONNECT state */
1503 result = Curl_async_resolved(data->easy_conn, &protocol_connect);
1506 /* if Curl_async_resolved() returns failure, the connection struct
1507 is already freed and gone */
1508 data->easy_conn = NULL; /* no more connection */
1510 /* call again please so that we get the next socket setup */
1511 rc = CURLM_CALL_MULTI_PERFORM;
1512 if(protocol_connect)
1513 multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
1514 CURLM_STATE_WAITDO:CURLM_STATE_DO);
1516 #ifndef CURL_DISABLE_HTTP
1517 if(Curl_connect_ongoing(data->easy_conn))
1518 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1521 multistate(data, CURLM_STATE_WAITCONNECT);
1527 /* failure detected */
1528 stream_error = TRUE;
1534 #ifndef CURL_DISABLE_HTTP
1535 case CURLM_STATE_WAITPROXYCONNECT:
1536 /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
1537 result = Curl_http_connect(data->easy_conn, &protocol_connect);
1539 if(data->easy_conn->bits.proxy_connect_closed) {
1540 rc = CURLM_CALL_MULTI_PERFORM;
1541 /* connect back to proxy again */
1543 multi_done(&data->easy_conn, CURLE_OK, FALSE);
1544 multistate(data, CURLM_STATE_CONNECT);
1547 if((data->easy_conn->http_proxy.proxytype != CURLPROXY_HTTPS ||
1548 data->easy_conn->bits.proxy_ssl_connected[FIRSTSOCKET]) &&
1549 Curl_connect_complete(data->easy_conn)) {
1550 rc = CURLM_CALL_MULTI_PERFORM;
1551 /* initiate protocol connect phase */
1552 multistate(data, CURLM_STATE_SENDPROTOCONNECT);
1558 case CURLM_STATE_WAITCONNECT:
1559 /* awaiting a completion of an asynch TCP connect */
1560 result = Curl_is_connected(data->easy_conn, FIRSTSOCKET, &connected);
1561 if(connected && !result) {
1562 #ifndef CURL_DISABLE_HTTP
1563 if((data->easy_conn->http_proxy.proxytype == CURLPROXY_HTTPS &&
1564 !data->easy_conn->bits.proxy_ssl_connected[FIRSTSOCKET]) ||
1565 Curl_connect_ongoing(data->easy_conn)) {
1566 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1570 rc = CURLM_CALL_MULTI_PERFORM;
1571 multistate(data, data->easy_conn->bits.tunnel_proxy?
1572 CURLM_STATE_WAITPROXYCONNECT:
1573 CURLM_STATE_SENDPROTOCONNECT);
1576 /* failure detected */
1577 /* Just break, the cleaning up is handled all in one place */
1578 stream_error = TRUE;
1583 case CURLM_STATE_SENDPROTOCONNECT:
1584 result = Curl_protocol_connect(data->easy_conn, &protocol_connect);
1585 if(!protocol_connect)
1586 /* switch to waiting state */
1587 multistate(data, CURLM_STATE_PROTOCONNECT);
1589 /* protocol connect has completed, go WAITDO or DO */
1590 multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
1591 CURLM_STATE_WAITDO:CURLM_STATE_DO);
1592 rc = CURLM_CALL_MULTI_PERFORM;
1595 /* failure detected */
1596 Curl_posttransfer(data);
1597 multi_done(&data->easy_conn, result, TRUE);
1598 stream_error = TRUE;
1602 case CURLM_STATE_PROTOCONNECT:
1603 /* protocol-specific connect phase */
1604 result = Curl_protocol_connecting(data->easy_conn, &protocol_connect);
1605 if(!result && protocol_connect) {
1606 /* after the connect has completed, go WAITDO or DO */
1607 multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
1608 CURLM_STATE_WAITDO:CURLM_STATE_DO);
1609 rc = CURLM_CALL_MULTI_PERFORM;
1612 /* failure detected */
1613 Curl_posttransfer(data);
1614 multi_done(&data->easy_conn, result, TRUE);
1615 stream_error = TRUE;
1619 case CURLM_STATE_WAITDO:
1620 /* Wait for our turn to DO when we're pipelining requests */
1621 if(Curl_pipeline_checkget_write(data, data->easy_conn)) {
1622 /* Grabbed the channel */
1623 multistate(data, CURLM_STATE_DO);
1624 rc = CURLM_CALL_MULTI_PERFORM;
1628 case CURLM_STATE_DO:
1629 if(data->set.connect_only) {
1630 /* keep connection open for application to use the socket */
1631 connkeep(data->easy_conn, "CONNECT_ONLY");
1632 multistate(data, CURLM_STATE_DONE);
1634 rc = CURLM_CALL_MULTI_PERFORM;
1637 /* Perform the protocol's DO action */
1638 result = multi_do(&data->easy_conn, &dophase_done);
1640 /* When multi_do() returns failure, data->easy_conn might be NULL! */
1644 /* some steps needed for wildcard matching */
1645 if(data->state.wildcardmatch) {
1646 struct WildcardData *wc = &data->wildcard;
1647 if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
1648 /* skip some states if it is important */
1649 multi_done(&data->easy_conn, CURLE_OK, FALSE);
1650 multistate(data, CURLM_STATE_DONE);
1651 rc = CURLM_CALL_MULTI_PERFORM;
1655 /* DO was not completed in one function call, we must continue
1657 multistate(data, CURLM_STATE_DOING);
1661 /* after DO, go DO_DONE... or DO_MORE */
1662 else if(data->easy_conn->bits.do_more) {
1663 /* we're supposed to do more, but we need to sit down, relax
1664 and wait a little while first */
1665 multistate(data, CURLM_STATE_DO_MORE);
1669 /* we're done with the DO, now DO_DONE */
1670 multistate(data, CURLM_STATE_DO_DONE);
1671 rc = CURLM_CALL_MULTI_PERFORM;
1674 else if((CURLE_SEND_ERROR == result) &&
1675 data->easy_conn->bits.reuse) {
1677 * In this situation, a connection that we were trying to use
1678 * may have unexpectedly died. If possible, send the connection
1679 * back to the CONNECT phase so we can try again.
1681 char *newurl = NULL;
1682 followtype follow = FOLLOW_NONE;
1686 drc = Curl_retry_request(data->easy_conn, &newurl);
1688 /* a failure here pretty much implies an out of memory */
1690 stream_error = TRUE;
1693 retry = (newurl)?TRUE:FALSE;
1695 Curl_posttransfer(data);
1696 drc = multi_done(&data->easy_conn, result, FALSE);
1698 /* When set to retry the connection, we must to go back to
1699 * the CONNECT state */
1701 if(!drc || (drc == CURLE_SEND_ERROR)) {
1702 follow = FOLLOW_RETRY;
1703 drc = Curl_follow(data, newurl, follow);
1705 multistate(data, CURLM_STATE_CONNECT);
1706 rc = CURLM_CALL_MULTI_PERFORM;
1715 /* done didn't return OK or SEND_ERROR */
1720 /* Have error handler disconnect conn if we can't retry */
1721 stream_error = TRUE;
1726 /* failure detected */
1727 Curl_posttransfer(data);
1729 multi_done(&data->easy_conn, result, FALSE);
1730 stream_error = TRUE;
1735 case CURLM_STATE_DOING:
1736 /* we continue DOING until the DO phase is complete */
1737 result = Curl_protocol_doing(data->easy_conn,
1741 /* after DO, go DO_DONE or DO_MORE */
1742 multistate(data, data->easy_conn->bits.do_more?
1743 CURLM_STATE_DO_MORE:
1744 CURLM_STATE_DO_DONE);
1745 rc = CURLM_CALL_MULTI_PERFORM;
1746 } /* dophase_done */
1749 /* failure detected */
1750 Curl_posttransfer(data);
1751 multi_done(&data->easy_conn, result, FALSE);
1752 stream_error = TRUE;
1756 case CURLM_STATE_DO_MORE:
1758 * When we are connected, DO MORE and then go DO_DONE
1760 result = multi_do_more(data->easy_conn, &control);
1762 /* No need to remove this handle from the send pipeline here since that
1763 is done in multi_done() */
1766 /* if positive, advance to DO_DONE
1767 if negative, go back to DOING */
1768 multistate(data, control == 1?
1769 CURLM_STATE_DO_DONE:
1771 rc = CURLM_CALL_MULTI_PERFORM;
1774 /* stay in DO_MORE */
1778 /* failure detected */
1779 Curl_posttransfer(data);
1780 multi_done(&data->easy_conn, result, FALSE);
1781 stream_error = TRUE;
1785 case CURLM_STATE_DO_DONE:
1786 /* Move ourselves from the send to recv pipeline */
1787 Curl_move_handle_from_send_to_recv_pipe(data, data->easy_conn);
1788 /* Check if we can move pending requests to send pipe */
1789 Curl_multi_process_pending_handles(multi);
1791 /* Only perform the transfer if there's a good socket to work with.
1792 Having both BAD is a signal to skip immediately to DONE */
1793 if((data->easy_conn->sockfd != CURL_SOCKET_BAD) ||
1794 (data->easy_conn->writesockfd != CURL_SOCKET_BAD))
1795 multistate(data, CURLM_STATE_WAITPERFORM);
1798 if(data->state.wildcardmatch &&
1799 ((data->easy_conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
1800 data->wildcard.state = CURLWC_DONE;
1802 multistate(data, CURLM_STATE_DONE);
1804 rc = CURLM_CALL_MULTI_PERFORM;
1807 case CURLM_STATE_WAITPERFORM:
1808 /* Wait for our turn to PERFORM */
1809 if(Curl_pipeline_checkget_read(data, data->easy_conn)) {
1810 /* Grabbed the channel */
1811 multistate(data, CURLM_STATE_PERFORM);
1812 rc = CURLM_CALL_MULTI_PERFORM;
1816 case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
1817 /* if both rates are within spec, resume transfer */
1818 if(Curl_pgrsUpdate(data->easy_conn))
1819 result = CURLE_ABORTED_BY_CALLBACK;
1821 result = Curl_speedcheck(data, now);
1824 send_timeout_ms = 0;
1825 if(data->set.max_send_speed > 0)
1826 send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
1827 data->progress.ul_limit_size,
1828 data->set.max_send_speed,
1829 data->progress.ul_limit_start,
1832 recv_timeout_ms = 0;
1833 if(data->set.max_recv_speed > 0)
1834 recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
1835 data->progress.dl_limit_size,
1836 data->set.max_recv_speed,
1837 data->progress.dl_limit_start,
1840 if(send_timeout_ms <= 0 && recv_timeout_ms <= 0)
1841 multistate(data, CURLM_STATE_PERFORM);
1842 else if(send_timeout_ms >= recv_timeout_ms)
1843 Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
1845 Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
1849 case CURLM_STATE_PERFORM:
1851 char *newurl = NULL;
1853 bool comeback = FALSE;
1855 /* check if over send speed */
1856 send_timeout_ms = 0;
1857 if(data->set.max_send_speed > 0)
1858 send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
1859 data->progress.ul_limit_size,
1860 data->set.max_send_speed,
1861 data->progress.ul_limit_start,
1864 /* check if over recv speed */
1865 recv_timeout_ms = 0;
1866 if(data->set.max_recv_speed > 0)
1867 recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
1868 data->progress.dl_limit_size,
1869 data->set.max_recv_speed,
1870 data->progress.dl_limit_start,
1873 if(send_timeout_ms > 0 || recv_timeout_ms > 0) {
1874 multistate(data, CURLM_STATE_TOOFAST);
1875 if(send_timeout_ms >= recv_timeout_ms)
1876 Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
1878 Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
1882 /* read/write data if it is ready to do so */
1883 result = Curl_readwrite(data->easy_conn, data, &done, &comeback);
1887 if(!(k->keepon & KEEP_RECV))
1888 /* We're done receiving */
1889 Curl_pipeline_leave_read(data->easy_conn);
1891 if(!(k->keepon & KEEP_SEND))
1892 /* We're done sending */
1893 Curl_pipeline_leave_write(data->easy_conn);
1895 if(done || (result == CURLE_RECV_ERROR)) {
1896 /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
1897 * condition and the server closed the re-used connection exactly when
1898 * we wanted to use it, so figure out if that is indeed the case.
1900 CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
1902 retry = (newurl)?TRUE:FALSE;
1905 /* if we are to retry, set the result to OK and consider the
1914 * The transfer phase returned error, we mark the connection to get
1915 * closed to prevent being re-used. This is because we can't possibly
1916 * know if the connection is in a good shape or not now. Unless it is
1917 * a protocol which uses two "channels" like FTP, as then the error
1918 * happened in the data connection.
1921 if(!(data->easy_conn->handler->flags & PROTOPT_DUAL) &&
1922 result != CURLE_HTTP2_STREAM)
1923 streamclose(data->easy_conn, "Transfer returned error");
1925 Curl_posttransfer(data);
1926 multi_done(&data->easy_conn, result, TRUE);
1929 followtype follow = FOLLOW_NONE;
1931 /* call this even if the readwrite function returned error */
1932 Curl_posttransfer(data);
1934 /* we're no longer receiving */
1935 Curl_removeHandleFromPipeline(data, &data->easy_conn->recv_pipe);
1937 /* expire the new receiving pipeline head */
1938 if(data->easy_conn->recv_pipe.head)
1939 Curl_expire(data->easy_conn->recv_pipe.head->ptr, 0, EXPIRE_RUN_NOW);
1941 /* Check if we can move pending requests to send pipe */
1942 Curl_multi_process_pending_handles(multi);
1944 /* When we follow redirects or is set to retry the connection, we must
1945 to go back to the CONNECT state */
1946 if(data->req.newurl || retry) {
1948 /* if the URL is a follow-location and not just a retried request
1949 then figure out the URL here */
1951 newurl = data->req.newurl;
1952 data->req.newurl = NULL;
1953 follow = FOLLOW_REDIR;
1956 follow = FOLLOW_RETRY;
1957 result = multi_done(&data->easy_conn, CURLE_OK, FALSE);
1959 result = Curl_follow(data, newurl, follow);
1961 multistate(data, CURLM_STATE_CONNECT);
1962 rc = CURLM_CALL_MULTI_PERFORM;
1967 /* after the transfer is done, go DONE */
1969 /* but first check to see if we got a location info even though we're
1970 not following redirects */
1971 if(data->req.location) {
1973 newurl = data->req.location;
1974 data->req.location = NULL;
1975 result = Curl_follow(data, newurl, FOLLOW_FAKE);
1977 stream_error = TRUE;
1980 multistate(data, CURLM_STATE_DONE);
1981 rc = CURLM_CALL_MULTI_PERFORM;
1985 rc = CURLM_CALL_MULTI_PERFORM;
1991 case CURLM_STATE_DONE:
1992 /* this state is highly transient, so run another loop after this */
1993 rc = CURLM_CALL_MULTI_PERFORM;
1995 if(data->easy_conn) {
1998 /* Remove ourselves from the receive pipeline, if we are there. */
1999 Curl_removeHandleFromPipeline(data, &data->easy_conn->recv_pipe);
2000 /* Check if we can move pending requests to send pipe */
2001 Curl_multi_process_pending_handles(multi);
2003 /* post-transfer command */
2004 res = multi_done(&data->easy_conn, result, FALSE);
2006 /* allow a previously set error code take precedence */
2011 * If there are other handles on the pipeline, multi_done won't set
2012 * easy_conn to NULL. In such a case, curl_multi_remove_handle() can
2013 * access free'd data, if the connection is free'd and the handle
2014 * removed before we perform the processing in CURLM_STATE_COMPLETED
2017 data->easy_conn = NULL;
2020 if(data->state.wildcardmatch) {
2021 if(data->wildcard.state != CURLWC_DONE) {
2022 /* if a wildcard is set and we are not ending -> lets start again
2023 with CURLM_STATE_INIT */
2024 multistate(data, CURLM_STATE_INIT);
2029 /* after we have DONE what we're supposed to do, go COMPLETED, and
2030 it doesn't matter what the multi_done() returned! */
2031 multistate(data, CURLM_STATE_COMPLETED);
2034 case CURLM_STATE_COMPLETED:
2035 /* this is a completed transfer, it is likely to still be connected */
2037 /* This node should be delinked from the list now and we should post
2038 an information message that we are complete. */
2040 /* Important: reset the conn pointer so that we don't point to memory
2041 that could be freed anytime */
2042 data->easy_conn = NULL;
2044 Curl_expire_clear(data); /* stop all timers */
2047 case CURLM_STATE_MSGSENT:
2048 data->result = result;
2049 return CURLM_OK; /* do nothing */
2052 return CURLM_INTERNAL_ERROR;
2056 if(data->mstate < CURLM_STATE_COMPLETED) {
2059 * If an error was returned, and we aren't in completed state now,
2060 * then we go to completed and consider this transfer aborted.
2063 /* NOTE: no attempt to disconnect connections must be made
2064 in the case blocks above - cleanup happens only here */
2066 data->state.pipe_broke = FALSE;
2068 /* Check if we can move pending requests to send pipe */
2069 Curl_multi_process_pending_handles(multi);
2071 if(data->easy_conn) {
2072 /* if this has a connection, unsubscribe from the pipelines */
2073 Curl_pipeline_leave_write(data->easy_conn);
2074 Curl_pipeline_leave_read(data->easy_conn);
2075 Curl_removeHandleFromPipeline(data, &data->easy_conn->send_pipe);
2076 Curl_removeHandleFromPipeline(data, &data->easy_conn->recv_pipe);
2079 /* Don't attempt to send data over a connection that timed out */
2080 bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
2081 /* disconnect properly */
2082 Curl_disconnect(data->easy_conn, dead_connection);
2084 /* This is where we make sure that the easy_conn pointer is reset.
2085 We don't have to do this in every case block above where a
2086 failure is detected */
2087 data->easy_conn = NULL;
2090 else if(data->mstate == CURLM_STATE_CONNECT) {
2091 /* Curl_connect() failed */
2092 (void)Curl_posttransfer(data);
2095 multistate(data, CURLM_STATE_COMPLETED);
2097 /* if there's still a connection to use, call the progress function */
2098 else if(data->easy_conn && Curl_pgrsUpdate(data->easy_conn)) {
2099 /* aborted due to progress callback return code must close the
2101 result = CURLE_ABORTED_BY_CALLBACK;
2102 streamclose(data->easy_conn, "Aborted by callback");
2104 /* if not yet in DONE state, go there, otherwise COMPLETED */
2105 multistate(data, (data->mstate < CURLM_STATE_DONE)?
2106 CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
2107 rc = CURLM_CALL_MULTI_PERFORM;
2111 if(CURLM_STATE_COMPLETED == data->mstate) {
2112 /* now fill in the Curl_message with this info */
2115 msg->extmsg.msg = CURLMSG_DONE;
2116 msg->extmsg.easy_handle = data;
2117 msg->extmsg.data.result = result;
2119 rc = multi_addmsg(multi, msg);
2121 multistate(data, CURLM_STATE_MSGSENT);
2123 } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
2125 data->result = result;
2132 CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
2134 struct Curl_easy *data;
2135 CURLMcode returncode = CURLM_OK;
2136 struct Curl_tree *t;
2137 struct curltime now = Curl_now();
2139 if(!GOOD_MULTI_HANDLE(multi))
2140 return CURLM_BAD_HANDLE;
2142 if(multi->in_callback)
2143 return CURLM_RECURSIVE_API_CALL;
2145 data = multi->easyp;
2148 SIGPIPE_VARIABLE(pipe_st);
2150 sigpipe_ignore(data, &pipe_st);
2151 result = multi_runsingle(multi, now, data);
2152 sigpipe_restore(&pipe_st);
2155 returncode = result;
2157 data = data->next; /* operate on next handle */
2161 * Simply remove all expired timers from the splay since handles are dealt
2162 * with unconditionally by this function and curl_multi_timeout() requires
2163 * that already passed/handled expire times are removed from the splay.
2165 * It is important that the 'now' value is set at the entry of this function
2166 * and not for the current time as it may have ticked a little while since
2167 * then and then we risk this loop to remove timers that actually have not
2171 multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2173 /* the removed may have another timeout in queue */
2174 (void)add_next_timeout(now, multi, t->payload);
2178 *running_handles = multi->num_alive;
2180 if(CURLM_OK >= returncode)
2181 update_timer(multi);
2186 CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
2188 struct Curl_easy *data;
2189 struct Curl_easy *nextdata;
2191 if(GOOD_MULTI_HANDLE(multi)) {
2192 if(multi->in_callback)
2193 return CURLM_RECURSIVE_API_CALL;
2195 multi->type = 0; /* not good anymore */
2197 /* Firsrt remove all remaining easy handles */
2198 data = multi->easyp;
2200 nextdata = data->next;
2201 if(!data->state.done && data->easy_conn)
2202 /* if DONE was never called for this handle */
2203 (void)multi_done(&data->easy_conn, CURLE_OK, TRUE);
2204 if(data->dns.hostcachetype == HCACHE_MULTI) {
2205 /* clear out the usage of the shared DNS cache */
2206 Curl_hostcache_clean(data, data->dns.hostcache);
2207 data->dns.hostcache = NULL;
2208 data->dns.hostcachetype = HCACHE_NONE;
2211 /* Clear the pointer to the connection cache */
2212 data->state.conn_cache = NULL;
2213 data->multi = NULL; /* clear the association */
2218 /* Close all the connections in the connection cache */
2219 Curl_conncache_close_all_connections(&multi->conn_cache);
2221 Curl_hash_destroy(&multi->sockhash);
2222 Curl_conncache_destroy(&multi->conn_cache);
2223 Curl_llist_destroy(&multi->msglist, NULL);
2224 Curl_llist_destroy(&multi->pending, NULL);
2226 Curl_hash_destroy(&multi->hostcache);
2228 /* Free the blacklists by setting them to NULL */
2229 Curl_pipeline_set_site_blacklist(NULL, &multi->pipelining_site_bl);
2230 Curl_pipeline_set_server_blacklist(NULL, &multi->pipelining_server_bl);
2236 return CURLM_BAD_HANDLE;
2240 * curl_multi_info_read()
2242 * This function is the primary way for a multi/multi_socket application to
2243 * figure out if a transfer has ended. We MUST make this function as fast as
2244 * possible as it will be polled frequently and we MUST NOT scan any lists in
2245 * here to figure out things. We must scale fine to thousands of handles and
2246 * beyond. The current design is fully O(1).
2249 CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
2251 struct Curl_message *msg;
2253 *msgs_in_queue = 0; /* default to none */
2255 if(GOOD_MULTI_HANDLE(multi) &&
2256 !multi->in_callback &&
2257 Curl_llist_count(&multi->msglist)) {
2258 /* there is one or more messages in the list */
2259 struct curl_llist_element *e;
2261 /* extract the head of the list to return */
2262 e = multi->msglist.head;
2266 /* remove the extracted entry */
2267 Curl_llist_remove(&multi->msglist, e, NULL);
2269 *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
2271 return &msg->extmsg;
2277 * singlesocket() checks what sockets we deal with and their "action state"
2278 * and if we have a different state in any of those sockets from last time we
2279 * call the callback accordingly.
2281 static void singlesocket(struct Curl_multi *multi,
2282 struct Curl_easy *data)
2284 curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
2286 struct Curl_sh_entry *entry;
2289 unsigned int curraction;
2291 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
2292 socks[i] = CURL_SOCKET_BAD;
2294 /* Fill in the 'current' struct with the state as it is now: what sockets to
2295 supervise and for what actions */
2296 curraction = multi_getsock(data, socks, MAX_SOCKSPEREASYHANDLE);
2298 /* We have 0 .. N sockets already and we get to know about the 0 .. M
2299 sockets we should have from now on. Detect the differences, remove no
2300 longer supervised ones and add new ones */
2302 /* walk over the sockets we got right now */
2303 for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
2304 (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
2306 int action = CURL_POLL_NONE;
2310 /* get it from the hash */
2311 entry = sh_getentry(&multi->sockhash, s);
2313 if(curraction & GETSOCK_READSOCK(i))
2314 action |= CURL_POLL_IN;
2315 if(curraction & GETSOCK_WRITESOCK(i))
2316 action |= CURL_POLL_OUT;
2319 /* yeps, already present so check if it has the same action set */
2320 if(entry->action == action)
2321 /* same, continue */
2325 /* this is a socket we didn't have before, add it! */
2326 entry = sh_addentry(&multi->sockhash, s, data);
2332 /* we know (entry != NULL) at this point, see the logic above */
2333 if(multi->socket_cb)
2334 multi->socket_cb(data,
2337 multi->socket_userp,
2340 entry->action = action; /* store the current action state */
2343 num = i; /* number of sockets */
2345 /* when we've walked over all the sockets we should have right now, we must
2346 make sure to detect sockets that are removed */
2347 for(i = 0; i< data->numsocks; i++) {
2349 s = data->sockets[i];
2350 for(j = 0; j<num; j++) {
2352 /* this is still supervised */
2353 s = CURL_SOCKET_BAD;
2358 entry = sh_getentry(&multi->sockhash, s);
2360 /* this socket has been removed. Tell the app to remove it */
2361 bool remove_sock_from_hash = TRUE;
2363 /* check if the socket to be removed serves a connection which has
2364 other easy-s in a pipeline. In this case the socket should not be
2366 struct connectdata *easy_conn = data->easy_conn;
2368 if(easy_conn->recv_pipe.size > 1) {
2369 /* the handle should not be removed from the pipe yet */
2370 remove_sock_from_hash = FALSE;
2372 /* Update the sockhash entry to instead point to the next in line
2373 for the recv_pipe, or the first (in case this particular easy
2375 if(entry->easy == data) {
2376 if(Curl_recvpipe_head(data, easy_conn))
2377 entry->easy = easy_conn->recv_pipe.head->next->ptr;
2379 entry->easy = easy_conn->recv_pipe.head->ptr;
2382 if(easy_conn->send_pipe.size > 1) {
2383 /* the handle should not be removed from the pipe yet */
2384 remove_sock_from_hash = FALSE;
2386 /* Update the sockhash entry to instead point to the next in line
2387 for the send_pipe, or the first (in case this particular easy
2389 if(entry->easy == data) {
2390 if(Curl_sendpipe_head(data, easy_conn))
2391 entry->easy = easy_conn->send_pipe.head->next->ptr;
2393 entry->easy = easy_conn->send_pipe.head->ptr;
2396 /* Don't worry about overwriting recv_pipe head with send_pipe_head,
2397 when action will be asked on the socket (see multi_socket()), the
2398 head of the correct pipe will be taken according to the
2402 if(remove_sock_from_hash) {
2403 /* in this case 'entry' is always non-NULL */
2404 if(multi->socket_cb)
2405 multi->socket_cb(data,
2408 multi->socket_userp,
2410 sh_delentry(&multi->sockhash, s);
2412 } /* if sockhash entry existed */
2413 } /* for loop over numsocks */
2415 memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
2416 data->numsocks = num;
2420 * Curl_multi_closed()
2422 * Used by the connect code to tell the multi_socket code that one of the
2423 * sockets we were using is about to be closed. This function will then
2424 * remove it from the sockethash for this handle to make the multi_socket API
2425 * behave properly, especially for the case when libcurl will create another
2426 * socket again and it gets the same file descriptor number.
2429 void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
2431 struct Curl_multi *multi = conn->data->multi;
2433 /* this is set if this connection is part of a handle that is added to
2434 a multi handle, and only then this is necessary */
2435 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
2438 if(multi->socket_cb)
2439 multi->socket_cb(conn->data, s, CURL_POLL_REMOVE,
2440 multi->socket_userp,
2443 /* now remove it from the socket hash */
2444 sh_delentry(&multi->sockhash, s);
2450 * add_next_timeout()
2452 * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
2453 * when it has just been removed from the splay tree because the timeout has
2454 * expired. This function is then to advance in the list to pick the next
2455 * timeout to use (skip the already expired ones) and add this node back to
2456 * the splay tree again.
2458 * The splay tree only has each sessionhandle as a single node and the nearest
2459 * timeout is used to sort it on.
2461 static CURLMcode add_next_timeout(struct curltime now,
2462 struct Curl_multi *multi,
2463 struct Curl_easy *d)
2465 struct curltime *tv = &d->state.expiretime;
2466 struct curl_llist *list = &d->state.timeoutlist;
2467 struct curl_llist_element *e;
2468 struct time_node *node = NULL;
2470 /* move over the timeout list for this specific handle and remove all
2471 timeouts that are now passed tense and store the next pending
2473 for(e = list->head; e;) {
2474 struct curl_llist_element *n = e->next;
2476 node = (struct time_node *)e->ptr;
2477 diff = Curl_timediff(node->time, now);
2479 /* remove outdated entry */
2480 Curl_llist_remove(list, e, NULL);
2482 /* the list is sorted so get out on the first mismatch */
2488 /* clear the expire times within the handles that we remove from the
2494 /* copy the first entry to 'tv' */
2495 memcpy(tv, &node->time, sizeof(*tv));
2497 /* Insert this node again into the splay. Keep the timer in the list in
2498 case we need to recompute future timers. */
2499 multi->timetree = Curl_splayinsert(*tv, multi->timetree,
2500 &d->state.timenode);
2505 static CURLMcode multi_socket(struct Curl_multi *multi,
2509 int *running_handles)
2511 CURLMcode result = CURLM_OK;
2512 struct Curl_easy *data = NULL;
2513 struct Curl_tree *t;
2514 struct curltime now = Curl_now();
2517 /* *perform() deals with running_handles on its own */
2518 result = curl_multi_perform(multi, running_handles);
2520 /* walk through each easy handle and do the socket state change magic
2522 if(result != CURLM_BAD_HANDLE) {
2523 data = multi->easyp;
2525 singlesocket(multi, data);
2530 /* or should we fall-through and do the timer-based stuff? */
2533 if(s != CURL_SOCKET_TIMEOUT) {
2535 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
2538 /* Unmatched socket, we can't act on it but we ignore this fact. In
2539 real-world tests it has been proved that libevent can in fact give
2540 the application actions even though the socket was just previously
2541 asked to get removed, so thus we better survive stray socket actions
2542 and just move on. */
2545 SIGPIPE_VARIABLE(pipe_st);
2549 if(data->magic != CURLEASY_MAGIC_NUMBER)
2550 /* bad bad bad bad bad bad bad */
2551 return CURLM_INTERNAL_ERROR;
2553 /* If the pipeline is enabled, take the handle which is in the head of
2554 the pipeline. If we should write into the socket, take the send_pipe
2555 head. If we should read from the socket, take the recv_pipe head. */
2556 if(data->easy_conn) {
2557 if((ev_bitmask & CURL_POLL_OUT) &&
2558 data->easy_conn->send_pipe.head)
2559 data = data->easy_conn->send_pipe.head->ptr;
2560 else if((ev_bitmask & CURL_POLL_IN) &&
2561 data->easy_conn->recv_pipe.head)
2562 data = data->easy_conn->recv_pipe.head->ptr;
2565 if(data->easy_conn &&
2566 !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
2567 /* set socket event bitmask if they're not locked */
2568 data->easy_conn->cselect_bits = ev_bitmask;
2570 sigpipe_ignore(data, &pipe_st);
2571 result = multi_runsingle(multi, now, data);
2572 sigpipe_restore(&pipe_st);
2574 if(data->easy_conn &&
2575 !(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
2576 /* clear the bitmask only if not locked */
2577 data->easy_conn->cselect_bits = 0;
2579 if(CURLM_OK >= result)
2580 /* get the socket(s) and check if the state has been changed since
2582 singlesocket(multi, data);
2584 /* Now we fall-through and do the timer-based stuff, since we don't want
2585 to force the user to have to deal with timeouts as long as at least
2586 one connection in fact has traffic. */
2588 data = NULL; /* set data to NULL again to avoid calling
2589 multi_runsingle() in case there's no need to */
2590 now = Curl_now(); /* get a newer time since the multi_runsingle() loop
2591 may have taken some time */
2595 /* Asked to run due to time-out. Clear the 'lastcall' variable to force
2596 update_timer() to trigger a callback to the app again even if the same
2597 timeout is still the one to run after this call. That handles the case
2598 when the application asks libcurl to run the timeout prematurely. */
2599 memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
2603 * The loop following here will go on as long as there are expire-times left
2604 * to process in the splay and 'data' will be re-assigned for every expired
2605 * handle we deal with.
2608 /* the first loop lap 'data' can be NULL */
2610 SIGPIPE_VARIABLE(pipe_st);
2612 sigpipe_ignore(data, &pipe_st);
2613 result = multi_runsingle(multi, now, data);
2614 sigpipe_restore(&pipe_st);
2616 if(CURLM_OK >= result)
2617 /* get the socket(s) and check if the state has been changed since
2619 singlesocket(multi, data);
2622 /* Check if there's one (more) expired timer to deal with! This function
2623 extracts a matching node if there is one */
2625 multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2627 data = t->payload; /* assign this for next loop */
2628 (void)add_next_timeout(now, multi, t->payload);
2633 *running_handles = multi->num_alive;
2637 #undef curl_multi_setopt
2638 CURLMcode curl_multi_setopt(struct Curl_multi *multi,
2639 CURLMoption option, ...)
2641 CURLMcode res = CURLM_OK;
2644 if(!GOOD_MULTI_HANDLE(multi))
2645 return CURLM_BAD_HANDLE;
2647 if(multi->in_callback)
2648 return CURLM_RECURSIVE_API_CALL;
2650 va_start(param, option);
2653 case CURLMOPT_SOCKETFUNCTION:
2654 multi->socket_cb = va_arg(param, curl_socket_callback);
2656 case CURLMOPT_SOCKETDATA:
2657 multi->socket_userp = va_arg(param, void *);
2659 case CURLMOPT_PUSHFUNCTION:
2660 multi->push_cb = va_arg(param, curl_push_callback);
2662 case CURLMOPT_PUSHDATA:
2663 multi->push_userp = va_arg(param, void *);
2665 case CURLMOPT_PIPELINING:
2666 multi->pipelining = va_arg(param, long);
2668 case CURLMOPT_TIMERFUNCTION:
2669 multi->timer_cb = va_arg(param, curl_multi_timer_callback);
2671 case CURLMOPT_TIMERDATA:
2672 multi->timer_userp = va_arg(param, void *);
2674 case CURLMOPT_MAXCONNECTS:
2675 multi->maxconnects = va_arg(param, long);
2677 case CURLMOPT_MAX_HOST_CONNECTIONS:
2678 multi->max_host_connections = va_arg(param, long);
2680 case CURLMOPT_MAX_PIPELINE_LENGTH:
2681 multi->max_pipeline_length = va_arg(param, long);
2683 case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
2684 multi->content_length_penalty_size = va_arg(param, long);
2686 case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
2687 multi->chunk_length_penalty_size = va_arg(param, long);
2689 case CURLMOPT_PIPELINING_SITE_BL:
2690 res = Curl_pipeline_set_site_blacklist(va_arg(param, char **),
2691 &multi->pipelining_site_bl);
2693 case CURLMOPT_PIPELINING_SERVER_BL:
2694 res = Curl_pipeline_set_server_blacklist(va_arg(param, char **),
2695 &multi->pipelining_server_bl);
2697 case CURLMOPT_MAX_TOTAL_CONNECTIONS:
2698 multi->max_total_connections = va_arg(param, long);
2701 res = CURLM_UNKNOWN_OPTION;
2708 /* we define curl_multi_socket() in the public multi.h header */
2709 #undef curl_multi_socket
2711 CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
2712 int *running_handles)
2715 if(multi->in_callback)
2716 return CURLM_RECURSIVE_API_CALL;
2717 result = multi_socket(multi, FALSE, s, 0, running_handles);
2718 if(CURLM_OK >= result)
2719 update_timer(multi);
2723 CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
2724 int ev_bitmask, int *running_handles)
2727 if(multi->in_callback)
2728 return CURLM_RECURSIVE_API_CALL;
2729 result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
2730 if(CURLM_OK >= result)
2731 update_timer(multi);
2735 CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
2739 if(multi->in_callback)
2740 return CURLM_RECURSIVE_API_CALL;
2741 result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
2742 if(CURLM_OK >= result)
2743 update_timer(multi);
2747 static CURLMcode multi_timeout(struct Curl_multi *multi,
2750 static struct curltime tv_zero = {0, 0};
2752 if(multi->timetree) {
2753 /* we have a tree of expire times */
2754 struct curltime now = Curl_now();
2756 /* splay the lowest to the bottom */
2757 multi->timetree = Curl_splay(tv_zero, multi->timetree);
2759 if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
2760 /* some time left before expiration */
2761 timediff_t diff = Curl_timediff(multi->timetree->key, now);
2764 * Since we only provide millisecond resolution on the returned value
2765 * and the diff might be less than one millisecond here, we don't
2766 * return zero as that may cause short bursts of busyloops on fast
2767 * processors while the diff is still present but less than one
2768 * millisecond! instead we return 1 until the time is ripe.
2772 /* this should be safe even on 64 bit archs, as we don't use that
2773 overly long timeouts */
2774 *timeout_ms = (long)diff;
2777 /* 0 means immediately */
2786 CURLMcode curl_multi_timeout(struct Curl_multi *multi,
2789 /* First, make some basic checks that the CURLM handle is a good handle */
2790 if(!GOOD_MULTI_HANDLE(multi))
2791 return CURLM_BAD_HANDLE;
2793 if(multi->in_callback)
2794 return CURLM_RECURSIVE_API_CALL;
2796 return multi_timeout(multi, timeout_ms);
2800 * Tell the application it should update its timers, if it subscribes to the
2801 * update timer callback.
2803 static int update_timer(struct Curl_multi *multi)
2807 if(!multi->timer_cb)
2809 if(multi_timeout(multi, &timeout_ms)) {
2812 if(timeout_ms < 0) {
2813 static const struct curltime none = {0, 0};
2814 if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
2815 multi->timer_lastcall = none;
2816 /* there's no timeout now but there was one previously, tell the app to
2818 return multi->timer_cb(multi, -1, multi->timer_userp);
2823 /* When multi_timeout() is done, multi->timetree points to the node with the
2824 * timeout we got the (relative) time-out time for. We can thus easily check
2825 * if this is the same (fixed) time as we got in a previous call and then
2826 * avoid calling the callback again. */
2827 if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
2830 multi->timer_lastcall = multi->timetree->key;
2832 return multi->timer_cb(multi, timeout_ms, multi->timer_userp);
2836 * multi_deltimeout()
2838 * Remove a given timestamp from the list of timeouts.
2841 multi_deltimeout(struct Curl_easy *data, expire_id eid)
2843 struct curl_llist_element *e;
2844 struct curl_llist *timeoutlist = &data->state.timeoutlist;
2845 /* find and remove the specific node from the list */
2846 for(e = timeoutlist->head; e; e = e->next) {
2847 struct time_node *n = (struct time_node *)e->ptr;
2849 Curl_llist_remove(timeoutlist, e, NULL);
2856 * multi_addtimeout()
2858 * Add a timestamp to the list of timeouts. Keep the list sorted so that head
2859 * of list is always the timeout nearest in time.
2863 multi_addtimeout(struct Curl_easy *data,
2864 struct curltime *stamp,
2867 struct curl_llist_element *e;
2868 struct time_node *node;
2869 struct curl_llist_element *prev = NULL;
2871 struct curl_llist *timeoutlist = &data->state.timeoutlist;
2873 node = &data->state.expires[eid];
2875 /* copy the timestamp and id */
2876 memcpy(&node->time, stamp, sizeof(*stamp));
2877 node->eid = eid; /* also marks it as in use */
2879 n = Curl_llist_count(timeoutlist);
2881 /* find the correct spot in the list */
2882 for(e = timeoutlist->head; e; e = e->next) {
2883 struct time_node *check = (struct time_node *)e->ptr;
2884 timediff_t diff = Curl_timediff(check->time, node->time);
2892 this is the first timeout on the list */
2894 Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
2901 * given a number of milliseconds from now to use to set the 'act before
2902 * this'-time for the transfer, to be extracted by curl_multi_timeout()
2904 * The timeout will be added to a queue of timeouts if it defines a moment in
2905 * time that is later than the current head of queue.
2907 * Expire replaces a former timeout using the same id if already set.
2909 void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id)
2911 struct Curl_multi *multi = data->multi;
2912 struct curltime *nowp = &data->state.expiretime;
2914 struct curltime set;
2916 /* this is only interesting while there is still an associated multi struct
2921 DEBUGASSERT(id < EXPIRE_LAST);
2924 set.tv_sec += milli/1000;
2925 set.tv_usec += (unsigned int)(milli%1000)*1000;
2927 if(set.tv_usec >= 1000000) {
2929 set.tv_usec -= 1000000;
2932 /* Remove any timer with the same id just in case. */
2933 multi_deltimeout(data, id);
2935 /* Add it to the timer list. It must stay in the list until it has expired
2936 in case we need to recompute the minimum timer later. */
2937 multi_addtimeout(data, &set, id);
2939 if(nowp->tv_sec || nowp->tv_usec) {
2940 /* This means that the struct is added as a node in the splay tree.
2941 Compare if the new time is earlier, and only remove-old/add-new if it
2943 timediff_t diff = Curl_timediff(set, *nowp);
2946 /* The current splay tree entry is sooner than this new expiry time.
2947 We don't need to update our splay tree entry. */
2951 /* Since this is an updated time, we must remove the previous entry from
2952 the splay tree first and then re-add the new value */
2953 rc = Curl_splayremovebyaddr(multi->timetree,
2954 &data->state.timenode,
2957 infof(data, "Internal error removing splay node = %d\n", rc);
2960 /* Indicate that we are in the splay tree and insert the new timer expiry
2961 value since it is our local minimum. */
2963 data->state.timenode.payload = data;
2964 multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
2965 &data->state.timenode);
2969 * Curl_expire_done()
2971 * Removes the expire timer. Marks it as done.
2974 void Curl_expire_done(struct Curl_easy *data, expire_id id)
2976 /* remove the timer, if there */
2977 multi_deltimeout(data, id);
2981 * Curl_expire_clear()
2983 * Clear ALL timeout values for this handle.
2985 void Curl_expire_clear(struct Curl_easy *data)
2987 struct Curl_multi *multi = data->multi;
2988 struct curltime *nowp = &data->state.expiretime;
2991 /* this is only interesting while there is still an associated multi struct
2996 if(nowp->tv_sec || nowp->tv_usec) {
2997 /* Since this is an cleared time, we must remove the previous entry from
2999 struct curl_llist *list = &data->state.timeoutlist;
3001 rc = Curl_splayremovebyaddr(multi->timetree,
3002 &data->state.timenode,
3005 infof(data, "Internal error clearing splay node = %d\n", rc);
3007 /* flush the timeout list too */
3008 while(list->size > 0) {
3009 Curl_llist_remove(list, list->tail, NULL);
3013 infof(data, "Expire cleared\n");
3023 CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
3026 struct Curl_sh_entry *there = NULL;
3028 if(multi->in_callback)
3029 return CURLM_RECURSIVE_API_CALL;
3031 there = sh_getentry(&multi->sockhash, s);
3034 return CURLM_BAD_SOCKET;
3036 there->socketp = hashp;
3041 size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
3043 return multi ? multi->max_host_connections : 0;
3046 size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
3048 return multi ? multi->max_total_connections : 0;
3051 curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi)
3053 return multi ? multi->content_length_penalty_size : 0;
3056 curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi)
3058 return multi ? multi->chunk_length_penalty_size : 0;
3061 struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi)
3063 return &multi->pipelining_site_bl;
3066 struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi)
3068 return &multi->pipelining_server_bl;
3071 void Curl_multi_process_pending_handles(struct Curl_multi *multi)
3073 struct curl_llist_element *e = multi->pending.head;
3076 struct Curl_easy *data = e->ptr;
3077 struct curl_llist_element *next = e->next;
3079 if(data->mstate == CURLM_STATE_CONNECT_PEND) {
3080 multistate(data, CURLM_STATE_CONNECT);
3082 /* Remove this node from the list */
3083 Curl_llist_remove(&multi->pending, e, NULL);
3085 /* Make sure that the handle will be processed soonish. */
3086 Curl_expire(data, 0, EXPIRE_RUN_NOW);
3089 e = next; /* operate on next handle */
3093 void Curl_set_in_callback(struct Curl_easy *easy, bool value)
3095 if(easy->multi_easy)
3096 easy->multi_easy->in_callback = value;
3097 else if(easy->multi)
3098 easy->multi->in_callback = value;
3101 bool Curl_is_in_callback(struct Curl_easy *easy)
3103 return ((easy->multi && easy->multi->in_callback) ||
3104 (easy->multi_easy && easy->multi_easy->in_callback));
3108 void Curl_multi_dump(struct Curl_multi *multi)
3110 struct Curl_easy *data;
3112 fprintf(stderr, "* Multi status: %d handles, %d alive\n",
3113 multi->num_easy, multi->num_alive);
3114 for(data = multi->easyp; data; data = data->next) {
3115 if(data->mstate < CURLM_STATE_COMPLETED) {
3116 /* only display handles that are not completed */
3117 fprintf(stderr, "handle %p, state %s, %d sockets\n",
3119 statename[data->mstate], data->numsocks);
3120 for(i = 0; i < data->numsocks; i++) {
3121 curl_socket_t s = data->sockets[i];
3122 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
3124 fprintf(stderr, "%d ", (int)s);
3126 fprintf(stderr, "INTERNAL CONFUSION\n");
3129 fprintf(stderr, "[%s %s] ",
3130 entry->action&CURL_POLL_IN?"RECVING":"",
3131 entry->action&CURL_POLL_OUT?"SENDING":"");
3134 fprintf(stderr, "\n");