Coverage Report

Created: 2026-12-01 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/conncache.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se>
9
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
10
 *
11
 * This software is licensed as described in the file COPYING, which
12
 * you should have received as part of this distribution. The terms
13
 * are also available at https://curl.se/docs/copyright.html.
14
 *
15
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16
 * copies of the Software, and permit persons to whom the Software is
17
 * furnished to do so, under the terms of the COPYING file.
18
 *
19
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20
 * KIND, either express or implied.
21
 *
22
 * SPDX-License-Identifier: curl
23
 *
24
 ***************************************************************************/
25
#include "curl_setup.h"
26
27
#include "urldata.h"
28
#include "url.h"
29
#include "cfilters.h"
30
#include "progress.h"
31
#include "multiif.h"
32
#include "curl_trc.h"
33
#include "cshutdn.h"
34
#include "conncache.h"
35
#include "curl_share.h"
36
#include "sigpipe.h"
37
#include "uint-spbset.h"
38
39
40
3.86k
#define CPOOL_IS_LOCKED(c)    ((c) && (c)->locked)
41
42
#define CPOOL_LOCK(c, d)                                                \
43
19.4k
  do {                                                                  \
44
19.4k
    if(c) {                                                             \
45
19.4k
      if(CURL_SHARE_KEEP_CONNECT((c)->share))                           \
46
19.4k
        Curl_share_lock_share((c)->share, (d), CURL_LOCK_DATA_CONNECT,  \
47
0
                        CURL_LOCK_ACCESS_SINGLE);                       \
48
19.4k
      DEBUGASSERT(!(c)->locked);                                        \
49
19.4k
      (c)->locked = TRUE;                                               \
50
19.4k
    }                                                                   \
51
19.4k
  } while(0)
52
53
#define CPOOL_UNLOCK(c, d)                                              \
54
19.4k
  do {                                                                  \
55
19.4k
    if(c) {                                                             \
56
19.4k
      DEBUGASSERT((c)->locked);                                         \
57
19.4k
      (c)->locked = FALSE;                                              \
58
19.4k
      if(CURL_SHARE_KEEP_CONNECT((c)->share))                           \
59
19.4k
        Curl_share_unlock_share((c)->share, (d), CURL_LOCK_DATA_CONNECT); \
60
19.4k
    }                                                                   \
61
19.4k
  } while(0)
62
63
/* A set of connection pool ids to the same destination. */
64
struct cpool_bundle {
65
  struct uint32_spbset ids; /* bitset of connection `pool_id`s  */
66
  uint32_t refcount;
67
};
68
69
static void cpool_bundle_unlink(struct cpool_bundle **pbundle)
70
19.2k
{
71
19.2k
  if(*pbundle) {
72
11.5k
    struct cpool_bundle *bundle = *pbundle;
73
74
11.5k
    DEBUGASSERT(bundle->refcount);
75
11.5k
    *pbundle = NULL;
76
11.5k
    if(bundle->refcount)
77
11.5k
      bundle->refcount--;
78
11.5k
    if(!bundle->refcount) {
79
3.85k
      Curl_uint32_spbset_destroy(&bundle->ids);
80
3.85k
      curlx_free(bundle);
81
3.85k
    }
82
11.5k
  }
83
19.2k
}
84
85
static void cpool_bundle_link(struct cpool_bundle **pdest,
86
                              struct cpool_bundle *src)
87
11.5k
{
88
11.5k
  if(*pdest != src) {
89
7.69k
    cpool_bundle_unlink(pdest);
90
7.69k
    *pdest = src;
91
7.69k
    if(src) {
92
7.69k
      DEBUGASSERT(src->refcount < UINT32_MAX);
93
7.69k
      src->refcount++;
94
7.69k
    }
95
7.69k
  }
96
11.5k
}
97
98
static struct cpool_bundle *cpool_create_bundle(void)
99
3.85k
{
100
  /* created with refcount == 1 */
101
3.85k
  struct cpool_bundle *bundle = curlx_calloc(1, sizeof(*bundle));
102
3.85k
  if(!bundle)
103
5
    return NULL;
104
105
3.85k
  Curl_uint32_spbset_init(&bundle->ids);
106
3.85k
  bundle->refcount = 1;
107
3.85k
  return bundle;
108
3.85k
}
109
110
/* Add a connection to a bundle */
111
static bool cpool_bundle_add_id(struct cpool *cpool,
112
                                struct cpool_bundle *bundle,
113
                                const char *destination,
114
                                uint32_t pool_id)
115
3.85k
{
116
3.85k
  if(!Curl_uint32_spbset_add(&bundle->ids, pool_id))
117
0
    return FALSE;
118
3.85k
  if(Curl_uint32_spbset_count(&bundle->ids) == 1) {
119
    /* first one added, register bundle */
120
3.85k
    struct cpool_bundle *new_ref = NULL;
121
3.85k
    cpool_bundle_link(&new_ref, bundle);
122
3.85k
    if(!Curl_hash_add(&cpool->dest2bundle,
123
3.85k
                      destination, strlen(destination), new_ref)) {
124
5
      cpool_bundle_unlink(&new_ref);
125
5
      return FALSE;
126
5
    }
127
3.85k
  }
128
3.84k
  return TRUE;
129
3.85k
}
130
131
/* Remove a connection from a bundle */
132
static void cpool_bundle_remove_id(struct cpool *cpool,
133
                                   struct cpool_bundle *bundle,
134
                                   const char *destination,
135
                                   uint32_t pool_id)
136
3.84k
{
137
3.84k
  Curl_uint32_spbset_remove(&bundle->ids, pool_id);
138
3.84k
  if(!Curl_uint32_spbset_count(&bundle->ids)) {
139
    /* Now empty, unregister bundle */
140
3.84k
    Curl_hash_delete(&cpool->dest2bundle, destination, strlen(destination));
141
3.84k
  }
142
3.84k
}
143
144
static void cpool_bundle_hash_dtor(void *entry)
145
3.84k
{
146
3.84k
  struct cpool_bundle *bundle = entry;
147
3.84k
  cpool_bundle_unlink(&bundle);
148
3.84k
}
149
150
static struct cpool_bundle *cpool_get_bundle(struct cpool *cpool,
151
                                             const char *destination)
152
7.70k
{
153
7.70k
  struct cpool_bundle *bundle = NULL;
154
7.70k
  cpool_bundle_link(&bundle, Curl_hash_pick(
155
7.70k
    &cpool->dest2bundle, destination, strlen(destination)));
156
7.70k
  return bundle;
157
7.70k
}
158
159
static void cpool_remove_conn(struct cpool *cpool,
160
                              struct connectdata *conn)
161
3.84k
{
162
3.84k
  uint32_t cpid = conn->cpid;
163
164
3.84k
  DEBUGASSERT(cpool);
165
3.84k
  if(cpid != UINT32_MAX) {
166
3.84k
    struct cpool_bundle *bundle;
167
168
3.84k
#ifdef DEBUGBUILD
169
3.84k
    {
170
3.84k
      struct connectdata *pooled_conn =
171
3.84k
        Curl_uint32_tbl_get(&cpool->conns, cpid);
172
3.84k
      DEBUGASSERT(conn == pooled_conn);
173
3.84k
    }
174
3.84k
#endif
175
3.84k
    Curl_uint32_tbl_remove(&cpool->conns, cpid);
176
3.84k
    Curl_uint32_bset_remove(&cpool->idles, cpid);
177
3.84k
    conn->cpid = UINT32_MAX;
178
179
3.84k
    bundle = cpool_get_bundle(cpool, conn->destination);
180
3.84k
    DEBUGASSERT(bundle);
181
3.84k
    if(bundle)
182
3.84k
      cpool_bundle_remove_id(cpool, bundle, conn->destination, cpid);
183
3.84k
    cpool_bundle_unlink(&bundle);
184
3.84k
  }
185
3.84k
}
186
187
static void cpool_discard_conn(struct cpool *cpool,
188
                               struct Curl_easy *data,
189
                               struct connectdata *conn,
190
                               bool aborted)
191
3.86k
{
192
3.86k
  struct Curl_easy *admin;
193
3.86k
  bool done = FALSE;
194
195
3.86k
  DEBUGASSERT(data);
196
3.86k
  DEBUGASSERT(!data->conn);
197
3.86k
  DEBUGASSERT(cpool);
198
3.86k
  DEBUGASSERT(conn->cpid == UINT32_MAX);
199
200
3.86k
  admin = Curl_get_admin(data);
201
  /* We MUST NOT discard a connection that is still in use and would
202
   * trigger Use-After-Free. */
203
3.86k
  if(CONN_INUSE(conn)) {
204
0
    CURL_TRC_M(admin, "[CPOOL] not discarding #%" FMT_OFF_T
205
0
               " still in use by %u transfers", conn->connection_id,
206
0
               conn->attached_xfers);
207
0
    DEBUGASSERT(0);
208
0
    return;
209
0
  }
210
211
  /* treat the connection as aborted in CONNECT_ONLY situations, we do
212
   * not know what the APP did with it. */
213
3.86k
  if(conn->bits.connect_only)
214
0
    aborted = TRUE;
215
3.86k
  conn->bits.aborted = aborted;
216
217
  /* We do not shutdown dead connections. The term 'dead' can be misleading
218
   * here, as we also mark errored connections/transfers as 'dead'.
219
   * If we do a shutdown for an aborted transfer, the server might think
220
   * it was successful otherwise (for example an ftps: upload). This is
221
   * not what we want. */
222
3.86k
  if(aborted)
223
102
    done = TRUE;
224
3.86k
  if(!done) {
225
    /* Attempt to shutdown the connection right away. */
226
3.76k
    Curl_cshutdn_try_once(admin, conn, &done);
227
3.76k
  }
228
229
3.86k
  if(done || !data->multi)
230
3.86k
    Curl_cshutdn_terminate(admin, conn, FALSE);
231
0
  else {
232
0
    struct Curl_multi *multi = data->multi;
233
0
    size_t max_shutdowns = multi->max_total_connections;
234
0
    uint32_t num_conns = Curl_uint32_tbl_count(&cpool->conns);
235
236
0
    if(num_conns < max_shutdowns)
237
0
      max_shutdowns -= num_conns;
238
0
    else if(max_shutdowns)
239
0
      max_shutdowns = 1;
240
0
    else /* no connection limit set, let's restrict growth nevertheless */
241
0
      max_shutdowns = CURLMAX(num_conns / 4, 128);
242
0
    Curl_cshutdn_add(&multi->cshutdn, multi, conn, max_shutdowns);
243
0
  }
244
3.86k
}
245
246
void Curl_cpool_init(struct cpool *cpool,
247
                     struct Curl_share *share,
248
                     size_t size)
249
3.94k
{
250
3.94k
  Curl_uint32_tbl_init(&cpool->conns);
251
3.94k
  Curl_uint32_bset_init(&cpool->idles);
252
3.94k
  Curl_hash_init(&cpool->dest2bundle, size, CURL_HASH_TYPE_BYTES,
253
3.94k
                 cpool_bundle_hash_dtor);
254
3.94k
  cpool->share = share;
255
3.94k
  cpool->initialized = TRUE;
256
3.94k
  cpool->in_shutdown = FALSE;
257
3.94k
  cpool->locked = FALSE;
258
3.94k
}
259
260
void Curl_cpool_destroy(struct cpool *cpool, struct Curl_easy *admin)
261
3.96k
{
262
3.96k
  if(cpool && cpool->initialized && admin) {
263
3.94k
    void *entry;
264
3.94k
    uint32_t cpid;
265
266
3.94k
    CURL_TRC_M(admin, "%s[CPOOL] destroy, %u connections",
267
3.94k
               cpool->share ? "[SHARE] " : "",
268
3.94k
               Curl_uint32_tbl_count(&cpool->conns));
269
    /* Move all connections to the shutdown list */
270
3.94k
    CPOOL_LOCK(cpool, admin);
271
3.94k
    if(Curl_uint32_tbl_first(&cpool->conns, &cpid, &entry)) {
272
0
      struct Curl_sigpipe_ctx pipe_ctx;
273
274
0
      sigpipe_init(&pipe_ctx);
275
0
      sigpipe_apply(admin, &pipe_ctx);
276
0
      do {
277
0
        struct connectdata *conn = entry;
278
0
        cpool_remove_conn(cpool, conn);
279
0
        cpool_discard_conn(cpool, admin, conn, FALSE);
280
0
      } while(Curl_uint32_tbl_next(&cpool->conns, cpid, &cpid, &entry));
281
0
      sigpipe_restore(&pipe_ctx);
282
0
    }
283
3.94k
    CPOOL_UNLOCK(cpool, admin);
284
3.94k
    Curl_hash_destroy(&cpool->dest2bundle);
285
3.94k
    Curl_uint32_bset_destroy(&cpool->idles);
286
3.94k
    Curl_uint32_tbl_destroy(&cpool->conns);
287
3.94k
  }
288
3.96k
}
289
290
static struct cpool *cpool_get_instance(struct Curl_easy *data)
291
23.3k
{
292
  /* admin handles do not necessarily find the correct pool */
293
23.3k
  DEBUGASSERT(data->mid);
294
23.3k
  if(CURL_SHARE_KEEP_CONNECT(data->share))
295
0
    return &data->share->cpool;
296
23.3k
  else if(data->multi_easy)
297
19.3k
    return &data->multi_easy->cpool;
298
3.99k
  else if(data->multi)
299
3.93k
    return &data->multi->cpool;
300
62
  return NULL;
301
23.3k
}
302
303
void Curl_cpool_xfer_init(struct Curl_easy *data)
304
3.93k
{
305
3.93k
  struct cpool *cpool = cpool_get_instance(data);
306
307
3.93k
  if(cpool) {
308
3.93k
    CPOOL_LOCK(cpool, data);
309
    /* the identifier inside the connection cache */
310
3.93k
    data->id = cpool->next_easy_id++;
311
3.93k
    if(cpool->next_easy_id == CURL_OFF_T_MAX)
312
0
      cpool->next_easy_id = 0;
313
3.93k
    data->state.last_conn_id = -1;
314
3.93k
    data->state.last_cpid = UINT32_MAX;
315
316
3.93k
    CPOOL_UNLOCK(cpool, data);
317
3.93k
  }
318
0
  else {
319
    /* We should not get here, but in a non-debug build, do something */
320
0
    DEBUGASSERT(0);
321
0
    data->id = 0;
322
0
    data->state.last_conn_id = -1;
323
0
    data->state.last_cpid = UINT32_MAX;
324
0
  }
325
3.93k
}
326
327
static bool cpool_conn_can_be_closed(struct connectdata *conn)
328
0
{
329
  /* CONNECT_ONLY sockets remain in use by the application. */
330
0
  return (conn && !CONN_INUSE(conn) && !conn->bits.connect_only);
331
0
}
332
333
static struct connectdata *cpool_bundle_get_oldest_idle(
334
  struct cpool *cpool,
335
  struct cpool_bundle *bundle,
336
  const struct curltime *pnow)
337
0
{
338
0
  uint32_t cpid, oldest_id = UINT32_MAX;
339
0
  timediff_t unused_ms;
340
0
  timediff_t oldest_ms = -1;
341
342
0
  if(Curl_uint32_spbset_first(&bundle->ids, &cpid)) {
343
0
    do {
344
0
      struct connectdata *conn = Curl_uint32_tbl_get(&cpool->conns, cpid);
345
0
      if(cpool_conn_can_be_closed(conn)) {
346
        /* Set higher score for the age passed since the connection was used */
347
0
        unused_ms =
348
0
          curlx_ptimediff_ms(pnow, &conn->created) - conn->lastused_ms;
349
0
        if(unused_ms > oldest_ms) {
350
0
          oldest_ms = unused_ms;
351
0
          oldest_id = cpid;
352
0
        }
353
0
      }
354
0
      else if(!conn) {
355
0
        DEBUGASSERT(0);
356
0
        Curl_uint32_spbset_remove(&bundle->ids, cpid);
357
0
      }
358
0
    } while(Curl_uint32_spbset_next(&bundle->ids, cpid, &cpid));
359
0
  }
360
0
  return Curl_uint32_tbl_get(&cpool->conns, oldest_id);
361
0
}
362
363
static struct connectdata *cpool_get_oldest_idle(struct cpool *cpool,
364
                                                 const struct curltime *pnow,
365
                                                 timediff_t min_age_ms)
366
0
{
367
0
  uint32_t cpid, oldest_id = UINT32_MAX;
368
0
  timediff_t oldest_idle_ms = -1;
369
0
  timediff_t idle_ms;
370
371
  /* Iterate over all connections that once were idle. They may
372
   * no longer be, in which case we remove them from the set again. */
373
0
  if(Curl_uint32_bset_first(&cpool->idles, &cpid)) {
374
0
    do {
375
0
      struct connectdata *conn = Curl_uint32_tbl_get(&cpool->conns, cpid);
376
0
      if(cpool_conn_can_be_closed(conn)) {
377
0
        idle_ms = curlx_ptimediff_ms(pnow, &conn->created) - conn->lastused_ms;
378
0
        if((idle_ms >= min_age_ms) && (idle_ms > oldest_idle_ms)) {
379
0
          oldest_idle_ms = idle_ms;
380
0
          oldest_id = cpid;
381
0
        }
382
0
      }
383
0
      else {
384
0
        DEBUGASSERT(conn);
385
0
        Curl_uint32_bset_remove(&cpool->idles, cpid);
386
0
      }
387
0
    } while(Curl_uint32_bset_next(&cpool->idles, cpid, &cpid));
388
0
  }
389
0
  return Curl_uint32_tbl_get(&cpool->conns, oldest_id);
390
0
}
391
392
static void cpool_conn_close(struct cpool *cpool,
393
                             struct Curl_easy *data,
394
                             struct connectdata *conn,
395
                             bool aborted)
396
3.86k
{
397
3.86k
  struct Curl_easy *admin;
398
3.86k
  bool do_lock;
399
400
3.86k
  DEBUGASSERT(cpool);
401
3.86k
  DEBUGASSERT(data && !data->conn);
402
3.86k
  if(!cpool)
403
0
    return;
404
405
  /* If this connection is still used by transfers, we cannot close it. */
406
3.86k
  if(CONN_INUSE(conn)) {
407
0
    DEBUGASSERT(0); /* we'd like to know when this happens */
408
0
    DEBUGF(infof(data, "conn terminate when inuse: %u", conn->attached_xfers));
409
0
    return;
410
0
  }
411
412
  /* This method may be called while we are under lock, e.g. from a
413
   * user callback in find. */
414
3.86k
  admin = Curl_get_admin(data);
415
3.86k
  do_lock = !CPOOL_IS_LOCKED(cpool);
416
3.86k
  if(do_lock)
417
15
    CPOOL_LOCK(cpool, admin);
418
419
3.86k
  if(conn->cpid != UINT32_MAX) {
420
3.84k
    cpool_remove_conn(cpool, conn);
421
3.84k
    DEBUGASSERT(conn->cpid == UINT32_MAX);
422
3.84k
  }
423
424
  /* treat the connection as aborted in CONNECT_ONLY situations,
425
   * so no graceful shutdown is attempted. */
426
3.86k
  if(conn->bits.connect_only)
427
0
    aborted = TRUE;
428
429
3.86k
  if(data->multi) {
430
    /* Add it to the multi's cpool for shutdown handling */
431
3.86k
    infof(data, "%s connection #%" FMT_OFF_T,
432
3.86k
          aborted ? "closing" : "shutting down", conn->connection_id);
433
3.86k
    cpool_discard_conn(&data->multi->cpool, data, conn, aborted);
434
3.86k
  }
435
0
  else {
436
    /* No multi available, terminate */
437
0
    infof(data, "closing connection #%" FMT_OFF_T, conn->connection_id);
438
0
    Curl_cshutdn_terminate(admin, conn, !aborted);
439
0
  }
440
441
3.86k
  if(do_lock)
442
15
    CPOOL_UNLOCK(cpool, admin);
443
3.86k
}
444
445
void Curl_conn_close(struct Curl_easy *data,
446
                     struct connectdata *conn,
447
                     bool aborted)
448
3.86k
{
449
3.86k
  struct cpool *cpool = cpool_get_instance(data);
450
3.86k
  cpool_conn_close(cpool, data, conn, aborted);
451
3.86k
}
452
453
/* Evict an idle connection to make room in the pool. A pool owned by
454
 * a share has no multi that could perform a controlled shutdown of the
455
 * connection; terminate it right away. Otherwise, hand it to the
456
 * transfer's multi for shutdown. Expects the pool to be locked. */
457
static void cpool_evict_conn(struct cpool *cpool,
458
                             struct Curl_easy *admin,
459
                             struct connectdata *conn)
460
0
{
461
0
  if(cpool->share) {
462
0
    cpool_remove_conn(cpool, conn);
463
0
    Curl_cshutdn_terminate(admin, conn, TRUE);
464
0
  }
465
0
  else
466
0
    cpool_conn_close(cpool, admin, conn, FALSE);
467
0
}
468
469
3.86k
#define CPOOL_LIMIT_OK     0
470
0
#define CPOOL_LIMIT_DEST   1
471
0
#define CPOOL_LIMIT_TOTAL  2
472
473
static int cpool_check_limits(struct Curl_easy *data,
474
                              uint32_t max_total,
475
                              struct connectdata *to_add,
476
                              uint32_t max_host,
477
                              struct cpool_bundle *bundle,
478
                              const struct curltime *pnow)
479
3.86k
{
480
3.86k
  struct cpool *cpool = cpool_get_instance(data);
481
3.86k
  struct cshutdn *cshutdn = data->multi ? &data->multi->cshutdn : NULL;
482
3.86k
  struct Curl_easy *admin = NULL;
483
484
3.86k
  if(!cpool)
485
0
    return CPOOL_LIMIT_OK;
486
487
3.86k
  if(!max_total && !max_host)
488
3.86k
    return CPOOL_LIMIT_OK;
489
490
0
  if(max_host) {
491
0
    size_t live = 0, shutdowns = 0;
492
    /* if we are at or above `dest_limit`, try to get rid of connections
493
     * in shutdown and, if that does not lower it, evict idle connections
494
     * from the pool. */
495
0
    admin = Curl_get_admin(data);
496
0
    if(bundle) {
497
0
      live = Curl_uint32_spbset_count(&bundle->ids);
498
0
      if(live >= max_host) {
499
0
        size_t over = live - max_host + 1;
500
0
        for(; over; --over) {
501
0
          struct connectdata *oldest_idle =
502
0
            cpool_bundle_get_oldest_idle(cpool, bundle, pnow);
503
0
          if(!oldest_idle)
504
0
            break;
505
          /* disconnect the old conn and continue */
506
0
          CURL_TRC_M(admin, "Shutting down connection #%" FMT_OFF_T
507
0
                     " to '%s' due to destination limit of %u",
508
0
                     oldest_idle->connection_id, oldest_idle->destination,
509
0
                     max_host);
510
0
          cpool_evict_conn(cpool, admin, oldest_idle);
511
0
        }
512
0
        live = Curl_uint32_spbset_count(&bundle->ids);
513
0
      }
514
0
    }
515
0
    if(cshutdn) {
516
0
      shutdowns = Curl_cshutdn_dest_count(cshutdn, to_add->destination);
517
0
      if(shutdowns && ((live + shutdowns) >= max_host)) {
518
0
        size_t over = live + shutdowns - max_host + 1;
519
0
        shutdowns -= Curl_cshutdn_close_oldest(cshutdn, admin,
520
0
                                               to_add->destination, over);
521
0
      }
522
0
    }
523
    /* We may not have gotten rid of as many connections as we wanted to */
524
0
    if((live + shutdowns) >= max_host)
525
0
      return CPOOL_LIMIT_DEST;
526
0
  }
527
528
  /* Internal transfers are outside the total limit */
529
0
  if(max_total && !data->state.internal) {
530
0
    size_t shutdowns = 0;
531
0
    uint32_t num_conns = Curl_uint32_tbl_count(&cpool->conns);
532
533
0
    if(!admin)
534
0
      admin = Curl_get_admin(data);
535
0
    if(num_conns >= max_total) {
536
0
      size_t over = num_conns - max_total + 1;
537
0
      for(; over; --over) {
538
0
        struct connectdata *oldest_idle =
539
0
          cpool_get_oldest_idle(cpool, pnow, 0);
540
0
        if(!oldest_idle)
541
0
          break;
542
        /* disconnect the old conn and continue */
543
0
        CURL_TRC_M(admin, "Shutting down idle connection #%"
544
0
                   FMT_OFF_T " to '%s' due to total limit of %u",
545
0
                   oldest_idle->connection_id, oldest_idle->destination,
546
0
                   max_total);
547
0
        cpool_evict_conn(cpool, admin, oldest_idle);
548
0
      }
549
0
    }
550
551
0
    num_conns = Curl_uint32_tbl_count(&cpool->conns);
552
0
    if(cshutdn) {
553
0
      shutdowns = Curl_cshutdn_count(cshutdn);
554
0
      if(shutdowns && (num_conns + shutdowns) >= max_total) {
555
0
        size_t over = num_conns + shutdowns - max_total + 1;
556
0
        shutdowns -= Curl_cshutdn_close_oldest(cshutdn, admin, NULL, over);
557
0
      }
558
0
    }
559
0
    if((num_conns + shutdowns) >= max_total)
560
0
      return CPOOL_LIMIT_TOTAL;
561
0
  }
562
563
0
  return CPOOL_LIMIT_OK;
564
0
}
565
566
CURLcode Curl_cpool_add(struct Curl_easy *data,
567
                        struct connectdata *conn,
568
                        uint32_t max_total,
569
                        uint32_t max_host,
570
                        const struct curltime *pnow)
571
3.86k
{
572
3.86k
  CURLcode result = CURLE_OK;
573
3.86k
  struct cpool_bundle *bundle = NULL;
574
3.86k
  struct cpool *cpool = cpool_get_instance(data);
575
3.86k
  uint32_t capacity, cpid;
576
3.86k
  DEBUGASSERT(conn);
577
578
3.86k
  DEBUGASSERT(cpool);
579
3.86k
  if(!cpool)
580
0
    return CURLE_FAILED_INIT;
581
582
3.86k
  DEBUGASSERT(conn->cpid == UINT32_MAX);
583
3.86k
  conn->created = *pnow;
584
3.86k
  conn->connect_start_ms = -1;
585
586
3.86k
  CPOOL_LOCK(cpool, data);
587
  /* Find the bundle, should it exist, and check the limits */
588
3.86k
  bundle = cpool_get_bundle(cpool, conn->destination);
589
590
3.86k
  switch(cpool_check_limits(data, max_total, conn, max_host, bundle, pnow)) {
591
0
  case CPOOL_LIMIT_DEST:
592
0
    infof(data, "No more connections allowed to host");
593
0
    result = CURLE_NO_CONNECTION_AVAILABLE;
594
0
    goto out;
595
0
  case CPOOL_LIMIT_TOTAL:
596
0
    infof(data, "No connections available, total of %u reached.",
597
0
          data->multi->max_total_connections);
598
0
    result = CURLE_NO_CONNECTION_AVAILABLE;
599
0
    goto out;
600
3.86k
  default:
601
3.86k
    break;
602
3.86k
  }
603
604
  /* We add the connection */
605
3.86k
  capacity = Curl_uint32_tbl_capacity(&cpool->conns);
606
3.86k
  if(capacity == UINT32_MAX) {
607
0
    infof(data, "No connections available, pool at max capacity");
608
0
    result = CURLE_NO_CONNECTION_AVAILABLE;
609
0
    goto out;
610
0
  }
611
3.86k
  if(Curl_uint32_tbl_count(&cpool->conns) >= capacity) {
612
3.86k
    uint32_t growth, ncapacity;
613
614
3.86k
    growth = CURLMAX(capacity, 16);
615
3.86k
    if((UINT32_MAX - growth) >= capacity)
616
3.86k
      ncapacity = capacity + growth;
617
0
    else
618
0
      ncapacity = UINT32_MAX;
619
    /* Grow bitset first, so table resize failure does not leave a too
620
     * short bitset should that one fail. */
621
3.86k
    if(Curl_uint32_bset_resize(&cpool->idles, ncapacity) ||
622
3.86k
       Curl_uint32_tbl_resize(&cpool->conns, ncapacity)) {
623
5
      result = CURLE_OUT_OF_MEMORY;
624
5
      goto out;
625
5
    }
626
3.86k
  }
627
628
3.85k
  if(!bundle) {
629
3.85k
    bundle = cpool_create_bundle();
630
3.85k
    if(!bundle) {
631
5
      result = CURLE_OUT_OF_MEMORY;
632
5
      goto out;
633
5
    }
634
3.85k
  }
635
636
3.85k
  if(!Curl_uint32_tbl_add(&cpool->conns, conn, &cpid)) {
637
0
    DEBUGASSERT(0);
638
0
    result = CURLE_OUT_OF_MEMORY;
639
0
    goto out;
640
0
  }
641
3.85k
  conn->cpid = cpid;
642
643
3.85k
  if(!cpool_bundle_add_id(cpool, bundle, conn->destination, cpid)) {
644
5
    Curl_uint32_tbl_remove(&cpool->conns, cpid);
645
5
    conn->cpid = UINT32_MAX;
646
5
    result = CURLE_OUT_OF_MEMORY;
647
5
    goto out;
648
5
  }
649
650
3.84k
  conn->connection_id = cpool->next_connection_id++;
651
3.84k
  CURL_TRC_M(data, "[CPOOL] added connection %" FMT_OFF_T ". "
652
3.84k
             "The cache now contains %u members",
653
3.84k
             conn->connection_id, Curl_uint32_tbl_count(&cpool->conns));
654
3.86k
out:
655
3.86k
  cpool_bundle_unlink(&bundle);
656
3.86k
  CPOOL_UNLOCK(cpool, data);
657
658
3.86k
  return result;
659
3.86k
}
660
661
/* This function iterates the entire connection pool and calls the function
662
   func() with the connection pointer as the first argument and the supplied
663
   'param' argument as the other.
664
665
   The cpool lock is still held when the callback is called. It needs it,
666
   so that it can safely continue traversing the lists once the callback
667
   returns.
668
669
   Returns TRUE if the loop was aborted due to the callback's return code.
670
671
   Return 0 from func() to continue the loop, return 1 to abort it.
672
 */
673
static bool cpool_foreach(struct Curl_easy *data,
674
                          struct cpool *cpool,
675
                          void *param,
676
                          int (*func)(struct cpool *cpool,
677
                                      struct Curl_easy *data,
678
                                      struct connectdata *conn, void *param))
679
0
{
680
0
  void *entry;
681
0
  uint32_t cpid;
682
683
0
  if(!cpool)
684
0
    return FALSE;
685
686
0
  if(Curl_uint32_tbl_first(&cpool->conns, &cpid, &entry)) {
687
0
    do {
688
0
      struct connectdata *conn = entry;
689
0
      if(conn && func(cpool, data, conn, param) == 1)
690
0
        return TRUE;
691
0
    } while(Curl_uint32_tbl_next(&cpool->conns, cpid, &cpid, &entry));
692
0
  }
693
0
  return FALSE;
694
0
}
695
696
/*
697
 * A connection (already in the pool) has become idle. Do any
698
 * cleanups in regard to the pool's limits.
699
 *
700
 * Return TRUE if idle connection kept in pool, FALSE if closed.
701
 */
702
static bool cpool_conn_now_idle(struct cpool *cpool,
703
                                struct Curl_easy *data,
704
                                struct connectdata *conn,
705
                                const struct curltime *pnow)
706
0
{
707
0
  struct connectdata *oldest_idle = NULL;
708
0
  struct Curl_easy *admin;
709
0
  uint32_t maxconnects;
710
0
  bool kept = TRUE;
711
0
  timediff_t min_age_ms = 0;
712
713
0
  if(!data || !data->multi)
714
0
    return kept;
715
716
0
  Curl_uint32_bset_add(&cpool->idles, conn->cpid);
717
718
0
  if(!data->multi->maxconnects) {
719
    /* Attached transfers is a weak indicator of business. */
720
0
    uint32_t attached = Curl_multi_xfers_attached(data->multi);
721
0
    maxconnects = (attached <= UINT32_MAX / 2) ? attached * 2 : UINT32_MAX;
722
    /* We are guessing. So, only evict a "seemingly superfluous" connection
723
     * when has not been used for this long, */
724
0
    min_age_ms = 1000;
725
0
  }
726
0
  else {
727
0
    maxconnects = data->multi->maxconnects;
728
0
  }
729
730
0
  if(cpool && maxconnects && (maxconnects < UINT32_MAX)) {
731
0
    uint32_t num_conns = Curl_uint32_tbl_count(&cpool->conns);
732
0
    admin = Curl_get_admin(data);
733
0
    if(num_conns > maxconnects) {
734
0
      infof(data, "Connection pool is full, closing the oldest of %u/%u",
735
0
            num_conns, maxconnects);
736
0
      oldest_idle = cpool_get_oldest_idle(cpool, pnow, min_age_ms);
737
0
      kept = (oldest_idle != conn);
738
0
      if(oldest_idle) {
739
0
        cpool_evict_conn(cpool, admin, oldest_idle);
740
0
      }
741
0
    }
742
0
  }
743
744
0
  return kept;
745
0
}
746
747
static void cpool_prune_dead(struct cpool *cpool,
748
                             struct Curl_easy *data,
749
                             const struct curltime *pnow);
750
751
static bool cpool_find_act(struct cpool *cpool,
752
                           struct Curl_easy *data,
753
                           struct connectdata *conn,
754
                           cpool_match_result match)
755
0
{
756
0
  switch(match) {
757
0
  case CPOOL_MATCH_FOUND:
758
0
    return TRUE;
759
0
  case CPOOL_MATCH_TOO_OLD:
760
0
    if(!cpool_conn_can_be_closed(conn))
761
0
      return FALSE;
762
0
    FALLTHROUGH();
763
0
  case CPOOL_MATCH_CLOSE:
764
0
    cpool_conn_close(cpool, data, conn, FALSE);
765
0
    break;
766
0
  default:
767
0
    break;
768
0
  }
769
0
  return FALSE;
770
0
}
771
772
bool Curl_cpool_find(struct Curl_easy *data,
773
                     const char *destination,
774
                     bool prune_dead,
775
                     const struct curltime *pnow,
776
                     Curl_cpool_conn_match_cb *conn_cb,
777
                     Curl_cpool_done_match_cb *done_cb,
778
                     void *userdata)
779
0
{
780
0
  struct cpool *cpool = cpool_get_instance(data);
781
0
  struct cpool_bundle *bundle = NULL;
782
0
  bool found = FALSE;
783
784
0
  DEBUGASSERT(cpool);
785
0
  DEBUGASSERT(conn_cb);
786
0
  if(!cpool)
787
0
    return FALSE;
788
789
0
  CPOOL_LOCK(cpool, data);
790
791
0
  if(prune_dead)
792
0
    cpool_prune_dead(cpool, data, pnow);
793
794
0
  if(data->state.last_cpid != UINT32_MAX) {
795
0
    struct connectdata *conn =
796
0
      Curl_uint32_tbl_get(&cpool->conns, data->state.last_cpid);
797
0
    if(conn && (data->state.last_conn_id == conn->connection_id)) {
798
      /* Indeed the last connection used by `data` still exists.
799
       * Check that first, so that connection use gets "sticky". */
800
0
      found = cpool_find_act(cpool, data, conn, conn_cb(conn, userdata));
801
0
      if(found)
802
0
        goto out;
803
0
    }
804
0
    else {
805
      /* No longer found here. */
806
0
      data->state.last_conn_id = -1;
807
0
      data->state.last_cpid = UINT32_MAX;
808
0
    }
809
0
  }
810
811
0
  bundle = cpool_get_bundle(cpool, destination);
812
0
  if(bundle) {
813
0
    uint32_t cpid;
814
0
    if(Curl_uint32_spbset_first(&bundle->ids, &cpid)) {
815
0
      do {
816
0
        struct connectdata *conn = Curl_uint32_tbl_get(&cpool->conns, cpid);
817
0
        if(conn) {
818
0
          if(data->state.last_conn_id != conn->connection_id) {
819
0
            found = cpool_find_act(cpool, data, conn, conn_cb(conn, userdata));
820
0
            if(found)
821
0
              goto out;
822
0
          }
823
0
        }
824
0
        else {
825
0
          DEBUGASSERT(0);
826
0
          Curl_uint32_spbset_remove(&bundle->ids, cpid);
827
0
        }
828
0
      } while(Curl_uint32_spbset_next(&bundle->ids, cpid, &cpid));
829
0
    }
830
0
  }
831
832
0
out:
833
0
  if(done_cb) {
834
0
    found = done_cb(userdata);
835
0
  }
836
0
  cpool_bundle_unlink(&bundle);
837
0
  CPOOL_UNLOCK(cpool, data);
838
0
  return found;
839
0
}
840
841
struct cpool_reaper_ctx {
842
  size_t reaped;
843
  const struct curltime *pnow;
844
};
845
846
static int cpool_reap_dead_cb(struct cpool *cpool,
847
                              struct Curl_easy *admin,
848
                              struct connectdata *conn, void *param)
849
0
{
850
0
  struct cpool_reaper_ctx *reaper = param;
851
852
0
  if(cpool_conn_can_be_closed(conn)) {
853
0
    if(conn->bits.no_reuse || conn->bits.close ||
854
0
       !Curl_cpool_conn_seems_healthy(conn, admin, reaper->pnow)) {
855
      /* terminate conn and stop the iteration */
856
0
      reaper->reaped++;
857
0
      cpool_conn_close(cpool, admin, conn, FALSE);
858
0
    }
859
0
  }
860
0
  return 0; /* continue iteration */
861
0
}
862
863
/*
864
 * This function scans the data's connection pool for half-open/dead
865
 * connections, closes and removes them.
866
 * The cleanup is done at most once per second.
867
 */
868
static void cpool_prune_dead(struct cpool *cpool,
869
                             struct Curl_easy *data,
870
                             const struct curltime *pnow)
871
0
{
872
0
  timediff_t elapsed_ms = curlx_ptimediff_ms(pnow, &cpool->last_cleanup);
873
874
0
  if(elapsed_ms >= 1000L) {
875
0
    struct Curl_easy *admin = Curl_get_admin(data);
876
0
    struct cpool_reaper_ctx reaper;
877
878
0
    memset(&reaper, 0, sizeof(reaper));
879
0
    reaper.pnow = pnow;
880
0
    cpool_foreach(admin, cpool, &reaper, cpool_reap_dead_cb);
881
0
    cpool->last_cleanup = *pnow;
882
0
  }
883
0
}
884
885
static int conn_upkeep(struct cpool *cpool,
886
                       struct Curl_easy *admin,
887
                       struct connectdata *conn,
888
                       void *param)
889
0
{
890
0
  const struct curltime *pnow = Curl_pgrs_now(admin);
891
892
0
  (void)param;
893
0
  if((curlx_ptimediff_ms(pnow, &conn->created) - conn->lastupkeep_ms) >=
894
0
     admin->set.upkeep_interval_ms) {
895
0
    CURLcode result;
896
897
0
    conn->lastupkeep_ms = curlx_ptimediff_ms(pnow, &conn->created);
898
    /* briefly attach for action */
899
0
    Curl_attach_connection(admin, conn, FALSE);
900
0
    result = Curl_conn_keep_alive(admin, conn);
901
0
    Curl_detach_connection(admin);
902
903
0
    if(result && cpool_conn_can_be_closed(conn)) {
904
0
      cpool_conn_close(cpool, admin, conn, FALSE);
905
0
    }
906
0
  }
907
0
  return 0; /* continue iteration */
908
0
}
909
910
CURLcode Curl_cpool_upkeep(struct Curl_easy *data)
911
0
{
912
0
  struct cpool *cpool = cpool_get_instance(data);
913
0
  struct Curl_easy *admin = Curl_get_admin(data);
914
915
0
  if(!cpool)
916
0
    return CURLE_OK;
917
918
0
  CPOOL_LOCK(cpool, admin);
919
0
  cpool_foreach(admin, cpool, NULL, conn_upkeep);
920
0
  CPOOL_UNLOCK(cpool, admin);
921
0
  return CURLE_OK;
922
0
}
923
924
struct connectdata *Curl_cpool_get_last_conn(struct Curl_easy *data)
925
3.99k
{
926
3.99k
  struct cpool *cpool = cpool_get_instance(data);
927
3.99k
  if(cpool && (data->state.last_cpid != UINT32_MAX)) {
928
3.84k
    struct connectdata *conn;
929
930
3.84k
    CPOOL_LOCK(cpool, data);
931
3.84k
    conn = Curl_uint32_tbl_get(&cpool->conns, data->state.last_cpid);
932
3.84k
    CPOOL_UNLOCK(cpool, data);
933
3.84k
    if(conn && (data->state.last_conn_id == conn->connection_id))
934
0
      return conn;
935
3.84k
    data->state.last_cpid = UINT32_MAX;
936
3.84k
    data->state.last_conn_id = -1;
937
3.84k
  }
938
3.99k
  return NULL;
939
3.99k
}
940
941
void Curl_cpool_return(struct Curl_easy *data,
942
                       struct connectdata *conn,
943
                       Curl_cpool_return_cb *cb, void *cbdata,
944
                       const struct curltime *pnow)
945
3.84k
{
946
3.84k
  struct cpool *cpool = cpool_get_instance(data);
947
948
3.84k
  CPOOL_LOCK(cpool, data);
949
950
  /* remember times, connection had been used just before */
951
3.84k
  conn->lastchecked_ms = conn->lastupkeep_ms = conn->lastused_ms =
952
3.84k
    curlx_ptimediff_ms(pnow, &conn->created);
953
954
3.84k
  switch(cb(data, conn, cbdata, pnow)) {
955
0
  case CPOOL_DO_KEEP:
956
0
    break;
957
0
  case CPOOL_DO_IDLE:
958
    /* the connection is no longer in use by any transfer */
959
0
    if(cpool_conn_now_idle(cpool, data, conn, pnow)) {
960
      /* connection kept in the cpool */
961
0
      infof(data, "Connection #%" FMT_OFF_T " to host %s:%u left intact",
962
0
            conn->connection_id, conn->origin->user_hostname,
963
0
            conn->origin->port);
964
0
    }
965
0
    else { /* connection was removed from the cpool and destroyed. */
966
0
      data->state.last_conn_id = -1;
967
0
      data->state.last_cpid = UINT32_MAX;
968
0
    }
969
0
    break;
970
3.76k
  case CPOOL_DO_CLOSE:
971
3.76k
    Curl_conn_close(data, conn, FALSE);
972
3.76k
    break;
973
87
  case CPOOL_DO_TERMINATE:
974
87
    Curl_conn_close(data, conn, TRUE);
975
87
    break;
976
3.84k
  }
977
978
3.84k
  CPOOL_UNLOCK(cpool, data);
979
3.84k
}
980
981
static int cpool_reap_no_reuse(struct cpool *cpool,
982
                               struct Curl_easy *admin,
983
                               struct connectdata *conn, void *param)
984
0
{
985
0
  (void)param;
986
0
  conn->bits.no_reuse = TRUE;
987
0
  if(cpool_conn_can_be_closed(conn))
988
0
    cpool_conn_close(cpool, admin, conn, FALSE);
989
0
  return 0; /* continue iteration */
990
0
}
991
992
void Curl_cpool_nw_changed(struct cpool *cpool, struct Curl_easy *admin)
993
0
{
994
0
  if(cpool && admin) {
995
0
    CPOOL_LOCK(cpool, admin);
996
0
    cpool_foreach(admin, cpool, NULL, cpool_reap_no_reuse);
997
0
    CPOOL_UNLOCK(cpool, admin);
998
0
  }
999
0
}
1000
1001
/* A connection has to have been idle for less than 'conn_max_idle_ms'
1002
   (the success rate is too low after this), or created less than
1003
   'conn_max_age_ms' ago, to be subject for reuse. */
1004
static bool cpool_conn_too_old(struct Curl_easy *data,
1005
                               struct connectdata *conn,
1006
                               const struct curltime *pnow)
1007
0
{
1008
0
  timediff_t age_ms;
1009
1010
0
  if(data->set.conn_max_idle_ms) {
1011
0
    age_ms = curlx_ptimediff_ms(pnow, &conn->created) - conn->lastused_ms;
1012
0
    if(age_ms > data->set.conn_max_idle_ms) {
1013
0
      infof(data, "Too old connection (%" FMT_TIMEDIFF_T
1014
0
            " ms idle, max idle is %" FMT_TIMEDIFF_T " ms), disconnect it",
1015
0
            age_ms, data->set.conn_max_idle_ms);
1016
0
      return TRUE;
1017
0
    }
1018
0
  }
1019
1020
0
  if(data->set.conn_max_age_ms) {
1021
0
    age_ms = curlx_ptimediff_ms(pnow, &conn->created);
1022
0
    if(age_ms > data->set.conn_max_age_ms) {
1023
0
      infof(data,
1024
0
            "Too old connection (created %" FMT_TIMEDIFF_T
1025
0
            " ms ago, max lifetime is %" FMT_TIMEDIFF_T " ms), disconnect it",
1026
0
            age_ms, data->set.conn_max_age_ms);
1027
0
      return TRUE;
1028
0
    }
1029
0
  }
1030
1031
0
  return FALSE;
1032
0
}
1033
1034
bool Curl_cpool_conn_seems_healthy(struct connectdata *conn,
1035
                                   struct Curl_easy *data,
1036
                                   const struct curltime *pnow)
1037
0
{
1038
0
  struct Curl_easy *admin;
1039
0
  bool healthy = TRUE;
1040
1041
0
  DEBUGASSERT(!data->conn);
1042
0
  if(cpool_conn_can_be_closed(conn) && cpool_conn_too_old(data, conn, pnow))
1043
0
    return FALSE;
1044
1045
  /* An idle, non-multiplexed connection must not be reused when it has
1046
   * input pending (RFC 9112, section 9.2). Check this:
1047
   * - on a connection that is not in use
1048
   * - or a connection having its own "is dead" callback
1049
   * - or the last check was more than a second ago */
1050
0
  if(CONN_INUSE(conn) &&
1051
0
     !conn->scheme->run->connection_is_dead &&
1052
0
     (curlx_ptimediff_ms(pnow, &conn->created) - conn->lastchecked_ms) < 1000)
1053
0
    return TRUE;
1054
1055
0
  admin = Curl_get_admin(data);
1056
0
  if(conn->scheme->run->connection_is_dead) {
1057
0
    Curl_attach_connection(admin, conn, FALSE);
1058
0
    healthy = !conn->scheme->run->connection_is_dead(admin, conn);
1059
0
    Curl_detach_connection(admin);
1060
0
  }
1061
0
  else {
1062
0
    bool input_pending = FALSE;
1063
1064
0
    Curl_attach_connection(admin, conn, FALSE);
1065
0
    healthy = Curl_conn_is_alive(admin, conn, &input_pending);
1066
0
    Curl_detach_connection(admin);
1067
0
    if(healthy && input_pending && !CONN_INUSE(conn) &&
1068
0
       !Curl_conn_is_multiplex(conn)) {
1069
      /* Non-multiplexed connections without attached transfers should
1070
       * not have input pending. The input might be a TLS Notify Close,
1071
       * for all we know. */
1072
0
      DEBUGF(infof(data, "connection has no transfer but input, not healthy"));
1073
0
      healthy = FALSE;
1074
0
    }
1075
0
  }
1076
1077
0
  if(healthy)
1078
0
    conn->lastchecked_ms = curlx_ptimediff_ms(pnow, &conn->created);
1079
0
  return healthy;
1080
0
}
1081
1082
void Curl_cpool_conn_was_used(struct Curl_easy *data,
1083
                              struct connectdata *conn,
1084
                              const struct curltime *pnow)
1085
0
{
1086
0
  (void)data;
1087
0
  conn->lastupkeep_ms = curlx_ptimediff_ms(pnow, &conn->created);
1088
0
}
1089
1090
timediff_t Curl_cpool_conn_age_ms(struct Curl_easy *data,
1091
                                  struct connectdata *conn,
1092
                                  const struct curltime *pnow)
1093
0
{
1094
0
  (void)data;
1095
0
  return curlx_ptimediff_ms(pnow, &conn->created);
1096
0
}