Coverage Report

Created: 2026-07-14 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Utilities/cmcurl/lib/connect.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 "curl_trc.h"
28
#include "strerror.h"
29
#include "cfilters.h"
30
#include "connect.h"
31
#include "cf-dns.h"
32
#include "cf-https-connect.h"
33
#include "cf-setup.h"
34
#include "multiif.h"
35
#include "progress.h"
36
#include "conncache.h"
37
#include "multihandle.h"
38
#include "select.h"
39
#include "curlx/strparse.h"
40
41
#if !defined(CURL_DISABLE_ALTSVC) || defined(USE_HTTPSRR)
42
43
enum alpnid Curl_alpn2alpnid(const unsigned char *name, size_t len)
44
{
45
  if(len == 2) {
46
    if(!memcmp(name, "h1", 2))
47
      return ALPN_h1;
48
    if(!memcmp(name, "h2", 2))
49
      return ALPN_h2;
50
    if(!memcmp(name, "h3", 2))
51
      return ALPN_h3;
52
  }
53
  else if(len == 8) {
54
    if(!memcmp(name, "http/1.1", 8))
55
      return ALPN_h1;
56
  }
57
  return ALPN_none; /* unknown, probably rubbish input */
58
}
59
60
enum alpnid Curl_str2alpnid(const struct Curl_str *cstr)
61
{
62
  return Curl_alpn2alpnid((const unsigned char *)curlx_str(cstr),
63
                          curlx_strlen(cstr));
64
}
65
66
#endif
67
68
/*
69
 * timeleft_now_ms() returns the amount of milliseconds left allowed for the
70
 * transfer/connection. If the value is 0, there is no timeout (ie there is
71
 * infinite time left). If the value is negative, the timeout time has already
72
 * elapsed.
73
 *
74
 * @unittest 1303
75
 */
76
UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data,
77
                                    const struct curltime *pnow);
78
UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data,
79
                                    const struct curltime *pnow)
80
0
{
81
0
  timediff_t timeleft_ms = 0;
82
0
  timediff_t ctimeleft_ms = 0;
83
84
0
  if(Curl_shutdown_started(data, FIRSTSOCKET))
85
0
    return Curl_shutdown_timeleft(data, data->conn, FIRSTSOCKET);
86
0
  else if(Curl_is_connecting(data)) {
87
0
    timediff_t ctimeout_ms = (data->set.connecttimeout > 0) ?
88
0
      data->set.connecttimeout : DEFAULT_CONNECT_TIMEOUT;
89
0
    ctimeleft_ms = ctimeout_ms -
90
0
      curlx_ptimediff_ms(pnow, &data->progress.t_startsingle);
91
0
    if(!ctimeleft_ms)
92
0
      ctimeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */
93
0
  }
94
0
  else if(!data->set.timeout || data->set.connect_only) {
95
0
    return 0; /* no timeout in place or checked, return "no limit" */
96
0
  }
97
98
0
  if(data->set.timeout) {
99
0
    timeleft_ms = data->set.timeout -
100
0
      curlx_ptimediff_ms(pnow, &data->progress.t_startop);
101
0
    if(!timeleft_ms)
102
0
      timeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */
103
0
  }
104
105
0
  if(!ctimeleft_ms)
106
0
    return timeleft_ms;
107
0
  else if(!timeleft_ms)
108
0
    return ctimeleft_ms;
109
0
  return CURLMIN(ctimeleft_ms, timeleft_ms);
110
0
}
111
112
timediff_t Curl_timeleft_ms(struct Curl_easy *data)
113
0
{
114
0
  return timeleft_now_ms(data, Curl_pgrs_now(data));
115
0
}
116
117
void Curl_shutdown_start(struct Curl_easy *data, int sockindex,
118
                         int timeout_ms)
119
0
{
120
0
  struct connectdata *conn = data->conn;
121
122
0
  DEBUGASSERT(conn);
123
0
  conn->shutdown.start[sockindex] = *Curl_pgrs_now(data);
124
0
  conn->shutdown.timeout_ms = (timeout_ms > 0) ?
125
0
    (timediff_t)timeout_ms :
126
0
    ((data->set.shutdowntimeout > 0) ?
127
0
     data->set.shutdowntimeout : DEFAULT_SHUTDOWN_TIMEOUT_MS);
128
  /* Set a timer, unless we operate on the admin handle */
129
0
  if(data->mid)
130
0
    Curl_expire_ex(data, conn->shutdown.timeout_ms, EXPIRE_SHUTDOWN);
131
0
  CURL_TRC_M(data, "shutdown start on%s connection",
132
0
             sockindex ? " secondary" : "");
133
0
}
134
135
timediff_t Curl_shutdown_timeleft(struct Curl_easy *data,
136
                                  struct connectdata *conn,
137
                                  int sockindex)
138
0
{
139
0
  timediff_t left_ms;
140
141
0
  if(!conn->shutdown.start[sockindex].tv_sec ||
142
0
     (conn->shutdown.timeout_ms <= 0))
143
0
    return 0; /* not started or no limits */
144
145
0
  left_ms = conn->shutdown.timeout_ms -
146
0
            curlx_ptimediff_ms(Curl_pgrs_now(data),
147
0
                               &conn->shutdown.start[sockindex]);
148
0
  return left_ms ? left_ms : -1;
149
0
}
150
151
timediff_t Curl_conn_shutdown_timeleft(struct Curl_easy *data,
152
                                       struct connectdata *conn)
153
0
{
154
0
  timediff_t left_ms = 0, ms;
155
0
  int i;
156
157
0
  for(i = 0; conn->shutdown.timeout_ms && (i < 2); ++i) {
158
0
    if(!conn->shutdown.start[i].tv_sec)
159
0
      continue;
160
0
    ms = Curl_shutdown_timeleft(data, conn, i);
161
0
    if(ms && (!left_ms || ms < left_ms))
162
0
      left_ms = ms;
163
0
  }
164
0
  return left_ms;
165
0
}
166
167
void Curl_shutdown_clear(struct Curl_easy *data, int sockindex)
168
0
{
169
0
  struct curltime *pt = &data->conn->shutdown.start[sockindex];
170
0
  memset(pt, 0, sizeof(*pt));
171
0
}
172
173
bool Curl_shutdown_started(struct Curl_easy *data, int sockindex)
174
0
{
175
0
  if(data->conn) {
176
0
    struct curltime *pt = &data->conn->shutdown.start[sockindex];
177
0
    return (pt->tv_sec > 0) || (pt->tv_usec > 0);
178
0
  }
179
0
  return FALSE;
180
0
}
181
182
/*
183
 * Used to extract socket and connectdata struct for the most recent
184
 * transfer on the given Curl_easy.
185
 *
186
 * The returned socket will be CURL_SOCKET_BAD in case of failure!
187
 */
188
curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
189
                                  struct connectdata **connp)
190
0
{
191
0
  DEBUGASSERT(data);
192
193
  /* this works for an easy handle:
194
   * - that has been used for curl_easy_perform()
195
   * - that is associated with a multi handle, and whose connection
196
   *   was detached with CURLOPT_CONNECT_ONLY
197
   */
198
0
  if(data->state.lastconnect_id != -1) {
199
0
    struct connectdata *conn;
200
201
0
    conn = Curl_cpool_get_conn(data, data->state.lastconnect_id);
202
0
    if(!conn) {
203
0
      data->state.lastconnect_id = -1;
204
0
      return CURL_SOCKET_BAD;
205
0
    }
206
207
0
    if(connp)
208
      /* only store this if the caller cares for it */
209
0
      *connp = conn;
210
0
    return conn->sock[FIRSTSOCKET];
211
0
  }
212
0
  return CURL_SOCKET_BAD;
213
0
}
214
215
/*
216
 * Curl_conncontrol() marks streams or connection for closure.
217
 */
218
void Curl_conncontrol(struct connectdata *conn,
219
                      int ctrl /* see defines in header */
220
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
221
                      , const char *reason
222
#endif
223
  )
224
0
{
225
  /* close if a connection, or a stream that is not multiplexed. */
226
  /* This function will be called both before and after this connection is
227
     associated with a transfer. */
228
0
  bool closeit, is_multiplex;
229
0
  DEBUGASSERT(conn);
230
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
231
  (void)reason; /* useful for debugging */
232
#endif
233
0
  is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET);
234
0
  closeit = (ctrl == CONNCTRL_CONNECTION) ||
235
0
            ((ctrl == CONNCTRL_STREAM) && !is_multiplex);
236
0
  if((ctrl == CONNCTRL_STREAM) && is_multiplex)
237
0
    ;  /* stream signal on multiplex conn never affects close state */
238
0
  else if((curl_bit)closeit != conn->bits.close) {
239
0
    conn->bits.close = closeit; /* the only place in the source code that
240
                                   should assign this bit */
241
0
  }
242
0
}
243
244
CURLcode Curl_conn_setup(struct Curl_easy *data,
245
                         struct connectdata *conn,
246
                         int sockindex,
247
                         int ssl_mode)
248
0
{
249
0
  CURLcode result = CURLE_OK;
250
0
  struct Curl_peer *peer = Curl_conn_get_first_peer(conn, sockindex);
251
0
  uint8_t dns_queries;
252
253
0
  DEBUGASSERT(data);
254
0
  DEBUGASSERT(conn->scheme);
255
0
  DEBUGASSERT(!conn->cfilter[sockindex]);
256
257
0
  if(!peer)
258
0
    return CURLE_FAILED_INIT;
259
260
0
#ifndef CURL_DISABLE_HTTP
261
0
  if(!conn->cfilter[sockindex] &&
262
0
     conn->scheme->protocol == CURLPROTO_HTTPS) {
263
0
    DEBUGASSERT(ssl_mode != CURL_CF_SSL_DISABLE);
264
0
    result = Curl_cf_https_setup(data, conn, sockindex);
265
0
    if(result)
266
0
      goto out;
267
0
  }
268
0
#endif /* !CURL_DISABLE_HTTP */
269
270
  /* Still no cfilter set, apply default. */
271
0
  if(!conn->cfilter[sockindex]) {
272
0
    result = Curl_cf_setup_add(data, conn, sockindex,
273
0
                               conn->transport_wanted, ssl_mode);
274
0
    if(result)
275
0
      goto out;
276
0
  }
277
278
0
  dns_queries = Curl_resolv_dns_queries(data, conn->ip_version);
279
#ifdef USE_HTTPSRR
280
  if(sockindex == FIRSTSOCKET)
281
    dns_queries |= CURL_DNSQ_HTTPS;
282
#endif
283
0
  result = Curl_cf_dns_add(data, conn, sockindex, peer, dns_queries,
284
0
                           conn->transport_wanted);
285
0
  DEBUGASSERT(conn->cfilter[sockindex]);
286
0
out:
287
0
  return result;
288
0
}
289
290
#ifdef CURLVERBOSE
291
static CURLcode conn_connect_trace(struct Curl_easy *data,
292
                                   struct Curl_cfilter *cf)
293
0
{
294
0
  if(Curl_trc_is_verbose(data)) {
295
0
    struct ip_quadruple ipquad;
296
0
    bool is_ipv6;
297
0
    CURLcode result;
298
299
0
    result = Curl_conn_cf_get_ip_info(cf, data, &is_ipv6, &ipquad);
300
0
    if(result)
301
0
      return result;
302
303
0
    infof(data, "Established %sconnection to %s (%s port %u) from %s port %u ",
304
0
          (cf->sockindex == SECONDARYSOCKET) ? "2nd " : "",
305
0
          CURL_CONN_HOST_DISPNAME(data->conn),
306
0
          ipquad.remote_ip, ipquad.remote_port,
307
0
          ipquad.local_ip, ipquad.local_port);
308
0
  }
309
0
  return CURLE_OK;
310
0
}
311
#endif
312
313
/**
314
 * Update connection statistics
315
 */
316
static void conn_report_connect_stats(struct Curl_cfilter *cf,
317
                                      struct Curl_easy *data)
318
0
{
319
0
  if(cf) {
320
0
    struct curltime connected;
321
0
    struct curltime appconnected;
322
323
0
    memset(&connected, 0, sizeof(connected));
324
0
    cf->cft->query(cf, data, CF_QUERY_TIMER_CONNECT, NULL, &connected);
325
0
    if(connected.tv_sec || connected.tv_usec)
326
0
      Curl_pgrsTimeWas(data, TIMER_CONNECT, connected);
327
328
0
    memset(&appconnected, 0, sizeof(appconnected));
329
0
    cf->cft->query(cf, data, CF_QUERY_TIMER_APPCONNECT, NULL, &appconnected);
330
0
    if(appconnected.tv_sec || appconnected.tv_usec)
331
0
      Curl_pgrsTimeWas(data, TIMER_APPCONNECT, appconnected);
332
0
  }
333
0
}
334
335
CURLcode Curl_conn_connect(struct Curl_easy *data,
336
                           int sockindex,
337
                           bool blocking,
338
                           bool *done)
339
0
{
340
0
#define CF_CONN_NUM_POLLS_ON_STACK 5
341
0
  struct pollfd a_few_on_stack[CF_CONN_NUM_POLLS_ON_STACK];
342
0
  struct easy_pollset ps;
343
0
  struct curl_pollfds cpfds;
344
0
  struct Curl_cfilter *cf;
345
0
  CURLcode result = CURLE_OK;
346
347
0
  DEBUGASSERT(data);
348
0
  DEBUGASSERT(data->conn);
349
0
  if(!CONN_SOCK_IDX_VALID(sockindex))
350
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
351
352
0
  if(data->conn->scheme->flags & PROTOPT_NONETWORK) {
353
0
    *done = TRUE;
354
0
    return CURLE_OK;
355
0
  }
356
357
0
  cf = data->conn->cfilter[sockindex];
358
0
  if(!cf) {
359
0
    *done = FALSE;
360
0
    return CURLE_FAILED_INIT;
361
0
  }
362
363
0
  *done = (bool)cf->connected;
364
0
  if(*done)
365
0
    return CURLE_OK;
366
367
0
  Curl_pollset_init(&ps);
368
0
  Curl_pollfds_init(&cpfds, a_few_on_stack, CF_CONN_NUM_POLLS_ON_STACK);
369
0
  while(!*done) {
370
0
    if(Curl_conn_needs_flush(data, sockindex)) {
371
0
      DEBUGF(infof(data, "Curl_conn_connect(index=%d), flush", sockindex));
372
0
      result = Curl_conn_flush(data, sockindex);
373
0
      if(result && (result != CURLE_AGAIN))
374
0
        goto out;
375
0
    }
376
377
0
    result = cf->cft->do_connect(cf, data, done);
378
0
    CURL_TRC_CF(data, cf, "Curl_conn_connect(block=%d) -> %d, done=%d",
379
0
                blocking, (int)result, *done);
380
0
    if(!result && *done) {
381
      /* A final sanity check on connection security */
382
0
      if((data->state.origin->scheme->flags & PROTOPT_SSL) &&
383
0
         (sockindex == FIRSTSOCKET) &&
384
0
         !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) {
385
0
        DEBUGASSERT(0);
386
0
        failf(data, "transfer requires SSL, but not connected via SSL");
387
0
        result = CURLE_FAILED_INIT;
388
0
        goto out;
389
0
      }
390
      /* Now that the complete filter chain is connected, let all filters
391
       * persist information at the connection. E.g. cf-socket sets the
392
       * socket and ip related information. */
393
0
      Curl_conn_cntrl_update_info(data, data->conn);
394
0
      conn_report_connect_stats(cf, data);
395
0
      data->conn->keepalive = *Curl_pgrs_now(data);
396
0
      VERBOSE(result = conn_connect_trace(data, cf));
397
0
      VERBOSE(Curl_conn_trc_filters(data, sockindex, "connected"));
398
0
      Curl_conn_remove_setup_filters(data, sockindex);
399
0
      VERBOSE(Curl_conn_trc_filters(data, sockindex, "reduced to"));
400
0
      goto out;
401
0
    }
402
0
    else if(result) {
403
0
      CURL_TRC_CF(data, cf, "Curl_conn_connect(), filter returned %d",
404
0
                  (int)result);
405
0
      VERBOSE(Curl_conn_trc_filters(data, sockindex, "failed to connect"));
406
0
      conn_report_connect_stats(cf, data);
407
0
      goto out;
408
0
    }
409
410
0
    if(!blocking)
411
0
      goto out;
412
0
    else {
413
      /* check allowed time left */
414
0
      const timediff_t timeout_ms = Curl_timeleft_ms(data);
415
0
      curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
416
0
      int rc;
417
418
0
      if(timeout_ms < 0) {
419
        /* no need to continue if time already is up */
420
0
        failf(data, "connect timeout");
421
0
        result = CURLE_OPERATION_TIMEDOUT;
422
0
        goto out;
423
0
      }
424
425
0
      CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), do poll");
426
0
      Curl_pollset_reset(&ps);
427
0
      Curl_pollfds_reset(&cpfds);
428
      /* In general, we want to send after connect, wait on that. */
429
0
      if(sockfd != CURL_SOCKET_BAD)
430
0
        result = Curl_pollset_set_out_only(data, &ps, sockfd);
431
0
      if(!result)
432
0
        result = Curl_conn_adjust_pollset(data, data->conn, &ps);
433
0
      if(result)
434
0
        goto out;
435
0
      result = Curl_pollfds_add_ps(&cpfds, &ps);
436
0
      if(result)
437
0
        goto out;
438
439
0
      rc = Curl_poll(cpfds.pfds, cpfds.n,
440
0
                     CURLMIN(timeout_ms, (cpfds.n ? 1000 : 10)));
441
0
      CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), Curl_poll() -> %d",
442
0
                  rc);
443
0
      if(rc < 0) {
444
0
        result = CURLE_COULDNT_CONNECT;
445
0
        goto out;
446
0
      }
447
      /* continue iterating */
448
0
    }
449
0
  }
450
451
0
out:
452
0
  Curl_pollset_cleanup(&ps);
453
0
  Curl_pollfds_cleanup(&cpfds);
454
0
  return result;
455
0
}
456
457
void Curl_conn_set_multiplex(struct connectdata *conn)
458
0
{
459
0
  if(!conn->bits.multiplex) {
460
0
    conn->bits.multiplex = TRUE;
461
0
    if(conn->attached_multi) {
462
0
      Curl_multi_connchanged(conn->attached_multi);
463
0
    }
464
0
  }
465
0
}
466
467
struct Curl_peer *Curl_conn_get_origin(struct connectdata *conn,
468
                                       int sockindex)
469
0
{
470
0
  return (sockindex == SECONDARYSOCKET) ?
471
0
    conn->origin2 : conn->origin;
472
0
}
473
474
struct Curl_peer *Curl_conn_get_destination(struct connectdata *conn,
475
                                            int sockindex)
476
0
{
477
0
  return (sockindex == SECONDARYSOCKET) ?
478
0
    (conn->via_peer2 ? conn->via_peer2 : conn->origin2) :
479
0
    (conn->via_peer ? conn->via_peer : conn->origin);
480
0
}
481
482
struct Curl_peer *Curl_conn_get_first_peer(struct connectdata *conn,
483
                                           int sockindex)
484
0
{
485
0
#ifndef CURL_DISABLE_PROXY
486
0
  if(conn->socks_proxy.peer)
487
0
    return conn->socks_proxy.peer;
488
0
  if(conn->http_proxy.peer)
489
0
    return conn->http_proxy.peer;
490
0
#endif
491
0
  return (sockindex == SECONDARYSOCKET) ?
492
0
    (conn->via_peer2 ? conn->via_peer2 : conn->origin2) :
493
0
    (conn->via_peer ? conn->via_peer : conn->origin);
494
0
}