Coverage Report

Created: 2026-09-01 06:58

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
3.36k
  ((('a' <= (str)[0] && (str)[0] <= 'z') ||                \
50
3.36k
    ('A' <= (str)[0] && (str)[0] <= 'Z')) &&               \
51
3.36k
   ((str)[1] == ':' || (str)[1] == '|') &&                 \
52
3.36k
   ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
53
54
/* scheme is not URL encoded, the longest libcurl supported ones are... */
55
25.4k
#define MAX_SCHEME_LEN 40
56
207
#define MAX_ZONEID_LEN 16
57
58
/* characters not allowed in hostnames */
59
1.48k
#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
8.83k
{
74
8.83k
  curlx_free(u->scheme);
75
8.83k
  curlx_free(u->user);
76
8.83k
  curlx_strzero(u->password);
77
8.83k
  curlx_free(u->password);
78
8.83k
  curlx_free(u->options);
79
8.83k
  curlx_free(u->host);
80
8.83k
  curlx_free(u->zoneid);
81
8.83k
  curlx_free(u->path);
82
8.83k
  curlx_free(u->query);
83
8.83k
  curlx_free(u->fragment);
84
8.83k
}
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
0
{
92
  /* Find the start of the hostname */
93
0
  const char *sep = strstr(url, "//");
94
0
  if(!sep)
95
0
    sep = url;
96
0
  else
97
0
    sep += 2;
98
99
  /* Find first / or ? */
100
0
  while(*sep && *sep != '/' && *sep != '?')
101
0
    sep++;
102
103
0
  return sep;
104
0
}
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
3.05k
{
134
  /* we must add this with whitespace-replacing */
135
3.05k
  const unsigned char *iptr;
136
3.05k
  const unsigned char *host_sep = (const unsigned char *)url;
137
3.05k
  CURLcode result = CURLE_OK;
138
139
3.05k
  DEBUGASSERT((query >= QUERY_NO) && (query <= QUERY_YES));
140
141
3.05k
  if(!relative) {
142
0
    size_t n;
143
0
    host_sep = (const unsigned char *)find_host_sep(url);
144
145
    /* output the first piece as-is */
146
0
    n = (const char *)host_sep - url;
147
0
    result = curlx_dyn_addn(o, url, n);
148
0
    len -= n;
149
0
  }
150
151
29.0M
  for(iptr = host_sep; len && !result; iptr++, len--) {
152
29.0M
    if(*iptr == ' ') {
153
0
      if(query != QUERY_YES)
154
0
        result = curlx_dyn_addn(o, "%20", 3);
155
0
      else
156
0
        result = curlx_dyn_addn(o, "+", 1);
157
0
    }
158
29.0M
    else if((*iptr < ' ') || (*iptr >= 0x7f)) {
159
23.9M
      unsigned char out[3] = { '%' };
160
23.9M
      Curl_hexbyte(&out[1], *iptr);
161
23.9M
      result = curlx_dyn_addn(o, out, 3);
162
23.9M
    }
163
5.09M
    else if(*iptr == '%' && (len >= 3) &&
164
3.55M
            ISXDIGIT(iptr[1]) && ISXDIGIT(iptr[2]) &&
165
76.0k
            (ISLOWER(iptr[1]) || ISLOWER(iptr[2]))) {
166
      /* uppercase it */
167
3.70k
      unsigned char hex = (unsigned char)((curlx_hexval(iptr[1]) << 4) |
168
3.70k
                                          curlx_hexval(iptr[2]));
169
3.70k
      unsigned char out[3] = { '%' };
170
3.70k
      Curl_hexbyte(&out[1], hex);
171
3.70k
      result = curlx_dyn_addn(o, out, 3);
172
3.70k
      iptr += 2;
173
3.70k
      len -= 2;
174
3.70k
    }
175
5.09M
    else {
176
5.09M
      result = curlx_dyn_addn(o, iptr, 1);
177
5.09M
      if(*iptr == '?' && (query == QUERY_NOT_YET))
178
0
        query = QUERY_YES;
179
5.09M
    }
180
29.0M
  }
181
182
3.05k
  if(result)
183
0
    return cc2cu(result);
184
3.05k
  return CURLUE_OK;
185
3.05k
}
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
8.41k
{
198
8.41k
  size_t i = 0;
199
8.41k
  DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
200
8.41k
  (void)buflen; /* only used in debug-builds */
201
8.41k
  if(buf)
202
4.12k
    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
8.41k
  if(ISALPHA(url[0]))
208
25.4k
    for(i = 1; i < MAX_SCHEME_LEN; ++i) {
209
25.3k
      char s = url[i];
210
25.3k
      if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.'))) {
211
        /* RFC 3986 3.1 explains:
212
           scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
213
         */
214
19.7k
      }
215
5.56k
      else {
216
5.56k
        break;
217
5.56k
      }
218
25.3k
    }
219
8.41k
  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
4.20k
    size_t len = i;
226
4.20k
    if(buf) {
227
2.10k
      Curl_strntolower(buf, url, i);
228
2.10k
      buf[i] = 0;
229
2.10k
    }
230
4.20k
    return len;
231
4.20k
  }
232
4.20k
  return 0;
233
8.41k
}
234
235
/* scan for byte values <= 31, 127 and sometimes space */
236
CURLUcode Curl_junkscan(const char *url, size_t *urllen, bool allowspace)
237
4.16k
{
238
4.16k
  size_t n = strlen(url);
239
4.16k
  size_t i;
240
4.16k
  unsigned char control;
241
4.16k
  const unsigned char *p = (const unsigned char *)url;
242
4.16k
  if(n > CURL_MAX_INPUT_LENGTH)
243
0
    return CURLUE_MALFORMED_INPUT;
244
245
4.16k
  control = allowspace ? 0x1f : 0x20;
246
46.8M
  for(i = 0; i < n; i++) {
247
46.8M
    if(p[i] <= control || p[i] == 127)
248
37
      return CURLUE_MALFORMED_INPUT;
249
46.8M
  }
250
4.12k
  *urllen = n;
251
4.12k
  return CURLUE_OK;
252
4.16k
}
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
2.37k
{
273
2.37k
  CURLUcode ures = CURLUE_OK;
274
2.37k
  CURLcode result;
275
2.37k
  char *userp = NULL;
276
2.37k
  char *passwdp = NULL;
277
2.37k
  char *optionsp = NULL;
278
2.37k
  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
2.37k
  const char *ptr;
288
289
2.37k
  DEBUGASSERT(login);
290
291
2.37k
  *hostname_offset = 0;
292
2.37k
  ptr = memchr(login, '@', len);
293
2.37k
  if(!ptr)
294
2.07k
    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
299
  ptr++;
300
301
  /* if this is a known scheme, get some details */
302
299
  if(u->scheme)
303
191
    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
299
  result = Curl_parse_login_details(login, ptr - login - 1,
308
299
                                    &userp, &passwdp,
309
299
                                    (h && (h->flags & PROTOPT_URLOPTIONS)) ?
310
299
                                    &optionsp : NULL);
311
299
  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
299
  if(userp) {
319
299
    if(flags & CURLU_DISALLOW_USER) {
320
      /* Option DISALLOW_USER is set and URL contains username. */
321
1
      ures = CURLUE_USER_NOT_ALLOWED;
322
1
      goto out;
323
1
    }
324
298
    curlx_free(u->user);
325
298
    u->user = userp;
326
298
  }
327
328
298
  if(passwdp) {
329
44
    curlx_strzero(u->password);
330
44
    curlx_free(u->password);
331
44
    u->password = passwdp;
332
44
  }
333
334
298
  if(optionsp) {
335
7
    curlx_free(u->options);
336
7
    u->options = optionsp;
337
7
  }
338
339
  /* the hostname starts at this offset */
340
298
  *hostname_offset = ptr - login;
341
298
  return CURLUE_OK;
342
343
2.07k
out:
344
345
2.07k
  curlx_free(userp);
346
2.07k
  curlx_strzero(passwdp);
347
2.07k
  curlx_free(passwdp);
348
2.07k
  curlx_free(optionsp);
349
2.07k
  curlx_safefree(u->user);
350
2.07k
  curlx_strzero(u->password);
351
2.07k
  curlx_safefree(u->password);
352
2.07k
  curlx_safefree(u->options);
353
354
2.07k
  return ures;
355
299
}
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
2.37k
{
363
2.37k
  const char *portptr;
364
2.37k
  const char *hostname = curlx_dyn_ptr(host);
365
  /*
366
   * Find the end of an IPv6 address on the ']' ending bracket.
367
   */
368
2.37k
  u->portnum = 0;
369
2.37k
  u->port_present = FALSE;
370
2.37k
  if(hostname[0] == '[') {
371
244
    portptr = strchr(hostname, ']');
372
244
    if(!portptr)
373
7
      return CURLUE_BAD_IPV6;
374
237
    portptr++;
375
    /* this is a RFC2732-style specified IP-address */
376
237
    if(*portptr) {
377
9
      if(*portptr != ':')
378
7
        return CURLUE_BAD_PORT_NUMBER;
379
9
    }
380
228
    else
381
228
      portptr = NULL;
382
237
  }
383
2.12k
  else
384
2.12k
    portptr = strchr(hostname, ':');
385
386
2.35k
  if(portptr) {
387
195
    curl_off_t port;
388
195
    size_t keep = portptr - hostname;
389
195
    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
195
    curlx_dyn_setlen(host, keep);
398
195
    portptr++;
399
195
    if(!*portptr)
400
102
      return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
401
93
    if(*portptr == '\\')
402
2
      return CURLUE_BACKSLASH;
403
91
    rc = curlx_str_number(&portptr, &port, 0xffff);
404
91
    if(rc)
405
42
      return CURLUE_BAD_PORT_NUMBER;
406
49
    else if(*portptr == '\\')
407
1
      return CURLUE_BACKSLASH;
408
48
    else if(*portptr)
409
13
      return CURLUE_BAD_PORT_NUMBER;
410
411
35
    u->portnum = (uint16_t)port;
412
35
    u->port_present = TRUE;
413
35
  }
414
415
2.19k
  return CURLUE_OK;
416
2.35k
}
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
262
{
428
262
  size_t len;
429
262
  DEBUGASSERT(*hostname == '[');
430
262
  if(hlen < 4) /* '[::]' is the shortest possible valid string */
431
4
    return CURLUE_BAD_IPV6;
432
258
  hostname++;
433
258
  hlen -= 2;
434
435
  /* only valid IPv6 letters are ok */
436
258
  len = strspn(hostname, "0123456789abcdefABCDEF:.");
437
438
258
  if(hlen != len) {
439
86
    hlen = len;
440
86
    if(hostname[len] == '%') {
441
      /* this could now be '%[zone id]' */
442
63
      char zoneid[MAX_ZONEID_LEN];
443
63
      int i = 0;
444
63
      char *h = &hostname[len + 1];
445
      /* pass '25' if present and is a URL encoded percent sign */
446
63
      if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
447
9
        h += 2;
448
263
      while(*h && (*h != ']') && (i < (MAX_ZONEID_LEN - 1)))
449
200
        zoneid[i++] = *h++;
450
63
      if(!i || (']' != *h))
451
20
        return CURLUE_BAD_IPV6;
452
43
      zoneid[i] = 0;
453
43
      u->zoneid = curlx_strdup(zoneid);
454
43
      if(!u->zoneid)
455
0
        return CURLUE_OUT_OF_MEMORY;
456
43
      hostname[len] = ']'; /* insert end bracket */
457
43
      hostname[len + 1] = 0; /* terminate the hostname */
458
43
    }
459
23
    else
460
23
      return CURLUE_BAD_IPV6;
461
    /* hostname is fine */
462
86
  }
463
464
  /* Normalize the IPv6 address */
465
215
  {
466
215
    char dest[16]; /* fits a binary IPv6 address */
467
215
    hostname[hlen] = 0; /* end the address there */
468
215
    if(curlx_inet_pton(AF_INET6, hostname, dest) != 1)
469
84
      return CURLUE_BAD_IPV6;
470
131
    if(!curlx_inet_ntop(AF_INET6, dest, hostname, hlen + 1)) {
471
107
      hlen = strlen(hostname); /* might be shorter now */
472
107
      hostname[hlen + 1] = 0;
473
107
    }
474
131
    hostname[hlen] = ']'; /* restore ending bracket */
475
131
  }
476
0
  return CURLUE_OK;
477
215
}
478
479
static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
480
                                size_t hlen) /* length of hostname */
481
1.48k
{
482
1.48k
  size_t len;
483
1.48k
  DEBUGASSERT(hostname);
484
485
1.48k
  if(!hlen)
486
0
    return CURLUE_NO_HOST;
487
1.48k
  else if(hostname[0] == '[')
488
0
    return ipv6_parse(u, hostname, hlen);
489
1.48k
  else {
490
    /* letters from the second string are not ok */
491
1.48k
    len = strcspn(hostname, HOSTNAME_INVALID_CHARS);
492
1.48k
    if(hlen != len)
493
      /* hostname with bad content */
494
138
      return CURLUE_BAD_HOSTNAME;
495
1.35k
    else if((hlen >= 2) &&
496
704
            (hostname[hlen - 1] == '.') && (hostname[hlen - 2] == '.'))
497
      /* more than one trailing dot is not allowed */
498
9
      return CURLUE_BAD_HOSTNAME;
499
1.34k
    else if((hlen == 1) && (hostname[0] == '.'))
500
      /* a single dot alone is not allowed */
501
2
      return CURLUE_BAD_HOSTNAME;
502
1.48k
  }
503
1.33k
  return CURLUE_OK;
504
1.48k
}
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
2.08k
{
526
2.08k
  bool done = FALSE;
527
2.08k
  int n = 0;
528
2.08k
  const char *c = curlx_dyn_ptr(host);
529
2.08k
  unsigned int parts[4] = { 0, 0, 0, 0 };
530
2.08k
  CURLcode result = CURLE_OK;
531
532
2.08k
  if(*c == '[')
533
262
    return HOST_IPV6;
534
535
3.31k
  while(!done) {
536
2.68k
    int rc;
537
2.68k
    curl_off_t l;
538
2.68k
    if(*c == '0') {
539
629
      if(Curl_raw_tolower(c[1]) == 'x') {
540
229
        c += 2; /* skip the prefix */
541
229
        rc = curlx_str_hex(&c, &l, UINT_MAX);
542
229
        if(rc)
543
6
          return HOST_NAME;
544
229
      }
545
400
      else
546
400
        rc = curlx_str_octal(&c, &l, UINT_MAX);
547
629
    }
548
2.05k
    else
549
2.05k
      rc = curlx_str_number(&c, &l, UINT_MAX);
550
551
2.67k
    if(rc) {
552
1.15k
      if(!n || (rc != STRE_NO_NUM) || *c)
553
1.14k
        return HOST_NAME;
554
5
      n--;
555
5
    }
556
1.52k
    else
557
1.52k
      parts[n] = (unsigned int)l;
558
559
1.53k
    switch(*c) {
560
864
    case '.':
561
864
      if(n == 3) {
562
2
        if(c[1])
563
          /* something follows this dot */
564
1
          return HOST_NAME;
565
1
        done = TRUE;
566
1
      }
567
862
      else {
568
862
        n++;
569
862
        c++;
570
862
      }
571
863
      break;
572
573
863
    case '\0':
574
632
      done = TRUE;
575
632
      break;
576
577
36
    default:
578
36
      return HOST_NAME;
579
1.53k
    }
580
1.53k
  }
581
582
633
  switch(n) {
583
240
  case 0: /* a -- 32 bits */
584
240
    curlx_dyn_reset(host);
585
586
240
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
587
240
                            (parts[0] >> 24),
588
240
                            ((parts[0] >> 16) & 0xff),
589
240
                            ((parts[0] >> 8) & 0xff),
590
240
                            (parts[0] & 0xff));
591
240
    break;
592
105
  case 1: /* a.b -- 8.24 bits */
593
105
    if((parts[0] > 0xff) || (parts[1] > 0xffffff))
594
57
      return HOST_NAME;
595
48
    curlx_dyn_reset(host);
596
48
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
597
48
                            parts[0],
598
48
                            ((parts[1] >> 16) & 0xff),
599
48
                            ((parts[1] >> 8) & 0xff),
600
48
                            (parts[1] & 0xff));
601
48
    break;
602
131
  case 2: /* a.b.c -- 8.8.16 bits */
603
131
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
604
96
      return HOST_NAME;
605
35
    curlx_dyn_reset(host);
606
35
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
607
35
                            parts[0],
608
35
                            parts[1],
609
35
                            ((parts[2] >> 8) & 0xff),
610
35
                            (parts[2] & 0xff));
611
35
    break;
612
157
  case 3: /* a.b.c.d -- 8.8.8.8 bits */
613
157
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
614
32
       (parts[3] > 0xff))
615
147
      return HOST_NAME;
616
10
    curlx_dyn_reset(host);
617
10
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
618
10
                            parts[0],
619
10
                            parts[1],
620
10
                            parts[2],
621
10
                            parts[3]);
622
10
    break;
623
633
  }
624
333
  if(result)
625
0
    return HOST_ERROR;
626
333
  return HOST_IPV4;
627
333
}
628
629
/* if necessary, replace the host content with a URL decoded version */
630
static CURLUcode urldecode_host(struct dynbuf *host)
631
2.08k
{
632
2.08k
  const char *per;
633
2.08k
  const char *hostname = curlx_dyn_ptr(host);
634
2.08k
  per = strchr(hostname, '%');
635
2.08k
  if(!per)
636
    /* nothing to decode */
637
1.89k
    return CURLUE_OK;
638
185
  else {
639
    /* encoded */
640
185
    size_t dlen;
641
185
    char *decoded;
642
185
    CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
643
185
                                     REJECT_CTRL);
644
185
    if(result)
645
1
      return CURLUE_BAD_HOSTNAME;
646
184
    curlx_dyn_reset(host);
647
184
    result = curlx_dyn_addn(host, decoded, dlen);
648
184
    curlx_free(decoded);
649
184
    if(result)
650
0
      return cc2cu(result);
651
184
  }
652
653
184
  return CURLUE_OK;
654
2.08k
}
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
2.37k
{
662
2.37k
  size_t offset;
663
2.37k
  CURLUcode uc;
664
2.37k
  CURLcode result;
665
666
  /*
667
   * Parse the login details and strip them out of the hostname.
668
   */
669
2.37k
  uc = parse_hostname_login(u, auth, authlen, flags, &offset);
670
2.37k
  if(uc)
671
1
    return uc;
672
673
2.37k
  result = curlx_dyn_addn(host, auth + offset, authlen - offset);
674
2.37k
  if(result) {
675
0
    uc = cc2cu(result);
676
0
    return uc;
677
0
  }
678
679
2.37k
  uc = parse_port(u, host, has_scheme);
680
681
2.37k
  if(!curlx_dyn_len(host))
682
    /* this makes no-host errors override port number problems */
683
235
    uc = CURLUE_NO_HOST;
684
2.37k
  if(!uc)
685
2.08k
    uc = urldecode_host(host);
686
2.37k
  if(uc)
687
290
    return uc;
688
689
2.08k
  switch(ipv4_normalize(host)) {
690
333
  case HOST_IPV4:
691
333
    break;
692
262
  case HOST_IPV6:
693
262
    uc = ipv6_parse(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
694
262
    break;
695
1.48k
  case HOST_NAME:
696
1.48k
    uc = hostname_check(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
697
1.48k
    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
2.08k
  }
705
706
2.08k
  return uc;
707
2.08k
}
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
5.97M
{
736
5.97M
  const char *p = *str;
737
5.97M
  if(*p == '.') {
738
348k
    (*str)++;
739
348k
    (*clen)--;
740
348k
    return TRUE;
741
348k
  }
742
5.62M
  else if((*clen >= 3) &&
743
5.61M
          (p[0] == '%') && (p[1] == '2') && ((p[2] | 0x20) == 'e')) {
744
104k
    *str += 3;
745
104k
    *clen -= 3;
746
104k
    return TRUE;
747
104k
  }
748
5.51M
  return FALSE;
749
5.97M
}
750
751
31.4M
#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
2.22k
{
756
  /* a single byte path cannot be cleaned up */
757
2.22k
  if(pn < 2)
758
597
    return FALSE;
759
4.92M
  while(pn) {
760
4.92M
    if(is_dot(&p, &pn)) {
761
      /* "./" or dot before end of string */
762
14.0k
      if(!pn || ISSLASH(*p))
763
415
        return TRUE;
764
      /* "../" or ".." before end of string */
765
13.6k
      else if(is_dot(&p, &pn) && (!pn || ISSLASH(*p)))
766
114
        return TRUE;
767
14.0k
    }
768
4.90M
    else {
769
4.90M
      p++;
770
4.90M
      pn--;
771
4.90M
    }
772
4.92M
  }
773
1.09k
  return FALSE;
774
1.62k
}
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
2.22k
{
795
2.22k
  struct dynbuf out;
796
2.22k
  CURLcode result = CURLE_OK;
797
798
  /* variables for leading dot checks */
799
2.22k
  const char *dinput = input;
800
2.22k
  size_t dlen = clen;
801
802
2.22k
  *outp = NULL;
803
2.22k
  if(!needs_dedotdot(input, clen))
804
1.69k
    return 0;
805
806
529
  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
529
  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
30.9M
  while(clen && !result) { /* until end of path content */
832
30.9M
    if(ISSLASH(*input)) {
833
781k
      const char *p = &input[1];
834
781k
      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
781k
      if(is_dot(&p, &blen)) {
839
352k
        if(!blen) { /* /. */
840
157
          result = curlx_dyn_addn(&out, "/", 1);
841
157
          break;
842
157
        }
843
352k
        else if(ISSLASH(*p)) { /* /./ */
844
99.9k
          input = p;
845
99.9k
          clen = blen;
846
99.9k
          continue;
847
99.9k
        }
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
252k
        else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) {
854
          /* remove the last segment from the output buffer */
855
68.7k
          size_t len = curlx_dyn_len(&out);
856
68.7k
          if(len) {
857
67.5k
            const char *ptr = curlx_dyn_ptr(&out);
858
67.5k
            const char *last = memrchr(ptr, '/', len);
859
67.5k
            if(last)
860
              /* trim the output at the slash */
861
67.5k
              curlx_dyn_setlen(&out, last - ptr);
862
67.5k
          }
863
864
68.7k
          if(blen) { /* /../ */
865
68.7k
            input = p;
866
68.7k
            clen = blen;
867
68.7k
            continue;
868
68.7k
          }
869
25
          result = curlx_dyn_addn(&out, "/", 1);
870
25
          break;
871
68.7k
        }
872
352k
      }
873
781k
    }
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
30.7M
    result = curlx_dyn_addn(&out, input, 1);
881
30.7M
    input++;
882
30.7M
    clen--;
883
30.7M
  }
884
529
end:
885
529
  if(!result) {
886
529
    if(curlx_dyn_len(&out))
887
529
      *outp = curlx_dyn_ptr(&out);
888
0
    else {
889
0
      *outp = curlx_strdup("");
890
0
      if(!*outp)
891
0
        return 1;
892
0
    }
893
529
  }
894
529
  return result ? 1 : 0; /* success */
895
529
}
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
1.70k
{
905
1.70k
  const char *path;
906
1.70k
  size_t pathlen;
907
908
1.70k
  *pathp = NULL;
909
1.70k
  *pathlenp = 0;
910
1.70k
  if(urllen <= 6)
911
    /* file:/ is not enough to actually be a complete file: URL */
912
2
    return CURLUE_BAD_FILE_URL;
913
914
  /* path has been allocated large enough to hold this */
915
1.70k
  path = &url[5];
916
1.70k
  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
1.70k
  if(path[0] != '/')
922
0
    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
1.70k
  if(path[1] == '/') {
931
    /* swallow the two slashes */
932
402
    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
402
    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
37
      if(checkprefix("localhost/", ptr) ||
954
36
         checkprefix("127.0.0.1/", ptr)) {
955
2
        ptr += 9; /* now points to the slash after the host */
956
2
      }
957
35
      else
958
        /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
959
           none */
960
35
        return CURLUE_BAD_FILE_URL;
961
37
    }
962
963
367
    path = ptr;
964
367
    pathlen = urllen - (ptr - url);
965
367
  }
966
967
1.66k
#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
1.66k
  if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
971
1.66k
     STARTS_WITH_URL_DRIVE_PREFIX(path)) {
972
    /* File drive letters are only accepted in MS-DOS/Windows */
973
19
    return CURLUE_BAD_FILE_URL;
974
19
  }
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
1.64k
  u->scheme = curlx_strdup("file");
984
1.64k
  if(!u->scheme)
985
0
    return CURLUE_OUT_OF_MEMORY;
986
987
1.64k
  *pathp = path;
988
1.64k
  *pathlenp = pathlen;
989
1.64k
  return CURLUE_OK;
990
1.64k
}
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
2.42k
{
996
  /* clear path */
997
2.42k
  const char *schemep = NULL;
998
999
2.42k
  if(schemelen) {
1000
397
    int num_slashes = 0;
1001
397
    const char *p = &url[schemelen + 1];
1002
397
    if(!Curl_get_scheme(schemebuf) && !(flags & CURLU_NON_SUPPORT_SCHEME))
1003
0
      return CURLUE_UNSUPPORTED_SCHEME;
1004
1005
397
    if(!ISSLASH(*p))
1006
      /* less than one */
1007
0
      return CURLUE_BAD_SLASHES;
1008
397
    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
397
    else {
1015
816
      while(ISSLASH(*p) && (num_slashes < 4)) {
1016
419
        p++;
1017
419
        num_slashes++;
1018
419
      }
1019
397
      if(num_slashes > 3)
1020
1
        return CURLUE_BAD_SLASHES;
1021
397
    }
1022
1023
396
    schemep = schemebuf;
1024
396
    *hostpp = p; /* hostname starts here */
1025
396
  }
1026
2.02k
  else {
1027
    /* no scheme! */
1028
1029
2.02k
    if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME)))
1030
0
      return CURLUE_BAD_SCHEME;
1031
1032
2.02k
    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
2.02k
    *hostpp = url;
1039
2.02k
  }
1040
1041
2.42k
  if(schemep) {
1042
396
    u->scheme = curlx_strdup(schemep);
1043
396
    if(!u->scheme)
1044
0
      return CURLUE_OUT_OF_MEMORY;
1045
396
  }
1046
2.42k
  return CURLUE_OK;
1047
2.42k
}
1048
1049
static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host)
1050
1.56k
{
1051
1.56k
  const char *hostname = curlx_dyn_ptr(host);
1052
1.56k
  const char *schemep = NULL;
1053
  /* legacy curl-style guess based on hostname */
1054
1.56k
  if(checkprefix("ftp.", hostname))
1055
10
    schemep = "ftp";
1056
1.55k
  else if(checkprefix("dict.", hostname))
1057
3
    schemep = "dict";
1058
1.55k
  else if(checkprefix("ldap.", hostname))
1059
2
    schemep = "ldap";
1060
1.55k
  else if(checkprefix("imap.", hostname))
1061
3
    schemep = "imap";
1062
1.54k
  else if(checkprefix("smtp.", hostname))
1063
2
    schemep = "smtp";
1064
1.54k
  else if(checkprefix("pop3.", hostname))
1065
2
    schemep = "pop3";
1066
1.54k
  else
1067
1.54k
    schemep = "http";
1068
1069
1.56k
  u->scheme = curlx_strdup(schemep);
1070
1.56k
  if(!u->scheme)
1071
0
    return CURLUE_OUT_OF_MEMORY;
1072
1073
1.56k
  u->guessed_scheme = TRUE;
1074
1.56k
  return CURLUE_OK;
1075
1.56k
}
1076
1077
static CURLUcode handle_fragment(CURLU *u, const char *fragment,
1078
                                 size_t fraglen, unsigned int flags)
1079
581
{
1080
581
  CURLUcode ures;
1081
581
  u->fragment_present = TRUE;
1082
581
  if(fraglen > 1) {
1083
    /* skip the leading '#' in the copy but include the null-terminator */
1084
15
    if(flags & CURLU_URLENCODE) {
1085
0
      struct dynbuf enc;
1086
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1087
0
      ures = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, QUERY_NO);
1088
0
      if(ures)
1089
0
        return ures;
1090
0
      u->fragment = curlx_dyn_ptr(&enc);
1091
0
    }
1092
15
    else {
1093
15
      u->fragment = curlx_memdup0(fragment + 1, fraglen - 1);
1094
15
      if(!u->fragment)
1095
0
        return CURLUE_OUT_OF_MEMORY;
1096
15
    }
1097
15
  }
1098
581
  return CURLUE_OK;
1099
581
}
1100
1101
static CURLUcode handle_query(CURLU *u, const char *query,
1102
                              size_t qlen, unsigned int flags)
1103
82
{
1104
82
  u->query_present = TRUE;
1105
82
  if(qlen > 1) {
1106
39
    if(flags & CURLU_URLENCODE) {
1107
0
      struct dynbuf enc;
1108
0
      CURLUcode ures;
1109
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1110
      /* skip the leading question mark */
1111
0
      ures = urlencode_str(&enc, query + 1, qlen - 1, TRUE, QUERY_YES);
1112
0
      if(ures)
1113
0
        return ures;
1114
0
      u->query = curlx_dyn_ptr(&enc);
1115
0
    }
1116
39
    else {
1117
39
      u->query = curlx_memdup0(query + 1, qlen - 1);
1118
39
      if(!u->query)
1119
0
        return CURLUE_OUT_OF_MEMORY;
1120
39
    }
1121
39
  }
1122
43
  else {
1123
    /* single byte query */
1124
43
    u->query = curlx_strdup("");
1125
43
    if(!u->query)
1126
0
      return CURLUE_OUT_OF_MEMORY;
1127
43
  }
1128
82
  return CURLUE_OK;
1129
82
}
1130
1131
static CURLUcode handle_path(CURLU *u, const char *path,
1132
                             size_t pathlen, unsigned int flags,
1133
                             bool is_file)
1134
3.45k
{
1135
3.45k
  CURLUcode ures;
1136
3.45k
  if(pathlen && (flags & CURLU_URLENCODE)) {
1137
0
    struct dynbuf enc;
1138
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1139
0
    ures = urlencode_str(&enc, path, pathlen, TRUE, QUERY_NO);
1140
0
    if(ures)
1141
0
      return ures;
1142
0
    pathlen = curlx_dyn_len(&enc);
1143
0
    path = u->path = curlx_dyn_ptr(&enc);
1144
0
  }
1145
1146
3.45k
  if(pathlen >= (size_t)(1 + !is_file)) {
1147
    /* paths for file:// scheme can be one byte, others need to be two */
1148
2.22k
    if(!u->path) {
1149
2.22k
      u->path = curlx_memdup0(path, pathlen);
1150
2.22k
      if(!u->path)
1151
0
        return CURLUE_OUT_OF_MEMORY;
1152
2.22k
      path = u->path;
1153
2.22k
    }
1154
0
    else if(flags & CURLU_URLENCODE)
1155
      /* it might have encoded more than the path so cut it */
1156
0
      u->path[pathlen] = 0;
1157
1158
2.22k
    if(!(flags & CURLU_PATH_AS_IS)) {
1159
      /* remove ../ and ./ sequences according to RFC3986 */
1160
2.22k
      char *dedot;
1161
2.22k
      int err = dedotdotify(path, pathlen, &dedot);
1162
2.22k
      if(err)
1163
0
        return CURLUE_OUT_OF_MEMORY;
1164
2.22k
      if(dedot) {
1165
529
        curlx_free(u->path);
1166
529
        u->path = dedot;
1167
529
      }
1168
2.22k
    }
1169
2.22k
  }
1170
3.45k
  return CURLUE_OK;
1171
3.45k
}
1172
1173
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
1174
4.16k
{
1175
4.16k
  const char *path;
1176
4.16k
  size_t pathlen;
1177
4.16k
  char schemebuf[MAX_SCHEME_LEN + 1];
1178
4.16k
  size_t schemelen = 0;
1179
4.16k
  size_t urllen;
1180
4.16k
  CURLUcode ures = CURLUE_OK;
1181
4.16k
  struct dynbuf host;
1182
4.16k
  bool is_file = FALSE;
1183
1184
4.16k
  DEBUGASSERT(url);
1185
1186
4.16k
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
1187
1188
4.16k
  ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE));
1189
4.16k
  if(ures)
1190
37
    goto fail;
1191
1192
4.12k
  schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
1193
4.12k
                                   flags & (CURLU_GUESS_SCHEME |
1194
4.12k
                                            CURLU_DEFAULT_SCHEME));
1195
1196
  /* handle the file: scheme */
1197
4.12k
  if(schemelen && !strcmp(schemebuf, "file")) {
1198
1.70k
    is_file = TRUE;
1199
1.70k
    ures = parse_file(url, urllen, u, &path, &pathlen);
1200
1.70k
  }
1201
2.42k
  else {
1202
2.42k
    const char *hostp = NULL;
1203
2.42k
    size_t hostlen;
1204
2.42k
    ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp);
1205
2.42k
    if(ures)
1206
1
      goto fail;
1207
1208
    /* find the end of the hostname + port number */
1209
2.42k
    hostlen = strcspn(hostp, "/?#");
1210
2.42k
    path = &hostp[hostlen];
1211
1212
    /* this pathlen also contains the query and the fragment */
1213
2.42k
    pathlen = urllen - (path - url);
1214
2.42k
    if(hostlen) {
1215
2.37k
      ures = parse_authority(u, hostp, hostlen, flags, &host, !!u->scheme);
1216
2.37k
      if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme)
1217
1.56k
        ures = guess_scheme(u, &host);
1218
2.37k
    }
1219
48
    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
48
    else
1225
48
      ures = CURLUE_NO_HOST;
1226
2.42k
  }
1227
4.12k
  if(!ures) {
1228
    /* The path might at this point contain a fragment and/or a query to
1229
       handle */
1230
3.45k
    const char *fragment = strchr(path, '#');
1231
3.45k
    if(fragment) {
1232
581
      size_t fraglen = pathlen - (fragment - path);
1233
581
      ures = handle_fragment(u, fragment, fraglen, flags);
1234
      /* after this, pathlen still contains the query */
1235
581
      pathlen -= fraglen;
1236
581
    }
1237
3.45k
  }
1238
4.12k
  if(!ures) {
1239
3.45k
    const char *query = memchr(path, '?', pathlen);
1240
3.45k
    if(query) {
1241
82
      size_t qlen = pathlen - (query - path);
1242
82
      ures = handle_query(u, query, qlen, flags);
1243
82
      pathlen -= qlen;
1244
82
    }
1245
3.45k
  }
1246
4.12k
  if(!ures)
1247
    /* the fragment and query parts are trimmed off from the path */
1248
3.45k
    ures = handle_path(u, path, pathlen, flags, is_file);
1249
4.12k
  if(!ures) {
1250
3.45k
    u->host = curlx_dyn_ptr(&host);
1251
3.45k
    return CURLUE_OK;
1252
3.45k
  }
1253
713
fail:
1254
713
  curlx_dyn_free(&host);
1255
713
  free_urlhandle(u);
1256
713
  return ures;
1257
4.12k
}
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
4.16k
{
1265
4.16k
  CURLUcode ures;
1266
4.16k
  CURLU tmpurl;
1267
4.16k
  memset(&tmpurl, 0, sizeof(tmpurl));
1268
4.16k
  ures = parseurl(url, &tmpurl, flags);
1269
4.16k
  if(!ures) {
1270
3.45k
    free_urlhandle(u);
1271
3.45k
    *u = tmpurl;
1272
3.45k
  }
1273
4.16k
  return ures;
1274
4.16k
}
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
0
{
1282
0
  struct dynbuf urlbuf;
1283
0
  bool host_changed = FALSE;
1284
0
  const char *useurl = relurl;
1285
0
  const char *cutoff = NULL;
1286
0
  size_t prelen;
1287
0
  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
0
  const char *scheme = u->scheme ? u->scheme : DEFAULT_SCHEME;
1291
1292
  /* protsep points to the start of the hostname, after [scheme]:// */
1293
0
  const char *protsep = base + strlen(scheme) + 3;
1294
0
  DEBUGASSERT(base && relurl && u); /* all set here */
1295
0
  if(!base)
1296
0
    return CURLUE_MALFORMED_INPUT; /* should never happen */
1297
1298
  /* handle different relative URL types */
1299
0
  switch(relurl[0]) {
1300
0
  case '/':
1301
0
    if(relurl[1] == '/') {
1302
      /* protocol-relative URL: //example.com/path */
1303
0
      cutoff = protsep;
1304
0
      useurl = &relurl[2];
1305
0
      host_changed = TRUE;
1306
0
    }
1307
0
    else
1308
      /* absolute /path */
1309
0
      cutoff = strchr(protsep, '/');
1310
0
    break;
1311
1312
0
  case '#':
1313
    /* fragment-only change */
1314
0
    if(u->fragment_present)
1315
0
      cutoff = strchr(protsep, '#');
1316
0
    break;
1317
1318
0
  default:
1319
    /* path or query-only change */
1320
0
    if(u->query_present)
1321
      /* remove existing query */
1322
0
      cutoff = strchr(protsep, '?');
1323
0
    else if(u->fragment_present)
1324
      /* Remove existing fragment */
1325
0
      cutoff = strchr(protsep, '#');
1326
1327
0
    if(relurl[0] != '?') {
1328
      /* append a relative path after the last slash */
1329
0
      cutoff = memrchr(protsep, '/',
1330
0
                       cutoff ? (size_t)(cutoff - protsep) : strlen(protsep));
1331
0
      if(cutoff)
1332
0
        cutoff++; /* truncate after last slash */
1333
0
    }
1334
0
    break;
1335
0
  }
1336
1337
0
  prelen = cutoff ? (size_t)(cutoff - base) : strlen(base);
1338
1339
  /* build new URL */
1340
0
  curlx_dyn_init(&urlbuf, CURL_MAX_INPUT_LENGTH);
1341
1342
0
  if(!curlx_dyn_addn(&urlbuf, base, prelen) &&
1343
0
     !urlencode_str(&urlbuf, useurl, strlen(useurl), !host_changed,
1344
0
                    QUERY_NOT_YET)) {
1345
0
    uc = parseurl_and_replace(curlx_dyn_ptr(&urlbuf), u,
1346
0
                              flags & ~U_CURLU_PATH_AS_IS);
1347
0
  }
1348
0
  else
1349
0
    uc = CURLUE_OUT_OF_MEMORY;
1350
1351
0
  curlx_dyn_free(&urlbuf);
1352
0
  return uc;
1353
0
}
1354
1355
/*
1356
 */
1357
CURLU *curl_url(void)
1358
4.67k
{
1359
4.67k
  return curlx_calloc(1, sizeof(struct Curl_URL));
1360
4.67k
}
1361
1362
void curl_url_cleanup(CURLU *u)
1363
25.6k
{
1364
25.6k
  if(u) {
1365
4.67k
    free_urlhandle(u);
1366
4.67k
    curlx_free(u);
1367
4.67k
  }
1368
25.6k
}
1369
1370
#define DUP(dest, src, name)                    \
1371
0
  do {                                          \
1372
0
    if((src)->name) {                           \
1373
0
      (dest)->name = curlx_strdup((src)->name); \
1374
0
      if(!(dest)->name)                         \
1375
0
        goto fail;                              \
1376
0
    }                                           \
1377
0
  } while(0)
1378
1379
CURLU *curl_url_dup(const CURLU *in)
1380
0
{
1381
0
  struct Curl_URL *u = curlx_calloc(1, sizeof(struct Curl_URL));
1382
0
  if(u) {
1383
0
    DUP(u, in, scheme);
1384
0
    DUP(u, in, user);
1385
0
    DUP(u, in, password);
1386
0
    DUP(u, in, options);
1387
0
    DUP(u, in, host);
1388
0
    DUP(u, in, path);
1389
0
    DUP(u, in, query);
1390
0
    DUP(u, in, fragment);
1391
0
    DUP(u, in, zoneid);
1392
0
    u->portnum = in->portnum;
1393
0
    u->port_present = in->port_present;
1394
0
    u->fragment_present = in->fragment_present;
1395
0
    u->query_present = in->query_present;
1396
0
  }
1397
0
  return u;
1398
0
fail:
1399
0
  curl_url_cleanup(u);
1400
0
  return NULL;
1401
0
}
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
8.33k
{
1430
8.33k
  CURLUcode uc = CURLUE_OK;
1431
8.33k
  size_t partlen = strlen(ptr);
1432
8.33k
  bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0;
1433
8.33k
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1434
8.33k
  bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST);
1435
8.33k
  bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST);
1436
8.33k
  char *part = curlx_memdup0(ptr, partlen);
1437
8.33k
  *partp = NULL;
1438
8.33k
  if(!part)
1439
0
    return CURLUE_OUT_OF_MEMORY;
1440
8.33k
  if(plusdecode) {
1441
    /* convert + to space */
1442
0
    char *plus = part;
1443
0
    size_t i = 0;
1444
0
    for(i = 0; i < partlen; ++plus, i++) {
1445
0
      if(*plus == '+')
1446
0
        *plus = ' ';
1447
0
    }
1448
0
  }
1449
8.33k
  if(urldecode) {
1450
5
    char *decoded;
1451
5
    size_t dlen;
1452
    /* this unconditional rejection of control bytes is documented API
1453
       behavior */
1454
5
    CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen,
1455
5
                                     REJECT_CTRL);
1456
5
    curlx_free(part);
1457
5
    if(result)
1458
1
      return CURLUE_URLDECODE;
1459
4
    part = decoded;
1460
4
    partlen = dlen;
1461
4
  }
1462
8.33k
  if(urlencode) {
1463
3.05k
    struct dynbuf enc;
1464
3.05k
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1465
3.05k
    uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ?
1466
3.05k
                       QUERY_YES : QUERY_NO);
1467
3.05k
    curlx_free(part);
1468
3.05k
    if(uc)
1469
0
      return uc;
1470
3.05k
    part = curlx_dyn_ptr(&enc);
1471
3.05k
  }
1472
5.28k
  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
5.28k
  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
8.33k
  *partp = part;
1493
8.33k
  return CURLUE_OK;
1494
8.33k
}
1495
1496
static CURLUcode file_url(const CURLU *u, char **part,
1497
                          const char *fragmentsep,
1498
                          const char *querysep)
1499
1.64k
{
1500
1.64k
  char *url = curl_maprintf("file://%s%s%s%s%s",
1501
1.64k
                            u->path, querysep, u->query ? u->query : "",
1502
1.64k
                            fragmentsep, u->fragment ? u->fragment : "");
1503
1.64k
  if(!url)
1504
0
    return CURLUE_OUT_OF_MEMORY;
1505
1506
1.64k
  *part = url;
1507
1.64k
  return CURLUE_OK;
1508
1.64k
}
1509
1510
static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags)
1511
6.01k
{
1512
6.01k
  char *url;
1513
6.01k
  char *allochost = NULL;
1514
6.01k
  const char *fragmentsep =
1515
6.01k
    (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ?
1516
5.43k
    "#" : "";
1517
6.01k
  const char *querysep = ((u->query && u->query[0]) ||
1518
5.98k
                          (u->query_present && flags & CURLU_GET_EMPTY)) ?
1519
5.93k
    "?" : "";
1520
6.01k
  char portbuf[7];
1521
6.01k
  if(curl_strequal("file", u->scheme))
1522
1.64k
    return file_url(u, part, fragmentsep, querysep);
1523
4.37k
  else if(!u->host)
1524
2.56k
    return CURLUE_NO_HOST;
1525
1.80k
  else {
1526
1.80k
    const char *scheme;
1527
1.80k
    char *options = u->options;
1528
1.80k
    char *port = NULL;
1529
1.80k
    const struct Curl_scheme *h = NULL;
1530
1.80k
    char schemebuf[MAX_SCHEME_LEN + 5];
1531
1.80k
    if(u->scheme)
1532
1.80k
      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
1.80k
    if(u->port_present) {
1539
32
      curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1540
32
      port = portbuf;
1541
32
    }
1542
1543
1.80k
    h = Curl_get_scheme(scheme);
1544
1.80k
    if(h) {
1545
1.63k
      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
1.63k
      else if(u->port_present && (h->defport == u->portnum) &&
1552
1
              (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
0
        port = NULL;
1556
0
      }
1557
1558
1.63k
      if(!(h->flags & PROTOPT_URLOPTIONS))
1559
1.61k
        options = NULL;
1560
1.63k
    }
1561
1562
1.80k
    if(u->host[0] == '[') {
1563
131
      if(u->zoneid) {
1564
        /* make it '[ host %25 zoneid ]' */
1565
19
        struct dynbuf enc;
1566
19
        size_t hostlen = strlen(u->host);
1567
19
        curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1568
19
        if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
1569
19
                          u->zoneid))
1570
0
          return CURLUE_OUT_OF_MEMORY;
1571
19
        allochost = curlx_dyn_ptr(&enc);
1572
19
      }
1573
131
    }
1574
1.67k
    else if(flags & CURLU_URLENCODE) {
1575
0
      allochost = curl_easy_escape(NULL, u->host, 0);
1576
0
      if(!allochost)
1577
0
        return CURLUE_OUT_OF_MEMORY;
1578
0
    }
1579
1.67k
    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
1.67k
    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
1.80k
    if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme)
1595
1.80k
      curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme);
1596
0
    else
1597
0
      schemebuf[0] = 0;
1598
1599
1.80k
    url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1600
1.80k
                        schemebuf,
1601
1.80k
                        u->user ? u->user : "",
1602
1.80k
                        u->password ? ":" : "",
1603
1.80k
                        u->password ? u->password : "",
1604
1.80k
                        options ? ";" : "",
1605
1.80k
                        options ? options : "",
1606
1.80k
                        (u->user || u->password || options) ? "@" : "",
1607
1.80k
                        allochost ? allochost : u->host,
1608
1.80k
                        port ? ":" : "",
1609
1.80k
                        port ? port : "",
1610
1.80k
                        u->path ? u->path : "/",
1611
1.80k
                        querysep,
1612
1.80k
                        u->query ? u->query : "",
1613
1.80k
                        fragmentsep,
1614
1.80k
                        u->fragment ? u->fragment : "");
1615
1.80k
    curlx_free(allochost);
1616
1.80k
  }
1617
1.80k
  if(!url)
1618
0
    return CURLUE_OUT_OF_MEMORY;
1619
1.80k
  *part = url;
1620
1.80k
  return CURLUE_OK;
1621
1.80k
}
1622
1623
CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
1624
                       char **part, unsigned int flags)
1625
30.9k
{
1626
30.9k
  const char *ptr;
1627
30.9k
  CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
1628
30.9k
  char portbuf[7];
1629
30.9k
  bool plusdecode = FALSE;
1630
30.9k
  if(!u)
1631
0
    return CURLUE_BAD_HANDLE;
1632
30.9k
  if(!part)
1633
0
    return CURLUE_BAD_PARTPOINTER;
1634
30.9k
  *part = NULL;
1635
1636
30.9k
  switch(what) {
1637
3.45k
  case CURLUPART_SCHEME:
1638
3.45k
    ptr = u->scheme;
1639
3.45k
    ifmissing = CURLUE_NO_SCHEME;
1640
3.45k
    flags &= ~U_CURLU_URLDECODE; /* never for schemes */
1641
3.45k
    if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme)
1642
0
      return CURLUE_NO_SCHEME;
1643
3.45k
    break;
1644
3.45k
  case CURLUPART_USER:
1645
3.01k
    ptr = u->user;
1646
3.01k
    ifmissing = CURLUE_NO_USER;
1647
3.01k
    break;
1648
3.01k
  case CURLUPART_PASSWORD:
1649
3.01k
    ptr = u->password;
1650
3.01k
    ifmissing = CURLUE_NO_PASSWORD;
1651
3.01k
    break;
1652
3.05k
  case CURLUPART_OPTIONS:
1653
3.05k
    ptr = u->options;
1654
3.05k
    ifmissing = CURLUE_NO_OPTIONS;
1655
3.05k
    break;
1656
3.28k
  case CURLUPART_HOST:
1657
3.28k
    ptr = u->host;
1658
3.28k
    ifmissing = CURLUE_NO_HOST;
1659
3.28k
    break;
1660
3.00k
  case CURLUPART_ZONEID:
1661
3.00k
    ptr = u->zoneid;
1662
3.00k
    ifmissing = CURLUE_NO_ZONEID;
1663
3.00k
    break;
1664
0
  case CURLUPART_PORT:
1665
0
    ptr = NULL;
1666
0
    ifmissing = CURLUE_NO_PORT;
1667
0
    flags &= ~U_CURLU_URLDECODE; /* never for port */
1668
0
    if(u->port_present) {
1669
0
      const struct Curl_scheme *h = u->scheme ?
1670
0
                                    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
0
      if(h && (h->defport == u->portnum) &&
1674
0
         (flags & CURLU_NO_DEFAULT_PORT)) {
1675
0
        ptr = NULL;
1676
0
      }
1677
0
      else {
1678
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1679
0
        ptr = portbuf;
1680
0
      }
1681
0
    }
1682
0
    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
0
    break;
1692
3.05k
  case CURLUPART_PATH:
1693
3.05k
    ptr = u->path;
1694
3.05k
    if(!ptr)
1695
928
      ptr = "/";
1696
3.05k
    break;
1697
3.05k
  case CURLUPART_QUERY:
1698
3.05k
    ptr = u->query;
1699
3.05k
    ifmissing = CURLUE_NO_QUERY;
1700
3.05k
    plusdecode = flags & CURLU_URLDECODE;
1701
3.05k
    if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY))
1702
      /* there was a blank query and the user does not ask for it */
1703
0
      ptr = NULL;
1704
3.05k
    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
6.01k
  case CURLUPART_URL:
1713
6.01k
    return urlget_url(u, part, flags);
1714
0
  default:
1715
0
    ptr = NULL;
1716
0
    break;
1717
30.9k
  }
1718
24.9k
  if(ptr)
1719
8.33k
    return urlget_format(u, what, ptr, part, plusdecode, flags);
1720
1721
16.5k
  return ifmissing;
1722
24.9k
}
1723
1724
static CURLUcode set_url_scheme(CURLU *u, const char *scheme,
1725
                                unsigned int flags)
1726
0
{
1727
0
  size_t plen = strlen(scheme);
1728
0
  const struct Curl_scheme *h = NULL;
1729
0
  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
0
  h = Curl_get_scheme(scheme);
1734
0
  if(!(flags & CURLU_NON_SUPPORT_SCHEME) && (!h || !h->run))
1735
0
    return CURLUE_UNSUPPORTED_SCHEME;
1736
0
  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
0
  u->guessed_scheme = FALSE;
1752
0
  return CURLUE_OK;
1753
0
}
1754
1755
static CURLUcode set_url_port(CURLU *u, const char *provided_port)
1756
32
{
1757
32
  curl_off_t port;
1758
32
  if(!ISDIGIT(provided_port[0]))
1759
    /* not a number */
1760
0
    return CURLUE_BAD_PORT_NUMBER;
1761
32
  if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port)
1762
    /* weirdly provided number, not good! */
1763
0
    return CURLUE_BAD_PORT_NUMBER;
1764
32
  u->portnum = (uint16_t)port;
1765
32
  u->port_present = TRUE;
1766
32
  return CURLUE_OK;
1767
32
}
1768
1769
static CURLUcode set_url(CURLU *u, const char *url, size_t part_size,
1770
                         unsigned int flags)
1771
4.67k
{
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
4.67k
  CURLUcode uc;
1779
4.67k
  char *oldurl = NULL;
1780
1781
4.67k
  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
508
    uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1785
508
    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
508
    if(uc == CURLUE_OUT_OF_MEMORY)
1795
0
      return uc;
1796
508
    return CURLUE_MALFORMED_INPUT;
1797
508
  }
1798
1799
  /* if the new URL is absolute replace the existing with the new. */
1800
4.16k
  if(Curl_is_absolute_url(url, NULL, 0,
1801
4.16k
                          flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME)))
1802
2.10k
    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
2.06k
  uc = curl_url_get(u, CURLUPART_URL, &oldurl,
1810
2.06k
                    (flags & ~CURLU_NO_GUESS_SCHEME) | CURLU_GET_EMPTY);
1811
2.06k
  if(uc == CURLUE_OUT_OF_MEMORY)
1812
0
    return uc;
1813
2.06k
  else if(uc)
1814
2.06k
    return parseurl_and_replace(url, u, flags);
1815
1816
0
  DEBUGASSERT(oldurl); /* it is set here */
1817
  /* apply the relative part to create a new URL */
1818
0
  uc = redirect_url(oldurl, url, u, flags);
1819
0
  curlx_free(oldurl);
1820
0
  return uc;
1821
0
}
1822
1823
static CURLUcode urlset_clear(CURLU *u, CURLUPart what)
1824
0
{
1825
0
  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
0
  case CURLUPART_USER:
1835
0
    curlx_safefree(u->user);
1836
0
    break;
1837
0
  case CURLUPART_PASSWORD:
1838
0
    curlx_strzero(u->password);
1839
0
    curlx_safefree(u->password);
1840
0
    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
0
  case CURLUPART_FRAGMENT:
1862
0
    curlx_safefree(u->fragment);
1863
0
    u->fragment_present = FALSE;
1864
0
    break;
1865
0
  default:
1866
0
    return CURLUE_UNKNOWN_PART;
1867
0
  }
1868
0
  return CURLUE_OK;
1869
0
}
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
0
{
1903
0
  const unsigned char *i;
1904
1905
0
  for(i = (const unsigned char *)part; *i; i++) {
1906
0
    CURLcode result;
1907
0
    if((*i == ' ') && plusencode)
1908
0
      result = curlx_dyn_addn(encp, "+", 1);
1909
0
    else if(ISUNRESERVED(*i) ||
1910
0
            (pathmode && allowed_in_path(*i)) ||
1911
0
            ((*i == '=') && equalsencode)) {
1912
0
      if((*i == '=') && equalsencode)
1913
        /* only skip the first equals sign */
1914
0
        equalsencode = FALSE;
1915
0
      result = curlx_dyn_addn(encp, i, 1);
1916
0
    }
1917
0
    else {
1918
0
      unsigned char out[3] = { '%' };
1919
0
      Curl_hexbyte(&out[1], *i);
1920
0
      result = curlx_dyn_addn(encp, out, 3);
1921
0
    }
1922
0
    if(result)
1923
0
      return cc2cu(result);
1924
0
  }
1925
0
  return CURLUE_OK;
1926
0
}
1927
1928
static CURLUcode url_uppercasehex_part(struct dynbuf *encp,
1929
                                       const char *part)
1930
0
{
1931
0
  char *p;
1932
0
  CURLcode result = curlx_dyn_add(encp, part);
1933
0
  if(result)
1934
0
    return cc2cu(result);
1935
0
  p = curlx_dyn_ptr(encp);
1936
0
  while(*p) {
1937
    /* make sure percent encoded are upper case */
1938
0
    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
0
    else
1945
0
      p++;
1946
0
  }
1947
0
  return CURLUE_OK;
1948
0
}
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
4.70k
{
2020
4.70k
  char **storep = NULL;
2021
4.70k
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
2022
4.70k
  bool plusencode = FALSE;
2023
4.70k
  bool pathmode = FALSE;
2024
4.70k
  bool leadingslash = FALSE;
2025
4.70k
  bool appendquery = FALSE;
2026
4.70k
  bool equalsencode = FALSE;
2027
4.70k
  size_t nalloc;
2028
2029
4.70k
  if(!u)
2030
0
    return CURLUE_BAD_HANDLE;
2031
4.70k
  if(!part)
2032
    /* setting a part to NULL clears it */
2033
0
    return urlset_clear(u, what);
2034
2035
4.70k
  nalloc = strlen(part);
2036
4.70k
  if(nalloc > CURL_MAX_INPUT_LENGTH)
2037
    /* excessive input length */
2038
0
    return CURLUE_MALFORMED_INPUT;
2039
2040
4.70k
  switch(what) {
2041
0
  case CURLUPART_SCHEME: {
2042
0
    CURLUcode status = set_url_scheme(u, part, flags);
2043
0
    if(status)
2044
0
      return status;
2045
0
    storep = &u->scheme;
2046
0
    urlencode = FALSE; /* never */
2047
0
    break;
2048
0
  }
2049
0
  case CURLUPART_USER:
2050
0
    storep = &u->user;
2051
0
    break;
2052
0
  case CURLUPART_PASSWORD:
2053
0
    storep = &u->password;
2054
0
    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
32
  case CURLUPART_PORT:
2066
32
    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
4.67k
  case CURLUPART_URL:
2084
4.67k
    return set_url(u, part, nalloc, flags);
2085
0
  default:
2086
0
    return CURLUE_UNKNOWN_PART;
2087
4.70k
  }
2088
0
  DEBUGASSERT(storep);
2089
0
  {
2090
0
    const char *newp = NULL;
2091
0
    struct dynbuf enc;
2092
0
    CURLUcode status;
2093
0
    curlx_dyn_init(&enc, (nalloc * 3) + 1 + leadingslash);
2094
2095
0
    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
0
    if(urlencode)
2101
0
      status = url_encode_part(&enc, part, plusencode, pathmode, equalsencode);
2102
0
    else
2103
0
      status = url_uppercasehex_part(&enc, part);
2104
0
    if(!status) {
2105
0
      newp = curlx_dyn_ptr(&enc);
2106
2107
0
      if(appendquery && newp)
2108
0
        return url_append_query(u, &enc);
2109
0
      else if(what == CURLUPART_HOST)
2110
0
        status = url_sethost(u, &enc, urlencode, flags);
2111
0
    }
2112
0
    if(status)
2113
0
      return status;
2114
2115
0
    if(what == CURLUPART_PASSWORD)
2116
0
      curlx_strzero(*storep);
2117
0
    curlx_free(*storep);
2118
0
    *storep = (char *)CURL_UNCONST(newp);
2119
0
  }
2120
0
  return CURLUE_OK;
2121
0
}
2122
2123
bool Curl_url_same_origin(CURLU *base, CURLU *href)
2124
0
{
2125
0
  const struct Curl_scheme *s = NULL;
2126
2127
  /* base must be an absolute URL */
2128
0
  if(!base->scheme || !base->host)
2129
0
    return FALSE;
2130
0
  if(href->scheme && !curl_strequal(base->scheme, href->scheme))
2131
0
    return FALSE;
2132
0
  if(href->host) {
2133
0
    if(!curl_strequal(base->host, href->host))
2134
0
      return FALSE;
2135
2136
0
    if(base->port_present != href->port_present) {
2137
      /* one is present, one is not */
2138
0
      s = Curl_get_scheme(base->scheme);
2139
0
      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
0
      if((base->port_present && (base->portnum != s->defport)) ||
2143
0
         (href->port_present && (href->portnum != s->defport)))
2144
0
        return FALSE;
2145
0
    }
2146
0
    else if(base->portnum != href->portnum) /* both present or missing */
2147
0
      return FALSE;
2148
2149
0
    if(!curl_strequal(base->zoneid ? base->zoneid : "",
2150
0
                      href->zoneid ? href->zoneid : ""))
2151
0
      return FALSE;
2152
0
  }
2153
0
  else if(href->port_present) /* no host in href, then there must be no port */
2154
0
    return FALSE;
2155
0
  return TRUE;
2156
0
}
2157
2158
CURLUcode Curl_url_get_port(CURLU *u, uint16_t *pport)
2159
3.01k
{
2160
3.01k
  if(u->port_present) {
2161
25
    *pport = u->portnum;
2162
25
    return CURLUE_OK;
2163
25
  }
2164
2.99k
  else if(u->scheme) {
2165
2.99k
    const struct Curl_scheme *s = Curl_get_scheme(u->scheme);
2166
2.99k
    if(s && s->defport) {
2167
1.36k
      *pport = s->defport;
2168
1.36k
      return CURLUE_OK;
2169
1.36k
    }
2170
2.99k
  }
2171
1.62k
  *pport = 0;
2172
1.62k
  return CURLUE_NO_PORT;
2173
3.01k
}