Imported Upstream version 7.59.0
[platform/upstream/curl.git] / lib / multi.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #include <curl/curl.h>
26
27 #include "urldata.h"
28 #include "transfer.h"
29 #include "url.h"
30 #include "connect.h"
31 #include "progress.h"
32 #include "easyif.h"
33 #include "share.h"
34 #include "multiif.h"
35 #include "sendf.h"
36 #include "timeval.h"
37 #include "http.h"
38 #include "select.h"
39 #include "warnless.h"
40 #include "speedcheck.h"
41 #include "conncache.h"
42 #include "multihandle.h"
43 #include "pipeline.h"
44 #include "sigpipe.h"
45 #include "vtls/vtls.h"
46 #include "connect.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"
51 #include "memdebug.h"
52
53 /*
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.
57 */
58 #ifndef CURL_SOCKET_HASH_TABLE_SIZE
59 #define CURL_SOCKET_HASH_TABLE_SIZE 911
60 #endif
61
62 #ifndef CURL_CONNECTION_HASH_SIZE
63 #define CURL_CONNECTION_HASH_SIZE 97
64 #endif
65
66 #define CURL_MULTI_HANDLE 0x000bab1e
67
68 #define GOOD_MULTI_HANDLE(x) \
69   ((x) && (x)->type == CURL_MULTI_HANDLE)
70
71 static void singlesocket(struct Curl_multi *multi,
72                          struct Curl_easy *data);
73 static int update_timer(struct Curl_multi *multi);
74
75 static CURLMcode add_next_timeout(struct curltime now,
76                                   struct Curl_multi *multi,
77                                   struct Curl_easy *d);
78 static CURLMcode multi_timeout(struct Curl_multi *multi,
79                                long *timeout_ms);
80
81 #ifdef DEBUGBUILD
82 static const char * const statename[]={
83   "INIT",
84   "CONNECT_PEND",
85   "CONNECT",
86   "WAITRESOLVE",
87   "WAITCONNECT",
88   "WAITPROXYCONNECT",
89   "SENDPROTOCONNECT",
90   "PROTOCONNECT",
91   "WAITDO",
92   "DO",
93   "DOING",
94   "DO_MORE",
95   "DO_DONE",
96   "WAITPERFORM",
97   "PERFORM",
98   "TOOFAST",
99   "DONE",
100   "COMPLETED",
101   "MSGSENT",
102 };
103 #endif
104
105 /* function pointer called once when switching TO a state */
106 typedef void (*init_multistate_func)(struct Curl_easy *data);
107
108 /* always use this function to change state, to make debugging easier */
109 static void mstate(struct Curl_easy *data, CURLMstate state
110 #ifdef DEBUGBUILD
111                    , int lineno
112 #endif
113 )
114 {
115   CURLMstate oldstate = data->mstate;
116   static const init_multistate_func finit[CURLM_STATE_LAST] = {
117     NULL,
118     NULL,
119     Curl_init_CONNECT, /* CONNECT */
120     NULL,
121     NULL,
122     NULL,
123     NULL,
124     NULL,
125     NULL,
126     Curl_connect_free /* DO */
127     /* the rest is NULL too */
128   };
129
130 #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
131   (void) lineno;
132 #endif
133
134   if(oldstate == state)
135     /* don't bother when the new state is the same as the old state */
136     return;
137
138   data->mstate = state;
139
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;
144
145     if(data->easy_conn)
146       connection_id = data->easy_conn->connection_id;
147
148     infof(data,
149           "STATE: %s => %s handle %p; line %d (connection #%ld)\n",
150           statename[oldstate], statename[data->mstate],
151           (void *)data, lineno, connection_id);
152   }
153 #endif
154
155   if(state == CURLM_STATE_COMPLETED)
156     /* changing to COMPLETED means there's one less easy handle 'alive' */
157     data->multi->num_alive--;
158
159   /* if this state has an init-function, run it */
160   if(finit[state])
161     finit[state](data);
162 }
163
164 #ifndef DEBUGBUILD
165 #define multistate(x,y) mstate(x,y)
166 #else
167 #define multistate(x,y) mstate(x,y, __LINE__)
168 #endif
169
170 /*
171  * We add one of these structs to the sockhash for a particular socket
172  */
173
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() */
179 };
180 /* bits for 'action' having no bits means this socket is not expecting any
181    action */
182 #define SH_READ  1
183 #define SH_WRITE 2
184
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,
187                                          curl_socket_t s)
188 {
189   if(s != CURL_SOCKET_BAD)
190     /* only look for proper sockets */
191     return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
192   return NULL;
193 }
194
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,
197                                          curl_socket_t s,
198                                          struct Curl_easy *data)
199 {
200   struct Curl_sh_entry *there = sh_getentry(sh, s);
201   struct Curl_sh_entry *check;
202
203   if(there)
204     /* it is present, return fine */
205     return there;
206
207   /* not present, add it */
208   check = calloc(1, sizeof(struct Curl_sh_entry));
209   if(!check)
210     return NULL; /* major failure */
211
212   check->easy = data;
213   check->socket = s;
214
215   /* make/add new hash entry */
216   if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
217     free(check);
218     return NULL; /* major failure */
219   }
220
221   return check; /* things are good in sockhash land */
222 }
223
224
225 /* delete the given socket + handle from the hash */
226 static void sh_delentry(struct curl_hash *sh, curl_socket_t s)
227 {
228   /* We remove the hash entry. This will end up in a call to
229      sh_freeentry(). */
230   Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
231 }
232
233 /*
234  * free a sockhash entry
235  */
236 static void sh_freeentry(void *freethis)
237 {
238   struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
239
240   free(p);
241 }
242
243 static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
244 {
245   (void) k1_len; (void) k2_len;
246
247   return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2));
248 }
249
250 static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
251 {
252   curl_socket_t fd = *((curl_socket_t *) key);
253   (void) key_length;
254
255   return (fd % slots_num);
256 }
257
258 /*
259  * sh_init() creates a new socket hash and returns the handle for it.
260  *
261  * Quote from README.multi_socket:
262  *
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
273  * per call."
274  *
275  */
276 static int sh_init(struct curl_hash *hash, int hashsize)
277 {
278   return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
279                         sh_freeentry);
280 }
281
282 /*
283  * multi_addmsg()
284  *
285  * Called when a transfer is completed. Adds the given msg pointer to
286  * the list kept in the multi handle.
287  */
288 static CURLMcode multi_addmsg(struct Curl_multi *multi,
289                               struct Curl_message *msg)
290 {
291   Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg,
292                          &msg->list);
293   return CURLM_OK;
294 }
295
296 /*
297  * multi_freeamsg()
298  *
299  * Callback used by the llist system when a single list entry is destroyed.
300  */
301 static void multi_freeamsg(void *a, void *b)
302 {
303   (void)a;
304   (void)b;
305 }
306
307 struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
308                                      int chashsize) /* connection hash */
309 {
310   struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
311
312   if(!multi)
313     return NULL;
314
315   multi->type = CURL_MULTI_HANDLE;
316
317   if(Curl_mk_dnscache(&multi->hostcache))
318     goto error;
319
320   if(sh_init(&multi->sockhash, hashsize))
321     goto error;
322
323   if(Curl_conncache_init(&multi->conn_cache, chashsize))
324     goto error;
325
326   Curl_llist_init(&multi->msglist, multi_freeamsg);
327   Curl_llist_init(&multi->pending, multi_freeamsg);
328
329   multi->max_pipeline_length = 5;
330
331   /* -1 means it not set by user, use the default value */
332   multi->maxconnects = -1;
333   return multi;
334
335   error:
336
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);
342
343   free(multi);
344   return NULL;
345 }
346
347 struct Curl_multi *curl_multi_init(void)
348 {
349   return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
350                            CURL_CONNECTION_HASH_SIZE);
351 }
352
353 CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
354                                 struct Curl_easy *data)
355 {
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;
359
360   /* Verify that we got a somewhat good easy handle too */
361   if(!GOOD_EASY_HANDLE(data))
362     return CURLM_BAD_EASY_HANDLE;
363
364   /* Prevent users from adding same easy handle more than once and prevent
365      adding to more than one multi stack */
366   if(data->multi)
367     return CURLM_ADDED_ALREADY;
368
369   if(multi->in_callback)
370     return CURLM_RECURSIVE_API_CALL;
371
372   /* Initialize timeout list for this handle */
373   Curl_llist_init(&data->state.timeoutlist, NULL);
374
375   /*
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.
380    */
381
382   /* set the easy handle */
383   multistate(data, CURLM_STATE_INIT);
384
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();
389     if(global) {
390       /* only do this if the global cache init works */
391       data->dns.hostcache = global;
392       data->dns.hostcachetype = HCACHE_GLOBAL;
393     }
394   }
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;
401   }
402
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;
406   else
407     data->state.conn_cache = &multi->conn_cache;
408
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. */
412
413   /* We add this new entry last in the list. */
414
415   data->next = NULL; /* end of the line */
416   if(multi->easyp) {
417     struct Curl_easy *last = multi->easylp;
418     last->next = data;
419     data->prev = last;
420     multi->easylp = data; /* the new last node */
421   }
422   else {
423     /* first node, make prev NULL! */
424     data->prev = NULL;
425     multi->easylp = multi->easyp = data; /* both first and last */
426   }
427
428   /* make the Curl_easy refer back to this multi handle */
429   data->multi = multi;
430
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
436      happen. */
437   Curl_expire(data, 0, EXPIRE_RUN_NOW);
438
439   /* increase the node-counter */
440   multi->num_easy++;
441
442   /* increase the alive-counter */
443   multi->num_alive++;
444
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.
451
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
454      handle is added */
455   memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
456
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
460      easy handle. */
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;
464
465   update_timer(multi);
466   return CURLM_OK;
467 }
468
469 #if 0
470 /* Debug-function, used like this:
471  *
472  * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
473  *
474  * Enable the hash print function first by editing hash.c
475  */
476 static void debug_print_sock_hash(void *p)
477 {
478   struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
479
480   fprintf(stderr, " [easy %p/magic %x/socket %d]",
481           (void *)sh->data, sh->data->magic, (int)sh->socket);
482 }
483 #endif
484
485 static CURLcode multi_done(struct connectdata **connp,
486                           CURLcode status,  /* an error if this is called
487                                                after an error was detected */
488                           bool premature)
489 {
490   CURLcode result;
491   struct connectdata *conn;
492   struct Curl_easy *data;
493   unsigned int i;
494
495   DEBUGASSERT(*connp);
496
497   conn = *connp;
498   data = conn->data;
499
500   DEBUGF(infof(data, "multi_done\n"));
501
502   if(data->state.done)
503     /* Stop if multi_done() has already been called */
504     return CURLE_OK;
505
506   Curl_getoff_all_pipelines(data, conn);
507
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;
513
514   switch(status) {
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. */
522     premature = TRUE;
523   default:
524     break;
525   }
526
527   /* this calls the protocol-specific function pointer previously set */
528   if(conn->handler->done)
529     result = conn->handler->done(conn, status, premature);
530   else
531     result = status;
532
533   if(CURLE_ABORTED_BY_CALLBACK != result) {
534     /* avoid this if we already aborted by callback to avoid this calling
535        another callback */
536     CURLcode rc = Curl_pgrsDone(conn);
537     if(!result && rc)
538       result = CURLE_ABORTED_BY_CALLBACK;
539   }
540
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"));
545     return CURLE_OK;
546   }
547
548   data->state.done = TRUE; /* called just now! */
549   Curl_resolver_cancel(conn);
550
551   if(conn->dns_entry) {
552     Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
553     conn->dns_entry = NULL;
554   }
555   Curl_hostcache_prune(data);
556
557   /* if the transfer was completed in a paused state there can be buffered
558      data left to free */
559   for(i = 0; i < data->state.tempcount; i++) {
560     free(data->state.tempwrite[i].buf);
561   }
562   data->state.tempcount = 0;
563
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
567
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
571
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.
577   */
578
579   if((data->set.reuse_forbid
580 #if defined(USE_NTLM)
581       && !(conn->ntlm.state == NTLMSTATE_TYPE2 ||
582            conn->proxyntlm.state == NTLMSTATE_TYPE2)
583 #endif
584      ) || conn->bits.close
585        || (premature && !(conn->handler->flags & PROTOPT_STREAM))) {
586     CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
587
588     /* If we had an error already, make sure we return that one. But
589        if we got a new error, return that. */
590     if(!result && res2)
591       result = res2;
592   }
593   else {
594     char buffer[256];
595     /* create string before returning the connection */
596     snprintf(buffer, sizeof(buffer),
597              "Connection #%ld to host %s left intact",
598              conn->connection_id,
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);
603
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);
609     }
610     else
611       data->state.lastconnect = NULL;
612   }
613
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
617                  */
618   Curl_free_request_state(data);
619
620   return result;
621 }
622
623 CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
624                                    struct Curl_easy *data)
625 {
626   struct Curl_easy *easy = data;
627   bool premature;
628   bool easy_owns_conn;
629   struct curl_llist_element *e;
630
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;
634
635   /* Verify that we got a somewhat good easy handle too */
636   if(!GOOD_EASY_HANDLE(data))
637     return CURLM_BAD_EASY_HANDLE;
638
639   /* Prevent users from trying to remove same easy handle more than once */
640   if(!data->multi)
641     return CURLM_OK; /* it is already removed so let's say it is fine! */
642
643   if(multi->in_callback)
644     return CURLM_RECURSIVE_API_CALL;
645
646   premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
647   easy_owns_conn = (data->easy_conn && (data->easy_conn->data == easy)) ?
648     TRUE : FALSE;
649
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. */
652   if(premature) {
653     /* this handle is "alive" so we need to count down the total number of
654        alive connections when this is removed */
655     multi->num_alive--;
656
657     /* When this handle gets removed, other handles may be able to get the
658        connection */
659     Curl_multi_process_pending_handles(multi);
660   }
661
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
670        connection. */
671     streamclose(data->easy_conn, "Removed with partial response");
672     easy_owns_conn = TRUE;
673   }
674
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);
679
680   if(data->easy_conn) {
681
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 */
684     if(easy_owns_conn) {
685
686       /* multi_done() clears the conn->data field to lose the association
687          between the easy handle and the connection
688
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);
692     }
693     else
694       /* Clear connection pipelines, if multi_done above was not called */
695       Curl_getoff_all_pipelines(data, data->easy_conn);
696   }
697
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;
703   }
704
705   Curl_wildcard_dtor(&data->wildcard);
706
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);
710
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;
714
715   /* change state without using multistate(), only to make singlesocket() do
716      what we want */
717   data->mstate = CURLM_STATE_COMPLETED;
718   singlesocket(multi, easy); /* to let the application know what sockets that
719                                 vanish with this handle */
720
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;
725   }
726
727   data->multi = NULL; /* clear the association to this multi handle */
728
729   /* make sure there's no pending message in the queue sent from this easy
730      handle */
731
732   for(e = multi->msglist.head; e; e = e->next) {
733     struct Curl_message *msg = e->ptr;
734
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 */
738       break;
739     }
740   }
741
742   /* make the previous node point to our next */
743   if(data->prev)
744     data->prev->next = data->next;
745   else
746     multi->easyp = data->next; /* point to first node */
747
748   /* make our next point to our previous node */
749   if(data->next)
750     data->next->prev = data->prev;
751   else
752     multi->easylp = data->prev; /* point to last node */
753
754   /* NOTE NOTE NOTE
755      We do not touch the easy handle here! */
756   multi->num_easy--; /* one less to care about now */
757
758   update_timer(multi);
759   return CURLM_OK;
760 }
761
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)
764 {
765   return (multi && (multi->pipelining & bits)) ? TRUE : FALSE;
766 }
767
768 void Curl_multi_handlePipeBreak(struct Curl_easy *data)
769 {
770   data->easy_conn = NULL;
771 }
772
773 static int waitconnect_getsock(struct connectdata *conn,
774                                curl_socket_t *sock,
775                                int numsocks)
776 {
777   int i;
778   int s = 0;
779   int rc = 0;
780
781   if(!numsocks)
782     return GETSOCK_BLANK;
783
784 #ifdef USE_SSL
785   if(CONNECT_FIRSTSOCKET_PROXY_SSL())
786     return Curl_ssl_getsock(conn, sock, numsocks);
787 #endif
788
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++);
793     }
794   }
795
796   return rc;
797 }
798
799 static int waitproxyconnect_getsock(struct connectdata *conn,
800                                     curl_socket_t *sock,
801                                     int numsocks)
802 {
803   if(!numsocks)
804     return GETSOCK_BLANK;
805
806   sock[0] = conn->sock[FIRSTSOCKET];
807
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);
812
813   return GETSOCK_WRITESOCK(0);
814 }
815
816 static int domore_getsock(struct connectdata *conn,
817                           curl_socket_t *socks,
818                           int numsocks)
819 {
820   if(conn && conn->handler->domore_getsock)
821     return conn->handler->domore_getsock(conn, socks, numsocks);
822   return GETSOCK_BLANK;
823 }
824
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
828                                                   of sockets */
829                          int numsocks)
830 {
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().
835   */
836   if(data->state.pipe_broke || !data->easy_conn)
837     return 0;
838
839   if(data->mstate > CURLM_STATE_CONNECT &&
840      data->mstate < CURLM_STATE_COMPLETED) {
841     /* Set up ownership correctly */
842     data->easy_conn->data = data;
843   }
844
845   switch(data->mstate) {
846   default:
847 #if 0 /* switch back on these cases to get the compiler to check for all enums
848          to be present */
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
858        removed */
859 #endif
860     return 0;
861
862   case CURLM_STATE_WAITRESOLVE:
863     return Curl_resolver_getsock(data->easy_conn, socks, numsocks);
864
865   case CURLM_STATE_PROTOCONNECT:
866   case CURLM_STATE_SENDPROTOCONNECT:
867     return Curl_protocol_getsock(data->easy_conn, socks, numsocks);
868
869   case CURLM_STATE_DO:
870   case CURLM_STATE_DOING:
871     return Curl_doing_getsock(data->easy_conn, socks, numsocks);
872
873   case CURLM_STATE_WAITPROXYCONNECT:
874     return waitproxyconnect_getsock(data->easy_conn, socks, numsocks);
875
876   case CURLM_STATE_WAITCONNECT:
877     return waitconnect_getsock(data->easy_conn, socks, numsocks);
878
879   case CURLM_STATE_DO_MORE:
880     return domore_getsock(data->easy_conn, socks, numsocks);
881
882   case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
883                                to waiting for the same as the *PERFORM
884                                states */
885   case CURLM_STATE_PERFORM:
886   case CURLM_STATE_WAITPERFORM:
887     return Curl_single_getsock(data->easy_conn, socks, numsocks);
888   }
889
890 }
891
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)
895 {
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];
902   int bitmap;
903   int i;
904   (void)exc_fd_set; /* not used */
905
906   if(!GOOD_MULTI_HANDLE(multi))
907     return CURLM_BAD_HANDLE;
908
909   if(multi->in_callback)
910     return CURLM_RECURSIVE_API_CALL;
911
912   data = multi->easyp;
913   while(data) {
914     bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
915
916     for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
917       curl_socket_t s = CURL_SOCKET_BAD;
918
919       if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
920         FD_SET(sockbunch[i], read_fd_set);
921         s = sockbunch[i];
922       }
923       if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
924         FD_SET(sockbunch[i], write_fd_set);
925         s = sockbunch[i];
926       }
927       if(s == CURL_SOCKET_BAD)
928         /* this socket is unused, break out of loop */
929         break;
930       if((int)s > this_max_fd)
931         this_max_fd = (int)s;
932     }
933
934     data = data->next; /* check next handle */
935   }
936
937   *max_fd = this_max_fd;
938
939   return CURLM_OK;
940 }
941
942 #define NUM_POLLS_ON_STACK 10
943
944 CURLMcode curl_multi_wait(struct Curl_multi *multi,
945                           struct curl_waitfd extra_fds[],
946                           unsigned int extra_nfds,
947                           int timeout_ms,
948                           int *ret)
949 {
950   struct Curl_easy *data;
951   curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
952   int bitmap;
953   unsigned int i;
954   unsigned int nfds = 0;
955   unsigned int curlfds;
956   struct pollfd *ufds = NULL;
957   bool ufds_malloc = FALSE;
958   long timeout_internal;
959   int retcode = 0;
960   struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
961
962   if(!GOOD_MULTI_HANDLE(multi))
963     return CURLM_BAD_HANDLE;
964
965   if(multi->in_callback)
966     return CURLM_RECURSIVE_API_CALL;
967
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;
974
975   /* Count up how many fds we have from the multi handle */
976   data = multi->easyp;
977   while(data) {
978     bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
979
980     for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
981       curl_socket_t s = CURL_SOCKET_BAD;
982
983       if(bitmap & GETSOCK_READSOCK(i)) {
984         ++nfds;
985         s = sockbunch[i];
986       }
987       if(bitmap & GETSOCK_WRITESOCK(i)) {
988         ++nfds;
989         s = sockbunch[i];
990       }
991       if(s == CURL_SOCKET_BAD) {
992         break;
993       }
994     }
995
996     data = data->next; /* check next handle */
997   }
998
999   curlfds = nfds; /* number of internal file descriptors */
1000   nfds += extra_nfds; /* add the externally provided ones */
1001
1002   if(nfds) {
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));
1009       if(!ufds)
1010         return CURLM_OUT_OF_MEMORY;
1011       ufds_malloc = TRUE;
1012     }
1013     else
1014       ufds = &a_few_on_stack[0];
1015   }
1016   nfds = 0;
1017
1018   /* only do the second loop if we found descriptors in the first stage run
1019      above */
1020
1021   if(curlfds) {
1022     /* Add the curl handles to our pollfds first */
1023     data = multi->easyp;
1024     while(data) {
1025       bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
1026
1027       for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
1028         curl_socket_t s = CURL_SOCKET_BAD;
1029
1030         if(bitmap & GETSOCK_READSOCK(i)) {
1031           ufds[nfds].fd = sockbunch[i];
1032           ufds[nfds].events = POLLIN;
1033           ++nfds;
1034           s = sockbunch[i];
1035         }
1036         if(bitmap & GETSOCK_WRITESOCK(i)) {
1037           ufds[nfds].fd = sockbunch[i];
1038           ufds[nfds].events = POLLOUT;
1039           ++nfds;
1040           s = sockbunch[i];
1041         }
1042         if(s == CURL_SOCKET_BAD) {
1043           break;
1044         }
1045       }
1046
1047       data = data->next; /* check next handle */
1048     }
1049   }
1050
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;
1061     ++nfds;
1062   }
1063
1064   if(nfds) {
1065     int pollrc;
1066     /* wait... */
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));
1070
1071     if(pollrc > 0) {
1072       retcode = 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;
1079
1080         if(r & POLLIN)
1081           mask |= CURL_WAIT_POLLIN;
1082         if(r & POLLOUT)
1083           mask |= CURL_WAIT_POLLOUT;
1084         if(r & POLLPRI)
1085           mask |= CURL_WAIT_POLLPRI;
1086
1087         extra_fds[i].revents = mask;
1088       }
1089     }
1090   }
1091
1092   if(ufds_malloc)
1093     free(ufds);
1094   if(ret)
1095     *ret = retcode;
1096   return CURLM_OK;
1097 }
1098
1099 /*
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
1104  * retry.
1105  */
1106 void Curl_multi_connchanged(struct Curl_multi *multi)
1107 {
1108   multi->recheckstate = TRUE;
1109 }
1110
1111 /*
1112  * multi_ischanged() is called
1113  *
1114  * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
1115  * => CONNECT action.
1116  *
1117  * Set 'clear' to TRUE to have it also clear the state variable.
1118  */
1119 static bool multi_ischanged(struct Curl_multi *multi, bool clear)
1120 {
1121   bool retval = multi->recheckstate;
1122   if(clear)
1123     multi->recheckstate = FALSE;
1124   return retval;
1125 }
1126
1127 CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
1128                                  struct Curl_easy *data,
1129                                  struct connectdata *conn)
1130 {
1131   CURLMcode rc;
1132
1133   if(multi->in_callback)
1134     return CURLM_RECURSIVE_API_CALL;
1135
1136   rc = curl_multi_add_handle(multi, data);
1137   if(!rc) {
1138     struct SingleRequest *k = &data->req;
1139
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);
1143
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! */
1148   }
1149   return rc;
1150 }
1151
1152 static CURLcode multi_reconnect_request(struct connectdata **connp)
1153 {
1154   CURLcode result = CURLE_OK;
1155   struct connectdata *conn = *connp;
1156   struct Curl_easy *data = conn->data;
1157
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
1162    * each.  */
1163
1164   infof(data, "Re-used connection seems dead, get a new one\n");
1165
1166   connclose(conn, "Reconnect dead connection"); /* enforce close */
1167   result = multi_done(&conn, result, FALSE); /* we are so done with this */
1168
1169   /* conn may no longer be a good pointer, clear it to avoid mistakes by
1170      parent functions */
1171   *connp = NULL;
1172
1173   /*
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).
1177    */
1178   if(!result || (CURLE_SEND_ERROR == result)) {
1179     bool async;
1180     bool protocol_done = TRUE;
1181
1182     /* Now, redo the connect and get a new connection */
1183     result = Curl_connect(data, connp, &async, &protocol_done);
1184     if(!result) {
1185       /* We have connected or sent away a name resolve query fine */
1186
1187       conn = *connp; /* setup conn to again point to something nice */
1188       if(async) {
1189         /* Now, if async is TRUE here, we need to wait for the name
1190            to resolve */
1191         result = Curl_resolver_wait_resolv(conn, NULL);
1192         if(result)
1193           return result;
1194
1195         /* Resolved, continue with the connection */
1196         result = Curl_async_resolved(conn, &protocol_done);
1197         if(result)
1198           return result;
1199       }
1200     }
1201   }
1202
1203   return result;
1204 }
1205
1206 /*
1207  * do_complete is called when the DO actions are complete.
1208  *
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.
1211  */
1212 static void do_complete(struct connectdata *conn)
1213 {
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);
1218 }
1219
1220 static CURLcode multi_do(struct connectdata **connp, bool *done)
1221 {
1222   CURLcode result = CURLE_OK;
1223   struct connectdata *conn = *connp;
1224   struct Curl_easy *data = conn->data;
1225
1226   if(conn->handler->do_it) {
1227     /* generic protocol-specific function pointer set in curl_connect() */
1228     result = conn->handler->do_it(conn, done);
1229
1230     /* This was formerly done in transfer.c, but we better do it here */
1231     if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
1232       /*
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.
1236        */
1237       if(!data->multi) {
1238         result = multi_reconnect_request(connp);
1239
1240         if(!result) {
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);
1245         }
1246       }
1247       else
1248         return result;
1249     }
1250
1251     if(!result && *done)
1252       /* do_complete must be called after the protocol-specific DO function */
1253       do_complete(conn);
1254   }
1255   return result;
1256 }
1257
1258 /*
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.
1262  *
1263  * TODO: A future libcurl should be able to work away this state.
1264  *
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!
1267  */
1268
1269 static CURLcode multi_do_more(struct connectdata *conn, int *complete)
1270 {
1271   CURLcode result = CURLE_OK;
1272
1273   *complete = 0;
1274
1275   if(conn->handler->do_more)
1276     result = conn->handler->do_more(conn, complete);
1277
1278   if(!result && (*complete == 1))
1279     /* do_complete must be called after the protocol-specific DO function */
1280     do_complete(conn);
1281
1282   return result;
1283 }
1284
1285 static CURLMcode multi_runsingle(struct Curl_multi *multi,
1286                                  struct curltime now,
1287                                  struct Curl_easy *data)
1288 {
1289   struct Curl_message *msg = NULL;
1290   bool connected;
1291   bool async;
1292   bool protocol_connect = FALSE;
1293   bool dophase_done = FALSE;
1294   bool done = FALSE;
1295   CURLMcode rc;
1296   CURLcode result = CURLE_OK;
1297   struct SingleRequest *k;
1298   time_t timeout_ms;
1299   time_t recv_timeout_ms;
1300   timediff_t send_timeout_ms;
1301   int control;
1302
1303   if(!GOOD_EASY_HANDLE(data))
1304     return CURLM_BAD_EASY_HANDLE;
1305
1306   do {
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;
1310     rc = CURLM_OK;
1311
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);
1317
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;
1322         result = CURLE_OK;
1323       }
1324
1325       data->state.pipe_broke = FALSE;
1326       data->easy_conn = NULL;
1327       continue;
1328     }
1329
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
1335          analyzers. */
1336       failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
1337       return CURLM_INTERNAL_ERROR;
1338     }
1339
1340     if(multi_ischanged(multi, TRUE)) {
1341       DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n"));
1342       Curl_multi_process_pending_handles(multi);
1343     }
1344
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;
1349     }
1350
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)?
1358                                  TRUE:FALSE);
1359
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));
1368         else {
1369           k = &data->req;
1370           if(k->size != -1) {
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);
1376           }
1377           else {
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),
1381                   k->bytecount);
1382           }
1383         }
1384
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;
1389         }
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;
1394       }
1395     }
1396
1397     switch(data->mstate) {
1398     case CURLM_STATE_INIT:
1399       /* init this transfer. */
1400       result = Curl_pretransfer(data);
1401
1402       if(!result) {
1403         /* after init, go CONNECT */
1404         multistate(data, CURLM_STATE_CONNECT);
1405         Curl_pgrsTime(data, TIMER_STARTOP);
1406         rc = CURLM_CALL_MULTI_PERFORM;
1407       }
1408       break;
1409
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. */
1413       break;
1414
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);
1424
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);
1428         result = CURLE_OK;
1429         break;
1430       }
1431
1432       if(!result) {
1433         /* Add this handle to the send or pend pipeline */
1434         result = Curl_add_handle_to_pipeline(data, data->easy_conn);
1435         if(result)
1436           stream_error = TRUE;
1437         else {
1438           if(async)
1439             /* We're now waiting for an asynchronous name lookup */
1440             multistate(data, CURLM_STATE_WAITRESOLVE);
1441           else {
1442             /* after the connect has been sent off, go WAITCONNECT unless the
1443                protocol connect is already done and we can go directly to
1444                WAITDO or DO! */
1445             rc = CURLM_CALL_MULTI_PERFORM;
1446
1447             if(protocol_connect)
1448               multistate(data, Curl_pipeline_wanted(multi, CURLPIPE_HTTP1)?
1449                          CURLM_STATE_WAITDO:CURLM_STATE_DO);
1450             else {
1451 #ifndef CURL_DISABLE_HTTP
1452               if(Curl_connect_ongoing(data->easy_conn))
1453                 multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1454               else
1455 #endif
1456                 multistate(data, CURLM_STATE_WAITCONNECT);
1457             }
1458           }
1459         }
1460       }
1461       break;
1462
1463     case CURLM_STATE_WAITRESOLVE:
1464       /* awaiting an asynch name resolve to complete */
1465     {
1466       struct Curl_dns_entry *dns = NULL;
1467       struct connectdata *conn = data->easy_conn;
1468       const char *hostname;
1469
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;
1474       else
1475         hostname = conn->host.name;
1476
1477       /* check if we have the name resolved by now */
1478       dns = Curl_fetch_addr(conn, hostname, (int)conn->port);
1479
1480       if(dns) {
1481 #ifdef CURLRES_ASYNCH
1482         conn->async.dns = dns;
1483         conn->async.done = TRUE;
1484 #endif
1485         result = CURLE_OK;
1486         infof(data, "Hostname '%s' was found in DNS cache\n", hostname);
1487       }
1488
1489       if(!dns)
1490         result = Curl_resolver_is_resolved(data->easy_conn, &dns);
1491
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);
1499
1500       if(dns) {
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);
1504
1505         if(result)
1506           /* if Curl_async_resolved() returns failure, the connection struct
1507              is already freed and gone */
1508           data->easy_conn = NULL;           /* no more connection */
1509         else {
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);
1515           else {
1516 #ifndef CURL_DISABLE_HTTP
1517             if(Curl_connect_ongoing(data->easy_conn))
1518               multistate(data, CURLM_STATE_WAITPROXYCONNECT);
1519             else
1520 #endif
1521               multistate(data, CURLM_STATE_WAITCONNECT);
1522           }
1523         }
1524       }
1525
1526       if(result) {
1527         /* failure detected */
1528         stream_error = TRUE;
1529         break;
1530       }
1531     }
1532     break;
1533
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);
1538
1539       if(data->easy_conn->bits.proxy_connect_closed) {
1540         rc = CURLM_CALL_MULTI_PERFORM;
1541         /* connect back to proxy again */
1542         result = CURLE_OK;
1543         multi_done(&data->easy_conn, CURLE_OK, FALSE);
1544         multistate(data, CURLM_STATE_CONNECT);
1545       }
1546       else if(!result) {
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);
1553         }
1554       }
1555       break;
1556 #endif
1557
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);
1567           break;
1568         }
1569 #endif
1570         rc = CURLM_CALL_MULTI_PERFORM;
1571         multistate(data, data->easy_conn->bits.tunnel_proxy?
1572                    CURLM_STATE_WAITPROXYCONNECT:
1573                    CURLM_STATE_SENDPROTOCONNECT);
1574       }
1575       else if(result) {
1576         /* failure detected */
1577         /* Just break, the cleaning up is handled all in one place */
1578         stream_error = TRUE;
1579         break;
1580       }
1581       break;
1582
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);
1588       else if(!result) {
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;
1593       }
1594       else if(result) {
1595         /* failure detected */
1596         Curl_posttransfer(data);
1597         multi_done(&data->easy_conn, result, TRUE);
1598         stream_error = TRUE;
1599       }
1600       break;
1601
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;
1610       }
1611       else if(result) {
1612         /* failure detected */
1613         Curl_posttransfer(data);
1614         multi_done(&data->easy_conn, result, TRUE);
1615         stream_error = TRUE;
1616       }
1617       break;
1618
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;
1625       }
1626       break;
1627
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);
1633         result = CURLE_OK;
1634         rc = CURLM_CALL_MULTI_PERFORM;
1635       }
1636       else {
1637         /* Perform the protocol's DO action */
1638         result = multi_do(&data->easy_conn, &dophase_done);
1639
1640         /* When multi_do() returns failure, data->easy_conn might be NULL! */
1641
1642         if(!result) {
1643           if(!dophase_done) {
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;
1652                 break;
1653               }
1654             }
1655             /* DO was not completed in one function call, we must continue
1656                DOING... */
1657             multistate(data, CURLM_STATE_DOING);
1658             rc = CURLM_OK;
1659           }
1660
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);
1666             rc = CURLM_OK;
1667           }
1668           else {
1669             /* we're done with the DO, now DO_DONE */
1670             multistate(data, CURLM_STATE_DO_DONE);
1671             rc = CURLM_CALL_MULTI_PERFORM;
1672           }
1673         }
1674         else if((CURLE_SEND_ERROR == result) &&
1675                 data->easy_conn->bits.reuse) {
1676           /*
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.
1680            */
1681           char *newurl = NULL;
1682           followtype follow = FOLLOW_NONE;
1683           CURLcode drc;
1684           bool retry = FALSE;
1685
1686           drc = Curl_retry_request(data->easy_conn, &newurl);
1687           if(drc) {
1688             /* a failure here pretty much implies an out of memory */
1689             result = drc;
1690             stream_error = TRUE;
1691           }
1692           else
1693             retry = (newurl)?TRUE:FALSE;
1694
1695           Curl_posttransfer(data);
1696           drc = multi_done(&data->easy_conn, result, FALSE);
1697
1698           /* When set to retry the connection, we must to go back to
1699            * the CONNECT state */
1700           if(retry) {
1701             if(!drc || (drc == CURLE_SEND_ERROR)) {
1702               follow = FOLLOW_RETRY;
1703               drc = Curl_follow(data, newurl, follow);
1704               if(!drc) {
1705                 multistate(data, CURLM_STATE_CONNECT);
1706                 rc = CURLM_CALL_MULTI_PERFORM;
1707                 result = CURLE_OK;
1708               }
1709               else {
1710                 /* Follow failed */
1711                 result = drc;
1712               }
1713             }
1714             else {
1715               /* done didn't return OK or SEND_ERROR */
1716               result = drc;
1717             }
1718           }
1719           else {
1720             /* Have error handler disconnect conn if we can't retry */
1721             stream_error = TRUE;
1722           }
1723           free(newurl);
1724         }
1725         else {
1726           /* failure detected */
1727           Curl_posttransfer(data);
1728           if(data->easy_conn)
1729             multi_done(&data->easy_conn, result, FALSE);
1730           stream_error = TRUE;
1731         }
1732       }
1733       break;
1734
1735     case CURLM_STATE_DOING:
1736       /* we continue DOING until the DO phase is complete */
1737       result = Curl_protocol_doing(data->easy_conn,
1738                                    &dophase_done);
1739       if(!result) {
1740         if(dophase_done) {
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 */
1747       }
1748       else {
1749         /* failure detected */
1750         Curl_posttransfer(data);
1751         multi_done(&data->easy_conn, result, FALSE);
1752         stream_error = TRUE;
1753       }
1754       break;
1755
1756     case CURLM_STATE_DO_MORE:
1757       /*
1758        * When we are connected, DO MORE and then go DO_DONE
1759        */
1760       result = multi_do_more(data->easy_conn, &control);
1761
1762       /* No need to remove this handle from the send pipeline here since that
1763          is done in multi_done() */
1764       if(!result) {
1765         if(control) {
1766           /* if positive, advance to DO_DONE
1767              if negative, go back to DOING */
1768           multistate(data, control == 1?
1769                      CURLM_STATE_DO_DONE:
1770                      CURLM_STATE_DOING);
1771           rc = CURLM_CALL_MULTI_PERFORM;
1772         }
1773         else
1774           /* stay in DO_MORE */
1775           rc = CURLM_OK;
1776       }
1777       else {
1778         /* failure detected */
1779         Curl_posttransfer(data);
1780         multi_done(&data->easy_conn, result, FALSE);
1781         stream_error = TRUE;
1782       }
1783       break;
1784
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);
1790
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);
1796       else
1797       {
1798         if(data->state.wildcardmatch &&
1799            ((data->easy_conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
1800            data->wildcard.state = CURLWC_DONE;
1801         }
1802         multistate(data, CURLM_STATE_DONE);
1803       }
1804       rc = CURLM_CALL_MULTI_PERFORM;
1805       break;
1806
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;
1813       }
1814       break;
1815
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;
1820       else
1821         result = Curl_speedcheck(data, now);
1822
1823       if(!result) {
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,
1830                                 now);
1831
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,
1838                                 now);
1839
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);
1844         else
1845           Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
1846       }
1847       break;
1848
1849     case CURLM_STATE_PERFORM:
1850     {
1851       char *newurl = NULL;
1852       bool retry = FALSE;
1853       bool comeback = FALSE;
1854
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,
1862                                                  now);
1863
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,
1871                                                  now);
1872
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);
1877         else
1878           Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
1879         break;
1880       }
1881
1882       /* read/write data if it is ready to do so */
1883       result = Curl_readwrite(data->easy_conn, data, &done, &comeback);
1884
1885       k = &data->req;
1886
1887       if(!(k->keepon & KEEP_RECV))
1888         /* We're done receiving */
1889         Curl_pipeline_leave_read(data->easy_conn);
1890
1891       if(!(k->keepon & KEEP_SEND))
1892         /* We're done sending */
1893         Curl_pipeline_leave_write(data->easy_conn);
1894
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.
1899          */
1900         CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
1901         if(!ret)
1902           retry = (newurl)?TRUE:FALSE;
1903
1904         if(retry) {
1905           /* if we are to retry, set the result to OK and consider the
1906              request as done */
1907           result = CURLE_OK;
1908           done = TRUE;
1909         }
1910       }
1911
1912       if(result) {
1913         /*
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.
1919          */
1920
1921         if(!(data->easy_conn->handler->flags & PROTOPT_DUAL) &&
1922            result != CURLE_HTTP2_STREAM)
1923           streamclose(data->easy_conn, "Transfer returned error");
1924
1925         Curl_posttransfer(data);
1926         multi_done(&data->easy_conn, result, TRUE);
1927       }
1928       else if(done) {
1929         followtype follow = FOLLOW_NONE;
1930
1931         /* call this even if the readwrite function returned error */
1932         Curl_posttransfer(data);
1933
1934         /* we're no longer receiving */
1935         Curl_removeHandleFromPipeline(data, &data->easy_conn->recv_pipe);
1936
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);
1940
1941         /* Check if we can move pending requests to send pipe */
1942         Curl_multi_process_pending_handles(multi);
1943
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) {
1947           if(!retry) {
1948             /* if the URL is a follow-location and not just a retried request
1949                then figure out the URL here */
1950             free(newurl);
1951             newurl = data->req.newurl;
1952             data->req.newurl = NULL;
1953             follow = FOLLOW_REDIR;
1954           }
1955           else
1956             follow = FOLLOW_RETRY;
1957           result = multi_done(&data->easy_conn, CURLE_OK, FALSE);
1958           if(!result) {
1959             result = Curl_follow(data, newurl, follow);
1960             if(!result) {
1961               multistate(data, CURLM_STATE_CONNECT);
1962               rc = CURLM_CALL_MULTI_PERFORM;
1963             }
1964           }
1965         }
1966         else {
1967           /* after the transfer is done, go DONE */
1968
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) {
1972             free(newurl);
1973             newurl = data->req.location;
1974             data->req.location = NULL;
1975             result = Curl_follow(data, newurl, FOLLOW_FAKE);
1976             if(result)
1977               stream_error = TRUE;
1978           }
1979
1980           multistate(data, CURLM_STATE_DONE);
1981           rc = CURLM_CALL_MULTI_PERFORM;
1982         }
1983       }
1984       else if(comeback)
1985         rc = CURLM_CALL_MULTI_PERFORM;
1986
1987       free(newurl);
1988       break;
1989     }
1990
1991     case CURLM_STATE_DONE:
1992       /* this state is highly transient, so run another loop after this */
1993       rc = CURLM_CALL_MULTI_PERFORM;
1994
1995       if(data->easy_conn) {
1996         CURLcode res;
1997
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);
2002
2003         /* post-transfer command */
2004         res = multi_done(&data->easy_conn, result, FALSE);
2005
2006         /* allow a previously set error code take precedence */
2007         if(!result)
2008           result = res;
2009
2010         /*
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
2015          */
2016         if(data->easy_conn)
2017           data->easy_conn = NULL;
2018       }
2019
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);
2025           break;
2026         }
2027       }
2028
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);
2032       break;
2033
2034     case CURLM_STATE_COMPLETED:
2035       /* this is a completed transfer, it is likely to still be connected */
2036
2037       /* This node should be delinked from the list now and we should post
2038          an information message that we are complete. */
2039
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;
2043
2044       Curl_expire_clear(data); /* stop all timers */
2045       break;
2046
2047     case CURLM_STATE_MSGSENT:
2048       data->result = result;
2049       return CURLM_OK; /* do nothing */
2050
2051     default:
2052       return CURLM_INTERNAL_ERROR;
2053     }
2054     statemachine_end:
2055
2056     if(data->mstate < CURLM_STATE_COMPLETED) {
2057       if(result) {
2058         /*
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.
2061          */
2062
2063         /* NOTE: no attempt to disconnect connections must be made
2064            in the case blocks above - cleanup happens only here */
2065
2066         data->state.pipe_broke = FALSE;
2067
2068         /* Check if we can move pending requests to send pipe */
2069         Curl_multi_process_pending_handles(multi);
2070
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);
2077
2078           if(stream_error) {
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);
2083
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;
2088           }
2089         }
2090         else if(data->mstate == CURLM_STATE_CONNECT) {
2091           /* Curl_connect() failed */
2092           (void)Curl_posttransfer(data);
2093         }
2094
2095         multistate(data, CURLM_STATE_COMPLETED);
2096       }
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
2100            connection */
2101         result = CURLE_ABORTED_BY_CALLBACK;
2102         streamclose(data->easy_conn, "Aborted by callback");
2103
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;
2108       }
2109     }
2110
2111     if(CURLM_STATE_COMPLETED == data->mstate) {
2112       /* now fill in the Curl_message with this info */
2113       msg = &data->msg;
2114
2115       msg->extmsg.msg = CURLMSG_DONE;
2116       msg->extmsg.easy_handle = data;
2117       msg->extmsg.data.result = result;
2118
2119       rc = multi_addmsg(multi, msg);
2120
2121       multistate(data, CURLM_STATE_MSGSENT);
2122     }
2123   } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
2124
2125   data->result = result;
2126
2127
2128   return rc;
2129 }
2130
2131
2132 CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
2133 {
2134   struct Curl_easy *data;
2135   CURLMcode returncode = CURLM_OK;
2136   struct Curl_tree *t;
2137   struct curltime now = Curl_now();
2138
2139   if(!GOOD_MULTI_HANDLE(multi))
2140     return CURLM_BAD_HANDLE;
2141
2142   if(multi->in_callback)
2143     return CURLM_RECURSIVE_API_CALL;
2144
2145   data = multi->easyp;
2146   while(data) {
2147     CURLMcode result;
2148     SIGPIPE_VARIABLE(pipe_st);
2149
2150     sigpipe_ignore(data, &pipe_st);
2151     result = multi_runsingle(multi, now, data);
2152     sigpipe_restore(&pipe_st);
2153
2154     if(result)
2155       returncode = result;
2156
2157     data = data->next; /* operate on next handle */
2158   }
2159
2160   /*
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.
2164    *
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
2168    * been handled!
2169    */
2170   do {
2171     multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2172     if(t)
2173       /* the removed may have another timeout in queue */
2174       (void)add_next_timeout(now, multi, t->payload);
2175
2176   } while(t);
2177
2178   *running_handles = multi->num_alive;
2179
2180   if(CURLM_OK >= returncode)
2181     update_timer(multi);
2182
2183   return returncode;
2184 }
2185
2186 CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
2187 {
2188   struct Curl_easy *data;
2189   struct Curl_easy *nextdata;
2190
2191   if(GOOD_MULTI_HANDLE(multi)) {
2192     if(multi->in_callback)
2193       return CURLM_RECURSIVE_API_CALL;
2194
2195     multi->type = 0; /* not good anymore */
2196
2197     /* Firsrt remove all remaining easy handles */
2198     data = multi->easyp;
2199     while(data) {
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;
2209       }
2210
2211       /* Clear the pointer to the connection cache */
2212       data->state.conn_cache = NULL;
2213       data->multi = NULL; /* clear the association */
2214
2215       data = nextdata;
2216     }
2217
2218     /* Close all the connections in the connection cache */
2219     Curl_conncache_close_all_connections(&multi->conn_cache);
2220
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);
2225
2226     Curl_hash_destroy(&multi->hostcache);
2227
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);
2231
2232     free(multi);
2233
2234     return CURLM_OK;
2235   }
2236   return CURLM_BAD_HANDLE;
2237 }
2238
2239 /*
2240  * curl_multi_info_read()
2241  *
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).
2247  */
2248
2249 CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
2250 {
2251   struct Curl_message *msg;
2252
2253   *msgs_in_queue = 0; /* default to none */
2254
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;
2260
2261     /* extract the head of the list to return */
2262     e = multi->msglist.head;
2263
2264     msg = e->ptr;
2265
2266     /* remove the extracted entry */
2267     Curl_llist_remove(&multi->msglist, e, NULL);
2268
2269     *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
2270
2271     return &msg->extmsg;
2272   }
2273   return NULL;
2274 }
2275
2276 /*
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.
2280  */
2281 static void singlesocket(struct Curl_multi *multi,
2282                          struct Curl_easy *data)
2283 {
2284   curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
2285   int i;
2286   struct Curl_sh_entry *entry;
2287   curl_socket_t s;
2288   int num;
2289   unsigned int curraction;
2290
2291   for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
2292     socks[i] = CURL_SOCKET_BAD;
2293
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);
2297
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 */
2301
2302   /* walk over the sockets we got right now */
2303   for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
2304         (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
2305       i++) {
2306     int action = CURL_POLL_NONE;
2307
2308     s = socks[i];
2309
2310     /* get it from the hash */
2311     entry = sh_getentry(&multi->sockhash, s);
2312
2313     if(curraction & GETSOCK_READSOCK(i))
2314       action |= CURL_POLL_IN;
2315     if(curraction & GETSOCK_WRITESOCK(i))
2316       action |= CURL_POLL_OUT;
2317
2318     if(entry) {
2319       /* yeps, already present so check if it has the same action set */
2320       if(entry->action == action)
2321         /* same, continue */
2322         continue;
2323     }
2324     else {
2325       /* this is a socket we didn't have before, add it! */
2326       entry = sh_addentry(&multi->sockhash, s, data);
2327       if(!entry)
2328         /* fatal */
2329         return;
2330     }
2331
2332     /* we know (entry != NULL) at this point, see the logic above */
2333     if(multi->socket_cb)
2334       multi->socket_cb(data,
2335                        s,
2336                        action,
2337                        multi->socket_userp,
2338                        entry->socketp);
2339
2340     entry->action = action; /* store the current action state */
2341   }
2342
2343   num = i; /* number of sockets */
2344
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++) {
2348     int j;
2349     s = data->sockets[i];
2350     for(j = 0; j<num; j++) {
2351       if(s == socks[j]) {
2352         /* this is still supervised */
2353         s = CURL_SOCKET_BAD;
2354         break;
2355       }
2356     }
2357
2358     entry = sh_getentry(&multi->sockhash, s);
2359     if(entry) {
2360       /* this socket has been removed. Tell the app to remove it */
2361       bool remove_sock_from_hash = TRUE;
2362
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
2365          removed. */
2366       struct connectdata *easy_conn = data->easy_conn;
2367       if(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;
2371
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
2374              isn't already) */
2375           if(entry->easy == data) {
2376             if(Curl_recvpipe_head(data, easy_conn))
2377               entry->easy = easy_conn->recv_pipe.head->next->ptr;
2378             else
2379               entry->easy = easy_conn->recv_pipe.head->ptr;
2380           }
2381         }
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;
2385
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
2388              isn't already) */
2389           if(entry->easy == data) {
2390             if(Curl_sendpipe_head(data, easy_conn))
2391               entry->easy = easy_conn->send_pipe.head->next->ptr;
2392             else
2393               entry->easy = easy_conn->send_pipe.head->ptr;
2394           }
2395         }
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
2399            action. */
2400       }
2401
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,
2406                            s,
2407                            CURL_POLL_REMOVE,
2408                            multi->socket_userp,
2409                            entry->socketp);
2410         sh_delentry(&multi->sockhash, s);
2411       }
2412     } /* if sockhash entry existed */
2413   } /* for loop over numsocks */
2414
2415   memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
2416   data->numsocks = num;
2417 }
2418
2419 /*
2420  * Curl_multi_closed()
2421  *
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.
2427  */
2428
2429 void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
2430 {
2431   struct Curl_multi *multi = conn->data->multi;
2432   if(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);
2436
2437     if(entry) {
2438       if(multi->socket_cb)
2439         multi->socket_cb(conn->data, s, CURL_POLL_REMOVE,
2440                          multi->socket_userp,
2441                          entry->socketp);
2442
2443       /* now remove it from the socket hash */
2444       sh_delentry(&multi->sockhash, s);
2445     }
2446   }
2447 }
2448
2449 /*
2450  * add_next_timeout()
2451  *
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.
2457  *
2458  * The splay tree only has each sessionhandle as a single node and the nearest
2459  * timeout is used to sort it on.
2460  */
2461 static CURLMcode add_next_timeout(struct curltime now,
2462                                   struct Curl_multi *multi,
2463                                   struct Curl_easy *d)
2464 {
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;
2469
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
2472      timeout in *tv */
2473   for(e = list->head; e;) {
2474     struct curl_llist_element *n = e->next;
2475     timediff_t diff;
2476     node = (struct time_node *)e->ptr;
2477     diff = Curl_timediff(node->time, now);
2478     if(diff <= 0)
2479       /* remove outdated entry */
2480       Curl_llist_remove(list, e, NULL);
2481     else
2482       /* the list is sorted so get out on the first mismatch */
2483       break;
2484     e = n;
2485   }
2486   e = list->head;
2487   if(!e) {
2488     /* clear the expire times within the handles that we remove from the
2489        splay tree */
2490     tv->tv_sec = 0;
2491     tv->tv_usec = 0;
2492   }
2493   else {
2494     /* copy the first entry to 'tv' */
2495     memcpy(tv, &node->time, sizeof(*tv));
2496
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);
2501   }
2502   return CURLM_OK;
2503 }
2504
2505 static CURLMcode multi_socket(struct Curl_multi *multi,
2506                               bool checkall,
2507                               curl_socket_t s,
2508                               int ev_bitmask,
2509                               int *running_handles)
2510 {
2511   CURLMcode result = CURLM_OK;
2512   struct Curl_easy *data = NULL;
2513   struct Curl_tree *t;
2514   struct curltime now = Curl_now();
2515
2516   if(checkall) {
2517     /* *perform() deals with running_handles on its own */
2518     result = curl_multi_perform(multi, running_handles);
2519
2520     /* walk through each easy handle and do the socket state change magic
2521        and callbacks */
2522     if(result != CURLM_BAD_HANDLE) {
2523       data = multi->easyp;
2524       while(data) {
2525         singlesocket(multi, data);
2526         data = data->next;
2527       }
2528     }
2529
2530     /* or should we fall-through and do the timer-based stuff? */
2531     return result;
2532   }
2533   if(s != CURL_SOCKET_TIMEOUT) {
2534
2535     struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
2536
2537     if(!entry)
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. */
2543       ;
2544     else {
2545       SIGPIPE_VARIABLE(pipe_st);
2546
2547       data = entry->easy;
2548
2549       if(data->magic != CURLEASY_MAGIC_NUMBER)
2550         /* bad bad bad bad bad bad bad */
2551         return CURLM_INTERNAL_ERROR;
2552
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;
2563       }
2564
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;
2569
2570       sigpipe_ignore(data, &pipe_st);
2571       result = multi_runsingle(multi, now, data);
2572       sigpipe_restore(&pipe_st);
2573
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;
2578
2579       if(CURLM_OK >= result)
2580         /* get the socket(s) and check if the state has been changed since
2581            last */
2582         singlesocket(multi, data);
2583
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. */
2587
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 */
2592     }
2593   }
2594   else {
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));
2600   }
2601
2602   /*
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.
2606    */
2607   do {
2608     /* the first loop lap 'data' can be NULL */
2609     if(data) {
2610       SIGPIPE_VARIABLE(pipe_st);
2611
2612       sigpipe_ignore(data, &pipe_st);
2613       result = multi_runsingle(multi, now, data);
2614       sigpipe_restore(&pipe_st);
2615
2616       if(CURLM_OK >= result)
2617         /* get the socket(s) and check if the state has been changed since
2618            last */
2619         singlesocket(multi, data);
2620     }
2621
2622     /* Check if there's one (more) expired timer to deal with! This function
2623        extracts a matching node if there is one */
2624
2625     multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2626     if(t) {
2627       data = t->payload; /* assign this for next loop */
2628       (void)add_next_timeout(now, multi, t->payload);
2629     }
2630
2631   } while(t);
2632
2633   *running_handles = multi->num_alive;
2634   return result;
2635 }
2636
2637 #undef curl_multi_setopt
2638 CURLMcode curl_multi_setopt(struct Curl_multi *multi,
2639                             CURLMoption option, ...)
2640 {
2641   CURLMcode res = CURLM_OK;
2642   va_list param;
2643
2644   if(!GOOD_MULTI_HANDLE(multi))
2645     return CURLM_BAD_HANDLE;
2646
2647   if(multi->in_callback)
2648     return CURLM_RECURSIVE_API_CALL;
2649
2650   va_start(param, option);
2651
2652   switch(option) {
2653   case CURLMOPT_SOCKETFUNCTION:
2654     multi->socket_cb = va_arg(param, curl_socket_callback);
2655     break;
2656   case CURLMOPT_SOCKETDATA:
2657     multi->socket_userp = va_arg(param, void *);
2658     break;
2659   case CURLMOPT_PUSHFUNCTION:
2660     multi->push_cb = va_arg(param, curl_push_callback);
2661     break;
2662   case CURLMOPT_PUSHDATA:
2663     multi->push_userp = va_arg(param, void *);
2664     break;
2665   case CURLMOPT_PIPELINING:
2666     multi->pipelining = va_arg(param, long);
2667     break;
2668   case CURLMOPT_TIMERFUNCTION:
2669     multi->timer_cb = va_arg(param, curl_multi_timer_callback);
2670     break;
2671   case CURLMOPT_TIMERDATA:
2672     multi->timer_userp = va_arg(param, void *);
2673     break;
2674   case CURLMOPT_MAXCONNECTS:
2675     multi->maxconnects = va_arg(param, long);
2676     break;
2677   case CURLMOPT_MAX_HOST_CONNECTIONS:
2678     multi->max_host_connections = va_arg(param, long);
2679     break;
2680   case CURLMOPT_MAX_PIPELINE_LENGTH:
2681     multi->max_pipeline_length = va_arg(param, long);
2682     break;
2683   case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
2684     multi->content_length_penalty_size = va_arg(param, long);
2685     break;
2686   case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
2687     multi->chunk_length_penalty_size = va_arg(param, long);
2688     break;
2689   case CURLMOPT_PIPELINING_SITE_BL:
2690     res = Curl_pipeline_set_site_blacklist(va_arg(param, char **),
2691                                            &multi->pipelining_site_bl);
2692     break;
2693   case CURLMOPT_PIPELINING_SERVER_BL:
2694     res = Curl_pipeline_set_server_blacklist(va_arg(param, char **),
2695                                              &multi->pipelining_server_bl);
2696     break;
2697   case CURLMOPT_MAX_TOTAL_CONNECTIONS:
2698     multi->max_total_connections = va_arg(param, long);
2699     break;
2700   default:
2701     res = CURLM_UNKNOWN_OPTION;
2702     break;
2703   }
2704   va_end(param);
2705   return res;
2706 }
2707
2708 /* we define curl_multi_socket() in the public multi.h header */
2709 #undef curl_multi_socket
2710
2711 CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
2712                             int *running_handles)
2713 {
2714   CURLMcode result;
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);
2720   return result;
2721 }
2722
2723 CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
2724                                    int ev_bitmask, int *running_handles)
2725 {
2726   CURLMcode result;
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);
2732   return result;
2733 }
2734
2735 CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
2736
2737 {
2738   CURLMcode result;
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);
2744   return result;
2745 }
2746
2747 static CURLMcode multi_timeout(struct Curl_multi *multi,
2748                                long *timeout_ms)
2749 {
2750   static struct curltime tv_zero = {0, 0};
2751
2752   if(multi->timetree) {
2753     /* we have a tree of expire times */
2754     struct curltime now = Curl_now();
2755
2756     /* splay the lowest to the bottom */
2757     multi->timetree = Curl_splay(tv_zero, multi->timetree);
2758
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);
2762       if(diff <= 0)
2763         /*
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.
2769          */
2770         *timeout_ms = 1;
2771       else
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;
2775     }
2776     else
2777       /* 0 means immediately */
2778       *timeout_ms = 0;
2779   }
2780   else
2781     *timeout_ms = -1;
2782
2783   return CURLM_OK;
2784 }
2785
2786 CURLMcode curl_multi_timeout(struct Curl_multi *multi,
2787                              long *timeout_ms)
2788 {
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;
2792
2793   if(multi->in_callback)
2794     return CURLM_RECURSIVE_API_CALL;
2795
2796   return multi_timeout(multi, timeout_ms);
2797 }
2798
2799 /*
2800  * Tell the application it should update its timers, if it subscribes to the
2801  * update timer callback.
2802  */
2803 static int update_timer(struct Curl_multi *multi)
2804 {
2805   long timeout_ms;
2806
2807   if(!multi->timer_cb)
2808     return 0;
2809   if(multi_timeout(multi, &timeout_ms)) {
2810     return -1;
2811   }
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
2817          disable it */
2818       return multi->timer_cb(multi, -1, multi->timer_userp);
2819     }
2820     return 0;
2821   }
2822
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)
2828     return 0;
2829
2830   multi->timer_lastcall = multi->timetree->key;
2831
2832   return multi->timer_cb(multi, timeout_ms, multi->timer_userp);
2833 }
2834
2835 /*
2836  * multi_deltimeout()
2837  *
2838  * Remove a given timestamp from the list of timeouts.
2839  */
2840 static void
2841 multi_deltimeout(struct Curl_easy *data, expire_id eid)
2842 {
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;
2848     if(n->eid == eid) {
2849       Curl_llist_remove(timeoutlist, e, NULL);
2850       return;
2851     }
2852   }
2853 }
2854
2855 /*
2856  * multi_addtimeout()
2857  *
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.
2860  *
2861  */
2862 static CURLMcode
2863 multi_addtimeout(struct Curl_easy *data,
2864                  struct curltime *stamp,
2865                  expire_id eid)
2866 {
2867   struct curl_llist_element *e;
2868   struct time_node *node;
2869   struct curl_llist_element *prev = NULL;
2870   size_t n;
2871   struct curl_llist *timeoutlist = &data->state.timeoutlist;
2872
2873   node = &data->state.expires[eid];
2874
2875   /* copy the timestamp and id */
2876   memcpy(&node->time, stamp, sizeof(*stamp));
2877   node->eid = eid; /* also marks it as in use */
2878
2879   n = Curl_llist_count(timeoutlist);
2880   if(n) {
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);
2885       if(diff > 0)
2886         break;
2887       prev = e;
2888     }
2889
2890   }
2891   /* else
2892      this is the first timeout on the list */
2893
2894   Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
2895   return CURLM_OK;
2896 }
2897
2898 /*
2899  * Curl_expire()
2900  *
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()
2903  *
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.
2906  *
2907  * Expire replaces a former timeout using the same id if already set.
2908  */
2909 void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id)
2910 {
2911   struct Curl_multi *multi = data->multi;
2912   struct curltime *nowp = &data->state.expiretime;
2913   int rc;
2914   struct curltime set;
2915
2916   /* this is only interesting while there is still an associated multi struct
2917      remaining! */
2918   if(!multi)
2919     return;
2920
2921   DEBUGASSERT(id < EXPIRE_LAST);
2922
2923   set = Curl_now();
2924   set.tv_sec += milli/1000;
2925   set.tv_usec += (unsigned int)(milli%1000)*1000;
2926
2927   if(set.tv_usec >= 1000000) {
2928     set.tv_sec++;
2929     set.tv_usec -= 1000000;
2930   }
2931
2932   /* Remove any timer with the same id just in case. */
2933   multi_deltimeout(data, id);
2934
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);
2938
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
2942        is. */
2943     timediff_t diff = Curl_timediff(set, *nowp);
2944
2945     if(diff > 0) {
2946       /* The current splay tree entry is sooner than this new expiry time.
2947          We don't need to update our splay tree entry. */
2948       return;
2949     }
2950
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,
2955                                 &multi->timetree);
2956     if(rc)
2957       infof(data, "Internal error removing splay node = %d\n", rc);
2958   }
2959
2960   /* Indicate that we are in the splay tree and insert the new timer expiry
2961      value since it is our local minimum. */
2962   *nowp = set;
2963   data->state.timenode.payload = data;
2964   multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
2965                                      &data->state.timenode);
2966 }
2967
2968 /*
2969  * Curl_expire_done()
2970  *
2971  * Removes the expire timer. Marks it as done.
2972  *
2973  */
2974 void Curl_expire_done(struct Curl_easy *data, expire_id id)
2975 {
2976   /* remove the timer, if there */
2977   multi_deltimeout(data, id);
2978 }
2979
2980 /*
2981  * Curl_expire_clear()
2982  *
2983  * Clear ALL timeout values for this handle.
2984  */
2985 void Curl_expire_clear(struct Curl_easy *data)
2986 {
2987   struct Curl_multi *multi = data->multi;
2988   struct curltime *nowp = &data->state.expiretime;
2989   int rc;
2990
2991   /* this is only interesting while there is still an associated multi struct
2992      remaining! */
2993   if(!multi)
2994     return;
2995
2996   if(nowp->tv_sec || nowp->tv_usec) {
2997     /* Since this is an cleared time, we must remove the previous entry from
2998        the splay tree */
2999     struct curl_llist *list = &data->state.timeoutlist;
3000
3001     rc = Curl_splayremovebyaddr(multi->timetree,
3002                                 &data->state.timenode,
3003                                 &multi->timetree);
3004     if(rc)
3005       infof(data, "Internal error clearing splay node = %d\n", rc);
3006
3007     /* flush the timeout list too */
3008     while(list->size > 0) {
3009       Curl_llist_remove(list, list->tail, NULL);
3010     }
3011
3012 #ifdef DEBUGBUILD
3013     infof(data, "Expire cleared\n");
3014 #endif
3015     nowp->tv_sec = 0;
3016     nowp->tv_usec = 0;
3017   }
3018 }
3019
3020
3021
3022
3023 CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
3024                             void *hashp)
3025 {
3026   struct Curl_sh_entry *there = NULL;
3027
3028   if(multi->in_callback)
3029     return CURLM_RECURSIVE_API_CALL;
3030
3031   there = sh_getentry(&multi->sockhash, s);
3032
3033   if(!there)
3034     return CURLM_BAD_SOCKET;
3035
3036   there->socketp = hashp;
3037
3038   return CURLM_OK;
3039 }
3040
3041 size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
3042 {
3043   return multi ? multi->max_host_connections : 0;
3044 }
3045
3046 size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
3047 {
3048   return multi ? multi->max_total_connections : 0;
3049 }
3050
3051 curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi)
3052 {
3053   return multi ? multi->content_length_penalty_size : 0;
3054 }
3055
3056 curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi)
3057 {
3058   return multi ? multi->chunk_length_penalty_size : 0;
3059 }
3060
3061 struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi)
3062 {
3063   return &multi->pipelining_site_bl;
3064 }
3065
3066 struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi)
3067 {
3068   return &multi->pipelining_server_bl;
3069 }
3070
3071 void Curl_multi_process_pending_handles(struct Curl_multi *multi)
3072 {
3073   struct curl_llist_element *e = multi->pending.head;
3074
3075   while(e) {
3076     struct Curl_easy *data = e->ptr;
3077     struct curl_llist_element *next = e->next;
3078
3079     if(data->mstate == CURLM_STATE_CONNECT_PEND) {
3080       multistate(data, CURLM_STATE_CONNECT);
3081
3082       /* Remove this node from the list */
3083       Curl_llist_remove(&multi->pending, e, NULL);
3084
3085       /* Make sure that the handle will be processed soonish. */
3086       Curl_expire(data, 0, EXPIRE_RUN_NOW);
3087     }
3088
3089     e = next; /* operate on next handle */
3090   }
3091 }
3092
3093 void Curl_set_in_callback(struct Curl_easy *easy, bool value)
3094 {
3095   if(easy->multi_easy)
3096     easy->multi_easy->in_callback = value;
3097   else if(easy->multi)
3098       easy->multi->in_callback = value;
3099 }
3100
3101 bool Curl_is_in_callback(struct Curl_easy *easy)
3102 {
3103   return ((easy->multi && easy->multi->in_callback) ||
3104           (easy->multi_easy && easy->multi_easy->in_callback));
3105 }
3106
3107 #ifdef DEBUGBUILD
3108 void Curl_multi_dump(struct Curl_multi *multi)
3109 {
3110   struct Curl_easy *data;
3111   int i;
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",
3118               (void *)data,
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);
3123
3124         fprintf(stderr, "%d ", (int)s);
3125         if(!entry) {
3126           fprintf(stderr, "INTERNAL CONFUSION\n");
3127           continue;
3128         }
3129         fprintf(stderr, "[%s %s] ",
3130                 entry->action&CURL_POLL_IN?"RECVING":"",
3131                 entry->action&CURL_POLL_OUT?"SENDING":"");
3132       }
3133       if(data->numsocks)
3134         fprintf(stderr, "\n");
3135     }
3136   }
3137 }
3138 #endif