Coverage Report

Created: 2026-07-16 06:10

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