Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/url.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
#ifdef HAVE_NETINET_IN_H
27
#include <netinet/in.h>
28
#endif
29
#ifdef HAVE_NETDB_H
30
#include <netdb.h>
31
#endif
32
#ifdef HAVE_ARPA_INET_H
33
#include <arpa/inet.h>
34
#endif
35
#ifdef HAVE_NET_IF_H
36
#include <net/if.h>
37
#endif
38
#ifdef HAVE_IPHLPAPI_H
39
#include <Iphlpapi.h>
40
#endif
41
#ifdef HAVE_SYS_IOCTL_H
42
#include <sys/ioctl.h>
43
#endif
44
#ifdef HAVE_SYS_PARAM_H
45
#include <sys/param.h>
46
#endif
47
48
#ifdef __VMS
49
#include <in.h>
50
#include <inet.h>
51
#endif
52
53
#ifdef HAVE_SYS_UN_H
54
#include <sys/un.h>
55
#endif
56
57
#ifndef HAVE_SOCKET
58
#error "We cannot compile without socket() support"
59
#endif
60
61
#if defined(HAVE_IF_NAMETOINDEX) && defined(USE_WINSOCK)
62
#if defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR <= 5)
63
#include <wincrypt.h>  /* workaround for old mingw-w64 missing to include it */
64
#endif
65
#include <iphlpapi.h>
66
#endif
67
68
#include "urldata.h"
69
#include "mime.h"
70
#include "bufref.h"
71
#include "vtls/vtls.h"
72
#include "vssh/vssh.h"
73
#include "transfer.h"
74
#include "curl_addrinfo.h"
75
#include "curl_trc.h"
76
#include "progress.h"
77
#include "cookie.h"
78
#include "strcase.h"
79
#include "escape.h"
80
#include "curl_share.h"
81
#include "http_digest.h"
82
#include "multiif.h"
83
#include "getinfo.h"
84
#include "pop3.h"
85
#include "urlapi-int.h"
86
#include "hsts.h"
87
#include "proxy.h"
88
#include "cfilters.h"
89
#include "idn.h"
90
#include "http_proxy.h"
91
#include "conncache.h"
92
#include "multihandle.h"
93
#include "curlx/strdup.h"
94
#include "setopt.h"
95
#include "altsvc.h"
96
#include "curlx/dynbuf.h"
97
#include "headers.h"
98
#include "curlx/strerr.h"
99
#include "curlx/strparse.h"
100
#include "peer.h"
101
102
/* Now for the protocols */
103
#include "ftp.h"
104
#include "dict.h"
105
#include "telnet.h"
106
#include "tftp.h"
107
#include "http.h"
108
#include "vauth/vauth.h"
109
#include "file.h"
110
#include "curl_ldap.h"
111
#include "vssh/ssh.h"
112
#include "imap.h"
113
#include "url.h"
114
#include "connect.h"
115
#include "gopher.h"
116
#include "mqtt.h"
117
#include "rtsp.h"
118
#include "smtp.h"
119
#include "ws.h"
120
121
/* Some parts of the code (e.g. chunked encoding) assume this buffer has more
122
 * than a few bytes to play with. Do not let it become too small or bad things
123
 * will happen.
124
 */
125
#if READBUFFER_SIZE < READBUFFER_MIN
126
# error READBUFFER_SIZE is too small
127
#endif
128
129
/*
130
 * get_protocol_family()
131
 *
132
 * This is used to return the protocol family for a given protocol.
133
 *
134
 * Parameters:
135
 *
136
 * 's'  [in]  - struct Curl_scheme pointer.
137
 *
138
 * Returns the family as a single bit protocol identifier.
139
 */
140
static curl_prot_t get_protocol_family(const struct Curl_scheme *s)
141
0
{
142
0
  DEBUGASSERT(s);
143
0
  DEBUGASSERT(s->family);
144
0
  return s->family;
145
0
}
146
147
void Curl_freeset(struct Curl_easy *data)
148
13.0k
{
149
  /* Free all dynamic strings stored in the data->set substructure. */
150
13.0k
  enum dupblob j;
151
152
13.0k
  CURL_EASY_STR_CLEAR0(data, STRING_PASSWORD);
153
13.0k
  CURL_EASY_STR_CLEAR0(data, STRING_KEY_PASSWD);
154
13.0k
  CURL_EASY_STR_CLEAR0(data, STRING_BEARER);
155
13.0k
#ifndef CURL_DISABLE_PROXY
156
13.0k
  CURL_EASY_STR_CLEAR0(data, STRING_PROXYPASSWORD);
157
13.0k
  CURL_EASY_STR_CLEAR0(data, STRING_KEY_PASSWD_PROXY);
158
13.0k
#endif
159
13.0k
  Curl_u8_strset_clear(&data->set.strings);
160
13.0k
  curlx_safefree(data->set.a.str_copypostfields);
161
162
117k
  for(j = (enum dupblob)0; j < BLOB_LAST; j++) {
163
104k
    curlx_safefree(data->set.a.blobs[j]);
164
104k
  }
165
166
13.0k
  Curl_frzn_strs_safefree(&data->set.a.resolve);
167
13.0k
  Curl_frzn_strs_safefree(&data->set.a.connect_to);
168
13.0k
#ifndef CURL_DISABLE_HSTS
169
13.0k
  Curl_frzn_strs_safefree(&data->set.a.hsts_files);
170
13.0k
#endif
171
13.0k
#ifndef CURL_DISABLE_TELNET
172
13.0k
  Curl_frzn_strs_safefree(&data->set.a.telnet_options);
173
13.0k
#endif
174
13.0k
#ifndef CURL_DISABLE_HTTP
175
13.0k
  Curl_frzn_strs_safefree(&data->set.a.http200aliases);
176
13.0k
#endif
177
13.0k
#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH)
178
13.0k
  Curl_frzn_strs_safefree(&data->set.a.quote);
179
13.0k
  Curl_frzn_strs_safefree(&data->set.a.postquote);
180
13.0k
  Curl_frzn_strs_safefree(&data->set.a.prequote);
181
13.0k
#endif
182
13.0k
#ifndef CURL_DISABLE_SMTP
183
13.0k
  Curl_frzn_strs_safefree(&data->set.a.mail_rcpt);
184
13.0k
#endif
185
186
13.0k
  Curl_bufref_free(&data->state.referer);
187
13.0k
  Curl_bufref_free(&data->state.url);
188
189
13.0k
#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API)
190
13.0k
  Curl_mime_cleanpart(data->set.a.mimepostp);
191
13.0k
  curlx_safefree(data->set.a.mimepostp);
192
13.0k
#endif
193
194
13.0k
#ifndef CURL_DISABLE_COOKIES
195
13.0k
  curl_slist_free_all(data->state.cookielist);
196
13.0k
  data->state.cookielist = NULL;
197
13.0k
#endif
198
13.0k
}
199
200
/* free the URL pieces */
201
static void up_free(struct Curl_easy *data)
202
19.4k
{
203
19.4k
  struct urlpieces *up = &data->state.up;
204
19.4k
  curlx_safefree(up->options);
205
19.4k
  curlx_safefree(up->path);
206
19.4k
  curlx_safefree(up->query);
207
19.4k
  curl_url_cleanup(data->state.uh);
208
19.4k
  data->state.uh = NULL;
209
19.4k
}
210
211
/*
212
 * This is the internal function curl_easy_cleanup() calls. This should
213
 * cleanup and free all resources associated with this Curl_easy.
214
 *
215
 * We ignore SIGPIPE when this is called from curl_easy_cleanup.
216
 */
217
CURLcode Curl_close(struct Curl_easy **datap)
218
13.0k
{
219
13.0k
  struct Curl_easy *data;
220
221
13.0k
  if(!datap || !*datap)
222
0
    return CURLE_OK;
223
224
13.0k
  data = *datap;
225
13.0k
  *datap = NULL;
226
227
13.0k
  if(!data->state.internal && data->multi) {
228
    /* This handle is still part of a multi handle, take care of this first
229
       and detach this handle from there.
230
       This detaches the connection. */
231
0
    Curl_multi_remove_handle(data->multi, data);
232
0
  }
233
13.0k
  else {
234
    /* Detach connection if any is left. This should not be normal, but can be
235
       the case for example with CONNECT_ONLY + recv/send (test 556) */
236
13.0k
    Curl_detach_connection(data);
237
13.0k
    if(!data->state.internal && data->multi_easy) {
238
      /* when curl_easy_perform() is used, it creates its own multi handle to
239
         use and this is the one */
240
0
      curl_multi_cleanup(data->multi_easy);
241
0
      data->multi_easy = NULL;
242
0
    }
243
13.0k
  }
244
13.0k
  DEBUGASSERT(!data->conn || data->state.internal);
245
246
13.0k
  Curl_expire_clear_all(data); /* shut off any timers left */
247
248
13.0k
  if(data->state.rangestringalloc)
249
0
    curlx_free(data->state.range);
250
251
  /* release any resolve information this transfer kept */
252
13.0k
  Curl_resolv_destroy_all(data);
253
254
13.0k
  data->set.verbose = FALSE; /* no more calls to DEBUGFUNCTION */
255
13.0k
  data->magic = 0; /* force a clear AFTER the possibly enforced removal from
256
                    * the multi handle and async dns shutdown. The multi
257
                    * handle might check the magic and so might any
258
                    * DEBUGFUNCTION invoked for tracing */
259
260
  /* freed here in case DONE was not called */
261
13.0k
  Curl_req_free(&data->req, data);
262
263
  /* Close down all open SSL info and sessions */
264
13.0k
  Curl_ssl_close_all(data);
265
13.0k
  Curl_peer_unlink(&data->state.origin);
266
13.0k
  Curl_peer_unlink(&data->state.initial_origin);
267
13.0k
#ifndef CURL_DISABLE_RTSP
268
13.0k
  Curl_peer_unlink(&data->state.rtsp_session_origin);
269
13.0k
#endif
270
13.0k
  Curl_ssl_free_certinfo(data);
271
272
13.0k
  Curl_bufref_free(&data->state.referer);
273
274
13.0k
  up_free(data);
275
13.0k
  curlx_dyn_free(&data->state.headerb);
276
13.0k
  Curl_flush_cookies(data, TRUE);
277
13.0k
#ifndef CURL_DISABLE_ALTSVC
278
13.0k
  Curl_altsvc_save(data, data->asi, CURL_EASY_STR(data, STRING_ALTSVC));
279
13.0k
  Curl_altsvc_cleanup(&data->asi);
280
13.0k
#endif
281
13.0k
#ifndef CURL_DISABLE_HSTS
282
13.0k
  Curl_hsts_save(data, data->hsts, CURL_EASY_STR(data, STRING_HSTS));
283
13.0k
  if(!data->share || !data->share->hsts)
284
13.0k
    Curl_hsts_cleanup(&data->hsts);
285
13.0k
#endif
286
13.0k
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH)
287
13.0k
  Curl_http_auth_cleanup_digest(data);
288
13.0k
#endif
289
13.0k
  curlx_safefree(data->state.most_recent_ftp_entrypath);
290
13.0k
  curlx_safefree(data->info.contenttype);
291
13.0k
  curlx_safefree(data->info.wouldredirect);
292
13.0k
  curlx_safefree(data->info.effective_url);
293
294
  /* No longer a dirty share, if it exists */
295
13.0k
  if(Curl_share_easy_unlink(data))
296
13.0k
    DEBUGASSERT(0);
297
298
13.0k
  Curl_hash_destroy(&data->meta_hash);
299
13.0k
  Curl_creds_unlink(&data->state.creds);
300
13.0k
#ifndef CURL_DISABLE_HTTP
301
13.0k
  curlx_safefree(data->state.rangeline);
302
13.0k
  curlx_safefree(data->state.http_host);
303
13.0k
#endif
304
13.0k
#ifndef CURL_DISABLE_RTSP
305
13.0k
  curlx_safefree(data->state.session_id);
306
13.0k
#endif
307
13.0k
#ifndef CURL_DISABLE_COOKIES
308
13.0k
  curlx_safefree(data->req.cookiehost);
309
13.0k
#endif
310
311
13.0k
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_FORM_API)
312
13.0k
  Curl_mime_cleanpart(data->state.formp);
313
13.0k
  curlx_safefree(data->state.formp);
314
13.0k
#endif
315
316
  /* destruct wildcard structures if it is needed */
317
13.0k
  Curl_wildcard_dtor(&data->wildcard);
318
13.0k
  Curl_freeset(data);
319
13.0k
  Curl_headers_cleanup(data);
320
13.0k
  Curl_netrc_cleanup(&data->state.netrc);
321
13.0k
#ifndef CURL_DISABLE_DIGEST_AUTH
322
13.0k
  curlx_free(data->state.envproxy);
323
13.0k
#endif
324
13.0k
  curlx_memzero(data, sizeof(*data));
325
13.0k
  curlx_free(data);
326
13.0k
  return CURLE_OK;
327
13.0k
}
328
329
/*
330
 * Initialize the UserDefined fields within a Curl_easy.
331
 * This may be safely called on a new or existing Curl_easy.
332
 */
333
void Curl_init_userdefined(struct Curl_easy *data)
334
13.0k
{
335
13.0k
  struct UserDefined *set = &data->set;
336
337
13.0k
  set->out = stdout;  /* default output to stdout */
338
13.0k
  set->in_set = stdin;  /* default input from stdin */
339
13.0k
  set->err = stderr;  /* default stderr to stderr */
340
341
13.0k
  Curl_u8_strset_init(&data->set.strings);
342
343
13.0k
#if defined(__clang__) && __clang_major__ >= 16
344
13.0k
#pragma clang diagnostic push
345
13.0k
#pragma clang diagnostic ignored "-Wcast-function-type-strict"
346
13.0k
#endif
347
  /* use fwrite as default function to store output */
348
13.0k
  set->fwrite_func = (curl_write_callback)fwrite;
349
350
  /* use fread as default function to read input */
351
13.0k
  set->fread_func_set = (curl_read_callback)fread;
352
13.0k
#if defined(__clang__) && __clang_major__ >= 16
353
13.0k
#pragma clang diagnostic pop
354
13.0k
#endif
355
13.0k
  set->is_fread_set = 0;
356
357
13.0k
  set->seek_client = ZERO_NULL;
358
359
13.0k
  set->filesize = -1;        /* we do not know the size */
360
13.0k
  set->postfieldsize = -1;   /* unknown size */
361
13.0k
  set->maxredirs = 30;       /* sensible default */
362
363
13.0k
  set->method = HTTPREQ_GET; /* Default HTTP request */
364
13.0k
#ifndef CURL_DISABLE_RTSP
365
13.0k
  set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
366
13.0k
#endif
367
13.0k
#ifndef CURL_DISABLE_FTP
368
13.0k
  set->ftp_use_epsv = TRUE;   /* FTP defaults to EPSV operations */
369
13.0k
  set->ftp_use_eprt = TRUE;   /* FTP defaults to EPRT operations */
370
13.0k
  set->ftp_use_pret = FALSE;  /* mainly useful for drftpd servers */
371
13.0k
  set->ftp_filemethod = FTPFILE_MULTICWD;
372
13.0k
  set->ftp_skip_ip = TRUE;    /* skip PASV IP by default */
373
13.0k
#endif
374
13.0k
  set->dns_cache_timeout_ms = 60000; /* Timeout every 60 seconds by default */
375
376
  /* Timeout every 24 hours by default */
377
13.0k
  set->ssl_ca_cache_timeout = 24 * 60 * 60;
378
379
13.0k
  set->httpauth = CURLAUTH_BASIC;  /* defaults to basic */
380
381
13.0k
  Curl_ssl_config_init(&data->set.ssl);
382
13.0k
#ifndef CURL_DISABLE_PROXY
383
13.0k
  Curl_ssl_config_init(&data->set.proxy_ssl);
384
13.0k
  set->proxyport = 0;
385
13.0k
  set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
386
13.0k
  set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
387
  /* SOCKS5 proxy auth defaults to username/password + GSS-API */
388
13.0k
  set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
389
13.0k
#endif
390
391
13.0k
#ifndef CURL_DISABLE_DOH
392
13.0k
  set->doh_verifyhost = TRUE;
393
13.0k
  set->doh_verifypeer = TRUE;
394
13.0k
#endif
395
#ifdef USE_SSH
396
  /* defaults to any auth type */
397
  set->ssh_auth_types = CURLSSH_AUTH_DEFAULT;
398
  set->new_directory_perms = 0755; /* Default permissions */
399
#endif
400
401
13.0k
  set->new_file_perms = 0644;    /* Default permissions */
402
13.0k
  set->allowed_protocols = (curl_prot_t)CURLPROTO_64ALL;
403
13.0k
  set->redir_protocols = CURLPROTO_REDIR;
404
405
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
406
  /*
407
   * disallow unprotected protection negotiation NEC reference implementation
408
   * seem not to follow rfc1961 section 4.3/4.4
409
   */
410
  set->socks5_gssapi_nec = FALSE;
411
#endif
412
413
  /* set default minimum TLS version */
414
13.0k
#ifdef USE_SSL
415
13.0k
  Curl_setopt_SSLVERSION(data, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
416
13.0k
#ifndef CURL_DISABLE_PROXY
417
13.0k
  Curl_setopt_SSLVERSION(data, CURLOPT_PROXY_SSLVERSION,
418
13.0k
                         CURL_SSLVERSION_DEFAULT);
419
13.0k
#endif
420
13.0k
#endif
421
13.0k
#ifndef CURL_DISABLE_FTP
422
13.0k
  set->wildcard_enabled = FALSE;
423
13.0k
  set->chunk_bgn = ZERO_NULL;
424
13.0k
  set->chunk_end = ZERO_NULL;
425
13.0k
  set->fnmatch = ZERO_NULL;
426
13.0k
#endif
427
13.0k
  set->tcp_keepalive = FALSE;
428
13.0k
  set->tcp_keepintvl = 60;
429
13.0k
  set->tcp_keepidle = 60;
430
13.0k
  set->tcp_keepcnt = 9;
431
13.0k
  set->tcp_fastopen = FALSE;
432
13.0k
  set->tcp_nodelay = TRUE;
433
13.0k
  set->ssl_enable_alpn = TRUE;
434
13.0k
  set->expect_100_timeout = 1000L; /* Wait for a second by default. */
435
13.0k
  set->sep_headers = TRUE; /* separated header lists by default */
436
13.0k
  set->buffer_size = READBUFFER_SIZE;
437
13.0k
  set->upload_buffer_size = UPLOADBUFFER_DEFAULT;
438
13.0k
  set->upload_flags = CURLULFLAG_SEEN;
439
13.0k
  set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
440
13.0k
  set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT;
441
13.0k
  set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
442
13.0k
  set->conn_max_idle_ms = 118 * 1000;
443
13.0k
  set->conn_max_age_ms = 24 * 3600 * 1000;
444
13.0k
  set->http09_allowed = FALSE;
445
13.0k
  set->httpwant = CURL_HTTP_VERSION_NONE;
446
13.0k
#if defined(USE_HTTP2) || defined(USE_HTTP3)
447
13.0k
  set->weight = 0;
448
13.0k
#endif
449
13.0k
  set->quick_exit = 0L;
450
13.0k
#ifndef CURL_DISABLE_WEBSOCKETS
451
13.0k
  set->ws_raw_mode = FALSE;
452
13.0k
  set->ws_no_auto_pong = FALSE;
453
13.0k
#endif
454
13.0k
}
455
456
/* easy->meta_hash destructor. Should never be called as elements
457
 * MUST be added with their own destructor */
458
static void easy_meta_freeentry(void *p)
459
0
{
460
0
  (void)p;
461
  /* Always FALSE. Cannot use a 0 assert here since compilers
462
   * are not in agreement if they then want a NORETURN attribute or
463
   * not. *sigh* */
464
0
  DEBUGASSERT(!p);
465
0
}
466
467
/**
468
 * Curl_open()
469
 *
470
 * @param curl is a pointer to a Curl_easy pointer that gets set by this
471
 * function.
472
 * @return CURLcode
473
 */
474
CURLcode Curl_open(struct Curl_easy **curl)
475
13.0k
{
476
13.0k
  struct Curl_easy *data;
477
478
  /* simple start-up: alloc the struct, init it with zeroes and return */
479
13.0k
  data = curlx_calloc(1, sizeof(struct Curl_easy));
480
13.0k
  if(!data) {
481
    /* this is a serious error */
482
54
    DEBUGF(curl_mfprintf(stderr, "Error: calloc of Curl_easy failed\n"));
483
54
    return CURLE_OUT_OF_MEMORY;
484
54
  }
485
486
13.0k
  data->magic = CURLEASY_MAGIC_NUMBER;
487
  /* most recent connection is not yet defined */
488
13.0k
  data->state.last_conn_id = -1;
489
13.0k
  data->state.last_cpid = UINT32_MAX;
490
  /* and not assigned an id yet */
491
13.0k
  data->id = -1;
492
13.0k
  data->mid = UINT32_MAX;
493
13.0k
  data->master_mid = UINT32_MAX;
494
13.0k
  data->progress.hide = TRUE;
495
496
13.0k
  Curl_hash_init(&data->meta_hash, 23, CURL_HASH_TYPE_BYTES,
497
13.0k
                 easy_meta_freeentry);
498
13.0k
  DEBUGASSERT(STRING_LAST <= UINT8_MAX);
499
13.0k
  Curl_u8_strset_init(&data->set.strings);
500
13.0k
  curlx_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER);
501
13.0k
  Curl_bufref_init(&data->state.url);
502
13.0k
  Curl_bufref_init(&data->state.referer);
503
13.0k
  Curl_req_init(&data->req);
504
13.0k
  Curl_initinfo(data);
505
13.0k
#ifndef CURL_DISABLE_HTTP
506
13.0k
  Curl_llist_init(&data->state.httphdrs, NULL);
507
13.0k
#endif
508
13.0k
  Curl_netrc_init(&data->state.netrc);
509
13.0k
  Curl_init_userdefined(data);
510
511
13.0k
  *curl = data;
512
13.0k
  return CURLE_OK;
513
13.0k
}
514
515
void Curl_conn_free(struct Curl_easy *data, struct connectdata *conn)
516
6.20k
{
517
6.20k
  DEBUGASSERT(conn);
518
519
6.20k
  if(conn->scheme && conn->scheme->run->disconnect &&
520
6.20k
     !conn->bits.shutdown_handler)
521
27
    conn->scheme->run->disconnect(data, conn, TRUE);
522
523
6.20k
  Curl_cfchain_cleanup(&conn->chain, data);
524
525
6.20k
#ifndef CURL_DISABLE_PROXY
526
6.20k
  Curl_peer_unlink(&conn->http_proxy.peer);
527
6.20k
  Curl_peer_unlink(&conn->socks_proxy.peer);
528
6.20k
  Curl_creds_unlink(&conn->http_proxy.creds);
529
6.20k
  Curl_creds_unlink(&conn->socks_proxy.creds);
530
6.20k
#endif
531
6.20k
  Curl_creds_unlink(&conn->creds);
532
6.20k
  Curl_peer_unlink(&conn->creds_origin);
533
6.20k
  curlx_safefree(conn->options);
534
6.20k
  curlx_safefree(conn->interface_opts);
535
6.20k
  Curl_ssl_conn_config_cleanup(conn);
536
537
6.20k
  curlx_safefree(conn->destination);
538
6.20k
  Curl_hash_destroy(&conn->meta_hash);
539
6.20k
  Curl_peer_unlink(&conn->origin);
540
6.20k
  Curl_peer_unlink(&conn->via_peer);
541
6.20k
  Curl_peer_unlink(&conn->origin2);
542
6.20k
  Curl_peer_unlink(&conn->via_peer2);
543
544
6.20k
  curlx_free(conn); /* free all the connection oriented data */
545
6.20k
}
546
547
/*
548
 * xfer_may_multiplex()
549
 *
550
 * Return a TRUE, iff the transfer can be done over an (appropriate)
551
 * multiplexed connection.
552
 */
553
static bool xfer_may_multiplex(const struct Curl_easy *data,
554
                               const struct connectdata *conn)
555
6.18k
{
556
6.18k
#ifndef CURL_DISABLE_HTTP
557
  /* If an HTTP protocol and multiplexing is enabled */
558
6.18k
  if((conn->scheme->protocol & PROTO_FAMILY_HTTP) &&
559
0
     (!conn->bits.protoconnstart || !conn->bits.close)) {
560
561
0
    if(Curl_multiplex_wanted(data->multi) &&
562
0
       (data->state.http_neg.allowed & (CURL_HTTP_V2x | CURL_HTTP_V3x)))
563
      /* allows HTTP/2 or newer */
564
0
      return TRUE;
565
0
  }
566
#else
567
  (void)data;
568
  (void)conn;
569
#endif
570
6.18k
  return FALSE;
571
6.18k
}
572
573
#ifndef CURL_DISABLE_PROXY
574
static bool proxy_info_matches(const struct proxy_info *data,
575
                               const struct proxy_info *needle)
576
0
{
577
0
  if((data->proxytype == needle->proxytype) &&
578
0
     Curl_peer_same_destination(data->peer, needle->peer) &&
579
0
     Curl_creds_same(data->creds, needle->creds)) {
580
0
    return TRUE;
581
0
  }
582
0
  return FALSE;
583
0
}
584
#endif
585
586
#ifdef USE_SSH
587
static bool ssh_config_matches(struct connectdata *one,
588
                               struct connectdata *two)
589
{
590
  struct ssh_conn *sshc1, *sshc2;
591
592
  sshc1 = Curl_conn_meta_get(one, CURL_META_SSH_CONN);
593
  sshc2 = Curl_conn_meta_get(two, CURL_META_SSH_CONN);
594
  return sshc1 && sshc2 && Curl_safecmp(sshc1->priv_key, sshc2->priv_key) &&
595
         Curl_safecmp(sshc1->pub_key, sshc2->pub_key);
596
}
597
#endif
598
599
struct url_conn_match {
600
  struct connectdata *found;
601
  struct Curl_easy *data;
602
  struct connectdata *needle;
603
  struct curltime now;
604
  struct ssl_filter_config ssl_config;
605
#ifndef CURL_DISABLE_PROXY
606
  struct ssl_filter_config proxy_ssl_config;
607
#endif
608
  BIT(may_multiplex);
609
  BIT(want_nego_http);
610
  BIT(want_proxy_nego_http);
611
  BIT(may_tls); /* May upgrade clear-text connection to TLS, can only reuse
612
                 * connections that have matching TLS configuration.
613
                 * Always TRUE if `req_tls` is TRUE. */
614
  BIT(require_tls); /* Requires TLS use from a clear-text start, can only
615
                 * reuse connections that have TLS. */
616
  BIT(wait_pipe);
617
  BIT(seen_pending_conn);
618
  BIT(seen_single_use_conn);
619
  BIT(seen_multiplex_conn);
620
};
621
622
static bool url_match_connect_config(struct connectdata *conn,
623
                                     struct url_conn_match *m)
624
0
{
625
  /* connect-only or to-be-closed connections will not be reused */
626
0
  if(conn->bits.connect_only || conn->bits.close || conn->bits.no_reuse)
627
0
    return FALSE;
628
629
  /* ip_version must match */
630
0
  if(m->data->set.ipver != CURL_IPRESOLVE_WHATEVER &&
631
0
     m->data->set.ipver != conn->ip_version)
632
0
    return FALSE;
633
634
  /* When needle has specific local bind settings, those have to match.
635
   * If it does not, any other connection might do when it comes to ports. */
636
0
  if(m->needle->localport &&
637
0
     ((conn->localport != m->needle->localport) ||
638
0
      (conn->localportrange != m->needle->localportrange)))
639
0
    return FALSE;
640
  /* For interface related bind options, we require a full match
641
   * as connection might go totally different ways (VPNs, for example). */
642
0
  if((m->needle->interface_opts != conn->interface_opts) &&
643
0
     (!m->needle->interface_opts || !conn->interface_opts ||
644
0
      strcmp(conn->interface_opts, m->needle->interface_opts)))
645
0
    return FALSE;
646
647
0
  if((m->needle->interface_opts || m->needle->localport) &&
648
    /* If we are bound to a specific local end (IP+port), we must not reuse a
649
       random other one, although if we did not ask for a particular one we
650
       can reuse one that was bound. */
651
0
    ((conn->localport != m->needle->localport) ||
652
0
     (conn->localportrange != m->needle->localportrange) ||
653
0
     (m->needle->interface_opts &&
654
0
      (!conn->interface_opts ||
655
0
       strcmp(conn->interface_opts, m->needle->interface_opts)))))
656
0
    return FALSE;
657
658
0
  if(!m->needle->via_peer != !conn->via_peer)
659
    /* do not mix connections that use the "connect to host" feature and
660
     * connections that do not use this feature */
661
0
    return FALSE;
662
663
0
  return TRUE;
664
0
}
665
666
static bool url_match_fully_connected(struct connectdata *conn,
667
                                      struct url_conn_match *m)
668
0
{
669
0
  if(!Curl_conn_is_connected(conn) || conn->bits.upgrade_in_progress) {
670
    /* Not yet connected, or a protocol upgrade is in progress. The later
671
     * happens for HTTP/2 Upgrade: requests that need a response. */
672
0
    if(m->may_multiplex) {
673
0
      m->seen_pending_conn = TRUE;
674
      /* Do not pick a connection that has not connected yet */
675
0
      infof(m->data, "Connection #%" FMT_OFF_T
676
0
            " is not open enough, cannot reuse", conn->connection_id);
677
0
    }
678
    /* Do not pick a connection that has not connected yet */
679
0
    return FALSE;
680
0
  }
681
0
  return TRUE;
682
0
}
683
684
static bool url_match_multi(struct connectdata *conn,
685
                            struct url_conn_match *m)
686
0
{
687
0
  if(CONN_INUSE(conn)) {
688
0
    DEBUGASSERT(conn->attached_multi);
689
0
    if(conn->attached_multi != m->data->multi)
690
0
      return FALSE;
691
0
  }
692
0
  return TRUE;
693
0
}
694
695
static bool url_match_multiplex_needs(struct connectdata *conn,
696
                                      struct url_conn_match *m)
697
0
{
698
0
  if(CONN_INUSE(conn)) {
699
0
    if(!conn->bits.multiplex) {
700
      /* conn busy and conn cannot take more transfers */
701
0
      m->seen_single_use_conn = TRUE;
702
0
      return FALSE;
703
0
    }
704
0
    m->seen_multiplex_conn = TRUE;
705
0
    if(!m->may_multiplex || !url_match_multi(conn, m))
706
      /* conn busy and transfer cannot be multiplexed */
707
0
      return FALSE;
708
0
  }
709
0
  return TRUE;
710
0
}
711
712
static bool url_match_multiplex_limits(struct connectdata *conn,
713
                                       struct url_conn_match *m)
714
0
{
715
0
  if(CONN_INUSE(conn) && m->may_multiplex) {
716
0
    DEBUGASSERT(conn->bits.multiplex);
717
    /* If multiplexed, make sure we do not go over concurrency limit */
718
0
    if(conn->attached_xfers >=
719
0
            Curl_multi_max_concurrent_streams(m->data->multi)) {
720
0
      infof(m->data, "connection #%" FMT_OFF_T " reached "
721
0
            "MAX_CONCURRENT_STREAMS(%u), skip",
722
0
            conn->connection_id, conn->attached_xfers);
723
0
      return FALSE;
724
0
    }
725
0
    if(conn->attached_xfers >=
726
0
       Curl_conn_get_max_concurrent(m->data, conn)) {
727
0
      infof(m->data, "connection #%" FMT_OFF_T "reached "
728
0
            "MAX_CONCURRENT_STREAMS(%u), skip",
729
0
            conn->connection_id, conn->attached_xfers);
730
0
      return FALSE;
731
0
    }
732
    /* When not multiplexed, we have a match here! */
733
0
    infof(m->data, "Multiplexed connection found");
734
0
  }
735
0
  return TRUE;
736
0
}
737
738
static bool url_match_ssl_use(struct connectdata *conn,
739
                              struct url_conn_match *m)
740
0
{
741
0
  if(m->needle->scheme->flags & PROTOPT_SSL) {
742
    /* We are looking for SSL, if `conn` does not do it, not a match. */
743
0
    if(!Curl_conn_is_ssl(conn))
744
0
      return FALSE;
745
0
  }
746
0
  else if(Curl_conn_is_ssl(conn)) {
747
    /* If the protocol does not allow reuse of SSL connections OR
748
       is of another protocol family, not a match. */
749
0
    if(!(m->needle->scheme->flags & PROTOPT_SSL_REUSE) ||
750
0
       (get_protocol_family(conn->scheme) != m->needle->scheme->protocol))
751
0
      return FALSE;
752
    /* We may reuse this as an auto-TLS upgrade, but only if the SSL
753
     * config parameters match. */
754
0
    if(!Curl_ssl_conn_config_match(m->data, &m->ssl_config, conn, FALSE))
755
0
      return FALSE;
756
0
  }
757
0
  else if(m->require_tls)
758
    /* a clear-text STARTTLS protocol with required TLS */
759
0
    return FALSE;
760
0
  return TRUE;
761
0
}
762
763
#ifndef CURL_DISABLE_PROXY
764
static bool url_match_proxy_use(struct connectdata *conn,
765
                                struct url_conn_match *m)
766
0
{
767
0
  if(m->needle->bits.origin_is_proxy != conn->bits.origin_is_proxy)
768
0
    return FALSE;
769
770
0
  if(!proxy_info_matches(&m->needle->socks_proxy, &conn->socks_proxy))
771
0
    return FALSE;
772
773
0
  if(!proxy_info_matches(&m->needle->http_proxy, &conn->http_proxy))
774
0
    return FALSE;
775
776
0
  if(m->data->set.socks5_auth_only && !conn->bits.socks5_authenticated &&
777
0
     ((conn->socks_proxy.proxytype == CURLPROXY_SOCKS5) ||
778
0
      (conn->socks_proxy.proxytype == CURLPROXY_SOCKS5_HOSTNAME))) {
779
0
    DEBUGF(infof(m->data,
780
0
                 "Connection #%" FMT_OFF_T
781
0
                 " was not SOCKS5 authenticated, cannot reuse",
782
0
                 conn->connection_id));
783
0
    return FALSE;
784
0
  }
785
786
0
  if(CURL_PROXY_IS_HTTPS(m->needle->http_proxy.proxytype)) {
787
    /* https proxies come in different types, http/1.1, h2, ... */
788
    /* match SSL config to proxy */
789
0
    if(!Curl_ssl_conn_config_match(m->data, &m->proxy_ssl_config,
790
0
                                   conn, TRUE)) {
791
0
      DEBUGF(infof(m->data,
792
0
                   "Connection #%" FMT_OFF_T
793
0
                   " has different SSL proxy parameters, cannot reuse",
794
0
                   conn->connection_id));
795
0
      return FALSE;
796
0
    }
797
    /* the SSL config to the server, which may apply here is checked
798
     * further below */
799
0
  }
800
0
  return TRUE;
801
0
}
802
#else
803
#define url_match_proxy_use(c, m) ((void)(c), (void)(m), TRUE)
804
#endif
805
806
#ifndef CURL_DISABLE_HTTP
807
static bool url_match_http_multiplex(struct connectdata *conn,
808
                                     struct url_conn_match *m,
809
                                     bool *pwait_pipe)
810
0
{
811
0
  if(m->may_multiplex &&
812
0
     (m->data->state.http_neg.allowed & (CURL_HTTP_V2x | CURL_HTTP_V3x)) &&
813
0
     (m->needle->scheme->protocol & CURLPROTO_HTTP) &&
814
0
     !conn->httpversion_seen) {
815
0
    if(m->data->set.pipewait) {
816
0
      infof(m->data, "Server upgrade does not support multiplex yet, wait");
817
0
      m->found = NULL;
818
0
      *pwait_pipe = TRUE;
819
0
      return TRUE; /* stop searching, we want to wait */
820
0
    }
821
0
    infof(m->data, "Server upgrade cannot be used");
822
0
    return FALSE;
823
0
  }
824
0
  return TRUE;
825
0
}
826
827
static bool url_match_http_version(struct connectdata *conn,
828
                                   struct url_conn_match *m)
829
0
{
830
  /* If looking for HTTP and the HTTP versions allowed do not include
831
   * the HTTP version of conn, continue looking. */
832
0
  if((m->needle->scheme->protocol & PROTO_FAMILY_HTTP)) {
833
0
    switch(Curl_conn_http_version(m->data, conn)) {
834
0
    case 30:
835
0
      if(!(m->data->state.http_neg.allowed & CURL_HTTP_V3x)) {
836
0
        DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T
837
0
                     ", we do not want h3", conn->connection_id));
838
0
        return FALSE;
839
0
      }
840
0
      break;
841
0
    case 20:
842
0
      if(!(m->data->state.http_neg.allowed & CURL_HTTP_V2x)) {
843
0
        DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T
844
0
                     ", we do not want h2", conn->connection_id));
845
0
        return FALSE;
846
0
      }
847
0
      break;
848
0
    default:
849
0
      if(!(m->data->state.http_neg.allowed & CURL_HTTP_V1x)) {
850
0
        DEBUGF(infof(m->data, "not reusing conn #%" CURL_FORMAT_CURL_OFF_T
851
0
                     ", we do not want h1", conn->connection_id));
852
0
        return FALSE;
853
0
      }
854
0
      break;
855
0
    }
856
0
  }
857
0
  return TRUE;
858
0
}
859
#else
860
#define url_match_http_multiplex(c, m, w) ((void)(c), (void)(m), TRUE)
861
#define url_match_http_version(c, m)      ((void)(c), (void)(m), TRUE)
862
#endif
863
864
static bool url_match_proto_config(struct connectdata *conn,
865
                                   struct url_conn_match *m)
866
0
{
867
0
  if(!url_match_http_version(conn, m))
868
0
    return FALSE;
869
870
#ifdef USE_SSH
871
  if(get_protocol_family(m->needle->scheme) & PROTO_FAMILY_SSH) {
872
    if(!ssh_config_matches(m->needle, conn))
873
      return FALSE;
874
  }
875
#endif
876
0
#ifndef CURL_DISABLE_FTP
877
0
  else if(get_protocol_family(m->needle->scheme) & PROTO_FAMILY_FTP) {
878
0
    if(!Curl_ftp_conn_matches(m->data, conn))
879
0
      return FALSE;
880
0
  }
881
0
#endif
882
0
  return TRUE;
883
0
}
884
885
static bool url_match_auth(struct connectdata *conn,
886
                           struct url_conn_match *m)
887
0
{
888
0
  if(!Curl_creds_same(m->needle->creds, conn->creds)) {
889
0
    if(m->needle->creds)
890
0
      return FALSE;
891
0
    if(!Curl_creds_same(m->data->state.creds, conn->creds))
892
0
      return FALSE;
893
0
  }
894
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
895
  /* GSS delegation differences do not actually affect every connection and
896
     auth method, but this check takes precaution before efficiency */
897
  if(m->needle->gssapi_delegation != conn->gssapi_delegation)
898
    return FALSE;
899
#endif
900
901
0
  return TRUE;
902
0
}
903
904
static bool url_match_destination(struct connectdata *conn,
905
                                  struct url_conn_match *m)
906
0
{
907
  /* Different connect-to peers never match */
908
0
  if(!Curl_peer_same_destination(m->needle->via_peer, conn->via_peer))
909
0
    return FALSE;
910
911
0
  if(m->needle->origin->scheme != conn->origin->scheme &&
912
    /* `needle` and `conn` not having the same scheme.
913
     * This is allowed for the same family *if* conn is using TLS.
914
     * - IMAP+STARTTLS works for IMAPS.
915
     * - IMAPS works for IMAP. */
916
0
     get_protocol_family(conn->origin->scheme) !=
917
0
     m->needle->scheme->protocol)
918
0
    return FALSE;
919
920
  /* Scheme mismatch is acceptable, compare hostname/port */
921
0
  return Curl_peer_same_destination(m->needle->origin, conn->origin);
922
0
}
923
924
static bool url_match_ssl_config(struct connectdata *conn,
925
                                 struct url_conn_match *m)
926
0
{
927
  /* If talking/upgrading to TLS, conn needs to use the same SSL options. */
928
0
  if(((m->needle->scheme->flags & PROTOPT_SSL) || m->may_tls) &&
929
0
     !Curl_ssl_conn_config_match(m->data, &m->ssl_config, conn, FALSE)) {
930
0
    DEBUGF(infof(m->data, "Connection #%" FMT_OFF_T
931
0
                 " has different SSL parameters, cannot reuse",
932
0
                 conn->connection_id));
933
0
    return FALSE;
934
0
  }
935
0
  return TRUE;
936
0
}
937
938
#ifdef USE_SPNEGO
939
static bool url_match_auth_nego(struct connectdata *conn,
940
                                struct url_conn_match *m)
941
{
942
  if(conn->http_negotiate_state != CURL_NEGO_AUTH_NONE) {
943
    /* Connection is using Negotiate. We cannot reuse if transfer
944
     * has different Auth input parameters. */
945
    if(!m->want_nego_http ||
946
       !Curl_creds_same(conn->creds, m->data->state.creds) ||
947
       !Curl_peer_equal(conn->creds_origin, m->data->state.origin))
948
      return FALSE;
949
  }
950
  else if(m->want_nego_http) {
951
    /* Transfer wants Negotiate, connection is not using it.
952
     * Do not reuse when connection credentials state is bound to an origin
953
     * and it or creds differ. */
954
    if(conn->creds_origin &&
955
       (!Curl_creds_same(conn->creds, m->data->state.creds) ||
956
        !Curl_peer_equal(conn->creds_origin, m->data->state.origin)))
957
      return FALSE;
958
  }
959
960
#ifndef CURL_DISABLE_PROXY
961
  /* Same for Proxy Negotiate authentication */
962
  if(conn->proxy_negotiate_state != CURL_NEGO_AUTH_NONE) {
963
    if(!m->want_proxy_nego_http ||
964
       !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds))
965
      return FALSE;
966
  }
967
  else if(m->want_proxy_nego_http) {
968
    if(conn->http_proxy.creds &&
969
       !Curl_creds_same(m->needle->http_proxy.creds, conn->http_proxy.creds))
970
      return FALSE;
971
  }
972
#endif
973
  return TRUE;
974
}
975
#else
976
0
#define url_match_auth_nego(c, m) ((void)(c), (void)(m), TRUE)
977
#endif
978
979
static cpool_match_result url_match_conn(struct connectdata *conn,
980
                                         void *userdata)
981
0
{
982
0
  struct url_conn_match *m = userdata;
983
0
  bool wait_pipe = FALSE;
984
985
  /* general connect config setting match? */
986
0
  if(!url_match_connect_config(conn, m))
987
0
    return CPOOL_MATCH_CONT;
988
989
  /* match for destination and protocol? */
990
0
  if(!url_match_destination(conn, m))
991
0
    return CPOOL_MATCH_CONT;
992
993
0
  if(!url_match_fully_connected(conn, m))
994
0
    return CPOOL_MATCH_CONT;
995
996
0
  if(!url_match_multiplex_needs(conn, m))
997
0
    return CPOOL_MATCH_CONT;
998
999
0
  if(!url_match_ssl_use(conn, m))
1000
0
    return CPOOL_MATCH_CONT;
1001
1002
0
  if(!url_match_proxy_use(conn, m))
1003
0
    return CPOOL_MATCH_CONT;
1004
0
  if(!url_match_ssl_config(conn, m))
1005
0
    return CPOOL_MATCH_CONT;
1006
1007
0
  if(!url_match_http_multiplex(conn, m, &wait_pipe))
1008
0
    return CPOOL_MATCH_CONT;
1009
1010
0
  if(!url_match_auth(conn, m))
1011
0
    return CPOOL_MATCH_CONT;
1012
1013
0
  if(!url_match_proto_config(conn, m))
1014
0
    return CPOOL_MATCH_CONT;
1015
1016
0
  if(!url_match_auth_nego(conn, m))
1017
0
    return CPOOL_MATCH_CONT;
1018
1019
0
  if(!url_match_multiplex_limits(conn, m))
1020
0
    return CPOOL_MATCH_CONT;
1021
1022
  /* The connection matches all conditions, but do we want to use it? */
1023
0
  if(wait_pipe) {
1024
    /* The connection fits, but its multiplex state has not been determined
1025
     * yet. Put the transfer into PENDING and wait for conn state change. */
1026
0
    DEBUGASSERT(!m->found);
1027
0
    m->wait_pipe = TRUE;
1028
0
    return CPOOL_MATCH_FOUND;
1029
0
  }
1030
1031
0
  if(m->data->set.conn_max_age_ms > 0) {
1032
0
    timediff_t age_ms = Curl_cpool_conn_age_ms(m->data, conn, &m->now);
1033
0
    if(age_ms > m->data->set.conn_max_age_ms) {
1034
      /* Transfer is looking for a younger connection. */
1035
0
      return CPOOL_MATCH_TOO_OLD;
1036
0
    }
1037
0
  }
1038
1039
  /* If we are going to pick an idle connection, do an extra
1040
   * health check before we reuse it. */
1041
0
  if(!CONN_INUSE(conn) &&
1042
0
     !Curl_cpool_conn_seems_healthy(conn, m->data, &m->now)) {
1043
0
    infof(m->data, "Connection %" FMT_OFF_T " seems to be dead, terminating",
1044
0
          conn->connection_id);
1045
0
    return CPOOL_MATCH_CLOSE;
1046
0
  }
1047
1048
  /* conn matches our needs. */
1049
0
  m->found = conn;
1050
0
  return CPOOL_MATCH_FOUND;
1051
0
}
1052
1053
static bool url_match_result(void *userdata)
1054
6.11k
{
1055
6.11k
  struct url_conn_match *match = userdata;
1056
6.11k
  if(match->found) {
1057
    /* Attach it now while still under lock, so the connection does
1058
     * no longer appear idle and can be reaped. */
1059
0
    Curl_attach_connection(match->data, match->found, TRUE);
1060
0
    return TRUE;
1061
0
  }
1062
6.11k
  else if(match->seen_single_use_conn && !match->seen_multiplex_conn) {
1063
    /* We have seen a single-use, existing connection to the destination and
1064
     * no multiplexed one. It seems safe to assume that the server does
1065
     * not support multiplexing. */
1066
0
    match->wait_pipe = FALSE;
1067
0
  }
1068
6.11k
  else if(match->seen_pending_conn && match->data->set.pipewait) {
1069
0
    infof(match->data,
1070
0
          "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set");
1071
0
    match->wait_pipe = TRUE;
1072
0
  }
1073
6.11k
  return FALSE;
1074
6.11k
}
1075
1076
/*
1077
 * Given a transfer and a prototype connection (needle),
1078
 * find and attach an existing connection that matches.
1079
 *
1080
 * Return TRUE if an existing connection was attached.
1081
 * `waitpipe` is TRUE if no existing connection matched, but there
1082
 * might be suitable one in the near future (common cause: multiplexing
1083
 * capability has not been determined yet, e.g. ALPN handshake).
1084
 */
1085
static bool url_attach_existing(struct Curl_easy *data,
1086
                                struct connectdata *needle,
1087
                                struct url_conn_match *m,
1088
                                const struct curltime *pnow)
1089
6.11k
{
1090
  /* Find a connection in the pool that matches what "data + needle"
1091
   * requires. If a suitable candidate is found, it is attached to "data". */
1092
6.11k
  return Curl_cpool_find(data, needle->destination, TRUE, pnow,
1093
6.11k
                         url_match_conn, url_match_result, m);
1094
6.11k
}
1095
1096
/*
1097
 * Allocate and initialize a new connectdata object.
1098
 */
1099
static struct connectdata *allocate_conn(struct Curl_easy *data)
1100
6.20k
{
1101
6.20k
  struct connectdata *conn = curlx_calloc(1, sizeof(struct connectdata));
1102
6.20k
  if(!conn)
1103
4
    return NULL;
1104
1105
  /* and we setup a few fields in case we end up actually using this struct */
1106
6.20k
  Curl_cfchain_init(&conn->chain, conn, TRUE);
1107
6.20k
  conn->connection_id = -1;    /* no ID */
1108
6.20k
  conn->cpid = UINT32_MAX;  /* not in connection pool yet */
1109
6.20k
  conn->attached_xfers = 0;
1110
6.20k
  conn->connect_start_ms = -1;
1111
1112
6.20k
#ifndef CURL_DISABLE_FTP
1113
6.20k
  conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
1114
6.20k
  conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
1115
6.20k
#endif
1116
6.20k
  conn->ip_version = data->set.ipver;
1117
6.20k
  conn->bits.connect_only = (bool)data->set.connect_only;
1118
6.20k
  conn->transport_wanted = TRNSPRT_TCP; /* most of them are TCP streams */
1119
1120
  /* Store the local bind parameters that will be used for this connection */
1121
6.20k
  if(CURL_EASY_STR(data, STRING_INTERFACE_OPT)) {
1122
0
    conn->interface_opts =
1123
0
      curlx_strdup(CURL_EASY_STR(data, STRING_INTERFACE_OPT));
1124
0
    if(!conn->interface_opts)
1125
0
      goto error;
1126
0
  }
1127
6.20k
#ifndef CURL_DISABLE_BINDLOCAL
1128
6.20k
  conn->localportrange = data->set.localportrange;
1129
6.20k
  conn->localport = data->set.localport;
1130
6.20k
#endif
1131
1132
  /* the close socket stuff needs to be copied to the connection struct as
1133
     it may live on without (this specific) Curl_easy */
1134
6.20k
  conn->fclosesocket = data->set.fclosesocket;
1135
6.20k
  conn->closesocket_client = data->set.closesocket_client;
1136
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1137
  conn->gssapi_delegation = data->set.gssapi_delegation;
1138
#endif
1139
6.20k
  return conn;
1140
0
error:
1141
1142
0
  curlx_free(conn->interface_opts);
1143
0
  curlx_free(conn);
1144
0
  return NULL;
1145
6.20k
}
1146
1147
static CURLcode url_set_conn_scheme(struct Curl_easy *data,
1148
                                    struct connectdata *conn)
1149
6.20k
{
1150
  /* URL scheme is usable for connection when it is
1151
   * - allowed
1152
   * - not from a redirect or an allowed redirect protocol */
1153
6.20k
  const struct Curl_scheme *scheme = conn->origin->scheme;
1154
6.20k
  if(scheme->run &&
1155
6.20k
     (data->set.allowed_protocols & scheme->protocol) &&
1156
6.20k
     (!data->state.this_is_a_follow ||
1157
6.20k
       (data->set.redir_protocols & scheme->protocol))) {
1158
6.20k
    conn->scheme = scheme;
1159
6.20k
    return CURLE_OK;
1160
6.20k
  }
1161
0
  if(scheme->flags & PROTOPT_NO_TRANSFER)
1162
0
    failf(data, "Protocol \"%s\" is not for transfers", scheme->name);
1163
0
  else
1164
0
    failf(data, "Protocol \"%s\" is disabled%s", scheme->name,
1165
0
          data->state.this_is_a_follow ? " (in redirect)" : "");
1166
0
  return CURLE_UNSUPPORTED_PROTOCOL;
1167
6.20k
}
1168
1169
CURLcode Curl_uc_to_curlcode(CURLUcode uc)
1170
355
{
1171
355
  switch(uc) {
1172
217
  default:
1173
217
    return CURLE_URL_MALFORMAT;
1174
0
  case CURLUE_UNSUPPORTED_SCHEME:
1175
0
    return CURLE_UNSUPPORTED_PROTOCOL;
1176
138
  case CURLUE_OUT_OF_MEMORY:
1177
138
    return CURLE_OUT_OF_MEMORY;
1178
0
  case CURLUE_USER_NOT_ALLOWED:
1179
0
    return CURLE_LOGIN_DENIED;
1180
355
  }
1181
355
}
1182
1183
#ifndef CURL_DISABLE_HSTS
1184
static CURLcode hsts_upgrade(struct Curl_easy *data,
1185
                             CURLU *uh,
1186
                             uint16_t port_override,
1187
                             uint32_t scope_id)
1188
6.22k
{
1189
  /* HSTS upgrade */
1190
6.22k
  if(data->hsts && (data->state.origin->scheme == &Curl_scheme_http) &&
1191
0
     Curl_hsts_applies(data->hsts, data->state.origin)) {
1192
0
    char *url;
1193
0
    CURLUcode uc;
1194
0
    CURLcode result;
1195
1196
0
    uc = curl_url_set(uh, CURLUPART_SCHEME, "https", 0);
1197
0
    if(uc)
1198
0
      return Curl_uc_to_curlcode(uc);
1199
0
    Curl_bufref_free(&data->state.url);
1200
    /* after update, get the updated version */
1201
0
    uc = curl_url_get(uh, CURLUPART_URL, &url, 0);
1202
0
    if(uc)
1203
0
      return Curl_uc_to_curlcode(uc);
1204
0
    Curl_bufref_set(&data->state.url, url, 0, curl_free);
1205
1206
0
    result = Curl_peer_from_url(uh, data, port_override, scope_id,
1207
0
                                &data->state.origin);
1208
0
    if(result)
1209
0
      return result;
1210
0
    infof(data, "Switched from HTTP to HTTPS due to HSTS => %s", url);
1211
0
  }
1212
6.22k
  return CURLE_OK;
1213
6.22k
}
1214
#else
1215
#define hsts_upgrade(x, y, z, a) CURLE_OK
1216
#endif
1217
1218
static bool str_has_ctrl(const char *input)
1219
1.89k
{
1220
1.89k
  if(input) {
1221
1.89k
    const unsigned char *str = (const unsigned char *)input;
1222
140k
    while(*str) {
1223
139k
      if(*str < 0x20)
1224
14
        return TRUE;
1225
138k
      str++;
1226
138k
    }
1227
1.89k
  }
1228
1.88k
  return FALSE;
1229
1.89k
}
1230
1231
#ifndef CURL_DISABLE_NETRC
1232
/*
1233
 * Override the login details from the URL with that in the CURLOPT_USERPWD
1234
 * option or a .netrc file, if applicable.
1235
 */
1236
static CURLcode url_set_data_creds_netrc(struct Curl_easy *data,
1237
                                         struct Curl_creds **pcreds)
1238
6.20k
{
1239
6.20k
  struct Curl_creds *ncreds_out = NULL;
1240
6.20k
  CURLcode result = CURLE_OK;
1241
1242
6.20k
  if(data->set.use_netrc) { /* not CURL_NETRC_IGNORED */
1243
0
    struct Curl_creds *ncreds_in = NULL;
1244
0
    bool scan_netrc = TRUE;
1245
0
    NETRCcode ret;
1246
0
    CURLUcode uc;
1247
1248
0
    if(*pcreds) {
1249
0
      switch((*pcreds)->source) {
1250
0
      case CREDS_OPTION:
1251
        /* we never override credentials set via CURLOPT_*, leave. */
1252
0
        scan_netrc = FALSE;
1253
0
        break;
1254
0
      case CREDS_URL: /* only apply when netrc is not required */
1255
0
        if(data->set.use_netrc == CURL_NETRC_REQUIRED) {
1256
          /* We ignore password from URL */
1257
0
          ncreds_in = *pcreds;
1258
0
        }
1259
0
        else if(!Curl_creds_has_user(*pcreds) ||
1260
0
                !Curl_creds_has_passwd(*pcreds)) {
1261
          /* We use netrc to complete what is missing */
1262
0
          ncreds_in = *pcreds;
1263
0
        }
1264
0
        else
1265
0
          scan_netrc = FALSE;
1266
0
        break;
1267
0
      default: /* ignore credentials from other sources */
1268
0
        break;
1269
0
      }
1270
0
    }
1271
1272
0
    if(!scan_netrc)
1273
0
      goto out;
1274
1275
0
    ret = Curl_netrc_scan(data, &data->state.netrc,
1276
0
                          data->state.origin->hostname,
1277
0
                          Curl_creds_user(ncreds_in),
1278
0
                          CURL_EASY_STR(data, STRING_NETRC_FILE),
1279
0
                          &ncreds_out);
1280
0
    DEBUGASSERT(!ret || !ncreds_out);
1281
0
    if(ret == NETRC_OUT_OF_MEMORY) {
1282
0
      result = CURLE_OUT_OF_MEMORY;
1283
0
      goto out;
1284
0
    }
1285
0
    else if(ret && ((ret == NETRC_NO_MATCH) ||
1286
0
                    (data->set.use_netrc == CURL_NETRC_OPTIONAL))) {
1287
0
      infof(data, "Could not find host %s in the %s file; using defaults",
1288
0
            data->state.origin->hostname,
1289
0
            (CURL_EASY_STR(data, STRING_NETRC_FILE) ?
1290
0
             CURL_EASY_STR(data, STRING_NETRC_FILE) : ".netrc"));
1291
0
    }
1292
0
    else if(ret) {
1293
0
      const char *m = Curl_netrc_strerror(ret);
1294
0
      failf(data, ".netrc error: %s", m);
1295
0
      result = CURLE_READ_ERROR;
1296
0
      goto out;
1297
0
    }
1298
0
    else if(ncreds_out) {
1299
0
      if(!(data->state.origin->scheme->flags & PROTOPT_USERPWDCTRL) &&
1300
         /* if the protocol cannot handle control codes in credentials, make
1301
            sure there are none */
1302
0
         (str_has_ctrl(ncreds_out->user) ||
1303
0
          str_has_ctrl(ncreds_out->passwd))) {
1304
0
        failf(data, "control code detected in .netrc credentials");
1305
0
        result = CURLE_READ_ERROR;
1306
0
        goto out;
1307
0
      }
1308
0
      CURL_TRC_M(data, "netrc: using credentials for %s as %s",
1309
0
                 data->state.origin->hostname, ncreds_out->user);
1310
0
      result = Curl_creds_merge(ncreds_out->user, ncreds_out->passwd,
1311
0
                                *pcreds, CREDS_NETRC, pcreds);
1312
0
      if(result)
1313
0
        goto out;
1314
      /* for updated strings, we update them in the URL */
1315
0
      uc = curl_url_set(data->state.uh, CURLUPART_USER,
1316
0
                        Curl_creds_user(*pcreds), CURLU_URLENCODE);
1317
0
      if(!uc)
1318
0
        uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD,
1319
0
                          Curl_creds_passwd(*pcreds),
1320
0
                          CURLU_URLENCODE);
1321
0
      if(uc)
1322
0
        result = Curl_uc_to_curlcode(uc);
1323
0
    }
1324
0
    else
1325
0
      DEBUGASSERT(0);
1326
0
  }
1327
1328
6.20k
#ifdef CURLVERBOSE
1329
6.20k
  Curl_creds_trace(data, data->state.creds, "transfer credentials");
1330
6.20k
#endif
1331
1332
6.20k
out:
1333
6.20k
  Curl_creds_unlink(&ncreds_out);
1334
6.20k
  return result;
1335
6.20k
}
1336
#endif /* CURL_DISABLE_NETRC */
1337
1338
static CURLcode url_set_data_creds(struct Curl_easy *data, CURLU *uh)
1339
6.22k
{
1340
6.22k
  struct Curl_creds *newcreds = NULL;
1341
6.22k
  CURLcode result = CURLE_OK;
1342
1343
6.22k
  if((CURL_EASY_STR(data, STRING_USERNAME) ||
1344
5.61k
      CURL_EASY_STR(data, STRING_PASSWORD) ||
1345
5.44k
      CURL_EASY_STR(data, STRING_BEARER) ||
1346
5.31k
      CURL_EASY_STR(data, STRING_SASL_AUTHZID) ||
1347
5.25k
      CURL_EASY_STR(data, STRING_SERVICE_NAME)) &&
1348
964
     Curl_auth_allowed_to_origin(data, data->state.origin)) {
1349
964
    result = Curl_creds_create(CURL_EASY_STR(data, STRING_USERNAME),
1350
964
                               CURL_EASY_STR(data, STRING_PASSWORD),
1351
964
                               CURL_EASY_STR(data, STRING_BEARER),
1352
964
                               CURL_EASY_STR(data, STRING_SASL_AUTHZID),
1353
964
                               CURL_EASY_STR(data, STRING_SERVICE_NAME),
1354
964
                               CREDS_OPTION, &newcreds);
1355
964
    if(result)
1356
0
      goto out;
1357
964
    if(newcreds &&
1358
952
       !(data->state.origin->scheme->flags & PROTOPT_USERPWDCTRL) &&
1359
952
       (str_has_ctrl(Curl_creds_user(newcreds)) ||
1360
942
        str_has_ctrl(Curl_creds_passwd(newcreds)))) {
1361
      /* if the protocol cannot handle control codes in credentials, make
1362
         sure there are none */
1363
14
      failf(data, "control code detected in credentials");
1364
14
      result = CURLE_BAD_FUNCTION_ARGUMENT;
1365
14
      goto out;
1366
14
    }
1367
964
  }
1368
1369
  /* Extract credentials from the URL only if there are none OR
1370
   * if no CURLOPT_USER was set. */
1371
6.20k
  if(!newcreds || !Curl_creds_has_user(newcreds)) {
1372
5.98k
    char *user = NULL;
1373
5.98k
    char *passwd = NULL;
1374
5.98k
    char *udecoded = NULL;
1375
5.98k
    char *pdecoded = NULL;
1376
5.98k
    CURLUcode uc;
1377
1378
5.98k
    uc = curl_url_get(uh, CURLUPART_USER, &user, 0);
1379
5.98k
    if(uc && (uc != CURLUE_NO_USER))
1380
0
      result = Curl_uc_to_curlcode(uc);
1381
5.98k
    if(!result) {
1382
5.98k
      uc = curl_url_get(uh, CURLUPART_PASSWORD, &passwd, 0);
1383
5.98k
      if(uc && (uc != CURLUE_NO_PASSWORD))
1384
0
        result = Curl_uc_to_curlcode(uc);
1385
5.98k
    }
1386
5.98k
    if(!result && user) {
1387
0
      result = Curl_urldecode(user, 0, &udecoded, NULL,
1388
0
                              (data->state.origin->scheme->flags &
1389
0
                               PROTOPT_USERPWDCTRL) ?
1390
0
                              REJECT_ZERO : REJECT_CTRL);
1391
0
    }
1392
5.98k
    if(!result && passwd) {
1393
0
      result = Curl_urldecode(passwd, 0, &pdecoded, NULL,
1394
0
                              (data->state.origin->scheme->flags &
1395
0
                               PROTOPT_USERPWDCTRL) ?
1396
0
                              REJECT_ZERO : REJECT_CTRL);
1397
0
    }
1398
5.98k
    if(!result)
1399
5.98k
      result = Curl_creds_merge(udecoded, pdecoded, newcreds,
1400
5.98k
                                CREDS_URL, &newcreds);
1401
1402
5.98k
    curlx_free(udecoded);
1403
5.98k
    curlx_free(pdecoded);
1404
5.98k
    curlx_free(passwd);
1405
5.98k
    curlx_free(user);
1406
5.98k
    if(result) {
1407
2
      failf(data, "error extracting credentials from URL");
1408
2
      goto out;
1409
2
    }
1410
5.98k
  }
1411
1412
6.20k
#ifndef CURL_DISABLE_NETRC
1413
  /* Check for overridden login details and set them accordingly so that
1414
     they are known when protocol->setup_connection is called! */
1415
6.20k
  result = url_set_data_creds_netrc(data, &newcreds);
1416
6.20k
#endif /* CURL_DISABLE_NETRC */
1417
1418
6.22k
out:
1419
6.22k
  if(!result && !Curl_creds_equal(data->state.creds, newcreds)) {
1420
    /* Do we have more things to trigger on credentials change? */
1421
936
    Curl_creds_link(&data->state.creds, newcreds);
1422
936
  }
1423
6.22k
  Curl_creds_unlink(&newcreds);
1424
6.22k
  return result;
1425
6.20k
}
1426
1427
static CURLcode url_set_conn_origin_etc(struct Curl_easy *data,
1428
                                        struct connectdata *conn)
1429
6.20k
{
1430
6.20k
  CURLcode result = CURLE_OK;
1431
1432
6.20k
  Curl_peer_link(&conn->origin, data->state.origin);
1433
1434
  /* set the connection scheme */
1435
6.20k
  result = url_set_conn_scheme(data, conn);
1436
6.20k
  if(result)
1437
0
    goto out;
1438
1439
  /* set the connection options */
1440
6.20k
  if(CURL_EASY_STR(data, STRING_OPTIONS)) {
1441
121
    conn->options = curlx_strdup(CURL_EASY_STR(data, STRING_OPTIONS));
1442
121
    if(!conn->options) {
1443
0
      result = CURLE_OUT_OF_MEMORY;
1444
0
      goto out;
1445
0
    }
1446
121
  }
1447
6.08k
  else if(data->state.up.options) {
1448
0
    conn->options = curlx_strdup(data->state.up.options);
1449
0
    if(!conn->options) {
1450
0
      result = CURLE_OUT_OF_MEMORY;
1451
0
      goto out;
1452
0
    }
1453
0
  }
1454
1455
6.20k
out:
1456
6.20k
  return result;
1457
6.20k
}
1458
1459
/*
1460
 * If we are doing a resumed transfer, we need to setup our stuff
1461
 * properly.
1462
 */
1463
static CURLcode setup_range(struct Curl_easy *data)
1464
6.17k
{
1465
6.17k
  struct UrlState *s = &data->state;
1466
6.17k
  s->resume_from = data->set.set_resume_from;
1467
6.17k
  if(s->resume_from || CURL_EASY_STR(data, STRING_SET_RANGE)) {
1468
0
    if(s->rangestringalloc)
1469
0
      curlx_free(s->range);
1470
1471
0
    if(s->resume_from)
1472
0
      s->range = curl_maprintf("%" FMT_OFF_T "-", s->resume_from);
1473
0
    else
1474
0
      s->range = curlx_strdup(CURL_EASY_STR(data, STRING_SET_RANGE));
1475
1476
0
    if(!s->range)
1477
0
      return CURLE_OUT_OF_MEMORY;
1478
1479
0
    s->rangestringalloc = TRUE;
1480
1481
    /* tell ourselves to fetch this range */
1482
0
    s->use_range = TRUE;        /* enable range download */
1483
0
  }
1484
6.17k
  else
1485
6.17k
    s->use_range = FALSE; /* disable range download */
1486
1487
6.17k
  return CURLE_OK;
1488
6.17k
}
1489
1490
/*
1491
 * setup_connection_internals() -
1492
 *
1493
 * Setup connection internals specific to the requested protocol in the
1494
 * Curl_easy. This is inited and setup before the connection is made but
1495
 * is about the particular protocol that is to be used.
1496
 *
1497
 * This MUST get called after proxy magic has been figured out.
1498
 */
1499
static CURLcode setup_connection_internals(struct Curl_easy *data,
1500
                                           struct connectdata *conn)
1501
6.20k
{
1502
6.20k
  struct Curl_peer *peer = NULL;
1503
1504
6.20k
  if(conn->scheme->run->setup_connection) {
1505
6.20k
    CURLcode result = conn->scheme->run->setup_connection(data, conn);
1506
6.20k
    if(result)
1507
14
      return result;
1508
6.20k
  }
1509
1510
  /* Now create the destination name */
1511
6.18k
  peer = Curl_conn_get_destination(conn);
1512
6.18k
  if(!peer)
1513
0
    return CURLE_FAILED_INIT;
1514
1515
  /* IPv6 addresses with a scope_id (0 is default == global) have a
1516
   * printable representation with a '%<scope_id>' suffix. */
1517
6.18k
  if(peer->ipv6)
1518
0
    if(peer->scopeid)
1519
0
      conn->destination = curl_maprintf("[%s%%%u]:%u",
1520
0
        peer->hostname, peer->scopeid, peer->port);
1521
0
    else
1522
0
      conn->destination = curl_maprintf("[%s]:%u",
1523
0
        peer->hostname, peer->port);
1524
6.18k
  else
1525
6.18k
    conn->destination = curl_maprintf("%s:%u", peer->hostname, peer->port);
1526
6.18k
  if(!conn->destination)
1527
2
    return CURLE_OUT_OF_MEMORY;
1528
1529
6.18k
  Curl_strntolower(conn->destination, conn->destination,
1530
6.18k
                   strlen(conn->destination));
1531
1532
6.18k
#ifdef USE_IPV6
1533
6.18k
  if(data->set.scope_id)
1534
0
    conn->scope_id = data->set.scope_id;
1535
6.18k
  else {
1536
6.18k
    peer = Curl_conn_get_first_peer(conn);
1537
6.18k
    if(!peer)
1538
0
      return CURLE_FAILED_INIT;
1539
6.18k
    conn->scope_id = peer->scopeid;
1540
6.18k
  }
1541
6.18k
#endif
1542
1543
6.18k
  return CURLE_OK;
1544
6.18k
}
1545
1546
/*
1547
 * Curl_parse_login_details()
1548
 *
1549
 * This is used to parse a login string for username, password and options in
1550
 * the following formats:
1551
 *
1552
 *   user
1553
 *   user:password
1554
 *   user:password;options
1555
 *   user;options
1556
 *   user;options:password
1557
 *   :password
1558
 *   :password;options
1559
 *   ;options
1560
 *   ;options:password
1561
 *
1562
 * Parameters:
1563
 *
1564
 * login    [in]     - login string.
1565
 * len      [in]     - length of the login string.
1566
 * userp    [in/out] - address where a pointer to newly allocated memory
1567
 *                     holding the user will be stored upon completion.
1568
 * passwdp  [in/out] - address where a pointer to newly allocated memory
1569
 *                     holding the password will be stored upon completion.
1570
 * optionsp [in/out] - OPTIONAL address where a pointer to newly allocated
1571
 *                     memory holding the options will be stored upon
1572
 *                     completion.
1573
 *
1574
 * Returns CURLE_OK on success.
1575
 */
1576
CURLcode Curl_parse_login_details(const char *login, const size_t len,
1577
                                  char **userp, char **passwdp,
1578
                                  char **optionsp)
1579
2.11k
{
1580
2.11k
  char *ubuf = NULL;
1581
2.11k
  char *pbuf = NULL;
1582
2.11k
  const char *psep = NULL;
1583
2.11k
  const char *osep = NULL;
1584
2.11k
  size_t ulen;
1585
2.11k
  size_t plen;
1586
2.11k
  size_t olen;
1587
1588
2.11k
  DEBUGASSERT(userp);
1589
2.11k
  DEBUGASSERT(passwdp);
1590
1591
  /* Attempt to find the password separator */
1592
2.11k
  psep = memchr(login, ':', len);
1593
1594
  /* Attempt to find the options separator */
1595
2.11k
  if(optionsp)
1596
0
    osep = memchr(login, ';', len);
1597
1598
  /* Calculate the portion lengths */
1599
2.11k
  ulen = (psep ?
1600
498
          (size_t)(osep && psep > osep ? osep - login : psep - login) :
1601
2.11k
          (osep ? (size_t)(osep - login) : len));
1602
2.11k
  plen = (psep ?
1603
498
          (osep && osep > psep ? (size_t)(osep - psep) :
1604
1.61k
           (size_t)(login + len - psep)) - 1 : 0);
1605
2.11k
  olen = (osep ?
1606
0
          (psep && psep > osep ? (size_t)(psep - osep) :
1607
2.11k
           (size_t)(login + len - osep)) - 1 : 0);
1608
1609
  /* Clone the user portion buffer, which can be zero length */
1610
2.11k
  ubuf = curlx_memdup0(login, ulen);
1611
2.11k
  if(!ubuf)
1612
7
    goto error;
1613
1614
  /* Clone the password portion buffer */
1615
2.10k
  if(psep) {
1616
497
    pbuf = curlx_memdup0(&psep[1], plen);
1617
497
    if(!pbuf)
1618
7
      goto error;
1619
497
  }
1620
1621
  /* Allocate the options portion buffer */
1622
2.10k
  if(optionsp) {
1623
0
    char *obuf = NULL;
1624
0
    if(olen) {
1625
0
      obuf = curlx_memdup0(&osep[1], olen);
1626
0
      if(!obuf)
1627
0
        goto error;
1628
0
    }
1629
0
    *optionsp = obuf;
1630
0
  }
1631
2.10k
  *userp = ubuf;
1632
2.10k
  *passwdp = pbuf;
1633
2.10k
  return CURLE_OK;
1634
14
error:
1635
14
  curlx_free(ubuf);
1636
14
  curlx_free(pbuf);
1637
14
  return CURLE_OUT_OF_MEMORY;
1638
2.10k
}
1639
1640
/*
1641
 * Set the login details so they are available in the connection
1642
 */
1643
static CURLcode url_set_conn_login(struct Curl_easy *data,
1644
                                   struct connectdata *conn)
1645
6.20k
{
1646
  /* If our protocol needs a password and we have none, use the defaults */
1647
6.20k
  if((conn->scheme->flags & PROTOPT_NEEDSPWD) && !conn->creds) {
1648
0
    Curl_peer_link(&conn->creds_origin, data->state.origin);
1649
0
    if(data->state.creds)
1650
0
      Curl_creds_link(&conn->creds, data->state.creds);
1651
0
    else
1652
0
      return Curl_creds_create(CURL_DEFAULT_USER, CURL_DEFAULT_PASSWORD,
1653
0
                               NULL, NULL, NULL, CREDS_NONE, &conn->creds);
1654
0
  }
1655
6.20k
  else if(!(conn->scheme->flags & PROTOPT_CREDSPERREQUEST)) {
1656
    /* for protocols that do not handle credentials per request,
1657
     * the connection credentials are set by the initial transfer. */
1658
6.20k
    Curl_peer_link(&conn->creds_origin, data->state.origin);
1659
6.20k
    Curl_creds_link(&conn->creds, data->state.creds);
1660
6.20k
  }
1661
1662
6.20k
  return CURLE_OK;
1663
6.20k
}
1664
1665
/*
1666
 * Parses one "connect to" string in the form:
1667
 * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
1668
 */
1669
static CURLcode parse_connect_to_string(struct Curl_easy *data,
1670
                                        const struct Curl_peer *dest,
1671
                                        const char *conn_to_line,
1672
                                        struct Curl_peer **pvia_dest)
1673
6.10k
{
1674
6.10k
  CURLcode result = CURLE_OK;
1675
6.10k
  const char *ptr = conn_to_line;
1676
6.10k
  bool host_match = FALSE;
1677
6.10k
  bool port_match = FALSE;
1678
1679
6.10k
  *pvia_dest = NULL;
1680
1681
6.10k
  if(*ptr == ':') {
1682
    /* an empty hostname always matches */
1683
6.10k
    host_match = TRUE;
1684
6.10k
    ptr++;
1685
6.10k
  }
1686
0
  else {
1687
    /* check whether the URL's hostname matches. Use the URL hostname
1688
     * when it was an IPv6 address. Otherwise use the connection's hostname
1689
     * that has IDN conversion. */
1690
0
    size_t hlen = strlen(dest->hostname);
1691
0
    host_match = curl_strnequal(ptr, dest->hostname, hlen);
1692
0
    if(!host_match && (dest->user_hostname != dest->hostname)) {
1693
      /* hostname was normalized, could be IPv6 or IDN */
1694
0
      hlen = strlen(dest->user_hostname);
1695
0
      host_match = curl_strnequal(ptr, dest->user_hostname, hlen);
1696
0
    }
1697
0
    host_match = host_match && ptr[hlen] == ':';
1698
0
    if(host_match)
1699
0
      ptr += hlen + 1;
1700
0
  }
1701
1702
6.10k
  if(host_match) {
1703
6.10k
    if(*ptr == ':') {
1704
      /* an empty port always matches */
1705
6.10k
      port_match = TRUE;
1706
6.10k
      ptr++;
1707
6.10k
    }
1708
0
    else {
1709
      /* check whether the URL's port matches */
1710
0
      const char *ptr_next = strchr(ptr, ':');
1711
0
      if(ptr_next) {
1712
0
        curl_off_t port_to_match;
1713
0
        if(!curlx_str_number(&ptr, &port_to_match, 0xffff) &&
1714
0
           ((uint16_t)port_to_match == dest->port)) {
1715
0
          port_match = TRUE;
1716
0
        }
1717
0
        ptr = ptr_next + 1;
1718
0
      }
1719
0
    }
1720
6.10k
  }
1721
1722
6.10k
  if(host_match && port_match && ptr && *ptr)
1723
6.10k
    result = Curl_peer_from_connect_to(data, dest, ptr, pvia_dest);
1724
1725
6.10k
  return result;
1726
6.10k
}
1727
1728
/* With `conn->origin` known, determine if we should talk to that
1729
 * directly or via another peer. This is the result of inspecting
1730
 * the "connect to" slist and "alt-svc" settings. */
1731
static CURLcode url_set_conn_peer(struct Curl_easy *data,
1732
                                  struct connectdata *conn)
1733
6.20k
{
1734
6.20k
  CURLcode result = CURLE_OK;
1735
6.20k
  struct Curl_peer *origin = conn->origin;
1736
6.20k
  struct Curl_peer *via_peer = NULL;
1737
6.20k
  struct Curl_frzn_strs *cto_strs = data->set.a.connect_to;
1738
6.20k
  const char *s;
1739
6.20k
  size_t i;
1740
1741
6.20k
  DEBUGASSERT(!conn->via_peer);
1742
6.20k
  Curl_peer_unlink(&conn->via_peer);
1743
1744
12.3k
  for(i = 0; (i < Curl_frzn_strs_count(cto_strs)) && !via_peer; ++i) {
1745
6.10k
    s = Curl_frzn_strs_get_str(cto_strs, i);
1746
6.10k
    if(!s)
1747
0
      continue;
1748
6.10k
    result = parse_connect_to_string(data, origin, s, &via_peer);
1749
6.10k
    if(result)
1750
2
      return result;
1751
6.10k
  }
1752
1753
6.20k
#ifndef CURL_DISABLE_ALTSVC
1754
6.20k
  if(data->asi && !via_peer &&
1755
94
     ((conn->scheme->protocol == CURLPROTO_HTTPS) ||
1756
94
#ifdef DEBUGBUILD
1757
      /* allow debug builds to circumvent the HTTPS restriction */
1758
94
      getenv("CURL_ALTSVC_HTTP")
1759
#else
1760
      0
1761
#endif
1762
94
       )) {
1763
    /* no connect_to match, try alt-svc! */
1764
94
    enum alpnid srcalpnid = ALPN_none;
1765
94
    bool hit = FALSE;
1766
94
    struct altsvc *as = NULL;
1767
94
    int allowed_alpns = ALPN_none;
1768
94
    struct http_negotiation *neg = &data->state.http_neg;
1769
94
    bool same_dest = FALSE;
1770
1771
94
    DEBUGF(infof(data, "Alt-svc check wanted=%x, allowed=%x",
1772
94
                 neg->wanted, neg->allowed));
1773
#ifdef USE_HTTP3
1774
    if(neg->allowed & CURL_HTTP_V3x)
1775
      allowed_alpns |= ALPN_h3;
1776
#endif
1777
94
#ifdef USE_HTTP2
1778
94
    if(neg->allowed & CURL_HTTP_V2x)
1779
94
      allowed_alpns |= ALPN_h2;
1780
94
#endif
1781
94
    if(neg->allowed & CURL_HTTP_V1x)
1782
94
      allowed_alpns |= ALPN_h1;
1783
94
    allowed_alpns &= (int)data->asi->flags;
1784
1785
94
    DEBUGF(infof(data, "check Alt-Svc for host '%s'", origin->hostname));
1786
#ifdef USE_HTTP3
1787
    if(!hit && (neg->wanted & CURL_HTTP_V3x)) {
1788
      srcalpnid = ALPN_h3;
1789
      hit = Curl_altsvc_lookup(data->asi,
1790
                               origin, ALPN_h3, /* from */
1791
                               &as /* to */,
1792
                               allowed_alpns, &same_dest);
1793
    }
1794
#endif
1795
94
#ifdef USE_HTTP2
1796
94
    if(!hit && (neg->wanted & CURL_HTTP_V2x) &&
1797
94
       !neg->h2_prior_knowledge) {
1798
94
      srcalpnid = ALPN_h2;
1799
94
      hit = Curl_altsvc_lookup(data->asi,
1800
94
                               origin, ALPN_h2, /* from */
1801
94
                               &as /* to */,
1802
94
                               allowed_alpns, &same_dest);
1803
94
    }
1804
94
#endif
1805
94
    if(!hit && (neg->wanted & CURL_HTTP_V1x) &&
1806
94
       !neg->only_10) {
1807
94
      srcalpnid = ALPN_h1;
1808
94
      hit = Curl_altsvc_lookup(data->asi,
1809
94
                               origin, ALPN_h1, /* from */
1810
94
                               &as /* to */,
1811
94
                               allowed_alpns, &same_dest);
1812
94
    }
1813
1814
94
    if(hit && same_dest) {
1815
      /* same destination, but more HTTPS version options */
1816
0
      switch(as->dst.alpnid) {
1817
0
      case ALPN_h1:
1818
0
        neg->wanted |= CURL_HTTP_V1x;
1819
0
        neg->preferred = CURL_HTTP_V1x;
1820
0
        break;
1821
0
      case ALPN_h2:
1822
0
        neg->wanted |= CURL_HTTP_V2x;
1823
0
        neg->preferred = CURL_HTTP_V2x;
1824
0
        break;
1825
0
      case ALPN_h3:
1826
0
        neg->wanted |= CURL_HTTP_V3x;
1827
0
        neg->preferred = CURL_HTTP_V3x;
1828
0
        break;
1829
0
      default: /* should not be possible */
1830
0
        break;
1831
0
      }
1832
0
    }
1833
94
    else if(hit) {
1834
0
      result = Curl_peer_create(data, conn->origin->scheme,
1835
0
                                as->dst.host, as->dst.port,
1836
0
                                &via_peer);
1837
0
      if(result)
1838
0
        return result;
1839
0
      infof(data, "Alt-svc connecting from [%s]%s:%u to [%s]%s:%u",
1840
0
            Curl_alpnid2str(srcalpnid), origin->hostname, origin->port,
1841
0
            Curl_alpnid2str(as->dst.alpnid),
1842
0
            via_peer->hostname, via_peer->port);
1843
0
      conn->bits.altused = TRUE;
1844
0
      if(srcalpnid != as->dst.alpnid) {
1845
        /* protocol version switch */
1846
0
        switch(as->dst.alpnid) {
1847
0
        case ALPN_h1:
1848
0
          neg->wanted = neg->allowed = CURL_HTTP_V1x;
1849
0
          neg->only_10 = FALSE;
1850
0
          break;
1851
0
        case ALPN_h2:
1852
0
          neg->wanted = neg->allowed = CURL_HTTP_V2x;
1853
0
          break;
1854
0
        case ALPN_h3:
1855
0
          conn->transport_wanted = TRNSPRT_QUIC;
1856
0
          neg->wanted = neg->allowed = CURL_HTTP_V3x;
1857
0
          break;
1858
0
        default: /* should not be possible */
1859
0
          break;
1860
0
        }
1861
0
      }
1862
0
    }
1863
94
  }
1864
6.20k
#endif
1865
1866
6.20k
  if(via_peer)
1867
6.09k
    conn->via_peer = via_peer;
1868
1869
6.20k
  return result;
1870
6.20k
}
1871
1872
/*
1873
 * Adjust reused connection settings to the transfer/needle.
1874
 */
1875
static void url_conn_reuse_adjust(struct Curl_easy *data,
1876
                                  struct connectdata *needle)
1877
0
{
1878
0
  struct connectdata *conn = data->conn;
1879
1880
  /* get the user+password information from the needle since it may
1881
   * be new for this request even when we reuse conn */
1882
0
  if(needle->creds) {
1883
    /* use the new username and password though */
1884
0
    Curl_creds_link(&conn->creds, needle->creds);
1885
0
  }
1886
1887
0
#ifndef CURL_DISABLE_PROXY
1888
  /* use the new proxy username and proxy password though */
1889
0
  Curl_creds_link(&conn->http_proxy.creds, needle->http_proxy.creds);
1890
0
  Curl_creds_link(&conn->socks_proxy.creds, needle->socks_proxy.creds);
1891
0
#endif
1892
1893
  /* Finding a connection for reuse in the cpool matches, among other
1894
   * things on the "remote-relevant" hostname. This is not necessarily
1895
   * the authority of the URL, e.g. conn->origin. For example:
1896
   * - we use a proxy (not tunneling). we want to send all requests
1897
   *   that use the same proxy on this connection.
1898
   * - we have a "connect-to" setting that may redirect the hostname of
1899
   *   a new request to the same remote endpoint of an existing conn.
1900
   *   We want to reuse an existing conn to the remote endpoint.
1901
   * Since connection reuse does not match on conn->origin necessarily, we
1902
   * switch conn to needle's host settings.
1903
   */
1904
0
  Curl_peer_link(&conn->origin, needle->origin);
1905
0
  Curl_peer_link(&conn->via_peer, needle->via_peer);
1906
0
  Curl_peer_link(&conn->origin2, needle->origin2);
1907
0
  Curl_peer_link(&conn->via_peer2, needle->via_peer2);
1908
0
}
1909
1910
static void conn_meta_freeentry(void *p)
1911
0
{
1912
0
  (void)p;
1913
  /* Always FALSE. Cannot use a 0 assert here since compilers
1914
   * are not in agreement if they then want a NORETURN attribute or
1915
   * not. *sigh* */
1916
0
  DEBUGASSERT(!p);
1917
0
}
1918
1919
static CURLcode url_create_needle(struct Curl_easy *data,
1920
                                  struct connectdata **pneedle)
1921
6.20k
{
1922
6.20k
  struct connectdata *needle = NULL;
1923
6.20k
  CURLcode result = CURLE_OK;
1924
6.20k
  bool network_scheme = TRUE; /* almost all are */
1925
1926
  /* Allocate a temporary connection data struct (needle) and fill in for
1927
     comparison purposes. */
1928
6.20k
  needle = allocate_conn(data);
1929
6.20k
  if(!needle) {
1930
4
    result = CURLE_OUT_OF_MEMORY;
1931
4
    goto out;
1932
4
  }
1933
1934
  /* Do the unfailable inits first, before checks that may early return */
1935
6.20k
  Curl_hash_init(&needle->meta_hash, 23, CURL_HASH_TYPE_BYTES,
1936
6.20k
                 conn_meta_freeentry);
1937
1938
  /*************************************************************
1939
   * Determine `conn->origin` and populate `data->state.up` and
1940
   * other URL related properties.
1941
   *************************************************************/
1942
6.20k
  result = url_set_conn_origin_etc(data, needle);
1943
6.20k
  if(result)
1944
0
    goto out;
1945
1946
6.20k
  DEBUGASSERT(needle->origin);
1947
6.20k
  network_scheme = !(needle->origin->scheme->flags & PROTOPT_NONETWORK);
1948
1949
6.20k
#ifdef USE_UNIX_SOCKETS
1950
  /*************************************************************
1951
   * Set UDS first. It overrides "via_peer" and proxy settings.
1952
   *************************************************************/
1953
6.20k
  if(network_scheme && CURL_EASY_STR(data, STRING_UNIX_SOCKET_PATH)) {
1954
0
    result = Curl_peer_uds_create(
1955
0
      needle->origin->scheme, CURL_EASY_STR(data, STRING_UNIX_SOCKET_PATH),
1956
0
      (bool)data->set.abstract_unix_socket, &needle->via_peer);
1957
0
    if(result)
1958
0
      goto out;
1959
0
  }
1960
6.20k
#endif /* USE_UNIX_SOCKETS */
1961
1962
6.20k
  if(network_scheme && !needle->via_peer) {
1963
    /*************************************************************
1964
     * If the `via_peer` is not already set (via UDS above),
1965
     * determine if we talk to `conn->origin` directly or use
1966
     * `conn->via_peer` using "connect to" and "alt-svc" properties.
1967
     *************************************************************/
1968
6.20k
    result = url_set_conn_peer(data, needle);
1969
6.20k
    if(result)
1970
2
      goto out;
1971
6.20k
  }
1972
1973
  /*************************************************************
1974
   * Check whether the host and the "connect to host" are equal.
1975
   * Do this after the hostnames have been IDN-converted and
1976
   * before initializing the proxy.
1977
   *************************************************************/
1978
6.20k
  if(Curl_peer_equal(needle->origin, needle->via_peer)) {
1979
0
    Curl_peer_unlink(&needle->via_peer);
1980
0
  }
1981
1982
6.20k
#ifndef CURL_DISABLE_PROXY
1983
  /* Going via a unix socket ignores any proxy settings */
1984
6.20k
  if(network_scheme &&
1985
6.20k
     (!needle->via_peer || !needle->via_peer->unix_socket)) {
1986
6.20k
    result = Curl_proxy_init_conn(data, needle);
1987
6.20k
    if(result)
1988
0
      goto out;
1989
6.20k
  }
1990
6.20k
#endif /* CURL_DISABLE_PROXY */
1991
1992
6.20k
  result = url_set_conn_login(data, needle); /* default credentials */
1993
6.20k
  if(result)
1994
0
    goto out;
1995
1996
  /*************************************************************
1997
   * Setup internals depending on protocol. Needs to be done after
1998
   * we figured out what/if proxy to use.
1999
   *************************************************************/
2000
6.20k
  result = setup_connection_internals(data, needle);
2001
6.20k
  if(result)
2002
16
    goto out;
2003
2004
6.18k
  if(needle->scheme->flags & PROTOPT_ALPN) {
2005
    /* The protocol wants it, so set the bits if enabled in the easy handle
2006
       (default) */
2007
0
    if(data->set.ssl_enable_alpn)
2008
0
      needle->bits.tls_enable_alpn = TRUE;
2009
0
  }
2010
2011
6.18k
  if(network_scheme) {
2012
    /* Setup callbacks for network connections */
2013
6.18k
    needle->do_recv = Curl_cf_recv;
2014
6.18k
    needle->do_send = Curl_cf_send;
2015
6.18k
    needle->bits.tcp_fastopen = data->set.tcp_fastopen;
2016
6.18k
#ifdef USE_UNIX_SOCKETS
2017
6.18k
    if(Curl_conn_get_first_peer(needle)->unix_socket)
2018
0
      needle->transport_wanted = TRNSPRT_UNIX;
2019
6.18k
#endif
2020
6.18k
  }
2021
2022
6.20k
out:
2023
6.20k
  if(!result) {
2024
6.18k
    DEBUGASSERT(needle);
2025
6.18k
    DEBUGASSERT(needle->origin);
2026
6.18k
    *pneedle = needle;
2027
6.18k
  }
2028
22
  else {
2029
22
    *pneedle = NULL;
2030
22
    if(needle)
2031
18
      Curl_conn_free(data, needle);
2032
22
  }
2033
6.20k
  return result;
2034
6.20k
}
2035
2036
static CURLcode url_set_data_origin_and_creds(struct Curl_easy *data)
2037
6.39k
{
2038
6.39k
  CURLcode result = CURLE_OK;
2039
6.39k
  CURLU *uh;
2040
6.39k
  CURLUcode uc = CURLUE_OK;
2041
6.39k
  bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow);
2042
6.39k
  uint16_t port_override = data->state.allow_port ? data->set.use_port : 0;
2043
6.39k
  uint32_t scope_id = 0;
2044
2045
  /*************************************************************
2046
   * Check input data
2047
   *************************************************************/
2048
6.39k
  if(!Curl_bufref_ptr(&data->state.url)) {
2049
0
    result = CURLE_URL_MALFORMAT;
2050
0
    goto out;
2051
0
  }
2052
2053
6.39k
  up_free(data); /* cleanup previous leftovers first */
2054
2055
  /* parse the URL */
2056
6.39k
  if(use_set_uh)
2057
0
    uh = data->state.uh = curl_url_dup(data->set.uh);
2058
6.39k
  else
2059
6.39k
    uh = data->state.uh = curl_url();
2060
6.39k
  if(!uh) {
2061
7
    result = CURLE_OUT_OF_MEMORY;
2062
7
    goto out;
2063
7
  }
2064
2065
6.39k
  if(!use_set_uh) {
2066
6.39k
    bool prepend_sheme = FALSE;
2067
    /* special-case when 'file' is default as a normal path is not a valid URL
2068
       without the 'file' scheme present */
2069
6.39k
    if(curl_strequal("file", CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL)) &&
2070
0
       !Curl_is_absolute_url(Curl_bufref_ptr(&data->state.url), NULL, 0, TRUE))
2071
0
      prepend_sheme = TRUE;
2072
6.39k
    else {
2073
6.39k
      uc = curl_url_set(uh, CURLUPART_URL, Curl_bufref_ptr(&data->state.url),
2074
6.39k
                        (unsigned int)
2075
6.39k
                        CURLU_GUESS_SCHEME |
2076
6.39k
                        CURLU_NON_SUPPORT_SCHEME |
2077
6.39k
                        (data->set.disallow_username_in_url ?
2078
6.39k
                         CURLU_DISALLOW_USER : 0) |
2079
6.39k
                        (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
2080
6.39k
      if(uc) {
2081
130
        failf(data, "URL rejected: %s", curl_url_strerror(uc));
2082
130
        result = Curl_uc_to_curlcode(uc);
2083
130
        goto out;
2084
130
      }
2085
2086
6.26k
      if(CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL)) {
2087
        /* check if we there was a scheme provided */
2088
0
        char *scheme;
2089
0
        uc = curl_url_get(uh, CURLUPART_SCHEME, &scheme,
2090
0
                          CURLU_NO_GUESS_SCHEME);
2091
0
        if(uc == CURLUE_NO_SCHEME)
2092
0
          prepend_sheme = TRUE;
2093
0
        curl_free(scheme);
2094
0
        if(uc && uc != CURLUE_NO_SCHEME) {
2095
0
          result = Curl_uc_to_curlcode(uc);
2096
0
          goto out;
2097
0
        }
2098
0
      }
2099
6.26k
    }
2100
2101
6.26k
    if(prepend_sheme) {
2102
0
      char *url = curl_maprintf("%s://%s",
2103
0
                                CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL),
2104
0
                                Curl_bufref_ptr(&data->state.url));
2105
0
      if(!url) {
2106
0
        result = CURLE_OUT_OF_MEMORY;
2107
0
        goto out;
2108
0
      }
2109
0
      uc = curl_url_set(uh, CURLUPART_URL, url,
2110
0
                        (unsigned int)
2111
0
                        CURLU_GUESS_SCHEME |
2112
0
                        CURLU_NON_SUPPORT_SCHEME |
2113
0
                        (data->set.disallow_username_in_url ?
2114
0
                         CURLU_DISALLOW_USER : 0) |
2115
0
                        (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
2116
0
      curl_free(url);
2117
0
      if(uc) {
2118
0
        failf(data, "URL rejected: %s", curl_url_strerror(uc));
2119
0
        result = Curl_uc_to_curlcode(uc);
2120
0
        goto out;
2121
0
      }
2122
0
    }
2123
6.26k
    {
2124
6.26k
      char *newurl;
2125
      /* after it was parsed, and possibly given a new scheme, get the
2126
         normalized version */
2127
6.26k
      uc = curl_url_get(uh, CURLUPART_URL, &newurl, CURLU_GET_EMPTY);
2128
6.26k
      if(uc) {
2129
24
        result = Curl_uc_to_curlcode(uc);
2130
24
        goto out;
2131
24
      }
2132
6.23k
      if(prepend_sheme)
2133
0
        infof(data, "Applied default protocol '%s'",
2134
6.23k
              CURL_EASY_STR(data, STRING_DEFAULT_PROTOCOL));
2135
6.23k
      Curl_bufref_set(&data->state.url, newurl, 0, curl_free);
2136
6.23k
    }
2137
6.23k
  }
2138
2139
6.23k
#ifdef USE_IPV6
2140
6.23k
  scope_id = data->set.scope_id;
2141
6.23k
#endif
2142
2143
  /* `uh` is now as the connection should use it, probably. */
2144
6.23k
  result = Curl_peer_from_url(uh, data, port_override, scope_id,
2145
6.23k
                              &data->state.origin);
2146
6.23k
  if(result)
2147
11
    goto out;
2148
  /* The origin might get changed when HSTS applies */
2149
6.22k
  result = hsts_upgrade(data, uh, port_override, scope_id);
2150
6.22k
  if(result)
2151
0
    goto out;
2152
2153
  /* When the transfers initial_origin is not set, this is the initial
2154
   * request. Remember this starting point. */
2155
6.22k
  if(!data->state.initial_origin)
2156
6.22k
    Curl_peer_link(&data->state.initial_origin, data->state.origin);
2157
2158
6.22k
  uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, CURLU_URLENCODE);
2159
6.22k
  if(uc) {
2160
3
    result = Curl_uc_to_curlcode(uc);
2161
3
    goto out;
2162
3
  }
2163
6.22k
  uc = curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query,
2164
6.22k
                    CURLU_GET_EMPTY);
2165
6.22k
  if(uc && (uc != CURLUE_NO_QUERY)) {
2166
0
    result = CURLE_OUT_OF_MEMORY;
2167
0
    goto out;
2168
0
  }
2169
2170
6.22k
  uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
2171
6.22k
                    CURLU_URLDECODE);
2172
6.22k
  if(uc && (uc != CURLUE_NO_OPTIONS)) {
2173
0
    result = Curl_uc_to_curlcode(uc);
2174
0
    goto out;
2175
0
  }
2176
2177
6.22k
  result = url_set_data_creds(data, uh);
2178
6.22k
  if(result)
2179
16
    goto out;
2180
2181
6.39k
out:
2182
6.39k
  return result;
2183
6.22k
}
2184
2185
static CURLcode url_match_init(struct Curl_easy *data,
2186
                               struct connectdata *needle,
2187
                               struct url_conn_match *m)
2188
6.18k
{
2189
6.18k
  memset(m, 0, sizeof(*m));
2190
6.18k
  m->data = data;
2191
6.18k
  m->needle = needle;
2192
6.18k
  m->now = *Curl_pgrs_now(data);
2193
6.18k
  m->may_multiplex = xfer_may_multiplex(data, needle);
2194
2195
#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO)
2196
  m->want_nego_http =
2197
    (data->state.authhost.want & CURLAUTH_NEGOTIATE) &&
2198
    (needle->scheme->protocol & PROTO_FAMILY_HTTP) &&
2199
    Curl_auth_allowed_to_host(data);
2200
#ifndef CURL_DISABLE_PROXY
2201
  m->want_proxy_nego_http =
2202
    needle->http_proxy.creds &&
2203
    (data->state.authproxy.want & CURLAUTH_NEGOTIATE) &&
2204
    (needle->scheme->protocol & PROTO_FAMILY_HTTP);
2205
#endif
2206
#endif
2207
6.18k
  m->require_tls = data->set.use_ssl >= CURLUSESSL_CONTROL;
2208
6.18k
  m->may_tls = data->set.use_ssl > CURLUSESSL_NONE;
2209
2210
  /* Get a shallow setup of filter configs for connection cache matching */
2211
6.18k
  return Curl_ssl_filter_config_tmp_init(data, needle->origin,
2212
6.18k
                                         &m->ssl_config,
2213
6.18k
#ifndef CURL_DISABLE_PROXY
2214
6.18k
                                         &m->proxy_ssl_config);
2215
#else
2216
                                         NULL);
2217
#endif
2218
6.18k
}
2219
2220
static void url_match_destroy(struct url_conn_match *m)
2221
6.18k
{
2222
6.18k
  Curl_ssl_config_cleanup(&m->ssl_config);
2223
6.18k
#ifndef CURL_DISABLE_PROXY
2224
6.18k
  Curl_ssl_config_cleanup(&m->proxy_ssl_config);
2225
6.18k
#endif
2226
6.18k
}
2227
2228
/**
2229
 * Find an existing connection for the transfer or create a new one.
2230
 * Returns
2231
 * - CURLE_OK on success with a connection attached to data
2232
 * - CURLE_NO_CONNECTION_AVAILABLE when connection limits apply or when
2233
 *   a suitable connection has not determined its multiplex capability.
2234
 * - a fatal error
2235
 */
2236
static CURLcode url_find_or_create_conn(struct Curl_easy *data,
2237
                                        const struct curltime *pnow)
2238
6.20k
{
2239
6.20k
  struct connectdata *needle = NULL;
2240
6.20k
  struct url_conn_match match;
2241
6.20k
  bool match_initialized = FALSE;
2242
6.20k
  CURLcode result;
2243
2244
  /* create the template connection for transfer data. Use this needle to
2245
   * find an existing connection or, if none exists, convert needle
2246
   * to a full connection and attach it to data. */
2247
6.20k
  result = url_create_needle(data, &needle);
2248
6.20k
  if(result)
2249
22
    goto out;
2250
6.18k
  DEBUGASSERT(needle);
2251
2252
6.18k
  result = url_match_init(data, needle, &match);
2253
6.18k
  if(result)
2254
0
    goto out;
2255
6.18k
  match_initialized = TRUE;
2256
2257
  /***********************************************************************
2258
   * file: is a special case in that it does not need a network connection
2259
   ***********************************************************************/
2260
6.18k
#ifndef CURL_DISABLE_FILE
2261
6.18k
  if(needle->scheme->flags & PROTOPT_NONETWORK) {
2262
0
    bool done;
2263
    /* this is supposed to be the connect function so we better at least check
2264
       that the file is present here! */
2265
0
    DEBUGASSERT(needle->scheme->run->connect_it);
2266
0
    data->info.conn_scheme = needle->scheme->name;
2267
    /* conn_protocol can only provide "old" protocols */
2268
0
    data->info.conn_protocol = needle->scheme->protocol & CURLPROTO_MASK;
2269
0
    result = needle->scheme->run->connect_it(data, &done);
2270
0
    if(result)
2271
0
      goto out;
2272
2273
    /* Setup a "faked" transfer that will do nothing */
2274
0
    result = Curl_cpool_add(data, needle, 0, 0, pnow);
2275
0
    Curl_attach_connection(data, needle, TRUE);
2276
0
    needle = NULL;
2277
0
    if(!result) {
2278
      /* Setup whatever necessary for a resumed transfer */
2279
0
      result = setup_range(data);
2280
0
      if(!result) {
2281
0
        Curl_xfer_setup_nop(data);
2282
0
        result = Curl_init_transfer(data, data->conn);
2283
0
      }
2284
0
    }
2285
2286
0
    if(result) {
2287
0
      DEBUGASSERT(data->conn->scheme->run->done);
2288
      /* we ignore the return code for the protocol-specific DONE */
2289
0
      (void)data->conn->scheme->run->done(data, result, FALSE);
2290
0
    }
2291
0
    goto out;
2292
0
  }
2293
6.18k
#endif
2294
2295
  /*************************************************************
2296
   * Reuse of existing connection is not allowed when
2297
   * - connect_only is set or
2298
   * - reuse_fresh is set and this is not a follow-up request
2299
   *   (like with HTTP followlocation)
2300
   *************************************************************/
2301
6.18k
  if((!data->set.reuse_fresh || data->state.followlocation) &&
2302
6.11k
     !data->set.connect_only) {
2303
    /* Ok, try to find and attach an existing one */
2304
6.11k
    if(url_attach_existing(data, needle, &match, pnow)) {
2305
      /* We attached an existing connection for this transfer. Copy
2306
       * over transfer specific properties over from needle. */
2307
0
      struct connectdata *conn = data->conn;
2308
0
      VERBOSE(bool tls_upgraded =
2309
0
        (!(needle->origin->scheme->flags & PROTOPT_SSL) &&
2310
0
         Curl_conn_is_ssl(conn)));
2311
2312
0
      DEBUGASSERT(conn);
2313
0
      conn->bits.reuse = TRUE;
2314
0
      url_conn_reuse_adjust(data, needle);
2315
2316
0
#ifndef CURL_DISABLE_PROXY
2317
0
      infof(data, "Reusing existing %s: connection%s with %s %s",
2318
0
            conn->origin->scheme->name,
2319
0
            tls_upgraded ? " (upgraded to SSL)" : "",
2320
0
            (conn->socks_proxy.peer || conn->http_proxy.peer) ?
2321
0
            "proxy" : "host",
2322
0
            conn->socks_proxy.peer ? conn->socks_proxy.peer->user_hostname :
2323
0
            conn->http_proxy.peer ? conn->http_proxy.peer->user_hostname :
2324
0
            conn->origin->hostname);
2325
#else
2326
      infof(data, "Reusing existing %s: connection%s with host %s",
2327
            conn->origin->scheme->name,
2328
            tls_upgraded ? " (upgraded to SSL)" : "",
2329
            conn->origin->hostname);
2330
#endif
2331
0
    }
2332
6.11k
  }
2333
2334
6.18k
  if(!data->conn) {
2335
    /* We have not attached an existing connection. `needle` may become
2336
     * the connection to use, if
2337
     * - we are not waiting on an existing connection result
2338
     * - the total/host limits on active connections allow it
2339
     */
2340
6.18k
    if(match.wait_pipe) {
2341
      /* There is a connection that *might* become usable for multiplexing
2342
         "soon", and we wait for that */
2343
0
      infof(data, "Waiting on connection to negotiate possible multiplexing.");
2344
0
      result = CURLE_NO_CONNECTION_AVAILABLE;
2345
0
      goto out;
2346
0
    }
2347
2348
    /* Add needle to conn pool, observing the limits.
2349
     * Initializes connection_id.
2350
     * May fail due to limits with CURLE_NO_CONNECTION_AVAILABLE. */
2351
6.18k
    result = Curl_cpool_add(data, needle,
2352
6.18k
                            data->multi->max_total_connections,
2353
6.18k
                            data->multi->max_host_connections,
2354
6.18k
                            pnow);
2355
6.18k
    if(result)
2356
9
      goto out;
2357
2358
    /* All fine, attach it and forget needle */
2359
6.17k
    Curl_attach_connection(data, needle, TRUE);
2360
6.17k
    needle = NULL;
2361
2362
    /* Clone the SSL filter configs into the new connection. */
2363
6.17k
    result = Curl_ssl_conn_config_clone(&match.ssl_config,
2364
6.17k
#ifndef CURL_DISABLE_PROXY
2365
6.17k
                                        &match.proxy_ssl_config,
2366
#else
2367
                                        NULL,
2368
#endif
2369
6.17k
                                        data->conn);
2370
6.17k
    if(result) {
2371
0
      DEBUGF(infof(data, "Error: clone connection SSL config"));
2372
0
      goto out;
2373
0
    }
2374
6.17k
  }
2375
2376
  /* COMMON setup code for reused and new connections from here on. */
2377
2378
  /* Setup and init stuff before DO starts, in preparing for the transfer. */
2379
6.17k
  result = Curl_init_transfer(data, data->conn);
2380
6.17k
  if(result)
2381
0
    goto out;
2382
2383
  /* Setup whatever necessary for a resumed transfer */
2384
6.17k
  result = setup_range(data);
2385
6.17k
  if(result)
2386
0
    goto out;
2387
2388
  /* persist the scheme and handler the transfer is using */
2389
6.17k
  data->info.conn_scheme = data->conn->scheme->name;
2390
  /* conn_protocol can only provide "old" protocols */
2391
6.17k
  data->info.conn_protocol = data->conn->scheme->protocol & CURLPROTO_MASK;
2392
6.17k
  data->info.used_proxy =
2393
#ifdef CURL_DISABLE_PROXY
2394
    0
2395
#else
2396
6.17k
    (data->conn->socks_proxy.peer || data->conn->http_proxy.peer)
2397
6.17k
#endif
2398
6.17k
    ;
2399
2400
  /* Lastly, inform connection filters that a new transfer is attached */
2401
6.17k
  result = Curl_conn_ev_data_setup(data);
2402
2403
6.20k
out:
2404
6.20k
  if(match_initialized)
2405
6.18k
    url_match_destroy(&match);
2406
6.20k
  if(needle)
2407
9
    Curl_conn_free(data, needle);
2408
6.20k
  DEBUGASSERT(result || data->conn);
2409
6.20k
  return result;
2410
6.20k
}
2411
2412
CURLcode Curl_connect(struct Curl_easy *data, bool *pconnected)
2413
6.39k
{
2414
6.39k
  CURLcode result;
2415
6.39k
  struct connectdata *conn = NULL;
2416
6.39k
  const struct curltime *pnow = NULL;
2417
6.39k
  *pconnected = FALSE;
2418
2419
  /* Set the request to virgin state based on transfer settings */
2420
6.39k
  Curl_req_hard_reset(&data->req, data);
2421
  /* Determine the origin of the transfer and what credentials to use */
2422
6.39k
  result = url_set_data_origin_and_creds(data);
2423
6.39k
  if(result)
2424
191
    goto out;
2425
6.20k
  if(!data->state.origin) { /* just make really sure */
2426
0
    DEBUGASSERT(0);
2427
0
    result = CURLE_FAILED_INIT;
2428
0
    goto out;
2429
0
  }
2430
2431
  /* Get or create a connection for the transfer. */
2432
6.20k
  pnow = Curl_pgrs_now(data);
2433
6.20k
  Curl_pgrsTimeWas(data, TIMER_POSTQUEUE, *pnow);
2434
6.20k
  result = url_find_or_create_conn(data, pnow);
2435
6.20k
  conn = data->conn;
2436
6.20k
  if(result)
2437
31
    goto out;
2438
6.17k
  if(!data->conn) { /* just make really sure */
2439
0
    DEBUGASSERT(0);
2440
0
    result = CURLE_FAILED_INIT;
2441
0
    goto out;
2442
0
  }
2443
2444
6.17k
  if(conn->bits.reuse) {
2445
0
    if(conn->attached_xfers > 1)
2446
      /* multiplexed */
2447
0
      *pconnected = TRUE;
2448
0
  }
2449
6.17k
  else if(conn->scheme->flags & PROTOPT_NONETWORK) {
2450
0
    Curl_pgrsTime(data, TIMER_NAMELOOKUP);
2451
0
    *pconnected = TRUE;
2452
0
  }
2453
6.17k
  else {
2454
6.17k
    result = Curl_conn_setup(data, conn, &conn->chain,
2455
6.17k
                             CURL_CF_SSL_DEFAULT);
2456
6.17k
    if(!result)
2457
6.16k
      result = Curl_headers_init(data);
2458
6.17k
    CURL_TRC_M(data, "Curl_conn_setup() -> %d", (int)result);
2459
6.17k
  }
2460
2461
6.39k
out:
2462
6.39k
  if(result == CURLE_NO_CONNECTION_AVAILABLE)
2463
6.39k
    DEBUGASSERT(!conn);
2464
2465
6.39k
  if(result && conn) {
2466
    /* Detach on error and close the connection if
2467
     * - it was not reused (meaning, ok before we picked it)
2468
     * - there are no other transfers attached to it */
2469
8
    Curl_detach_connection(data);
2470
8
    if(!conn->bits.reuse && !CONN_INUSE(conn))
2471
8
      Curl_conn_close(data, conn, TRUE);
2472
8
  }
2473
2474
6.39k
  return result;
2475
6.39k
}
2476
2477
/*
2478
 * Curl_init_transfer() is called each time before the transfer starts - to
2479
 * prepare for a transfer, sometimes multiple times on the same Curl_easy.
2480
 * Make sure nothing in here depends on stuff that is setup dynamically for
2481
 * the transfer.
2482
 *
2483
 * Allow this function to get called with 'conn' set to NULL.
2484
 */
2485
2486
CURLcode Curl_init_transfer(struct Curl_easy *data, struct connectdata *conn)
2487
6.17k
{
2488
6.17k
  CURLcode result;
2489
2490
6.17k
  if(conn) {
2491
6.17k
    conn->bits.do_more = FALSE; /* by default there is no curl_do_more() to
2492
                                   use */
2493
    /* if the protocol used does not support wildcards, switch it off */
2494
6.17k
    if(data->state.wildcardmatch &&
2495
0
       !(conn->scheme->flags & PROTOPT_WILDCARD))
2496
0
      data->state.wildcardmatch = FALSE;
2497
6.17k
  }
2498
2499
6.17k
  data->state.done = FALSE; /* *_done() is not called yet */
2500
2501
6.17k
  data->req.no_body = data->set.opt_no_body;
2502
6.17k
  if(data->req.no_body)
2503
    /* in HTTP lingo, no body means using the HEAD request... */
2504
39
    data->state.httpreq = HTTPREQ_HEAD;
2505
2506
6.17k
  result = Curl_req_start(&data->req, data);
2507
6.17k
  if(!result) {
2508
6.17k
    Curl_pgrsReset(data);
2509
6.17k
  }
2510
6.17k
  return result;
2511
6.17k
}
2512
2513
#if defined(USE_HTTP2) || defined(USE_HTTP3)
2514
2515
void Curl_data_priority_clear_state(struct Curl_easy *data)
2516
6.42k
{
2517
6.42k
  data->state.weight = 0;
2518
6.42k
}
2519
2520
#endif /* USE_HTTP2 || USE_HTTP3 */
2521
2522
CURLcode Curl_conn_meta_set(struct connectdata *conn, const char *key,
2523
                            void *meta_data, Curl_meta_dtor *meta_dtor)
2524
6.19k
{
2525
6.19k
  if(!Curl_hash_add2(&conn->meta_hash, key, strlen(key) + 1,
2526
6.19k
                     meta_data, meta_dtor)) {
2527
4
    meta_dtor(key, strlen(key) + 1, meta_data);
2528
4
    return CURLE_OUT_OF_MEMORY;
2529
4
  }
2530
6.19k
  return CURLE_OK;
2531
6.19k
}
2532
2533
void Curl_conn_meta_remove(struct connectdata *conn, const char *key)
2534
6.17k
{
2535
6.17k
  Curl_hash_delete(&conn->meta_hash, key, strlen(key) + 1);
2536
6.17k
}
2537
2538
void *Curl_conn_meta_get(struct connectdata *conn, const char *key)
2539
23.8M
{
2540
23.8M
  return Curl_hash_pick(&conn->meta_hash, key, strlen(key) + 1);
2541
23.8M
}
2542
2543
struct Curl_easy *Curl_get_admin(struct Curl_easy *data)
2544
18.4k
{
2545
18.4k
  struct Curl_easy *admin;
2546
2547
18.4k
  if(!data->mid) /* already an admin handle */
2548
1.32k
    admin = data;
2549
17.1k
  else if(data->multi)
2550
17.1k
    admin = data->multi->admin;
2551
0
  else if(data->multi_easy)
2552
0
    admin = data->multi_easy->admin;
2553
0
  else {
2554
0
    DEBUGASSERT(0); /* we do not want this. does it happen? */
2555
0
    admin = data;
2556
0
  }
2557
18.4k
  if(admin != data) {
2558
17.1k
    admin->set.conn_max_idle_ms = data->set.conn_max_idle_ms;
2559
17.1k
    admin->set.conn_max_age_ms = data->set.conn_max_age_ms;
2560
17.1k
    admin->set.upkeep_interval_ms = data->set.upkeep_interval_ms;
2561
17.1k
    admin->set.timeout = data->set.timeout;
2562
17.1k
    admin->set.server_response_timeout = data->set.server_response_timeout;
2563
17.1k
    admin->set.no_signal = data->set.no_signal;
2564
17.1k
  }
2565
18.4k
  return admin;
2566
18.4k
}
2567
2568
CURLcode Curl_1st_fatal(CURLcode r1, CURLcode r2)
2569
6.16k
{
2570
6.16k
  if(r1 && (r1 != CURLE_AGAIN))
2571
2.50k
    return r1;
2572
3.66k
  if(r2 && (r2 != CURLE_AGAIN))
2573
0
    return r2;
2574
3.66k
  return r1;
2575
3.66k
}