Coverage Report

Created: 2026-08-31 06:47

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
0
  ((('a' <= (str)[0] && (str)[0] <= 'z') ||                \
50
0
    ('A' <= (str)[0] && (str)[0] <= 'Z')) &&               \
51
0
   ((str)[1] == ':' || (str)[1] == '|') &&                 \
52
0
   ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
53
54
/* scheme is not URL encoded, the longest libcurl supported ones are... */
55
0
#define MAX_SCHEME_LEN 40
56
0
#define MAX_ZONEID_LEN 16
57
58
/* characters not allowed in hostnames */
59
0
#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
0
{
74
0
  curlx_free(u->scheme);
75
0
  curlx_free(u->user);
76
0
  curlx_strzero(u->password);
77
0
  curlx_free(u->password);
78
0
  curlx_free(u->options);
79
0
  curlx_free(u->host);
80
0
  curlx_free(u->zoneid);
81
0
  curlx_free(u->path);
82
0
  curlx_free(u->query);
83
0
  curlx_free(u->fragment);
84
0
}
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
0
{
134
  /* we must add this with whitespace-replacing */
135
0
  const unsigned char *iptr;
136
0
  const unsigned char *host_sep = (const unsigned char *)url;
137
0
  CURLcode result = CURLE_OK;
138
139
0
  DEBUGASSERT((query >= QUERY_NO) && (query <= QUERY_YES));
140
141
0
  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
0
  for(iptr = host_sep; len && !result; iptr++, len--) {
152
0
    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
0
    else if((*iptr < ' ') || (*iptr >= 0x7f)) {
159
0
      unsigned char out[3] = { '%' };
160
0
      Curl_hexbyte(&out[1], *iptr);
161
0
      result = curlx_dyn_addn(o, out, 3);
162
0
    }
163
0
    else if(*iptr == '%' && (len >= 3) &&
164
0
            ISXDIGIT(iptr[1]) && ISXDIGIT(iptr[2]) &&
165
0
            (ISLOWER(iptr[1]) || ISLOWER(iptr[2]))) {
166
      /* uppercase it */
167
0
      unsigned char hex = (unsigned char)((curlx_hexval(iptr[1]) << 4) |
168
0
                                          curlx_hexval(iptr[2]));
169
0
      unsigned char out[3] = { '%' };
170
0
      Curl_hexbyte(&out[1], hex);
171
0
      result = curlx_dyn_addn(o, out, 3);
172
0
      iptr += 2;
173
0
      len -= 2;
174
0
    }
175
0
    else {
176
0
      result = curlx_dyn_addn(o, iptr, 1);
177
0
      if(*iptr == '?' && (query == QUERY_NOT_YET))
178
0
        query = QUERY_YES;
179
0
    }
180
0
  }
181
182
0
  if(result)
183
0
    return cc2cu(result);
184
0
  return CURLUE_OK;
185
0
}
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
0
{
198
0
  size_t i = 0;
199
0
  DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
200
0
  (void)buflen; /* only used in debug-builds */
201
0
  if(buf)
202
0
    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
0
  if(ISALPHA(url[0]))
208
0
    for(i = 1; i < MAX_SCHEME_LEN; ++i) {
209
0
      char s = url[i];
210
0
      if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.'))) {
211
        /* RFC 3986 3.1 explains:
212
           scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
213
         */
214
0
      }
215
0
      else {
216
0
        break;
217
0
      }
218
0
    }
219
0
  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
0
    size_t len = i;
226
0
    if(buf) {
227
0
      Curl_strntolower(buf, url, i);
228
0
      buf[i] = 0;
229
0
    }
230
0
    return len;
231
0
  }
232
0
  return 0;
233
0
}
234
235
/* scan for byte values <= 31, 127 and sometimes space */
236
CURLUcode Curl_junkscan(const char *url, size_t *urllen, bool allowspace)
237
0
{
238
0
  size_t n = strlen(url);
239
0
  size_t i;
240
0
  unsigned char control;
241
0
  const unsigned char *p = (const unsigned char *)url;
242
0
  if(n > CURL_MAX_INPUT_LENGTH)
243
0
    return CURLUE_MALFORMED_INPUT;
244
245
0
  control = allowspace ? 0x1f : 0x20;
246
0
  for(i = 0; i < n; i++) {
247
0
    if(p[i] <= control || p[i] == 127)
248
0
      return CURLUE_MALFORMED_INPUT;
249
0
  }
250
0
  *urllen = n;
251
0
  return CURLUE_OK;
252
0
}
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
0
{
273
0
  CURLUcode ures = CURLUE_OK;
274
0
  CURLcode result;
275
0
  char *userp = NULL;
276
0
  char *passwdp = NULL;
277
0
  char *optionsp = NULL;
278
0
  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
0
  const char *ptr;
288
289
0
  DEBUGASSERT(login);
290
291
0
  *hostname_offset = 0;
292
0
  ptr = memchr(login, '@', len);
293
0
  if(!ptr)
294
0
    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
0
  ptr++;
300
301
  /* if this is a known scheme, get some details */
302
0
  if(u->scheme)
303
0
    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
0
  result = Curl_parse_login_details(login, ptr - login - 1,
308
0
                                    &userp, &passwdp,
309
0
                                    (h && (h->flags & PROTOPT_URLOPTIONS)) ?
310
0
                                    &optionsp : NULL);
311
0
  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
0
  if(userp) {
319
0
    if(flags & CURLU_DISALLOW_USER) {
320
      /* Option DISALLOW_USER is set and URL contains username. */
321
0
      ures = CURLUE_USER_NOT_ALLOWED;
322
0
      goto out;
323
0
    }
324
0
    curlx_free(u->user);
325
0
    u->user = userp;
326
0
  }
327
328
0
  if(passwdp) {
329
0
    curlx_strzero(u->password);
330
0
    curlx_free(u->password);
331
0
    u->password = passwdp;
332
0
  }
333
334
0
  if(optionsp) {
335
0
    curlx_free(u->options);
336
0
    u->options = optionsp;
337
0
  }
338
339
  /* the hostname starts at this offset */
340
0
  *hostname_offset = ptr - login;
341
0
  return CURLUE_OK;
342
343
0
out:
344
345
0
  curlx_free(userp);
346
0
  curlx_strzero(passwdp);
347
0
  curlx_free(passwdp);
348
0
  curlx_free(optionsp);
349
0
  curlx_safefree(u->user);
350
0
  curlx_strzero(u->password);
351
0
  curlx_safefree(u->password);
352
0
  curlx_safefree(u->options);
353
354
0
  return ures;
355
0
}
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
0
{
363
0
  const char *portptr;
364
0
  const char *hostname = curlx_dyn_ptr(host);
365
  /*
366
   * Find the end of an IPv6 address on the ']' ending bracket.
367
   */
368
0
  u->portnum = 0;
369
0
  u->port_present = FALSE;
370
0
  if(hostname[0] == '[') {
371
0
    portptr = strchr(hostname, ']');
372
0
    if(!portptr)
373
0
      return CURLUE_BAD_IPV6;
374
0
    portptr++;
375
    /* this is a RFC2732-style specified IP-address */
376
0
    if(*portptr) {
377
0
      if(*portptr != ':')
378
0
        return CURLUE_BAD_PORT_NUMBER;
379
0
    }
380
0
    else
381
0
      portptr = NULL;
382
0
  }
383
0
  else
384
0
    portptr = strchr(hostname, ':');
385
386
0
  if(portptr) {
387
0
    curl_off_t port;
388
0
    size_t keep = portptr - hostname;
389
0
    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
0
    curlx_dyn_setlen(host, keep);
398
0
    portptr++;
399
0
    if(!*portptr)
400
0
      return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
401
0
    if(*portptr == '\\')
402
0
      return CURLUE_BACKSLASH;
403
0
    rc = curlx_str_number(&portptr, &port, 0xffff);
404
0
    if(rc)
405
0
      return CURLUE_BAD_PORT_NUMBER;
406
0
    else if(*portptr == '\\')
407
0
      return CURLUE_BACKSLASH;
408
0
    else if(*portptr)
409
0
      return CURLUE_BAD_PORT_NUMBER;
410
411
0
    u->portnum = (uint16_t)port;
412
0
    u->port_present = TRUE;
413
0
  }
414
415
0
  return CURLUE_OK;
416
0
}
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
0
{
428
0
  size_t len;
429
0
  DEBUGASSERT(*hostname == '[');
430
0
  if(hlen < 4) /* '[::]' is the shortest possible valid string */
431
0
    return CURLUE_BAD_IPV6;
432
0
  hostname++;
433
0
  hlen -= 2;
434
435
  /* only valid IPv6 letters are ok */
436
0
  len = strspn(hostname, "0123456789abcdefABCDEF:.");
437
438
0
  if(hlen != len) {
439
0
    hlen = len;
440
0
    if(hostname[len] == '%') {
441
      /* this could now be '%[zone id]' */
442
0
      char zoneid[MAX_ZONEID_LEN];
443
0
      int i = 0;
444
0
      char *h = &hostname[len + 1];
445
      /* pass '25' if present and is a URL encoded percent sign */
446
0
      if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
447
0
        h += 2;
448
0
      while(*h && (*h != ']') && (i < (MAX_ZONEID_LEN - 1)))
449
0
        zoneid[i++] = *h++;
450
0
      if(!i || (']' != *h))
451
0
        return CURLUE_BAD_IPV6;
452
0
      zoneid[i] = 0;
453
0
      u->zoneid = curlx_strdup(zoneid);
454
0
      if(!u->zoneid)
455
0
        return CURLUE_OUT_OF_MEMORY;
456
0
      hostname[len] = ']'; /* insert end bracket */
457
0
      hostname[len + 1] = 0; /* terminate the hostname */
458
0
    }
459
0
    else
460
0
      return CURLUE_BAD_IPV6;
461
    /* hostname is fine */
462
0
  }
463
464
  /* Normalize the IPv6 address */
465
0
  {
466
0
    char dest[16]; /* fits a binary IPv6 address */
467
0
    hostname[hlen] = 0; /* end the address there */
468
0
    if(curlx_inet_pton(AF_INET6, hostname, dest) != 1)
469
0
      return CURLUE_BAD_IPV6;
470
0
    if(!curlx_inet_ntop(AF_INET6, dest, hostname, hlen + 1)) {
471
0
      hlen = strlen(hostname); /* might be shorter now */
472
0
      hostname[hlen + 1] = 0;
473
0
    }
474
0
    hostname[hlen] = ']'; /* restore ending bracket */
475
0
  }
476
0
  return CURLUE_OK;
477
0
}
478
479
static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
480
                                size_t hlen) /* length of hostname */
481
0
{
482
0
  size_t len;
483
0
  DEBUGASSERT(hostname);
484
485
0
  if(!hlen)
486
0
    return CURLUE_NO_HOST;
487
0
  else if(hostname[0] == '[')
488
0
    return ipv6_parse(u, hostname, hlen);
489
0
  else {
490
    /* letters from the second string are not ok */
491
0
    len = strcspn(hostname, HOSTNAME_INVALID_CHARS);
492
0
    if(hlen != len)
493
      /* hostname with bad content */
494
0
      return CURLUE_BAD_HOSTNAME;
495
0
    else if((hlen >= 2) &&
496
0
            (hostname[hlen - 1] == '.') && (hostname[hlen - 2] == '.'))
497
      /* more than one trailing dot is not allowed */
498
0
      return CURLUE_BAD_HOSTNAME;
499
0
    else if((hlen == 1) && (hostname[0] == '.'))
500
      /* a single dot alone is not allowed */
501
0
      return CURLUE_BAD_HOSTNAME;
502
0
  }
503
0
  return CURLUE_OK;
504
0
}
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
0
{
526
0
  bool done = FALSE;
527
0
  int n = 0;
528
0
  const char *c = curlx_dyn_ptr(host);
529
0
  unsigned int parts[4] = { 0, 0, 0, 0 };
530
0
  CURLcode result = CURLE_OK;
531
532
0
  if(*c == '[')
533
0
    return HOST_IPV6;
534
535
0
  while(!done) {
536
0
    int rc;
537
0
    curl_off_t l;
538
0
    if(*c == '0') {
539
0
      if(Curl_raw_tolower(c[1]) == 'x') {
540
0
        c += 2; /* skip the prefix */
541
0
        rc = curlx_str_hex(&c, &l, UINT_MAX);
542
0
        if(rc)
543
0
          return HOST_NAME;
544
0
      }
545
0
      else
546
0
        rc = curlx_str_octal(&c, &l, UINT_MAX);
547
0
    }
548
0
    else
549
0
      rc = curlx_str_number(&c, &l, UINT_MAX);
550
551
0
    if(rc) {
552
0
      if(!n || (rc != STRE_NO_NUM) || *c)
553
0
        return HOST_NAME;
554
0
      n--;
555
0
    }
556
0
    else
557
0
      parts[n] = (unsigned int)l;
558
559
0
    switch(*c) {
560
0
    case '.':
561
0
      if(n == 3) {
562
0
        if(c[1])
563
          /* something follows this dot */
564
0
          return HOST_NAME;
565
0
        done = TRUE;
566
0
      }
567
0
      else {
568
0
        n++;
569
0
        c++;
570
0
      }
571
0
      break;
572
573
0
    case '\0':
574
0
      done = TRUE;
575
0
      break;
576
577
0
    default:
578
0
      return HOST_NAME;
579
0
    }
580
0
  }
581
582
0
  switch(n) {
583
0
  case 0: /* a -- 32 bits */
584
0
    curlx_dyn_reset(host);
585
586
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
587
0
                            (parts[0] >> 24),
588
0
                            ((parts[0] >> 16) & 0xff),
589
0
                            ((parts[0] >> 8) & 0xff),
590
0
                            (parts[0] & 0xff));
591
0
    break;
592
0
  case 1: /* a.b -- 8.24 bits */
593
0
    if((parts[0] > 0xff) || (parts[1] > 0xffffff))
594
0
      return HOST_NAME;
595
0
    curlx_dyn_reset(host);
596
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
597
0
                            parts[0],
598
0
                            ((parts[1] >> 16) & 0xff),
599
0
                            ((parts[1] >> 8) & 0xff),
600
0
                            (parts[1] & 0xff));
601
0
    break;
602
0
  case 2: /* a.b.c -- 8.8.16 bits */
603
0
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
604
0
      return HOST_NAME;
605
0
    curlx_dyn_reset(host);
606
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
607
0
                            parts[0],
608
0
                            parts[1],
609
0
                            ((parts[2] >> 8) & 0xff),
610
0
                            (parts[2] & 0xff));
611
0
    break;
612
0
  case 3: /* a.b.c.d -- 8.8.8.8 bits */
613
0
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
614
0
       (parts[3] > 0xff))
615
0
      return HOST_NAME;
616
0
    curlx_dyn_reset(host);
617
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
618
0
                            parts[0],
619
0
                            parts[1],
620
0
                            parts[2],
621
0
                            parts[3]);
622
0
    break;
623
0
  }
624
0
  if(result)
625
0
    return HOST_ERROR;
626
0
  return HOST_IPV4;
627
0
}
628
629
/* if necessary, replace the host content with a URL decoded version */
630
static CURLUcode urldecode_host(struct dynbuf *host)
631
0
{
632
0
  const char *per;
633
0
  const char *hostname = curlx_dyn_ptr(host);
634
0
  per = strchr(hostname, '%');
635
0
  if(!per)
636
    /* nothing to decode */
637
0
    return CURLUE_OK;
638
0
  else {
639
    /* encoded */
640
0
    size_t dlen;
641
0
    char *decoded;
642
0
    CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
643
0
                                     REJECT_CTRL);
644
0
    if(result)
645
0
      return CURLUE_BAD_HOSTNAME;
646
0
    curlx_dyn_reset(host);
647
0
    result = curlx_dyn_addn(host, decoded, dlen);
648
0
    curlx_free(decoded);
649
0
    if(result)
650
0
      return cc2cu(result);
651
0
  }
652
653
0
  return CURLUE_OK;
654
0
}
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
0
{
662
0
  size_t offset;
663
0
  CURLUcode uc;
664
0
  CURLcode result;
665
666
  /*
667
   * Parse the login details and strip them out of the hostname.
668
   */
669
0
  uc = parse_hostname_login(u, auth, authlen, flags, &offset);
670
0
  if(uc)
671
0
    return uc;
672
673
0
  result = curlx_dyn_addn(host, auth + offset, authlen - offset);
674
0
  if(result) {
675
0
    uc = cc2cu(result);
676
0
    return uc;
677
0
  }
678
679
0
  uc = parse_port(u, host, has_scheme);
680
681
0
  if(!curlx_dyn_len(host))
682
    /* this makes no-host errors override port number problems */
683
0
    uc = CURLUE_NO_HOST;
684
0
  if(!uc)
685
0
    uc = urldecode_host(host);
686
0
  if(uc)
687
0
    return uc;
688
689
0
  switch(ipv4_normalize(host)) {
690
0
  case HOST_IPV4:
691
0
    break;
692
0
  case HOST_IPV6:
693
0
    uc = ipv6_parse(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
694
0
    break;
695
0
  case HOST_NAME:
696
0
    uc = hostname_check(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
697
0
    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
0
  }
705
706
0
  return uc;
707
0
}
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
0
{
736
0
  const char *p = *str;
737
0
  if(*p == '.') {
738
0
    (*str)++;
739
0
    (*clen)--;
740
0
    return TRUE;
741
0
  }
742
0
  else if((*clen >= 3) &&
743
0
          (p[0] == '%') && (p[1] == '2') && ((p[2] | 0x20) == 'e')) {
744
0
    *str += 3;
745
0
    *clen -= 3;
746
0
    return TRUE;
747
0
  }
748
0
  return FALSE;
749
0
}
750
751
0
#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
0
{
756
  /* a single byte path cannot be cleaned up */
757
0
  if(pn < 2)
758
0
    return FALSE;
759
0
  while(pn) {
760
0
    if(is_dot(&p, &pn)) {
761
      /* "./" or dot before end of string */
762
0
      if(!pn || ISSLASH(*p))
763
0
        return TRUE;
764
      /* "../" or ".." before end of string */
765
0
      else if(is_dot(&p, &pn) && (!pn || ISSLASH(*p)))
766
0
        return TRUE;
767
0
    }
768
0
    else {
769
0
      p++;
770
0
      pn--;
771
0
    }
772
0
  }
773
0
  return FALSE;
774
0
}
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
0
{
795
0
  struct dynbuf out;
796
0
  CURLcode result = CURLE_OK;
797
798
  /* variables for leading dot checks */
799
0
  const char *dinput = input;
800
0
  size_t dlen = clen;
801
802
0
  *outp = NULL;
803
0
  if(!needs_dedotdot(input, clen))
804
0
    return 0;
805
806
0
  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
0
  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
0
  while(clen && !result) { /* until end of path content */
832
0
    if(ISSLASH(*input)) {
833
0
      const char *p = &input[1];
834
0
      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
0
      if(is_dot(&p, &blen)) {
839
0
        if(!blen) { /* /. */
840
0
          result = curlx_dyn_addn(&out, "/", 1);
841
0
          break;
842
0
        }
843
0
        else if(ISSLASH(*p)) { /* /./ */
844
0
          input = p;
845
0
          clen = blen;
846
0
          continue;
847
0
        }
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
0
        else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) {
854
          /* remove the last segment from the output buffer */
855
0
          size_t len = curlx_dyn_len(&out);
856
0
          if(len) {
857
0
            const char *ptr = curlx_dyn_ptr(&out);
858
0
            const char *last = memrchr(ptr, '/', len);
859
0
            if(last)
860
              /* trim the output at the slash */
861
0
              curlx_dyn_setlen(&out, last - ptr);
862
0
          }
863
864
0
          if(blen) { /* /../ */
865
0
            input = p;
866
0
            clen = blen;
867
0
            continue;
868
0
          }
869
0
          result = curlx_dyn_addn(&out, "/", 1);
870
0
          break;
871
0
        }
872
0
      }
873
0
    }
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
0
    result = curlx_dyn_addn(&out, input, 1);
881
0
    input++;
882
0
    clen--;
883
0
  }
884
0
end:
885
0
  if(!result) {
886
0
    if(curlx_dyn_len(&out))
887
0
      *outp = curlx_dyn_ptr(&out);
888
0
    else {
889
0
      *outp = curlx_strdup("");
890
0
      if(!*outp)
891
0
        return 1;
892
0
    }
893
0
  }
894
0
  return result ? 1 : 0; /* success */
895
0
}
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
0
{
905
0
  const char *path;
906
0
  size_t pathlen;
907
908
0
  *pathp = NULL;
909
0
  *pathlenp = 0;
910
0
  if(urllen <= 6)
911
    /* file:/ is not enough to actually be a complete file: URL */
912
0
    return CURLUE_BAD_FILE_URL;
913
914
  /* path has been allocated large enough to hold this */
915
0
  path = &url[5];
916
0
  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
0
  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
0
  if(path[1] == '/') {
931
    /* swallow the two slashes */
932
0
    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
0
    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
0
      if(checkprefix("localhost/", ptr) ||
954
0
         checkprefix("127.0.0.1/", ptr)) {
955
0
        ptr += 9; /* now points to the slash after the host */
956
0
      }
957
0
      else
958
        /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
959
           none */
960
0
        return CURLUE_BAD_FILE_URL;
961
0
    }
962
963
0
    path = ptr;
964
0
    pathlen = urllen - (ptr - url);
965
0
  }
966
967
0
#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
0
  if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
971
0
     STARTS_WITH_URL_DRIVE_PREFIX(path)) {
972
    /* File drive letters are only accepted in MS-DOS/Windows */
973
0
    return CURLUE_BAD_FILE_URL;
974
0
  }
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
0
  u->scheme = curlx_strdup("file");
984
0
  if(!u->scheme)
985
0
    return CURLUE_OUT_OF_MEMORY;
986
987
0
  *pathp = path;
988
0
  *pathlenp = pathlen;
989
0
  return CURLUE_OK;
990
0
}
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
0
{
996
  /* clear path */
997
0
  const char *schemep = NULL;
998
999
0
  if(schemelen) {
1000
0
    int num_slashes = 0;
1001
0
    const char *p = &url[schemelen + 1];
1002
0
    if(!Curl_get_scheme(schemebuf) && !(flags & CURLU_NON_SUPPORT_SCHEME))
1003
0
      return CURLUE_UNSUPPORTED_SCHEME;
1004
1005
0
    if(!ISSLASH(*p))
1006
      /* less than one */
1007
0
      return CURLUE_BAD_SLASHES;
1008
0
    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
0
    else {
1015
0
      while(ISSLASH(*p) && (num_slashes < 4)) {
1016
0
        p++;
1017
0
        num_slashes++;
1018
0
      }
1019
0
      if(num_slashes > 3)
1020
0
        return CURLUE_BAD_SLASHES;
1021
0
    }
1022
1023
0
    schemep = schemebuf;
1024
0
    *hostpp = p; /* hostname starts here */
1025
0
  }
1026
0
  else {
1027
    /* no scheme! */
1028
1029
0
    if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME)))
1030
0
      return CURLUE_BAD_SCHEME;
1031
1032
0
    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
0
    *hostpp = url;
1039
0
  }
1040
1041
0
  if(schemep) {
1042
0
    u->scheme = curlx_strdup(schemep);
1043
0
    if(!u->scheme)
1044
0
      return CURLUE_OUT_OF_MEMORY;
1045
0
  }
1046
0
  return CURLUE_OK;
1047
0
}
1048
1049
static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host)
1050
0
{
1051
0
  const char *hostname = curlx_dyn_ptr(host);
1052
0
  const char *schemep = NULL;
1053
  /* legacy curl-style guess based on hostname */
1054
0
  if(checkprefix("ftp.", hostname))
1055
0
    schemep = "ftp";
1056
0
  else if(checkprefix("dict.", hostname))
1057
0
    schemep = "dict";
1058
0
  else if(checkprefix("ldap.", hostname))
1059
0
    schemep = "ldap";
1060
0
  else if(checkprefix("imap.", hostname))
1061
0
    schemep = "imap";
1062
0
  else if(checkprefix("smtp.", hostname))
1063
0
    schemep = "smtp";
1064
0
  else if(checkprefix("pop3.", hostname))
1065
0
    schemep = "pop3";
1066
0
  else
1067
0
    schemep = "http";
1068
1069
0
  u->scheme = curlx_strdup(schemep);
1070
0
  if(!u->scheme)
1071
0
    return CURLUE_OUT_OF_MEMORY;
1072
1073
0
  u->guessed_scheme = TRUE;
1074
0
  return CURLUE_OK;
1075
0
}
1076
1077
static CURLUcode handle_fragment(CURLU *u, const char *fragment,
1078
                                 size_t fraglen, unsigned int flags)
1079
0
{
1080
0
  CURLUcode ures;
1081
0
  u->fragment_present = TRUE;
1082
0
  if(fraglen > 1) {
1083
    /* skip the leading '#' in the copy but include the null-terminator */
1084
0
    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
0
    else {
1093
0
      u->fragment = curlx_memdup0(fragment + 1, fraglen - 1);
1094
0
      if(!u->fragment)
1095
0
        return CURLUE_OUT_OF_MEMORY;
1096
0
    }
1097
0
  }
1098
0
  return CURLUE_OK;
1099
0
}
1100
1101
static CURLUcode handle_query(CURLU *u, const char *query,
1102
                              size_t qlen, unsigned int flags)
1103
0
{
1104
0
  u->query_present = TRUE;
1105
0
  if(qlen > 1) {
1106
0
    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
0
    else {
1117
0
      u->query = curlx_memdup0(query + 1, qlen - 1);
1118
0
      if(!u->query)
1119
0
        return CURLUE_OUT_OF_MEMORY;
1120
0
    }
1121
0
  }
1122
0
  else {
1123
    /* single byte query */
1124
0
    u->query = curlx_strdup("");
1125
0
    if(!u->query)
1126
0
      return CURLUE_OUT_OF_MEMORY;
1127
0
  }
1128
0
  return CURLUE_OK;
1129
0
}
1130
1131
static CURLUcode handle_path(CURLU *u, const char *path,
1132
                             size_t pathlen, unsigned int flags,
1133
                             bool is_file)
1134
0
{
1135
0
  CURLUcode ures;
1136
0
  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
0
  if(pathlen >= (size_t)(1 + !is_file)) {
1147
    /* paths for file:// scheme can be one byte, others need to be two */
1148
0
    if(!u->path) {
1149
0
      u->path = curlx_memdup0(path, pathlen);
1150
0
      if(!u->path)
1151
0
        return CURLUE_OUT_OF_MEMORY;
1152
0
      path = u->path;
1153
0
    }
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
0
    if(!(flags & CURLU_PATH_AS_IS)) {
1159
      /* remove ../ and ./ sequences according to RFC3986 */
1160
0
      char *dedot;
1161
0
      int err = dedotdotify(path, pathlen, &dedot);
1162
0
      if(err)
1163
0
        return CURLUE_OUT_OF_MEMORY;
1164
0
      if(dedot) {
1165
0
        curlx_free(u->path);
1166
0
        u->path = dedot;
1167
0
      }
1168
0
    }
1169
0
  }
1170
0
  return CURLUE_OK;
1171
0
}
1172
1173
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
1174
0
{
1175
0
  const char *path;
1176
0
  size_t pathlen;
1177
0
  char schemebuf[MAX_SCHEME_LEN + 1];
1178
0
  size_t schemelen = 0;
1179
0
  size_t urllen;
1180
0
  CURLUcode ures = CURLUE_OK;
1181
0
  struct dynbuf host;
1182
0
  bool is_file = FALSE;
1183
1184
0
  DEBUGASSERT(url);
1185
1186
0
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
1187
1188
0
  ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE));
1189
0
  if(ures)
1190
0
    goto fail;
1191
1192
0
  schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
1193
0
                                   flags & (CURLU_GUESS_SCHEME |
1194
0
                                            CURLU_DEFAULT_SCHEME));
1195
1196
  /* handle the file: scheme */
1197
0
  if(schemelen && !strcmp(schemebuf, "file")) {
1198
0
    is_file = TRUE;
1199
0
    ures = parse_file(url, urllen, u, &path, &pathlen);
1200
0
  }
1201
0
  else {
1202
0
    const char *hostp = NULL;
1203
0
    size_t hostlen;
1204
0
    ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp);
1205
0
    if(ures)
1206
0
      goto fail;
1207
1208
    /* find the end of the hostname + port number */
1209
0
    hostlen = strcspn(hostp, "/?#");
1210
0
    path = &hostp[hostlen];
1211
1212
    /* this pathlen also contains the query and the fragment */
1213
0
    pathlen = urllen - (path - url);
1214
0
    if(hostlen) {
1215
0
      ures = parse_authority(u, hostp, hostlen, flags, &host, !!u->scheme);
1216
0
      if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme)
1217
0
        ures = guess_scheme(u, &host);
1218
0
    }
1219
0
    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
0
    else
1225
0
      ures = CURLUE_NO_HOST;
1226
0
  }
1227
0
  if(!ures) {
1228
    /* The path might at this point contain a fragment and/or a query to
1229
       handle */
1230
0
    const char *fragment = strchr(path, '#');
1231
0
    if(fragment) {
1232
0
      size_t fraglen = pathlen - (fragment - path);
1233
0
      ures = handle_fragment(u, fragment, fraglen, flags);
1234
      /* after this, pathlen still contains the query */
1235
0
      pathlen -= fraglen;
1236
0
    }
1237
0
  }
1238
0
  if(!ures) {
1239
0
    const char *query = memchr(path, '?', pathlen);
1240
0
    if(query) {
1241
0
      size_t qlen = pathlen - (query - path);
1242
0
      ures = handle_query(u, query, qlen, flags);
1243
0
      pathlen -= qlen;
1244
0
    }
1245
0
  }
1246
0
  if(!ures)
1247
    /* the fragment and query parts are trimmed off from the path */
1248
0
    ures = handle_path(u, path, pathlen, flags, is_file);
1249
0
  if(!ures) {
1250
0
    u->host = curlx_dyn_ptr(&host);
1251
0
    return CURLUE_OK;
1252
0
  }
1253
0
fail:
1254
0
  curlx_dyn_free(&host);
1255
0
  free_urlhandle(u);
1256
0
  return ures;
1257
0
}
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
0
{
1265
0
  CURLUcode ures;
1266
0
  CURLU tmpurl;
1267
0
  memset(&tmpurl, 0, sizeof(tmpurl));
1268
0
  ures = parseurl(url, &tmpurl, flags);
1269
0
  if(!ures) {
1270
0
    free_urlhandle(u);
1271
0
    *u = tmpurl;
1272
0
  }
1273
0
  return ures;
1274
0
}
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
0
{
1359
0
  return curlx_calloc(1, sizeof(struct Curl_URL));
1360
0
}
1361
1362
void curl_url_cleanup(CURLU *u)
1363
7.77k
{
1364
7.77k
  if(u) {
1365
0
    free_urlhandle(u);
1366
0
    curlx_free(u);
1367
0
  }
1368
7.77k
}
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
0
{
1430
0
  CURLUcode uc = CURLUE_OK;
1431
0
  size_t partlen = strlen(ptr);
1432
0
  bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0;
1433
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1434
0
  bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST);
1435
0
  bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST);
1436
0
  char *part = curlx_memdup0(ptr, partlen);
1437
0
  *partp = NULL;
1438
0
  if(!part)
1439
0
    return CURLUE_OUT_OF_MEMORY;
1440
0
  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
0
  if(urldecode) {
1450
0
    char *decoded;
1451
0
    size_t dlen;
1452
    /* this unconditional rejection of control bytes is documented API
1453
       behavior */
1454
0
    CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen,
1455
0
                                     REJECT_CTRL);
1456
0
    curlx_free(part);
1457
0
    if(result)
1458
0
      return CURLUE_URLDECODE;
1459
0
    part = decoded;
1460
0
    partlen = dlen;
1461
0
  }
1462
0
  if(urlencode) {
1463
0
    struct dynbuf enc;
1464
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1465
0
    uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ?
1466
0
                       QUERY_YES : QUERY_NO);
1467
0
    curlx_free(part);
1468
0
    if(uc)
1469
0
      return uc;
1470
0
    part = curlx_dyn_ptr(&enc);
1471
0
  }
1472
0
  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
0
  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
0
  *partp = part;
1493
0
  return CURLUE_OK;
1494
0
}
1495
1496
static CURLUcode file_url(const CURLU *u, char **part,
1497
                          const char *fragmentsep,
1498
                          const char *querysep)
1499
0
{
1500
0
  char *url = curl_maprintf("file://%s%s%s%s%s",
1501
0
                            u->path, querysep, u->query ? u->query : "",
1502
0
                            fragmentsep, u->fragment ? u->fragment : "");
1503
0
  if(!url)
1504
0
    return CURLUE_OUT_OF_MEMORY;
1505
1506
0
  *part = url;
1507
0
  return CURLUE_OK;
1508
0
}
1509
1510
static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags)
1511
0
{
1512
0
  char *url;
1513
0
  char *allochost = NULL;
1514
0
  const char *fragmentsep =
1515
0
    (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ?
1516
0
    "#" : "";
1517
0
  const char *querysep = ((u->query && u->query[0]) ||
1518
0
                          (u->query_present && flags & CURLU_GET_EMPTY)) ?
1519
0
    "?" : "";
1520
0
  char portbuf[7];
1521
0
  if(curl_strequal("file", u->scheme))
1522
0
    return file_url(u, part, fragmentsep, querysep);
1523
0
  else if(!u->host)
1524
0
    return CURLUE_NO_HOST;
1525
0
  else {
1526
0
    const char *scheme;
1527
0
    char *options = u->options;
1528
0
    char *port = NULL;
1529
0
    const struct Curl_scheme *h = NULL;
1530
0
    char schemebuf[MAX_SCHEME_LEN + 5];
1531
0
    if(u->scheme)
1532
0
      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
0
    if(u->port_present) {
1539
0
      curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1540
0
      port = portbuf;
1541
0
    }
1542
1543
0
    h = Curl_get_scheme(scheme);
1544
0
    if(h) {
1545
0
      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
0
      else if(u->port_present && (h->defport == u->portnum) &&
1552
0
              (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
0
      if(!(h->flags & PROTOPT_URLOPTIONS))
1559
0
        options = NULL;
1560
0
    }
1561
1562
0
    if(u->host[0] == '[') {
1563
0
      if(u->zoneid) {
1564
        /* make it '[ host %25 zoneid ]' */
1565
0
        struct dynbuf enc;
1566
0
        size_t hostlen = strlen(u->host);
1567
0
        curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1568
0
        if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
1569
0
                          u->zoneid))
1570
0
          return CURLUE_OUT_OF_MEMORY;
1571
0
        allochost = curlx_dyn_ptr(&enc);
1572
0
      }
1573
0
    }
1574
0
    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
0
    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
0
    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
0
    if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme)
1595
0
      curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme);
1596
0
    else
1597
0
      schemebuf[0] = 0;
1598
1599
0
    url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1600
0
                        schemebuf,
1601
0
                        u->user ? u->user : "",
1602
0
                        u->password ? ":" : "",
1603
0
                        u->password ? u->password : "",
1604
0
                        options ? ";" : "",
1605
0
                        options ? options : "",
1606
0
                        (u->user || u->password || options) ? "@" : "",
1607
0
                        allochost ? allochost : u->host,
1608
0
                        port ? ":" : "",
1609
0
                        port ? port : "",
1610
0
                        u->path ? u->path : "/",
1611
0
                        querysep,
1612
0
                        u->query ? u->query : "",
1613
0
                        fragmentsep,
1614
0
                        u->fragment ? u->fragment : "");
1615
0
    curlx_free(allochost);
1616
0
  }
1617
0
  if(!url)
1618
0
    return CURLUE_OUT_OF_MEMORY;
1619
0
  *part = url;
1620
0
  return CURLUE_OK;
1621
0
}
1622
1623
CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
1624
                       char **part, unsigned int flags)
1625
0
{
1626
0
  const char *ptr;
1627
0
  CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
1628
0
  char portbuf[7];
1629
0
  bool plusdecode = FALSE;
1630
0
  if(!u)
1631
0
    return CURLUE_BAD_HANDLE;
1632
0
  if(!part)
1633
0
    return CURLUE_BAD_PARTPOINTER;
1634
0
  *part = NULL;
1635
1636
0
  switch(what) {
1637
0
  case CURLUPART_SCHEME:
1638
0
    ptr = u->scheme;
1639
0
    ifmissing = CURLUE_NO_SCHEME;
1640
0
    flags &= ~U_CURLU_URLDECODE; /* never for schemes */
1641
0
    if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme)
1642
0
      return CURLUE_NO_SCHEME;
1643
0
    break;
1644
0
  case CURLUPART_USER:
1645
0
    ptr = u->user;
1646
0
    ifmissing = CURLUE_NO_USER;
1647
0
    break;
1648
0
  case CURLUPART_PASSWORD:
1649
0
    ptr = u->password;
1650
0
    ifmissing = CURLUE_NO_PASSWORD;
1651
0
    break;
1652
0
  case CURLUPART_OPTIONS:
1653
0
    ptr = u->options;
1654
0
    ifmissing = CURLUE_NO_OPTIONS;
1655
0
    break;
1656
0
  case CURLUPART_HOST:
1657
0
    ptr = u->host;
1658
0
    ifmissing = CURLUE_NO_HOST;
1659
0
    break;
1660
0
  case CURLUPART_ZONEID:
1661
0
    ptr = u->zoneid;
1662
0
    ifmissing = CURLUE_NO_ZONEID;
1663
0
    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
0
  case CURLUPART_PATH:
1693
0
    ptr = u->path;
1694
0
    if(!ptr)
1695
0
      ptr = "/";
1696
0
    break;
1697
0
  case CURLUPART_QUERY:
1698
0
    ptr = u->query;
1699
0
    ifmissing = CURLUE_NO_QUERY;
1700
0
    plusdecode = flags & CURLU_URLDECODE;
1701
0
    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
0
    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
0
  case CURLUPART_URL:
1713
0
    return urlget_url(u, part, flags);
1714
0
  default:
1715
0
    ptr = NULL;
1716
0
    break;
1717
0
  }
1718
0
  if(ptr)
1719
0
    return urlget_format(u, what, ptr, part, plusdecode, flags);
1720
1721
0
  return ifmissing;
1722
0
}
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
0
{
1757
0
  curl_off_t port;
1758
0
  if(!ISDIGIT(provided_port[0]))
1759
    /* not a number */
1760
0
    return CURLUE_BAD_PORT_NUMBER;
1761
0
  if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port)
1762
    /* weirdly provided number, not good! */
1763
0
    return CURLUE_BAD_PORT_NUMBER;
1764
0
  u->portnum = (uint16_t)port;
1765
0
  u->port_present = TRUE;
1766
0
  return CURLUE_OK;
1767
0
}
1768
1769
static CURLUcode set_url(CURLU *u, const char *url, size_t part_size,
1770
                         unsigned int flags)
1771
0
{
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
0
  CURLUcode uc;
1779
0
  char *oldurl = NULL;
1780
1781
0
  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
0
    uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1785
0
    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
0
    if(uc == CURLUE_OUT_OF_MEMORY)
1795
0
      return uc;
1796
0
    return CURLUE_MALFORMED_INPUT;
1797
0
  }
1798
1799
  /* if the new URL is absolute replace the existing with the new. */
1800
0
  if(Curl_is_absolute_url(url, NULL, 0,
1801
0
                          flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME)))
1802
0
    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
0
  uc = curl_url_get(u, CURLUPART_URL, &oldurl,
1810
0
                    (flags & ~CURLU_NO_GUESS_SCHEME) | CURLU_GET_EMPTY);
1811
0
  if(uc == CURLUE_OUT_OF_MEMORY)
1812
0
    return uc;
1813
0
  else if(uc)
1814
0
    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
0
{
2020
0
  char **storep = NULL;
2021
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
2022
0
  bool plusencode = FALSE;
2023
0
  bool pathmode = FALSE;
2024
0
  bool leadingslash = FALSE;
2025
0
  bool appendquery = FALSE;
2026
0
  bool equalsencode = FALSE;
2027
0
  size_t nalloc;
2028
2029
0
  if(!u)
2030
0
    return CURLUE_BAD_HANDLE;
2031
0
  if(!part)
2032
    /* setting a part to NULL clears it */
2033
0
    return urlset_clear(u, what);
2034
2035
0
  nalloc = strlen(part);
2036
0
  if(nalloc > CURL_MAX_INPUT_LENGTH)
2037
    /* excessive input length */
2038
0
    return CURLUE_MALFORMED_INPUT;
2039
2040
0
  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
0
  case CURLUPART_PORT:
2066
0
    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
0
  case CURLUPART_URL:
2084
0
    return set_url(u, part, nalloc, flags);
2085
0
  default:
2086
0
    return CURLUE_UNKNOWN_PART;
2087
0
  }
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
0
{
2160
0
  if(u->port_present) {
2161
0
    *pport = u->portnum;
2162
0
    return CURLUE_OK;
2163
0
  }
2164
0
  else if(u->scheme) {
2165
0
    const struct Curl_scheme *s = Curl_get_scheme(u->scheme);
2166
0
    if(s && s->defport) {
2167
0
      *pport = s->defport;
2168
0
      return CURLUE_OK;
2169
0
    }
2170
0
  }
2171
0
  *pport = 0;
2172
0
  return CURLUE_NO_PORT;
2173
0
}