Coverage Report

Created: 2026-08-15 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/urlapi.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#include "urldata.h"
27
#include "urlapi-int.h"
28
#include "strcase.h"
29
#include "url.h"
30
#include "escape.h"
31
#include "curlx/inet_pton.h"
32
#include "curlx/inet_ntop.h"
33
#include "curlx/strdup.h"
34
#include "idn.h"
35
#include "curlx/strparse.h"
36
#include "curl_memrchr.h"
37
38
#ifdef _WIN32
39
/* MS-DOS/Windows style drive prefix, eg c: in c:foo */
40
#define STARTS_WITH_DRIVE_PREFIX(str)        \
41
  ((('a' <= (str)[0] && (str)[0] <= 'z') ||  \
42
    ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
43
   ((str)[1] == ':'))
44
#endif
45
46
/* MS-DOS/Windows style drive prefix, optionally with
47
 * a '|' instead of ':', followed by a slash or NUL */
48
#define STARTS_WITH_URL_DRIVE_PREFIX(str)                  \
49
5.38k
  ((('a' <= (str)[0] && (str)[0] <= 'z') ||                \
50
5.38k
    ('A' <= (str)[0] && (str)[0] <= 'Z')) &&               \
51
5.38k
   ((str)[1] == ':' || (str)[1] == '|') &&                 \
52
5.38k
   ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
53
54
/* scheme is not URL encoded, the longest libcurl supported ones are... */
55
1.89M
#define MAX_SCHEME_LEN 40
56
18.5k
#define MAX_ZONEID_LEN 16
57
58
/* characters not allowed in hostnames */
59
137k
#define HOSTNAME_INVALID_CHARS " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%|"
60
61
/*
62
 * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make
63
 * sure we have _some_ value for AF_INET6 without polluting our fake value
64
 * everywhere.
65
 */
66
#if !defined(USE_IPV6) && !defined(AF_INET6)
67
#define AF_INET6 (AF_INET + 1)
68
#endif
69
70
0
#define DEFAULT_SCHEME "https"
71
72
static void free_urlhandle(struct Curl_URL *u)
73
573k
{
74
573k
  curlx_free(u->scheme);
75
573k
  curlx_free(u->user);
76
573k
  curlx_strzero(u->password);
77
573k
  curlx_free(u->password);
78
573k
  curlx_free(u->options);
79
573k
  curlx_free(u->host);
80
573k
  curlx_free(u->zoneid);
81
573k
  curlx_free(u->path);
82
573k
  curlx_free(u->query);
83
573k
  curlx_free(u->fragment);
84
573k
}
85
86
/*
87
 * Find the separator at the end of the hostname, or the '?' in cases like
88
 * http://www.example.com?id=2380
89
 */
90
static const char *find_host_sep(const char *url)
91
302
{
92
  /* Find the start of the hostname */
93
302
  const char *sep = strstr(url, "//");
94
302
  if(!sep)
95
284
    sep = url;
96
18
  else
97
18
    sep += 2;
98
99
  /* Find first / or ? */
100
3.33k
  while(*sep && *sep != '/' && *sep != '?')
101
3.03k
    sep++;
102
103
302
  return sep;
104
302
}
105
106
/* convert CURLcode to CURLUcode */
107
#define cc2cu(x) \
108
0
  ((x) == CURLE_TOO_LARGE ? CURLUE_TOO_LARGE : CURLUE_OUT_OF_MEMORY)
109
110
/* urlencode_str() writes data into an output dynbuf and URL-encodes the
111
 * spaces in the source URL accordingly.
112
 *
113
 * This function re-encodes the string, meaning that it leaves already encoded
114
 * bytes as-is and works by encoding only what *has* to be encoded - unless it
115
 * has to uppercase the hex to normalize.
116
 *
117
 * Illegal percent-encoding sequences are left as-is.
118
 *
119
 * URL encoding should be skipped for hostnames, otherwise IDN resolution
120
 * will fail.
121
 *
122
 * 'query' tells if it is a query part or not, or if it is allowed to
123
 * "transition" into a query part with a question mark.
124
 *
125
 * @unittest 1675
126
 */
127
UNITTEST CURLUcode urlencode_str(struct dynbuf *o, const char *url,
128
                                 size_t len, bool relative,
129
                                 unsigned int query);
130
UNITTEST CURLUcode urlencode_str(struct dynbuf *o, const char *url,
131
                                 size_t len, bool relative,
132
                                 unsigned int query)
133
281k
{
134
  /* we must add this with whitespace-replacing */
135
281k
  const unsigned char *iptr;
136
281k
  const unsigned char *host_sep = (const unsigned char *)url;
137
281k
  CURLcode result = CURLE_OK;
138
139
281k
  DEBUGASSERT((query >= QUERY_NO) && (query <= QUERY_YES));
140
141
281k
  if(!relative) {
142
302
    size_t n;
143
302
    host_sep = (const unsigned char *)find_host_sep(url);
144
145
    /* output the first piece as-is */
146
302
    n = (const char *)host_sep - url;
147
302
    result = curlx_dyn_addn(o, url, n);
148
302
    len -= n;
149
302
  }
150
151
287M
  for(iptr = host_sep; len && !result; iptr++, len--) {
152
287M
    if(*iptr == ' ') {
153
24.9k
      if(query != QUERY_YES)
154
14.0k
        result = curlx_dyn_addn(o, "%20", 3);
155
10.8k
      else
156
10.8k
        result = curlx_dyn_addn(o, "+", 1);
157
24.9k
    }
158
287M
    else if((*iptr < ' ') || (*iptr >= 0x7f)) {
159
140M
      unsigned char out[3] = { '%' };
160
140M
      Curl_hexbyte(&out[1], *iptr);
161
140M
      result = curlx_dyn_addn(o, out, 3);
162
140M
    }
163
147M
    else if(*iptr == '%' && (len >= 3) &&
164
66.1M
            ISXDIGIT(iptr[1]) && ISXDIGIT(iptr[2]) &&
165
6.18M
            (ISLOWER(iptr[1]) || ISLOWER(iptr[2]))) {
166
      /* uppercase it */
167
104k
      unsigned char hex = (unsigned char)((curlx_hexval(iptr[1]) << 4) |
168
104k
                                          curlx_hexval(iptr[2]));
169
104k
      unsigned char out[3] = { '%' };
170
104k
      Curl_hexbyte(&out[1], hex);
171
104k
      result = curlx_dyn_addn(o, out, 3);
172
104k
      iptr += 2;
173
104k
      len -= 2;
174
104k
    }
175
147M
    else {
176
147M
      result = curlx_dyn_addn(o, iptr, 1);
177
147M
      if(*iptr == '?' && (query == QUERY_NOT_YET))
178
4.27k
        query = QUERY_YES;
179
147M
    }
180
287M
  }
181
182
281k
  if(result)
183
0
    return cc2cu(result);
184
281k
  return CURLUE_OK;
185
281k
}
186
187
/*
188
 * Returns the length of the scheme if the given URL is absolute (as opposed
189
 * to relative). Stores the scheme in the buffer if TRUE and 'buf' is
190
 * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set.
191
 *
192
 * If 'guess_scheme' is TRUE, it means the URL might be provided without
193
 * scheme.
194
 */
195
size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen,
196
                            bool guess_scheme)
197
638k
{
198
638k
  size_t i = 0;
199
638k
  DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
200
638k
  (void)buflen; /* only used in debug-builds */
201
638k
  if(buf)
202
296k
    buf[0] = 0; /* always leave a defined value in buf */
203
#ifdef _WIN32
204
  if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url))
205
    return 0;
206
#endif
207
638k
  if(ISALPHA(url[0]))
208
1.89M
    for(i = 1; i < MAX_SCHEME_LEN; ++i) {
209
1.89M
      char s = url[i];
210
1.89M
      if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.'))) {
211
        /* RFC 3986 3.1 explains:
212
           scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
213
         */
214
1.43M
      }
215
466k
      else {
216
466k
        break;
217
466k
      }
218
1.89M
    }
219
638k
  if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) {
220
    /* If this does not guess scheme, the scheme always ends with the colon so
221
       that this also detects data: URLs etc. In guessing mode, data: could
222
       be the hostname "data" with a specified port number. */
223
224
    /* the length of the scheme is the name part only */
225
355k
    size_t len = i;
226
355k
    if(buf) {
227
185k
      Curl_strntolower(buf, url, i);
228
185k
      buf[i] = 0;
229
185k
    }
230
355k
    return len;
231
355k
  }
232
282k
  return 0;
233
638k
}
234
235
/* scan for byte values <= 31, 127 and sometimes space */
236
CURLUcode Curl_junkscan(const char *url, size_t *urllen, bool allowspace)
237
297k
{
238
297k
  size_t n = strlen(url);
239
297k
  size_t i;
240
297k
  unsigned char control;
241
297k
  const unsigned char *p = (const unsigned char *)url;
242
297k
  if(n > CURL_MAX_INPUT_LENGTH)
243
0
    return CURLUE_MALFORMED_INPUT;
244
245
297k
  control = allowspace ? 0x1f : 0x20;
246
519M
  for(i = 0; i < n; i++) {
247
519M
    if(p[i] <= control || p[i] == 127)
248
533
      return CURLUE_MALFORMED_INPUT;
249
519M
  }
250
296k
  *urllen = n;
251
296k
  return CURLUE_OK;
252
297k
}
253
254
/*
255
 * parse_hostname_login()
256
 *
257
 * Parse the login details (username, password and options) from the URL and
258
 * strip them out of the hostname
259
 *
260
 * @unittest 1675
261
 */
262
UNITTEST CURLUcode parse_hostname_login(struct Curl_URL *u,
263
                                        const char *login,
264
                                        size_t len,
265
                                        unsigned int flags,
266
                                        size_t *hostname_offset);
267
UNITTEST CURLUcode parse_hostname_login(struct Curl_URL *u,
268
                                        const char *login,
269
                                        size_t len,
270
                                        unsigned int flags,
271
                                        size_t *hostname_offset)
272
292k
{
273
292k
  CURLUcode ures = CURLUE_OK;
274
292k
  CURLcode result;
275
292k
  char *userp = NULL;
276
292k
  char *passwdp = NULL;
277
292k
  char *optionsp = NULL;
278
292k
  const struct Curl_scheme *h = NULL;
279
280
  /* At this point, we assume all the other special cases have been taken
281
   * care of, so the host is at most
282
   *
283
   *   [user[:password][;options]]@]hostname
284
   *
285
   * We need somewhere to put the embedded details, so do that first.
286
   */
287
292k
  const char *ptr;
288
289
292k
  DEBUGASSERT(login);
290
291
292k
  *hostname_offset = 0;
292
292k
  ptr = memchr(login, '@', len);
293
292k
  if(!ptr)
294
244k
    goto out;
295
296
  /* We will now try to extract the
297
   * possible login information in a string like:
298
   * ftp://user:password@ftp.site.example:8021/README */
299
48.0k
  ptr++;
300
301
  /* if this is a known scheme, get some details */
302
48.0k
  if(u->scheme)
303
31.3k
    h = Curl_get_scheme(u->scheme);
304
305
  /* We could use the login information in the URL so extract it. Only parse
306
     options if the handler says we should. Note that 'h' might be NULL! */
307
48.0k
  result = Curl_parse_login_details(login, ptr - login - 1,
308
48.0k
                                    &userp, &passwdp,
309
48.0k
                                    (h && (h->flags & PROTOPT_URLOPTIONS)) ?
310
48.0k
                                    &optionsp : NULL);
311
48.0k
  if(result) {
312
    /* the only possible error from Curl_parse_login_details is out of
313
       memory: */
314
0
    ures = CURLUE_OUT_OF_MEMORY;
315
0
    goto out;
316
0
  }
317
318
48.0k
  if(userp) {
319
48.0k
    if(flags & CURLU_DISALLOW_USER) {
320
      /* Option DISALLOW_USER is set and URL contains username. */
321
14
      ures = CURLUE_USER_NOT_ALLOWED;
322
14
      goto out;
323
14
    }
324
48.0k
    curlx_free(u->user);
325
48.0k
    u->user = userp;
326
48.0k
  }
327
328
48.0k
  if(passwdp) {
329
11.0k
    curlx_strzero(u->password);
330
11.0k
    curlx_free(u->password);
331
11.0k
    u->password = passwdp;
332
11.0k
  }
333
334
48.0k
  if(optionsp) {
335
206
    curlx_free(u->options);
336
206
    u->options = optionsp;
337
206
  }
338
339
  /* the hostname starts at this offset */
340
48.0k
  *hostname_offset = ptr - login;
341
48.0k
  return CURLUE_OK;
342
343
244k
out:
344
345
244k
  curlx_free(userp);
346
244k
  curlx_strzero(passwdp);
347
244k
  curlx_free(passwdp);
348
244k
  curlx_free(optionsp);
349
244k
  curlx_safefree(u->user);
350
244k
  curlx_strzero(u->password);
351
244k
  curlx_safefree(u->password);
352
244k
  curlx_safefree(u->options);
353
354
244k
  return ures;
355
48.0k
}
356
357
/* @unittest 1653 */
358
UNITTEST CURLUcode parse_port(struct Curl_URL *u, struct dynbuf *host,
359
                              bool has_scheme);
360
UNITTEST CURLUcode parse_port(struct Curl_URL *u, struct dynbuf *host,
361
                              bool has_scheme)
362
292k
{
363
292k
  const char *portptr;
364
292k
  const char *hostname = curlx_dyn_ptr(host);
365
  /*
366
   * Find the end of an IPv6 address on the ']' ending bracket.
367
   */
368
292k
  u->portnum = 0;
369
292k
  u->port_present = FALSE;
370
292k
  if(hostname[0] == '[') {
371
9.24k
    portptr = strchr(hostname, ']');
372
9.24k
    if(!portptr)
373
64
      return CURLUE_BAD_IPV6;
374
9.18k
    portptr++;
375
    /* this is a RFC2732-style specified IP-address */
376
9.18k
    if(*portptr) {
377
451
      if(*portptr != ':')
378
101
        return CURLUE_BAD_PORT_NUMBER;
379
451
    }
380
8.73k
    else
381
8.73k
      portptr = NULL;
382
9.18k
  }
383
283k
  else
384
283k
    portptr = strchr(hostname, ':');
385
386
292k
  if(portptr) {
387
13.7k
    curl_off_t port;
388
13.7k
    size_t keep = portptr - hostname;
389
13.7k
    int rc;
390
391
    /* Browser behavior adaptation. If there is a colon with no digits after,
392
       cut off the name there which makes us ignore the colon and use the
393
       default port. Firefox, Chrome and Safari all do that.
394
395
       Do not do it if the URL has no scheme, to make something that looks like
396
       a scheme not work! */
397
13.7k
    curlx_dyn_setlen(host, keep);
398
13.7k
    portptr++;
399
13.7k
    if(!*portptr)
400
2.61k
      return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
401
11.0k
    if(*portptr == '\\')
402
44
      return CURLUE_BACKSLASH;
403
11.0k
    rc = curlx_str_number(&portptr, &port, 0xffff);
404
11.0k
    if(rc)
405
451
      return CURLUE_BAD_PORT_NUMBER;
406
10.6k
    else if(*portptr == '\\')
407
42
      return CURLUE_BACKSLASH;
408
10.5k
    else if(*portptr)
409
138
      return CURLUE_BAD_PORT_NUMBER;
410
411
10.4k
    u->portnum = (uint16_t)port;
412
10.4k
    u->port_present = TRUE;
413
10.4k
  }
414
415
288k
  return CURLUE_OK;
416
292k
}
417
418
/* This function assumes 'hostname' now starts with [. It trims 'hostname' in
419
 * place and it sets u->zoneid if present.
420
 *
421
 * @unittest 1675
422
 */
423
UNITTEST CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname,
424
                              size_t hlen);
425
UNITTEST CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname,
426
                              size_t hlen) /* length of hostname */
427
9.57k
{
428
9.57k
  size_t len;
429
9.57k
  DEBUGASSERT(*hostname == '[');
430
9.57k
  if(hlen < 4) /* '[::]' is the shortest possible valid string */
431
64
    return CURLUE_BAD_IPV6;
432
9.51k
  hostname++;
433
9.51k
  hlen -= 2;
434
435
  /* only valid IPv6 letters are ok */
436
9.51k
  len = strspn(hostname, "0123456789abcdefABCDEF:.");
437
438
9.51k
  if(hlen != len) {
439
3.76k
    hlen = len;
440
3.76k
    if(hostname[len] == '%') {
441
      /* this could now be '%[zone id]' */
442
3.60k
      char zoneid[MAX_ZONEID_LEN];
443
3.60k
      int i = 0;
444
3.60k
      char *h = &hostname[len + 1];
445
      /* pass '25' if present and is a URL encoded percent sign */
446
3.60k
      if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
447
92
        h += 2;
448
21.9k
      while(*h && (*h != ']') && (i < (MAX_ZONEID_LEN - 1)))
449
18.3k
        zoneid[i++] = *h++;
450
3.60k
      if(!i || (']' != *h))
451
490
        return CURLUE_BAD_IPV6;
452
3.11k
      zoneid[i] = 0;
453
3.11k
      u->zoneid = curlx_strdup(zoneid);
454
3.11k
      if(!u->zoneid)
455
0
        return CURLUE_OUT_OF_MEMORY;
456
3.11k
      hostname[len] = ']'; /* insert end bracket */
457
3.11k
      hostname[len + 1] = 0; /* terminate the hostname */
458
3.11k
    }
459
157
    else
460
157
      return CURLUE_BAD_IPV6;
461
    /* hostname is fine */
462
3.76k
  }
463
464
  /* Normalize the IPv6 address */
465
8.86k
  {
466
8.86k
    char dest[16]; /* fits a binary IPv6 address */
467
8.86k
    hostname[hlen] = 0; /* end the address there */
468
8.86k
    if(curlx_inet_pton(AF_INET6, hostname, dest) != 1)
469
953
      return CURLUE_BAD_IPV6;
470
7.91k
    if(curlx_inet_ntop(AF_INET6, dest, hostname, hlen + 1)) {
471
6.43k
      hlen = strlen(hostname); /* might be shorter now */
472
6.43k
      hostname[hlen + 1] = 0;
473
6.43k
    }
474
7.91k
    hostname[hlen] = ']'; /* restore ending bracket */
475
7.91k
  }
476
0
  return CURLUE_OK;
477
8.86k
}
478
479
static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
480
                                size_t hlen) /* length of hostname */
481
137k
{
482
137k
  size_t len;
483
137k
  DEBUGASSERT(hostname);
484
485
137k
  if(!hlen)
486
0
    return CURLUE_NO_HOST;
487
137k
  else if(hostname[0] == '[')
488
0
    return ipv6_parse(u, hostname, hlen);
489
137k
  else {
490
    /* letters from the second string are not ok */
491
137k
    len = strcspn(hostname, HOSTNAME_INVALID_CHARS);
492
137k
    if(hlen != len)
493
      /* hostname with bad content */
494
1.79k
      return CURLUE_BAD_HOSTNAME;
495
135k
    else if((hlen >= 2) &&
496
76.3k
            (hostname[hlen - 1] == '.') && (hostname[hlen - 2] == '.'))
497
      /* more than one trailing dot is not allowed */
498
144
      return CURLUE_BAD_HOSTNAME;
499
135k
    else if((hlen == 1) && (hostname[0] == '.'))
500
      /* a single dot alone is not allowed */
501
112
      return CURLUE_BAD_HOSTNAME;
502
137k
  }
503
135k
  return CURLUE_OK;
504
137k
}
505
506
/*
507
 * Handle partial IPv4 numerical addresses and different bases, like
508
 * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc.
509
 *
510
 * If the given input string is syntactically wrong IPv4 or any part for
511
 * example is too big, this function returns HOST_NAME.
512
 *
513
 * Output the "normalized" version of that input string in plain quad decimal
514
 * integers.
515
 *
516
 * A single dot following the numerical address is accepted and "swallowed" as
517
 * if it was never there.
518
 *
519
 * Returns the host type.
520
 *
521
 * @unittest 1675
522
 */
523
UNITTEST int ipv4_normalize(struct dynbuf *host);
524
UNITTEST int ipv4_normalize(struct dynbuf *host)
525
290k
{
526
290k
  bool done = FALSE;
527
290k
  int n = 0;
528
290k
  const char *c = curlx_dyn_ptr(host);
529
290k
  unsigned int parts[4] = { 0, 0, 0, 0 };
530
290k
  CURLcode result = CURLE_OK;
531
532
290k
  if(*c == '[')
533
9.57k
    return HOST_IPV6;
534
535
636k
  while(!done) {
536
487k
    int rc;
537
487k
    curl_off_t l;
538
487k
    if(*c == '0') {
539
204k
      if(Curl_raw_tolower(c[1]) == 'x') {
540
1.61k
        c += 2; /* skip the prefix */
541
1.61k
        rc = curlx_str_hex(&c, &l, UINT_MAX);
542
1.61k
        if(rc)
543
590
          return HOST_NAME;
544
1.61k
      }
545
203k
      else
546
203k
        rc = curlx_str_octal(&c, &l, UINT_MAX);
547
204k
    }
548
282k
    else
549
282k
      rc = curlx_str_number(&c, &l, UINT_MAX);
550
551
486k
    if(rc) {
552
115k
      if(!n || (rc != STRE_NO_NUM) || *c)
553
114k
        return HOST_NAME;
554
1.77k
      n--;
555
1.77k
    }
556
370k
    else
557
370k
      parts[n] = (unsigned int)l;
558
559
372k
    switch(*c) {
560
207k
    case '.':
561
207k
      if(n == 3) {
562
777
        if(c[1])
563
          /* something follows this dot */
564
435
          return HOST_NAME;
565
342
        done = TRUE;
566
342
      }
567
206k
      else {
568
206k
        n++;
569
206k
        c++;
570
206k
      }
571
207k
      break;
572
573
207k
    case '\0':
574
149k
      done = TRUE;
575
149k
      break;
576
577
15.6k
    default:
578
15.6k
      return HOST_NAME;
579
372k
    }
580
372k
  }
581
582
149k
  switch(n) {
583
79.8k
  case 0: /* a -- 32 bits */
584
79.8k
    curlx_dyn_reset(host);
585
586
79.8k
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
587
79.8k
                            (parts[0] >> 24),
588
79.8k
                            ((parts[0] >> 16) & 0xff),
589
79.8k
                            ((parts[0] >> 8) & 0xff),
590
79.8k
                            (parts[0] & 0xff));
591
79.8k
    break;
592
2.99k
  case 1: /* a.b -- 8.24 bits */
593
2.99k
    if((parts[0] > 0xff) || (parts[1] > 0xffffff))
594
1.46k
      return HOST_NAME;
595
1.52k
    curlx_dyn_reset(host);
596
1.52k
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
597
1.52k
                            parts[0],
598
1.52k
                            ((parts[1] >> 16) & 0xff),
599
1.52k
                            ((parts[1] >> 8) & 0xff),
600
1.52k
                            (parts[1] & 0xff));
601
1.52k
    break;
602
2.92k
  case 2: /* a.b.c -- 8.8.16 bits */
603
2.92k
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
604
2.16k
      return HOST_NAME;
605
755
    curlx_dyn_reset(host);
606
755
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
607
755
                            parts[0],
608
755
                            parts[1],
609
755
                            ((parts[2] >> 8) & 0xff),
610
755
                            (parts[2] & 0xff));
611
755
    break;
612
63.9k
  case 3: /* a.b.c.d -- 8.8.8.8 bits */
613
63.9k
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
614
62.0k
       (parts[3] > 0xff))
615
2.71k
      return HOST_NAME;
616
61.2k
    curlx_dyn_reset(host);
617
61.2k
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
618
61.2k
                            parts[0],
619
61.2k
                            parts[1],
620
61.2k
                            parts[2],
621
61.2k
                            parts[3]);
622
61.2k
    break;
623
149k
  }
624
143k
  if(result)
625
0
    return HOST_ERROR;
626
143k
  return HOST_IPV4;
627
143k
}
628
629
/* if necessary, replace the host content with a URL decoded version */
630
static CURLUcode urldecode_host(struct dynbuf *host)
631
290k
{
632
290k
  const char *per;
633
290k
  const char *hostname = curlx_dyn_ptr(host);
634
290k
  per = strchr(hostname, '%');
635
290k
  if(!per)
636
    /* nothing to decode */
637
284k
    return CURLUE_OK;
638
5.48k
  else {
639
    /* encoded */
640
5.48k
    size_t dlen;
641
5.48k
    char *decoded;
642
5.48k
    CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
643
5.48k
                                     REJECT_CTRL);
644
5.48k
    if(result)
645
109
      return CURLUE_BAD_HOSTNAME;
646
5.37k
    curlx_dyn_reset(host);
647
5.37k
    result = curlx_dyn_addn(host, decoded, dlen);
648
5.37k
    curlx_free(decoded);
649
5.37k
    if(result)
650
0
      return cc2cu(result);
651
5.37k
  }
652
653
5.37k
  return CURLUE_OK;
654
290k
}
655
656
static CURLUcode parse_authority(struct Curl_URL *u,
657
                                 const char *auth, size_t authlen,
658
                                 unsigned int flags,
659
                                 struct dynbuf *host,
660
                                 bool has_scheme)
661
292k
{
662
292k
  size_t offset;
663
292k
  CURLUcode uc;
664
292k
  CURLcode result;
665
666
  /*
667
   * Parse the login details and strip them out of the hostname.
668
   */
669
292k
  uc = parse_hostname_login(u, auth, authlen, flags, &offset);
670
292k
  if(uc)
671
14
    return uc;
672
673
292k
  result = curlx_dyn_addn(host, auth + offset, authlen - offset);
674
292k
  if(result) {
675
0
    uc = cc2cu(result);
676
0
    return uc;
677
0
  }
678
679
292k
  uc = parse_port(u, host, has_scheme);
680
681
292k
  if(!curlx_dyn_len(host))
682
    /* this makes no-host errors override port number problems */
683
1.52k
    uc = CURLUE_NO_HOST;
684
292k
  if(!uc)
685
290k
    uc = urldecode_host(host);
686
292k
  if(uc)
687
2.24k
    return uc;
688
689
290k
  switch(ipv4_normalize(host)) {
690
143k
  case HOST_IPV4:
691
143k
    break;
692
9.57k
  case HOST_IPV6:
693
9.57k
    uc = ipv6_parse(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
694
9.57k
    break;
695
137k
  case HOST_NAME:
696
137k
    uc = hostname_check(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
697
137k
    break;
698
0
  case HOST_ERROR:
699
0
    uc = CURLUE_OUT_OF_MEMORY;
700
0
    break;
701
0
  default:
702
0
    uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */
703
0
    break;
704
290k
  }
705
706
290k
  return uc;
707
290k
}
708
709
/* used for HTTP/2 server push */
710
CURLUcode Curl_url_set_authority(CURLU *u, const char *authority)
711
0
{
712
0
  CURLUcode ures;
713
0
  struct dynbuf host;
714
715
0
  DEBUGASSERT(authority);
716
0
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
717
718
0
  ures = parse_authority(u, authority, strlen(authority),
719
0
                         CURLU_DISALLOW_USER, &host, !!u->scheme);
720
0
  if(ures)
721
0
    curlx_dyn_free(&host);
722
0
  else {
723
0
    curlx_free(u->host);
724
0
    u->host = curlx_dyn_ptr(&host);
725
0
  }
726
0
  return ures;
727
0
}
728
729
/*
730
 * "Remove Dot Segments"
731
 * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
732
 */
733
734
static bool is_dot(const char **str, size_t *clen)
735
140M
{
736
140M
  const char *p = *str;
737
140M
  if(*p == '.') {
738
2.26M
    (*str)++;
739
2.26M
    (*clen)--;
740
2.26M
    return TRUE;
741
2.26M
  }
742
138M
  else if((*clen >= 3) &&
743
138M
          (p[0] == '%') && (p[1] == '2') && ((p[2] | 0x20) == 'e')) {
744
439k
    *str += 3;
745
439k
    *clen -= 3;
746
439k
    return TRUE;
747
439k
  }
748
138M
  return FALSE;
749
140M
}
750
751
262M
#define ISSLASH(x) ((x) == '/')
752
753
/* prescan the string to see if it needs work */
754
static bool needs_dedotdot(const char *p, size_t pn)
755
89.9k
{
756
  /* a single byte path cannot be cleaned up */
757
89.9k
  if(pn < 2)
758
804
    return FALSE;
759
107M
  while(pn) {
760
107M
    if(is_dot(&p, &pn)) {
761
      /* "./" or dot before end of string */
762
526k
      if(!pn || ISSLASH(*p))
763
6.40k
        return TRUE;
764
      /* "../" or ".." before end of string */
765
520k
      else if(is_dot(&p, &pn) && (!pn || ISSLASH(*p)))
766
2.71k
        return TRUE;
767
526k
    }
768
106M
    else {
769
106M
      p++;
770
106M
      pn--;
771
106M
    }
772
107M
  }
773
80.0k
  return FALSE;
774
89.1k
}
775
776
/*
777
 * dedotdotify()
778
 *
779
 * This function gets a null-terminated path with dot and dotdot sequences
780
 * passed in and strips them off according to the rules in RFC 3986 section
781
 * 5.2.4.
782
 *
783
 * The function handles a path. It should not contain the query nor fragment.
784
 *
785
 * RETURNS
786
 *
787
 * Zero for success and 'out' set to an allocated string (or NULL if there's
788
 * nothing to do).
789
 *
790
 * @unittest 1395
791
 */
792
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp);
793
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp)
794
89.9k
{
795
89.9k
  struct dynbuf out;
796
89.9k
  CURLcode result = CURLE_OK;
797
798
  /* variables for leading dot checks */
799
89.9k
  const char *dinput = input;
800
89.9k
  size_t dlen = clen;
801
802
89.9k
  *outp = NULL;
803
89.9k
  if(!needs_dedotdot(input, clen))
804
80.8k
    return 0;
805
806
9.11k
  curlx_dyn_init(&out, clen + 1);
807
808
  /* if the input buffer begins with a prefix of "../" or "./", then remove
809
     that prefix from the input buffer; otherwise, */
810
9.11k
  if(is_dot(&dinput, &dlen)) {
811
0
    if(ISSLASH(*dinput)) {
812
      /* one dot followed by a slash */
813
0
      input = dinput + 1;
814
0
      clen = dlen - 1;
815
0
    }
816
817
    /* if the input buffer consists only of "." or "..", then remove
818
       that from the input buffer; otherwise, */
819
0
    else if(is_dot(&dinput, &dlen)) {
820
0
      if(!dlen)
821
        /* .. [end] */
822
0
        goto end;
823
0
      else if(ISSLASH(*dinput)) {
824
        /* ../ */
825
0
        input = dinput + 1;
826
0
        clen = dlen - 1;
827
0
      }
828
0
    }
829
0
  }
830
831
258M
  while(clen && !result) { /* until end of path content */
832
258M
    if(ISSLASH(*input)) {
833
32.0M
      const char *p = &input[1];
834
32.0M
      size_t blen = clen - 1;
835
      /* if the input buffer begins with a prefix of "/./" or "/.", where "."
836
         is a complete path segment, then replace that prefix with "/" in the
837
         input buffer; otherwise, */
838
32.0M
      if(is_dot(&p, &blen)) {
839
1.52M
        if(!blen) { /* /. */
840
780
          result = curlx_dyn_addn(&out, "/", 1);
841
780
          break;
842
780
        }
843
1.52M
        else if(ISSLASH(*p)) { /* /./ */
844
396k
          input = p;
845
396k
          clen = blen;
846
396k
          continue;
847
396k
        }
848
849
        /* if the input buffer begins with a prefix of "/../" or "/..", where
850
           ".." is a complete path segment, then replace that prefix with "/"
851
           in the input buffer and remove the last segment and its preceding
852
           "/" (if any) from the output buffer; otherwise, */
853
1.13M
        else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) {
854
          /* remove the last segment from the output buffer */
855
427k
          size_t len = curlx_dyn_len(&out);
856
427k
          if(len) {
857
397k
            const char *ptr = curlx_dyn_ptr(&out);
858
397k
            const char *last = memrchr(ptr, '/', len);
859
397k
            if(last)
860
              /* trim the output at the slash */
861
397k
              curlx_dyn_setlen(&out, last - ptr);
862
397k
          }
863
864
427k
          if(blen) { /* /../ */
865
427k
            input = p;
866
427k
            clen = blen;
867
427k
            continue;
868
427k
          }
869
587
          result = curlx_dyn_addn(&out, "/", 1);
870
587
          break;
871
427k
        }
872
1.52M
      }
873
32.0M
    }
874
875
    /* move the first path segment in the input buffer to the end of the
876
       output buffer, including the initial "/" character (if any) and any
877
       subsequent characters up to, but not including, the next "/" character
878
       or the end of the input buffer. */
879
880
257M
    result = curlx_dyn_addn(&out, input, 1);
881
257M
    input++;
882
257M
    clen--;
883
257M
  }
884
9.11k
end:
885
9.11k
  if(!result) {
886
9.11k
    if(curlx_dyn_len(&out))
887
9.11k
      *outp = curlx_dyn_ptr(&out);
888
0
    else {
889
0
      *outp = curlx_strdup("");
890
0
      if(!*outp)
891
0
        return 1;
892
0
    }
893
9.11k
  }
894
9.11k
  return result ? 1 : 0; /* success */
895
9.11k
}
896
897
/*
898
 * @unittest 1675
899
 */
900
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
901
                              const char **pathp, size_t *pathlenp);
902
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
903
                              const char **pathp, size_t *pathlenp)
904
3.04k
{
905
3.04k
  const char *path;
906
3.04k
  size_t pathlen;
907
908
3.04k
  *pathp = NULL;
909
3.04k
  *pathlenp = 0;
910
3.04k
  if(urllen <= 6)
911
    /* file:/ is not enough to actually be a complete file: URL */
912
42
    return CURLUE_BAD_FILE_URL;
913
914
  /* path has been allocated large enough to hold this */
915
3.00k
  path = &url[5];
916
3.00k
  pathlen = urllen - 5;
917
918
  /* RFC 8089: file-hier-part = ( "//" auth-path ) / local-path, where
919
     local-path also starts with a "/". So reject anything that does not
920
     start with at least one "/" */
921
3.00k
  if(path[0] != '/')
922
4
    return CURLUE_BAD_FILE_URL;
923
924
  /* Extra handling URLs with an authority component (i.e. that start with
925
   * "file://")
926
   *
927
   * We allow omitted hostname (e.g. file:/<path>) -- valid according to
928
   * RFC 8089, but not the (current) WHAT-WG URL spec.
929
   */
930
3.00k
  if(path[1] == '/') {
931
    /* swallow the two slashes */
932
822
    const char *ptr = &path[2];
933
934
    /*
935
     * According to RFC 8089, a file: URL can be reliably dereferenced if:
936
     *
937
     *  o it has no/blank hostname, or
938
     *
939
     *  o the hostname matches "localhost" (case-insensitively), or
940
     *
941
     *  o the hostname is a FQDN that resolves to this machine, or
942
     *
943
     * For brevity, we only consider URLs with empty, "localhost", or
944
     * "127.0.0.1" hostnames as local, otherwise as an UNC String.
945
     *
946
     * Additionally, there is an exception for URLs with a Windows drive
947
     * letter in the authority (which was accidentally omitted from RFC 8089
948
     * Appendix E, but believe me, it was meant to be there. --MK)
949
     */
950
822
    if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
951
      /* the URL includes a hostname, it must match "localhost" or
952
         "127.0.0.1" to be valid */
953
547
      if(checkprefix("localhost/", ptr) ||
954
531
         checkprefix("127.0.0.1/", ptr)) {
955
39
        ptr += 9; /* now points to the slash after the host */
956
39
      }
957
508
      else
958
        /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
959
           none */
960
508
        return CURLUE_BAD_FILE_URL;
961
547
    }
962
963
314
    path = ptr;
964
314
    pathlen = urllen - (ptr - url);
965
314
  }
966
967
2.49k
#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__)
968
  /* Do not allow Windows drive letters when not in Windows.
969
   * This catches both "file:/c:" and "file:c:" */
970
2.49k
  if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
971
2.34k
     STARTS_WITH_URL_DRIVE_PREFIX(path)) {
972
    /* File drive letters are only accepted in MS-DOS/Windows */
973
368
    return CURLUE_BAD_FILE_URL;
974
368
  }
975
#else
976
  /* If the path starts with a slash and a drive letter, ditch the slash */
977
  if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
978
    /* This cannot be done with strcpy, as the memory chunks overlap! */
979
    path++;
980
    pathlen--;
981
  }
982
#endif
983
2.12k
  u->scheme = curlx_strdup("file");
984
2.12k
  if(!u->scheme)
985
0
    return CURLUE_OUT_OF_MEMORY;
986
987
2.12k
  *pathp = path;
988
2.12k
  *pathlenp = pathlen;
989
2.12k
  return CURLUE_OK;
990
2.12k
}
991
992
static CURLUcode parse_scheme(const char *url, CURLU *u, char *schemebuf,
993
                              size_t schemelen, unsigned int flags,
994
                              const char **hostpp)
995
293k
{
996
  /* clear path */
997
293k
  const char *schemep = NULL;
998
999
293k
  if(schemelen) {
1000
182k
    int num_slashes = 0;
1001
182k
    const char *p = &url[schemelen + 1];
1002
182k
    if(!Curl_get_scheme(schemebuf) && !(flags & CURLU_NON_SUPPORT_SCHEME))
1003
74
      return CURLUE_UNSUPPORTED_SCHEME;
1004
1005
182k
    if(!ISSLASH(*p))
1006
      /* less than one */
1007
22
      return CURLUE_BAD_SLASHES;
1008
182k
    if((flags & CURLU_NO_AUTHORITY)) {
1009
0
      while(ISSLASH(*p) && (num_slashes < 2)) {
1010
0
        p++;
1011
0
        num_slashes++;
1012
0
      }
1013
0
    }
1014
182k
    else {
1015
481k
      while(ISSLASH(*p) && (num_slashes < 4)) {
1016
299k
        p++;
1017
299k
        num_slashes++;
1018
299k
      }
1019
182k
      if(num_slashes > 3)
1020
47
        return CURLUE_BAD_SLASHES;
1021
182k
    }
1022
1023
182k
    schemep = schemebuf;
1024
182k
    *hostpp = p; /* hostname starts here */
1025
182k
  }
1026
111k
  else {
1027
    /* no scheme! */
1028
1029
111k
    if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME)))
1030
0
      return CURLUE_BAD_SCHEME;
1031
1032
111k
    if(flags & CURLU_DEFAULT_SCHEME)
1033
0
      schemep = DEFAULT_SCHEME;
1034
1035
    /*
1036
     * The URL was badly formatted, let's try without scheme specified.
1037
     */
1038
111k
    *hostpp = url;
1039
111k
  }
1040
1041
293k
  if(schemep) {
1042
182k
    u->scheme = curlx_strdup(schemep);
1043
182k
    if(!u->scheme)
1044
0
      return CURLUE_OUT_OF_MEMORY;
1045
182k
  }
1046
293k
  return CURLUE_OK;
1047
293k
}
1048
1049
static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host)
1050
107k
{
1051
107k
  const char *hostname = curlx_dyn_ptr(host);
1052
107k
  const char *schemep = NULL;
1053
  /* legacy curl-style guess based on hostname */
1054
107k
  if(checkprefix("ftp.", hostname))
1055
3.16k
    schemep = "ftp";
1056
104k
  else if(checkprefix("dict.", hostname))
1057
5.01k
    schemep = "dict";
1058
99.2k
  else if(checkprefix("ldap.", hostname))
1059
1.97k
    schemep = "ldap";
1060
97.2k
  else if(checkprefix("imap.", hostname))
1061
1.79k
    schemep = "imap";
1062
95.4k
  else if(checkprefix("smtp.", hostname))
1063
3.84k
    schemep = "smtp";
1064
91.5k
  else if(checkprefix("pop3.", hostname))
1065
3.61k
    schemep = "pop3";
1066
87.9k
  else
1067
87.9k
    schemep = "http";
1068
1069
107k
  u->scheme = curlx_strdup(schemep);
1070
107k
  if(!u->scheme)
1071
0
    return CURLUE_OUT_OF_MEMORY;
1072
1073
107k
  u->guessed_scheme = TRUE;
1074
107k
  return CURLUE_OK;
1075
107k
}
1076
1077
static CURLUcode handle_fragment(CURLU *u, const char *fragment,
1078
                                 size_t fraglen, unsigned int flags)
1079
40.6k
{
1080
40.6k
  CURLUcode ures;
1081
40.6k
  u->fragment_present = TRUE;
1082
40.6k
  if(fraglen > 1) {
1083
    /* skip the leading '#' in the copy but include the null-terminator */
1084
36.8k
    if(flags & CURLU_URLENCODE) {
1085
18.1k
      struct dynbuf enc;
1086
18.1k
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1087
18.1k
      ures = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, QUERY_NO);
1088
18.1k
      if(ures)
1089
0
        return ures;
1090
18.1k
      u->fragment = curlx_dyn_ptr(&enc);
1091
18.1k
    }
1092
18.7k
    else {
1093
18.7k
      u->fragment = curlx_memdup0(fragment + 1, fraglen - 1);
1094
18.7k
      if(!u->fragment)
1095
0
        return CURLUE_OUT_OF_MEMORY;
1096
18.7k
    }
1097
36.8k
  }
1098
40.6k
  return CURLUE_OK;
1099
40.6k
}
1100
1101
static CURLUcode handle_query(CURLU *u, const char *query,
1102
                              size_t qlen, unsigned int flags)
1103
37.4k
{
1104
37.4k
  u->query_present = TRUE;
1105
37.4k
  if(qlen > 1) {
1106
32.1k
    if(flags & CURLU_URLENCODE) {
1107
11.5k
      struct dynbuf enc;
1108
11.5k
      CURLUcode ures;
1109
11.5k
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1110
      /* skip the leading question mark */
1111
11.5k
      ures = urlencode_str(&enc, query + 1, qlen - 1, TRUE, QUERY_YES);
1112
11.5k
      if(ures)
1113
0
        return ures;
1114
11.5k
      u->query = curlx_dyn_ptr(&enc);
1115
11.5k
    }
1116
20.5k
    else {
1117
20.5k
      u->query = curlx_memdup0(query + 1, qlen - 1);
1118
20.5k
      if(!u->query)
1119
0
        return CURLUE_OUT_OF_MEMORY;
1120
20.5k
    }
1121
32.1k
  }
1122
5.36k
  else {
1123
    /* single byte query */
1124
5.36k
    u->query = curlx_strdup("");
1125
5.36k
    if(!u->query)
1126
0
      return CURLUE_OUT_OF_MEMORY;
1127
5.36k
  }
1128
37.4k
  return CURLUE_OK;
1129
37.4k
}
1130
1131
static CURLUcode handle_path(CURLU *u, const char *path,
1132
                             size_t pathlen, unsigned int flags,
1133
                             bool is_file)
1134
288k
{
1135
288k
  CURLUcode ures;
1136
288k
  if(pathlen && (flags & CURLU_URLENCODE)) {
1137
51.5k
    struct dynbuf enc;
1138
51.5k
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1139
51.5k
    ures = urlencode_str(&enc, path, pathlen, TRUE, QUERY_NO);
1140
51.5k
    if(ures)
1141
0
      return ures;
1142
51.5k
    pathlen = curlx_dyn_len(&enc);
1143
51.5k
    path = u->path = curlx_dyn_ptr(&enc);
1144
51.5k
  }
1145
1146
288k
  if(pathlen >= (size_t)(1 + !is_file)) {
1147
    /* paths for file:// scheme can be one byte, others need to be two */
1148
95.0k
    if(!u->path) {
1149
54.1k
      u->path = curlx_memdup0(path, pathlen);
1150
54.1k
      if(!u->path)
1151
0
        return CURLUE_OUT_OF_MEMORY;
1152
54.1k
      path = u->path;
1153
54.1k
    }
1154
40.8k
    else if(flags & CURLU_URLENCODE)
1155
      /* it might have encoded more than the path so cut it */
1156
40.8k
      u->path[pathlen] = 0;
1157
1158
95.0k
    if(!(flags & CURLU_PATH_AS_IS)) {
1159
      /* remove ../ and ./ sequences according to RFC3986 */
1160
89.9k
      char *dedot;
1161
89.9k
      int err = dedotdotify(path, pathlen, &dedot);
1162
89.9k
      if(err)
1163
0
        return CURLUE_OUT_OF_MEMORY;
1164
89.9k
      if(dedot) {
1165
9.11k
        curlx_free(u->path);
1166
9.11k
        u->path = dedot;
1167
9.11k
      }
1168
89.9k
    }
1169
95.0k
  }
1170
288k
  return CURLUE_OK;
1171
288k
}
1172
1173
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
1174
297k
{
1175
297k
  const char *path;
1176
297k
  size_t pathlen;
1177
297k
  char schemebuf[MAX_SCHEME_LEN + 1];
1178
297k
  size_t schemelen = 0;
1179
297k
  size_t urllen;
1180
297k
  CURLUcode ures = CURLUE_OK;
1181
297k
  struct dynbuf host;
1182
297k
  bool is_file = FALSE;
1183
1184
297k
  DEBUGASSERT(url);
1185
1186
297k
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
1187
1188
297k
  ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE));
1189
297k
  if(ures)
1190
533
    goto fail;
1191
1192
296k
  schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
1193
296k
                                   flags & (CURLU_GUESS_SCHEME |
1194
296k
                                            CURLU_DEFAULT_SCHEME));
1195
1196
  /* handle the file: scheme */
1197
296k
  if(schemelen && !strcmp(schemebuf, "file")) {
1198
3.04k
    is_file = TRUE;
1199
3.04k
    ures = parse_file(url, urllen, u, &path, &pathlen);
1200
3.04k
  }
1201
293k
  else {
1202
293k
    const char *hostp = NULL;
1203
293k
    size_t hostlen;
1204
293k
    ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp);
1205
293k
    if(ures)
1206
143
      goto fail;
1207
1208
    /* find the end of the hostname + port number */
1209
293k
    hostlen = strcspn(hostp, "/?#");
1210
293k
    path = &hostp[hostlen];
1211
1212
    /* this pathlen also contains the query and the fragment */
1213
293k
    pathlen = urllen - (path - url);
1214
293k
    if(hostlen) {
1215
292k
      ures = parse_authority(u, hostp, hostlen, flags, &host, !!u->scheme);
1216
292k
      if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme)
1217
107k
        ures = guess_scheme(u, &host);
1218
292k
    }
1219
1.37k
    else if(flags & CURLU_NO_AUTHORITY) {
1220
      /* allowed to be empty. */
1221
0
      if(curlx_dyn_add(&host, ""))
1222
0
        ures = CURLUE_OUT_OF_MEMORY;
1223
0
    }
1224
1.37k
    else
1225
1.37k
      ures = CURLUE_NO_HOST;
1226
293k
  }
1227
296k
  if(!ures) {
1228
    /* The path might at this point contain a fragment and/or a query to
1229
       handle */
1230
288k
    const char *fragment = strchr(path, '#');
1231
288k
    if(fragment) {
1232
40.6k
      size_t fraglen = pathlen - (fragment - path);
1233
40.6k
      ures = handle_fragment(u, fragment, fraglen, flags);
1234
      /* after this, pathlen still contains the query */
1235
40.6k
      pathlen -= fraglen;
1236
40.6k
    }
1237
288k
  }
1238
296k
  if(!ures) {
1239
288k
    const char *query = memchr(path, '?', pathlen);
1240
288k
    if(query) {
1241
37.4k
      size_t qlen = pathlen - (query - path);
1242
37.4k
      ures = handle_query(u, query, qlen, flags);
1243
37.4k
      pathlen -= qlen;
1244
37.4k
    }
1245
288k
  }
1246
296k
  if(!ures)
1247
    /* the fragment and query parts are trimmed off from the path */
1248
288k
    ures = handle_path(u, path, pathlen, flags, is_file);
1249
296k
  if(!ures) {
1250
288k
    u->host = curlx_dyn_ptr(&host);
1251
288k
    return CURLUE_OK;
1252
288k
  }
1253
8.94k
fail:
1254
8.94k
  curlx_dyn_free(&host);
1255
8.94k
  free_urlhandle(u);
1256
8.94k
  return ures;
1257
296k
}
1258
1259
/*
1260
 * Parse the URL and, if successful, replace everything in the Curl_URL struct.
1261
 */
1262
static CURLUcode parseurl_and_replace(const char *url, CURLU *u,
1263
                                      unsigned int flags)
1264
297k
{
1265
297k
  CURLUcode ures;
1266
297k
  CURLU tmpurl;
1267
297k
  memset(&tmpurl, 0, sizeof(tmpurl));
1268
297k
  ures = parseurl(url, &tmpurl, flags);
1269
297k
  if(!ures) {
1270
288k
    free_urlhandle(u);
1271
288k
    *u = tmpurl;
1272
288k
  }
1273
297k
  return ures;
1274
297k
}
1275
1276
/*
1277
 * Concatenate a relative URL onto a base URL making it absolute.
1278
 */
1279
static CURLUcode redirect_url(const char *base, const char *relurl,
1280
                              CURLU *u, unsigned int flags)
1281
24.2k
{
1282
24.2k
  struct dynbuf urlbuf;
1283
24.2k
  bool host_changed = FALSE;
1284
24.2k
  const char *useurl = relurl;
1285
24.2k
  const char *cutoff = NULL;
1286
24.2k
  size_t prelen;
1287
24.2k
  CURLUcode uc;
1288
  /* this can get here with a NULL u->scheme only if asked to use the default
1289
     scheme, so allow fallback to that */
1290
24.2k
  const char *scheme = u->scheme ? u->scheme : DEFAULT_SCHEME;
1291
1292
  /* protsep points to the start of the hostname, after [scheme]:// */
1293
24.2k
  const char *protsep = base + strlen(scheme) + 3;
1294
24.2k
  DEBUGASSERT(base && relurl && u); /* all set here */
1295
24.2k
  if(!base)
1296
0
    return CURLUE_MALFORMED_INPUT; /* should never happen */
1297
1298
  /* handle different relative URL types */
1299
24.2k
  switch(relurl[0]) {
1300
1.09k
  case '/':
1301
1.09k
    if(relurl[1] == '/') {
1302
      /* protocol-relative URL: //example.com/path */
1303
302
      cutoff = protsep;
1304
302
      useurl = &relurl[2];
1305
302
      host_changed = TRUE;
1306
302
    }
1307
791
    else
1308
      /* absolute /path */
1309
791
      cutoff = strchr(protsep, '/');
1310
1.09k
    break;
1311
1312
7.49k
  case '#':
1313
    /* fragment-only change */
1314
7.49k
    if(u->fragment_present)
1315
6.19k
      cutoff = strchr(protsep, '#');
1316
7.49k
    break;
1317
1318
15.6k
  default:
1319
    /* path or query-only change */
1320
15.6k
    if(u->query_present)
1321
      /* remove existing query */
1322
3.36k
      cutoff = strchr(protsep, '?');
1323
12.2k
    else if(u->fragment_present)
1324
      /* Remove existing fragment */
1325
2.23k
      cutoff = strchr(protsep, '#');
1326
1327
15.6k
    if(relurl[0] != '?') {
1328
      /* append a relative path after the last slash */
1329
14.9k
      cutoff = memrchr(protsep, '/',
1330
14.9k
                       cutoff ? (size_t)(cutoff - protsep) : strlen(protsep));
1331
14.9k
      if(cutoff)
1332
14.9k
        cutoff++; /* truncate after last slash */
1333
14.9k
    }
1334
15.6k
    break;
1335
24.2k
  }
1336
1337
24.2k
  prelen = cutoff ? (size_t)(cutoff - base) : strlen(base);
1338
1339
  /* build new URL */
1340
24.2k
  curlx_dyn_init(&urlbuf, CURL_MAX_INPUT_LENGTH);
1341
1342
24.2k
  if(!curlx_dyn_addn(&urlbuf, base, prelen) &&
1343
24.2k
     !urlencode_str(&urlbuf, useurl, strlen(useurl), !host_changed,
1344
24.2k
                    QUERY_NOT_YET)) {
1345
24.2k
    uc = parseurl_and_replace(curlx_dyn_ptr(&urlbuf), u,
1346
24.2k
                              flags & ~U_CURLU_PATH_AS_IS);
1347
24.2k
  }
1348
0
  else
1349
0
    uc = CURLUE_OUT_OF_MEMORY;
1350
1351
24.2k
  curlx_dyn_free(&urlbuf);
1352
24.2k
  return uc;
1353
24.2k
}
1354
1355
/*
1356
 */
1357
CURLU *curl_url(void)
1358
273k
{
1359
273k
  return curlx_calloc(1, sizeof(struct Curl_URL));
1360
273k
}
1361
1362
void curl_url_cleanup(CURLU *u)
1363
762k
{
1364
762k
  if(u) {
1365
276k
    free_urlhandle(u);
1366
276k
    curlx_free(u);
1367
276k
  }
1368
762k
}
1369
1370
#define DUP(dest, src, name)                    \
1371
26.5k
  do {                                          \
1372
26.5k
    if((src)->name) {                           \
1373
6.90k
      (dest)->name = curlx_strdup((src)->name); \
1374
6.90k
      if(!(dest)->name)                         \
1375
6.90k
        goto fail;                              \
1376
6.90k
    }                                           \
1377
26.5k
  } while(0)
1378
1379
CURLU *curl_url_dup(const CURLU *in)
1380
2.94k
{
1381
2.94k
  struct Curl_URL *u = curlx_calloc(1, sizeof(struct Curl_URL));
1382
2.94k
  if(u) {
1383
2.94k
    DUP(u, in, scheme);
1384
2.94k
    DUP(u, in, user);
1385
2.94k
    DUP(u, in, password);
1386
2.94k
    DUP(u, in, options);
1387
2.94k
    DUP(u, in, host);
1388
2.94k
    DUP(u, in, path);
1389
2.94k
    DUP(u, in, query);
1390
2.94k
    DUP(u, in, fragment);
1391
2.94k
    DUP(u, in, zoneid);
1392
2.94k
    u->portnum = in->portnum;
1393
2.94k
    u->port_present = in->port_present;
1394
2.94k
    u->fragment_present = in->fragment_present;
1395
2.94k
    u->query_present = in->query_present;
1396
2.94k
  }
1397
2.94k
  return u;
1398
0
fail:
1399
0
  curl_url_cleanup(u);
1400
0
  return NULL;
1401
2.94k
}
1402
1403
#ifndef USE_IDN
1404
#define host_decode(x, y) CURLUE_LACKS_IDN
1405
#define host_encode(x, y) CURLUE_LACKS_IDN
1406
#else
1407
static CURLUcode host_decode(const char *host, char **allochost)
1408
0
{
1409
0
  CURLcode result = Curl_idn_decode(host, allochost);
1410
0
  if(result)
1411
0
    return (result == CURLE_OUT_OF_MEMORY) ?
1412
0
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1413
0
  return CURLUE_OK;
1414
0
}
1415
1416
static CURLUcode host_encode(const char *host, char **allochost)
1417
0
{
1418
0
  CURLcode result = Curl_idn_encode(host, allochost);
1419
0
  if(result)
1420
0
    return (result == CURLE_OUT_OF_MEMORY) ?
1421
0
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1422
0
  return CURLUE_OK;
1423
0
}
1424
#endif
1425
1426
static CURLUcode urlget_format(const CURLU *u, CURLUPart what,
1427
                               const char *ptr, char **partp,
1428
                               bool plusdecode, unsigned int flags)
1429
641k
{
1430
641k
  CURLUcode uc = CURLUE_OK;
1431
641k
  size_t partlen = strlen(ptr);
1432
641k
  bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0;
1433
641k
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1434
641k
  bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST);
1435
641k
  bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST);
1436
641k
  char *part = curlx_memdup0(ptr, partlen);
1437
641k
  *partp = NULL;
1438
641k
  if(!part)
1439
0
    return CURLUE_OUT_OF_MEMORY;
1440
641k
  if(plusdecode) {
1441
    /* convert + to space */
1442
81
    char *plus = part;
1443
81
    size_t i = 0;
1444
695
    for(i = 0; i < partlen; ++plus, i++) {
1445
614
      if(*plus == '+')
1446
42
        *plus = ' ';
1447
614
    }
1448
81
  }
1449
641k
  if(urldecode) {
1450
57.7k
    char *decoded;
1451
57.7k
    size_t dlen;
1452
    /* this unconditional rejection of control bytes is documented API
1453
       behavior */
1454
57.7k
    CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen,
1455
57.7k
                                     REJECT_CTRL);
1456
57.7k
    curlx_free(part);
1457
57.7k
    if(result)
1458
43
      return CURLUE_URLDECODE;
1459
57.7k
    part = decoded;
1460
57.7k
    partlen = dlen;
1461
57.7k
  }
1462
641k
  if(urlencode) {
1463
176k
    struct dynbuf enc;
1464
176k
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1465
176k
    uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ?
1466
176k
                       QUERY_YES : QUERY_NO);
1467
176k
    curlx_free(part);
1468
176k
    if(uc)
1469
0
      return uc;
1470
176k
    part = curlx_dyn_ptr(&enc);
1471
176k
  }
1472
465k
  else if(punycode) {
1473
0
    if(!Curl_is_ASCII_name(u->host)) {
1474
0
      char *punyversion = NULL;
1475
0
      uc = host_decode(part, &punyversion);
1476
0
      curlx_free(part);
1477
0
      if(uc)
1478
0
        return uc;
1479
0
      part = punyversion;
1480
0
    }
1481
0
  }
1482
465k
  else if(depunyfy) {
1483
0
    if(Curl_is_ASCII_name(u->host)) {
1484
0
      char *unpunified = NULL;
1485
0
      uc = host_encode(part, &unpunified);
1486
0
      curlx_free(part);
1487
0
      if(uc)
1488
0
        return uc;
1489
0
      part = unpunified;
1490
0
    }
1491
0
  }
1492
641k
  *partp = part;
1493
641k
  return CURLUE_OK;
1494
641k
}
1495
1496
static CURLUcode file_url(const CURLU *u, char **part,
1497
                          const char *fragmentsep,
1498
                          const char *querysep)
1499
2.05k
{
1500
2.05k
  char *url = curl_maprintf("file://%s%s%s%s%s",
1501
2.05k
                            u->path, querysep, u->query ? u->query : "",
1502
2.05k
                            fragmentsep, u->fragment ? u->fragment : "");
1503
2.05k
  if(!url)
1504
0
    return CURLUE_OUT_OF_MEMORY;
1505
1506
2.05k
  *part = url;
1507
2.05k
  return CURLUE_OK;
1508
2.05k
}
1509
1510
static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags)
1511
356k
{
1512
356k
  char *url;
1513
356k
  char *allochost = NULL;
1514
356k
  const char *fragmentsep =
1515
356k
    (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ?
1516
325k
    "#" : "";
1517
356k
  const char *querysep = ((u->query && u->query[0]) ||
1518
325k
                          (u->query_present && flags & CURLU_GET_EMPTY)) ?
1519
323k
    "?" : "";
1520
356k
  char portbuf[7];
1521
356k
  if(curl_strequal("file", u->scheme))
1522
2.05k
    return file_url(u, part, fragmentsep, querysep);
1523
354k
  else if(!u->host)
1524
115k
    return CURLUE_NO_HOST;
1525
239k
  else {
1526
239k
    const char *scheme;
1527
239k
    char *options = u->options;
1528
239k
    char *port = NULL;
1529
239k
    const struct Curl_scheme *h = NULL;
1530
239k
    char schemebuf[MAX_SCHEME_LEN + 5];
1531
239k
    if(u->scheme)
1532
239k
      scheme = u->scheme;
1533
0
    else if(flags & CURLU_DEFAULT_SCHEME)
1534
0
      scheme = DEFAULT_SCHEME;
1535
0
    else
1536
0
      return CURLUE_NO_SCHEME;
1537
1538
239k
    if(u->port_present) {
1539
9.27k
      curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1540
9.27k
      port = portbuf;
1541
9.27k
    }
1542
1543
239k
    h = Curl_get_scheme(scheme);
1544
239k
    if(h) {
1545
238k
      if(!u->port_present && (flags & CURLU_DEFAULT_PORT)) {
1546
        /* there is no stored port number, but asked to deliver a default one
1547
           for the scheme */
1548
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1549
0
        port = portbuf;
1550
0
      }
1551
238k
      else if(u->port_present && (h->defport == u->portnum) &&
1552
625
              (flags & CURLU_NO_DEFAULT_PORT)) {
1553
        /* there is a stored port number, but asked to inhibit if it matches
1554
           the default port for the scheme */
1555
244
        port = NULL;
1556
244
      }
1557
1558
238k
      if(!(h->flags & PROTOPT_URLOPTIONS))
1559
216k
        options = NULL;
1560
238k
    }
1561
1562
239k
    if(u->host[0] == '[') {
1563
6.85k
      if(u->zoneid) {
1564
        /* make it '[ host %25 zoneid ]' */
1565
2.38k
        struct dynbuf enc;
1566
2.38k
        size_t hostlen = strlen(u->host);
1567
2.38k
        curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1568
2.38k
        if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
1569
2.38k
                          u->zoneid))
1570
0
          return CURLUE_OUT_OF_MEMORY;
1571
2.38k
        allochost = curlx_dyn_ptr(&enc);
1572
2.38k
      }
1573
6.85k
    }
1574
232k
    else if(flags & CURLU_URLENCODE) {
1575
22.5k
      allochost = curl_easy_escape(NULL, u->host, 0);
1576
22.5k
      if(!allochost)
1577
0
        return CURLUE_OUT_OF_MEMORY;
1578
22.5k
    }
1579
209k
    else if(flags & CURLU_PUNYCODE) {
1580
0
      if(!Curl_is_ASCII_name(u->host)) {
1581
0
        CURLUcode ret = host_decode(u->host, &allochost);
1582
0
        if(ret)
1583
0
          return ret;
1584
0
      }
1585
0
    }
1586
209k
    else if(flags & CURLU_PUNY2IDN) {
1587
0
      if(Curl_is_ASCII_name(u->host)) {
1588
0
        CURLUcode ret = host_encode(u->host, &allochost);
1589
0
        if(ret)
1590
0
          return ret;
1591
0
      }
1592
0
    }
1593
1594
239k
    if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme)
1595
239k
      curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme);
1596
0
    else
1597
0
      schemebuf[0] = 0;
1598
1599
239k
    url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1600
239k
                        schemebuf,
1601
239k
                        u->user ? u->user : "",
1602
239k
                        u->password ? ":" : "",
1603
239k
                        u->password ? u->password : "",
1604
239k
                        options ? ";" : "",
1605
239k
                        options ? options : "",
1606
239k
                        (u->user || u->password || options) ? "@" : "",
1607
239k
                        allochost ? allochost : u->host,
1608
239k
                        port ? ":" : "",
1609
239k
                        port ? port : "",
1610
239k
                        u->path ? u->path : "/",
1611
239k
                        querysep,
1612
239k
                        u->query ? u->query : "",
1613
239k
                        fragmentsep,
1614
239k
                        u->fragment ? u->fragment : "");
1615
239k
    curlx_free(allochost);
1616
239k
  }
1617
239k
  if(!url)
1618
0
    return CURLUE_OUT_OF_MEMORY;
1619
239k
  *part = url;
1620
239k
  return CURLUE_OK;
1621
239k
}
1622
1623
CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
1624
                       char **part, unsigned int flags)
1625
2.07M
{
1626
2.07M
  const char *ptr;
1627
2.07M
  CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
1628
2.07M
  char portbuf[7];
1629
2.07M
  bool plusdecode = FALSE;
1630
2.07M
  if(!u)
1631
0
    return CURLUE_BAD_HANDLE;
1632
2.07M
  if(!part)
1633
0
    return CURLUE_BAD_PARTPOINTER;
1634
2.07M
  *part = NULL;
1635
1636
2.07M
  switch(what) {
1637
268k
  case CURLUPART_SCHEME:
1638
268k
    ptr = u->scheme;
1639
268k
    ifmissing = CURLUE_NO_SCHEME;
1640
268k
    flags &= ~U_CURLU_URLDECODE; /* never for schemes */
1641
268k
    if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme)
1642
88.5k
      return CURLUE_NO_SCHEME;
1643
180k
    break;
1644
217k
  case CURLUPART_USER:
1645
217k
    ptr = u->user;
1646
217k
    ifmissing = CURLUE_NO_USER;
1647
217k
    break;
1648
217k
  case CURLUPART_PASSWORD:
1649
217k
    ptr = u->password;
1650
217k
    ifmissing = CURLUE_NO_PASSWORD;
1651
217k
    break;
1652
176k
  case CURLUPART_OPTIONS:
1653
176k
    ptr = u->options;
1654
176k
    ifmissing = CURLUE_NO_OPTIONS;
1655
176k
    break;
1656
223k
  case CURLUPART_HOST:
1657
223k
    ptr = u->host;
1658
223k
    ifmissing = CURLUE_NO_HOST;
1659
223k
    break;
1660
216k
  case CURLUPART_ZONEID:
1661
216k
    ptr = u->zoneid;
1662
216k
    ifmissing = CURLUE_NO_ZONEID;
1663
216k
    break;
1664
45.1k
  case CURLUPART_PORT:
1665
45.1k
    ptr = NULL;
1666
45.1k
    ifmissing = CURLUE_NO_PORT;
1667
45.1k
    flags &= ~U_CURLU_URLDECODE; /* never for port */
1668
45.1k
    if(u->port_present) {
1669
1.73k
      const struct Curl_scheme *h = u->scheme ?
1670
1.73k
                                    Curl_get_scheme(u->scheme) : NULL;
1671
      /* there is a stored port number, but ask to inhibit if
1672
         it matches the default one for the scheme */
1673
1.73k
      if(h && (h->defport == u->portnum) &&
1674
13
         (flags & CURLU_NO_DEFAULT_PORT)) {
1675
13
        ptr = NULL;
1676
13
      }
1677
1.72k
      else {
1678
1.72k
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1679
1.72k
        ptr = portbuf;
1680
1.72k
      }
1681
1.73k
    }
1682
43.4k
    else if((flags & CURLU_DEFAULT_PORT) && u->scheme) {
1683
      /* there is no stored port number, but asked to deliver
1684
         a default one for the scheme */
1685
0
      const struct Curl_scheme *h = Curl_get_scheme(u->scheme);
1686
0
      if(h) {
1687
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1688
0
        ptr = portbuf;
1689
0
      }
1690
0
    }
1691
45.1k
    break;
1692
176k
  case CURLUPART_PATH:
1693
176k
    ptr = u->path;
1694
176k
    if(!ptr)
1695
133k
      ptr = "/";
1696
176k
    break;
1697
176k
  case CURLUPART_QUERY:
1698
176k
    ptr = u->query;
1699
176k
    ifmissing = CURLUE_NO_QUERY;
1700
176k
    plusdecode = flags & CURLU_URLDECODE;
1701
176k
    if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY))
1702
      /* there was a blank query and the user do not ask for it */
1703
23
      ptr = NULL;
1704
176k
    break;
1705
0
  case CURLUPART_FRAGMENT:
1706
0
    ptr = u->fragment;
1707
0
    ifmissing = CURLUE_NO_FRAGMENT;
1708
0
    if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY)
1709
      /* there was a blank fragment and the user asks for it */
1710
0
      ptr = "";
1711
0
    break;
1712
356k
  case CURLUPART_URL:
1713
356k
    return urlget_url(u, part, flags);
1714
0
  default:
1715
0
    ptr = NULL;
1716
0
    break;
1717
2.07M
  }
1718
1.63M
  if(ptr)
1719
641k
    return urlget_format(u, what, ptr, part, plusdecode, flags);
1720
1721
989k
  return ifmissing;
1722
1.63M
}
1723
1724
static CURLUcode set_url_scheme(CURLU *u, const char *scheme,
1725
                                unsigned int flags)
1726
1
{
1727
1
  size_t plen = strlen(scheme);
1728
1
  const struct Curl_scheme *h = NULL;
1729
1
  if((plen > MAX_SCHEME_LEN) || (plen < 1))
1730
    /* too long or too short */
1731
0
    return CURLUE_BAD_SCHEME;
1732
  /* verify that it is a fine scheme */
1733
1
  h = Curl_get_scheme(scheme);
1734
1
  if(!(flags & CURLU_NON_SUPPORT_SCHEME) && (!h || !h->run))
1735
0
    return CURLUE_UNSUPPORTED_SCHEME;
1736
1
  if(!h) {
1737
0
    const char *s = scheme;
1738
0
    if(ISALPHA(*s)) {
1739
      /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
1740
0
      s++;
1741
0
      while(--plen) {
1742
0
        if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.'))
1743
0
          s++; /* fine */
1744
0
        else
1745
0
          return CURLUE_BAD_SCHEME;
1746
0
      }
1747
0
    }
1748
0
    else
1749
0
      return CURLUE_BAD_SCHEME;
1750
0
  }
1751
1
  u->guessed_scheme = FALSE;
1752
1
  return CURLUE_OK;
1753
1
}
1754
1755
static CURLUcode set_url_port(CURLU *u, const char *provided_port)
1756
1.56k
{
1757
1.56k
  curl_off_t port;
1758
1.56k
  if(!ISDIGIT(provided_port[0]))
1759
    /* not a number */
1760
0
    return CURLUE_BAD_PORT_NUMBER;
1761
1.56k
  if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port)
1762
    /* weirdly provided number, not good! */
1763
0
    return CURLUE_BAD_PORT_NUMBER;
1764
1.56k
  u->portnum = (uint16_t)port;
1765
1.56k
  u->port_present = TRUE;
1766
1.56k
  return CURLUE_OK;
1767
1.56k
}
1768
1769
static CURLUcode set_url(CURLU *u, const char *url, size_t part_size,
1770
                         unsigned int flags)
1771
301k
{
1772
  /*
1773
   * Allow a new URL to replace the existing (if any) contents.
1774
   *
1775
   * If the existing contents is enough for a URL, allow a relative URL to
1776
   * replace it.
1777
   */
1778
301k
  CURLUcode uc;
1779
301k
  char *oldurl = NULL;
1780
1781
301k
  if(!part_size) {
1782
    /* a blank URL is not a valid URL unless we already have a complete one
1783
       and this is a redirect */
1784
3.63k
    uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1785
3.63k
    if(!uc) {
1786
      /* success, meaning the "" is a fine relative URL, and the new URL
1787
         inherits scheme/authority/path/query, but not fragment, from the
1788
         existing URL (RFC 3986 section 5.2.2) */
1789
0
      curlx_safefree(u->fragment);
1790
0
      u->fragment_present = FALSE;
1791
0
      curlx_free(oldurl);
1792
0
      return CURLUE_OK;
1793
0
    }
1794
3.63k
    if(uc == CURLUE_OUT_OF_MEMORY)
1795
0
      return uc;
1796
3.63k
    return CURLUE_MALFORMED_INPUT;
1797
3.63k
  }
1798
1799
  /* if the new URL is absolute replace the existing with the new. */
1800
297k
  if(Curl_is_absolute_url(url, NULL, 0,
1801
297k
                          flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME)))
1802
161k
    return parseurl_and_replace(url, u, flags);
1803
1804
  /* if the old URL is incomplete (we cannot get an absolute URL in
1805
     'oldurl'), replace the existing with the new.
1806
     Always include "scheme://" to make the URL "complete" */
1807
  /* Preserve empty query/fragment separators: they affect where relative
1808
     references splice into the base URL. */
1809
136k
  uc = curl_url_get(u, CURLUPART_URL, &oldurl,
1810
136k
                    (flags & ~CURLU_NO_GUESS_SCHEME) | CURLU_GET_EMPTY);
1811
136k
  if(uc == CURLUE_OUT_OF_MEMORY)
1812
0
    return uc;
1813
136k
  else if(uc)
1814
111k
    return parseurl_and_replace(url, u, flags);
1815
1816
24.2k
  DEBUGASSERT(oldurl); /* it is set here */
1817
  /* apply the relative part to create a new URL */
1818
24.2k
  uc = redirect_url(oldurl, url, u, flags);
1819
24.2k
  curlx_free(oldurl);
1820
24.2k
  return uc;
1821
24.2k
}
1822
1823
static CURLUcode urlset_clear(CURLU *u, CURLUPart what)
1824
26.6k
{
1825
26.6k
  switch(what) {
1826
0
  case CURLUPART_URL:
1827
0
    free_urlhandle(u);
1828
0
    memset(u, 0, sizeof(struct Curl_URL));
1829
0
    break;
1830
0
  case CURLUPART_SCHEME:
1831
0
    curlx_safefree(u->scheme);
1832
0
    u->guessed_scheme = FALSE;
1833
0
    break;
1834
7.98k
  case CURLUPART_USER:
1835
7.98k
    curlx_safefree(u->user);
1836
7.98k
    break;
1837
7.98k
  case CURLUPART_PASSWORD:
1838
7.98k
    curlx_strzero(u->password);
1839
7.98k
    curlx_safefree(u->password);
1840
7.98k
    break;
1841
0
  case CURLUPART_OPTIONS:
1842
0
    curlx_safefree(u->options);
1843
0
    break;
1844
0
  case CURLUPART_HOST:
1845
0
    curlx_safefree(u->host);
1846
0
    break;
1847
0
  case CURLUPART_ZONEID:
1848
0
    curlx_safefree(u->zoneid);
1849
0
    break;
1850
0
  case CURLUPART_PORT:
1851
0
    u->portnum = 0;
1852
0
    u->port_present = FALSE;
1853
0
    break;
1854
0
  case CURLUPART_PATH:
1855
0
    curlx_safefree(u->path);
1856
0
    break;
1857
0
  case CURLUPART_QUERY:
1858
0
    curlx_safefree(u->query);
1859
0
    u->query_present = FALSE;
1860
0
    break;
1861
10.6k
  case CURLUPART_FRAGMENT:
1862
10.6k
    curlx_safefree(u->fragment);
1863
10.6k
    u->fragment_present = FALSE;
1864
10.6k
    break;
1865
0
  default:
1866
0
    return CURLUE_UNKNOWN_PART;
1867
26.6k
  }
1868
26.6k
  return CURLUE_OK;
1869
26.6k
}
1870
1871
static bool allowed_in_path(unsigned char x)
1872
0
{
1873
0
  switch(x) {
1874
0
  case '!':
1875
0
  case '$':
1876
0
  case '&':
1877
0
  case '\'':
1878
0
  case '(':
1879
0
  case ')':
1880
0
  case '{':
1881
0
  case '}':
1882
0
  case '[':
1883
0
  case ']':
1884
0
  case '*':
1885
0
  case '+':
1886
0
  case ',':
1887
0
  case ';':
1888
0
  case '=':
1889
0
  case ':':
1890
0
  case '@':
1891
0
  case '/':
1892
0
    return TRUE;
1893
0
  }
1894
0
  return FALSE;
1895
0
}
1896
1897
static CURLUcode url_encode_part(struct dynbuf *encp,
1898
                                 const char *part,
1899
                                 bool plusencode,
1900
                                 bool pathmode,
1901
                                 bool equalsencode)
1902
280
{
1903
280
  const unsigned char *i;
1904
1905
1.06M
  for(i = (const unsigned char *)part; *i; i++) {
1906
1.06M
    CURLcode result;
1907
1.06M
    if((*i == ' ') && plusencode)
1908
0
      result = curlx_dyn_addn(encp, "+", 1);
1909
1.06M
    else if(ISUNRESERVED(*i) ||
1910
634k
            (pathmode && allowed_in_path(*i)) ||
1911
634k
            ((*i == '=') && equalsencode)) {
1912
427k
      if((*i == '=') && equalsencode)
1913
        /* only skip the first equals sign */
1914
0
        equalsencode = FALSE;
1915
427k
      result = curlx_dyn_addn(encp, i, 1);
1916
427k
    }
1917
634k
    else {
1918
634k
      unsigned char out[3] = { '%' };
1919
634k
      Curl_hexbyte(&out[1], *i);
1920
634k
      result = curlx_dyn_addn(encp, out, 3);
1921
634k
    }
1922
1.06M
    if(result)
1923
0
      return cc2cu(result);
1924
1.06M
  }
1925
280
  return CURLUE_OK;
1926
280
}
1927
1928
static CURLUcode url_uppercasehex_part(struct dynbuf *encp,
1929
                                       const char *part)
1930
1
{
1931
1
  char *p;
1932
1
  CURLcode result = curlx_dyn_add(encp, part);
1933
1
  if(result)
1934
0
    return cc2cu(result);
1935
1
  p = curlx_dyn_ptr(encp);
1936
6
  while(*p) {
1937
    /* make sure percent encoded are upper case */
1938
5
    if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
1939
0
       (ISLOWER(p[1]) || ISLOWER(p[2]))) {
1940
0
      p[1] = Curl_raw_toupper(p[1]);
1941
0
      p[2] = Curl_raw_toupper(p[2]);
1942
0
      p += 3;
1943
0
    }
1944
5
    else
1945
5
      p++;
1946
5
  }
1947
1
  return CURLUE_OK;
1948
1
}
1949
1950
static CURLUcode url_append_query(CURLU *u, struct dynbuf *encp)
1951
0
{
1952
  /* Append the 'encp' string onto the old query. Add a '&' separator if none
1953
     is already present at the end of the existing query */
1954
1955
0
  size_t querylen = u->query ? strlen(u->query) : 0;
1956
0
  bool addamperand = querylen && (u->query[querylen - 1] != '&');
1957
0
  if(querylen) {
1958
0
    struct dynbuf qbuf;
1959
0
    CURLcode result;
1960
0
    const char *newp = curlx_dyn_ptr(encp);
1961
0
    curlx_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH);
1962
1963
    /* add original query */
1964
0
    result = curlx_dyn_addn(&qbuf, u->query, querylen);
1965
0
    if(!result && addamperand)
1966
      /* add ampersand */
1967
0
      result = curlx_dyn_addn(&qbuf, "&", 1);
1968
0
    if(!result)
1969
      /* add new query part */
1970
0
      result = curlx_dyn_add(&qbuf, newp);
1971
0
    if(result)
1972
0
      goto nomem;
1973
0
    curlx_dyn_free(encp);
1974
0
    curlx_free(u->query);
1975
0
    u->query = curlx_dyn_ptr(&qbuf);
1976
0
    return CURLUE_OK;
1977
0
nomem:
1978
0
    curlx_dyn_free(encp);
1979
0
    return cc2cu(result);
1980
0
  }
1981
0
  else {
1982
0
    curlx_free(u->query);
1983
0
    u->query = curlx_dyn_ptr(encp);
1984
0
  }
1985
0
  return CURLUE_OK;
1986
0
}
1987
1988
static CURLUcode url_sethost(CURLU *u, struct dynbuf *encp,
1989
                             bool urlencode,
1990
                             unsigned int flags)
1991
0
{
1992
0
  size_t n = curlx_dyn_len(encp);
1993
0
  bool bad = FALSE;
1994
0
  char *newp = curlx_dyn_ptr(encp);
1995
0
  if(!n)
1996
    /* an empty hostname is okay if told so */
1997
0
    bad = (flags & CURLU_NO_AUTHORITY) ? FALSE : TRUE;
1998
0
  else if(!urlencode) {
1999
    /* if the hostname part was not URL encoded here, it was set already URL
2000
       encoded so we need to decode it to check */
2001
0
    size_t dlen;
2002
0
    char *decoded = NULL;
2003
0
    CURLcode result = Curl_urldecode(newp, n, &decoded, &dlen, REJECT_CTRL);
2004
0
    if(result || hostname_check(u, decoded, dlen))
2005
0
      bad = TRUE;
2006
0
    curlx_free(decoded);
2007
0
  }
2008
0
  else if(hostname_check(u, newp, n))
2009
0
    bad = TRUE;
2010
0
  if(bad) {
2011
0
    curlx_dyn_free(encp);
2012
0
    return CURLUE_BAD_HOSTNAME;
2013
0
  }
2014
0
  return CURLUE_OK;
2015
0
}
2016
2017
CURLUcode curl_url_set(CURLU *u, CURLUPart what,
2018
                       const char *part, unsigned int flags)
2019
329k
{
2020
329k
  char **storep = NULL;
2021
329k
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
2022
329k
  bool plusencode = FALSE;
2023
329k
  bool pathmode = FALSE;
2024
329k
  bool leadingslash = FALSE;
2025
329k
  bool appendquery = FALSE;
2026
329k
  bool equalsencode = FALSE;
2027
329k
  size_t nalloc;
2028
2029
329k
  if(!u)
2030
0
    return CURLUE_BAD_HANDLE;
2031
329k
  if(!part)
2032
    /* setting a part to NULL clears it */
2033
26.6k
    return urlset_clear(u, what);
2034
2035
302k
  nalloc = strlen(part);
2036
302k
  if(nalloc > CURL_MAX_INPUT_LENGTH)
2037
    /* excessive input length */
2038
0
    return CURLUE_MALFORMED_INPUT;
2039
2040
302k
  switch(what) {
2041
1
  case CURLUPART_SCHEME: {
2042
1
    CURLUcode status = set_url_scheme(u, part, flags);
2043
1
    if(status)
2044
0
      return status;
2045
1
    storep = &u->scheme;
2046
1
    urlencode = FALSE; /* never */
2047
1
    break;
2048
1
  }
2049
140
  case CURLUPART_USER:
2050
140
    storep = &u->user;
2051
140
    break;
2052
140
  case CURLUPART_PASSWORD:
2053
140
    storep = &u->password;
2054
140
    break;
2055
0
  case CURLUPART_OPTIONS:
2056
0
    storep = &u->options;
2057
0
    break;
2058
0
  case CURLUPART_HOST:
2059
0
    storep = &u->host;
2060
0
    curlx_safefree(u->zoneid);
2061
0
    break;
2062
0
  case CURLUPART_ZONEID:
2063
0
    storep = &u->zoneid;
2064
0
    break;
2065
1.56k
  case CURLUPART_PORT:
2066
1.56k
    return set_url_port(u, part);
2067
0
  case CURLUPART_PATH:
2068
0
    pathmode = TRUE;
2069
0
    leadingslash = TRUE; /* enforce */
2070
0
    storep = &u->path;
2071
0
    break;
2072
0
  case CURLUPART_QUERY:
2073
0
    plusencode = urlencode;
2074
0
    appendquery = (flags & CURLU_APPENDQUERY) ? 1 : 0;
2075
0
    equalsencode = appendquery;
2076
0
    storep = &u->query;
2077
0
    u->query_present = TRUE;
2078
0
    break;
2079
0
  case CURLUPART_FRAGMENT:
2080
0
    storep = &u->fragment;
2081
0
    u->fragment_present = TRUE;
2082
0
    break;
2083
301k
  case CURLUPART_URL:
2084
301k
    return set_url(u, part, nalloc, flags);
2085
0
  default:
2086
0
    return CURLUE_UNKNOWN_PART;
2087
302k
  }
2088
281
  DEBUGASSERT(storep);
2089
281
  {
2090
281
    const char *newp = NULL;
2091
281
    struct dynbuf enc;
2092
281
    CURLUcode status;
2093
281
    curlx_dyn_init(&enc, (nalloc * 3) + 1 + leadingslash);
2094
2095
281
    if(leadingslash && (part[0] != '/')) {
2096
0
      CURLcode result = curlx_dyn_addn(&enc, "/", 1);
2097
0
      if(result)
2098
0
        return cc2cu(result);
2099
0
    }
2100
281
    if(urlencode)
2101
280
      status = url_encode_part(&enc, part, plusencode, pathmode, equalsencode);
2102
1
    else
2103
1
      status = url_uppercasehex_part(&enc, part);
2104
281
    if(!status) {
2105
281
      newp = curlx_dyn_ptr(&enc);
2106
2107
281
      if(appendquery && newp)
2108
0
        return url_append_query(u, &enc);
2109
281
      else if(what == CURLUPART_HOST)
2110
0
        status = url_sethost(u, &enc, urlencode, flags);
2111
281
    }
2112
281
    if(status)
2113
0
      return status;
2114
2115
281
    if(what == CURLUPART_PASSWORD)
2116
140
      curlx_strzero(*storep);
2117
281
    curlx_free(*storep);
2118
281
    *storep = (char *)CURL_UNCONST(newp);
2119
281
  }
2120
0
  return CURLUE_OK;
2121
281
}
2122
2123
bool Curl_url_same_origin(CURLU *base, CURLU *href)
2124
27.7k
{
2125
27.7k
  const struct Curl_scheme *s = NULL;
2126
2127
  /* base must be an absolute URL */
2128
27.7k
  if(!base->scheme || !base->host)
2129
0
    return FALSE;
2130
27.7k
  if(href->scheme && !curl_strequal(base->scheme, href->scheme))
2131
39
    return FALSE;
2132
27.6k
  if(href->host) {
2133
27.6k
    if(!curl_strequal(base->host, href->host))
2134
277
      return FALSE;
2135
2136
27.4k
    if(base->port_present != href->port_present) {
2137
      /* one is present, one is not */
2138
113
      s = Curl_get_scheme(base->scheme);
2139
113
      if(!s) /* Cannot match default port for unknown scheme */
2140
0
        return FALSE;
2141
      /* to match, the present one must be the default port */
2142
113
      if((base->port_present && (base->portnum != s->defport)) ||
2143
107
         (href->port_present && (href->portnum != s->defport)))
2144
109
        return FALSE;
2145
113
    }
2146
27.2k
    else if(base->portnum != href->portnum) /* both present or missing */
2147
27
      return FALSE;
2148
2149
27.2k
    if(!curl_strequal(base->zoneid ? base->zoneid : "",
2150
27.2k
                      href->zoneid ? href->zoneid : ""))
2151
0
      return FALSE;
2152
27.2k
  }
2153
0
  else if(href->port_present) /* no host in href, then there must be no port */
2154
0
    return FALSE;
2155
27.2k
  return TRUE;
2156
27.6k
}
2157
2158
CURLUcode Curl_url_get_port(CURLU *u, uint16_t *pport)
2159
174k
{
2160
174k
  if(u->port_present) {
2161
3.15k
    *pport = u->portnum;
2162
3.15k
    return CURLUE_OK;
2163
3.15k
  }
2164
171k
  else if(u->scheme) {
2165
171k
    const struct Curl_scheme *s = Curl_get_scheme(u->scheme);
2166
171k
    if(s && s->defport) {
2167
169k
      *pport = s->defport;
2168
169k
      return CURLUE_OK;
2169
169k
    }
2170
171k
  }
2171
1.99k
  *pport = 0;
2172
1.99k
  return CURLUE_NO_PORT;
2173
174k
}