Coverage Report

Created: 2026-09-14 07:05

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