Coverage Report

Created: 2025-10-10 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PROJ/curl/lib/multi.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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.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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
25
#include "curl_setup.h"
26
27
#include <curl/curl.h>
28
29
#include "urldata.h"
30
#include "transfer.h"
31
#include "url.h"
32
#include "cfilters.h"
33
#include "connect.h"
34
#include "progress.h"
35
#include "easyif.h"
36
#include "share.h"
37
#include "psl.h"
38
#include "multiif.h"
39
#include "multi_ev.h"
40
#include "sendf.h"
41
#include "curlx/timeval.h"
42
#include "http.h"
43
#include "select.h"
44
#include "curlx/warnless.h"
45
#include "curlx/wait.h"
46
#include "speedcheck.h"
47
#include "conncache.h"
48
#include "multihandle.h"
49
#include "sigpipe.h"
50
#include "vtls/vtls.h"
51
#include "vtls/vtls_scache.h"
52
#include "http_proxy.h"
53
#include "http2.h"
54
#include "socketpair.h"
55
#include "socks.h"
56
#include "urlapi-int.h"
57
58
/* The last 2 #include files should be in this order */
59
#include "curl_memory.h"
60
#include "memdebug.h"
61
62
/* initial multi->xfers table size for a full multi */
63
0
#define CURL_XFER_TABLE_SIZE    512
64
65
/*
66
  CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
67
  to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
68
  curl handle takes 6K memory, therefore this 3K are not significant.
69
*/
70
#ifndef CURL_SOCKET_HASH_TABLE_SIZE
71
0
#define CURL_SOCKET_HASH_TABLE_SIZE 911
72
#endif
73
74
#ifndef CURL_CONNECTION_HASH_SIZE
75
0
#define CURL_CONNECTION_HASH_SIZE 97
76
#endif
77
78
#ifndef CURL_DNS_HASH_SIZE
79
0
#define CURL_DNS_HASH_SIZE 71
80
#endif
81
82
#ifndef CURL_TLS_SESSION_SIZE
83
0
#define CURL_TLS_SESSION_SIZE 25
84
#endif
85
86
0
#define CURL_MULTI_HANDLE 0x000bab1e
87
88
#ifdef DEBUGBUILD
89
/* On a debug build, we want to fail hard on multi handles that
90
 * are not NULL, but no longer have the MAGIC touch. This gives
91
 * us early warning on things only discovered by valgrind otherwise. */
92
#define GOOD_MULTI_HANDLE(x) \
93
  (((x) && (x)->magic == CURL_MULTI_HANDLE)? TRUE:      \
94
  (DEBUGASSERT(!(x)), FALSE))
95
#else
96
#define GOOD_MULTI_HANDLE(x) \
97
0
  ((x) && (x)->magic == CURL_MULTI_HANDLE)
98
#endif
99
100
static void move_pending_to_connect(struct Curl_multi *multi,
101
                                    struct Curl_easy *data);
102
static CURLMcode add_next_timeout(struct curltime now,
103
                                  struct Curl_multi *multi,
104
                                  struct Curl_easy *d);
105
static CURLMcode multi_timeout(struct Curl_multi *multi,
106
                               struct curltime *expire_time,
107
                               long *timeout_ms);
108
static void process_pending_handles(struct Curl_multi *multi);
109
static void multi_xfer_bufs_free(struct Curl_multi *multi);
110
#ifdef DEBUGBUILD
111
static void multi_xfer_tbl_dump(struct Curl_multi *multi);
112
#endif
113
114
/* function pointer called once when switching TO a state */
115
typedef void (*init_multistate_func)(struct Curl_easy *data);
116
117
/* called in DID state, before PERFORMING state */
118
static void before_perform(struct Curl_easy *data)
119
0
{
120
0
  data->req.chunk = FALSE;
121
0
  Curl_pgrsTime(data, TIMER_PRETRANSFER);
122
0
}
123
124
static void init_completed(struct Curl_easy *data)
125
0
{
126
  /* this is a completed transfer */
127
128
  /* Important: reset the conn pointer so that we do not point to memory
129
     that could be freed anytime */
130
0
  Curl_detach_connection(data);
131
0
  Curl_expire_clear(data); /* stop all timers */
132
0
}
133
134
/* always use this function to change state, to make debugging easier */
135
static void mstate(struct Curl_easy *data, CURLMstate state
136
#ifdef DEBUGBUILD
137
                   , int lineno
138
#endif
139
)
140
0
{
141
0
  CURLMstate oldstate = data->mstate;
142
0
  static const init_multistate_func finit[MSTATE_LAST] = {
143
0
    NULL,              /* INIT */
144
0
    NULL,              /* PENDING */
145
0
    NULL,              /* SETUP */
146
0
    Curl_init_CONNECT, /* CONNECT */
147
0
    NULL,              /* RESOLVING */
148
0
    NULL,              /* CONNECTING */
149
0
    NULL,              /* TUNNELING */
150
0
    NULL,              /* PROTOCONNECT */
151
0
    NULL,              /* PROTOCONNECTING */
152
0
    NULL,              /* DO */
153
0
    NULL,              /* DOING */
154
0
    NULL,              /* DOING_MORE */
155
0
    before_perform,    /* DID */
156
0
    NULL,              /* PERFORMING */
157
0
    NULL,              /* RATELIMITING */
158
0
    NULL,              /* DONE */
159
0
    init_completed,    /* COMPLETED */
160
    NULL               /* MSGSENT */
161
0
  };
162
163
0
  if(oldstate == state)
164
    /* do not bother when the new state is the same as the old state */
165
0
    return;
166
167
#ifdef DEBUGBUILD
168
  CURL_TRC_M(data, "-> [%s] (line %d)", CURL_MSTATE_NAME(state), lineno);
169
#else
170
0
  CURL_TRC_M(data, "-> [%s]", CURL_MSTATE_NAME(state));
171
0
#endif
172
173
0
  data->mstate = state;
174
0
  switch(state) {
175
0
  case MSTATE_DONE:
176
0
    CURLM_NTFY(data, CURLMNOTIFY_EASY_DONE);
177
0
    break;
178
0
  case MSTATE_COMPLETED:
179
    /* we sometimes directly jump to COMPLETED, trigger also a notification
180
     * in that case. */
181
0
    if(oldstate < MSTATE_DONE)
182
0
      CURLM_NTFY(data, CURLMNOTIFY_EASY_DONE);
183
    /* changing to COMPLETED means it is in process and needs to go */
184
0
    DEBUGASSERT(Curl_uint_bset_contains(&data->multi->process, data->mid));
185
0
    Curl_uint_bset_remove(&data->multi->process, data->mid);
186
0
    Curl_uint_bset_remove(&data->multi->pending, data->mid); /* to be sure */
187
188
0
    if(Curl_uint_bset_empty(&data->multi->process)) {
189
      /* free the transfer buffer when we have no more active transfers */
190
0
      multi_xfer_bufs_free(data->multi);
191
0
    }
192
0
    break;
193
0
  default:
194
0
    break;
195
0
  }
196
197
  /* if this state has an init-function, run it */
198
0
  if(finit[state])
199
0
    finit[state](data);
200
0
}
201
202
#ifndef DEBUGBUILD
203
0
#define multistate(x,y) mstate(x,y)
204
#else
205
#define multistate(x,y) mstate(x,y, __LINE__)
206
#endif
207
208
209
/* multi->proto_hash destructor. Should never be called as elements
210
 * MUST be added with their own destructor */
211
static void ph_freeentry(void *p)
212
0
{
213
0
  (void)p;
214
  /* Will always be FALSE. Cannot use a 0 assert here since compilers
215
   * are not in agreement if they then want a NORETURN attribute or
216
   * not. *sigh* */
217
0
  DEBUGASSERT(p == NULL);
218
0
}
219
220
/*
221
 * multi_addmsg()
222
 *
223
 * Called when a transfer is completed. Adds the given msg pointer to
224
 * the list kept in the multi handle.
225
 */
226
static void multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg)
227
0
{
228
0
  if(!Curl_llist_count(&multi->msglist))
229
0
    CURLM_NTFY(multi->admin, CURLMNOTIFY_INFO_READ);
230
0
  Curl_llist_append(&multi->msglist, msg, &msg->list);
231
0
}
232
233
struct Curl_multi *Curl_multi_handle(unsigned int xfer_table_size,
234
                                     size_t ev_hashsize,  /* event hash */
235
                                     size_t chashsize, /* connection hash */
236
                                     size_t dnssize,   /* dns hash */
237
                                     size_t sesssize)  /* TLS session cache */
238
0
{
239
0
  struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
240
241
0
  if(!multi)
242
0
    return NULL;
243
244
0
  multi->magic = CURL_MULTI_HANDLE;
245
246
0
  Curl_dnscache_init(&multi->dnscache, dnssize);
247
0
  Curl_mntfy_init(multi);
248
0
  Curl_multi_ev_init(multi, ev_hashsize);
249
0
  Curl_uint_tbl_init(&multi->xfers, NULL);
250
0
  Curl_uint_bset_init(&multi->process);
251
0
  Curl_uint_bset_init(&multi->dirty);
252
0
  Curl_uint_bset_init(&multi->pending);
253
0
  Curl_uint_bset_init(&multi->msgsent);
254
0
  Curl_hash_init(&multi->proto_hash, 23,
255
0
                 Curl_hash_str, curlx_str_key_compare, ph_freeentry);
256
0
  Curl_llist_init(&multi->msglist, NULL);
257
258
0
  multi->multiplexing = TRUE;
259
0
  multi->max_concurrent_streams = 100;
260
0
  multi->last_timeout_ms = -1;
261
262
0
  if(Curl_mntfy_resize(multi) ||
263
0
     Curl_uint_bset_resize(&multi->process, xfer_table_size) ||
264
0
     Curl_uint_bset_resize(&multi->pending, xfer_table_size) ||
265
0
     Curl_uint_bset_resize(&multi->dirty, xfer_table_size) ||
266
0
     Curl_uint_bset_resize(&multi->msgsent, xfer_table_size) ||
267
0
     Curl_uint_tbl_resize(&multi->xfers, xfer_table_size))
268
0
    goto error;
269
270
0
  multi->admin = curl_easy_init();
271
0
  if(!multi->admin)
272
0
    goto error;
273
  /* Initialize admin handle to operate inside this multi */
274
0
  multi->admin->multi = multi;
275
0
  multi->admin->state.internal = TRUE;
276
0
  Curl_llist_init(&multi->admin->state.timeoutlist, NULL);
277
#ifdef DEBUGBUILD
278
  if(getenv("CURL_DEBUG"))
279
    multi->admin->set.verbose = TRUE;
280
#endif
281
0
  Curl_uint_tbl_add(&multi->xfers, multi->admin, &multi->admin->mid);
282
283
0
  if(Curl_cshutdn_init(&multi->cshutdn, multi))
284
0
    goto error;
285
286
0
  Curl_cpool_init(&multi->cpool, multi->admin, NULL, chashsize);
287
288
0
#ifdef USE_SSL
289
0
  if(Curl_ssl_scache_create(sesssize, 2, &multi->ssl_scache))
290
0
    goto error;
291
#else
292
  (void)sesssize;
293
#endif
294
295
#ifdef USE_WINSOCK
296
  multi->wsa_event = WSACreateEvent();
297
  if(multi->wsa_event == WSA_INVALID_EVENT)
298
    goto error;
299
#elif defined(ENABLE_WAKEUP)
300
0
  if(wakeup_create(multi->wakeup_pair, TRUE) < 0) {
301
0
    multi->wakeup_pair[0] = CURL_SOCKET_BAD;
302
0
    multi->wakeup_pair[1] = CURL_SOCKET_BAD;
303
0
  }
304
0
#endif
305
306
0
  return multi;
307
308
0
error:
309
310
0
  Curl_multi_ev_cleanup(multi);
311
0
  Curl_hash_destroy(&multi->proto_hash);
312
0
  Curl_dnscache_destroy(&multi->dnscache);
313
0
  Curl_cpool_destroy(&multi->cpool);
314
0
  Curl_cshutdn_destroy(&multi->cshutdn, multi->admin);
315
0
#ifdef USE_SSL
316
0
  Curl_ssl_scache_destroy(multi->ssl_scache);
317
0
#endif
318
0
  if(multi->admin) {
319
0
    multi->admin->multi = NULL;
320
0
    Curl_close(&multi->admin);
321
0
  }
322
0
  Curl_mntfy_cleanup(multi);
323
324
0
  Curl_uint_bset_destroy(&multi->process);
325
0
  Curl_uint_bset_destroy(&multi->dirty);
326
0
  Curl_uint_bset_destroy(&multi->pending);
327
0
  Curl_uint_bset_destroy(&multi->msgsent);
328
0
  Curl_uint_tbl_destroy(&multi->xfers);
329
330
0
  free(multi);
331
0
  return NULL;
332
0
}
333
334
CURLM *curl_multi_init(void)
335
0
{
336
0
  return Curl_multi_handle(CURL_XFER_TABLE_SIZE,
337
0
                           CURL_SOCKET_HASH_TABLE_SIZE,
338
0
                           CURL_CONNECTION_HASH_SIZE,
339
0
                           CURL_DNS_HASH_SIZE,
340
0
                           CURL_TLS_SESSION_SIZE);
341
0
}
342
343
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
344
static void multi_warn_debug(struct Curl_multi *multi, struct Curl_easy *data)
345
{
346
  if(!multi->warned) {
347
    infof(data, "!!! WARNING !!!");
348
    infof(data, "This is a debug build of libcurl, "
349
          "do not use in production.");
350
    multi->warned = TRUE;
351
  }
352
}
353
#else
354
0
#define multi_warn_debug(x,y) Curl_nop_stmt
355
#endif
356
357
358
static CURLMcode multi_xfers_add(struct Curl_multi *multi,
359
                                 struct Curl_easy *data)
360
0
{
361
0
  unsigned int capacity = Curl_uint_tbl_capacity(&multi->xfers);
362
0
  unsigned int new_size = 0;
363
  /* Prepare to make this into a CURLMOPT_MAX_TRANSFERS, because some
364
   * applications may want to prevent a run-away of their memory use. */
365
  /* UINT_MAX is our "invalid" id, do not let the table grow up to that. */
366
0
  const unsigned int max_capacity = UINT_MAX - 1;
367
368
0
  if(capacity < max_capacity) {
369
    /* We want `multi->xfers` to have "sufficient" free rows, so that we do
370
     * have to reuse the `mid` from a just removed easy right away.
371
     * Since uint_tbl and uint_bset are quite memory efficient,
372
     * regard less than 25% free as insufficient.
373
     * (for low capacities, e.g. multi_easy, 4 or less). */
374
0
    unsigned int used = Curl_uint_tbl_count(&multi->xfers);
375
0
    unsigned int unused = capacity - used;
376
0
    unsigned int min_unused = CURLMAX(capacity >> 2, 4);
377
0
    if(unused <= min_unused) {
378
      /* Make sure the uint arithmetic here works on the corner
379
       * cases where we are close to max_capacity or UINT_MAX */
380
0
      if((min_unused >= max_capacity) ||
381
0
         ((max_capacity - min_unused) <= capacity) ||
382
0
         ((UINT_MAX - min_unused - 63) <= capacity)) {
383
0
        new_size = max_capacity; /* can not be larger than this */
384
0
      }
385
0
      else {
386
         /* make it a 64 multiple, since our bitsets frow by that and
387
          * small (easy_multi) grows to at least 64 on first resize. */
388
0
        new_size = (((used + min_unused) + 63) / 64) * 64;
389
0
      }
390
0
    }
391
0
  }
392
393
0
  if(new_size > capacity) {
394
    /* Grow the bitsets first. Should one fail, we do not need
395
     * to downsize the already resized ones. The sets continue
396
     * to work properly when larger than the table, but not
397
     * the other way around. */
398
0
    CURL_TRC_M(data, "increasing xfer table size to %u", new_size);
399
0
    if(Curl_uint_bset_resize(&multi->process, new_size) ||
400
0
       Curl_uint_bset_resize(&multi->dirty, new_size) ||
401
0
       Curl_uint_bset_resize(&multi->pending, new_size) ||
402
0
       Curl_uint_bset_resize(&multi->msgsent, new_size) ||
403
0
       Curl_uint_tbl_resize(&multi->xfers, new_size))
404
0
      return CURLM_OUT_OF_MEMORY;
405
0
  }
406
407
  /* Insert the easy into the table now */
408
0
  if(!Curl_uint_tbl_add(&multi->xfers, data, &data->mid)) {
409
    /* MUST only happen when table is full */
410
0
    DEBUGASSERT(Curl_uint_tbl_capacity(&multi->xfers) <=
411
0
                Curl_uint_tbl_count(&multi->xfers));
412
0
    return CURLM_OUT_OF_MEMORY;
413
0
  }
414
0
  return CURLM_OK;
415
0
}
416
417
418
CURLMcode curl_multi_add_handle(CURLM *m, CURL *d)
419
0
{
420
0
  CURLMcode rc;
421
0
  struct Curl_multi *multi = m;
422
0
  struct Curl_easy *data = d;
423
  /* First, make some basic checks that the CURLM handle is a good handle */
424
0
  if(!GOOD_MULTI_HANDLE(multi))
425
0
    return CURLM_BAD_HANDLE;
426
427
  /* Verify that we got a somewhat good easy handle too */
428
0
  if(!GOOD_EASY_HANDLE(data))
429
0
    return CURLM_BAD_EASY_HANDLE;
430
431
  /* Prevent users from adding same easy handle more than once and prevent
432
     adding to more than one multi stack */
433
0
  if(data->multi)
434
0
    return CURLM_ADDED_ALREADY;
435
436
0
  if(multi->in_callback)
437
0
    return CURLM_RECURSIVE_API_CALL;
438
439
0
  if(multi->dead) {
440
    /* a "dead" handle cannot get added transfers while any existing easy
441
       handles are still alive - but if there are none alive anymore, it is
442
       fine to start over and unmark the "deadness" of this handle.
443
       This means only the admin handle MUST be present. */
444
0
    if((Curl_uint_tbl_count(&multi->xfers) != 1) ||
445
0
       !Curl_uint_tbl_contains(&multi->xfers, 0))
446
0
      return CURLM_ABORTED_BY_CALLBACK;
447
0
    multi->dead = FALSE;
448
0
    Curl_uint_bset_clear(&multi->process);
449
0
    Curl_uint_bset_clear(&multi->dirty);
450
0
    Curl_uint_bset_clear(&multi->pending);
451
0
    Curl_uint_bset_clear(&multi->msgsent);
452
0
  }
453
454
0
  if(data->multi_easy) {
455
    /* if this easy handle was previously used for curl_easy_perform(), there
456
       is a private multi handle here that we can kill */
457
0
    curl_multi_cleanup(data->multi_easy);
458
0
    data->multi_easy = NULL;
459
0
  }
460
461
  /* Insert the easy into the multi->xfers table, assigning it a `mid`. */
462
0
  if(multi_xfers_add(multi, data))
463
0
    return CURLM_OUT_OF_MEMORY;
464
465
  /* Initialize timeout list for this handle */
466
0
  Curl_llist_init(&data->state.timeoutlist, NULL);
467
468
  /*
469
   * No failure allowed in this function beyond this point. No modification of
470
   * easy nor multi handle allowed before this except for potential multi's
471
   * connection pool growing which will not be undone in this function no
472
   * matter what.
473
   */
474
0
  if(data->set.errorbuffer)
475
0
    data->set.errorbuffer[0] = 0;
476
477
0
  data->state.os_errno = 0;
478
479
  /* make the Curl_easy refer back to this multi handle - before Curl_expire()
480
     is called. */
481
0
  data->multi = multi;
482
483
  /* set the easy handle */
484
0
  multistate(data, MSTATE_INIT);
485
486
#ifdef USE_LIBPSL
487
  /* Do the same for PSL. */
488
  if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL)))
489
    data->psl = &data->share->psl;
490
  else
491
    data->psl = &multi->psl;
492
#endif
493
494
  /* add the easy handle to the process set */
495
0
  Curl_uint_bset_add(&multi->process, data->mid);
496
0
  ++multi->xfers_alive;
497
0
  ++multi->xfers_total_ever;
498
499
0
  Curl_cpool_xfer_init(data);
500
0
  multi_warn_debug(multi, data);
501
502
  /* Make sure the new handle will run */
503
0
  Curl_multi_mark_dirty(data);
504
  /* Necessary in event based processing, where dirty handles trigger
505
   * a timeout callback invocation. */
506
0
  rc = Curl_update_timer(multi);
507
0
  if(rc) {
508
0
    data->multi = NULL; /* not anymore */
509
0
    Curl_uint_tbl_remove(&multi->xfers, data->mid);
510
0
    data->mid = UINT_MAX;
511
0
    return rc;
512
0
  }
513
514
  /* The admin handle only ever has default timeouts set. To improve the
515
     state somewhat we clone the timeouts from each added handle so that the
516
     admin handle always has the same timeouts as the most recently added
517
     easy handle. */
518
0
  multi->admin->set.timeout = data->set.timeout;
519
0
  multi->admin->set.server_response_timeout =
520
0
    data->set.server_response_timeout;
521
0
  multi->admin->set.no_signal = data->set.no_signal;
522
523
0
  CURL_TRC_M(data, "added to multi, mid=%u, running=%u, total=%u",
524
0
             data->mid, Curl_multi_xfers_running(multi),
525
0
             Curl_uint_tbl_count(&multi->xfers));
526
0
  return CURLM_OK;
527
0
}
528
529
#if 0
530
/* Debug-function, used like this:
531
 *
532
 * Curl_hash_print(&multi->sockhash, debug_print_sock_hash);
533
 *
534
 * Enable the hash print function first by editing hash.c
535
 */
536
static void debug_print_sock_hash(void *p)
537
{
538
  struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
539
540
  curl_mfprintf(stderr, " [readers %u][writers %u]",
541
                sh->readers, sh->writers);
542
}
543
#endif
544
545
struct multi_done_ctx {
546
  BIT(premature);
547
};
548
549
static void multi_done_locked(struct connectdata *conn,
550
                              struct Curl_easy *data,
551
                              void *userdata)
552
0
{
553
0
  struct multi_done_ctx *mdctx = userdata;
554
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
555
0
  const char *host =
556
0
#ifndef CURL_DISABLE_PROXY
557
0
        conn->bits.socksproxy ?
558
0
        conn->socks_proxy.host.dispname :
559
0
        conn->bits.httpproxy ? conn->http_proxy.host.dispname :
560
0
#endif
561
0
        conn->bits.conn_to_host ? conn->conn_to_host.dispname :
562
0
        conn->host.dispname;
563
0
  int port =
564
0
#ifndef CURL_DISABLE_PROXY
565
0
        conn->bits.httpproxy ? conn->http_proxy.port :
566
0
#endif
567
0
        conn->bits.conn_to_port ? conn->conn_to_port :
568
0
        conn->remote_port;
569
0
#endif
570
571
0
  Curl_detach_connection(data);
572
573
0
  CURL_TRC_M(data, "multi_done_locked, in use=%u",
574
0
             Curl_uint_spbset_count(&conn->xfers_attached));
575
0
  if(CONN_INUSE(conn)) {
576
    /* Stop if still used. */
577
0
    CURL_TRC_M(data, "Connection still in use %u, no more multi_done now!",
578
0
               Curl_uint_spbset_count(&conn->xfers_attached));
579
0
    return;
580
0
  }
581
582
0
  data->state.done = TRUE; /* called just now! */
583
0
  data->state.recent_conn_id = conn->connection_id;
584
585
0
  Curl_resolv_unlink(data, &data->state.dns[0]); /* done with this */
586
0
  Curl_resolv_unlink(data, &data->state.dns[1]);
587
0
  Curl_dnscache_prune(data);
588
589
  /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
590
     forced us to close this connection. This is ignored for requests taking
591
     place in a NTLM/NEGOTIATE authentication handshake
592
593
     if conn->bits.close is TRUE, it means that the connection should be
594
     closed in spite of all our efforts to be nice, due to protocol
595
     restrictions in our or the server's end
596
597
     if premature is TRUE, it means this connection was said to be DONE before
598
     the entire request operation is complete and thus we cannot know in what
599
     state it is for reusing, so we are forced to close it. In a perfect world
600
     we can add code that keep track of if we really must close it here or not,
601
     but currently we have no such detail knowledge.
602
  */
603
604
0
  if((data->set.reuse_forbid
605
0
#ifdef USE_NTLM
606
0
      && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 ||
607
0
           conn->proxy_ntlm_state == NTLMSTATE_TYPE2)
608
0
#endif
609
#ifdef USE_SPNEGO
610
      && !(conn->http_negotiate_state == GSS_AUTHRECV ||
611
           conn->proxy_negotiate_state == GSS_AUTHRECV)
612
#endif
613
0
     ) || conn->bits.close
614
0
       || (mdctx->premature && !Curl_conn_is_multiplex(conn, FIRSTSOCKET))) {
615
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
616
0
    CURL_TRC_M(data, "multi_done, terminating conn #%" FMT_OFF_T " to %s:%d, "
617
0
               "forbid=%d, close=%d, premature=%d, conn_multiplex=%d",
618
0
               conn->connection_id, host, port, data->set.reuse_forbid,
619
0
               conn->bits.close, mdctx->premature,
620
0
               Curl_conn_is_multiplex(conn, FIRSTSOCKET));
621
0
#endif
622
0
    connclose(conn, "disconnecting");
623
0
    Curl_conn_terminate(data, conn, mdctx->premature);
624
0
  }
625
0
  else if(!Curl_conn_get_max_concurrent(data, conn, FIRSTSOCKET)) {
626
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
627
0
    CURL_TRC_M(data, "multi_done, conn #%" FMT_OFF_T " to %s:%d was shutdown"
628
0
               " by server, not reusing", conn->connection_id, host, port);
629
0
#endif
630
0
    connclose(conn, "server shutdown");
631
0
    Curl_conn_terminate(data, conn, mdctx->premature);
632
0
  }
633
0
  else {
634
    /* the connection is no longer in use by any transfer */
635
0
    if(Curl_cpool_conn_now_idle(data, conn)) {
636
      /* connection kept in the cpool */
637
0
      data->state.lastconnect_id = conn->connection_id;
638
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
639
0
      infof(data, "Connection #%" FMT_OFF_T " to host %s:%d left intact",
640
0
            conn->connection_id, host, port);
641
0
#endif
642
0
    }
643
0
    else {
644
      /* connection was removed from the cpool and destroyed. */
645
0
      data->state.lastconnect_id = -1;
646
0
    }
647
0
  }
648
0
}
649
650
static CURLcode multi_done(struct Curl_easy *data,
651
                           CURLcode status,  /* an error if this is called
652
                                                after an error was detected */
653
                           bool premature)
654
0
{
655
0
  CURLcode result;
656
0
  struct connectdata *conn = data->conn;
657
0
  struct multi_done_ctx mdctx;
658
659
0
  memset(&mdctx, 0, sizeof(mdctx));
660
661
0
  CURL_TRC_M(data, "multi_done: status: %d prem: %d done: %d",
662
0
             (int)status, (int)premature, data->state.done);
663
664
0
  if(data->state.done)
665
    /* Stop if multi_done() has already been called */
666
0
    return CURLE_OK;
667
668
  /* Shut down any ongoing async resolver operation. */
669
0
  Curl_async_shutdown(data);
670
671
  /* Cleanup possible redirect junk */
672
0
  Curl_safefree(data->req.newurl);
673
0
  Curl_safefree(data->req.location);
674
675
0
  switch(status) {
676
0
  case CURLE_ABORTED_BY_CALLBACK:
677
0
  case CURLE_READ_ERROR:
678
0
  case CURLE_WRITE_ERROR:
679
    /* When we are aborted due to a callback return code it basically have to
680
       be counted as premature as there is trouble ahead if we do not. We have
681
       many callbacks and protocols work differently, we could potentially do
682
       this more fine-grained in the future. */
683
0
    premature = TRUE;
684
0
    FALLTHROUGH();
685
0
  default:
686
0
    break;
687
0
  }
688
689
  /* this calls the protocol-specific function pointer previously set */
690
0
  if(conn->handler->done && (data->mstate >= MSTATE_PROTOCONNECT))
691
0
    result = conn->handler->done(data, status, premature);
692
0
  else
693
0
    result = status;
694
695
0
  if(CURLE_ABORTED_BY_CALLBACK != result) {
696
    /* avoid this if we already aborted by callback to avoid this calling
697
       another callback */
698
0
    int rc = Curl_pgrsDone(data);
699
0
    if(!result && rc)
700
0
      result = CURLE_ABORTED_BY_CALLBACK;
701
0
  }
702
703
  /* Make sure that transfer client writes are really done now. */
704
0
  result = Curl_1st_err(result, Curl_xfer_write_done(data, premature));
705
706
  /* Inform connection filters that this transfer is done */
707
0
  Curl_conn_ev_data_done(data, premature);
708
709
0
  process_pending_handles(data->multi); /* connection / multiplex */
710
711
0
  if(!result)
712
0
    result = Curl_req_done(&data->req, data, premature);
713
714
  /* Under the potential connection pool's share lock, decide what to
715
   * do with the transfer's connection. */
716
0
  mdctx.premature = premature;
717
0
  Curl_cpool_do_locked(data, data->conn, multi_done_locked, &mdctx);
718
719
  /* flush the netrc cache */
720
0
  Curl_netrc_cleanup(&data->state.netrc);
721
0
  return result;
722
0
}
723
724
static void close_connect_only(struct connectdata *conn,
725
                               struct Curl_easy *data,
726
                               void *userdata)
727
0
{
728
0
  (void)userdata;
729
0
  (void)data;
730
0
  if(conn->connect_only)
731
0
    connclose(conn, "Removing connect-only easy handle");
732
0
}
733
734
CURLMcode curl_multi_remove_handle(CURLM *m, CURL *d)
735
0
{
736
0
  struct Curl_multi *multi = m;
737
0
  struct Curl_easy *data = d;
738
0
  bool premature;
739
0
  struct Curl_llist_node *e;
740
0
  CURLMcode rc;
741
0
  bool removed_timer = FALSE;
742
0
  unsigned int mid;
743
744
  /* First, make some basic checks that the CURLM handle is a good handle */
745
0
  if(!GOOD_MULTI_HANDLE(multi))
746
0
    return CURLM_BAD_HANDLE;
747
748
  /* Verify that we got a somewhat good easy handle too */
749
0
  if(!GOOD_EASY_HANDLE(data))
750
0
    return CURLM_BAD_EASY_HANDLE;
751
752
  /* Prevent users from trying to remove same easy handle more than once */
753
0
  if(!data->multi)
754
0
    return CURLM_OK; /* it is already removed so let's say it is fine! */
755
756
  /* Prevent users from trying to remove an easy handle from the wrong multi */
757
0
  if(data->multi != multi)
758
0
    return CURLM_BAD_EASY_HANDLE;
759
760
0
  if(data->mid == UINT_MAX) {
761
0
    DEBUGASSERT(0);
762
0
    return CURLM_INTERNAL_ERROR;
763
0
  }
764
0
  if(Curl_uint_tbl_get(&multi->xfers, data->mid) != data) {
765
0
    DEBUGASSERT(0);
766
0
    return CURLM_INTERNAL_ERROR;
767
0
  }
768
769
0
  if(multi->in_callback)
770
0
    return CURLM_RECURSIVE_API_CALL;
771
772
0
  premature = (data->mstate < MSTATE_COMPLETED);
773
774
  /* If the 'state' is not INIT or COMPLETED, we might need to do something
775
     nice to put the easy_handle in a good known state when this returns. */
776
0
  if(data->conn &&
777
0
     data->mstate > MSTATE_DO &&
778
0
     data->mstate < MSTATE_COMPLETED) {
779
    /* Set connection owner so that the DONE function closes it. We can
780
       safely do this here since connection is killed. */
781
0
    streamclose(data->conn, "Removed with partial response");
782
0
  }
783
784
0
  if(data->conn) {
785
    /* multi_done() clears the association between the easy handle and the
786
       connection.
787
788
       Note that this ignores the return code simply because there is
789
       nothing really useful to do with it anyway! */
790
0
    (void)multi_done(data, data->result, premature);
791
0
  }
792
793
  /* The timer must be shut down before data->multi is set to NULL, else the
794
     timenode will remain in the splay tree after curl_easy_cleanup is
795
     called. Do it after multi_done() in case that sets another time! */
796
0
  removed_timer = Curl_expire_clear(data);
797
798
  /* If in `msgsent`, it was deducted from `multi->xfers_alive` already. */
799
0
  if(!Curl_uint_bset_contains(&multi->msgsent, data->mid))
800
0
    --multi->xfers_alive;
801
802
0
  Curl_wildcard_dtor(&data->wildcard);
803
804
0
  data->mstate = MSTATE_COMPLETED;
805
806
  /* Remove the association between the connection and the handle */
807
0
  Curl_detach_connection(data);
808
809
  /* Tell event handling that this transfer is definitely going away */
810
0
  Curl_multi_ev_xfer_done(multi, data);
811
812
0
  if(data->set.connect_only && !data->multi_easy) {
813
    /* This removes a handle that was part the multi interface that used
814
       CONNECT_ONLY, that connection is now left alive but since this handle
815
       has bits.close set nothing can use that transfer anymore and it is
816
       forbidden from reuse. This easy handle cannot find the connection
817
       anymore once removed from the multi handle
818
819
       Better close the connection here, at once.
820
    */
821
0
    struct connectdata *c;
822
0
    curl_socket_t s;
823
0
    s = Curl_getconnectinfo(data, &c);
824
0
    if((s != CURL_SOCKET_BAD) && c) {
825
0
      Curl_conn_terminate(data, c, TRUE);
826
0
    }
827
0
  }
828
829
0
  if(data->state.lastconnect_id != -1) {
830
    /* Mark any connect-only connection for closure */
831
0
    Curl_cpool_do_by_id(data, data->state.lastconnect_id,
832
0
                            close_connect_only, NULL);
833
0
  }
834
835
#ifdef USE_LIBPSL
836
  /* Remove the PSL association. */
837
  if(data->psl == &multi->psl)
838
    data->psl = NULL;
839
#endif
840
841
  /* make sure there is no pending message in the queue sent from this easy
842
     handle */
843
0
  for(e = Curl_llist_head(&multi->msglist); e; e = Curl_node_next(e)) {
844
0
    struct Curl_message *msg = Curl_node_elem(e);
845
846
0
    if(msg->extmsg.easy_handle == data) {
847
0
      Curl_node_remove(e);
848
      /* there can only be one from this specific handle */
849
0
      break;
850
0
    }
851
0
  }
852
853
  /* clear the association to this multi handle */
854
0
  mid = data->mid;
855
0
  DEBUGASSERT(Curl_uint_tbl_contains(&multi->xfers, mid));
856
0
  Curl_uint_tbl_remove(&multi->xfers, mid);
857
0
  Curl_uint_bset_remove(&multi->process, mid);
858
0
  Curl_uint_bset_remove(&multi->dirty, mid);
859
0
  Curl_uint_bset_remove(&multi->pending, mid);
860
0
  Curl_uint_bset_remove(&multi->msgsent, mid);
861
0
  data->multi = NULL;
862
0
  data->mid = UINT_MAX;
863
0
  data->master_mid = UINT_MAX;
864
865
  /* NOTE NOTE NOTE
866
     We do not touch the easy handle here! */
867
0
  process_pending_handles(multi);
868
869
0
  if(removed_timer) {
870
0
    rc = Curl_update_timer(multi);
871
0
    if(rc)
872
0
      return rc;
873
0
  }
874
875
0
  CURL_TRC_M(data, "removed from multi, mid=%u, running=%u, total=%u",
876
0
             mid, Curl_multi_xfers_running(multi),
877
0
             Curl_uint_tbl_count(&multi->xfers));
878
0
  return CURLM_OK;
879
0
}
880
881
/* Return TRUE if the application asked for multiplexing */
882
bool Curl_multiplex_wanted(const struct Curl_multi *multi)
883
0
{
884
0
  return multi && multi->multiplexing;
885
0
}
886
887
/*
888
 * Curl_detach_connection() removes the given transfer from the connection.
889
 *
890
 * This is the only function that should clear data->conn. This will
891
 * occasionally be called with the data->conn pointer already cleared.
892
 */
893
void Curl_detach_connection(struct Curl_easy *data)
894
0
{
895
0
  struct connectdata *conn = data->conn;
896
0
  if(conn) {
897
0
    Curl_uint_spbset_remove(&conn->xfers_attached, data->mid);
898
0
    if(Curl_uint_spbset_empty(&conn->xfers_attached))
899
0
      conn->attached_multi = NULL;
900
0
  }
901
0
  data->conn = NULL;
902
0
}
903
904
/*
905
 * Curl_attach_connection() attaches this transfer to this connection.
906
 *
907
 * This is the only function that should assign data->conn
908
 */
909
void Curl_attach_connection(struct Curl_easy *data,
910
                            struct connectdata *conn)
911
0
{
912
0
  DEBUGASSERT(data);
913
0
  DEBUGASSERT(!data->conn);
914
0
  DEBUGASSERT(conn);
915
0
  data->conn = conn;
916
0
  Curl_uint_spbset_add(&conn->xfers_attached, data->mid);
917
  /* all attached transfers must be from the same multi */
918
0
  if(!conn->attached_multi)
919
0
    conn->attached_multi = data->multi;
920
0
  DEBUGASSERT(conn->attached_multi == data->multi);
921
922
0
  if(conn->handler && conn->handler->attach)
923
0
    conn->handler->attach(data, conn);
924
0
}
925
926
static CURLcode mstate_connecting_pollset(struct Curl_easy *data,
927
                                          struct easy_pollset *ps)
928
0
{
929
0
  if(data->conn) {
930
0
    curl_socket_t sockfd = Curl_conn_get_first_socket(data);
931
0
    if(sockfd != CURL_SOCKET_BAD) {
932
      /* Default is to wait to something from the server */
933
0
      return Curl_pollset_change(data, ps, sockfd, CURL_POLL_IN, 0);
934
0
    }
935
0
  }
936
0
  return CURLE_OK;
937
0
}
938
939
static CURLcode mstate_protocol_pollset(struct Curl_easy *data,
940
                                        struct easy_pollset *ps)
941
0
{
942
0
  if(data->conn) {
943
0
    curl_socket_t sockfd;
944
0
    if(data->conn->handler->proto_pollset)
945
0
      return data->conn->handler->proto_pollset(data, ps);
946
0
    sockfd = data->conn->sock[FIRSTSOCKET];
947
0
    if(sockfd != CURL_SOCKET_BAD) {
948
      /* Default is to wait to something from the server */
949
0
      return Curl_pollset_change(data, ps, sockfd, CURL_POLL_IN, 0);
950
0
    }
951
0
  }
952
0
  return CURLE_OK;
953
0
}
954
955
static CURLcode mstate_do_pollset(struct Curl_easy *data,
956
                                  struct easy_pollset *ps)
957
0
{
958
0
  if(data->conn) {
959
0
    if(data->conn->handler->doing_pollset)
960
0
      return data->conn->handler->doing_pollset(data, ps);
961
0
    else if(CONN_SOCK_IDX_VALID(data->conn->send_idx)) {
962
      /* Default is that we want to send something to the server */
963
0
      return Curl_pollset_add_out(
964
0
        data, ps, data->conn->sock[data->conn->send_idx]);
965
0
    }
966
0
  }
967
0
  return CURLE_OK;
968
0
}
969
970
static CURLcode mstate_domore_pollset(struct Curl_easy *data,
971
                                      struct easy_pollset *ps)
972
0
{
973
0
  if(data->conn) {
974
0
    if(data->conn->handler->domore_pollset)
975
0
      return data->conn->handler->domore_pollset(data, ps);
976
0
    else if(CONN_SOCK_IDX_VALID(data->conn->send_idx)) {
977
      /* Default is that we want to send something to the server */
978
0
      return Curl_pollset_add_out(
979
0
        data, ps, data->conn->sock[data->conn->send_idx]);
980
0
    }
981
0
  }
982
0
  return CURLE_OK;
983
0
}
984
985
static CURLcode mstate_perform_pollset(struct Curl_easy *data,
986
                                       struct easy_pollset *ps)
987
0
{
988
0
  if(!data->conn)
989
0
    return CURLE_OK;
990
0
  else if(data->conn->handler->perform_pollset)
991
0
    return data->conn->handler->perform_pollset(data, ps);
992
0
  else {
993
    /* Default is to obey the data->req.keepon flags for send/recv */
994
0
    CURLcode result = CURLE_OK;
995
0
    if(CURL_WANT_RECV(data) && CONN_SOCK_IDX_VALID(data->conn->recv_idx)) {
996
0
      result = Curl_pollset_add_in(
997
0
        data, ps, data->conn->sock[data->conn->recv_idx]);
998
0
    }
999
1000
0
    if(!result && Curl_req_want_send(data) &&
1001
0
       CONN_SOCK_IDX_VALID(data->conn->send_idx)) {
1002
0
      result = Curl_pollset_add_out(
1003
0
        data, ps, data->conn->sock[data->conn->send_idx]);
1004
0
    }
1005
0
    return result;
1006
0
  }
1007
0
}
1008
1009
/* Initializes `poll_set` with the current socket poll actions needed
1010
 * for transfer `data`. */
1011
CURLMcode Curl_multi_pollset(struct Curl_easy *data,
1012
                             struct easy_pollset *ps,
1013
                             const char *caller)
1014
0
{
1015
0
  CURLMcode mresult = CURLM_OK;
1016
0
  CURLcode result = CURLE_OK;
1017
0
  bool expect_sockets = TRUE;
1018
1019
  /* If the transfer has no connection, this is fine. Happens when
1020
     called via curl_multi_remove_handle() => Curl_multi_ev_assess() =>
1021
     Curl_multi_pollset(). */
1022
0
  Curl_pollset_reset(ps);
1023
0
  if(!data->conn)
1024
0
    return CURLM_OK;
1025
1026
0
  switch(data->mstate) {
1027
0
  case MSTATE_INIT:
1028
0
  case MSTATE_PENDING:
1029
0
  case MSTATE_SETUP:
1030
0
  case MSTATE_CONNECT:
1031
    /* nothing to poll for yet */
1032
0
    expect_sockets = FALSE;
1033
0
    break;
1034
1035
0
  case MSTATE_RESOLVING:
1036
0
    result = Curl_resolv_pollset(data, ps);
1037
    /* connection filters are not involved in this phase. It's ok if we get no
1038
     * sockets to wait for. Resolving can wake up from other sources. */
1039
0
    expect_sockets = FALSE;
1040
0
    break;
1041
1042
0
  case MSTATE_CONNECTING:
1043
0
  case MSTATE_TUNNELING:
1044
0
    if(!Curl_xfer_recv_is_paused(data)) {
1045
0
      result = mstate_connecting_pollset(data, ps);
1046
0
      if(!result)
1047
0
        result = Curl_conn_adjust_pollset(data, data->conn, ps);
1048
0
    }
1049
0
    else
1050
0
      expect_sockets = FALSE;
1051
0
    break;
1052
1053
0
  case MSTATE_PROTOCONNECT:
1054
0
  case MSTATE_PROTOCONNECTING:
1055
0
    result = mstate_protocol_pollset(data, ps);
1056
0
    if(!result)
1057
0
      result = Curl_conn_adjust_pollset(data, data->conn, ps);
1058
0
    break;
1059
1060
0
  case MSTATE_DO:
1061
0
  case MSTATE_DOING:
1062
0
    result = mstate_do_pollset(data, ps);
1063
0
    if(!result)
1064
0
      result = Curl_conn_adjust_pollset(data, data->conn, ps);
1065
0
    break;
1066
1067
0
  case MSTATE_DOING_MORE:
1068
0
    result = mstate_domore_pollset(data, ps);
1069
0
    if(!result)
1070
0
      result = Curl_conn_adjust_pollset(data, data->conn, ps);
1071
0
    break;
1072
1073
0
  case MSTATE_DID: /* same as PERFORMING in regard to polling */
1074
0
  case MSTATE_PERFORMING:
1075
0
    result = mstate_perform_pollset(data, ps);
1076
0
    if(!result)
1077
0
      result = Curl_conn_adjust_pollset(data, data->conn, ps);
1078
0
    break;
1079
1080
0
  case MSTATE_RATELIMITING:
1081
    /* we need to let time pass, ignore socket(s) */
1082
0
    expect_sockets = FALSE;
1083
0
    break;
1084
1085
0
  case MSTATE_DONE:
1086
0
  case MSTATE_COMPLETED:
1087
0
  case MSTATE_MSGSENT:
1088
    /* nothing more to poll for */
1089
0
    expect_sockets = FALSE;
1090
0
    break;
1091
1092
0
  default:
1093
0
    failf(data, "multi_getsock: unexpected multi state %d", data->mstate);
1094
0
    DEBUGASSERT(0);
1095
0
    expect_sockets = FALSE;
1096
0
    break;
1097
0
  }
1098
1099
0
  if(result) {
1100
0
    if(result == CURLE_OUT_OF_MEMORY)
1101
0
      mresult = CURLM_OUT_OF_MEMORY;
1102
0
    else {
1103
0
      failf(data, "error determining pollset: %d", result);
1104
0
      mresult = CURLM_INTERNAL_ERROR;
1105
0
    }
1106
0
    goto out;
1107
0
  }
1108
1109
  /* Unblocked and waiting to receive with buffered input.
1110
   * Make transfer run again at next opportunity. */
1111
0
  if(!Curl_xfer_is_blocked(data) && !Curl_xfer_is_too_fast(data) &&
1112
0
     ((Curl_pollset_want_read(data, ps, data->conn->sock[FIRSTSOCKET]) &&
1113
0
       Curl_conn_data_pending(data, FIRSTSOCKET)) ||
1114
0
      (Curl_pollset_want_read(data, ps, data->conn->sock[SECONDARYSOCKET]) &&
1115
0
       Curl_conn_data_pending(data, SECONDARYSOCKET)))) {
1116
0
    CURL_TRC_M(data, "%s pollset[] has POLLIN, but there is still "
1117
0
               "buffered input to consume -> mark as dirty", caller);
1118
0
    Curl_multi_mark_dirty(data);
1119
0
  }
1120
1121
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1122
0
  if(CURL_TRC_M_is_verbose(data)) {
1123
0
    size_t timeout_count = Curl_llist_count(&data->state.timeoutlist);
1124
0
    switch(ps->n) {
1125
0
      case 0:
1126
0
        CURL_TRC_M(data, "%s pollset[], timeouts=%zu, paused %d/%d (r/w)",
1127
0
                   caller, timeout_count,
1128
0
                   Curl_xfer_send_is_paused(data),
1129
0
                   Curl_xfer_recv_is_paused(data));
1130
0
        break;
1131
0
      case 1:
1132
0
        CURL_TRC_M(data, "%s pollset[fd=%" FMT_SOCKET_T " %s%s], timeouts=%zu",
1133
0
                   caller, ps->sockets[0],
1134
0
                   (ps->actions[0] & CURL_POLL_IN) ? "IN" : "",
1135
0
                   (ps->actions[0] & CURL_POLL_OUT) ? "OUT" : "",
1136
0
                   timeout_count);
1137
0
        break;
1138
0
      case 2:
1139
0
        CURL_TRC_M(data, "%s pollset[fd=%" FMT_SOCKET_T " %s%s, "
1140
0
                   "fd=%" FMT_SOCKET_T " %s%s], timeouts=%zu",
1141
0
                   caller, ps->sockets[0],
1142
0
                   (ps->actions[0] & CURL_POLL_IN) ? "IN" : "",
1143
0
                   (ps->actions[0] & CURL_POLL_OUT) ? "OUT" : "",
1144
0
                   ps->sockets[1],
1145
0
                   (ps->actions[1] & CURL_POLL_IN) ? "IN" : "",
1146
0
                   (ps->actions[1] & CURL_POLL_OUT) ? "OUT" : "",
1147
0
                   timeout_count);
1148
0
        break;
1149
0
      default:
1150
0
        CURL_TRC_M(data, "%s pollset[fds=%u], timeouts=%zu",
1151
0
                   caller, ps->n, timeout_count);
1152
0
        break;
1153
0
    }
1154
0
    CURL_TRC_EASY_TIMERS(data);
1155
0
  }
1156
0
#endif
1157
1158
0
  if(expect_sockets && !ps->n && data->multi &&
1159
0
     !Curl_uint_bset_contains(&data->multi->dirty, data->mid) &&
1160
0
     !Curl_llist_count(&data->state.timeoutlist) &&
1161
0
     !Curl_cwriter_is_paused(data) && !Curl_creader_is_paused(data) &&
1162
0
     Curl_conn_is_ip_connected(data, FIRSTSOCKET)) {
1163
    /* We expected sockets for POLL monitoring, but none are set.
1164
     * We are not dirty (and run anyway).
1165
     * We are not waiting on any timer.
1166
     * None of the READ/WRITE directions are paused.
1167
     * We are connected to the server on IP level, at least. */
1168
0
    infof(data, "WARNING: no socket in pollset or timer, transfer may stall!");
1169
0
    DEBUGASSERT(0);
1170
0
  }
1171
0
out:
1172
0
  return mresult;
1173
0
}
1174
1175
CURLMcode curl_multi_fdset(CURLM *m,
1176
                           fd_set *read_fd_set, fd_set *write_fd_set,
1177
                           fd_set *exc_fd_set, int *max_fd)
1178
0
{
1179
  /* Scan through all the easy handles to get the file descriptors set.
1180
     Some easy handles may not have connected to the remote host yet,
1181
     and then we must make sure that is done. */
1182
0
  int this_max_fd = -1;
1183
0
  struct Curl_multi *multi = m;
1184
0
  struct easy_pollset ps;
1185
0
  unsigned int i, mid;
1186
0
  (void)exc_fd_set;
1187
1188
0
  if(!GOOD_MULTI_HANDLE(multi))
1189
0
    return CURLM_BAD_HANDLE;
1190
1191
0
  if(multi->in_callback)
1192
0
    return CURLM_RECURSIVE_API_CALL;
1193
1194
0
  Curl_pollset_init(&ps);
1195
0
  if(Curl_uint_bset_first(&multi->process, &mid)) {
1196
0
    do {
1197
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
1198
1199
0
      if(!data) {
1200
0
        DEBUGASSERT(0);
1201
0
        continue;
1202
0
      }
1203
1204
0
      Curl_multi_pollset(data, &ps, "curl_multi_fdset");
1205
0
      for(i = 0; i < ps.n; i++) {
1206
0
        if(!FDSET_SOCK(ps.sockets[i]))
1207
          /* pretend it does not exist */
1208
0
          continue;
1209
#ifdef __DJGPP__
1210
#pragma GCC diagnostic push
1211
#pragma GCC diagnostic ignored "-Warith-conversion"
1212
#endif
1213
0
        if(ps.actions[i] & CURL_POLL_IN)
1214
0
          FD_SET(ps.sockets[i], read_fd_set);
1215
0
        if(ps.actions[i] & CURL_POLL_OUT)
1216
0
          FD_SET(ps.sockets[i], write_fd_set);
1217
#ifdef __DJGPP__
1218
#pragma GCC diagnostic pop
1219
#endif
1220
0
        if((int)ps.sockets[i] > this_max_fd)
1221
0
          this_max_fd = (int)ps.sockets[i];
1222
0
      }
1223
0
    }
1224
0
    while(Curl_uint_bset_next(&multi->process, mid, &mid));
1225
0
  }
1226
1227
0
  Curl_cshutdn_setfds(&multi->cshutdn, multi->admin,
1228
0
                      read_fd_set, write_fd_set, &this_max_fd);
1229
1230
0
  *max_fd = this_max_fd;
1231
0
  Curl_pollset_cleanup(&ps);
1232
1233
0
  return CURLM_OK;
1234
0
}
1235
1236
CURLMcode curl_multi_waitfds(CURLM *m,
1237
                             struct curl_waitfd *ufds,
1238
                             unsigned int size,
1239
                             unsigned int *fd_count)
1240
0
{
1241
0
  struct Curl_waitfds cwfds;
1242
0
  CURLMcode result = CURLM_OK;
1243
0
  struct Curl_multi *multi = m;
1244
0
  struct easy_pollset ps;
1245
0
  unsigned int need = 0, mid;
1246
1247
0
  if(!ufds && (size || !fd_count))
1248
0
    return CURLM_BAD_FUNCTION_ARGUMENT;
1249
1250
0
  if(!GOOD_MULTI_HANDLE(multi))
1251
0
    return CURLM_BAD_HANDLE;
1252
1253
0
  if(multi->in_callback)
1254
0
    return CURLM_RECURSIVE_API_CALL;
1255
1256
0
  Curl_pollset_init(&ps);
1257
0
  Curl_waitfds_init(&cwfds, ufds, size);
1258
0
  if(Curl_uint_bset_first(&multi->process, &mid)) {
1259
0
    do {
1260
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
1261
0
      if(!data) {
1262
0
        DEBUGASSERT(0);
1263
0
        Curl_uint_bset_remove(&multi->process, mid);
1264
0
        Curl_uint_bset_remove(&multi->dirty, mid);
1265
0
        continue;
1266
0
      }
1267
0
      Curl_multi_pollset(data, &ps, "curl_multi_waitfds");
1268
0
      need += Curl_waitfds_add_ps(&cwfds, &ps);
1269
0
    }
1270
0
    while(Curl_uint_bset_next(&multi->process, mid, &mid));
1271
0
  }
1272
1273
0
  need += Curl_cshutdn_add_waitfds(&multi->cshutdn, multi->admin, &cwfds);
1274
1275
0
  if(need != cwfds.n && ufds) {
1276
0
    result = CURLM_OUT_OF_MEMORY;
1277
0
  }
1278
1279
0
  if(fd_count)
1280
0
    *fd_count = need;
1281
0
  Curl_pollset_cleanup(&ps);
1282
0
  return result;
1283
0
}
1284
1285
#ifdef USE_WINSOCK
1286
/* Reset FD_WRITE for TCP sockets. Nothing is actually sent. UDP sockets cannot
1287
 * be reset this way because an empty datagram would be sent. #9203
1288
 *
1289
 * "On Windows the internal state of FD_WRITE as returned from
1290
 * WSAEnumNetworkEvents is only reset after successful send()."
1291
 */
1292
static void reset_socket_fdwrite(curl_socket_t s)
1293
{
1294
  int t;
1295
  int l = (int)sizeof(t);
1296
  if(!getsockopt(s, SOL_SOCKET, SO_TYPE, (char *)&t, &l) && t == SOCK_STREAM)
1297
    CURL_SEND(s, NULL, 0, 0);
1298
}
1299
#endif
1300
1301
0
#define NUM_POLLS_ON_STACK 10
1302
1303
static CURLMcode multi_wait(struct Curl_multi *multi,
1304
                            struct curl_waitfd extra_fds[],
1305
                            unsigned int extra_nfds,
1306
                            int timeout_ms,
1307
                            int *ret,
1308
                            bool extrawait, /* when no socket, wait */
1309
                            bool use_wakeup)
1310
0
{
1311
0
  size_t i;
1312
0
  struct curltime expire_time;
1313
0
  long timeout_internal;
1314
0
  int retcode = 0;
1315
0
  struct easy_pollset ps;
1316
0
  struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
1317
0
  struct curl_pollfds cpfds;
1318
0
  unsigned int curl_nfds = 0; /* how many pfds are for curl transfers */
1319
0
  struct Curl_easy *data = NULL;
1320
0
  CURLMcode result = CURLM_OK;
1321
0
  unsigned int mid;
1322
1323
#ifdef USE_WINSOCK
1324
  WSANETWORKEVENTS wsa_events;
1325
  DEBUGASSERT(multi->wsa_event != WSA_INVALID_EVENT);
1326
#endif
1327
#ifndef ENABLE_WAKEUP
1328
  (void)use_wakeup;
1329
#endif
1330
1331
0
  if(!GOOD_MULTI_HANDLE(multi))
1332
0
    return CURLM_BAD_HANDLE;
1333
1334
0
  if(multi->in_callback)
1335
0
    return CURLM_RECURSIVE_API_CALL;
1336
1337
0
  if(timeout_ms < 0)
1338
0
    return CURLM_BAD_FUNCTION_ARGUMENT;
1339
1340
0
  Curl_pollset_init(&ps);
1341
0
  Curl_pollfds_init(&cpfds, a_few_on_stack, NUM_POLLS_ON_STACK);
1342
1343
  /* Add the curl handles to our pollfds first */
1344
0
  if(Curl_uint_bset_first(&multi->process, &mid)) {
1345
0
    do {
1346
0
      data = Curl_multi_get_easy(multi, mid);
1347
0
      if(!data) {
1348
0
        DEBUGASSERT(0);
1349
0
        Curl_uint_bset_remove(&multi->process, mid);
1350
0
        Curl_uint_bset_remove(&multi->dirty, mid);
1351
0
        continue;
1352
0
      }
1353
0
      Curl_multi_pollset(data, &ps, "multi_wait");
1354
0
      if(Curl_pollfds_add_ps(&cpfds, &ps)) {
1355
0
        result = CURLM_OUT_OF_MEMORY;
1356
0
        goto out;
1357
0
      }
1358
0
    }
1359
0
    while(Curl_uint_bset_next(&multi->process, mid, &mid));
1360
0
  }
1361
1362
0
  if(Curl_cshutdn_add_pollfds(&multi->cshutdn, multi->admin, &cpfds)) {
1363
0
    result = CURLM_OUT_OF_MEMORY;
1364
0
    goto out;
1365
0
  }
1366
1367
0
  curl_nfds = cpfds.n; /* what curl internally uses in cpfds */
1368
  /* Add external file descriptions from poll-like struct curl_waitfd */
1369
0
  for(i = 0; i < extra_nfds; i++) {
1370
0
    unsigned short events = 0;
1371
0
    if(extra_fds[i].events & CURL_WAIT_POLLIN)
1372
0
      events |= POLLIN;
1373
0
    if(extra_fds[i].events & CURL_WAIT_POLLPRI)
1374
0
      events |= POLLPRI;
1375
0
    if(extra_fds[i].events & CURL_WAIT_POLLOUT)
1376
0
      events |= POLLOUT;
1377
0
    if(Curl_pollfds_add_sock(&cpfds, extra_fds[i].fd, events)) {
1378
0
      result = CURLM_OUT_OF_MEMORY;
1379
0
      goto out;
1380
0
    }
1381
0
  }
1382
1383
#ifdef USE_WINSOCK
1384
  /* Set the WSA events based on the collected pollds */
1385
  for(i = 0; i < cpfds.n; i++) {
1386
    long mask = 0;
1387
    if(cpfds.pfds[i].events & POLLIN)
1388
      mask |= FD_READ|FD_ACCEPT|FD_CLOSE;
1389
    if(cpfds.pfds[i].events & POLLPRI)
1390
      mask |= FD_OOB;
1391
    if(cpfds.pfds[i].events & POLLOUT) {
1392
      mask |= FD_WRITE|FD_CONNECT|FD_CLOSE;
1393
      reset_socket_fdwrite(cpfds.pfds[i].fd);
1394
    }
1395
    if(mask) {
1396
      if(WSAEventSelect(cpfds.pfds[i].fd, multi->wsa_event, mask) != 0) {
1397
        result = CURLM_OUT_OF_MEMORY;
1398
        goto out;
1399
      }
1400
    }
1401
  }
1402
#endif
1403
1404
0
#ifdef ENABLE_WAKEUP
1405
0
#ifndef USE_WINSOCK
1406
0
  if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
1407
0
    if(Curl_pollfds_add_sock(&cpfds, multi->wakeup_pair[0], POLLIN)) {
1408
0
      result = CURLM_OUT_OF_MEMORY;
1409
0
      goto out;
1410
0
    }
1411
0
  }
1412
0
#endif
1413
0
#endif
1414
1415
  /* We check the internal timeout *AFTER* we collected all sockets to
1416
   * poll. Collecting the sockets may install new timers by protocols
1417
   * and connection filters.
1418
   * Use the shorter one of the internal and the caller requested timeout. */
1419
0
  (void)multi_timeout(multi, &expire_time, &timeout_internal);
1420
0
  if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
1421
0
    timeout_ms = (int)timeout_internal;
1422
1423
0
  if(data)
1424
0
    CURL_TRC_M(data, "multi_wait(fds=%d, timeout=%d) tinternal=%ld",
1425
0
               cpfds.n, timeout_ms, timeout_internal);
1426
#if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
1427
  if(cpfds.n || use_wakeup) {
1428
#else
1429
0
  if(cpfds.n) {
1430
0
#endif
1431
0
    int pollrc;
1432
#ifdef USE_WINSOCK
1433
    if(cpfds.n)         /* just pre-check with Winsock */
1434
      pollrc = Curl_poll(cpfds.pfds, cpfds.n, 0);
1435
    else
1436
      pollrc = 0;
1437
#else
1438
0
    pollrc = Curl_poll(cpfds.pfds, cpfds.n, timeout_ms); /* wait... */
1439
0
#endif
1440
0
    if(pollrc < 0) {
1441
0
      result = CURLM_UNRECOVERABLE_POLL;
1442
0
      goto out;
1443
0
    }
1444
1445
0
    if(pollrc > 0) {
1446
0
      retcode = pollrc;
1447
#ifdef USE_WINSOCK
1448
    }
1449
    else { /* now wait... if not ready during the pre-check (pollrc == 0) */
1450
      WSAWaitForMultipleEvents(1, &multi->wsa_event, FALSE, (DWORD)timeout_ms,
1451
                               FALSE);
1452
    }
1453
    /* With Winsock, we have to run the following section unconditionally
1454
       to call WSAEventSelect(fd, event, 0) on all the sockets */
1455
    {
1456
#endif
1457
      /* copy revents results from the poll to the curl_multi_wait poll
1458
         struct, the bit values of the actual underlying poll() implementation
1459
         may not be the same as the ones in the public libcurl API! */
1460
0
      for(i = 0; i < extra_nfds; i++) {
1461
0
        unsigned r = (unsigned)cpfds.pfds[curl_nfds + i].revents;
1462
0
        unsigned short mask = 0;
1463
#ifdef USE_WINSOCK
1464
        curl_socket_t s = extra_fds[i].fd;
1465
        wsa_events.lNetworkEvents = 0;
1466
        if(WSAEnumNetworkEvents(s, NULL, &wsa_events) == 0) {
1467
          if(wsa_events.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))
1468
            mask |= CURL_WAIT_POLLIN;
1469
          if(wsa_events.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))
1470
            mask |= CURL_WAIT_POLLOUT;
1471
          if(wsa_events.lNetworkEvents & FD_OOB)
1472
            mask |= CURL_WAIT_POLLPRI;
1473
          if(ret && !pollrc && wsa_events.lNetworkEvents)
1474
            retcode++;
1475
        }
1476
        WSAEventSelect(s, multi->wsa_event, 0);
1477
        if(!pollrc) {
1478
          extra_fds[i].revents = (short)mask;
1479
          continue;
1480
        }
1481
#endif
1482
0
        if(r & POLLIN)
1483
0
          mask |= CURL_WAIT_POLLIN;
1484
0
        if(r & POLLOUT)
1485
0
          mask |= CURL_WAIT_POLLOUT;
1486
0
        if(r & POLLPRI)
1487
0
          mask |= CURL_WAIT_POLLPRI;
1488
0
        extra_fds[i].revents = (short)mask;
1489
0
      }
1490
1491
#ifdef USE_WINSOCK
1492
      /* Count up all our own sockets that had activity,
1493
         and remove them from the event. */
1494
      for(i = 0; i < curl_nfds; ++i) {
1495
        wsa_events.lNetworkEvents = 0;
1496
        if(WSAEnumNetworkEvents(cpfds.pfds[i].fd, NULL, &wsa_events) == 0) {
1497
          if(ret && !pollrc && wsa_events.lNetworkEvents)
1498
            retcode++;
1499
        }
1500
        WSAEventSelect(cpfds.pfds[i].fd, multi->wsa_event, 0);
1501
      }
1502
      WSAResetEvent(multi->wsa_event);
1503
#else
1504
0
#ifdef ENABLE_WAKEUP
1505
0
      if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
1506
0
        if(cpfds.pfds[curl_nfds + extra_nfds].revents & POLLIN) {
1507
0
          char buf[64];
1508
0
          ssize_t nread;
1509
0
          while(1) {
1510
            /* the reading socket is non-blocking, try to read
1511
               data from it until it receives an error (except EINTR).
1512
               In normal cases it will get EAGAIN or EWOULDBLOCK
1513
               when there is no more data, breaking the loop. */
1514
0
            nread = wakeup_read(multi->wakeup_pair[0], buf, sizeof(buf));
1515
0
            if(nread <= 0) {
1516
0
              if(nread < 0 && SOCKEINTR == SOCKERRNO)
1517
0
                continue;
1518
0
              break;
1519
0
            }
1520
0
          }
1521
          /* do not count the wakeup socket into the returned value */
1522
0
          retcode--;
1523
0
        }
1524
0
      }
1525
0
#endif
1526
0
#endif
1527
0
    }
1528
0
  }
1529
1530
0
  if(ret)
1531
0
    *ret = retcode;
1532
#if defined(ENABLE_WAKEUP) && defined(USE_WINSOCK)
1533
  if(extrawait && !cpfds.n && !use_wakeup) {
1534
#else
1535
0
  if(extrawait && !cpfds.n) {
1536
0
#endif
1537
0
    long sleep_ms = 0;
1538
1539
    /* Avoid busy-looping when there is nothing particular to wait for */
1540
0
    if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) {
1541
0
      if(sleep_ms > timeout_ms)
1542
0
        sleep_ms = timeout_ms;
1543
      /* when there are no easy handles in the multi, this holds a -1
1544
         timeout */
1545
0
      else if(sleep_ms < 0)
1546
0
        sleep_ms = timeout_ms;
1547
0
      curlx_wait_ms(sleep_ms);
1548
0
    }
1549
0
  }
1550
1551
0
out:
1552
0
  Curl_pollset_cleanup(&ps);
1553
0
  Curl_pollfds_cleanup(&cpfds);
1554
0
  return result;
1555
0
}
1556
1557
CURLMcode curl_multi_wait(CURLM *multi,
1558
                          struct curl_waitfd extra_fds[],
1559
                          unsigned int extra_nfds,
1560
                          int timeout_ms,
1561
                          int *ret)
1562
0
{
1563
0
  return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE,
1564
0
                    FALSE);
1565
0
}
1566
1567
CURLMcode curl_multi_poll(CURLM *multi,
1568
                          struct curl_waitfd extra_fds[],
1569
                          unsigned int extra_nfds,
1570
                          int timeout_ms,
1571
                          int *ret)
1572
0
{
1573
0
  return multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE,
1574
0
                    TRUE);
1575
0
}
1576
1577
CURLMcode curl_multi_wakeup(CURLM *m)
1578
0
{
1579
  /* this function is usually called from another thread,
1580
     it has to be careful only to access parts of the
1581
     Curl_multi struct that are constant */
1582
0
  struct Curl_multi *multi = m;
1583
1584
  /* GOOD_MULTI_HANDLE can be safely called */
1585
0
  if(!GOOD_MULTI_HANDLE(multi))
1586
0
    return CURLM_BAD_HANDLE;
1587
1588
0
#ifdef ENABLE_WAKEUP
1589
#ifdef USE_WINSOCK
1590
  if(WSASetEvent(multi->wsa_event))
1591
    return CURLM_OK;
1592
#else
1593
  /* the wakeup_pair variable is only written during init and cleanup,
1594
     making it safe to access from another thread after the init part
1595
     and before cleanup */
1596
0
  if(multi->wakeup_pair[1] != CURL_SOCKET_BAD) {
1597
0
    while(1) {
1598
0
#ifdef USE_EVENTFD
1599
      /* eventfd has a stringent rule of requiring the 8-byte buffer when
1600
         calling write(2) on it */
1601
0
      const uint64_t buf[1] = { 1 };
1602
#else
1603
      const char buf[1] = { 1 };
1604
#endif
1605
      /* swrite() is not thread-safe in general, because concurrent calls
1606
         can have their messages interleaved, but in this case the content
1607
         of the messages does not matter, which makes it ok to call.
1608
1609
         The write socket is set to non-blocking, this way this function
1610
         cannot block, making it safe to call even from the same thread
1611
         that will call curl_multi_wait(). If swrite() returns that it
1612
         would block, it is considered successful because it means that
1613
         previous calls to this function will wake up the poll(). */
1614
0
      if(wakeup_write(multi->wakeup_pair[1], buf, sizeof(buf)) < 0) {
1615
0
        int err = SOCKERRNO;
1616
0
        int return_success;
1617
#ifdef USE_WINSOCK
1618
        return_success = SOCKEWOULDBLOCK == err;
1619
#else
1620
0
        if(SOCKEINTR == err)
1621
0
          continue;
1622
0
        return_success = SOCKEWOULDBLOCK == err || EAGAIN == err;
1623
0
#endif
1624
0
        if(!return_success)
1625
0
          return CURLM_WAKEUP_FAILURE;
1626
0
      }
1627
0
      return CURLM_OK;
1628
0
    }
1629
0
  }
1630
0
#endif
1631
0
#endif
1632
0
  return CURLM_WAKEUP_FAILURE;
1633
0
}
1634
1635
/*
1636
 * multi_ischanged() is called
1637
 *
1638
 * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND
1639
 * => CONNECT action.
1640
 *
1641
 * Set 'clear' to TRUE to have it also clear the state variable.
1642
 */
1643
static bool multi_ischanged(struct Curl_multi *multi, bool clear)
1644
0
{
1645
0
  bool retval = multi->recheckstate;
1646
0
  if(clear)
1647
0
    multi->recheckstate = FALSE;
1648
0
  return retval;
1649
0
}
1650
1651
/*
1652
 * Curl_multi_connchanged() is called to tell that there is a connection in
1653
 * this multi handle that has changed state (multiplexing become possible, the
1654
 * number of allowed streams changed or similar), and a subsequent use of this
1655
 * multi handle should move CONNECT_PEND handles back to CONNECT to have them
1656
 * retry.
1657
 */
1658
void Curl_multi_connchanged(struct Curl_multi *multi)
1659
0
{
1660
0
  multi->recheckstate = TRUE;
1661
0
}
1662
1663
CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
1664
                                 struct Curl_easy *data,
1665
                                 struct connectdata *conn)
1666
0
{
1667
0
  CURLMcode rc;
1668
1669
0
  if(multi->in_callback)
1670
0
    return CURLM_RECURSIVE_API_CALL;
1671
1672
0
  rc = curl_multi_add_handle(multi, data);
1673
0
  if(!rc) {
1674
0
    struct SingleRequest *k = &data->req;
1675
0
    CURLcode result;
1676
1677
    /* pass in NULL for 'conn' here since we do not want to init the
1678
       connection, only this transfer */
1679
0
    result = Curl_init_do(data, NULL);
1680
0
    if(result) {
1681
0
      curl_multi_remove_handle(multi, data);
1682
0
      return CURLM_INTERNAL_ERROR;
1683
0
    }
1684
1685
    /* take this handle to the perform state right away */
1686
0
    multistate(data, MSTATE_PERFORMING);
1687
0
    Curl_attach_connection(data, conn);
1688
0
    k->keepon |= KEEP_RECV; /* setup to receive! */
1689
0
  }
1690
0
  return rc;
1691
0
}
1692
1693
static CURLcode multi_do(struct Curl_easy *data, bool *done)
1694
0
{
1695
0
  CURLcode result = CURLE_OK;
1696
0
  struct connectdata *conn = data->conn;
1697
1698
0
  DEBUGASSERT(conn);
1699
0
  DEBUGASSERT(conn->handler);
1700
1701
0
  if(conn->handler->do_it)
1702
0
    result = conn->handler->do_it(data, done);
1703
1704
0
  return result;
1705
0
}
1706
1707
/*
1708
 * multi_do_more() is called during the DO_MORE multi state. It is basically a
1709
 * second stage DO state which (wrongly) was introduced to support FTP's
1710
 * second connection.
1711
 *
1712
 * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
1713
 * DOING state there is more work to do!
1714
 */
1715
1716
static CURLcode multi_do_more(struct Curl_easy *data, int *complete)
1717
0
{
1718
0
  CURLcode result = CURLE_OK;
1719
0
  struct connectdata *conn = data->conn;
1720
1721
0
  *complete = 0;
1722
1723
0
  if(conn->handler->do_more)
1724
0
    result = conn->handler->do_more(data, complete);
1725
1726
0
  return result;
1727
0
}
1728
1729
/*
1730
 * Check whether a timeout occurred, and handle it if it did
1731
 */
1732
static bool multi_handle_timeout(struct Curl_easy *data,
1733
                                 struct curltime *now,
1734
                                 bool *stream_error,
1735
                                 CURLcode *result)
1736
0
{
1737
0
  bool connect_timeout = data->mstate < MSTATE_DO;
1738
0
  timediff_t timeout_ms = Curl_timeleft(data, now, connect_timeout);
1739
0
  if(timeout_ms < 0) {
1740
    /* Handle timed out */
1741
0
    struct curltime since;
1742
0
    if(connect_timeout)
1743
0
      since = data->progress.t_startsingle;
1744
0
    else
1745
0
      since = data->progress.t_startop;
1746
0
    if(data->mstate == MSTATE_RESOLVING)
1747
0
      failf(data, "Resolving timed out after %" FMT_TIMEDIFF_T
1748
0
            " milliseconds", curlx_timediff(*now, since));
1749
0
    else if(data->mstate == MSTATE_CONNECTING)
1750
0
      failf(data, "Connection timed out after %" FMT_TIMEDIFF_T
1751
0
            " milliseconds", curlx_timediff(*now, since));
1752
0
    else {
1753
0
      struct SingleRequest *k = &data->req;
1754
0
      if(k->size != -1) {
1755
0
        failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
1756
0
              " milliseconds with %" FMT_OFF_T " out of %"
1757
0
              FMT_OFF_T " bytes received",
1758
0
              curlx_timediff(*now, since), k->bytecount, k->size);
1759
0
      }
1760
0
      else {
1761
0
        failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
1762
0
              " milliseconds with %" FMT_OFF_T " bytes received",
1763
0
              curlx_timediff(*now, since), k->bytecount);
1764
0
      }
1765
0
    }
1766
0
    *result = CURLE_OPERATION_TIMEDOUT;
1767
0
    if(data->conn) {
1768
      /* Force connection closed if the connection has indeed been used */
1769
0
      if(data->mstate > MSTATE_DO) {
1770
0
        streamclose(data->conn, "Disconnect due to timeout");
1771
0
        *stream_error = TRUE;
1772
0
      }
1773
0
      (void)multi_done(data, *result, TRUE);
1774
0
    }
1775
0
    return TRUE;
1776
0
  }
1777
1778
0
  return FALSE;
1779
0
}
1780
1781
/*
1782
 * We are doing protocol-specific connecting and this is being called over and
1783
 * over from the multi interface until the connection phase is done on
1784
 * protocol layer.
1785
 */
1786
1787
static CURLcode protocol_connecting(struct Curl_easy *data, bool *done)
1788
0
{
1789
0
  CURLcode result = CURLE_OK;
1790
0
  struct connectdata *conn = data->conn;
1791
1792
0
  if(conn && conn->handler->connecting) {
1793
0
    *done = FALSE;
1794
0
    result = conn->handler->connecting(data, done);
1795
0
  }
1796
0
  else
1797
0
    *done = TRUE;
1798
1799
0
  return result;
1800
0
}
1801
1802
/*
1803
 * We are DOING this is being called over and over from the multi interface
1804
 * until the DOING phase is done on protocol layer.
1805
 */
1806
1807
static CURLcode protocol_doing(struct Curl_easy *data, bool *done)
1808
0
{
1809
0
  CURLcode result = CURLE_OK;
1810
0
  struct connectdata *conn = data->conn;
1811
1812
0
  if(conn && conn->handler->doing) {
1813
0
    *done = FALSE;
1814
0
    result = conn->handler->doing(data, done);
1815
0
  }
1816
0
  else
1817
0
    *done = TRUE;
1818
1819
0
  return result;
1820
0
}
1821
1822
/*
1823
 * We have discovered that the TCP connection has been successful, we can now
1824
 * proceed with some action.
1825
 *
1826
 */
1827
static CURLcode protocol_connect(struct Curl_easy *data,
1828
                                 bool *protocol_done)
1829
0
{
1830
0
  CURLcode result = CURLE_OK;
1831
0
  struct connectdata *conn = data->conn;
1832
0
  DEBUGASSERT(conn);
1833
0
  DEBUGASSERT(protocol_done);
1834
1835
0
  *protocol_done = FALSE;
1836
1837
0
  if(Curl_conn_is_connected(conn, FIRSTSOCKET)
1838
0
     && conn->bits.protoconnstart) {
1839
    /* We already are connected, get back. This may happen when the connect
1840
       worked fine in the first call, like when we connect to a local server
1841
       or proxy. Note that we do not know if the protocol is actually done.
1842
1843
       Unless this protocol does not have any protocol-connect callback, as
1844
       then we know we are done. */
1845
0
    if(!conn->handler->connecting)
1846
0
      *protocol_done = TRUE;
1847
1848
0
    return CURLE_OK;
1849
0
  }
1850
1851
0
  if(!conn->bits.protoconnstart) {
1852
0
    if(conn->handler->connect_it) {
1853
      /* is there a protocol-specific connect() procedure? */
1854
1855
      /* Call the protocol-specific connect function */
1856
0
      result = conn->handler->connect_it(data, protocol_done);
1857
0
    }
1858
0
    else
1859
0
      *protocol_done = TRUE;
1860
1861
    /* it has started, possibly even completed but that knowledge is not stored
1862
       in this bit! */
1863
0
    if(!result)
1864
0
      conn->bits.protoconnstart = TRUE;
1865
0
  }
1866
1867
0
  return result; /* pass back status */
1868
0
}
1869
1870
static void set_in_callback(struct Curl_multi *multi, bool value)
1871
0
{
1872
0
  multi->in_callback = value;
1873
0
}
1874
1875
/*
1876
 * posttransfer() is called immediately after a transfer ends
1877
 */
1878
static void multi_posttransfer(struct Curl_easy *data)
1879
0
{
1880
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1881
  /* restore the signal handler for SIGPIPE before we get back */
1882
  if(!data->set.no_signal)
1883
    signal(SIGPIPE, data->state.prev_signal);
1884
#else
1885
0
  (void)data;
1886
0
#endif
1887
0
}
1888
1889
/*
1890
 * multi_follow() handles the URL redirect magic. Pass in the 'newurl' string
1891
 * as given by the remote server and set up the new URL to request.
1892
 *
1893
 * This function DOES NOT FREE the given url.
1894
 */
1895
static CURLcode multi_follow(struct Curl_easy *data,
1896
                             const struct Curl_handler *handler,
1897
                             const char *newurl, /* the Location: string */
1898
                             followtype type) /* see transfer.h */
1899
0
{
1900
0
  if(handler && handler->follow)
1901
0
    return handler->follow(data, newurl, type);
1902
0
  return CURLE_TOO_MANY_REDIRECTS;
1903
0
}
1904
1905
static CURLcode mspeed_check(struct Curl_easy *data,
1906
                             struct curltime *nowp)
1907
0
{
1908
0
  timediff_t recv_wait_ms = 0;
1909
0
  timediff_t send_wait_ms = 0;
1910
1911
  /* check if over send speed */
1912
0
  if(data->set.max_send_speed)
1913
0
    send_wait_ms = Curl_pgrsLimitWaitTime(&data->progress.ul,
1914
0
                                          data->set.max_send_speed,
1915
0
                                          *nowp);
1916
1917
  /* check if over recv speed */
1918
0
  if(data->set.max_recv_speed)
1919
0
    recv_wait_ms = Curl_pgrsLimitWaitTime(&data->progress.dl,
1920
0
                                          data->set.max_recv_speed,
1921
0
                                          *nowp);
1922
1923
0
  if(send_wait_ms || recv_wait_ms) {
1924
0
    if(data->mstate != MSTATE_RATELIMITING) {
1925
0
      Curl_ratelimit(data, *nowp);
1926
0
      multistate(data, MSTATE_RATELIMITING);
1927
0
    }
1928
0
    Curl_expire(data, CURLMAX(send_wait_ms, recv_wait_ms), EXPIRE_TOOFAST);
1929
0
    Curl_multi_clear_dirty(data);
1930
0
    return CURLE_AGAIN;
1931
0
  }
1932
0
  else if(data->mstate != MSTATE_PERFORMING) {
1933
0
    multistate(data, MSTATE_PERFORMING);
1934
0
    Curl_ratelimit(data, *nowp);
1935
0
  }
1936
0
  return CURLE_OK;
1937
0
}
1938
1939
static CURLMcode state_performing(struct Curl_easy *data,
1940
                                  struct curltime *nowp,
1941
                                  bool *stream_errorp,
1942
                                  CURLcode *resultp)
1943
0
{
1944
0
  char *newurl = NULL;
1945
0
  bool retry = FALSE;
1946
0
  CURLMcode rc = CURLM_OK;
1947
0
  CURLcode result = *resultp = CURLE_OK;
1948
0
  *stream_errorp = FALSE;
1949
1950
0
  if(mspeed_check(data, nowp) == CURLE_AGAIN)
1951
0
    return CURLM_OK;
1952
1953
  /* read/write data if it is ready to do so */
1954
0
  result = Curl_sendrecv(data, nowp);
1955
1956
0
  if(data->req.done || (result == CURLE_RECV_ERROR)) {
1957
    /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
1958
     * condition and the server closed the reused connection exactly when we
1959
     * wanted to use it, so figure out if that is indeed the case.
1960
     */
1961
0
    CURLcode ret = Curl_retry_request(data, &newurl);
1962
0
    if(!ret)
1963
0
      retry = !!newurl;
1964
0
    else if(!result)
1965
0
      result = ret;
1966
1967
0
    if(retry) {
1968
      /* if we are to retry, set the result to OK and consider the
1969
         request as done */
1970
0
      result = CURLE_OK;
1971
0
      data->req.done = TRUE;
1972
0
    }
1973
0
  }
1974
0
#ifndef CURL_DISABLE_HTTP
1975
0
  else if((CURLE_HTTP2_STREAM == result) &&
1976
0
          Curl_h2_http_1_1_error(data)) {
1977
0
    CURLcode ret = Curl_retry_request(data, &newurl);
1978
1979
0
    if(!ret) {
1980
0
      infof(data, "Downgrades to HTTP/1.1");
1981
0
      streamclose(data->conn, "Disconnect HTTP/2 for HTTP/1");
1982
0
      data->state.http_neg.wanted = CURL_HTTP_V1x;
1983
0
      data->state.http_neg.allowed = CURL_HTTP_V1x;
1984
      /* clear the error message bit too as we ignore the one we got */
1985
0
      data->state.errorbuf = FALSE;
1986
0
      if(!newurl)
1987
        /* typically for HTTP_1_1_REQUIRED error on first flight */
1988
0
        newurl = strdup(data->state.url);
1989
      /* if we are to retry, set the result to OK and consider the request
1990
         as done */
1991
0
      retry = TRUE;
1992
0
      result = CURLE_OK;
1993
0
      data->req.done = TRUE;
1994
0
    }
1995
0
    else
1996
0
      result = ret;
1997
0
  }
1998
0
#endif
1999
2000
0
  if(result) {
2001
    /*
2002
     * The transfer phase returned error, we mark the connection to get closed
2003
     * to prevent being reused. This is because we cannot possibly know if the
2004
     * connection is in a good shape or not now. Unless it is a protocol which
2005
     * uses two "channels" like FTP, as then the error happened in the data
2006
     * connection.
2007
     */
2008
2009
0
    if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
2010
0
       result != CURLE_HTTP2_STREAM)
2011
0
      streamclose(data->conn, "Transfer returned error");
2012
2013
0
    multi_posttransfer(data);
2014
0
    multi_done(data, result, TRUE);
2015
0
  }
2016
0
  else if(data->req.done && !Curl_cwriter_is_paused(data)) {
2017
0
    const struct Curl_handler *handler = data->conn->handler;
2018
2019
    /* call this even if the readwrite function returned error */
2020
0
    multi_posttransfer(data);
2021
2022
    /* When we follow redirects or is set to retry the connection, we must to
2023
       go back to the CONNECT state */
2024
0
    if(data->req.newurl || retry) {
2025
0
      followtype follow = FOLLOW_NONE;
2026
0
      if(!retry) {
2027
        /* if the URL is a follow-location and not just a retried request then
2028
           figure out the URL here */
2029
0
        free(newurl);
2030
0
        newurl = data->req.newurl;
2031
0
        data->req.newurl = NULL;
2032
0
        follow = FOLLOW_REDIR;
2033
0
      }
2034
0
      else
2035
0
        follow = FOLLOW_RETRY;
2036
0
      (void)multi_done(data, CURLE_OK, FALSE);
2037
      /* multi_done() might return CURLE_GOT_NOTHING */
2038
0
      result = multi_follow(data, handler, newurl, follow);
2039
0
      if(!result) {
2040
0
        multistate(data, MSTATE_SETUP);
2041
0
        rc = CURLM_CALL_MULTI_PERFORM;
2042
0
      }
2043
0
    }
2044
0
    else {
2045
      /* after the transfer is done, go DONE */
2046
2047
      /* but first check to see if we got a location info even though we are
2048
         not following redirects */
2049
0
      if(data->req.location) {
2050
0
        free(newurl);
2051
0
        newurl = data->req.location;
2052
0
        data->req.location = NULL;
2053
0
        result = multi_follow(data, handler, newurl, FOLLOW_FAKE);
2054
0
        if(result) {
2055
0
          *stream_errorp = TRUE;
2056
0
          result = multi_done(data, result, TRUE);
2057
0
        }
2058
0
      }
2059
2060
0
      if(!result) {
2061
0
        multistate(data, MSTATE_DONE);
2062
0
        rc = CURLM_CALL_MULTI_PERFORM;
2063
0
      }
2064
0
    }
2065
0
  }
2066
0
  else { /* not errored, not done */
2067
0
    mspeed_check(data, nowp);
2068
0
  }
2069
0
  free(newurl);
2070
0
  *resultp = result;
2071
0
  return rc;
2072
0
}
2073
2074
static CURLMcode state_do(struct Curl_easy *data,
2075
                          bool *stream_errorp,
2076
                          CURLcode *resultp)
2077
0
{
2078
0
  CURLMcode rc = CURLM_OK;
2079
0
  CURLcode result = CURLE_OK;
2080
0
  if(data->set.fprereq) {
2081
0
    int prereq_rc;
2082
2083
    /* call the prerequest callback function */
2084
0
    Curl_set_in_callback(data, TRUE);
2085
0
    prereq_rc = data->set.fprereq(data->set.prereq_userp,
2086
0
                                  data->info.primary.remote_ip,
2087
0
                                  data->info.primary.local_ip,
2088
0
                                  data->info.primary.remote_port,
2089
0
                                  data->info.primary.local_port);
2090
0
    Curl_set_in_callback(data, FALSE);
2091
0
    if(prereq_rc != CURL_PREREQFUNC_OK) {
2092
0
      failf(data, "operation aborted by pre-request callback");
2093
      /* failure in pre-request callback - do not do any other processing */
2094
0
      result = CURLE_ABORTED_BY_CALLBACK;
2095
0
      multi_posttransfer(data);
2096
0
      multi_done(data, result, FALSE);
2097
0
      *stream_errorp = TRUE;
2098
0
      goto end;
2099
0
    }
2100
0
  }
2101
2102
0
  if(data->set.connect_only && !data->set.connect_only_ws) {
2103
    /* keep connection open for application to use the socket */
2104
0
    connkeep(data->conn, "CONNECT_ONLY");
2105
0
    multistate(data, MSTATE_DONE);
2106
0
    rc = CURLM_CALL_MULTI_PERFORM;
2107
0
  }
2108
0
  else {
2109
0
    bool dophase_done = FALSE;
2110
    /* Perform the protocol's DO action */
2111
0
    result = multi_do(data, &dophase_done);
2112
2113
    /* When multi_do() returns failure, data->conn might be NULL! */
2114
2115
0
    if(!result) {
2116
0
      if(!dophase_done) {
2117
0
#ifndef CURL_DISABLE_FTP
2118
        /* some steps needed for wildcard matching */
2119
0
        if(data->state.wildcardmatch) {
2120
0
          struct WildcardData *wc = data->wildcard;
2121
0
          if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
2122
            /* skip some states if it is important */
2123
0
            multi_done(data, CURLE_OK, FALSE);
2124
2125
            /* if there is no connection left, skip the DONE state */
2126
0
            multistate(data, data->conn ?
2127
0
                       MSTATE_DONE : MSTATE_COMPLETED);
2128
0
            rc = CURLM_CALL_MULTI_PERFORM;
2129
0
            goto end;
2130
0
          }
2131
0
        }
2132
0
#endif
2133
        /* DO was not completed in one function call, we must continue
2134
           DOING... */
2135
0
        multistate(data, MSTATE_DOING);
2136
0
        rc = CURLM_CALL_MULTI_PERFORM;
2137
0
      }
2138
2139
      /* after DO, go DO_DONE... or DO_MORE */
2140
0
      else if(data->conn->bits.do_more) {
2141
        /* we are supposed to do more, but we need to sit down, relax and wait
2142
           a little while first */
2143
0
        multistate(data, MSTATE_DOING_MORE);
2144
0
        rc = CURLM_CALL_MULTI_PERFORM;
2145
0
      }
2146
0
      else {
2147
        /* we are done with the DO, now DID */
2148
0
        multistate(data, MSTATE_DID);
2149
0
        rc = CURLM_CALL_MULTI_PERFORM;
2150
0
      }
2151
0
    }
2152
0
    else if((CURLE_SEND_ERROR == result) &&
2153
0
            data->conn->bits.reuse) {
2154
      /*
2155
       * In this situation, a connection that we were trying to use may have
2156
       * unexpectedly died. If possible, send the connection back to the
2157
       * CONNECT phase so we can try again.
2158
       */
2159
0
      const struct Curl_handler *handler = data->conn->handler;
2160
0
      char *newurl = NULL;
2161
0
      followtype follow = FOLLOW_NONE;
2162
0
      CURLcode drc;
2163
2164
0
      drc = Curl_retry_request(data, &newurl);
2165
0
      if(drc) {
2166
        /* a failure here pretty much implies an out of memory */
2167
0
        result = drc;
2168
0
        *stream_errorp = TRUE;
2169
0
      }
2170
2171
0
      multi_posttransfer(data);
2172
0
      drc = multi_done(data, result, FALSE);
2173
2174
      /* When set to retry the connection, we must go back to the CONNECT
2175
       * state */
2176
0
      if(newurl) {
2177
0
        if(!drc || (drc == CURLE_SEND_ERROR)) {
2178
0
          follow = FOLLOW_RETRY;
2179
0
          drc = multi_follow(data, handler, newurl, follow);
2180
0
          if(!drc) {
2181
0
            multistate(data, MSTATE_SETUP);
2182
0
            rc = CURLM_CALL_MULTI_PERFORM;
2183
0
            result = CURLE_OK;
2184
0
          }
2185
0
          else {
2186
            /* Follow failed */
2187
0
            result = drc;
2188
0
          }
2189
0
        }
2190
0
        else {
2191
          /* done did not return OK or SEND_ERROR */
2192
0
          result = drc;
2193
0
        }
2194
0
      }
2195
0
      else {
2196
        /* Have error handler disconnect conn if we cannot retry */
2197
0
        *stream_errorp = TRUE;
2198
0
      }
2199
0
      free(newurl);
2200
0
    }
2201
0
    else {
2202
      /* failure detected */
2203
0
      multi_posttransfer(data);
2204
0
      if(data->conn)
2205
0
        multi_done(data, result, FALSE);
2206
0
      *stream_errorp = TRUE;
2207
0
    }
2208
0
  }
2209
0
end:
2210
0
  *resultp = result;
2211
0
  return rc;
2212
0
}
2213
2214
static CURLMcode state_ratelimiting(struct Curl_easy *data,
2215
                                    struct curltime *nowp,
2216
                                    CURLcode *resultp)
2217
0
{
2218
0
  CURLcode result = CURLE_OK;
2219
0
  CURLMcode rc = CURLM_OK;
2220
0
  DEBUGASSERT(data->conn);
2221
  /* if both rates are within spec, resume transfer */
2222
0
  if(Curl_pgrsUpdate(data))
2223
0
    result = CURLE_ABORTED_BY_CALLBACK;
2224
0
  else
2225
0
    result = Curl_speedcheck(data, *nowp);
2226
2227
0
  if(result) {
2228
0
    if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
2229
0
       result != CURLE_HTTP2_STREAM)
2230
0
      streamclose(data->conn, "Transfer returned error");
2231
2232
0
    multi_posttransfer(data);
2233
0
    multi_done(data, result, TRUE);
2234
0
  }
2235
0
  else {
2236
0
    if(!mspeed_check(data, nowp))
2237
0
      rc = CURLM_CALL_MULTI_PERFORM;
2238
0
  }
2239
0
  *resultp = result;
2240
0
  return rc;
2241
0
}
2242
2243
static CURLMcode state_resolving(struct Curl_multi *multi,
2244
                                 struct Curl_easy *data,
2245
                                 bool *stream_errorp,
2246
                                 CURLcode *resultp)
2247
0
{
2248
0
  struct Curl_dns_entry *dns = NULL;
2249
0
  CURLcode result;
2250
0
  CURLMcode rc = CURLM_OK;
2251
2252
0
  result = Curl_resolv_check(data, &dns);
2253
0
  CURL_TRC_DNS(data, "Curl_resolv_check() -> %d, %s",
2254
0
               result, dns ? "found" : "missing");
2255
  /* Update sockets here, because the socket(s) may have been closed and the
2256
     application thus needs to be told, even if it is likely that the same
2257
     socket(s) will again be used further down. If the name has not yet been
2258
     resolved, it is likely that new sockets have been opened in an attempt to
2259
     contact another resolver. */
2260
0
  rc = Curl_multi_ev_assess_xfer(multi, data);
2261
0
  if(rc)
2262
0
    return rc;
2263
2264
0
  if(dns) {
2265
0
    bool connected;
2266
    /* Perform the next step in the connection phase, and then move on to the
2267
       WAITCONNECT state */
2268
0
    result = Curl_once_resolved(data, dns, &connected);
2269
2270
0
    if(result)
2271
      /* if Curl_once_resolved() returns failure, the connection struct is
2272
         already freed and gone */
2273
0
      data->conn = NULL; /* no more connection */
2274
0
    else {
2275
      /* call again please so that we get the next socket setup */
2276
0
      rc = CURLM_CALL_MULTI_PERFORM;
2277
0
      if(connected)
2278
0
        multistate(data, MSTATE_PROTOCONNECT);
2279
0
      else {
2280
0
        multistate(data, MSTATE_CONNECTING);
2281
0
      }
2282
0
    }
2283
0
  }
2284
2285
0
  if(result)
2286
    /* failure detected */
2287
0
    *stream_errorp = TRUE;
2288
2289
0
  *resultp = result;
2290
0
  return rc;
2291
0
}
2292
2293
static CURLMcode state_connect(struct Curl_multi *multi,
2294
                               struct Curl_easy *data,
2295
                               struct curltime *nowp,
2296
                               CURLcode *resultp)
2297
0
{
2298
  /* Connect. We want to get a connection identifier filled in. This state can
2299
     be entered from SETUP and from PENDING. */
2300
0
  bool connected;
2301
0
  bool async;
2302
0
  CURLMcode rc = CURLM_OK;
2303
0
  CURLcode result = Curl_connect(data, &async, &connected);
2304
0
  if(CURLE_NO_CONNECTION_AVAILABLE == result) {
2305
    /* There was no connection available. We will go to the pending state and
2306
       wait for an available connection. */
2307
0
    multistate(data, MSTATE_PENDING);
2308
    /* move from process to pending set */
2309
0
    Curl_uint_bset_remove(&multi->process, data->mid);
2310
0
    Curl_uint_bset_remove(&multi->dirty, data->mid);
2311
0
    Curl_uint_bset_add(&multi->pending, data->mid);
2312
0
    *resultp = CURLE_OK;
2313
0
    return rc;
2314
0
  }
2315
0
  else
2316
0
    process_pending_handles(data->multi);
2317
2318
0
  if(!result) {
2319
0
    *nowp = Curl_pgrsTime(data, TIMER_POSTQUEUE);
2320
0
    if(async)
2321
      /* We are now waiting for an asynchronous name lookup */
2322
0
      multistate(data, MSTATE_RESOLVING);
2323
0
    else {
2324
      /* after the connect has been sent off, go WAITCONNECT unless the
2325
         protocol connect is already done and we can go directly to WAITDO or
2326
         DO! */
2327
0
      rc = CURLM_CALL_MULTI_PERFORM;
2328
2329
0
      if(connected) {
2330
0
        if(!data->conn->bits.reuse &&
2331
0
           Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) {
2332
          /* new connection, can multiplex, wake pending handles */
2333
0
          process_pending_handles(data->multi);
2334
0
        }
2335
0
        multistate(data, MSTATE_PROTOCONNECT);
2336
0
      }
2337
0
      else {
2338
0
        multistate(data, MSTATE_CONNECTING);
2339
0
      }
2340
0
    }
2341
0
  }
2342
0
  *resultp = result;
2343
0
  return rc;
2344
0
}
2345
2346
static CURLMcode multi_runsingle(struct Curl_multi *multi,
2347
                                 struct curltime *nowp,
2348
                                 struct Curl_easy *data)
2349
0
{
2350
0
  struct Curl_message *msg = NULL;
2351
0
  bool connected;
2352
0
  bool protocol_connected = FALSE;
2353
0
  bool dophase_done = FALSE;
2354
0
  CURLMcode rc;
2355
0
  CURLcode result = CURLE_OK;
2356
0
  int control;
2357
2358
0
  if(!GOOD_EASY_HANDLE(data))
2359
0
    return CURLM_BAD_EASY_HANDLE;
2360
2361
0
  if(multi->dead) {
2362
    /* a multi-level callback returned error before, meaning every individual
2363
     transfer now has failed */
2364
0
    result = CURLE_ABORTED_BY_CALLBACK;
2365
0
    multi_posttransfer(data);
2366
0
    multi_done(data, result, FALSE);
2367
0
    multistate(data, MSTATE_COMPLETED);
2368
0
  }
2369
2370
0
  multi_warn_debug(multi, data);
2371
2372
  /* transfer runs now, clear the dirty bit. This may be set
2373
   * again during processing, triggering a re-run later. */
2374
0
  Curl_uint_bset_remove(&multi->dirty, data->mid);
2375
2376
0
  do {
2377
    /* A "stream" here is a logical stream if the protocol can handle that
2378
       (HTTP/2), or the full connection for older protocols */
2379
0
    bool stream_error = FALSE;
2380
0
    rc = CURLM_OK;
2381
2382
0
    if(multi_ischanged(multi, TRUE)) {
2383
0
      CURL_TRC_M(data, "multi changed, check CONNECT_PEND queue");
2384
0
      process_pending_handles(multi); /* multiplexed */
2385
0
    }
2386
2387
0
    if(data->mstate > MSTATE_CONNECT &&
2388
0
       data->mstate < MSTATE_COMPLETED) {
2389
      /* Make sure we set the connection's current owner */
2390
0
      DEBUGASSERT(data->conn);
2391
0
      if(!data->conn)
2392
0
        return CURLM_INTERNAL_ERROR;
2393
0
    }
2394
2395
    /* Wait for the connect state as only then is the start time stored, but
2396
       we must not check already completed handles */
2397
0
    if((data->mstate >= MSTATE_CONNECT) && (data->mstate < MSTATE_COMPLETED) &&
2398
0
       multi_handle_timeout(data, nowp, &stream_error, &result))
2399
      /* Skip the statemachine and go directly to error handling section. */
2400
0
      goto statemachine_end;
2401
2402
0
    switch(data->mstate) {
2403
0
    case MSTATE_INIT:
2404
      /* Transitional state. init this transfer. A handle never comes back to
2405
         this state. */
2406
0
      result = Curl_pretransfer(data);
2407
0
      if(result)
2408
0
        break;
2409
2410
      /* after init, go SETUP */
2411
0
      multistate(data, MSTATE_SETUP);
2412
0
      (void)Curl_pgrsTime(data, TIMER_STARTOP);
2413
0
      FALLTHROUGH();
2414
2415
0
    case MSTATE_SETUP:
2416
      /* Transitional state. Setup things for a new transfer. The handle
2417
         can come back to this state on a redirect. */
2418
0
      *nowp = Curl_pgrsTime(data, TIMER_STARTSINGLE);
2419
0
      if(data->set.timeout)
2420
0
        Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT);
2421
0
      if(data->set.connecttimeout)
2422
        /* Since a connection might go to pending and back to CONNECT several
2423
           times before it actually takes off, we need to set the timeout once
2424
           in SETUP before we enter CONNECT the first time. */
2425
0
        Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT);
2426
2427
0
      multistate(data, MSTATE_CONNECT);
2428
0
      FALLTHROUGH();
2429
2430
0
    case MSTATE_CONNECT:
2431
0
      rc = state_connect(multi, data, nowp, &result);
2432
0
      break;
2433
2434
0
    case MSTATE_RESOLVING:
2435
      /* awaiting an asynch name resolve to complete */
2436
0
      rc = state_resolving(multi, data, &stream_error, &result);
2437
0
      break;
2438
2439
0
#ifndef CURL_DISABLE_HTTP
2440
0
    case MSTATE_TUNNELING:
2441
      /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
2442
0
      DEBUGASSERT(data->conn);
2443
0
      result = Curl_http_connect(data, &protocol_connected);
2444
0
      if(!result) {
2445
0
        rc = CURLM_CALL_MULTI_PERFORM;
2446
        /* initiate protocol connect phase */
2447
0
        multistate(data, MSTATE_PROTOCONNECT);
2448
0
      }
2449
0
      else
2450
0
        stream_error = TRUE;
2451
0
      break;
2452
0
#endif
2453
2454
0
    case MSTATE_CONNECTING:
2455
      /* awaiting a completion of an asynch TCP connect */
2456
0
      DEBUGASSERT(data->conn);
2457
0
      if(!Curl_xfer_recv_is_paused(data)) {
2458
0
        result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &connected);
2459
0
        if(connected && !result) {
2460
0
          if(!data->conn->bits.reuse &&
2461
0
             Curl_conn_is_multiplex(data->conn, FIRSTSOCKET)) {
2462
            /* new connection, can multiplex, wake pending handles */
2463
0
            process_pending_handles(data->multi);
2464
0
          }
2465
0
          rc = CURLM_CALL_MULTI_PERFORM;
2466
0
          multistate(data, MSTATE_PROTOCONNECT);
2467
0
        }
2468
0
        else if(result) {
2469
          /* failure detected */
2470
0
          multi_posttransfer(data);
2471
0
          multi_done(data, result, TRUE);
2472
0
          stream_error = TRUE;
2473
0
          break;
2474
0
        }
2475
0
      }
2476
0
      break;
2477
2478
0
    case MSTATE_PROTOCONNECT:
2479
0
      if(!result && data->conn->bits.reuse) {
2480
        /* ftp seems to hang when protoconnect on reused connection since we
2481
         * handle PROTOCONNECT in general inside the filers, it seems wrong to
2482
         * restart this on a reused connection.
2483
         */
2484
0
        multistate(data, MSTATE_DO);
2485
0
        rc = CURLM_CALL_MULTI_PERFORM;
2486
0
        break;
2487
0
      }
2488
0
      if(!result)
2489
0
        result = protocol_connect(data, &protocol_connected);
2490
0
      if(!result && !protocol_connected) {
2491
        /* switch to waiting state */
2492
0
        multistate(data, MSTATE_PROTOCONNECTING);
2493
0
        rc = CURLM_CALL_MULTI_PERFORM;
2494
0
      }
2495
0
      else if(!result) {
2496
        /* protocol connect has completed, go WAITDO or DO */
2497
0
        multistate(data, MSTATE_DO);
2498
0
        rc = CURLM_CALL_MULTI_PERFORM;
2499
0
      }
2500
0
      else {
2501
        /* failure detected */
2502
0
        multi_posttransfer(data);
2503
0
        multi_done(data, result, TRUE);
2504
0
        stream_error = TRUE;
2505
0
      }
2506
0
      break;
2507
2508
0
    case MSTATE_PROTOCONNECTING:
2509
      /* protocol-specific connect phase */
2510
0
      result = protocol_connecting(data, &protocol_connected);
2511
0
      if(!result && protocol_connected) {
2512
        /* after the connect has completed, go WAITDO or DO */
2513
0
        multistate(data, MSTATE_DO);
2514
0
        rc = CURLM_CALL_MULTI_PERFORM;
2515
0
      }
2516
0
      else if(result) {
2517
        /* failure detected */
2518
0
        multi_posttransfer(data);
2519
0
        multi_done(data, result, TRUE);
2520
0
        stream_error = TRUE;
2521
0
      }
2522
0
      break;
2523
2524
0
    case MSTATE_DO:
2525
0
      rc = state_do(data, &stream_error, &result);
2526
0
      break;
2527
2528
0
    case MSTATE_DOING:
2529
      /* we continue DOING until the DO phase is complete */
2530
0
      DEBUGASSERT(data->conn);
2531
0
      result = protocol_doing(data, &dophase_done);
2532
0
      if(!result) {
2533
0
        if(dophase_done) {
2534
          /* after DO, go DO_DONE or DO_MORE */
2535
0
          multistate(data, data->conn->bits.do_more ?
2536
0
                     MSTATE_DOING_MORE : MSTATE_DID);
2537
0
          rc = CURLM_CALL_MULTI_PERFORM;
2538
0
        } /* dophase_done */
2539
0
      }
2540
0
      else {
2541
        /* failure detected */
2542
0
        multi_posttransfer(data);
2543
0
        multi_done(data, result, FALSE);
2544
0
        stream_error = TRUE;
2545
0
      }
2546
0
      break;
2547
2548
0
    case MSTATE_DOING_MORE:
2549
      /*
2550
       * When we are connected, DOING MORE and then go DID
2551
       */
2552
0
      DEBUGASSERT(data->conn);
2553
0
      result = multi_do_more(data, &control);
2554
2555
0
      if(!result) {
2556
0
        if(control) {
2557
          /* if positive, advance to DO_DONE
2558
             if negative, go back to DOING */
2559
0
          multistate(data, control == 1 ?
2560
0
                     MSTATE_DID : MSTATE_DOING);
2561
0
          rc = CURLM_CALL_MULTI_PERFORM;
2562
0
        }
2563
        /* else
2564
           stay in DO_MORE */
2565
0
      }
2566
0
      else {
2567
        /* failure detected */
2568
0
        multi_posttransfer(data);
2569
0
        multi_done(data, result, FALSE);
2570
0
        stream_error = TRUE;
2571
0
      }
2572
0
      break;
2573
2574
0
    case MSTATE_DID:
2575
0
      DEBUGASSERT(data->conn);
2576
0
      if(data->conn->bits.multiplex)
2577
        /* Check if we can move pending requests to send pipe */
2578
0
        process_pending_handles(multi); /*  multiplexed */
2579
2580
      /* Only perform the transfer if there is a good socket to work with.
2581
         Having both BAD is a signal to skip immediately to DONE */
2582
0
      if(CONN_SOCK_IDX_VALID(data->conn->recv_idx) ||
2583
0
         CONN_SOCK_IDX_VALID(data->conn->send_idx))
2584
0
        multistate(data, MSTATE_PERFORMING);
2585
0
      else {
2586
0
#ifndef CURL_DISABLE_FTP
2587
0
        if(data->state.wildcardmatch &&
2588
0
           ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) {
2589
0
          data->wildcard->state = CURLWC_DONE;
2590
0
        }
2591
0
#endif
2592
0
        multistate(data, MSTATE_DONE);
2593
0
      }
2594
0
      rc = CURLM_CALL_MULTI_PERFORM;
2595
0
      break;
2596
2597
0
    case MSTATE_RATELIMITING: /* limit-rate exceeded in either direction */
2598
0
      rc = state_ratelimiting(data, nowp, &result);
2599
0
      break;
2600
2601
0
    case MSTATE_PERFORMING:
2602
0
      rc = state_performing(data, nowp, &stream_error, &result);
2603
0
      break;
2604
2605
0
    case MSTATE_DONE:
2606
      /* this state is highly transient, so run another loop after this */
2607
0
      rc = CURLM_CALL_MULTI_PERFORM;
2608
2609
0
      if(data->conn) {
2610
0
        CURLcode res;
2611
2612
        /* post-transfer command */
2613
0
        res = multi_done(data, result, FALSE);
2614
2615
        /* allow a previously set error code take precedence */
2616
0
        if(!result)
2617
0
          result = res;
2618
0
      }
2619
2620
0
#ifndef CURL_DISABLE_FTP
2621
0
      if(data->state.wildcardmatch) {
2622
0
        if(data->wildcard->state != CURLWC_DONE) {
2623
          /* if a wildcard is set and we are not ending -> lets start again
2624
             with MSTATE_INIT */
2625
0
          multistate(data, MSTATE_INIT);
2626
0
          break;
2627
0
        }
2628
0
      }
2629
0
#endif
2630
      /* after we have DONE what we are supposed to do, go COMPLETED, and
2631
         it does not matter what the multi_done() returned! */
2632
0
      multistate(data, MSTATE_COMPLETED);
2633
0
      break;
2634
2635
0
    case MSTATE_COMPLETED:
2636
0
      break;
2637
2638
0
    case MSTATE_PENDING:
2639
0
    case MSTATE_MSGSENT:
2640
      /* handles in these states should NOT be in this list */
2641
0
      break;
2642
2643
0
    default:
2644
0
      return CURLM_INTERNAL_ERROR;
2645
0
    }
2646
2647
0
    if(data->mstate >= MSTATE_CONNECT &&
2648
0
       data->mstate < MSTATE_DO &&
2649
0
       rc != CURLM_CALL_MULTI_PERFORM &&
2650
0
       !multi_ischanged(multi, FALSE)) {
2651
      /* We now handle stream timeouts if and only if this will be the last
2652
       * loop iteration. We only check this on the last iteration to ensure
2653
       * that if we know we have additional work to do immediately
2654
       * (i.e. CURLM_CALL_MULTI_PERFORM == TRUE) then we should do that before
2655
       * declaring the connection timed out as we may almost have a completed
2656
       * connection. */
2657
0
      multi_handle_timeout(data, nowp, &stream_error, &result);
2658
0
    }
2659
2660
0
statemachine_end:
2661
2662
0
    if(data->mstate < MSTATE_COMPLETED) {
2663
0
      if(result) {
2664
        /*
2665
         * If an error was returned, and we are not in completed state now,
2666
         * then we go to completed and consider this transfer aborted.
2667
         */
2668
2669
        /* NOTE: no attempt to disconnect connections must be made
2670
           in the case blocks above - cleanup happens only here */
2671
2672
        /* Check if we can move pending requests to send pipe */
2673
0
        process_pending_handles(multi); /* connection */
2674
2675
0
        if(data->conn) {
2676
0
          if(stream_error) {
2677
            /* Do not attempt to send data over a connection that timed out */
2678
0
            bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
2679
0
            struct connectdata *conn = data->conn;
2680
2681
            /* This is where we make sure that the conn pointer is reset.
2682
               We do not have to do this in every case block above where a
2683
               failure is detected */
2684
0
            Curl_detach_connection(data);
2685
0
            Curl_conn_terminate(data, conn, dead_connection);
2686
0
          }
2687
0
        }
2688
0
        else if(data->mstate == MSTATE_CONNECT) {
2689
          /* Curl_connect() failed */
2690
0
          multi_posttransfer(data);
2691
0
          Curl_pgrsUpdate_nometer(data);
2692
0
        }
2693
2694
0
        multistate(data, MSTATE_COMPLETED);
2695
0
        rc = CURLM_CALL_MULTI_PERFORM;
2696
0
      }
2697
      /* if there is still a connection to use, call the progress function */
2698
0
      else if(data->conn && Curl_pgrsUpdate(data)) {
2699
        /* aborted due to progress callback return code must close the
2700
           connection */
2701
0
        result = CURLE_ABORTED_BY_CALLBACK;
2702
0
        streamclose(data->conn, "Aborted by callback");
2703
2704
        /* if not yet in DONE state, go there, otherwise COMPLETED */
2705
0
        multistate(data, (data->mstate < MSTATE_DONE) ?
2706
0
                   MSTATE_DONE : MSTATE_COMPLETED);
2707
0
        rc = CURLM_CALL_MULTI_PERFORM;
2708
0
      }
2709
0
    }
2710
2711
0
    if(MSTATE_COMPLETED == data->mstate) {
2712
0
      if(data->master_mid != UINT_MAX) {
2713
        /* A sub transfer, not for msgsent to application */
2714
0
        struct Curl_easy *mdata;
2715
2716
0
        CURL_TRC_M(data, "sub xfer done for master %u", data->master_mid);
2717
0
        mdata = Curl_multi_get_easy(multi, data->master_mid);
2718
0
        if(mdata) {
2719
0
          if(mdata->sub_xfer_done)
2720
0
            mdata->sub_xfer_done(mdata, data, result);
2721
0
          else
2722
0
            CURL_TRC_M(data, "master easy %u without sub_xfer_done callback.",
2723
0
                       data->master_mid);
2724
0
        }
2725
0
        else {
2726
0
          CURL_TRC_M(data, "master easy %u already gone.", data->master_mid);
2727
0
        }
2728
0
      }
2729
0
      else {
2730
        /* now fill in the Curl_message with this info */
2731
0
        msg = &data->msg;
2732
2733
0
        msg->extmsg.msg = CURLMSG_DONE;
2734
0
        msg->extmsg.easy_handle = data;
2735
0
        msg->extmsg.data.result = result;
2736
2737
0
        multi_addmsg(multi, msg);
2738
0
        DEBUGASSERT(!data->conn);
2739
0
      }
2740
0
      multistate(data, MSTATE_MSGSENT);
2741
2742
      /* remove from the other sets, add to msgsent */
2743
0
      Curl_uint_bset_remove(&multi->process, data->mid);
2744
0
      Curl_uint_bset_remove(&multi->dirty, data->mid);
2745
0
      Curl_uint_bset_remove(&multi->pending, data->mid);
2746
0
      Curl_uint_bset_add(&multi->msgsent, data->mid);
2747
0
      --multi->xfers_alive;
2748
0
      return CURLM_OK;
2749
0
    }
2750
0
  } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
2751
2752
0
  data->result = result;
2753
0
  return rc;
2754
0
}
2755
2756
2757
CURLMcode curl_multi_perform(CURLM *m, int *running_handles)
2758
0
{
2759
0
  CURLMcode returncode = CURLM_OK;
2760
0
  struct Curl_tree *t = NULL;
2761
0
  struct curltime now = curlx_now();
2762
0
  struct Curl_multi *multi = m;
2763
0
  unsigned int mid;
2764
0
  SIGPIPE_VARIABLE(pipe_st);
2765
2766
0
  if(!GOOD_MULTI_HANDLE(multi))
2767
0
    return CURLM_BAD_HANDLE;
2768
2769
0
  if(multi->in_callback)
2770
0
    return CURLM_RECURSIVE_API_CALL;
2771
2772
0
  if(multi->in_ntfy_callback)
2773
0
    return CURLM_RECURSIVE_API_CALL;
2774
2775
0
  sigpipe_init(&pipe_st);
2776
0
  if(Curl_uint_bset_first(&multi->process, &mid)) {
2777
0
    CURL_TRC_M(multi->admin, "multi_perform(running=%u)",
2778
0
               Curl_multi_xfers_running(multi));
2779
0
    do {
2780
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
2781
0
      CURLMcode result;
2782
0
      if(!data) {
2783
0
        DEBUGASSERT(0);
2784
0
        Curl_uint_bset_remove(&multi->process, mid);
2785
0
        Curl_uint_bset_remove(&multi->dirty, mid);
2786
0
        continue;
2787
0
      }
2788
0
      if(data != multi->admin) {
2789
        /* admin handle is processed below */
2790
0
        sigpipe_apply(data, &pipe_st);
2791
0
        result = multi_runsingle(multi, &now, data);
2792
0
        if(result)
2793
0
          returncode = result;
2794
0
      }
2795
0
    }
2796
0
    while(Curl_uint_bset_next(&multi->process, mid, &mid));
2797
0
  }
2798
2799
0
  sigpipe_apply(multi->admin, &pipe_st);
2800
0
  Curl_cshutdn_perform(&multi->cshutdn, multi->admin, CURL_SOCKET_TIMEOUT);
2801
0
  sigpipe_restore(&pipe_st);
2802
2803
0
  if(multi_ischanged(m, TRUE))
2804
0
    process_pending_handles(m);
2805
2806
0
  if(!returncode)
2807
0
    returncode = Curl_mntfy_dispatch_all(multi);
2808
2809
  /*
2810
   * Simply remove all expired timers from the splay since handles are dealt
2811
   * with unconditionally by this function and curl_multi_timeout() requires
2812
   * that already passed/handled expire times are removed from the splay.
2813
   *
2814
   * It is important that the 'now' value is set at the entry of this function
2815
   * and not for the current time as it may have ticked a little while since
2816
   * then and then we risk this loop to remove timers that actually have not
2817
   * been handled!
2818
   */
2819
0
  do {
2820
0
    multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
2821
0
    if(t) {
2822
      /* the removed may have another timeout in queue */
2823
0
      struct Curl_easy *data = Curl_splayget(t);
2824
0
      (void)add_next_timeout(now, multi, data);
2825
0
      if(data->mstate == MSTATE_PENDING) {
2826
0
        bool stream_unused;
2827
0
        CURLcode result_unused;
2828
0
        if(multi_handle_timeout(data, &now, &stream_unused, &result_unused)) {
2829
0
          infof(data, "PENDING handle timeout");
2830
0
          move_pending_to_connect(multi, data);
2831
0
        }
2832
0
      }
2833
0
    }
2834
0
  } while(t);
2835
2836
0
  if(running_handles) {
2837
0
    unsigned int running = Curl_multi_xfers_running(multi);
2838
0
    *running_handles = (running < INT_MAX) ? (int)running : INT_MAX;
2839
0
  }
2840
2841
0
  if(CURLM_OK >= returncode)
2842
0
    returncode = Curl_update_timer(multi);
2843
2844
0
  return returncode;
2845
0
}
2846
2847
CURLMcode curl_multi_cleanup(CURLM *m)
2848
0
{
2849
0
  struct Curl_multi *multi = m;
2850
0
  if(GOOD_MULTI_HANDLE(multi)) {
2851
0
    void *entry;
2852
0
    unsigned int mid;
2853
0
    if(multi->in_callback)
2854
0
      return CURLM_RECURSIVE_API_CALL;
2855
0
    if(multi->in_ntfy_callback)
2856
0
      return CURLM_RECURSIVE_API_CALL;
2857
2858
    /* First remove all remaining easy handles,
2859
     * close internal ones. admin handle is special */
2860
0
    if(Curl_uint_tbl_first(&multi->xfers, &mid, &entry)) {
2861
0
      do {
2862
0
        struct Curl_easy *data = entry;
2863
0
        if(!GOOD_EASY_HANDLE(data))
2864
0
          return CURLM_BAD_HANDLE;
2865
2866
#ifdef DEBUGBUILD
2867
        if(mid != data->mid) {
2868
          CURL_TRC_M(data, "multi_cleanup: still present with mid=%u, "
2869
                     "but unexpected data->mid=%u\n", mid, data->mid);
2870
          DEBUGASSERT(0);
2871
        }
2872
#endif
2873
2874
0
        if(data == multi->admin)
2875
0
          continue;
2876
2877
0
        if(!data->state.done && data->conn)
2878
          /* if DONE was never called for this handle */
2879
0
          (void)multi_done(data, CURLE_OK, TRUE);
2880
2881
0
        data->multi = NULL; /* clear the association */
2882
0
        Curl_uint_tbl_remove(&multi->xfers, mid);
2883
0
        data->mid = UINT_MAX;
2884
2885
#ifdef USE_LIBPSL
2886
        if(data->psl == &multi->psl)
2887
          data->psl = NULL;
2888
#endif
2889
0
        if(data->state.internal)
2890
0
          Curl_close(&data);
2891
0
      }
2892
0
      while(Curl_uint_tbl_next(&multi->xfers, mid, &mid, &entry));
2893
0
    }
2894
2895
0
    Curl_cpool_destroy(&multi->cpool);
2896
0
    Curl_cshutdn_destroy(&multi->cshutdn, multi->admin);
2897
0
    if(multi->admin) {
2898
0
      CURL_TRC_M(multi->admin, "multi_cleanup, closing admin handle, done");
2899
0
      multi->admin->multi = NULL;
2900
0
      Curl_uint_tbl_remove(&multi->xfers, multi->admin->mid);
2901
0
      Curl_close(&multi->admin);
2902
0
    }
2903
2904
0
    multi->magic = 0; /* not good anymore */
2905
2906
0
    Curl_multi_ev_cleanup(multi);
2907
0
    Curl_hash_destroy(&multi->proto_hash);
2908
0
    Curl_dnscache_destroy(&multi->dnscache);
2909
0
    Curl_psl_destroy(&multi->psl);
2910
0
#ifdef USE_SSL
2911
0
    Curl_ssl_scache_destroy(multi->ssl_scache);
2912
0
#endif
2913
2914
#ifdef USE_WINSOCK
2915
    WSACloseEvent(multi->wsa_event);
2916
#else
2917
0
#ifdef ENABLE_WAKEUP
2918
0
    wakeup_close(multi->wakeup_pair[0]);
2919
#ifndef USE_EVENTFD
2920
    wakeup_close(multi->wakeup_pair[1]);
2921
#endif
2922
0
#endif
2923
0
#endif
2924
2925
0
    multi_xfer_bufs_free(multi);
2926
0
    Curl_mntfy_cleanup(multi);
2927
#ifdef DEBUGBUILD
2928
    if(Curl_uint_tbl_count(&multi->xfers)) {
2929
      multi_xfer_tbl_dump(multi);
2930
      DEBUGASSERT(0);
2931
    }
2932
#endif
2933
0
    Curl_uint_bset_destroy(&multi->process);
2934
0
    Curl_uint_bset_destroy(&multi->dirty);
2935
0
    Curl_uint_bset_destroy(&multi->pending);
2936
0
    Curl_uint_bset_destroy(&multi->msgsent);
2937
0
    Curl_uint_tbl_destroy(&multi->xfers);
2938
0
    free(multi);
2939
2940
0
    return CURLM_OK;
2941
0
  }
2942
0
  return CURLM_BAD_HANDLE;
2943
0
}
2944
2945
/*
2946
 * curl_multi_info_read()
2947
 *
2948
 * This function is the primary way for a multi/multi_socket application to
2949
 * figure out if a transfer has ended. We MUST make this function as fast as
2950
 * possible as it will be polled frequently and we MUST NOT scan any lists in
2951
 * here to figure out things. We must scale fine to thousands of handles and
2952
 * beyond. The current design is fully O(1).
2953
 */
2954
2955
CURLMsg *curl_multi_info_read(CURLM *m, int *msgs_in_queue)
2956
0
{
2957
0
  struct Curl_message *msg;
2958
0
  struct Curl_multi *multi = m;
2959
2960
0
  *msgs_in_queue = 0; /* default to none */
2961
2962
0
  if(GOOD_MULTI_HANDLE(multi) &&
2963
0
     !multi->in_callback &&
2964
0
     Curl_llist_count(&multi->msglist)) {
2965
    /* there is one or more messages in the list */
2966
0
    struct Curl_llist_node *e;
2967
2968
    /* extract the head of the list to return */
2969
0
    e = Curl_llist_head(&multi->msglist);
2970
2971
0
    msg = Curl_node_elem(e);
2972
2973
    /* remove the extracted entry */
2974
0
    Curl_node_remove(e);
2975
2976
0
    *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
2977
2978
0
    return &msg->extmsg;
2979
0
  }
2980
0
  return NULL;
2981
0
}
2982
2983
2984
void Curl_multi_will_close(struct Curl_easy *data, curl_socket_t s)
2985
0
{
2986
0
  if(data) {
2987
0
    struct Curl_multi *multi = data->multi;
2988
0
    if(multi) {
2989
0
      CURL_TRC_M(data, "Curl_multi_will_close fd=%" FMT_SOCKET_T, s);
2990
0
      Curl_multi_ev_socket_done(multi, data, s);
2991
0
    }
2992
0
  }
2993
0
}
2994
2995
/*
2996
 * add_next_timeout()
2997
 *
2998
 * Each Curl_easy has a list of timeouts. The add_next_timeout() is called
2999
 * when it has just been removed from the splay tree because the timeout has
3000
 * expired. This function is then to advance in the list to pick the next
3001
 * timeout to use (skip the already expired ones) and add this node back to
3002
 * the splay tree again.
3003
 *
3004
 * The splay tree only has each sessionhandle as a single node and the nearest
3005
 * timeout is used to sort it on.
3006
 */
3007
static CURLMcode add_next_timeout(struct curltime now,
3008
                                  struct Curl_multi *multi,
3009
                                  struct Curl_easy *d)
3010
0
{
3011
0
  struct curltime *tv = &d->state.expiretime;
3012
0
  struct Curl_llist *list = &d->state.timeoutlist;
3013
0
  struct Curl_llist_node *e;
3014
3015
  /* move over the timeout list for this specific handle and remove all
3016
     timeouts that are now passed tense and store the next pending
3017
     timeout in *tv */
3018
0
  for(e = Curl_llist_head(list); e;) {
3019
0
    struct Curl_llist_node *n = Curl_node_next(e);
3020
0
    struct time_node *node = Curl_node_elem(e);
3021
0
    timediff_t diff = curlx_timediff_us(node->time, now);
3022
0
    if(diff <= 0)
3023
      /* remove outdated entry */
3024
0
      Curl_node_remove(e);
3025
0
    else
3026
      /* the list is sorted so get out on the first mismatch */
3027
0
      break;
3028
0
    e = n;
3029
0
  }
3030
0
  e = Curl_llist_head(list);
3031
0
  if(!e) {
3032
    /* clear the expire times within the handles that we remove from the
3033
       splay tree */
3034
0
    tv->tv_sec = 0;
3035
0
    tv->tv_usec = 0;
3036
0
  }
3037
0
  else {
3038
0
    struct time_node *node = Curl_node_elem(e);
3039
    /* copy the first entry to 'tv' */
3040
0
    memcpy(tv, &node->time, sizeof(*tv));
3041
3042
    /* Insert this node again into the splay. Keep the timer in the list in
3043
       case we need to recompute future timers. */
3044
0
    multi->timetree = Curl_splayinsert(*tv, multi->timetree,
3045
0
                                       &d->state.timenode);
3046
0
  }
3047
0
  return CURLM_OK;
3048
0
}
3049
3050
struct multi_run_ctx {
3051
  struct Curl_multi *multi;
3052
  struct curltime now;
3053
  size_t run_xfers;
3054
  SIGPIPE_MEMBER(pipe_st);
3055
  bool run_cpool;
3056
};
3057
3058
static void multi_mark_expired_as_dirty(struct multi_run_ctx *mrc)
3059
0
{
3060
0
  struct Curl_multi *multi = mrc->multi;
3061
0
  struct Curl_easy *data = NULL;
3062
0
  struct Curl_tree *t = NULL;
3063
3064
  /*
3065
   * The loop following here will go on as long as there are expire-times left
3066
   * to process (compared to mrc->now) in the splay and 'data' will be
3067
   * re-assigned for every expired handle we deal with.
3068
   */
3069
0
  while(1) {
3070
    /* Check if there is one (more) expired timer to deal with! This function
3071
       extracts a matching node if there is one */
3072
0
    multi->timetree = Curl_splaygetbest(mrc->now, multi->timetree, &t);
3073
0
    if(!t)
3074
0
      return;
3075
3076
0
    data = Curl_splayget(t); /* assign this for next loop */
3077
0
    if(!data)
3078
0
      continue;
3079
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
3080
0
    if(CURL_TRC_TIMER_is_verbose(data)) {
3081
0
      struct Curl_llist_node *e = Curl_llist_head(&data->state.timeoutlist);
3082
0
      if(e) {
3083
0
        struct time_node *n = Curl_node_elem(e);
3084
0
        CURL_TRC_TIMER(data, n->eid, "has expired");
3085
0
      }
3086
0
    }
3087
0
#endif
3088
0
    (void)add_next_timeout(mrc->now, multi, data);
3089
0
    Curl_multi_mark_dirty(data);
3090
0
  }
3091
0
}
3092
3093
static CURLMcode multi_run_dirty(struct multi_run_ctx *mrc)
3094
0
{
3095
0
  struct Curl_multi *multi = mrc->multi;
3096
0
  CURLMcode result = CURLM_OK;
3097
0
  unsigned int mid;
3098
3099
0
  if(Curl_uint_bset_first(&multi->dirty, &mid)) {
3100
0
    do {
3101
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
3102
0
      if(data) {
3103
0
        CURL_TRC_M(data, "multi_run_dirty");
3104
3105
0
        if(data == multi->admin) {
3106
0
          Curl_uint_bset_remove(&multi->dirty, mid);
3107
0
          mrc->run_cpool = TRUE;
3108
0
          continue;
3109
0
        }
3110
0
        else if(!Curl_uint_bset_contains(&multi->process, mid)) {
3111
          /* We are no longer processing this transfer */
3112
0
          Curl_uint_bset_remove(&multi->dirty, mid);
3113
0
          continue;
3114
0
        }
3115
3116
0
        mrc->run_xfers++;
3117
0
        sigpipe_apply(data, &mrc->pipe_st);
3118
        /* runsingle() clears the dirty mid */
3119
0
        result = multi_runsingle(multi, &mrc->now, data);
3120
3121
0
        if(CURLM_OK >= result) {
3122
          /* reassess event handling of data */
3123
0
          result = Curl_multi_ev_assess_xfer(multi, data);
3124
0
          if(result)
3125
0
            goto out;
3126
0
        }
3127
0
      }
3128
0
      else {
3129
0
        CURL_TRC_M(multi->admin, "multi_run_dirty, %u no longer found", mid);
3130
0
        Curl_uint_bset_remove(&multi->dirty, mid);
3131
0
      }
3132
0
    }
3133
0
    while(Curl_uint_bset_next(&multi->dirty, mid, &mid));
3134
0
  }
3135
3136
0
out:
3137
0
  return result;
3138
0
}
3139
3140
static CURLMcode multi_socket(struct Curl_multi *multi,
3141
                              bool checkall,
3142
                              curl_socket_t s,
3143
                              int ev_bitmask,
3144
                              int *running_handles)
3145
0
{
3146
0
  CURLMcode result = CURLM_OK;
3147
0
  struct multi_run_ctx mrc;
3148
3149
0
  (void)ev_bitmask;
3150
0
  memset(&mrc, 0, sizeof(mrc));
3151
0
  mrc.multi = multi;
3152
0
  mrc.now = curlx_now();
3153
0
  sigpipe_init(&mrc.pipe_st);
3154
3155
0
  if(checkall) {
3156
    /* *perform() deals with running_handles on its own */
3157
0
    result = curl_multi_perform(multi, running_handles);
3158
3159
0
    if(result != CURLM_BAD_HANDLE) {
3160
      /* Reassess event status of all active transfers */
3161
0
      result = Curl_multi_ev_assess_xfer_bset(multi, &multi->process);
3162
0
    }
3163
0
    mrc.run_cpool = TRUE;
3164
0
    goto out;
3165
0
  }
3166
3167
0
  if(s != CURL_SOCKET_TIMEOUT) {
3168
    /* Mark all transfers of that socket as dirty */
3169
0
    Curl_multi_ev_dirty_xfers(multi, s, &mrc.run_cpool);
3170
0
  }
3171
0
  else {
3172
    /* Asked to run due to time-out. Clear the 'last_expire_ts' variable to
3173
       force Curl_update_timer() to trigger a callback to the app again even
3174
       if the same timeout is still the one to run after this call. That
3175
       handles the case when the application asks libcurl to run the timeout
3176
       prematurely. */
3177
0
    memset(&multi->last_expire_ts, 0, sizeof(multi->last_expire_ts));
3178
0
    mrc.run_cpool = TRUE;
3179
0
  }
3180
3181
0
  multi_mark_expired_as_dirty(&mrc);
3182
0
  result = multi_run_dirty(&mrc);
3183
0
  if(result)
3184
0
    goto out;
3185
3186
0
  if(mrc.run_xfers) {
3187
    /* Running transfers takes time. With a new timestamp, we might catch
3188
     * other expires which are due now. Instead of telling the application
3189
     * to set a 0 timeout and call us again, we run them here.
3190
     * Do that only once or it might be unfair to transfers on other
3191
     * sockets. */
3192
0
    mrc.now = curlx_now();
3193
0
    multi_mark_expired_as_dirty(&mrc);
3194
0
    result = multi_run_dirty(&mrc);
3195
0
  }
3196
3197
0
out:
3198
0
  if(mrc.run_cpool) {
3199
0
    sigpipe_apply(multi->admin, &mrc.pipe_st);
3200
0
    Curl_cshutdn_perform(&multi->cshutdn, multi->admin, s);
3201
0
  }
3202
0
  sigpipe_restore(&mrc.pipe_st);
3203
3204
0
  if(multi_ischanged(multi, TRUE))
3205
0
    process_pending_handles(multi);
3206
3207
0
  if(!result)
3208
0
    result = Curl_mntfy_dispatch_all(multi);
3209
3210
0
  if(running_handles) {
3211
0
    unsigned int running = Curl_multi_xfers_running(multi);
3212
0
    *running_handles = (running < INT_MAX) ? (int)running : INT_MAX;
3213
0
  }
3214
3215
0
  if(CURLM_OK >= result)
3216
0
    result = Curl_update_timer(multi);
3217
0
  return result;
3218
0
}
3219
3220
#undef curl_multi_setopt
3221
CURLMcode curl_multi_setopt(CURLM *m,
3222
                            CURLMoption option, ...)
3223
0
{
3224
0
  CURLMcode res = CURLM_OK;
3225
0
  va_list param;
3226
0
  unsigned long uarg;
3227
0
  struct Curl_multi *multi = m;
3228
3229
0
  if(!GOOD_MULTI_HANDLE(multi))
3230
0
    return CURLM_BAD_HANDLE;
3231
3232
0
  if(multi->in_callback)
3233
0
    return CURLM_RECURSIVE_API_CALL;
3234
3235
0
  va_start(param, option);
3236
3237
0
  switch(option) {
3238
0
  case CURLMOPT_SOCKETFUNCTION:
3239
0
    multi->socket_cb = va_arg(param, curl_socket_callback);
3240
0
    break;
3241
0
  case CURLMOPT_SOCKETDATA:
3242
0
    multi->socket_userp = va_arg(param, void *);
3243
0
    break;
3244
0
  case CURLMOPT_PUSHFUNCTION:
3245
0
    multi->push_cb = va_arg(param, curl_push_callback);
3246
0
    break;
3247
0
  case CURLMOPT_PUSHDATA:
3248
0
    multi->push_userp = va_arg(param, void *);
3249
0
    break;
3250
0
  case CURLMOPT_PIPELINING:
3251
0
    multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX ? 1 : 0;
3252
0
    break;
3253
0
  case CURLMOPT_TIMERFUNCTION:
3254
0
    multi->timer_cb = va_arg(param, curl_multi_timer_callback);
3255
0
    break;
3256
0
  case CURLMOPT_TIMERDATA:
3257
0
    multi->timer_userp = va_arg(param, void *);
3258
0
    break;
3259
0
  case CURLMOPT_MAXCONNECTS:
3260
0
    uarg = va_arg(param, unsigned long);
3261
0
    if(uarg <= UINT_MAX)
3262
0
      multi->maxconnects = (unsigned int)uarg;
3263
0
    break;
3264
0
  case CURLMOPT_MAX_HOST_CONNECTIONS:
3265
0
    multi->max_host_connections = va_arg(param, long);
3266
0
    break;
3267
0
  case CURLMOPT_MAX_TOTAL_CONNECTIONS:
3268
0
    multi->max_total_connections = va_arg(param, long);
3269
0
    break;
3270
    /* options formerly used for pipelining */
3271
0
  case CURLMOPT_MAX_PIPELINE_LENGTH:
3272
0
    break;
3273
0
  case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
3274
0
    break;
3275
0
  case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
3276
0
    break;
3277
0
  case CURLMOPT_PIPELINING_SITE_BL:
3278
0
    break;
3279
0
  case CURLMOPT_PIPELINING_SERVER_BL:
3280
0
    break;
3281
0
  case CURLMOPT_MAX_CONCURRENT_STREAMS:
3282
0
    {
3283
0
      long streams = va_arg(param, long);
3284
0
      if((streams < 1) || (streams > INT_MAX))
3285
0
        streams = 100;
3286
0
      multi->max_concurrent_streams = (unsigned int)streams;
3287
0
    }
3288
0
    break;
3289
0
  case CURLMOPT_NETWORK_CHANGED: {
3290
0
    long val = va_arg(param, long);
3291
0
    if(val & CURLMNWC_CLEAR_DNS) {
3292
0
      Curl_dnscache_clear(multi->admin);
3293
0
    }
3294
0
    if(val & CURLMNWC_CLEAR_CONNS) {
3295
0
      Curl_cpool_nw_changed(multi->admin);
3296
0
    }
3297
0
    break;
3298
0
  }
3299
0
  case CURLMOPT_NOTIFYFUNCTION:
3300
0
    multi->ntfy.ntfy_cb = va_arg(param, curl_notify_callback);
3301
0
    break;
3302
0
  case CURLMOPT_NOTIFYDATA:
3303
0
    multi->ntfy.ntfy_cb_data = va_arg(param, void *);
3304
0
    break;
3305
0
  default:
3306
0
    res = CURLM_UNKNOWN_OPTION;
3307
0
    break;
3308
0
  }
3309
0
  va_end(param);
3310
0
  return res;
3311
0
}
3312
3313
/* we define curl_multi_socket() in the public multi.h header */
3314
#undef curl_multi_socket
3315
3316
CURLMcode curl_multi_socket(CURLM *m, curl_socket_t s, int *running_handles)
3317
0
{
3318
0
  struct Curl_multi *multi = m;
3319
0
  if(multi->in_callback)
3320
0
    return CURLM_RECURSIVE_API_CALL;
3321
0
  if(multi->in_ntfy_callback)
3322
0
    return CURLM_RECURSIVE_API_CALL;
3323
0
  return multi_socket(multi, FALSE, s, 0, running_handles);
3324
0
}
3325
3326
CURLMcode curl_multi_socket_action(CURLM *m, curl_socket_t s,
3327
                                   int ev_bitmask, int *running_handles)
3328
0
{
3329
0
  struct Curl_multi *multi = m;
3330
0
  if(multi->in_callback)
3331
0
    return CURLM_RECURSIVE_API_CALL;
3332
0
  if(multi->in_ntfy_callback)
3333
0
    return CURLM_RECURSIVE_API_CALL;
3334
0
  return multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
3335
0
}
3336
3337
CURLMcode curl_multi_socket_all(CURLM *m, int *running_handles)
3338
0
{
3339
0
  struct Curl_multi *multi = m;
3340
0
  if(multi->in_callback)
3341
0
    return CURLM_RECURSIVE_API_CALL;
3342
0
  if(multi->in_ntfy_callback)
3343
0
    return CURLM_RECURSIVE_API_CALL;
3344
0
  return multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
3345
0
}
3346
3347
3348
static bool multi_has_dirties(struct Curl_multi *multi)
3349
0
{
3350
0
  unsigned int mid;
3351
0
  if(Curl_uint_bset_first(&multi->dirty, &mid)) {
3352
0
    do {
3353
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
3354
0
      if(data) {
3355
0
        if(Curl_uint_bset_contains(&multi->process, mid))
3356
0
          return TRUE;
3357
        /* We are no longer processing this transfer */
3358
0
        Curl_uint_bset_remove(&multi->dirty, mid);
3359
0
      }
3360
0
      else {
3361
0
        CURL_TRC_M(multi->admin, "dirty transfer %u no longer found", mid);
3362
0
        Curl_uint_bset_remove(&multi->dirty, mid);
3363
0
      }
3364
0
    }
3365
0
    while(Curl_uint_bset_next(&multi->dirty, mid, &mid));
3366
0
  }
3367
0
  return FALSE;
3368
0
}
3369
3370
static CURLMcode multi_timeout(struct Curl_multi *multi,
3371
                               struct curltime *expire_time,
3372
                               long *timeout_ms)
3373
0
{
3374
0
  static const struct curltime tv_zero = {0, 0};
3375
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
3376
0
  struct Curl_easy *data = NULL;
3377
0
#endif
3378
3379
0
  if(multi->dead) {
3380
0
    *timeout_ms = 0;
3381
0
    return CURLM_OK;
3382
0
  }
3383
3384
0
  if(multi_has_dirties(multi)) {
3385
0
    *expire_time = curlx_now();
3386
0
    *timeout_ms = 0;
3387
0
    return CURLM_OK;
3388
0
  }
3389
0
  else if(multi->timetree) {
3390
    /* we have a tree of expire times */
3391
0
    struct curltime now = curlx_now();
3392
3393
    /* splay the lowest to the bottom */
3394
0
    multi->timetree = Curl_splay(tv_zero, multi->timetree);
3395
    /* this will not return NULL from a non-empty tree, but some compilers
3396
     * are not convinced of that. Analyzers are hard. */
3397
0
    *expire_time = multi->timetree ? multi->timetree->key : tv_zero;
3398
3399
    /* 'multi->timetree' will be non-NULL here but the compilers sometimes
3400
       yell at us if we assume so */
3401
0
    if(multi->timetree &&
3402
0
       curlx_timediff_us(multi->timetree->key, now) > 0) {
3403
      /* some time left before expiration */
3404
0
      timediff_t diff = curlx_timediff_ceil(multi->timetree->key, now);
3405
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
3406
0
      data = Curl_splayget(multi->timetree);
3407
0
#endif
3408
      /* this should be safe even on 32-bit archs, as we do not use that
3409
         overly long timeouts */
3410
0
      *timeout_ms = (long)diff;
3411
0
    }
3412
0
    else {
3413
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
3414
0
      if(multi->timetree) {
3415
0
        data = Curl_splayget(multi->timetree);
3416
0
      }
3417
0
#endif
3418
      /* 0 means immediately */
3419
0
      *timeout_ms = 0;
3420
0
    }
3421
0
  }
3422
0
  else {
3423
0
    *expire_time = tv_zero;
3424
0
    *timeout_ms = -1;
3425
0
  }
3426
3427
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
3428
0
  if(data && CURL_TRC_TIMER_is_verbose(data)) {
3429
0
    struct Curl_llist_node *e =
3430
0
      Curl_llist_head(&data->state.timeoutlist);
3431
0
    if(e) {
3432
0
      struct time_node *n = Curl_node_elem(e);
3433
0
      CURL_TRC_TIMER(data, n->eid, "gives multi timeout in %ldms",
3434
0
                     *timeout_ms);
3435
0
    }
3436
0
  }
3437
0
#endif
3438
3439
0
  return CURLM_OK;
3440
0
}
3441
3442
CURLMcode curl_multi_timeout(CURLM *m,
3443
                             long *timeout_ms)
3444
0
{
3445
0
  struct curltime expire_time;
3446
0
  struct Curl_multi *multi = m;
3447
3448
  /* First, make some basic checks that the CURLM handle is a good handle */
3449
0
  if(!GOOD_MULTI_HANDLE(multi))
3450
0
    return CURLM_BAD_HANDLE;
3451
3452
0
  if(multi->in_callback)
3453
0
    return CURLM_RECURSIVE_API_CALL;
3454
3455
0
  return multi_timeout(multi, &expire_time, timeout_ms);
3456
0
}
3457
3458
/*
3459
 * Tell the application it should update its timers, if it subscribes to the
3460
 * update timer callback.
3461
 */
3462
CURLMcode Curl_update_timer(struct Curl_multi *multi)
3463
0
{
3464
0
  struct curltime expire_ts;
3465
0
  long timeout_ms;
3466
0
  int rc;
3467
0
  bool set_value = FALSE;
3468
3469
0
  if(!multi->timer_cb || multi->dead)
3470
0
    return CURLM_OK;
3471
0
  if(multi_timeout(multi, &expire_ts, &timeout_ms)) {
3472
0
    return CURLM_OK;
3473
0
  }
3474
3475
0
  if(timeout_ms < 0 && multi->last_timeout_ms < 0) {
3476
    /* nothing to do */
3477
0
  }
3478
0
  else if(timeout_ms < 0) {
3479
    /* there is no timeout now but there was one previously */
3480
0
    CURL_TRC_M(multi->admin, "[TIMER] clear");
3481
0
    timeout_ms = -1; /* normalize */
3482
0
    set_value = TRUE;
3483
0
  }
3484
0
  else if(multi->last_timeout_ms < 0) {
3485
0
    CURL_TRC_M(multi->admin, "[TIMER] set %ldms, none before",
3486
0
               timeout_ms);
3487
0
    set_value = TRUE;
3488
0
  }
3489
0
  else if(curlx_timediff_us(multi->last_expire_ts, expire_ts)) {
3490
    /* We had a timeout before and have one now, the absolute timestamp
3491
     * differs. The relative timeout_ms may be the same, but the starting
3492
     * point differs. Let the application restart its timer. */
3493
0
    CURL_TRC_M(multi->admin, "[TIMER] set %ldms, replace previous",
3494
0
               timeout_ms);
3495
0
    set_value = TRUE;
3496
0
  }
3497
0
  else {
3498
    /* We have same expire time as previously. Our relative 'timeout_ms'
3499
     * may be different now, but the application has the timer running
3500
     * and we do not to tell it to start this again. */
3501
0
  }
3502
3503
0
  if(set_value) {
3504
0
    multi->last_expire_ts = expire_ts;
3505
0
    multi->last_timeout_ms = timeout_ms;
3506
0
    set_in_callback(multi, TRUE);
3507
0
    rc = multi->timer_cb(multi, timeout_ms, multi->timer_userp);
3508
0
    set_in_callback(multi, FALSE);
3509
0
    if(rc == -1) {
3510
0
      multi->dead = TRUE;
3511
0
      return CURLM_ABORTED_BY_CALLBACK;
3512
0
    }
3513
0
  }
3514
0
  return CURLM_OK;
3515
0
}
3516
3517
/*
3518
 * multi_deltimeout()
3519
 *
3520
 * Remove a given timestamp from the list of timeouts.
3521
 */
3522
static void
3523
multi_deltimeout(struct Curl_easy *data, expire_id eid)
3524
0
{
3525
0
  struct Curl_llist_node *e;
3526
0
  struct Curl_llist *timeoutlist = &data->state.timeoutlist;
3527
  /* find and remove the specific node from the list */
3528
0
  for(e = Curl_llist_head(timeoutlist); e; e = Curl_node_next(e)) {
3529
0
    struct time_node *n = Curl_node_elem(e);
3530
0
    if(n->eid == eid) {
3531
0
      Curl_node_remove(e);
3532
0
      return;
3533
0
    }
3534
0
  }
3535
0
}
3536
3537
/*
3538
 * multi_addtimeout()
3539
 *
3540
 * Add a timestamp to the list of timeouts. Keep the list sorted so that head
3541
 * of list is always the timeout nearest in time.
3542
 *
3543
 */
3544
static CURLMcode
3545
multi_addtimeout(struct Curl_easy *data,
3546
                 struct curltime *stamp,
3547
                 expire_id eid,
3548
                 const struct curltime *nowp)
3549
0
{
3550
0
  struct Curl_llist_node *e;
3551
0
  struct time_node *node;
3552
0
  struct Curl_llist_node *prev = NULL;
3553
0
  size_t n;
3554
0
  struct Curl_llist *timeoutlist = &data->state.timeoutlist;
3555
3556
0
  (void)nowp;
3557
0
  node = &data->state.expires[eid];
3558
3559
  /* copy the timestamp and id */
3560
0
  memcpy(&node->time, stamp, sizeof(*stamp));
3561
0
  node->eid = eid; /* also marks it as in use */
3562
3563
0
  n = Curl_llist_count(timeoutlist);
3564
0
  if(n) {
3565
    /* find the correct spot in the list */
3566
0
    for(e = Curl_llist_head(timeoutlist); e; e = Curl_node_next(e)) {
3567
0
      struct time_node *check = Curl_node_elem(e);
3568
0
      timediff_t diff = curlx_timediff(check->time, node->time);
3569
0
      if(diff > 0)
3570
0
        break;
3571
0
      prev = e;
3572
0
    }
3573
3574
0
  }
3575
  /* else
3576
     this is the first timeout on the list */
3577
3578
0
  Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
3579
0
  CURL_TRC_TIMER(data, eid, "set for %" FMT_TIMEDIFF_T "ns",
3580
0
                 curlx_timediff_us(node->time, *nowp));
3581
0
  return CURLM_OK;
3582
0
}
3583
3584
void Curl_expire_ex(struct Curl_easy *data,
3585
                    const struct curltime *nowp,
3586
                    timediff_t milli, expire_id id)
3587
0
{
3588
0
  struct Curl_multi *multi = data->multi;
3589
0
  struct curltime *curr_expire = &data->state.expiretime;
3590
0
  struct curltime set;
3591
3592
  /* this is only interesting while there is still an associated multi struct
3593
     remaining! */
3594
0
  if(!multi)
3595
0
    return;
3596
3597
0
  DEBUGASSERT(id < EXPIRE_LAST);
3598
3599
0
  set = *nowp;
3600
0
  set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bits conversion */
3601
0
  set.tv_usec += (int)(milli%1000)*1000;
3602
3603
0
  if(set.tv_usec >= 1000000) {
3604
0
    set.tv_sec++;
3605
0
    set.tv_usec -= 1000000;
3606
0
  }
3607
3608
  /* Remove any timer with the same id just in case. */
3609
0
  multi_deltimeout(data, id);
3610
3611
  /* Add it to the timer list. It must stay in the list until it has expired
3612
     in case we need to recompute the minimum timer later. */
3613
0
  multi_addtimeout(data, &set, id, nowp);
3614
3615
0
  if(curr_expire->tv_sec || curr_expire->tv_usec) {
3616
    /* This means that the struct is added as a node in the splay tree.
3617
       Compare if the new time is earlier, and only remove-old/add-new if it
3618
       is. */
3619
0
    timediff_t diff = curlx_timediff(set, *curr_expire);
3620
0
    int rc;
3621
3622
0
    if(diff > 0) {
3623
      /* The current splay tree entry is sooner than this new expiry time.
3624
         We do not need to update our splay tree entry. */
3625
0
      return;
3626
0
    }
3627
3628
    /* Since this is an updated time, we must remove the previous entry from
3629
       the splay tree first and then re-add the new value */
3630
0
    rc = Curl_splayremove(multi->timetree, &data->state.timenode,
3631
0
                          &multi->timetree);
3632
0
    if(rc)
3633
0
      infof(data, "Internal error removing splay node = %d", rc);
3634
0
  }
3635
3636
  /* Indicate that we are in the splay tree and insert the new timer expiry
3637
     value since it is our local minimum. */
3638
0
  *curr_expire = set;
3639
0
  Curl_splayset(&data->state.timenode, data);
3640
0
  multi->timetree = Curl_splayinsert(*curr_expire, multi->timetree,
3641
0
                                     &data->state.timenode);
3642
0
}
3643
3644
/*
3645
 * Curl_expire()
3646
 *
3647
 * given a number of milliseconds from now to use to set the 'act before
3648
 * this'-time for the transfer, to be extracted by curl_multi_timeout()
3649
 *
3650
 * The timeout will be added to a queue of timeouts if it defines a moment in
3651
 * time that is later than the current head of queue.
3652
 *
3653
 * Expire replaces a former timeout using the same id if already set.
3654
 */
3655
void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
3656
0
{
3657
0
  struct curltime now = curlx_now();
3658
0
  Curl_expire_ex(data, &now, milli, id);
3659
0
}
3660
3661
/*
3662
 * Curl_expire_done()
3663
 *
3664
 * Removes the expire timer. Marks it as done.
3665
 *
3666
 */
3667
void Curl_expire_done(struct Curl_easy *data, expire_id eid)
3668
0
{
3669
  /* remove the timer, if there */
3670
0
  multi_deltimeout(data, eid);
3671
0
  CURL_TRC_TIMER(data, eid, "cleared");
3672
0
}
3673
3674
/*
3675
 * Curl_expire_clear()
3676
 *
3677
 * Clear ALL timeout values for this handle.
3678
 */
3679
bool Curl_expire_clear(struct Curl_easy *data)
3680
0
{
3681
0
  struct Curl_multi *multi = data->multi;
3682
0
  struct curltime *nowp = &data->state.expiretime;
3683
3684
  /* this is only interesting while there is still an associated multi struct
3685
     remaining! */
3686
0
  if(!multi)
3687
0
    return FALSE;
3688
3689
0
  if(nowp->tv_sec || nowp->tv_usec) {
3690
    /* Since this is an cleared time, we must remove the previous entry from
3691
       the splay tree */
3692
0
    struct Curl_llist *list = &data->state.timeoutlist;
3693
0
    int rc;
3694
3695
0
    rc = Curl_splayremove(multi->timetree, &data->state.timenode,
3696
0
                          &multi->timetree);
3697
0
    if(rc)
3698
0
      infof(data, "Internal error clearing splay node = %d", rc);
3699
3700
    /* clear the timeout list too */
3701
0
    Curl_llist_destroy(list, NULL);
3702
3703
0
    if(data->id >= 0)
3704
0
      CURL_TRC_M(data, "[TIMEOUT] all cleared");
3705
0
    nowp->tv_sec = 0;
3706
0
    nowp->tv_usec = 0;
3707
0
    return TRUE;
3708
0
  }
3709
0
  return FALSE;
3710
0
}
3711
3712
CURLMcode curl_multi_assign(CURLM *m, curl_socket_t s,
3713
                            void *hashp)
3714
0
{
3715
0
  struct Curl_multi *multi = m;
3716
0
  if(!GOOD_MULTI_HANDLE(multi))
3717
0
    return CURLM_BAD_HANDLE;
3718
3719
0
  return Curl_multi_ev_assign(multi, s, hashp);
3720
0
}
3721
3722
static void move_pending_to_connect(struct Curl_multi *multi,
3723
                                    struct Curl_easy *data)
3724
0
{
3725
0
  DEBUGASSERT(data->mstate == MSTATE_PENDING);
3726
3727
  /* Remove this node from the pending set, add into process set */
3728
0
  Curl_uint_bset_remove(&multi->pending, data->mid);
3729
0
  Curl_uint_bset_add(&multi->process, data->mid);
3730
3731
0
  multistate(data, MSTATE_CONNECT);
3732
0
  Curl_multi_mark_dirty(data); /* make it run */
3733
0
}
3734
3735
/* process_pending_handles() moves a handle from PENDING back into the process
3736
   list and change state to CONNECT.
3737
3738
   We do not move all transfers because that can be a significant amount.
3739
   Since this is tried every now and then doing too many too often becomes a
3740
   performance problem.
3741
3742
   When there is a change for connection limits like max host connections etc,
3743
   this likely only allows one new transfer. When there is a pipewait change,
3744
   it can potentially allow hundreds of new transfers.
3745
3746
   We could consider an improvement where we store the queue reason and allow
3747
   more pipewait rechecks than others.
3748
*/
3749
static void process_pending_handles(struct Curl_multi *multi)
3750
0
{
3751
0
  unsigned int mid;
3752
0
  if(Curl_uint_bset_first(&multi->pending, &mid)) {
3753
0
    do {
3754
0
      struct Curl_easy *data = Curl_multi_get_easy(multi, mid);
3755
0
      if(data) {
3756
0
        move_pending_to_connect(multi, data);
3757
0
        break;
3758
0
      }
3759
      /* transfer no longer known, should not happen */
3760
0
      Curl_uint_bset_remove(&multi->pending, mid);
3761
0
      DEBUGASSERT(0);
3762
0
    }
3763
0
    while(Curl_uint_bset_next(&multi->pending, mid, &mid));
3764
0
  }
3765
0
}
3766
3767
void Curl_set_in_callback(struct Curl_easy *data, bool value)
3768
0
{
3769
0
  if(data && data->multi)
3770
0
    data->multi->in_callback = value;
3771
0
}
3772
3773
bool Curl_is_in_callback(struct Curl_easy *data)
3774
0
{
3775
0
  return data && data->multi && data->multi->in_callback;
3776
0
}
3777
3778
unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
3779
0
{
3780
0
  DEBUGASSERT(multi);
3781
0
  return multi->max_concurrent_streams;
3782
0
}
3783
3784
CURL **curl_multi_get_handles(CURLM *m)
3785
0
{
3786
0
  struct Curl_multi *multi = m;
3787
0
  void *entry;
3788
0
  unsigned int count = Curl_uint_tbl_count(&multi->xfers);
3789
0
  CURL **a = malloc(sizeof(struct Curl_easy *) * (count + 1));
3790
0
  if(a) {
3791
0
    unsigned int i = 0, mid;
3792
3793
0
    if(Curl_uint_tbl_first(&multi->xfers, &mid, &entry)) {
3794
0
      do {
3795
0
        struct Curl_easy *data = entry;
3796
0
        DEBUGASSERT(i < count);
3797
0
        if(!data->state.internal)
3798
0
          a[i++] = data;
3799
0
      }
3800
0
      while(Curl_uint_tbl_next(&multi->xfers, mid, &mid, &entry));
3801
0
    }
3802
0
    a[i] = NULL; /* last entry is a NULL */
3803
0
  }
3804
0
  return a;
3805
0
}
3806
3807
CURLMcode curl_multi_get_offt(CURLM *m,
3808
                              CURLMinfo_offt info,
3809
                              curl_off_t *pvalue)
3810
0
{
3811
0
  struct Curl_multi *multi = m;
3812
3813
0
  if(!GOOD_MULTI_HANDLE(multi))
3814
0
    return CURLM_BAD_HANDLE;
3815
0
  if(!pvalue)
3816
0
    return CURLM_BAD_FUNCTION_ARGUMENT;
3817
3818
0
  switch(info) {
3819
0
  case CURLMINFO_XFERS_CURRENT: {
3820
0
    unsigned int n = Curl_uint_tbl_count(&multi->xfers);
3821
0
    if(n && multi->admin)
3822
0
      --n;
3823
0
    *pvalue = (curl_off_t)n;
3824
0
    return CURLM_OK;
3825
0
  }
3826
0
  case CURLMINFO_XFERS_RUNNING:
3827
0
    *pvalue = (curl_off_t)Curl_uint_bset_count(&multi->process);
3828
0
    return CURLM_OK;
3829
0
  case CURLMINFO_XFERS_PENDING:
3830
0
    *pvalue = (curl_off_t)Curl_uint_bset_count(&multi->pending);
3831
0
    return CURLM_OK;
3832
0
  case CURLMINFO_XFERS_DONE:
3833
0
    *pvalue = (curl_off_t)Curl_uint_bset_count(&multi->msgsent);
3834
0
    return CURLM_OK;
3835
0
  case CURLMINFO_XFERS_ADDED:
3836
0
    *pvalue = multi->xfers_total_ever;
3837
0
    return CURLM_OK;
3838
0
  default:
3839
0
    *pvalue = -1;
3840
0
    return CURLM_UNKNOWN_OPTION;
3841
0
  }
3842
0
}
3843
3844
CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data,
3845
                                    char **pbuf, size_t *pbuflen)
3846
0
{
3847
0
  DEBUGASSERT(data);
3848
0
  DEBUGASSERT(data->multi);
3849
0
  *pbuf = NULL;
3850
0
  *pbuflen = 0;
3851
0
  if(!data->multi) {
3852
0
    failf(data, "transfer has no multi handle");
3853
0
    return CURLE_FAILED_INIT;
3854
0
  }
3855
0
  if(!data->set.buffer_size) {
3856
0
    failf(data, "transfer buffer size is 0");
3857
0
    return CURLE_FAILED_INIT;
3858
0
  }
3859
0
  if(data->multi->xfer_buf_borrowed) {
3860
0
    failf(data, "attempt to borrow xfer_buf when already borrowed");
3861
0
    return CURLE_AGAIN;
3862
0
  }
3863
3864
0
  if(data->multi->xfer_buf &&
3865
0
     data->set.buffer_size > data->multi->xfer_buf_len) {
3866
    /* not large enough, get a new one */
3867
0
    free(data->multi->xfer_buf);
3868
0
    data->multi->xfer_buf = NULL;
3869
0
    data->multi->xfer_buf_len = 0;
3870
0
  }
3871
3872
0
  if(!data->multi->xfer_buf) {
3873
0
    data->multi->xfer_buf = malloc((size_t)data->set.buffer_size);
3874
0
    if(!data->multi->xfer_buf) {
3875
0
      failf(data, "could not allocate xfer_buf of %zu bytes",
3876
0
            (size_t)data->set.buffer_size);
3877
0
      return CURLE_OUT_OF_MEMORY;
3878
0
    }
3879
0
    data->multi->xfer_buf_len = data->set.buffer_size;
3880
0
  }
3881
3882
0
  data->multi->xfer_buf_borrowed = TRUE;
3883
0
  *pbuf = data->multi->xfer_buf;
3884
0
  *pbuflen = data->multi->xfer_buf_len;
3885
0
  return CURLE_OK;
3886
0
}
3887
3888
void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf)
3889
0
{
3890
0
  (void)buf;
3891
0
  DEBUGASSERT(data);
3892
0
  DEBUGASSERT(data->multi);
3893
0
  DEBUGASSERT(!buf || data->multi->xfer_buf == buf);
3894
0
  data->multi->xfer_buf_borrowed = FALSE;
3895
0
}
3896
3897
CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data,
3898
                                      char **pbuf, size_t *pbuflen)
3899
0
{
3900
0
  DEBUGASSERT(data);
3901
0
  DEBUGASSERT(data->multi);
3902
0
  *pbuf = NULL;
3903
0
  *pbuflen = 0;
3904
0
  if(!data->multi) {
3905
0
    failf(data, "transfer has no multi handle");
3906
0
    return CURLE_FAILED_INIT;
3907
0
  }
3908
0
  if(!data->set.upload_buffer_size) {
3909
0
    failf(data, "transfer upload buffer size is 0");
3910
0
    return CURLE_FAILED_INIT;
3911
0
  }
3912
0
  if(data->multi->xfer_ulbuf_borrowed) {
3913
0
    failf(data, "attempt to borrow xfer_ulbuf when already borrowed");
3914
0
    return CURLE_AGAIN;
3915
0
  }
3916
3917
0
  if(data->multi->xfer_ulbuf &&
3918
0
     data->set.upload_buffer_size > data->multi->xfer_ulbuf_len) {
3919
    /* not large enough, get a new one */
3920
0
    free(data->multi->xfer_ulbuf);
3921
0
    data->multi->xfer_ulbuf = NULL;
3922
0
    data->multi->xfer_ulbuf_len = 0;
3923
0
  }
3924
3925
0
  if(!data->multi->xfer_ulbuf) {
3926
0
    data->multi->xfer_ulbuf = malloc((size_t)data->set.upload_buffer_size);
3927
0
    if(!data->multi->xfer_ulbuf) {
3928
0
      failf(data, "could not allocate xfer_ulbuf of %zu bytes",
3929
0
            (size_t)data->set.upload_buffer_size);
3930
0
      return CURLE_OUT_OF_MEMORY;
3931
0
    }
3932
0
    data->multi->xfer_ulbuf_len = data->set.upload_buffer_size;
3933
0
  }
3934
3935
0
  data->multi->xfer_ulbuf_borrowed = TRUE;
3936
0
  *pbuf = data->multi->xfer_ulbuf;
3937
0
  *pbuflen = data->multi->xfer_ulbuf_len;
3938
0
  return CURLE_OK;
3939
0
}
3940
3941
void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf)
3942
0
{
3943
0
  (void)buf;
3944
0
  DEBUGASSERT(data);
3945
0
  DEBUGASSERT(data->multi);
3946
0
  DEBUGASSERT(!buf || data->multi->xfer_ulbuf == buf);
3947
0
  data->multi->xfer_ulbuf_borrowed = FALSE;
3948
0
}
3949
3950
CURLcode Curl_multi_xfer_sockbuf_borrow(struct Curl_easy *data,
3951
                                        size_t blen, char **pbuf)
3952
0
{
3953
0
  DEBUGASSERT(data);
3954
0
  DEBUGASSERT(data->multi);
3955
0
  *pbuf = NULL;
3956
0
  if(!data->multi) {
3957
0
    failf(data, "transfer has no multi handle");
3958
0
    return CURLE_FAILED_INIT;
3959
0
  }
3960
0
  if(data->multi->xfer_sockbuf_borrowed) {
3961
0
    failf(data, "attempt to borrow xfer_sockbuf when already borrowed");
3962
0
    return CURLE_AGAIN;
3963
0
  }
3964
3965
0
  if(data->multi->xfer_sockbuf && blen > data->multi->xfer_sockbuf_len) {
3966
    /* not large enough, get a new one */
3967
0
    free(data->multi->xfer_sockbuf);
3968
0
    data->multi->xfer_sockbuf = NULL;
3969
0
    data->multi->xfer_sockbuf_len = 0;
3970
0
  }
3971
3972
0
  if(!data->multi->xfer_sockbuf) {
3973
0
    data->multi->xfer_sockbuf = malloc(blen);
3974
0
    if(!data->multi->xfer_sockbuf) {
3975
0
      failf(data, "could not allocate xfer_sockbuf of %zu bytes", blen);
3976
0
      return CURLE_OUT_OF_MEMORY;
3977
0
    }
3978
0
    data->multi->xfer_sockbuf_len = blen;
3979
0
  }
3980
3981
0
  data->multi->xfer_sockbuf_borrowed = TRUE;
3982
0
  *pbuf = data->multi->xfer_sockbuf;
3983
0
  return CURLE_OK;
3984
0
}
3985
3986
void Curl_multi_xfer_sockbuf_release(struct Curl_easy *data, char *buf)
3987
0
{
3988
0
  (void)buf;
3989
0
  DEBUGASSERT(data);
3990
0
  DEBUGASSERT(data->multi);
3991
0
  DEBUGASSERT(!buf || data->multi->xfer_sockbuf == buf);
3992
0
  data->multi->xfer_sockbuf_borrowed = FALSE;
3993
0
}
3994
3995
static void multi_xfer_bufs_free(struct Curl_multi *multi)
3996
0
{
3997
0
  DEBUGASSERT(multi);
3998
0
  Curl_safefree(multi->xfer_buf);
3999
0
  multi->xfer_buf_len = 0;
4000
0
  multi->xfer_buf_borrowed = FALSE;
4001
0
  Curl_safefree(multi->xfer_ulbuf);
4002
0
  multi->xfer_ulbuf_len = 0;
4003
0
  multi->xfer_ulbuf_borrowed = FALSE;
4004
0
  Curl_safefree(multi->xfer_sockbuf);
4005
0
  multi->xfer_sockbuf_len = 0;
4006
0
  multi->xfer_sockbuf_borrowed = FALSE;
4007
0
}
4008
4009
struct Curl_easy *Curl_multi_get_easy(struct Curl_multi *multi,
4010
                                      unsigned int mid)
4011
0
{
4012
0
  struct Curl_easy *data = mid ? Curl_uint_tbl_get(&multi->xfers, mid) : NULL;
4013
0
  if(data && GOOD_EASY_HANDLE(data))
4014
0
    return data;
4015
0
  CURL_TRC_M(multi->admin, "invalid easy handle in xfer table for mid=%u",
4016
0
             mid);
4017
0
  Curl_uint_tbl_remove(&multi->xfers, mid);
4018
0
  return NULL;
4019
0
}
4020
4021
unsigned int Curl_multi_xfers_running(struct Curl_multi *multi)
4022
0
{
4023
0
  return multi->xfers_alive;
4024
0
}
4025
4026
void Curl_multi_mark_dirty(struct Curl_easy *data)
4027
0
{
4028
0
  if(data->multi && data->mid != UINT_MAX)
4029
0
    Curl_uint_bset_add(&data->multi->dirty, data->mid);
4030
0
}
4031
4032
void Curl_multi_clear_dirty(struct Curl_easy *data)
4033
0
{
4034
0
  if(data->multi && data->mid != UINT_MAX)
4035
0
    Curl_uint_bset_remove(&data->multi->dirty, data->mid);
4036
0
}
4037
4038
CURLMcode curl_multi_notify_enable(CURLM *m, unsigned int notification)
4039
0
{
4040
0
  struct Curl_multi *multi = m;
4041
4042
0
  if(!GOOD_MULTI_HANDLE(multi))
4043
0
    return CURLM_BAD_HANDLE;
4044
0
  return Curl_mntfy_enable(multi, notification);
4045
0
}
4046
4047
CURLMcode curl_multi_notify_disable(CURLM *m, unsigned int notification)
4048
0
{
4049
0
  struct Curl_multi *multi = m;
4050
4051
0
  if(!GOOD_MULTI_HANDLE(multi))
4052
0
    return CURLM_BAD_HANDLE;
4053
0
  return Curl_mntfy_disable(multi, notification);
4054
0
}
4055
4056
#ifdef DEBUGBUILD
4057
static void multi_xfer_dump(struct Curl_multi *multi, unsigned int mid,
4058
                            void *entry)
4059
{
4060
  struct Curl_easy *data = entry;
4061
4062
  (void)multi;
4063
  if(!data) {
4064
    curl_mfprintf(stderr, "mid=%u, entry=NULL, bug in xfer table?\n", mid);
4065
  }
4066
  else {
4067
    curl_mfprintf(stderr, "mid=%u, magic=%s, p=%p, id=%" FMT_OFF_T
4068
                  ", url=%s\n",
4069
                  mid,
4070
                  (data->magic == CURLEASY_MAGIC_NUMBER) ? "GOOD" : "BAD!",
4071
                  (void *)data, data->id, data->state.url);
4072
  }
4073
}
4074
4075
static void multi_xfer_tbl_dump(struct Curl_multi *multi)
4076
{
4077
  unsigned int mid;
4078
  void *entry;
4079
  curl_mfprintf(stderr, "=== multi xfer table (count=%u, capacity=%u\n",
4080
                Curl_uint_tbl_count(&multi->xfers),
4081
                Curl_uint_tbl_capacity(&multi->xfers));
4082
  if(Curl_uint_tbl_first(&multi->xfers, &mid, &entry)) {
4083
    multi_xfer_dump(multi, mid, entry);
4084
    while(Curl_uint_tbl_next(&multi->xfers, mid, &mid, &entry))
4085
      multi_xfer_dump(multi, mid, entry);
4086
  }
4087
  curl_mfprintf(stderr, "===\n");
4088
  fflush(stderr);
4089
}
4090
#endif /* DEBUGBUILD */