Coverage Report

Created: 2026-07-30 07:03

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
/*
754
 * dedotdotify()
755
 *
756
 * This function gets a null-terminated path with dot and dotdot sequences
757
 * passed in and strips them off according to the rules in RFC 3986 section
758
 * 5.2.4.
759
 *
760
 * The function handles a path. It should not contain the query nor fragment.
761
 *
762
 * RETURNS
763
 *
764
 * Zero for success and 'out' set to an allocated dedotdotified string.
765
 *
766
 * @unittest 1395
767
 */
768
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp);
769
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp)
770
0
{
771
0
  struct dynbuf out;
772
0
  CURLcode result = CURLE_OK;
773
774
  /* variables for leading dot checks */
775
0
  const char *dinput = input;
776
0
  size_t dlen = clen;
777
778
0
  *outp = NULL;
779
  /* a single byte path cannot be cleaned up */
780
0
  if(clen < 2)
781
0
    return 0;
782
783
0
  curlx_dyn_init(&out, clen + 1);
784
785
  /* if the input buffer begins with a prefix of "../" or "./", then remove
786
     that prefix from the input buffer; otherwise, */
787
0
  if(is_dot(&dinput, &dlen)) {
788
0
    if(ISSLASH(*dinput)) {
789
      /* one dot followed by a slash */
790
0
      input = dinput + 1;
791
0
      clen = dlen - 1;
792
0
    }
793
794
    /* if the input buffer consists only of "." or "..", then remove
795
       that from the input buffer; otherwise, */
796
0
    else if(is_dot(&dinput, &dlen)) {
797
0
      if(!dlen)
798
        /* .. [end] */
799
0
        goto end;
800
0
      else if(ISSLASH(*dinput)) {
801
        /* ../ */
802
0
        input = dinput + 1;
803
0
        clen = dlen - 1;
804
0
      }
805
0
    }
806
0
  }
807
808
0
  while(clen && !result) { /* until end of path content */
809
0
    if(ISSLASH(*input)) {
810
0
      const char *p = &input[1];
811
0
      size_t blen = clen - 1;
812
      /* if the input buffer begins with a prefix of "/./" or "/.", where "."
813
         is a complete path segment, then replace that prefix with "/" in the
814
         input buffer; otherwise, */
815
0
      if(is_dot(&p, &blen)) {
816
0
        if(!blen) { /* /. */
817
0
          result = curlx_dyn_addn(&out, "/", 1);
818
0
          break;
819
0
        }
820
0
        else if(ISSLASH(*p)) { /* /./ */
821
0
          input = p;
822
0
          clen = blen;
823
0
          continue;
824
0
        }
825
826
        /* if the input buffer begins with a prefix of "/../" or "/..", where
827
           ".." is a complete path segment, then replace that prefix with "/"
828
           in the input buffer and remove the last segment and its preceding
829
           "/" (if any) from the output buffer; otherwise, */
830
0
        else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) {
831
          /* remove the last segment from the output buffer */
832
0
          size_t len = curlx_dyn_len(&out);
833
0
          if(len) {
834
0
            const char *ptr = curlx_dyn_ptr(&out);
835
0
            const char *last = memrchr(ptr, '/', len);
836
0
            if(last)
837
              /* trim the output at the slash */
838
0
              curlx_dyn_setlen(&out, last - ptr);
839
0
          }
840
841
0
          if(blen) { /* /../ */
842
0
            input = p;
843
0
            clen = blen;
844
0
            continue;
845
0
          }
846
0
          result = curlx_dyn_addn(&out, "/", 1);
847
0
          break;
848
0
        }
849
0
      }
850
0
    }
851
852
    /* move the first path segment in the input buffer to the end of the
853
       output buffer, including the initial "/" character (if any) and any
854
       subsequent characters up to, but not including, the next "/" character
855
       or the end of the input buffer. */
856
857
0
    result = curlx_dyn_addn(&out, input, 1);
858
0
    input++;
859
0
    clen--;
860
0
  }
861
0
end:
862
0
  if(!result) {
863
0
    if(curlx_dyn_len(&out))
864
0
      *outp = curlx_dyn_ptr(&out);
865
0
    else {
866
0
      *outp = curlx_strdup("");
867
0
      if(!*outp)
868
0
        return 1;
869
0
    }
870
0
  }
871
0
  return result ? 1 : 0; /* success */
872
0
}
873
874
/*
875
 * @unittest 1675
876
 */
877
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
878
                              const char **pathp, size_t *pathlenp);
879
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
880
                              const char **pathp, size_t *pathlenp)
881
0
{
882
0
  const char *path;
883
0
  size_t pathlen;
884
885
0
  *pathp = NULL;
886
0
  *pathlenp = 0;
887
0
  if(urllen <= 6)
888
    /* file:/ is not enough to actually be a complete file: URL */
889
0
    return CURLUE_BAD_FILE_URL;
890
891
  /* path has been allocated large enough to hold this */
892
0
  path = &url[5];
893
0
  pathlen = urllen - 5;
894
895
  /* RFC 8089: file-hier-part = ( "//" auth-path ) / local-path, where
896
     local-path also starts with a "/". So reject anything that does not
897
     start with at least one "/" */
898
0
  if(path[0] != '/')
899
0
    return CURLUE_BAD_FILE_URL;
900
901
  /* Extra handling URLs with an authority component (i.e. that start with
902
   * "file://")
903
   *
904
   * We allow omitted hostname (e.g. file:/<path>) -- valid according to
905
   * RFC 8089, but not the (current) WHAT-WG URL spec.
906
   */
907
0
  if(path[1] == '/') {
908
    /* swallow the two slashes */
909
0
    const char *ptr = &path[2];
910
911
    /*
912
     * According to RFC 8089, a file: URL can be reliably dereferenced if:
913
     *
914
     *  o it has no/blank hostname, or
915
     *
916
     *  o the hostname matches "localhost" (case-insensitively), or
917
     *
918
     *  o the hostname is a FQDN that resolves to this machine, or
919
     *
920
     * For brevity, we only consider URLs with empty, "localhost", or
921
     * "127.0.0.1" hostnames as local, otherwise as an UNC String.
922
     *
923
     * Additionally, there is an exception for URLs with a Windows drive
924
     * letter in the authority (which was accidentally omitted from RFC 8089
925
     * Appendix E, but believe me, it was meant to be there. --MK)
926
     */
927
0
    if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
928
      /* the URL includes a hostname, it must match "localhost" or
929
         "127.0.0.1" to be valid */
930
0
      if(checkprefix("localhost/", ptr) ||
931
0
         checkprefix("127.0.0.1/", ptr)) {
932
0
        ptr += 9; /* now points to the slash after the host */
933
0
      }
934
0
      else
935
        /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
936
           none */
937
0
        return CURLUE_BAD_FILE_URL;
938
0
    }
939
940
0
    path = ptr;
941
0
    pathlen = urllen - (ptr - url);
942
0
  }
943
944
0
#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__)
945
  /* Do not allow Windows drive letters when not in Windows.
946
   * This catches both "file:/c:" and "file:c:" */
947
0
  if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
948
0
     STARTS_WITH_URL_DRIVE_PREFIX(path)) {
949
    /* File drive letters are only accepted in MS-DOS/Windows */
950
0
    return CURLUE_BAD_FILE_URL;
951
0
  }
952
#else
953
  /* If the path starts with a slash and a drive letter, ditch the slash */
954
  if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
955
    /* This cannot be done with strcpy, as the memory chunks overlap! */
956
    path++;
957
    pathlen--;
958
  }
959
#endif
960
0
  u->scheme = curlx_strdup("file");
961
0
  if(!u->scheme)
962
0
    return CURLUE_OUT_OF_MEMORY;
963
964
0
  *pathp = path;
965
0
  *pathlenp = pathlen;
966
0
  return CURLUE_OK;
967
0
}
968
969
static CURLUcode parse_scheme(const char *url, CURLU *u, char *schemebuf,
970
                              size_t schemelen, unsigned int flags,
971
                              const char **hostpp)
972
0
{
973
  /* clear path */
974
0
  const char *schemep = NULL;
975
976
0
  if(schemelen) {
977
0
    int num_slashes = 0;
978
0
    const char *p = &url[schemelen + 1];
979
0
    if(!Curl_get_scheme(schemebuf) && !(flags & CURLU_NON_SUPPORT_SCHEME))
980
0
      return CURLUE_UNSUPPORTED_SCHEME;
981
982
0
    if(!ISSLASH(*p))
983
      /* less than one */
984
0
      return CURLUE_BAD_SLASHES;
985
0
    if((flags & CURLU_NO_AUTHORITY)) {
986
0
      while(ISSLASH(*p) && (num_slashes < 2)) {
987
0
        p++;
988
0
        num_slashes++;
989
0
      }
990
0
    }
991
0
    else {
992
0
      while(ISSLASH(*p) && (num_slashes < 4)) {
993
0
        p++;
994
0
        num_slashes++;
995
0
      }
996
0
      if(num_slashes > 3)
997
0
        return CURLUE_BAD_SLASHES;
998
0
    }
999
1000
0
    schemep = schemebuf;
1001
0
    *hostpp = p; /* hostname starts here */
1002
0
  }
1003
0
  else {
1004
    /* no scheme! */
1005
1006
0
    if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME)))
1007
0
      return CURLUE_BAD_SCHEME;
1008
1009
0
    if(flags & CURLU_DEFAULT_SCHEME)
1010
0
      schemep = DEFAULT_SCHEME;
1011
1012
    /*
1013
     * The URL was badly formatted, let's try without scheme specified.
1014
     */
1015
0
    *hostpp = url;
1016
0
  }
1017
1018
0
  if(schemep) {
1019
0
    u->scheme = curlx_strdup(schemep);
1020
0
    if(!u->scheme)
1021
0
      return CURLUE_OUT_OF_MEMORY;
1022
0
  }
1023
0
  return CURLUE_OK;
1024
0
}
1025
1026
static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host)
1027
0
{
1028
0
  const char *hostname = curlx_dyn_ptr(host);
1029
0
  const char *schemep = NULL;
1030
  /* legacy curl-style guess based on hostname */
1031
0
  if(checkprefix("ftp.", hostname))
1032
0
    schemep = "ftp";
1033
0
  else if(checkprefix("dict.", hostname))
1034
0
    schemep = "dict";
1035
0
  else if(checkprefix("ldap.", hostname))
1036
0
    schemep = "ldap";
1037
0
  else if(checkprefix("imap.", hostname))
1038
0
    schemep = "imap";
1039
0
  else if(checkprefix("smtp.", hostname))
1040
0
    schemep = "smtp";
1041
0
  else if(checkprefix("pop3.", hostname))
1042
0
    schemep = "pop3";
1043
0
  else
1044
0
    schemep = "http";
1045
1046
0
  u->scheme = curlx_strdup(schemep);
1047
0
  if(!u->scheme)
1048
0
    return CURLUE_OUT_OF_MEMORY;
1049
1050
0
  u->guessed_scheme = TRUE;
1051
0
  return CURLUE_OK;
1052
0
}
1053
1054
static CURLUcode handle_fragment(CURLU *u, const char *fragment,
1055
                                 size_t fraglen, unsigned int flags)
1056
0
{
1057
0
  CURLUcode ures;
1058
0
  u->fragment_present = TRUE;
1059
0
  if(fraglen > 1) {
1060
    /* skip the leading '#' in the copy but include the null-terminator */
1061
0
    if(flags & CURLU_URLENCODE) {
1062
0
      struct dynbuf enc;
1063
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1064
0
      ures = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, QUERY_NO);
1065
0
      if(ures)
1066
0
        return ures;
1067
0
      u->fragment = curlx_dyn_ptr(&enc);
1068
0
    }
1069
0
    else {
1070
0
      u->fragment = curlx_memdup0(fragment + 1, fraglen - 1);
1071
0
      if(!u->fragment)
1072
0
        return CURLUE_OUT_OF_MEMORY;
1073
0
    }
1074
0
  }
1075
0
  return CURLUE_OK;
1076
0
}
1077
1078
static CURLUcode handle_query(CURLU *u, const char *query,
1079
                              size_t qlen, unsigned int flags)
1080
0
{
1081
0
  u->query_present = TRUE;
1082
0
  if(qlen > 1) {
1083
0
    if(flags & CURLU_URLENCODE) {
1084
0
      struct dynbuf enc;
1085
0
      CURLUcode ures;
1086
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1087
      /* skip the leading question mark */
1088
0
      ures = urlencode_str(&enc, query + 1, qlen - 1, TRUE, QUERY_YES);
1089
0
      if(ures)
1090
0
        return ures;
1091
0
      u->query = curlx_dyn_ptr(&enc);
1092
0
    }
1093
0
    else {
1094
0
      u->query = curlx_memdup0(query + 1, qlen - 1);
1095
0
      if(!u->query)
1096
0
        return CURLUE_OUT_OF_MEMORY;
1097
0
    }
1098
0
  }
1099
0
  else {
1100
    /* single byte query */
1101
0
    u->query = curlx_strdup("");
1102
0
    if(!u->query)
1103
0
      return CURLUE_OUT_OF_MEMORY;
1104
0
  }
1105
0
  return CURLUE_OK;
1106
0
}
1107
1108
static CURLUcode handle_path(CURLU *u, const char *path,
1109
                             size_t pathlen, unsigned int flags,
1110
                             bool is_file)
1111
0
{
1112
0
  CURLUcode ures;
1113
0
  if(pathlen && (flags & CURLU_URLENCODE)) {
1114
0
    struct dynbuf enc;
1115
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1116
0
    ures = urlencode_str(&enc, path, pathlen, TRUE, QUERY_NO);
1117
0
    if(ures)
1118
0
      return ures;
1119
0
    pathlen = curlx_dyn_len(&enc);
1120
0
    path = u->path = curlx_dyn_ptr(&enc);
1121
0
  }
1122
1123
0
  if(pathlen >= (size_t)(1 + !is_file)) {
1124
    /* paths for file:// scheme can be one byte, others need to be two */
1125
0
    if(!u->path) {
1126
0
      u->path = curlx_memdup0(path, pathlen);
1127
0
      if(!u->path)
1128
0
        return CURLUE_OUT_OF_MEMORY;
1129
0
      path = u->path;
1130
0
    }
1131
0
    else if(flags & CURLU_URLENCODE)
1132
      /* it might have encoded more than the path so cut it */
1133
0
      u->path[pathlen] = 0;
1134
1135
0
    if(!(flags & CURLU_PATH_AS_IS)) {
1136
      /* remove ../ and ./ sequences according to RFC3986 */
1137
0
      char *dedot;
1138
0
      int err = dedotdotify(path, pathlen, &dedot);
1139
0
      if(err)
1140
0
        return CURLUE_OUT_OF_MEMORY;
1141
0
      if(dedot) {
1142
0
        curlx_free(u->path);
1143
0
        u->path = dedot;
1144
0
      }
1145
0
    }
1146
0
  }
1147
0
  return CURLUE_OK;
1148
0
}
1149
1150
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
1151
0
{
1152
0
  const char *path;
1153
0
  size_t pathlen;
1154
0
  char schemebuf[MAX_SCHEME_LEN + 1];
1155
0
  size_t schemelen = 0;
1156
0
  size_t urllen;
1157
0
  CURLUcode ures = CURLUE_OK;
1158
0
  struct dynbuf host;
1159
0
  bool is_file = FALSE;
1160
1161
0
  DEBUGASSERT(url);
1162
1163
0
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
1164
1165
0
  ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE));
1166
0
  if(ures)
1167
0
    goto fail;
1168
1169
0
  schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
1170
0
                                   flags & (CURLU_GUESS_SCHEME |
1171
0
                                            CURLU_DEFAULT_SCHEME));
1172
1173
  /* handle the file: scheme */
1174
0
  if(schemelen && !strcmp(schemebuf, "file")) {
1175
0
    is_file = TRUE;
1176
0
    ures = parse_file(url, urllen, u, &path, &pathlen);
1177
0
  }
1178
0
  else {
1179
0
    const char *hostp = NULL;
1180
0
    size_t hostlen;
1181
0
    ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp);
1182
0
    if(ures)
1183
0
      goto fail;
1184
1185
    /* find the end of the hostname + port number */
1186
0
    hostlen = strcspn(hostp, "/?#");
1187
0
    path = &hostp[hostlen];
1188
1189
    /* this pathlen also contains the query and the fragment */
1190
0
    pathlen = urllen - (path - url);
1191
0
    if(hostlen) {
1192
0
      ures = parse_authority(u, hostp, hostlen, flags, &host, !!u->scheme);
1193
0
      if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme)
1194
0
        ures = guess_scheme(u, &host);
1195
0
    }
1196
0
    else if(flags & CURLU_NO_AUTHORITY) {
1197
      /* allowed to be empty. */
1198
0
      if(curlx_dyn_add(&host, ""))
1199
0
        ures = CURLUE_OUT_OF_MEMORY;
1200
0
    }
1201
0
    else
1202
0
      ures = CURLUE_NO_HOST;
1203
0
  }
1204
0
  if(!ures) {
1205
    /* The path might at this point contain a fragment and/or a query to
1206
       handle */
1207
0
    const char *fragment = strchr(path, '#');
1208
0
    if(fragment) {
1209
0
      size_t fraglen = pathlen - (fragment - path);
1210
0
      ures = handle_fragment(u, fragment, fraglen, flags);
1211
      /* after this, pathlen still contains the query */
1212
0
      pathlen -= fraglen;
1213
0
    }
1214
0
  }
1215
0
  if(!ures) {
1216
0
    const char *query = memchr(path, '?', pathlen);
1217
0
    if(query) {
1218
0
      size_t qlen = pathlen - (query - path);
1219
0
      ures = handle_query(u, query, qlen, flags);
1220
0
      pathlen -= qlen;
1221
0
    }
1222
0
  }
1223
0
  if(!ures)
1224
    /* the fragment and query parts are trimmed off from the path */
1225
0
    ures = handle_path(u, path, pathlen, flags, is_file);
1226
0
  if(!ures) {
1227
0
    u->host = curlx_dyn_ptr(&host);
1228
0
    return CURLUE_OK;
1229
0
  }
1230
0
fail:
1231
0
  curlx_dyn_free(&host);
1232
0
  free_urlhandle(u);
1233
0
  return ures;
1234
0
}
1235
1236
/*
1237
 * Parse the URL and, if successful, replace everything in the Curl_URL struct.
1238
 */
1239
static CURLUcode parseurl_and_replace(const char *url, CURLU *u,
1240
                                      unsigned int flags)
1241
0
{
1242
0
  CURLUcode ures;
1243
0
  CURLU tmpurl;
1244
0
  memset(&tmpurl, 0, sizeof(tmpurl));
1245
0
  ures = parseurl(url, &tmpurl, flags);
1246
0
  if(!ures) {
1247
0
    free_urlhandle(u);
1248
0
    *u = tmpurl;
1249
0
  }
1250
0
  return ures;
1251
0
}
1252
1253
/*
1254
 * Concatenate a relative URL onto a base URL making it absolute.
1255
 */
1256
static CURLUcode redirect_url(const char *base, const char *relurl,
1257
                              CURLU *u, unsigned int flags)
1258
0
{
1259
0
  struct dynbuf urlbuf;
1260
0
  bool host_changed = FALSE;
1261
0
  const char *useurl = relurl;
1262
0
  const char *cutoff = NULL;
1263
0
  size_t prelen;
1264
0
  CURLUcode uc;
1265
  /* this can get here with a NULL u->scheme only if asked to use the default
1266
     scheme, so allow fallback to that */
1267
0
  const char *scheme = u->scheme ? u->scheme : DEFAULT_SCHEME;
1268
1269
  /* protsep points to the start of the hostname, after [scheme]:// */
1270
0
  const char *protsep = base + strlen(scheme) + 3;
1271
0
  DEBUGASSERT(base && relurl && u); /* all set here */
1272
0
  if(!base)
1273
0
    return CURLUE_MALFORMED_INPUT; /* should never happen */
1274
1275
  /* handle different relative URL types */
1276
0
  switch(relurl[0]) {
1277
0
  case '/':
1278
0
    if(relurl[1] == '/') {
1279
      /* protocol-relative URL: //example.com/path */
1280
0
      cutoff = protsep;
1281
0
      useurl = &relurl[2];
1282
0
      host_changed = TRUE;
1283
0
    }
1284
0
    else
1285
      /* absolute /path */
1286
0
      cutoff = strchr(protsep, '/');
1287
0
    break;
1288
1289
0
  case '#':
1290
    /* fragment-only change */
1291
0
    if(u->fragment_present)
1292
0
      cutoff = strchr(protsep, '#');
1293
0
    break;
1294
1295
0
  default:
1296
    /* path or query-only change */
1297
0
    if(u->query_present)
1298
      /* remove existing query */
1299
0
      cutoff = strchr(protsep, '?');
1300
0
    else if(u->fragment_present)
1301
      /* Remove existing fragment */
1302
0
      cutoff = strchr(protsep, '#');
1303
1304
0
    if(relurl[0] != '?') {
1305
      /* append a relative path after the last slash */
1306
0
      cutoff = memrchr(protsep, '/',
1307
0
                       cutoff ? (size_t)(cutoff - protsep) : strlen(protsep));
1308
0
      if(cutoff)
1309
0
        cutoff++; /* truncate after last slash */
1310
0
    }
1311
0
    break;
1312
0
  }
1313
1314
0
  prelen = cutoff ? (size_t)(cutoff - base) : strlen(base);
1315
1316
  /* build new URL */
1317
0
  curlx_dyn_init(&urlbuf, CURL_MAX_INPUT_LENGTH);
1318
1319
0
  if(!curlx_dyn_addn(&urlbuf, base, prelen) &&
1320
0
     !urlencode_str(&urlbuf, useurl, strlen(useurl), !host_changed,
1321
0
                    QUERY_NOT_YET)) {
1322
0
    uc = parseurl_and_replace(curlx_dyn_ptr(&urlbuf), u,
1323
0
                              flags & ~U_CURLU_PATH_AS_IS);
1324
0
  }
1325
0
  else
1326
0
    uc = CURLUE_OUT_OF_MEMORY;
1327
1328
0
  curlx_dyn_free(&urlbuf);
1329
0
  return uc;
1330
0
}
1331
1332
/*
1333
 */
1334
CURLU *curl_url(void)
1335
0
{
1336
0
  return curlx_calloc(1, sizeof(struct Curl_URL));
1337
0
}
1338
1339
void curl_url_cleanup(CURLU *u)
1340
0
{
1341
0
  if(u) {
1342
0
    free_urlhandle(u);
1343
0
    curlx_free(u);
1344
0
  }
1345
0
}
1346
1347
#define DUP(dest, src, name)                    \
1348
0
  do {                                          \
1349
0
    if((src)->name) {                           \
1350
0
      (dest)->name = curlx_strdup((src)->name); \
1351
0
      if(!(dest)->name)                         \
1352
0
        goto fail;                              \
1353
0
    }                                           \
1354
0
  } while(0)
1355
1356
CURLU *curl_url_dup(const CURLU *in)
1357
0
{
1358
0
  struct Curl_URL *u = curlx_calloc(1, sizeof(struct Curl_URL));
1359
0
  if(u) {
1360
0
    DUP(u, in, scheme);
1361
0
    DUP(u, in, user);
1362
0
    DUP(u, in, password);
1363
0
    DUP(u, in, options);
1364
0
    DUP(u, in, host);
1365
0
    DUP(u, in, path);
1366
0
    DUP(u, in, query);
1367
0
    DUP(u, in, fragment);
1368
0
    DUP(u, in, zoneid);
1369
0
    u->portnum = in->portnum;
1370
0
    u->port_present = in->port_present;
1371
0
    u->fragment_present = in->fragment_present;
1372
0
    u->query_present = in->query_present;
1373
0
  }
1374
0
  return u;
1375
0
fail:
1376
0
  curl_url_cleanup(u);
1377
0
  return NULL;
1378
0
}
1379
1380
#ifndef USE_IDN
1381
#define host_decode(x, y) CURLUE_LACKS_IDN
1382
#define host_encode(x, y) CURLUE_LACKS_IDN
1383
#else
1384
static CURLUcode host_decode(const char *host, char **allochost)
1385
0
{
1386
0
  CURLcode result = Curl_idn_decode(host, allochost);
1387
0
  if(result)
1388
0
    return (result == CURLE_OUT_OF_MEMORY) ?
1389
0
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1390
0
  return CURLUE_OK;
1391
0
}
1392
1393
static CURLUcode host_encode(const char *host, char **allochost)
1394
0
{
1395
0
  CURLcode result = Curl_idn_encode(host, allochost);
1396
0
  if(result)
1397
0
    return (result == CURLE_OUT_OF_MEMORY) ?
1398
0
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1399
0
  return CURLUE_OK;
1400
0
}
1401
#endif
1402
1403
static CURLUcode urlget_format(const CURLU *u, CURLUPart what,
1404
                               const char *ptr, char **partp,
1405
                               bool plusdecode, unsigned int flags)
1406
0
{
1407
0
  CURLUcode uc = CURLUE_OK;
1408
0
  size_t partlen = strlen(ptr);
1409
0
  bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0;
1410
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1411
0
  bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST);
1412
0
  bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST);
1413
0
  char *part = curlx_memdup0(ptr, partlen);
1414
0
  *partp = NULL;
1415
0
  if(!part)
1416
0
    return CURLUE_OUT_OF_MEMORY;
1417
0
  if(plusdecode) {
1418
    /* convert + to space */
1419
0
    char *plus = part;
1420
0
    size_t i = 0;
1421
0
    for(i = 0; i < partlen; ++plus, i++) {
1422
0
      if(*plus == '+')
1423
0
        *plus = ' ';
1424
0
    }
1425
0
  }
1426
0
  if(urldecode) {
1427
0
    char *decoded;
1428
0
    size_t dlen;
1429
    /* this unconditional rejection of control bytes is documented API
1430
       behavior */
1431
0
    CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen,
1432
0
                                     REJECT_CTRL);
1433
0
    curlx_free(part);
1434
0
    if(result)
1435
0
      return CURLUE_URLDECODE;
1436
0
    part = decoded;
1437
0
    partlen = dlen;
1438
0
  }
1439
0
  if(urlencode) {
1440
0
    struct dynbuf enc;
1441
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1442
0
    uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ?
1443
0
                       QUERY_YES : QUERY_NO);
1444
0
    curlx_free(part);
1445
0
    if(uc)
1446
0
      return uc;
1447
0
    part = curlx_dyn_ptr(&enc);
1448
0
  }
1449
0
  else if(punycode) {
1450
0
    if(!Curl_is_ASCII_name(u->host)) {
1451
0
      char *punyversion = NULL;
1452
0
      uc = host_decode(part, &punyversion);
1453
0
      curlx_free(part);
1454
0
      if(uc)
1455
0
        return uc;
1456
0
      part = punyversion;
1457
0
    }
1458
0
  }
1459
0
  else if(depunyfy) {
1460
0
    if(Curl_is_ASCII_name(u->host)) {
1461
0
      char *unpunified = NULL;
1462
0
      uc = host_encode(part, &unpunified);
1463
0
      curlx_free(part);
1464
0
      if(uc)
1465
0
        return uc;
1466
0
      part = unpunified;
1467
0
    }
1468
0
  }
1469
0
  *partp = part;
1470
0
  return CURLUE_OK;
1471
0
}
1472
1473
static CURLUcode file_url(const CURLU *u, char **part,
1474
                          const char *fragmentsep,
1475
                          const char *querysep)
1476
0
{
1477
0
  char *url = curl_maprintf("file://%s%s%s%s%s",
1478
0
                            u->path, querysep, u->query ? u->query : "",
1479
0
                            fragmentsep, u->fragment ? u->fragment : "");
1480
0
  if(!url)
1481
0
    return CURLUE_OUT_OF_MEMORY;
1482
1483
0
  *part = url;
1484
0
  return CURLUE_OK;
1485
0
}
1486
1487
static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags)
1488
0
{
1489
0
  char *url;
1490
0
  char *allochost = NULL;
1491
0
  const char *fragmentsep =
1492
0
    (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ?
1493
0
    "#" : "";
1494
0
  const char *querysep = ((u->query && u->query[0]) ||
1495
0
                          (u->query_present && flags & CURLU_GET_EMPTY)) ?
1496
0
    "?" : "";
1497
0
  char portbuf[7];
1498
0
  if(curl_strequal("file", u->scheme))
1499
0
    return file_url(u, part, fragmentsep, querysep);
1500
0
  else if(!u->host)
1501
0
    return CURLUE_NO_HOST;
1502
0
  else {
1503
0
    const char *scheme;
1504
0
    char *options = u->options;
1505
0
    char *port = NULL;
1506
0
    const struct Curl_scheme *h = NULL;
1507
0
    char schemebuf[MAX_SCHEME_LEN + 5];
1508
0
    if(u->scheme)
1509
0
      scheme = u->scheme;
1510
0
    else if(flags & CURLU_DEFAULT_SCHEME)
1511
0
      scheme = DEFAULT_SCHEME;
1512
0
    else
1513
0
      return CURLUE_NO_SCHEME;
1514
1515
0
    if(u->port_present) {
1516
0
      curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1517
0
      port = portbuf;
1518
0
    }
1519
1520
0
    h = Curl_get_scheme(scheme);
1521
0
    if(h) {
1522
0
      if(!u->port_present && (flags & CURLU_DEFAULT_PORT)) {
1523
        /* there is no stored port number, but asked to deliver a default one
1524
           for the scheme */
1525
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1526
0
        port = portbuf;
1527
0
      }
1528
0
      else if(u->port_present && (h->defport == u->portnum) &&
1529
0
              (flags & CURLU_NO_DEFAULT_PORT)) {
1530
        /* there is a stored port number, but asked to inhibit if it matches
1531
           the default port for the scheme */
1532
0
        port = NULL;
1533
0
      }
1534
1535
0
      if(!(h->flags & PROTOPT_URLOPTIONS))
1536
0
        options = NULL;
1537
0
    }
1538
1539
0
    if(u->host[0] == '[') {
1540
0
      if(u->zoneid) {
1541
        /* make it '[ host %25 zoneid ]' */
1542
0
        struct dynbuf enc;
1543
0
        size_t hostlen = strlen(u->host);
1544
0
        curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1545
0
        if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
1546
0
                          u->zoneid))
1547
0
          return CURLUE_OUT_OF_MEMORY;
1548
0
        allochost = curlx_dyn_ptr(&enc);
1549
0
      }
1550
0
    }
1551
0
    else if(flags & CURLU_URLENCODE) {
1552
0
      allochost = curl_easy_escape(NULL, u->host, 0);
1553
0
      if(!allochost)
1554
0
        return CURLUE_OUT_OF_MEMORY;
1555
0
    }
1556
0
    else if(flags & CURLU_PUNYCODE) {
1557
0
      if(!Curl_is_ASCII_name(u->host)) {
1558
0
        CURLUcode ret = host_decode(u->host, &allochost);
1559
0
        if(ret)
1560
0
          return ret;
1561
0
      }
1562
0
    }
1563
0
    else if(flags & CURLU_PUNY2IDN) {
1564
0
      if(Curl_is_ASCII_name(u->host)) {
1565
0
        CURLUcode ret = host_encode(u->host, &allochost);
1566
0
        if(ret)
1567
0
          return ret;
1568
0
      }
1569
0
    }
1570
1571
0
    if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme)
1572
0
      curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme);
1573
0
    else
1574
0
      schemebuf[0] = 0;
1575
1576
0
    url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1577
0
                        schemebuf,
1578
0
                        u->user ? u->user : "",
1579
0
                        u->password ? ":" : "",
1580
0
                        u->password ? u->password : "",
1581
0
                        options ? ";" : "",
1582
0
                        options ? options : "",
1583
0
                        (u->user || u->password || options) ? "@" : "",
1584
0
                        allochost ? allochost : u->host,
1585
0
                        port ? ":" : "",
1586
0
                        port ? port : "",
1587
0
                        u->path ? u->path : "/",
1588
0
                        querysep,
1589
0
                        u->query ? u->query : "",
1590
0
                        fragmentsep,
1591
0
                        u->fragment ? u->fragment : "");
1592
0
    curlx_free(allochost);
1593
0
  }
1594
0
  if(!url)
1595
0
    return CURLUE_OUT_OF_MEMORY;
1596
0
  *part = url;
1597
0
  return CURLUE_OK;
1598
0
}
1599
1600
CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
1601
                       char **part, unsigned int flags)
1602
0
{
1603
0
  const char *ptr;
1604
0
  CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
1605
0
  char portbuf[7];
1606
0
  bool plusdecode = FALSE;
1607
0
  if(!u)
1608
0
    return CURLUE_BAD_HANDLE;
1609
0
  if(!part)
1610
0
    return CURLUE_BAD_PARTPOINTER;
1611
0
  *part = NULL;
1612
1613
0
  switch(what) {
1614
0
  case CURLUPART_SCHEME:
1615
0
    ptr = u->scheme;
1616
0
    ifmissing = CURLUE_NO_SCHEME;
1617
0
    flags &= ~U_CURLU_URLDECODE; /* never for schemes */
1618
0
    if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme)
1619
0
      return CURLUE_NO_SCHEME;
1620
0
    break;
1621
0
  case CURLUPART_USER:
1622
0
    ptr = u->user;
1623
0
    ifmissing = CURLUE_NO_USER;
1624
0
    break;
1625
0
  case CURLUPART_PASSWORD:
1626
0
    ptr = u->password;
1627
0
    ifmissing = CURLUE_NO_PASSWORD;
1628
0
    break;
1629
0
  case CURLUPART_OPTIONS:
1630
0
    ptr = u->options;
1631
0
    ifmissing = CURLUE_NO_OPTIONS;
1632
0
    break;
1633
0
  case CURLUPART_HOST:
1634
0
    ptr = u->host;
1635
0
    ifmissing = CURLUE_NO_HOST;
1636
0
    break;
1637
0
  case CURLUPART_ZONEID:
1638
0
    ptr = u->zoneid;
1639
0
    ifmissing = CURLUE_NO_ZONEID;
1640
0
    break;
1641
0
  case CURLUPART_PORT:
1642
0
    ptr = NULL;
1643
0
    ifmissing = CURLUE_NO_PORT;
1644
0
    flags &= ~U_CURLU_URLDECODE; /* never for port */
1645
0
    if(u->port_present) {
1646
0
      const struct Curl_scheme *h = u->scheme ?
1647
0
                                    Curl_get_scheme(u->scheme) : NULL;
1648
      /* there is a stored port number, but ask to inhibit if
1649
         it matches the default one for the scheme */
1650
0
      if(h && (h->defport == u->portnum) &&
1651
0
         (flags & CURLU_NO_DEFAULT_PORT)) {
1652
0
        ptr = NULL;
1653
0
      }
1654
0
      else {
1655
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", u->portnum);
1656
0
        ptr = portbuf;
1657
0
      }
1658
0
    }
1659
0
    else if((flags & CURLU_DEFAULT_PORT) && u->scheme) {
1660
      /* there is no stored port number, but asked to deliver
1661
         a default one for the scheme */
1662
0
      const struct Curl_scheme *h = Curl_get_scheme(u->scheme);
1663
0
      if(h) {
1664
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1665
0
        ptr = portbuf;
1666
0
      }
1667
0
    }
1668
0
    break;
1669
0
  case CURLUPART_PATH:
1670
0
    ptr = u->path;
1671
0
    if(!ptr)
1672
0
      ptr = "/";
1673
0
    break;
1674
0
  case CURLUPART_QUERY:
1675
0
    ptr = u->query;
1676
0
    ifmissing = CURLUE_NO_QUERY;
1677
0
    plusdecode = flags & CURLU_URLDECODE;
1678
0
    if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY))
1679
      /* there was a blank query and the user do not ask for it */
1680
0
      ptr = NULL;
1681
0
    break;
1682
0
  case CURLUPART_FRAGMENT:
1683
0
    ptr = u->fragment;
1684
0
    ifmissing = CURLUE_NO_FRAGMENT;
1685
0
    if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY)
1686
      /* there was a blank fragment and the user asks for it */
1687
0
      ptr = "";
1688
0
    break;
1689
0
  case CURLUPART_URL:
1690
0
    return urlget_url(u, part, flags);
1691
0
  default:
1692
0
    ptr = NULL;
1693
0
    break;
1694
0
  }
1695
0
  if(ptr)
1696
0
    return urlget_format(u, what, ptr, part, plusdecode, flags);
1697
1698
0
  return ifmissing;
1699
0
}
1700
1701
static CURLUcode set_url_scheme(CURLU *u, const char *scheme,
1702
                                unsigned int flags)
1703
0
{
1704
0
  size_t plen = strlen(scheme);
1705
0
  const struct Curl_scheme *h = NULL;
1706
0
  if((plen > MAX_SCHEME_LEN) || (plen < 1))
1707
    /* too long or too short */
1708
0
    return CURLUE_BAD_SCHEME;
1709
  /* verify that it is a fine scheme */
1710
0
  h = Curl_get_scheme(scheme);
1711
0
  if(!(flags & CURLU_NON_SUPPORT_SCHEME) && (!h || !h->run))
1712
0
    return CURLUE_UNSUPPORTED_SCHEME;
1713
0
  if(!h) {
1714
0
    const char *s = scheme;
1715
0
    if(ISALPHA(*s)) {
1716
      /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
1717
0
      s++;
1718
0
      while(--plen) {
1719
0
        if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.'))
1720
0
          s++; /* fine */
1721
0
        else
1722
0
          return CURLUE_BAD_SCHEME;
1723
0
      }
1724
0
    }
1725
0
    else
1726
0
      return CURLUE_BAD_SCHEME;
1727
0
  }
1728
0
  u->guessed_scheme = FALSE;
1729
0
  return CURLUE_OK;
1730
0
}
1731
1732
static CURLUcode set_url_port(CURLU *u, const char *provided_port)
1733
0
{
1734
0
  curl_off_t port;
1735
0
  if(!ISDIGIT(provided_port[0]))
1736
    /* not a number */
1737
0
    return CURLUE_BAD_PORT_NUMBER;
1738
0
  if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port)
1739
    /* weirdly provided number, not good! */
1740
0
    return CURLUE_BAD_PORT_NUMBER;
1741
0
  u->portnum = (uint16_t)port;
1742
0
  u->port_present = TRUE;
1743
0
  return CURLUE_OK;
1744
0
}
1745
1746
static CURLUcode set_url(CURLU *u, const char *url, size_t part_size,
1747
                         unsigned int flags)
1748
0
{
1749
  /*
1750
   * Allow a new URL to replace the existing (if any) contents.
1751
   *
1752
   * If the existing contents is enough for a URL, allow a relative URL to
1753
   * replace it.
1754
   */
1755
0
  CURLUcode uc;
1756
0
  char *oldurl = NULL;
1757
1758
0
  if(!part_size) {
1759
    /* a blank URL is not a valid URL unless we already have a complete one
1760
       and this is a redirect */
1761
0
    uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1762
0
    if(!uc) {
1763
      /* success, meaning the "" is a fine relative URL, and the new URL
1764
         inherits scheme/authority/path/query, but not fragment, from the
1765
         existing URL (RFC 3986 section 5.2.2) */
1766
0
      curlx_safefree(u->fragment);
1767
0
      u->fragment_present = FALSE;
1768
0
      curlx_free(oldurl);
1769
0
      return CURLUE_OK;
1770
0
    }
1771
0
    if(uc == CURLUE_OUT_OF_MEMORY)
1772
0
      return uc;
1773
0
    return CURLUE_MALFORMED_INPUT;
1774
0
  }
1775
1776
  /* if the new URL is absolute replace the existing with the new. */
1777
0
  if(Curl_is_absolute_url(url, NULL, 0,
1778
0
                          flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME)))
1779
0
    return parseurl_and_replace(url, u, flags);
1780
1781
  /* if the old URL is incomplete (we cannot get an absolute URL in
1782
     'oldurl'), replace the existing with the new.
1783
     Always include "scheme://" to make the URL "complete" */
1784
  /* Preserve empty query/fragment separators: they affect where relative
1785
     references splice into the base URL. */
1786
0
  uc = curl_url_get(u, CURLUPART_URL, &oldurl,
1787
0
                    (flags & ~CURLU_NO_GUESS_SCHEME) | CURLU_GET_EMPTY);
1788
0
  if(uc == CURLUE_OUT_OF_MEMORY)
1789
0
    return uc;
1790
0
  else if(uc)
1791
0
    return parseurl_and_replace(url, u, flags);
1792
1793
0
  DEBUGASSERT(oldurl); /* it is set here */
1794
  /* apply the relative part to create a new URL */
1795
0
  uc = redirect_url(oldurl, url, u, flags);
1796
0
  curlx_free(oldurl);
1797
0
  return uc;
1798
0
}
1799
1800
static CURLUcode urlset_clear(CURLU *u, CURLUPart what)
1801
0
{
1802
0
  switch(what) {
1803
0
  case CURLUPART_URL:
1804
0
    free_urlhandle(u);
1805
0
    memset(u, 0, sizeof(struct Curl_URL));
1806
0
    break;
1807
0
  case CURLUPART_SCHEME:
1808
0
    curlx_safefree(u->scheme);
1809
0
    u->guessed_scheme = FALSE;
1810
0
    break;
1811
0
  case CURLUPART_USER:
1812
0
    curlx_safefree(u->user);
1813
0
    break;
1814
0
  case CURLUPART_PASSWORD:
1815
0
    curlx_strzero(u->password);
1816
0
    curlx_safefree(u->password);
1817
0
    break;
1818
0
  case CURLUPART_OPTIONS:
1819
0
    curlx_safefree(u->options);
1820
0
    break;
1821
0
  case CURLUPART_HOST:
1822
0
    curlx_safefree(u->host);
1823
0
    break;
1824
0
  case CURLUPART_ZONEID:
1825
0
    curlx_safefree(u->zoneid);
1826
0
    break;
1827
0
  case CURLUPART_PORT:
1828
0
    u->portnum = 0;
1829
0
    u->port_present = FALSE;
1830
0
    break;
1831
0
  case CURLUPART_PATH:
1832
0
    curlx_safefree(u->path);
1833
0
    break;
1834
0
  case CURLUPART_QUERY:
1835
0
    curlx_safefree(u->query);
1836
0
    u->query_present = FALSE;
1837
0
    break;
1838
0
  case CURLUPART_FRAGMENT:
1839
0
    curlx_safefree(u->fragment);
1840
0
    u->fragment_present = FALSE;
1841
0
    break;
1842
0
  default:
1843
0
    return CURLUE_UNKNOWN_PART;
1844
0
  }
1845
0
  return CURLUE_OK;
1846
0
}
1847
1848
static bool allowed_in_path(unsigned char x)
1849
0
{
1850
0
  switch(x) {
1851
0
  case '!':
1852
0
  case '$':
1853
0
  case '&':
1854
0
  case '\'':
1855
0
  case '(':
1856
0
  case ')':
1857
0
  case '{':
1858
0
  case '}':
1859
0
  case '[':
1860
0
  case ']':
1861
0
  case '*':
1862
0
  case '+':
1863
0
  case ',':
1864
0
  case ';':
1865
0
  case '=':
1866
0
  case ':':
1867
0
  case '@':
1868
0
  case '/':
1869
0
    return TRUE;
1870
0
  }
1871
0
  return FALSE;
1872
0
}
1873
1874
static CURLUcode url_encode_part(struct dynbuf *encp,
1875
                                 const char *part,
1876
                                 bool plusencode,
1877
                                 bool pathmode,
1878
                                 bool equalsencode)
1879
0
{
1880
0
  const unsigned char *i;
1881
1882
0
  for(i = (const unsigned char *)part; *i; i++) {
1883
0
    CURLcode result;
1884
0
    if((*i == ' ') && plusencode)
1885
0
      result = curlx_dyn_addn(encp, "+", 1);
1886
0
    else if(ISUNRESERVED(*i) ||
1887
0
            (pathmode && allowed_in_path(*i)) ||
1888
0
            ((*i == '=') && equalsencode)) {
1889
0
      if((*i == '=') && equalsencode)
1890
        /* only skip the first equals sign */
1891
0
        equalsencode = FALSE;
1892
0
      result = curlx_dyn_addn(encp, i, 1);
1893
0
    }
1894
0
    else {
1895
0
      unsigned char out[3] = { '%' };
1896
0
      Curl_hexbyte(&out[1], *i);
1897
0
      result = curlx_dyn_addn(encp, out, 3);
1898
0
    }
1899
0
    if(result)
1900
0
      return cc2cu(result);
1901
0
  }
1902
0
  return CURLUE_OK;
1903
0
}
1904
1905
static CURLUcode url_uppercasehex_part(struct dynbuf *encp,
1906
                                       const char *part)
1907
0
{
1908
0
  char *p;
1909
0
  CURLcode result = curlx_dyn_add(encp, part);
1910
0
  if(result)
1911
0
    return cc2cu(result);
1912
0
  p = curlx_dyn_ptr(encp);
1913
0
  while(*p) {
1914
    /* make sure percent encoded are upper case */
1915
0
    if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
1916
0
       (ISLOWER(p[1]) || ISLOWER(p[2]))) {
1917
0
      p[1] = Curl_raw_toupper(p[1]);
1918
0
      p[2] = Curl_raw_toupper(p[2]);
1919
0
      p += 3;
1920
0
    }
1921
0
    else
1922
0
      p++;
1923
0
  }
1924
0
  return CURLUE_OK;
1925
0
}
1926
1927
static CURLUcode url_append_query(CURLU *u, struct dynbuf *encp)
1928
0
{
1929
  /* Append the 'encp' string onto the old query. Add a '&' separator if none
1930
     is already present at the end of the existing query */
1931
1932
0
  size_t querylen = u->query ? strlen(u->query) : 0;
1933
0
  bool addamperand = querylen && (u->query[querylen - 1] != '&');
1934
0
  if(querylen) {
1935
0
    struct dynbuf qbuf;
1936
0
    CURLcode result;
1937
0
    const char *newp = curlx_dyn_ptr(encp);
1938
0
    curlx_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH);
1939
1940
    /* add original query */
1941
0
    result = curlx_dyn_addn(&qbuf, u->query, querylen);
1942
0
    if(!result && addamperand)
1943
      /* add ampersand */
1944
0
      result = curlx_dyn_addn(&qbuf, "&", 1);
1945
0
    if(!result)
1946
      /* add new query part */
1947
0
      result = curlx_dyn_add(&qbuf, newp);
1948
0
    if(result)
1949
0
      goto nomem;
1950
0
    curlx_dyn_free(encp);
1951
0
    curlx_free(u->query);
1952
0
    u->query = curlx_dyn_ptr(&qbuf);
1953
0
    return CURLUE_OK;
1954
0
nomem:
1955
0
    curlx_dyn_free(encp);
1956
0
    return cc2cu(result);
1957
0
  }
1958
0
  else {
1959
0
    curlx_free(u->query);
1960
0
    u->query = curlx_dyn_ptr(encp);
1961
0
  }
1962
0
  return CURLUE_OK;
1963
0
}
1964
1965
static CURLUcode url_sethost(CURLU *u, struct dynbuf *encp,
1966
                             bool urlencode,
1967
                             unsigned int flags)
1968
0
{
1969
0
  size_t n = curlx_dyn_len(encp);
1970
0
  bool bad = FALSE;
1971
0
  char *newp = curlx_dyn_ptr(encp);
1972
0
  if(!n)
1973
    /* an empty hostname is okay if told so */
1974
0
    bad = (flags & CURLU_NO_AUTHORITY) ? FALSE : TRUE;
1975
0
  else if(!urlencode) {
1976
    /* if the hostname part was not URL encoded here, it was set already URL
1977
       encoded so we need to decode it to check */
1978
0
    size_t dlen;
1979
0
    char *decoded = NULL;
1980
0
    CURLcode result = Curl_urldecode(newp, n, &decoded, &dlen, REJECT_CTRL);
1981
0
    if(result || hostname_check(u, decoded, dlen))
1982
0
      bad = TRUE;
1983
0
    curlx_free(decoded);
1984
0
  }
1985
0
  else if(hostname_check(u, newp, n))
1986
0
    bad = TRUE;
1987
0
  if(bad) {
1988
0
    curlx_dyn_free(encp);
1989
0
    return CURLUE_BAD_HOSTNAME;
1990
0
  }
1991
0
  return CURLUE_OK;
1992
0
}
1993
1994
CURLUcode curl_url_set(CURLU *u, CURLUPart what,
1995
                       const char *part, unsigned int flags)
1996
0
{
1997
0
  char **storep = NULL;
1998
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1999
0
  bool plusencode = FALSE;
2000
0
  bool pathmode = FALSE;
2001
0
  bool leadingslash = FALSE;
2002
0
  bool appendquery = FALSE;
2003
0
  bool equalsencode = FALSE;
2004
0
  size_t nalloc;
2005
2006
0
  if(!u)
2007
0
    return CURLUE_BAD_HANDLE;
2008
0
  if(!part)
2009
    /* setting a part to NULL clears it */
2010
0
    return urlset_clear(u, what);
2011
2012
0
  nalloc = strlen(part);
2013
0
  if(nalloc > CURL_MAX_INPUT_LENGTH)
2014
    /* excessive input length */
2015
0
    return CURLUE_MALFORMED_INPUT;
2016
2017
0
  switch(what) {
2018
0
  case CURLUPART_SCHEME: {
2019
0
    CURLUcode status = set_url_scheme(u, part, flags);
2020
0
    if(status)
2021
0
      return status;
2022
0
    storep = &u->scheme;
2023
0
    urlencode = FALSE; /* never */
2024
0
    break;
2025
0
  }
2026
0
  case CURLUPART_USER:
2027
0
    storep = &u->user;
2028
0
    break;
2029
0
  case CURLUPART_PASSWORD:
2030
0
    storep = &u->password;
2031
0
    break;
2032
0
  case CURLUPART_OPTIONS:
2033
0
    storep = &u->options;
2034
0
    break;
2035
0
  case CURLUPART_HOST:
2036
0
    storep = &u->host;
2037
0
    curlx_safefree(u->zoneid);
2038
0
    break;
2039
0
  case CURLUPART_ZONEID:
2040
0
    storep = &u->zoneid;
2041
0
    break;
2042
0
  case CURLUPART_PORT:
2043
0
    return set_url_port(u, part);
2044
0
  case CURLUPART_PATH:
2045
0
    pathmode = TRUE;
2046
0
    leadingslash = TRUE; /* enforce */
2047
0
    storep = &u->path;
2048
0
    break;
2049
0
  case CURLUPART_QUERY:
2050
0
    plusencode = urlencode;
2051
0
    appendquery = (flags & CURLU_APPENDQUERY) ? 1 : 0;
2052
0
    equalsencode = appendquery;
2053
0
    storep = &u->query;
2054
0
    u->query_present = TRUE;
2055
0
    break;
2056
0
  case CURLUPART_FRAGMENT:
2057
0
    storep = &u->fragment;
2058
0
    u->fragment_present = TRUE;
2059
0
    break;
2060
0
  case CURLUPART_URL:
2061
0
    return set_url(u, part, nalloc, flags);
2062
0
  default:
2063
0
    return CURLUE_UNKNOWN_PART;
2064
0
  }
2065
0
  DEBUGASSERT(storep);
2066
0
  {
2067
0
    const char *newp = NULL;
2068
0
    struct dynbuf enc;
2069
0
    CURLUcode status;
2070
0
    curlx_dyn_init(&enc, (nalloc * 3) + 1 + leadingslash);
2071
2072
0
    if(leadingslash && (part[0] != '/')) {
2073
0
      CURLcode result = curlx_dyn_addn(&enc, "/", 1);
2074
0
      if(result)
2075
0
        return cc2cu(result);
2076
0
    }
2077
0
    if(urlencode)
2078
0
      status = url_encode_part(&enc, part, plusencode, pathmode, equalsencode);
2079
0
    else
2080
0
      status = url_uppercasehex_part(&enc, part);
2081
0
    if(!status) {
2082
0
      newp = curlx_dyn_ptr(&enc);
2083
2084
0
      if(appendquery && newp)
2085
0
        return url_append_query(u, &enc);
2086
0
      else if(what == CURLUPART_HOST)
2087
0
        status = url_sethost(u, &enc, urlencode, flags);
2088
0
    }
2089
0
    if(status)
2090
0
      return status;
2091
2092
0
    if(what == CURLUPART_PASSWORD)
2093
0
      curlx_strzero(*storep);
2094
0
    curlx_free(*storep);
2095
0
    *storep = (char *)CURL_UNCONST(newp);
2096
0
  }
2097
0
  return CURLUE_OK;
2098
0
}
2099
2100
bool Curl_url_same_origin(CURLU *base, CURLU *href)
2101
0
{
2102
0
  const struct Curl_scheme *s = NULL;
2103
2104
  /* base must be an absolute URL */
2105
0
  if(!base->scheme || !base->host)
2106
0
    return FALSE;
2107
0
  if(href->scheme && !curl_strequal(base->scheme, href->scheme))
2108
0
    return FALSE;
2109
0
  if(href->host) {
2110
0
    if(!curl_strequal(base->host, href->host))
2111
0
      return FALSE;
2112
2113
0
    if(base->port_present != href->port_present) {
2114
      /* one is present, one is not */
2115
0
      s = Curl_get_scheme(base->scheme);
2116
0
      if(!s) /* Cannot match default port for unknown scheme */
2117
0
        return FALSE;
2118
      /* to match, the present one must be the default port */
2119
0
      if((base->port_present && (base->portnum != s->defport)) ||
2120
0
         (href->port_present && (href->portnum != s->defport)))
2121
0
        return FALSE;
2122
0
    }
2123
0
    else if(base->portnum != href->portnum) /* both present or missing */
2124
0
      return FALSE;
2125
2126
0
    if(!curl_strequal(base->zoneid ? base->zoneid : "",
2127
0
                      href->zoneid ? href->zoneid : ""))
2128
0
      return FALSE;
2129
0
  }
2130
0
  else if(href->port_present) /* no host in href, then there must be no port */
2131
0
    return FALSE;
2132
0
  return TRUE;
2133
0
}
2134
2135
CURLUcode Curl_url_get_port(CURLU *u, uint16_t *pport)
2136
0
{
2137
0
  if(u->port_present) {
2138
0
    *pport = u->portnum;
2139
0
    return CURLUE_OK;
2140
0
  }
2141
0
  else if(u->scheme) {
2142
0
    const struct Curl_scheme *s = Curl_get_scheme(u->scheme);
2143
0
    if(s && s->defport) {
2144
0
      *pport = s->defport;
2145
0
      return CURLUE_OK;
2146
0
    }
2147
0
  }
2148
0
  *pport = 0;
2149
0
  return CURLUE_NO_PORT;
2150
0
}