Coverage Report

Created: 2026-05-30 06:06

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