1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2020, 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>
41 #include "speedcheck.h"
42 #include "conncache.h"
43 #include "multihandle.h"
45 #include "vtls/vtls.h"
47 #include "http_proxy.h"
49 #include "socketpair.h"
51 /* The last 3 #include files should be in this order */
52 #include "curl_printf.h"
53 #include "curl_memory.h"
57 CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
58 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
59 CURL handle takes 45-50 K memory, therefore this 3K are not significant.
61 #ifndef CURL_SOCKET_HASH_TABLE_SIZE
62 #define CURL_SOCKET_HASH_TABLE_SIZE 911
65 #ifndef CURL_CONNECTION_HASH_SIZE
66 #define CURL_CONNECTION_HASH_SIZE 97
69 #define CURL_MULTI_HANDLE 0x000bab1e
71 #define GOOD_MULTI_HANDLE(x) \
72 ((x) && (x)->type == CURL_MULTI_HANDLE)
74 static CURLMcode singlesocket(struct Curl_multi *multi,
75 struct Curl_easy *data);
76 static CURLMcode add_next_timeout(struct curltime now,
77 struct Curl_multi *multi,
79 static CURLMcode multi_timeout(struct Curl_multi *multi,
81 static void process_pending_handles(struct Curl_multi *multi);
84 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 static void Curl_init_completed(struct Curl_easy *data)
110 /* this is a completed transfer */
112 /* Important: reset the conn pointer so that we don't point to memory
113 that could be freed anytime */
114 Curl_detach_connnection(data);
115 Curl_expire_clear(data); /* stop all timers */
118 /* always use this function to change state, to make debugging easier */
119 static void mstate(struct Curl_easy *data, CURLMstate state
125 CURLMstate oldstate = data->mstate;
126 static const init_multistate_func finit[CURLM_STATE_LAST] = {
128 NULL, /* CONNECT_PEND */
129 Curl_init_CONNECT, /* CONNECT */
130 NULL, /* WAITRESOLVE */
131 NULL, /* WAITCONNECT */
132 NULL, /* WAITPROXYCONNECT */
133 NULL, /* SENDPROTOCONNECT */
134 NULL, /* PROTOCONNECT */
135 Curl_connect_free, /* DO */
142 Curl_init_completed, /* COMPLETED */
146 #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
150 if(oldstate == state)
151 /* don't bother when the new state is the same as the old state */
154 data->mstate = state;
156 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
157 if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
158 data->mstate < CURLM_STATE_COMPLETED) {
159 long connection_id = -5000;
162 connection_id = data->conn->connection_id;
165 "STATE: %s => %s handle %p; line %d (connection #%ld)\n",
166 statename[oldstate], statename[data->mstate],
167 (void *)data, lineno, connection_id);
171 if(state == CURLM_STATE_COMPLETED) {
172 /* changing to COMPLETED means there's one less easy handle 'alive' */
173 DEBUGASSERT(data->multi->num_alive > 0);
174 data->multi->num_alive--;
177 /* if this state has an init-function, run it */
183 #define multistate(x,y) mstate(x,y)
185 #define multistate(x,y) mstate(x,y, __LINE__)
189 * We add one of these structs to the sockhash for each socket
192 struct Curl_sh_entry {
193 struct Curl_hash transfers; /* hash of transfers using this socket */
194 unsigned int action; /* what combined action READ/WRITE this socket waits
196 void *socketp; /* settable by users with curl_multi_assign() */
197 unsigned int users; /* number of transfers using this */
198 unsigned int readers; /* this many transfers want to read */
199 unsigned int writers; /* this many transfers want to write */
201 /* bits for 'action' having no bits means this socket is not expecting any
206 /* look up a given socket in the socket hash, skip invalid sockets */
207 static struct Curl_sh_entry *sh_getentry(struct Curl_hash *sh,
210 if(s != CURL_SOCKET_BAD) {
211 /* only look for proper sockets */
212 return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
217 #define TRHASH_SIZE 13
218 static size_t trhash(void *key, size_t key_length, size_t slots_num)
220 size_t keyval = (size_t)*(struct Curl_easy **)key;
223 return (keyval % slots_num);
226 static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
231 return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2;
234 static void trhash_dtor(void *nada)
240 /* make sure this socket is present in the hash for this handle */
241 static struct Curl_sh_entry *sh_addentry(struct Curl_hash *sh,
244 struct Curl_sh_entry *there = sh_getentry(sh, s);
245 struct Curl_sh_entry *check;
248 /* it is present, return fine */
252 /* not present, add it */
253 check = calloc(1, sizeof(struct Curl_sh_entry));
255 return NULL; /* major failure */
257 if(Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash,
258 trhash_compare, trhash_dtor)) {
263 /* make/add new hash entry */
264 if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
265 Curl_hash_destroy(&check->transfers);
267 return NULL; /* major failure */
270 return check; /* things are good in sockhash land */
274 /* delete the given socket + handle from the hash */
275 static void sh_delentry(struct Curl_sh_entry *entry,
276 struct Curl_hash *sh, curl_socket_t s)
278 Curl_hash_destroy(&entry->transfers);
280 /* We remove the hash entry. This will end up in a call to
282 Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
286 * free a sockhash entry
288 static void sh_freeentry(void *freethis)
290 struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
295 static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
297 (void) k1_len; (void) k2_len;
299 return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2));
302 static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
304 curl_socket_t fd = *((curl_socket_t *) key);
307 return (fd % slots_num);
311 * sh_init() creates a new socket hash and returns the handle for it.
313 * Quote from README.multi_socket:
315 * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
316 * is somewhat of a bottle neck. Its current implementation may be a bit too
317 * limiting. It simply has a fixed-size array, and on each entry in the array
318 * it has a linked list with entries. So the hash only checks which list to
319 * scan through. The code I had used so for used a list with merely 7 slots
320 * (as that is what the DNS hash uses) but with 7000 connections that would
321 * make an average of 1000 nodes in each list to run through. I upped that to
322 * 97 slots (I believe a prime is suitable) and noticed a significant speed
323 * increase. I need to reconsider the hash implementation or use a rather
324 * large default value like this. At 9000 connections I was still below 10us
328 static int sh_init(struct Curl_hash *hash, int hashsize)
330 return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
337 * Called when a transfer is completed. Adds the given msg pointer to
338 * the list kept in the multi handle.
340 static CURLMcode multi_addmsg(struct Curl_multi *multi,
341 struct Curl_message *msg)
343 Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg,
348 struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
349 int chashsize) /* connection hash */
351 struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
356 multi->type = CURL_MULTI_HANDLE;
358 if(Curl_mk_dnscache(&multi->hostcache))
361 if(sh_init(&multi->sockhash, hashsize))
364 if(Curl_conncache_init(&multi->conn_cache, chashsize))
367 Curl_llist_init(&multi->msglist, NULL);
368 Curl_llist_init(&multi->pending, NULL);
370 multi->multiplexing = TRUE;
372 /* -1 means it not set by user, use the default value */
373 multi->maxconnects = -1;
374 multi->max_concurrent_streams = 100;
375 multi->ipv6_works = Curl_ipv6works(NULL);
378 multi->wsa_event = WSACreateEvent();
379 if(multi->wsa_event == WSA_INVALID_EVENT)
383 if(Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, multi->wakeup_pair) < 0) {
384 multi->wakeup_pair[0] = CURL_SOCKET_BAD;
385 multi->wakeup_pair[1] = CURL_SOCKET_BAD;
387 else if(curlx_nonblock(multi->wakeup_pair[0], TRUE) < 0 ||
388 curlx_nonblock(multi->wakeup_pair[1], TRUE) < 0) {
389 sclose(multi->wakeup_pair[0]);
390 sclose(multi->wakeup_pair[1]);
391 multi->wakeup_pair[0] = CURL_SOCKET_BAD;
392 multi->wakeup_pair[1] = CURL_SOCKET_BAD;
401 Curl_hash_destroy(&multi->sockhash);
402 Curl_hash_destroy(&multi->hostcache);
403 Curl_conncache_destroy(&multi->conn_cache);
404 Curl_llist_destroy(&multi->msglist, NULL);
405 Curl_llist_destroy(&multi->pending, NULL);
411 struct Curl_multi *curl_multi_init(void)
413 return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
414 CURL_CONNECTION_HASH_SIZE);
417 CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
418 struct Curl_easy *data)
420 /* First, make some basic checks that the CURLM handle is a good handle */
421 if(!GOOD_MULTI_HANDLE(multi))
422 return CURLM_BAD_HANDLE;
424 /* Verify that we got a somewhat good easy handle too */
425 if(!GOOD_EASY_HANDLE(data))
426 return CURLM_BAD_EASY_HANDLE;
428 /* Prevent users from adding same easy handle more than once and prevent
429 adding to more than one multi stack */
431 return CURLM_ADDED_ALREADY;
433 if(multi->in_callback)
434 return CURLM_RECURSIVE_API_CALL;
436 /* Initialize timeout list for this handle */
437 Curl_llist_init(&data->state.timeoutlist, NULL);
440 * No failure allowed in this function beyond this point. And no
441 * modification of easy nor multi handle allowed before this except for
442 * potential multi's connection cache growing which won't be undone in this
443 * function no matter what.
445 if(data->set.errorbuffer)
446 data->set.errorbuffer[0] = 0;
448 /* set the easy handle */
449 multistate(data, CURLM_STATE_INIT);
451 /* for multi interface connections, we share DNS cache automatically if the
452 easy handle's one is currently not set. */
453 if(!data->dns.hostcache ||
454 (data->dns.hostcachetype == HCACHE_NONE)) {
455 data->dns.hostcache = &multi->hostcache;
456 data->dns.hostcachetype = HCACHE_MULTI;
459 /* Point to the shared or multi handle connection cache */
460 if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT)))
461 data->state.conn_cache = &data->share->conn_cache;
463 data->state.conn_cache = &multi->conn_cache;
464 data->state.lastconnect_id = -1;
467 /* Do the same for PSL. */
468 if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL)))
469 data->psl = &data->share->psl;
471 data->psl = &multi->psl;
474 /* We add the new entry last in the list. */
475 data->next = NULL; /* end of the line */
477 struct Curl_easy *last = multi->easylp;
480 multi->easylp = data; /* the new last node */
483 /* first node, make prev NULL! */
485 multi->easylp = multi->easyp = data; /* both first and last */
488 /* make the Curl_easy refer back to this multi handle */
491 /* Set the timeout for this handle to expire really soon so that it will
492 be taken care of even when this handle is added in the midst of operation
493 when only the curl_multi_socket() API is used. During that flow, only
494 sockets that time-out or have actions will be dealt with. Since this
495 handle has no action yet, we make sure it times out to get things to
497 Curl_expire(data, 0, EXPIRE_RUN_NOW);
499 /* increase the node-counter */
502 /* increase the alive-counter */
505 /* A somewhat crude work-around for a little glitch in Curl_update_timer()
506 that happens if the lastcall time is set to the same time when the handle
507 is removed as when the next handle is added, as then the check in
508 Curl_update_timer() that prevents calling the application multiple times
509 with the same timer info will not trigger and then the new handle's
510 timeout will not be notified to the app.
512 The work-around is thus simply to clear the 'lastcall' variable to force
513 Curl_update_timer() to always trigger a callback to the app when a new
514 easy handle is added */
515 memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
517 CONNCACHE_LOCK(data);
518 /* The closure handle only ever has default timeouts set. To improve the
519 state somewhat we clone the timeouts from each added handle so that the
520 closure handle always has the same timeouts as the most recently added
522 data->state.conn_cache->closure_handle->set.timeout = data->set.timeout;
523 data->state.conn_cache->closure_handle->set.server_response_timeout =
524 data->set.server_response_timeout;
525 data->state.conn_cache->closure_handle->set.no_signal =
527 CONNCACHE_UNLOCK(data);
529 Curl_update_timer(multi);
534 /* Debug-function, used like this:
536 * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
538 * Enable the hash print function first by editing hash.c
540 static void debug_print_sock_hash(void *p)
542 struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
544 fprintf(stderr, " [easy %p/magic %x/socket %d]",
545 (void *)sh->data, sh->data->magic, (int)sh->socket);
549 static CURLcode multi_done(struct Curl_easy *data,
550 CURLcode status, /* an error if this is called
551 after an error was detected */
555 struct connectdata *conn = data->conn;
558 DEBUGF(infof(data, "multi_done\n"));
561 /* Stop if multi_done() has already been called */
564 conn->data = data; /* ensure the connection uses this transfer now */
566 /* Stop the resolver and free its own resources (but not dns_entry yet). */
567 Curl_resolver_kill(conn);
569 /* Cleanup possible redirect junk */
570 Curl_safefree(data->req.newurl);
571 Curl_safefree(data->req.location);
574 case CURLE_ABORTED_BY_CALLBACK:
575 case CURLE_READ_ERROR:
576 case CURLE_WRITE_ERROR:
577 /* When we're aborted due to a callback return code it basically have to
578 be counted as premature as there is trouble ahead if we don't. We have
579 many callbacks and protocols work differently, we could potentially do
580 this more fine-grained in the future. */
586 /* this calls the protocol-specific function pointer previously set */
587 if(conn->handler->done)
588 result = conn->handler->done(conn, status, premature);
592 if(CURLE_ABORTED_BY_CALLBACK != result) {
593 /* avoid this if we already aborted by callback to avoid this calling
595 CURLcode rc = Curl_pgrsDone(conn);
597 result = CURLE_ABORTED_BY_CALLBACK;
600 process_pending_handles(data->multi); /* connection / multiplex */
602 CONNCACHE_LOCK(data);
603 Curl_detach_connnection(data);
604 if(CONN_INUSE(conn)) {
605 /* Stop if still used. */
606 /* conn->data must not remain pointing to this transfer since it is going
607 away! Find another to own it! */
608 conn->data = conn->easyq.head->ptr;
609 CONNCACHE_UNLOCK(data);
610 DEBUGF(infof(data, "Connection still in use %zu, "
611 "no more multi_done now!\n",
615 conn->data = NULL; /* the connection now has no owner */
616 data->state.done = TRUE; /* called just now! */
618 if(conn->dns_entry) {
619 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
620 conn->dns_entry = NULL;
622 Curl_hostcache_prune(data);
623 Curl_safefree(data->state.ulbuf);
625 /* if the transfer was completed in a paused state there can be buffered
627 for(i = 0; i < data->state.tempcount; i++) {
628 Curl_dyn_free(&data->state.tempwrite[i].b);
630 data->state.tempcount = 0;
632 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
633 forced us to close this connection. This is ignored for requests taking
634 place in a NTLM/NEGOTIATE authentication handshake
636 if conn->bits.close is TRUE, it means that the connection should be
637 closed in spite of all our efforts to be nice, due to protocol
638 restrictions in our or the server's end
640 if premature is TRUE, it means this connection was said to be DONE before
641 the entire request operation is complete and thus we can't know in what
642 state it is for re-using, so we're forced to close it. In a perfect world
643 we can add code that keep track of if we really must close it here or not,
644 but currently we have no such detail knowledge.
647 if((data->set.reuse_forbid
648 #if defined(USE_NTLM)
649 && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 ||
650 conn->proxy_ntlm_state == NTLMSTATE_TYPE2)
652 #if defined(USE_SPNEGO)
653 && !(conn->http_negotiate_state == GSS_AUTHRECV ||
654 conn->proxy_negotiate_state == GSS_AUTHRECV)
656 ) || conn->bits.close
657 || (premature && !(conn->handler->flags & PROTOPT_STREAM))) {
659 connclose(conn, "disconnecting");
660 Curl_conncache_remove_conn(data, conn, FALSE);
661 CONNCACHE_UNLOCK(data);
662 res2 = Curl_disconnect(data, conn, premature);
664 /* If we had an error already, make sure we return that one. But
665 if we got a new error, return that. */
672 #ifndef CURL_DISABLE_PROXY
673 conn->bits.socksproxy ?
674 conn->socks_proxy.host.dispname :
675 conn->bits.httpproxy ? conn->http_proxy.host.dispname :
677 conn->bits.conn_to_host ? conn->conn_to_host.dispname :
679 /* create string before returning the connection */
680 msnprintf(buffer, sizeof(buffer),
681 "Connection #%ld to host %s left intact",
682 conn->connection_id, host);
683 /* the connection is no longer in use by this transfer */
684 CONNCACHE_UNLOCK(data);
685 if(Curl_conncache_return_conn(data, conn)) {
686 /* remember the most recently used connection */
687 data->state.lastconnect_id = conn->connection_id;
688 infof(data, "%s\n", buffer);
691 data->state.lastconnect_id = -1;
694 Curl_safefree(data->state.buffer);
695 Curl_free_request_state(data);
699 static int close_connect_only(struct connectdata *conn, void *param)
701 struct Curl_easy *data = param;
703 if(data->state.lastconnect_id != conn->connection_id)
706 if(conn->data != data)
710 if(!conn->bits.connect_only)
713 connclose(conn, "Removing connect-only easy handle");
714 conn->bits.connect_only = FALSE;
719 CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
720 struct Curl_easy *data)
722 struct Curl_easy *easy = data;
725 struct Curl_llist_element *e;
727 /* First, make some basic checks that the CURLM handle is a good handle */
728 if(!GOOD_MULTI_HANDLE(multi))
729 return CURLM_BAD_HANDLE;
731 /* Verify that we got a somewhat good easy handle too */
732 if(!GOOD_EASY_HANDLE(data))
733 return CURLM_BAD_EASY_HANDLE;
735 /* Prevent users from trying to remove same easy handle more than once */
737 return CURLM_OK; /* it is already removed so let's say it is fine! */
739 /* Prevent users from trying to remove an easy handle from the wrong multi */
740 if(data->multi != multi)
741 return CURLM_BAD_EASY_HANDLE;
743 if(multi->in_callback)
744 return CURLM_RECURSIVE_API_CALL;
746 premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
747 easy_owns_conn = (data->conn && (data->conn->data == easy)) ?
750 /* If the 'state' is not INIT or COMPLETED, we might need to do something
751 nice to put the easy_handle in a good known state when this returns. */
753 /* this handle is "alive" so we need to count down the total number of
754 alive connections when this is removed */
759 data->mstate > CURLM_STATE_DO &&
760 data->mstate < CURLM_STATE_COMPLETED) {
761 /* Set connection owner so that the DONE function closes it. We can
762 safely do this here since connection is killed. */
763 data->conn->data = easy;
764 streamclose(data->conn, "Removed with partial response");
765 easy_owns_conn = TRUE;
770 /* we must call multi_done() here (if we still own the connection) so that
771 we don't leave a half-baked one around */
774 /* multi_done() clears the association between the easy handle and the
777 Note that this ignores the return code simply because there's
778 nothing really useful to do with it anyway! */
779 (void)multi_done(data, data->result, premature);
783 /* The timer must be shut down before data->multi is set to NULL, else the
784 timenode will remain in the splay tree after curl_easy_cleanup is
785 called. Do it after multi_done() in case that sets another time! */
786 Curl_expire_clear(data);
788 if(data->connect_queue.ptr)
789 /* the handle was in the pending list waiting for an available connection,
790 so go ahead and remove it */
791 Curl_llist_remove(&multi->pending, &data->connect_queue, NULL);
793 if(data->dns.hostcachetype == HCACHE_MULTI) {
794 /* stop using the multi handle's DNS cache, *after* the possible
795 multi_done() call above */
796 data->dns.hostcache = NULL;
797 data->dns.hostcachetype = HCACHE_NONE;
800 Curl_wildcard_dtor(&data->wildcard);
802 /* destroy the timeout list that is held in the easy handle, do this *after*
803 multi_done() as that may actually call Curl_expire that uses this */
804 Curl_llist_destroy(&data->state.timeoutlist, NULL);
806 /* change state without using multistate(), only to make singlesocket() do
808 data->mstate = CURLM_STATE_COMPLETED;
809 singlesocket(multi, easy); /* to let the application know what sockets that
810 vanish with this handle */
812 /* Remove the association between the connection and the handle */
813 Curl_detach_connnection(data);
815 if(data->state.lastconnect_id != -1) {
816 /* Mark any connect-only connection for closure */
817 Curl_conncache_foreach(data, data->state.conn_cache,
818 data, &close_connect_only);
822 /* Remove the PSL association. */
823 if(data->psl == &multi->psl)
827 /* as this was using a shared connection cache we clear the pointer to that
828 since we're not part of that multi handle anymore */
829 data->state.conn_cache = NULL;
831 data->multi = NULL; /* clear the association to this multi handle */
833 /* make sure there's no pending message in the queue sent from this easy
836 for(e = multi->msglist.head; e; e = e->next) {
837 struct Curl_message *msg = e->ptr;
839 if(msg->extmsg.easy_handle == easy) {
840 Curl_llist_remove(&multi->msglist, e, NULL);
841 /* there can only be one from this specific handle */
846 /* make the previous node point to our next */
848 data->prev->next = data->next;
850 multi->easyp = data->next; /* point to first node */
852 /* make our next point to our previous node */
854 data->next->prev = data->prev;
856 multi->easylp = data->prev; /* point to last node */
859 We do not touch the easy handle here! */
860 multi->num_easy--; /* one less to care about now */
862 Curl_update_timer(multi);
866 /* Return TRUE if the application asked for multiplexing */
867 bool Curl_multiplex_wanted(const struct Curl_multi *multi)
869 return (multi && (multi->multiplexing));
873 * Curl_detach_connnection() removes the given transfer from the connection.
875 * This is the only function that should clear data->conn. This will
876 * occasionally be called with the data->conn pointer already cleared.
878 void Curl_detach_connnection(struct Curl_easy *data)
880 struct connectdata *conn = data->conn;
882 Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL);
887 * Curl_attach_connnection() attaches this transfer to this connection.
889 * This is the only function that should assign data->conn
891 void Curl_attach_connnection(struct Curl_easy *data,
892 struct connectdata *conn)
894 DEBUGASSERT(!data->conn);
897 Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data,
901 static int waitconnect_getsock(struct connectdata *conn,
909 #ifndef CURL_DISABLE_PROXY
910 if(CONNECT_FIRSTSOCKET_PROXY_SSL())
911 return Curl_ssl_getsock(conn, sock);
915 if(SOCKS_STATE(conn->cnnct.state))
916 return Curl_SOCKS_getsock(conn, sock, FIRSTSOCKET);
918 for(i = 0; i<2; i++) {
919 if(conn->tempsock[i] != CURL_SOCKET_BAD) {
920 sock[s] = conn->tempsock[i];
921 rc |= GETSOCK_WRITESOCK(s);
923 if(conn->transport == TRNSPRT_QUIC)
924 /* when connecting QUIC, we want to read the socket too */
925 rc |= GETSOCK_READSOCK(s);
934 static int waitproxyconnect_getsock(struct connectdata *conn,
937 sock[0] = conn->sock[FIRSTSOCKET];
939 /* when we've sent a CONNECT to a proxy, we should rather wait for the
940 socket to become readable to be able to get the response headers */
941 if(conn->connect_state)
942 return GETSOCK_READSOCK(0);
944 return GETSOCK_WRITESOCK(0);
947 static int domore_getsock(struct connectdata *conn,
948 curl_socket_t *socks)
950 if(conn && conn->handler->domore_getsock)
951 return conn->handler->domore_getsock(conn, socks);
952 return GETSOCK_BLANK;
955 static int doing_getsock(struct connectdata *conn,
956 curl_socket_t *socks)
958 if(conn && conn->handler->doing_getsock)
959 return conn->handler->doing_getsock(conn, socks);
960 return GETSOCK_BLANK;
963 static int protocol_getsock(struct connectdata *conn,
964 curl_socket_t *socks)
966 if(conn->handler->proto_getsock)
967 return conn->handler->proto_getsock(conn, socks);
968 /* Backup getsock logic. Since there is a live socket in use, we must wait
969 for it or it will be removed from watching when the multi_socket API is
971 socks[0] = conn->sock[FIRSTSOCKET];
972 return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
975 /* returns bitmapped flags for this handle and its sockets. The 'socks[]'
976 array contains MAX_SOCKSPEREASYHANDLE entries. */
977 static int multi_getsock(struct Curl_easy *data,
978 curl_socket_t *socks)
980 /* The no connection case can happen when this is called from
981 curl_multi_remove_handle() => singlesocket() => multi_getsock().
986 if(data->mstate > CURLM_STATE_CONNECT &&
987 data->mstate < CURLM_STATE_COMPLETED) {
988 /* Set up ownership correctly */
989 data->conn->data = data;
992 switch(data->mstate) {
996 case CURLM_STATE_WAITRESOLVE:
997 return Curl_resolv_getsock(data->conn, socks);
999 case CURLM_STATE_PROTOCONNECT:
1000 case CURLM_STATE_SENDPROTOCONNECT:
1001 return protocol_getsock(data->conn, socks);
1003 case CURLM_STATE_DO:
1004 case CURLM_STATE_DOING:
1005 return doing_getsock(data->conn, socks);
1007 case CURLM_STATE_WAITPROXYCONNECT:
1008 return waitproxyconnect_getsock(data->conn, socks);
1010 case CURLM_STATE_WAITCONNECT:
1011 return waitconnect_getsock(data->conn, socks);
1013 case CURLM_STATE_DO_MORE:
1014 return domore_getsock(data->conn, socks);
1016 case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
1017 to waiting for the same as the *PERFORM
1019 case CURLM_STATE_PERFORM:
1020 return Curl_single_getsock(data->conn, socks);
1025 CURLMcode curl_multi_fdset(struct Curl_multi *multi,
1026 fd_set *read_fd_set, fd_set *write_fd_set,
1027 fd_set *exc_fd_set, int *max_fd)
1029 /* Scan through all the easy handles to get the file descriptors set.
1030 Some easy handles may not have connected to the remote host yet,
1031 and then we must make sure that is done. */
1032 struct Curl_easy *data;
1033 int this_max_fd = -1;
1034 curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
1036 (void)exc_fd_set; /* not used */
1038 if(!GOOD_MULTI_HANDLE(multi))
1039 return CURLM_BAD_HANDLE;
1041 if(multi->in_callback)
1042 return CURLM_RECURSIVE_API_CALL;
1044 data = multi->easyp;
1046 int bitmap = multi_getsock(data, sockbunch);
1048 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
1049 curl_socket_t s = CURL_SOCKET_BAD;
1051 if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
1052 FD_SET(sockbunch[i], read_fd_set);
1055 if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
1056 FD_SET(sockbunch[i], write_fd_set);
1059 if(s == CURL_SOCKET_BAD)
1060 /* this socket is unused, break out of loop */
1062 if((int)s > this_max_fd)
1063 this_max_fd = (int)s;
1066 data = data->next; /* check next handle */
1069 *max_fd = this_max_fd;
1074 #define NUM_POLLS_ON_STACK 10
1076 static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
1077 struct curl_waitfd extra_fds[],
1078 unsigned int extra_nfds,
1081 bool extrawait, /* when no socket, wait */
1084 struct Curl_easy *data;
1085 curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
1088 unsigned int nfds = 0;
1089 unsigned int curlfds;
1090 long timeout_internal;
1093 struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
1094 struct pollfd *ufds = &a_few_on_stack[0];
1095 bool ufds_malloc = FALSE;
1097 struct pollfd pre_poll;
1098 WSANETWORKEVENTS wsa_events;
1099 DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT);
1102 if(!GOOD_MULTI_HANDLE(multi))
1103 return CURLM_BAD_HANDLE;
1105 if(multi->in_callback)
1106 return CURLM_RECURSIVE_API_CALL;
1109 return CURLM_BAD_FUNCTION_ARGUMENT;
1111 /* Count up how many fds we have from the multi handle */
1112 data = multi->easyp;
1114 bitmap = multi_getsock(data, sockbunch);
1116 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
1117 curl_socket_t s = CURL_SOCKET_BAD;
1119 if(bitmap & GETSOCK_READSOCK(i)) {
1123 if(bitmap & GETSOCK_WRITESOCK(i)) {
1127 if(s == CURL_SOCKET_BAD) {
1132 data = data->next; /* check next handle */
1135 /* If the internally desired timeout is actually shorter than requested from
1136 the outside, then use the shorter time! But only if the internal timer
1137 is actually larger than -1! */
1138 (void)multi_timeout(multi, &timeout_internal);
1139 if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
1140 timeout_ms = (int)timeout_internal;
1142 curlfds = nfds; /* number of internal file descriptors */
1143 nfds += extra_nfds; /* add the externally provided ones */
1145 #ifdef ENABLE_WAKEUP
1149 if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
1156 if(nfds > NUM_POLLS_ON_STACK) {
1157 /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes
1158 big, so at 2^29 sockets this value might wrap. When a process gets
1159 the capability to actually handle over 500 million sockets this
1160 calculation needs a integer overflow check. */
1161 ufds = malloc(nfds * sizeof(struct pollfd));
1163 return CURLM_OUT_OF_MEMORY;
1170 /* only do the second loop if we found descriptors in the first stage run
1174 /* Add the curl handles to our pollfds first */
1175 data = multi->easyp;
1177 bitmap = multi_getsock(data, sockbunch);
1179 for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
1180 curl_socket_t s = CURL_SOCKET_BAD;
1184 if(bitmap & GETSOCK_READSOCK(i)) {
1186 if(timeout_ms && SOCKET_READABLE(sockbunch[i], 0) > 0)
1188 mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
1190 ufds[nfds].fd = sockbunch[i];
1191 ufds[nfds].events = POLLIN;
1196 if(bitmap & GETSOCK_WRITESOCK(i)) {
1198 if(timeout_ms && SOCKET_WRITABLE(sockbunch[i], 0) > 0)
1200 mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
1202 ufds[nfds].fd = sockbunch[i];
1203 ufds[nfds].events = POLLOUT;
1208 if(s == CURL_SOCKET_BAD) {
1212 if(WSAEventSelect(s, multi->wsa_event, mask) != 0)
1213 return CURLM_INTERNAL_ERROR;
1217 data = data->next; /* check next handle */
1221 /* Add external file descriptions from poll-like struct curl_waitfd */
1222 for(i = 0; i < extra_nfds; i++) {
1225 extra_fds[i].revents = 0;
1226 pre_poll.fd = extra_fds[i].fd;
1227 pre_poll.events = 0;
1228 pre_poll.revents = 0;
1229 if(extra_fds[i].events & CURL_WAIT_POLLIN) {
1230 mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
1231 pre_poll.events |= POLLIN;
1233 if(extra_fds[i].events & CURL_WAIT_POLLPRI) {
1235 pre_poll.events |= POLLPRI;
1237 if(extra_fds[i].events & CURL_WAIT_POLLOUT) {
1238 mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
1239 pre_poll.events |= POLLOUT;
1241 if(Curl_poll(&pre_poll, 1, 0) > 0) {
1242 if(pre_poll.revents & POLLIN)
1243 extra_fds[i].revents |= CURL_WAIT_POLLIN;
1244 if(pre_poll.revents & POLLPRI)
1245 extra_fds[i].revents |= CURL_WAIT_POLLPRI;
1246 if(pre_poll.revents & POLLOUT)
1247 extra_fds[i].revents |= CURL_WAIT_POLLOUT;
1248 if(extra_fds[i].revents)
1251 if(WSAEventSelect(extra_fds[i].fd, multi->wsa_event, mask) != 0)
1252 return CURLM_INTERNAL_ERROR;
1254 ufds[nfds].fd = extra_fds[i].fd;
1255 ufds[nfds].events = 0;
1256 if(extra_fds[i].events & CURL_WAIT_POLLIN)
1257 ufds[nfds].events |= POLLIN;
1258 if(extra_fds[i].events & CURL_WAIT_POLLPRI)
1259 ufds[nfds].events |= POLLPRI;
1260 if(extra_fds[i].events & CURL_WAIT_POLLOUT)
1261 ufds[nfds].events |= POLLOUT;
1266 #ifdef ENABLE_WAKEUP
1268 if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
1269 ufds[nfds].fd = multi->wakeup_pair[0];
1270 ufds[nfds].events = POLLIN;
1279 WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, timeout_ms, FALSE);
1281 int pollrc = Curl_poll(ufds, nfds, timeout_ms);
1285 /* With Winsock, we have to run this unconditionally to call
1286 WSAEventSelect(fd, event, 0) on all the sockets */
1293 /* copy revents results from the poll to the curl_multi_wait poll
1294 struct, the bit values of the actual underlying poll() implementation
1295 may not be the same as the ones in the public libcurl API! */
1296 for(i = 0; i < extra_nfds; i++) {
1297 unsigned short mask = 0;
1299 wsa_events.lNetworkEvents = 0;
1300 mask = extra_fds[i].revents;
1301 if(WSAEnumNetworkEvents(extra_fds[i].fd, multi->wsa_event,
1302 &wsa_events) == 0) {
1303 if(wsa_events.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))
1304 mask |= CURL_WAIT_POLLIN;
1305 if(wsa_events.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))
1306 mask |= CURL_WAIT_POLLOUT;
1307 if(wsa_events.lNetworkEvents & FD_OOB)
1308 mask |= CURL_WAIT_POLLPRI;
1309 if(ret && wsa_events.lNetworkEvents != 0)
1312 WSAEventSelect(extra_fds[i].fd, multi->wsa_event, 0);
1314 unsigned r = ufds[curlfds + i].revents;
1317 mask |= CURL_WAIT_POLLIN;
1319 mask |= CURL_WAIT_POLLOUT;
1321 mask |= CURL_WAIT_POLLPRI;
1323 extra_fds[i].revents = mask;
1327 /* Count up all our own sockets that had activity,
1328 and remove them from the event. */
1330 data = multi->easyp;
1332 bitmap = multi_getsock(data, sockbunch);
1334 for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
1335 if(bitmap & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))) {
1336 wsa_events.lNetworkEvents = 0;
1337 if(WSAEnumNetworkEvents(sockbunch[i], multi->wsa_event,
1338 &wsa_events) == 0) {
1339 if(ret && wsa_events.lNetworkEvents != 0)
1342 if(ret && !timeout_ms && wsa_events.lNetworkEvents == 0) {
1343 if((bitmap & GETSOCK_READSOCK(i)) &&
1344 SOCKET_READABLE(sockbunch[i], 0) > 0)
1346 else if((bitmap & GETSOCK_WRITESOCK(i)) &&
1347 SOCKET_WRITABLE(sockbunch[i], 0) > 0)
1350 WSAEventSelect(sockbunch[i], multi->wsa_event, 0);
1360 WSAResetEvent(multi->wsa_event);
1362 #ifdef ENABLE_WAKEUP
1363 if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
1364 if(ufds[curlfds + extra_nfds].revents & POLLIN) {
1368 /* the reading socket is non-blocking, try to read
1369 data from it until it receives an error (except EINTR).
1370 In normal cases it will get EAGAIN or EWOULDBLOCK
1371 when there is no more data, breaking the loop. */
1372 nread = sread(multi->wakeup_pair[0], buf, sizeof(buf));
1374 if(nread < 0 && EINTR == SOCKERRNO)
1379 /* do not count the wakeup socket into the returned value */
1394 if(!extrawait || nfds)
1395 /* if any socket was checked */
1400 /* Avoid busy-looping when there's nothing particular to wait for */
1401 if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) {
1402 if(sleep_ms > timeout_ms)
1403 sleep_ms = timeout_ms;
1404 /* when there are no easy handles in the multi, this holds a -1
1406 else if(sleep_ms < 0)
1407 sleep_ms = timeout_ms;
1408 Curl_wait_ms(sleep_ms);
1415 CURLMcode curl_multi_wait(struct Curl_multi *multi,
1416 struct curl_waitfd extra_fds[],
1417 unsigned int extra_nfds,
1421 return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE,
1425 CURLMcode curl_multi_poll(struct Curl_multi *multi,
1426 struct curl_waitfd extra_fds[],
1427 unsigned int extra_nfds,
1431 return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE,
1435 CURLMcode curl_multi_wakeup(struct Curl_multi *multi)
1437 /* this function is usually called from another thread,
1438 it has to be careful only to access parts of the
1439 Curl_multi struct that are constant */
1441 /* GOOD_MULTI_HANDLE can be safely called */
1442 if(!GOOD_MULTI_HANDLE(multi))
1443 return CURLM_BAD_HANDLE;
1445 #ifdef ENABLE_WAKEUP
1447 if(WSASetEvent(multi->wsa_event))
1450 /* the wakeup_pair variable is only written during init and cleanup,
1451 making it safe to access from another thread after the init part
1452 and before cleanup */
1453 if(multi->wakeup_pair[1] != CURL_SOCKET_BAD) {
1457 /* swrite() is not thread-safe in general, because concurrent calls
1458 can have their messages interleaved, but in this case the content
1459 of the messages does not matter, which makes it ok to call.
1461 The write socket is set to non-blocking, this way this function
1462 cannot block, making it safe to call even from the same thread
1463 that will call Curl_multi_wait(). If swrite() returns that it
1464 would block, it's considered successful because it means that
1465 previous calls to this function will wake up the poll(). */
1466 if(swrite(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) {
1467 int err = SOCKERRNO;
1470 return_success = WSAEWOULDBLOCK == err;
1474 return_success = EWOULDBLOCK == err || EAGAIN == err;
1477 return CURLM_WAKEUP_FAILURE;
1484 return CURLM_WAKEUP_FAILURE;
1488 * multi_ischanged() is called
1490 * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
1491 * => CONNECT action.
1493 * Set 'clear' to TRUE to have it also clear the state variable.
1495 static bool multi_ischanged(struct Curl_multi *multi, bool clear)
1497 bool retval = multi->recheckstate;
1499 multi->recheckstate = FALSE;
1503 CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
1504 struct Curl_easy *data,
1505 struct connectdata *conn)
1509 if(multi->in_callback)
1510 return CURLM_RECURSIVE_API_CALL;
1512 rc = curl_multi_add_handle(multi, data);
1514 struct SingleRequest *k = &data->req;
1516 /* pass in NULL for 'conn' here since we don't want to init the
1517 connection, only this transfer */
1518 Curl_init_do(data, NULL);
1520 /* take this handle to the perform state right away */
1521 multistate(data, CURLM_STATE_PERFORM);
1522 Curl_attach_connnection(data, conn);
1523 k->keepon |= KEEP_RECV; /* setup to receive! */
1529 * do_complete is called when the DO actions are complete.
1531 * We init chunking and trailer bits to their default values here immediately
1532 * before receiving any header data for the current request.
1534 static void do_complete(struct connectdata *conn)
1536 conn->data->req.chunk = FALSE;
1537 Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
1540 static CURLcode multi_do(struct Curl_easy *data, bool *done)
1542 CURLcode result = CURLE_OK;
1543 struct connectdata *conn = data->conn;
1546 DEBUGASSERT(conn->handler);
1547 DEBUGASSERT(conn->data == data);
1549 if(conn->handler->do_it) {
1550 /* generic protocol-specific function pointer set in curl_connect() */
1551 result = conn->handler->do_it(conn, done);
1553 if(!result && *done)
1554 /* do_complete must be called after the protocol-specific DO function */
1561 * multi_do_more() is called during the DO_MORE multi state. It is basically a
1562 * second stage DO state which (wrongly) was introduced to support FTP's
1563 * second connection.
1565 * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
1566 * DOING state there's more work to do!
1569 static CURLcode multi_do_more(struct connectdata *conn, int *complete)
1571 CURLcode result = CURLE_OK;
1575 if(conn->handler->do_more)
1576 result = conn->handler->do_more(conn, complete);
1578 if(!result && (*complete == 1))
1579 /* do_complete must be called after the protocol-specific DO function */
1586 * We are doing protocol-specific connecting and this is being called over and
1587 * over from the multi interface until the connection phase is done on
1591 static CURLcode protocol_connecting(struct connectdata *conn,
1594 CURLcode result = CURLE_OK;
1596 if(conn && conn->handler->connecting) {
1598 result = conn->handler->connecting(conn, done);
1607 * We are DOING this is being called over and over from the multi interface
1608 * until the DOING phase is done on protocol layer.
1611 static CURLcode protocol_doing(struct connectdata *conn, bool *done)
1613 CURLcode result = CURLE_OK;
1615 if(conn && conn->handler->doing) {
1617 result = conn->handler->doing(conn, done);
1626 * We have discovered that the TCP connection has been successful, we can now
1627 * proceed with some action.
1630 static CURLcode protocol_connect(struct connectdata *conn,
1631 bool *protocol_done)
1633 CURLcode result = CURLE_OK;
1636 DEBUGASSERT(protocol_done);
1638 *protocol_done = FALSE;
1640 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
1641 /* We already are connected, get back. This may happen when the connect
1642 worked fine in the first call, like when we connect to a local server
1643 or proxy. Note that we don't know if the protocol is actually done.
1645 Unless this protocol doesn't have any protocol-connect callback, as
1646 then we know we're done. */
1647 if(!conn->handler->connecting)
1648 *protocol_done = TRUE;
1653 if(!conn->bits.protoconnstart) {
1654 #ifndef CURL_DISABLE_PROXY
1655 result = Curl_proxy_connect(conn, FIRSTSOCKET);
1659 if(CONNECT_FIRSTSOCKET_PROXY_SSL())
1660 /* wait for HTTPS proxy SSL initialization to complete */
1663 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
1664 Curl_connect_ongoing(conn))
1665 /* when using an HTTP tunnel proxy, await complete tunnel establishment
1666 before proceeding further. Return CURLE_OK so we'll be called again */
1669 if(conn->handler->connect_it) {
1670 /* is there a protocol-specific connect() procedure? */
1672 /* Call the protocol-specific connect function */
1673 result = conn->handler->connect_it(conn, protocol_done);
1676 *protocol_done = TRUE;
1678 /* it has started, possibly even completed but that knowledge isn't stored
1681 conn->bits.protoconnstart = TRUE;
1684 return result; /* pass back status */
1688 * Curl_preconnect() is called immediately before a connect starts. When a
1689 * redirect is followed, this is then called multiple times during a single
1692 CURLcode Curl_preconnect(struct Curl_easy *data)
1694 if(!data->state.buffer) {
1695 data->state.buffer = malloc(data->set.buffer_size + 1);
1696 if(!data->state.buffer)
1697 return CURLE_OUT_OF_MEMORY;
1703 static CURLMcode multi_runsingle(struct Curl_multi *multi,
1704 struct curltime *nowp,
1705 struct Curl_easy *data)
1707 struct Curl_message *msg = NULL;
1710 bool protocol_connected = FALSE;
1711 bool dophase_done = FALSE;
1714 CURLcode result = CURLE_OK;
1715 timediff_t timeout_ms;
1716 timediff_t recv_timeout_ms;
1717 timediff_t send_timeout_ms;
1720 if(!GOOD_EASY_HANDLE(data))
1721 return CURLM_BAD_EASY_HANDLE;
1724 /* A "stream" here is a logical stream if the protocol can handle that
1725 (HTTP/2), or the full connection for older protocols */
1726 bool stream_error = FALSE;
1729 if(multi_ischanged(multi, TRUE)) {
1730 DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n"));
1731 process_pending_handles(multi); /* multiplexed */
1734 if(data->conn && data->mstate > CURLM_STATE_CONNECT &&
1735 data->mstate < CURLM_STATE_COMPLETED) {
1736 /* Make sure we set the connection's current owner */
1737 data->conn->data = data;
1741 (data->mstate >= CURLM_STATE_CONNECT) &&
1742 (data->mstate < CURLM_STATE_COMPLETED)) {
1743 /* we need to wait for the connect state as only then is the start time
1744 stored, but we must not check already completed handles */
1745 timeout_ms = Curl_timeleft(data, nowp,
1746 (data->mstate <= CURLM_STATE_DO)?
1749 if(timeout_ms < 0) {
1750 /* Handle timed out */
1751 if(data->mstate == CURLM_STATE_WAITRESOLVE)
1752 failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T
1754 Curl_timediff(*nowp, data->progress.t_startsingle));
1755 else if(data->mstate == CURLM_STATE_WAITCONNECT)
1756 failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T
1758 Curl_timediff(*nowp, data->progress.t_startsingle));
1760 struct SingleRequest *k = &data->req;
1762 failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
1763 " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
1764 CURL_FORMAT_CURL_OFF_T " bytes received",
1765 Curl_timediff(*nowp, data->progress.t_startsingle),
1766 k->bytecount, k->size);
1769 failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
1770 " milliseconds with %" CURL_FORMAT_CURL_OFF_T
1772 Curl_timediff(*nowp, data->progress.t_startsingle),
1777 /* Force connection closed if the connection has indeed been used */
1778 if(data->mstate > CURLM_STATE_DO) {
1779 streamclose(data->conn, "Disconnected with pending data");
1780 stream_error = TRUE;
1782 result = CURLE_OPERATION_TIMEDOUT;
1783 (void)multi_done(data, result, TRUE);
1784 /* Skip the statemachine and go directly to error handling section. */
1785 goto statemachine_end;
1789 switch(data->mstate) {
1790 case CURLM_STATE_INIT:
1791 /* init this transfer. */
1792 result = Curl_pretransfer(data);
1795 /* after init, go CONNECT */
1796 multistate(data, CURLM_STATE_CONNECT);
1797 *nowp = Curl_pgrsTime(data, TIMER_STARTOP);
1798 rc = CURLM_CALL_MULTI_PERFORM;
1802 case CURLM_STATE_CONNECT_PEND:
1803 /* We will stay here until there is a connection available. Then
1804 we try again in the CURLM_STATE_CONNECT state. */
1807 case CURLM_STATE_CONNECT:
1808 /* Connect. We want to get a connection identifier filled in. */
1809 /* init this transfer. */
1810 result = Curl_preconnect(data);
1814 *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE);
1815 if(data->set.timeout)
1816 Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT);
1818 if(data->set.connecttimeout)
1819 Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT);
1821 result = Curl_connect(data, &async, &protocol_connected);
1822 if(CURLE_NO_CONNECTION_AVAILABLE == result) {
1823 /* There was no connection available. We will go to the pending
1824 state and wait for an available connection. */
1825 multistate(data, CURLM_STATE_CONNECT_PEND);
1827 /* add this handle to the list of connect-pending handles */
1828 Curl_llist_insert_next(&multi->pending, multi->pending.tail, data,
1829 &data->connect_queue);
1833 else if(data->state.previouslypending) {
1834 /* this transfer comes from the pending queue so try move another */
1835 infof(data, "Transfer was pending, now try another\n");
1836 process_pending_handles(data->multi);
1841 /* We're now waiting for an asynchronous name lookup */
1842 multistate(data, CURLM_STATE_WAITRESOLVE);
1844 /* after the connect has been sent off, go WAITCONNECT unless the
1845 protocol connect is already done and we can go directly to
1847 rc = CURLM_CALL_MULTI_PERFORM;
1849 if(protocol_connected)
1850 multistate(data, CURLM_STATE_DO);
1852 #ifndef CURL_DISABLE_HTTP
1853 if(Curl_connect_ongoing(data->conn))
1854 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1857 multistate(data, CURLM_STATE_WAITCONNECT);
1863 case CURLM_STATE_WAITRESOLVE:
1864 /* awaiting an asynch name resolve to complete */
1866 struct Curl_dns_entry *dns = NULL;
1867 struct connectdata *conn = data->conn;
1868 const char *hostname;
1871 #ifndef CURL_DISABLE_PROXY
1872 if(conn->bits.httpproxy)
1873 hostname = conn->http_proxy.host.name;
1876 if(conn->bits.conn_to_host)
1877 hostname = conn->conn_to_host.name;
1879 hostname = conn->host.name;
1881 /* check if we have the name resolved by now */
1882 dns = Curl_fetch_addr(conn, hostname, (int)conn->port);
1885 #ifdef CURLRES_ASYNCH
1886 conn->async.dns = dns;
1887 conn->async.done = TRUE;
1890 infof(data, "Hostname '%s' was found in DNS cache\n", hostname);
1894 result = Curl_resolv_check(data->conn, &dns);
1896 /* Update sockets here, because the socket(s) may have been
1897 closed and the application thus needs to be told, even if it
1898 is likely that the same socket(s) will again be used further
1899 down. If the name has not yet been resolved, it is likely
1900 that new sockets have been opened in an attempt to contact
1901 another resolver. */
1902 singlesocket(multi, data);
1905 /* Perform the next step in the connection phase, and then move on
1906 to the WAITCONNECT state */
1907 result = Curl_once_resolved(data->conn, &protocol_connected);
1910 /* if Curl_once_resolved() returns failure, the connection struct
1911 is already freed and gone */
1912 data->conn = NULL; /* no more connection */
1914 /* call again please so that we get the next socket setup */
1915 rc = CURLM_CALL_MULTI_PERFORM;
1916 if(protocol_connected)
1917 multistate(data, CURLM_STATE_DO);
1919 #ifndef CURL_DISABLE_HTTP
1920 if(Curl_connect_ongoing(data->conn))
1921 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1924 multistate(data, CURLM_STATE_WAITCONNECT);
1930 /* failure detected */
1931 stream_error = TRUE;
1937 #ifndef CURL_DISABLE_HTTP
1938 case CURLM_STATE_WAITPROXYCONNECT:
1939 /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
1940 DEBUGASSERT(data->conn);
1941 result = Curl_http_connect(data->conn, &protocol_connected);
1942 #ifndef CURL_DISABLE_PROXY
1943 if(data->conn->bits.proxy_connect_closed) {
1944 rc = CURLM_CALL_MULTI_PERFORM;
1945 /* connect back to proxy again */
1947 multi_done(data, CURLE_OK, FALSE);
1948 multistate(data, CURLM_STATE_CONNECT);
1954 #ifndef CURL_DISABLE_PROXY
1955 (data->conn->http_proxy.proxytype != CURLPROXY_HTTPS ||
1956 data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) &&
1958 Curl_connect_complete(data->conn)) {
1959 rc = CURLM_CALL_MULTI_PERFORM;
1960 /* initiate protocol connect phase */
1961 multistate(data, CURLM_STATE_SENDPROTOCONNECT);
1965 stream_error = TRUE;
1969 case CURLM_STATE_WAITCONNECT:
1970 /* awaiting a completion of an asynch TCP connect */
1971 DEBUGASSERT(data->conn);
1972 result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected);
1973 if(connected && !result) {
1974 #ifndef CURL_DISABLE_HTTP
1976 #ifndef CURL_DISABLE_PROXY
1977 (data->conn->http_proxy.proxytype == CURLPROXY_HTTPS &&
1978 !data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) ||
1980 Curl_connect_ongoing(data->conn)) {
1981 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1985 rc = CURLM_CALL_MULTI_PERFORM;
1986 #ifndef CURL_DISABLE_PROXY
1988 data->conn->bits.tunnel_proxy?
1989 CURLM_STATE_WAITPROXYCONNECT:
1990 CURLM_STATE_SENDPROTOCONNECT);
1992 multistate(data, CURLM_STATE_SENDPROTOCONNECT);
1996 /* failure detected */
1997 Curl_posttransfer(data);
1998 multi_done(data, result, TRUE);
1999 stream_error = TRUE;
2004 case CURLM_STATE_SENDPROTOCONNECT:
2005 result = protocol_connect(data->conn, &protocol_connected);
2006 if(!result && !protocol_connected)
2007 /* switch to waiting state */
2008 multistate(data, CURLM_STATE_PROTOCONNECT);
2010 /* protocol connect has completed, go WAITDO or DO */
2011 multistate(data, CURLM_STATE_DO);
2012 rc = CURLM_CALL_MULTI_PERFORM;
2015 /* failure detected */
2016 Curl_posttransfer(data);
2017 multi_done(data, result, TRUE);
2018 stream_error = TRUE;
2022 case CURLM_STATE_PROTOCONNECT:
2023 /* protocol-specific connect phase */
2024 result = protocol_connecting(data->conn, &protocol_connected);
2025 if(!result && protocol_connected) {
2026 /* after the connect has completed, go WAITDO or DO */
2027 multistate(data, CURLM_STATE_DO);
2028 rc = CURLM_CALL_MULTI_PERFORM;
2031 /* failure detected */
2032 Curl_posttransfer(data);
2033 multi_done(data, result, TRUE);
2034 stream_error = TRUE;
2038 case CURLM_STATE_DO:
2039 if(data->set.connect_only) {
2040 /* keep connection open for application to use the socket */
2041 connkeep(data->conn, "CONNECT_ONLY");
2042 multistate(data, CURLM_STATE_DONE);
2044 rc = CURLM_CALL_MULTI_PERFORM;
2047 /* Perform the protocol's DO action */
2048 result = multi_do(data, &dophase_done);
2050 /* When multi_do() returns failure, data->conn might be NULL! */
2054 #ifndef CURL_DISABLE_FTP
2055 /* some steps needed for wildcard matching */
2056 if(data->state.wildcardmatch) {
2057 struct WildcardData *wc = &data->wildcard;
2058 if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
2059 /* skip some states if it is important */
2060 multi_done(data, CURLE_OK, FALSE);
2061 multistate(data, CURLM_STATE_DONE);
2062 rc = CURLM_CALL_MULTI_PERFORM;
2067 /* DO was not completed in one function call, we must continue
2069 multistate(data, CURLM_STATE_DOING);
2073 /* after DO, go DO_DONE... or DO_MORE */
2074 else if(data->conn->bits.do_more) {
2075 /* we're supposed to do more, but we need to sit down, relax
2076 and wait a little while first */
2077 multistate(data, CURLM_STATE_DO_MORE);
2081 /* we're done with the DO, now DO_DONE */
2082 multistate(data, CURLM_STATE_DO_DONE);
2083 rc = CURLM_CALL_MULTI_PERFORM;
2086 else if((CURLE_SEND_ERROR == result) &&
2087 data->conn->bits.reuse) {
2089 * In this situation, a connection that we were trying to use
2090 * may have unexpectedly died. If possible, send the connection
2091 * back to the CONNECT phase so we can try again.
2093 char *newurl = NULL;
2094 followtype follow = FOLLOW_NONE;
2097 drc = Curl_retry_request(data->conn, &newurl);
2099 /* a failure here pretty much implies an out of memory */
2101 stream_error = TRUE;
2104 Curl_posttransfer(data);
2105 drc = multi_done(data, result, FALSE);
2107 /* When set to retry the connection, we must to go back to
2108 * the CONNECT state */
2110 if(!drc || (drc == CURLE_SEND_ERROR)) {
2111 follow = FOLLOW_RETRY;
2112 drc = Curl_follow(data, newurl, follow);
2114 multistate(data, CURLM_STATE_CONNECT);
2115 rc = CURLM_CALL_MULTI_PERFORM;
2124 /* done didn't return OK or SEND_ERROR */
2129 /* Have error handler disconnect conn if we can't retry */
2130 stream_error = TRUE;
2135 /* failure detected */
2136 Curl_posttransfer(data);
2138 multi_done(data, result, FALSE);
2139 stream_error = TRUE;
2144 case CURLM_STATE_DOING:
2145 /* we continue DOING until the DO phase is complete */
2146 DEBUGASSERT(data->conn);
2147 result = protocol_doing(data->conn, &dophase_done);
2150 /* after DO, go DO_DONE or DO_MORE */
2151 multistate(data, data->conn->bits.do_more?
2152 CURLM_STATE_DO_MORE:
2153 CURLM_STATE_DO_DONE);
2154 rc = CURLM_CALL_MULTI_PERFORM;
2155 } /* dophase_done */
2158 /* failure detected */
2159 Curl_posttransfer(data);
2160 multi_done(data, result, FALSE);
2161 stream_error = TRUE;
2165 case CURLM_STATE_DO_MORE:
2167 * When we are connected, DO MORE and then go DO_DONE
2169 DEBUGASSERT(data->conn);
2170 result = multi_do_more(data->conn, &control);
2174 /* if positive, advance to DO_DONE
2175 if negative, go back to DOING */
2176 multistate(data, control == 1?
2177 CURLM_STATE_DO_DONE:
2179 rc = CURLM_CALL_MULTI_PERFORM;
2182 /* stay in DO_MORE */
2186 /* failure detected */
2187 Curl_posttransfer(data);
2188 multi_done(data, result, FALSE);
2189 stream_error = TRUE;
2193 case CURLM_STATE_DO_DONE:
2194 DEBUGASSERT(data->conn);
2195 if(data->conn->bits.multiplex)
2196 /* Check if we can move pending requests to send pipe */
2197 process_pending_handles(multi); /* multiplexed */
2199 /* Only perform the transfer if there's a good socket to work with.
2200 Having both BAD is a signal to skip immediately to DONE */
2201 if((data->conn->sockfd != CURL_SOCKET_BAD) ||
2202 (data->conn->writesockfd != CURL_SOCKET_BAD))
2203 multistate(data, CURLM_STATE_PERFORM);
2205 #ifndef CURL_DISABLE_FTP
2206 if(data->state.wildcardmatch &&
2207 ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
2208 data->wildcard.state = CURLWC_DONE;
2211 multistate(data, CURLM_STATE_DONE);
2213 rc = CURLM_CALL_MULTI_PERFORM;
2216 case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
2217 DEBUGASSERT(data->conn);
2218 /* if both rates are within spec, resume transfer */
2219 if(Curl_pgrsUpdate(data->conn))
2220 result = CURLE_ABORTED_BY_CALLBACK;
2222 result = Curl_speedcheck(data, *nowp);
2225 send_timeout_ms = 0;
2226 if(data->set.max_send_speed > 0)
2228 Curl_pgrsLimitWaitTime(data->progress.uploaded,
2229 data->progress.ul_limit_size,
2230 data->set.max_send_speed,
2231 data->progress.ul_limit_start,
2234 recv_timeout_ms = 0;
2235 if(data->set.max_recv_speed > 0)
2237 Curl_pgrsLimitWaitTime(data->progress.downloaded,
2238 data->progress.dl_limit_size,
2239 data->set.max_recv_speed,
2240 data->progress.dl_limit_start,
2243 if(!send_timeout_ms && !recv_timeout_ms) {
2244 multistate(data, CURLM_STATE_PERFORM);
2245 Curl_ratelimit(data, *nowp);
2247 else if(send_timeout_ms >= recv_timeout_ms)
2248 Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
2250 Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
2254 case CURLM_STATE_PERFORM:
2256 char *newurl = NULL;
2258 bool comeback = FALSE;
2259 DEBUGASSERT(data->state.buffer);
2260 /* check if over send speed */
2261 send_timeout_ms = 0;
2262 if(data->set.max_send_speed > 0)
2263 send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
2264 data->progress.ul_limit_size,
2265 data->set.max_send_speed,
2266 data->progress.ul_limit_start,
2269 /* check if over recv speed */
2270 recv_timeout_ms = 0;
2271 if(data->set.max_recv_speed > 0)
2272 recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
2273 data->progress.dl_limit_size,
2274 data->set.max_recv_speed,
2275 data->progress.dl_limit_start,
2278 if(send_timeout_ms || recv_timeout_ms) {
2279 Curl_ratelimit(data, *nowp);
2280 multistate(data, CURLM_STATE_TOOFAST);
2281 if(send_timeout_ms >= recv_timeout_ms)
2282 Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
2284 Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
2288 /* read/write data if it is ready to do so */
2289 result = Curl_readwrite(data->conn, data, &done, &comeback);
2291 if(done || (result == CURLE_RECV_ERROR)) {
2292 /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
2293 * condition and the server closed the re-used connection exactly when
2294 * we wanted to use it, so figure out if that is indeed the case.
2296 CURLcode ret = Curl_retry_request(data->conn, &newurl);
2298 retry = (newurl)?TRUE:FALSE;
2303 /* if we are to retry, set the result to OK and consider the
2309 else if((CURLE_HTTP2_STREAM == result) &&
2310 Curl_h2_http_1_1_error(data->conn)) {
2311 CURLcode ret = Curl_retry_request(data->conn, &newurl);
2314 infof(data, "Downgrades to HTTP/1.1!\n");
2315 data->set.httpversion = CURL_HTTP_VERSION_1_1;
2316 /* clear the error message bit too as we ignore the one we got */
2317 data->state.errorbuf = FALSE;
2319 /* typically for HTTP_1_1_REQUIRED error on first flight */
2320 newurl = strdup(data->change.url);
2321 /* if we are to retry, set the result to OK and consider the request
2333 * The transfer phase returned error, we mark the connection to get
2334 * closed to prevent being re-used. This is because we can't possibly
2335 * know if the connection is in a good shape or not now. Unless it is
2336 * a protocol which uses two "channels" like FTP, as then the error
2337 * happened in the data connection.
2340 if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
2341 result != CURLE_HTTP2_STREAM)
2342 streamclose(data->conn, "Transfer returned error");
2344 Curl_posttransfer(data);
2345 multi_done(data, result, TRUE);
2348 followtype follow = FOLLOW_NONE;
2350 /* call this even if the readwrite function returned error */
2351 Curl_posttransfer(data);
2353 /* When we follow redirects or is set to retry the connection, we must
2354 to go back to the CONNECT state */
2355 if(data->req.newurl || retry) {
2357 /* if the URL is a follow-location and not just a retried request
2358 then figure out the URL here */
2360 newurl = data->req.newurl;
2361 data->req.newurl = NULL;
2362 follow = FOLLOW_REDIR;
2365 follow = FOLLOW_RETRY;
2366 (void)multi_done(data, CURLE_OK, FALSE);
2367 /* multi_done() might return CURLE_GOT_NOTHING */
2368 result = Curl_follow(data, newurl, follow);
2370 multistate(data, CURLM_STATE_CONNECT);
2371 rc = CURLM_CALL_MULTI_PERFORM;
2376 /* after the transfer is done, go DONE */
2378 /* but first check to see if we got a location info even though we're
2379 not following redirects */
2380 if(data->req.location) {
2382 newurl = data->req.location;
2383 data->req.location = NULL;
2384 result = Curl_follow(data, newurl, FOLLOW_FAKE);
2387 stream_error = TRUE;
2388 result = multi_done(data, result, TRUE);
2393 multistate(data, CURLM_STATE_DONE);
2394 rc = CURLM_CALL_MULTI_PERFORM;
2399 /* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer
2400 won't get stuck on this transfer at the expense of other concurrent
2402 Curl_expire(data, 0, EXPIRE_RUN_NOW);
2408 case CURLM_STATE_DONE:
2409 /* this state is highly transient, so run another loop after this */
2410 rc = CURLM_CALL_MULTI_PERFORM;
2415 if(data->conn->bits.multiplex)
2416 /* Check if we can move pending requests to connection */
2417 process_pending_handles(multi); /* multiplexing */
2419 /* post-transfer command */
2420 res = multi_done(data, result, FALSE);
2422 /* allow a previously set error code take precedence */
2427 * If there are other handles on the connection, multi_done won't set
2428 * conn to NULL. In such a case, curl_multi_remove_handle() can
2429 * access free'd data, if the connection is free'd and the handle
2430 * removed before we perform the processing in CURLM_STATE_COMPLETED
2432 Curl_detach_connnection(data);
2435 #ifndef CURL_DISABLE_FTP
2436 if(data->state.wildcardmatch) {
2437 if(data->wildcard.state != CURLWC_DONE) {
2438 /* if a wildcard is set and we are not ending -> lets start again
2439 with CURLM_STATE_INIT */
2440 multistate(data, CURLM_STATE_INIT);
2445 /* after we have DONE what we're supposed to do, go COMPLETED, and
2446 it doesn't matter what the multi_done() returned! */
2447 multistate(data, CURLM_STATE_COMPLETED);
2450 case CURLM_STATE_COMPLETED:
2453 case CURLM_STATE_MSGSENT:
2454 data->result = result;
2455 return CURLM_OK; /* do nothing */
2458 return CURLM_INTERNAL_ERROR;
2462 if(data->mstate < CURLM_STATE_COMPLETED) {
2465 * If an error was returned, and we aren't in completed state now,
2466 * then we go to completed and consider this transfer aborted.
2469 /* NOTE: no attempt to disconnect connections must be made
2470 in the case blocks above - cleanup happens only here */
2472 /* Check if we can move pending requests to send pipe */
2473 process_pending_handles(multi); /* connection */
2477 /* Don't attempt to send data over a connection that timed out */
2478 bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
2479 struct connectdata *conn = data->conn;
2481 /* This is where we make sure that the conn pointer is reset.
2482 We don't have to do this in every case block above where a
2483 failure is detected */
2484 Curl_detach_connnection(data);
2486 /* remove connection from cache */
2487 Curl_conncache_remove_conn(data, conn, TRUE);
2489 /* disconnect properly */
2490 Curl_disconnect(data, conn, dead_connection);
2493 else if(data->mstate == CURLM_STATE_CONNECT) {
2494 /* Curl_connect() failed */
2495 (void)Curl_posttransfer(data);
2498 multistate(data, CURLM_STATE_COMPLETED);
2499 rc = CURLM_CALL_MULTI_PERFORM;
2501 /* if there's still a connection to use, call the progress function */
2502 else if(data->conn && Curl_pgrsUpdate(data->conn)) {
2503 /* aborted due to progress callback return code must close the
2505 result = CURLE_ABORTED_BY_CALLBACK;
2506 streamclose(data->conn, "Aborted by callback");
2508 /* if not yet in DONE state, go there, otherwise COMPLETED */
2509 multistate(data, (data->mstate < CURLM_STATE_DONE)?
2510 CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
2511 rc = CURLM_CALL_MULTI_PERFORM;
2515 if(CURLM_STATE_COMPLETED == data->mstate) {
2516 if(data->set.fmultidone) {
2517 /* signal via callback instead */
2518 data->set.fmultidone(data, result);
2521 /* now fill in the Curl_message with this info */
2524 msg->extmsg.msg = CURLMSG_DONE;
2525 msg->extmsg.easy_handle = data;
2526 msg->extmsg.data.result = result;
2528 rc = multi_addmsg(multi, msg);
2529 DEBUGASSERT(!data->conn);
2531 multistate(data, CURLM_STATE_MSGSENT);
2533 } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
2535 data->result = result;
2540 CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
2542 struct Curl_easy *data;
2543 CURLMcode returncode = CURLM_OK;
2544 struct Curl_tree *t;
2545 struct curltime now = Curl_now();
2547 if(!GOOD_MULTI_HANDLE(multi))
2548 return CURLM_BAD_HANDLE;
2550 if(multi->in_callback)
2551 return CURLM_RECURSIVE_API_CALL;
2553 data = multi->easyp;
2556 SIGPIPE_VARIABLE(pipe_st);
2558 sigpipe_ignore(data, &pipe_st);
2559 result = multi_runsingle(multi, &now, data);
2560 sigpipe_restore(&pipe_st);
2563 returncode = result;
2565 data = data->next; /* operate on next handle */
2569 * Simply remove all expired timers from the splay since handles are dealt
2570 * with unconditionally by this function and curl_multi_timeout() requires
2571 * that already passed/handled expire times are removed from the splay.
2573 * It is important that the 'now' value is set at the entry of this function
2574 * and not for the current time as it may have ticked a little while since
2575 * then and then we risk this loop to remove timers that actually have not
2579 multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2581 /* the removed may have another timeout in queue */
2582 (void)add_next_timeout(now, multi, t->payload);
2586 *running_handles = multi->num_alive;
2588 if(CURLM_OK >= returncode)
2589 Curl_update_timer(multi);
2594 CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
2596 struct Curl_easy *data;
2597 struct Curl_easy *nextdata;
2599 if(GOOD_MULTI_HANDLE(multi)) {
2600 if(multi->in_callback)
2601 return CURLM_RECURSIVE_API_CALL;
2603 multi->type = 0; /* not good anymore */
2605 /* Firsrt remove all remaining easy handles */
2606 data = multi->easyp;
2608 nextdata = data->next;
2609 if(!data->state.done && data->conn)
2610 /* if DONE was never called for this handle */
2611 (void)multi_done(data, CURLE_OK, TRUE);
2612 if(data->dns.hostcachetype == HCACHE_MULTI) {
2613 /* clear out the usage of the shared DNS cache */
2614 Curl_hostcache_clean(data, data->dns.hostcache);
2615 data->dns.hostcache = NULL;
2616 data->dns.hostcachetype = HCACHE_NONE;
2619 /* Clear the pointer to the connection cache */
2620 data->state.conn_cache = NULL;
2621 data->multi = NULL; /* clear the association */
2624 if(data->psl == &multi->psl)
2631 /* Close all the connections in the connection cache */
2632 Curl_conncache_close_all_connections(&multi->conn_cache);
2634 Curl_hash_destroy(&multi->sockhash);
2635 Curl_conncache_destroy(&multi->conn_cache);
2636 Curl_llist_destroy(&multi->msglist, NULL);
2637 Curl_llist_destroy(&multi->pending, NULL);
2639 Curl_hash_destroy(&multi->hostcache);
2640 Curl_psl_destroy(&multi->psl);
2643 WSACloseEvent(multi->wsa_event);
2645 #ifdef ENABLE_WAKEUP
2646 sclose(multi->wakeup_pair[0]);
2647 sclose(multi->wakeup_pair[1]);
2654 return CURLM_BAD_HANDLE;
2658 * curl_multi_info_read()
2660 * This function is the primary way for a multi/multi_socket application to
2661 * figure out if a transfer has ended. We MUST make this function as fast as
2662 * possible as it will be polled frequently and we MUST NOT scan any lists in
2663 * here to figure out things. We must scale fine to thousands of handles and
2664 * beyond. The current design is fully O(1).
2667 CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
2669 struct Curl_message *msg;
2671 *msgs_in_queue = 0; /* default to none */
2673 if(GOOD_MULTI_HANDLE(multi) &&
2674 !multi->in_callback &&
2675 Curl_llist_count(&multi->msglist)) {
2676 /* there is one or more messages in the list */
2677 struct Curl_llist_element *e;
2679 /* extract the head of the list to return */
2680 e = multi->msglist.head;
2684 /* remove the extracted entry */
2685 Curl_llist_remove(&multi->msglist, e, NULL);
2687 *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
2689 return &msg->extmsg;
2695 * singlesocket() checks what sockets we deal with and their "action state"
2696 * and if we have a different state in any of those sockets from last time we
2697 * call the callback accordingly.
2699 static CURLMcode singlesocket(struct Curl_multi *multi,
2700 struct Curl_easy *data)
2702 curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
2704 struct Curl_sh_entry *entry;
2707 unsigned int curraction;
2708 int actions[MAX_SOCKSPEREASYHANDLE];
2710 for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
2711 socks[i] = CURL_SOCKET_BAD;
2713 /* Fill in the 'current' struct with the state as it is now: what sockets to
2714 supervise and for what actions */
2715 curraction = multi_getsock(data, socks);
2717 /* We have 0 .. N sockets already and we get to know about the 0 .. M
2718 sockets we should have from now on. Detect the differences, remove no
2719 longer supervised ones and add new ones */
2721 /* walk over the sockets we got right now */
2722 for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
2723 (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
2725 unsigned int action = CURL_POLL_NONE;
2726 unsigned int prevaction = 0;
2727 unsigned int comboaction;
2728 bool sincebefore = FALSE;
2732 /* get it from the hash */
2733 entry = sh_getentry(&multi->sockhash, s);
2735 if(curraction & GETSOCK_READSOCK(i))
2736 action |= CURL_POLL_IN;
2737 if(curraction & GETSOCK_WRITESOCK(i))
2738 action |= CURL_POLL_OUT;
2740 actions[i] = action;
2742 /* check if new for this transfer */
2744 for(j = 0; j< data->numsocks; j++) {
2745 if(s == data->sockets[j]) {
2746 prevaction = data->actions[j];
2753 /* this is a socket we didn't have before, add it to the hash! */
2754 entry = sh_addentry(&multi->sockhash, s);
2757 return CURLM_OUT_OF_MEMORY;
2759 if(sincebefore && (prevaction != action)) {
2760 /* Socket was used already, but different action now */
2761 if(prevaction & CURL_POLL_IN)
2763 if(prevaction & CURL_POLL_OUT)
2765 if(action & CURL_POLL_IN)
2767 if(action & CURL_POLL_OUT)
2770 else if(!sincebefore) {
2773 if(action & CURL_POLL_IN)
2775 if(action & CURL_POLL_OUT)
2778 /* add 'data' to the transfer hash on this socket! */
2779 if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */
2780 sizeof(struct Curl_easy *), data))
2781 return CURLM_OUT_OF_MEMORY;
2784 comboaction = (entry->writers? CURL_POLL_OUT : 0) |
2785 (entry->readers ? CURL_POLL_IN : 0);
2787 /* socket existed before and has the same action set as before */
2788 if(sincebefore && (entry->action == comboaction))
2789 /* same, continue */
2792 if(multi->socket_cb)
2793 multi->socket_cb(data, s, comboaction, multi->socket_userp,
2796 entry->action = comboaction; /* store the current action state */
2799 num = i; /* number of sockets */
2801 /* when we've walked over all the sockets we should have right now, we must
2802 make sure to detect sockets that are removed */
2803 for(i = 0; i< data->numsocks; i++) {
2805 bool stillused = FALSE;
2806 s = data->sockets[i];
2807 for(j = 0; j < num; j++) {
2809 /* this is still supervised */
2817 entry = sh_getentry(&multi->sockhash, s);
2818 /* if this is NULL here, the socket has been closed and notified so
2819 already by Curl_multi_closed() */
2821 int oldactions = data->actions[i];
2822 /* this socket has been removed. Decrease user count */
2824 if(oldactions & CURL_POLL_OUT)
2826 if(oldactions & CURL_POLL_IN)
2829 if(multi->socket_cb)
2830 multi->socket_cb(data, s, CURL_POLL_REMOVE,
2831 multi->socket_userp,
2833 sh_delentry(entry, &multi->sockhash, s);
2836 /* still users, but remove this handle as a user of this socket */
2837 if(Curl_hash_delete(&entry->transfers, (char *)&data,
2838 sizeof(struct Curl_easy *))) {
2843 } /* for loop over numsocks */
2845 memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
2846 memcpy(data->actions, actions, num*sizeof(int));
2847 data->numsocks = num;
2851 void Curl_updatesocket(struct Curl_easy *data)
2853 singlesocket(data->multi, data);
2858 * Curl_multi_closed()
2860 * Used by the connect code to tell the multi_socket code that one of the
2861 * sockets we were using is about to be closed. This function will then
2862 * remove it from the sockethash for this handle to make the multi_socket API
2863 * behave properly, especially for the case when libcurl will create another
2864 * socket again and it gets the same file descriptor number.
2867 void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
2870 /* if there's still an easy handle associated with this connection */
2871 struct Curl_multi *multi = data->multi;
2873 /* this is set if this connection is part of a handle that is added to
2874 a multi handle, and only then this is necessary */
2875 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
2878 if(multi->socket_cb)
2879 multi->socket_cb(data, s, CURL_POLL_REMOVE,
2880 multi->socket_userp,
2883 /* now remove it from the socket hash */
2884 sh_delentry(entry, &multi->sockhash, s);
2891 * add_next_timeout()
2893 * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
2894 * when it has just been removed from the splay tree because the timeout has
2895 * expired. This function is then to advance in the list to pick the next
2896 * timeout to use (skip the already expired ones) and add this node back to
2897 * the splay tree again.
2899 * The splay tree only has each sessionhandle as a single node and the nearest
2900 * timeout is used to sort it on.
2902 static CURLMcode add_next_timeout(struct curltime now,
2903 struct Curl_multi *multi,
2904 struct Curl_easy *d)
2906 struct curltime *tv = &d->state.expiretime;
2907 struct Curl_llist *list = &d->state.timeoutlist;
2908 struct Curl_llist_element *e;
2909 struct time_node *node = NULL;
2911 /* move over the timeout list for this specific handle and remove all
2912 timeouts that are now passed tense and store the next pending
2914 for(e = list->head; e;) {
2915 struct Curl_llist_element *n = e->next;
2917 node = (struct time_node *)e->ptr;
2918 diff = Curl_timediff(node->time, now);
2920 /* remove outdated entry */
2921 Curl_llist_remove(list, e, NULL);
2923 /* the list is sorted so get out on the first mismatch */
2929 /* clear the expire times within the handles that we remove from the
2935 /* copy the first entry to 'tv' */
2936 memcpy(tv, &node->time, sizeof(*tv));
2938 /* Insert this node again into the splay. Keep the timer in the list in
2939 case we need to recompute future timers. */
2940 multi->timetree = Curl_splayinsert(*tv, multi->timetree,
2941 &d->state.timenode);
2946 static CURLMcode multi_socket(struct Curl_multi *multi,
2950 int *running_handles)
2952 CURLMcode result = CURLM_OK;
2953 struct Curl_easy *data = NULL;
2954 struct Curl_tree *t;
2955 struct curltime now = Curl_now();
2958 /* *perform() deals with running_handles on its own */
2959 result = curl_multi_perform(multi, running_handles);
2961 /* walk through each easy handle and do the socket state change magic
2963 if(result != CURLM_BAD_HANDLE) {
2964 data = multi->easyp;
2965 while(data && !result) {
2966 result = singlesocket(multi, data);
2971 /* or should we fall-through and do the timer-based stuff? */
2974 if(s != CURL_SOCKET_TIMEOUT) {
2975 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
2978 /* Unmatched socket, we can't act on it but we ignore this fact. In
2979 real-world tests it has been proved that libevent can in fact give
2980 the application actions even though the socket was just previously
2981 asked to get removed, so thus we better survive stray socket actions
2982 and just move on. */
2985 struct Curl_hash_iterator iter;
2986 struct Curl_hash_element *he;
2988 /* the socket can be shared by many transfers, iterate */
2989 Curl_hash_start_iterate(&entry->transfers, &iter);
2990 for(he = Curl_hash_next_element(&iter); he;
2991 he = Curl_hash_next_element(&iter)) {
2992 data = (struct Curl_easy *)he->ptr;
2994 DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER);
2996 if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK))
2997 /* set socket event bitmask if they're not locked */
2998 data->conn->cselect_bits = ev_bitmask;
3000 Curl_expire(data, 0, EXPIRE_RUN_NOW);
3003 /* Now we fall-through and do the timer-based stuff, since we don't want
3004 to force the user to have to deal with timeouts as long as at least
3005 one connection in fact has traffic. */
3007 data = NULL; /* set data to NULL again to avoid calling
3008 multi_runsingle() in case there's no need to */
3009 now = Curl_now(); /* get a newer time since the multi_runsingle() loop
3010 may have taken some time */
3014 /* Asked to run due to time-out. Clear the 'lastcall' variable to force
3015 Curl_update_timer() to trigger a callback to the app again even if the
3016 same timeout is still the one to run after this call. That handles the
3017 case when the application asks libcurl to run the timeout
3019 memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
3023 * The loop following here will go on as long as there are expire-times left
3024 * to process in the splay and 'data' will be re-assigned for every expired
3025 * handle we deal with.
3028 /* the first loop lap 'data' can be NULL */
3030 SIGPIPE_VARIABLE(pipe_st);
3032 sigpipe_ignore(data, &pipe_st);
3033 result = multi_runsingle(multi, &now, data);
3034 sigpipe_restore(&pipe_st);
3036 if(CURLM_OK >= result) {
3037 /* get the socket(s) and check if the state has been changed since
3039 result = singlesocket(multi, data);
3045 /* Check if there's one (more) expired timer to deal with! This function
3046 extracts a matching node if there is one */
3048 multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
3050 data = t->payload; /* assign this for next loop */
3051 (void)add_next_timeout(now, multi, t->payload);
3056 *running_handles = multi->num_alive;
3060 #undef curl_multi_setopt
3061 CURLMcode curl_multi_setopt(struct Curl_multi *multi,
3062 CURLMoption option, ...)
3064 CURLMcode res = CURLM_OK;
3067 if(!GOOD_MULTI_HANDLE(multi))
3068 return CURLM_BAD_HANDLE;
3070 if(multi->in_callback)
3071 return CURLM_RECURSIVE_API_CALL;
3073 va_start(param, option);
3076 case CURLMOPT_SOCKETFUNCTION:
3077 multi->socket_cb = va_arg(param, curl_socket_callback);
3079 case CURLMOPT_SOCKETDATA:
3080 multi->socket_userp = va_arg(param, void *);
3082 case CURLMOPT_PUSHFUNCTION:
3083 multi->push_cb = va_arg(param, curl_push_callback);
3085 case CURLMOPT_PUSHDATA:
3086 multi->push_userp = va_arg(param, void *);
3088 case CURLMOPT_PIPELINING:
3089 multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX;
3091 case CURLMOPT_TIMERFUNCTION:
3092 multi->timer_cb = va_arg(param, curl_multi_timer_callback);
3094 case CURLMOPT_TIMERDATA:
3095 multi->timer_userp = va_arg(param, void *);
3097 case CURLMOPT_MAXCONNECTS:
3098 multi->maxconnects = va_arg(param, long);
3100 case CURLMOPT_MAX_HOST_CONNECTIONS:
3101 multi->max_host_connections = va_arg(param, long);
3103 case CURLMOPT_MAX_TOTAL_CONNECTIONS:
3104 multi->max_total_connections = va_arg(param, long);
3106 /* options formerly used for pipelining */
3107 case CURLMOPT_MAX_PIPELINE_LENGTH:
3109 case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
3111 case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
3113 case CURLMOPT_PIPELINING_SITE_BL:
3115 case CURLMOPT_PIPELINING_SERVER_BL:
3117 case CURLMOPT_MAX_CONCURRENT_STREAMS:
3119 long streams = va_arg(param, long);
3122 multi->max_concurrent_streams = curlx_sltoui(streams);
3126 res = CURLM_UNKNOWN_OPTION;
3133 /* we define curl_multi_socket() in the public multi.h header */
3134 #undef curl_multi_socket
3136 CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
3137 int *running_handles)
3140 if(multi->in_callback)
3141 return CURLM_RECURSIVE_API_CALL;
3142 result = multi_socket(multi, FALSE, s, 0, running_handles);
3143 if(CURLM_OK >= result)
3144 Curl_update_timer(multi);
3148 CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
3149 int ev_bitmask, int *running_handles)
3152 if(multi->in_callback)
3153 return CURLM_RECURSIVE_API_CALL;
3154 result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
3155 if(CURLM_OK >= result)
3156 Curl_update_timer(multi);
3160 CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
3164 if(multi->in_callback)
3165 return CURLM_RECURSIVE_API_CALL;
3166 result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
3167 if(CURLM_OK >= result)
3168 Curl_update_timer(multi);
3172 static CURLMcode multi_timeout(struct Curl_multi *multi,
3175 static struct curltime tv_zero = {0, 0};
3177 if(multi->timetree) {
3178 /* we have a tree of expire times */
3179 struct curltime now = Curl_now();
3181 /* splay the lowest to the bottom */
3182 multi->timetree = Curl_splay(tv_zero, multi->timetree);
3184 if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
3185 /* some time left before expiration */
3186 timediff_t diff = Curl_timediff(multi->timetree->key, now);
3189 * Since we only provide millisecond resolution on the returned value
3190 * and the diff might be less than one millisecond here, we don't
3191 * return zero as that may cause short bursts of busyloops on fast
3192 * processors while the diff is still present but less than one
3193 * millisecond! instead we return 1 until the time is ripe.
3197 /* this should be safe even on 64 bit archs, as we don't use that
3198 overly long timeouts */
3199 *timeout_ms = (long)diff;
3202 /* 0 means immediately */
3211 CURLMcode curl_multi_timeout(struct Curl_multi *multi,
3214 /* First, make some basic checks that the CURLM handle is a good handle */
3215 if(!GOOD_MULTI_HANDLE(multi))
3216 return CURLM_BAD_HANDLE;
3218 if(multi->in_callback)
3219 return CURLM_RECURSIVE_API_CALL;
3221 return multi_timeout(multi, timeout_ms);
3225 * Tell the application it should update its timers, if it subscribes to the
3226 * update timer callback.
3228 void Curl_update_timer(struct Curl_multi *multi)
3232 if(!multi->timer_cb)
3234 if(multi_timeout(multi, &timeout_ms)) {
3237 if(timeout_ms < 0) {
3238 static const struct curltime none = {0, 0};
3239 if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
3240 multi->timer_lastcall = none;
3241 /* there's no timeout now but there was one previously, tell the app to
3243 multi->timer_cb(multi, -1, multi->timer_userp);
3249 /* When multi_timeout() is done, multi->timetree points to the node with the
3250 * timeout we got the (relative) time-out time for. We can thus easily check
3251 * if this is the same (fixed) time as we got in a previous call and then
3252 * avoid calling the callback again. */
3253 if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
3256 multi->timer_lastcall = multi->timetree->key;
3258 multi->timer_cb(multi, timeout_ms, multi->timer_userp);
3262 * multi_deltimeout()
3264 * Remove a given timestamp from the list of timeouts.
3267 multi_deltimeout(struct Curl_easy *data, expire_id eid)
3269 struct Curl_llist_element *e;
3270 struct Curl_llist *timeoutlist = &data->state.timeoutlist;
3271 /* find and remove the specific node from the list */
3272 for(e = timeoutlist->head; e; e = e->next) {
3273 struct time_node *n = (struct time_node *)e->ptr;
3275 Curl_llist_remove(timeoutlist, e, NULL);
3282 * multi_addtimeout()
3284 * Add a timestamp to the list of timeouts. Keep the list sorted so that head
3285 * of list is always the timeout nearest in time.
3289 multi_addtimeout(struct Curl_easy *data,
3290 struct curltime *stamp,
3293 struct Curl_llist_element *e;
3294 struct time_node *node;
3295 struct Curl_llist_element *prev = NULL;
3297 struct Curl_llist *timeoutlist = &data->state.timeoutlist;
3299 node = &data->state.expires[eid];
3301 /* copy the timestamp and id */
3302 memcpy(&node->time, stamp, sizeof(*stamp));
3303 node->eid = eid; /* also marks it as in use */
3305 n = Curl_llist_count(timeoutlist);
3307 /* find the correct spot in the list */
3308 for(e = timeoutlist->head; e; e = e->next) {
3309 struct time_node *check = (struct time_node *)e->ptr;
3310 timediff_t diff = Curl_timediff(check->time, node->time);
3318 this is the first timeout on the list */
3320 Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
3327 * given a number of milliseconds from now to use to set the 'act before
3328 * this'-time for the transfer, to be extracted by curl_multi_timeout()
3330 * The timeout will be added to a queue of timeouts if it defines a moment in
3331 * time that is later than the current head of queue.
3333 * Expire replaces a former timeout using the same id if already set.
3335 void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
3337 struct Curl_multi *multi = data->multi;
3338 struct curltime *nowp = &data->state.expiretime;
3339 struct curltime set;
3341 /* this is only interesting while there is still an associated multi struct
3346 DEBUGASSERT(id < EXPIRE_LAST);
3349 set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */
3350 set.tv_usec += (unsigned int)(milli%1000)*1000;
3352 if(set.tv_usec >= 1000000) {
3354 set.tv_usec -= 1000000;
3357 /* Remove any timer with the same id just in case. */
3358 multi_deltimeout(data, id);
3360 /* Add it to the timer list. It must stay in the list until it has expired
3361 in case we need to recompute the minimum timer later. */
3362 multi_addtimeout(data, &set, id);
3364 if(nowp->tv_sec || nowp->tv_usec) {
3365 /* This means that the struct is added as a node in the splay tree.
3366 Compare if the new time is earlier, and only remove-old/add-new if it
3368 timediff_t diff = Curl_timediff(set, *nowp);
3372 /* The current splay tree entry is sooner than this new expiry time.
3373 We don't need to update our splay tree entry. */
3377 /* Since this is an updated time, we must remove the previous entry from
3378 the splay tree first and then re-add the new value */
3379 rc = Curl_splayremovebyaddr(multi->timetree,
3380 &data->state.timenode,
3383 infof(data, "Internal error removing splay node = %d\n", rc);
3386 /* Indicate that we are in the splay tree and insert the new timer expiry
3387 value since it is our local minimum. */
3389 data->state.timenode.payload = data;
3390 multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
3391 &data->state.timenode);
3395 * Curl_expire_done()
3397 * Removes the expire timer. Marks it as done.
3400 void Curl_expire_done(struct Curl_easy *data, expire_id id)
3402 /* remove the timer, if there */
3403 multi_deltimeout(data, id);
3407 * Curl_expire_clear()
3409 * Clear ALL timeout values for this handle.
3411 void Curl_expire_clear(struct Curl_easy *data)
3413 struct Curl_multi *multi = data->multi;
3414 struct curltime *nowp = &data->state.expiretime;
3416 /* this is only interesting while there is still an associated multi struct
3421 if(nowp->tv_sec || nowp->tv_usec) {
3422 /* Since this is an cleared time, we must remove the previous entry from
3424 struct Curl_llist *list = &data->state.timeoutlist;
3427 rc = Curl_splayremovebyaddr(multi->timetree,
3428 &data->state.timenode,
3431 infof(data, "Internal error clearing splay node = %d\n", rc);
3433 /* flush the timeout list too */
3434 while(list->size > 0) {
3435 Curl_llist_remove(list, list->tail, NULL);
3439 infof(data, "Expire cleared (transfer %p)\n", data);
3449 CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
3452 struct Curl_sh_entry *there = NULL;
3454 if(multi->in_callback)
3455 return CURLM_RECURSIVE_API_CALL;
3457 there = sh_getentry(&multi->sockhash, s);
3460 return CURLM_BAD_SOCKET;
3462 there->socketp = hashp;
3467 size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
3469 return multi ? multi->max_host_connections : 0;
3472 size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
3474 return multi ? multi->max_total_connections : 0;
3478 * When information about a connection has appeared, call this!
3481 void Curl_multiuse_state(struct connectdata *conn,
3482 int bundlestate) /* use BUNDLE_* defines */
3485 DEBUGASSERT(conn->bundle);
3486 DEBUGASSERT(conn->data);
3487 DEBUGASSERT(conn->data->multi);
3489 conn->bundle->multiuse = bundlestate;
3490 process_pending_handles(conn->data->multi);
3493 static void process_pending_handles(struct Curl_multi *multi)
3495 struct Curl_llist_element *e = multi->pending.head;
3497 struct Curl_easy *data = e->ptr;
3499 DEBUGASSERT(data->mstate == CURLM_STATE_CONNECT_PEND);
3501 multistate(data, CURLM_STATE_CONNECT);
3503 /* Remove this node from the list */
3504 Curl_llist_remove(&multi->pending, e, NULL);
3506 /* Make sure that the handle will be processed soonish. */
3507 Curl_expire(data, 0, EXPIRE_RUN_NOW);
3509 /* mark this as having been in the pending queue */
3510 data->state.previouslypending = TRUE;
3514 void Curl_set_in_callback(struct Curl_easy *data, bool value)
3516 /* might get called when there is no data pointer! */
3518 if(data->multi_easy)
3519 data->multi_easy->in_callback = value;
3520 else if(data->multi)
3521 data->multi->in_callback = value;
3525 bool Curl_is_in_callback(struct Curl_easy *easy)
3527 return ((easy->multi && easy->multi->in_callback) ||
3528 (easy->multi_easy && easy->multi_easy->in_callback));
3532 void Curl_multi_dump(struct Curl_multi *multi)
3534 struct Curl_easy *data;
3536 fprintf(stderr, "* Multi status: %d handles, %d alive\n",
3537 multi->num_easy, multi->num_alive);
3538 for(data = multi->easyp; data; data = data->next) {
3539 if(data->mstate < CURLM_STATE_COMPLETED) {
3540 /* only display handles that are not completed */
3541 fprintf(stderr, "handle %p, state %s, %d sockets\n",
3543 statename[data->mstate], data->numsocks);
3544 for(i = 0; i < data->numsocks; i++) {
3545 curl_socket_t s = data->sockets[i];
3546 struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
3548 fprintf(stderr, "%d ", (int)s);
3550 fprintf(stderr, "INTERNAL CONFUSION\n");
3553 fprintf(stderr, "[%s %s] ",
3554 (entry->action&CURL_POLL_IN)?"RECVING":"",
3555 (entry->action&CURL_POLL_OUT)?"SENDING":"");
3558 fprintf(stderr, "\n");
3564 unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
3567 return multi->max_concurrent_streams;