Coverage Report

Created: 2026-08-31 06:46

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