Coverage Report

Created: 2026-06-15 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Utilities/cmcurl/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
  }
479
0
  return CURLUE_OK;
480
0
}
481
482
/*
483
 * Handle partial IPv4 numerical addresses and different bases, like
484
 * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc.
485
 *
486
 * If the given input string is syntactically wrong IPv4 or any part for
487
 * example is too big, this function returns HOST_NAME.
488
 *
489
 * Output the "normalized" version of that input string in plain quad decimal
490
 * integers.
491
 *
492
 * Returns the host type.
493
 *
494
 * @unittest 1675
495
 */
496
497
UNITTEST int ipv4_normalize(struct dynbuf *host);
498
UNITTEST int ipv4_normalize(struct dynbuf *host)
499
0
{
500
0
  bool done = FALSE;
501
0
  int n = 0;
502
0
  const char *c = curlx_dyn_ptr(host);
503
0
  unsigned int parts[4] = { 0, 0, 0, 0 };
504
0
  CURLcode result = CURLE_OK;
505
506
0
  if(*c == '[')
507
0
    return HOST_IPV6;
508
509
0
  while(!done) {
510
0
    int rc;
511
0
    curl_off_t l;
512
0
    if(*c == '0') {
513
0
      if(c[1] == 'x') {
514
0
        c += 2; /* skip the prefix */
515
0
        rc = curlx_str_hex(&c, &l, UINT_MAX);
516
0
      }
517
0
      else
518
0
        rc = curlx_str_octal(&c, &l, UINT_MAX);
519
0
    }
520
0
    else
521
0
      rc = curlx_str_number(&c, &l, UINT_MAX);
522
523
0
    if(rc)
524
0
      return HOST_NAME;
525
526
0
    parts[n] = (unsigned int)l;
527
528
0
    switch(*c) {
529
0
    case '.':
530
0
      if(n == 3)
531
0
        return HOST_NAME;
532
0
      n++;
533
0
      c++;
534
0
      break;
535
536
0
    case '\0':
537
0
      done = TRUE;
538
0
      break;
539
540
0
    default:
541
0
      return HOST_NAME;
542
0
    }
543
0
  }
544
545
0
  switch(n) {
546
0
  case 0: /* a -- 32 bits */
547
0
    curlx_dyn_reset(host);
548
549
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
550
0
                            (parts[0] >> 24),
551
0
                            ((parts[0] >> 16) & 0xff),
552
0
                            ((parts[0] >> 8) & 0xff),
553
0
                            (parts[0] & 0xff));
554
0
    break;
555
0
  case 1: /* a.b -- 8.24 bits */
556
0
    if((parts[0] > 0xff) || (parts[1] > 0xffffff))
557
0
      return HOST_NAME;
558
0
    curlx_dyn_reset(host);
559
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
560
0
                            (parts[0]),
561
0
                            ((parts[1] >> 16) & 0xff),
562
0
                            ((parts[1] >> 8) & 0xff),
563
0
                            (parts[1] & 0xff));
564
0
    break;
565
0
  case 2: /* a.b.c -- 8.8.16 bits */
566
0
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
567
0
      return HOST_NAME;
568
0
    curlx_dyn_reset(host);
569
0
    result = curlx_dyn_addf(host, "%u.%u.%u.%u",
570
0
                            (parts[0]),
571
0
                            (parts[1]),
572
0
                            ((parts[2] >> 8) & 0xff),
573
0
                            (parts[2] & 0xff));
574
0
    break;
575
0
  case 3: /* a.b.c.d -- 8.8.8.8 bits */
576
0
    if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
577
0
       (parts[3] > 0xff))
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]),
583
0
                            (parts[2]),
584
0
                            (parts[3]));
585
0
    break;
586
0
  }
587
0
  if(result)
588
0
    return HOST_ERROR;
589
0
  return HOST_IPV4;
590
0
}
591
592
/* if necessary, replace the host content with a URL decoded version */
593
static CURLUcode urldecode_host(struct dynbuf *host)
594
0
{
595
0
  const char *per;
596
0
  const char *hostname = curlx_dyn_ptr(host);
597
0
  per = strchr(hostname, '%');
598
0
  if(!per)
599
    /* nothing to decode */
600
0
    return CURLUE_OK;
601
0
  else {
602
    /* encoded */
603
0
    size_t dlen;
604
0
    char *decoded;
605
0
    CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
606
0
                                     REJECT_CTRL);
607
0
    if(result)
608
0
      return CURLUE_BAD_HOSTNAME;
609
0
    curlx_dyn_reset(host);
610
0
    result = curlx_dyn_addn(host, decoded, dlen);
611
0
    curlx_free(decoded);
612
0
    if(result)
613
0
      return cc2cu(result);
614
0
  }
615
616
0
  return CURLUE_OK;
617
0
}
618
619
static CURLUcode parse_authority(struct Curl_URL *u,
620
                                 const char *auth, size_t authlen,
621
                                 unsigned int flags,
622
                                 struct dynbuf *host,
623
                                 bool has_scheme)
624
0
{
625
0
  size_t offset;
626
0
  CURLUcode uc;
627
0
  CURLcode result;
628
629
  /*
630
   * Parse the login details and strip them out of the hostname.
631
   */
632
0
  uc = parse_hostname_login(u, auth, authlen, flags, &offset);
633
0
  if(uc)
634
0
    goto out;
635
636
0
  result = curlx_dyn_addn(host, auth + offset, authlen - offset);
637
0
  if(result) {
638
0
    uc = cc2cu(result);
639
0
    goto out;
640
0
  }
641
642
0
  uc = parse_port(u, host, has_scheme);
643
0
  if(uc)
644
0
    goto out;
645
646
0
  if(!curlx_dyn_len(host))
647
0
    return CURLUE_NO_HOST;
648
649
0
  switch(ipv4_normalize(host)) {
650
0
  case HOST_IPV4:
651
0
    break;
652
0
  case HOST_IPV6:
653
0
    uc = ipv6_parse(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
654
0
    break;
655
0
  case HOST_NAME:
656
0
    uc = urldecode_host(host);
657
0
    if(!uc)
658
0
      uc = hostname_check(u, curlx_dyn_ptr(host), curlx_dyn_len(host));
659
0
    break;
660
0
  case HOST_ERROR:
661
0
    uc = CURLUE_OUT_OF_MEMORY;
662
0
    break;
663
0
  default:
664
0
    uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */
665
0
    break;
666
0
  }
667
668
0
out:
669
0
  return uc;
670
0
}
671
672
/* used for HTTP/2 server push */
673
CURLUcode Curl_url_set_authority(CURLU *u, const char *authority)
674
0
{
675
0
  CURLUcode ures;
676
0
  struct dynbuf host;
677
678
0
  DEBUGASSERT(authority);
679
0
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
680
681
0
  ures = parse_authority(u, authority, strlen(authority),
682
0
                         CURLU_DISALLOW_USER, &host, !!u->scheme);
683
0
  if(ures)
684
0
    curlx_dyn_free(&host);
685
0
  else {
686
0
    curlx_free(u->host);
687
0
    u->host = curlx_dyn_ptr(&host);
688
0
  }
689
0
  return ures;
690
0
}
691
692
/*
693
 * "Remove Dot Segments"
694
 * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
695
 */
696
697
static bool is_dot(const char **str, size_t *clen)
698
0
{
699
0
  const char *p = *str;
700
0
  if(*p == '.') {
701
0
    (*str)++;
702
0
    (*clen)--;
703
0
    return TRUE;
704
0
  }
705
0
  else if((*clen >= 3) &&
706
0
          (p[0] == '%') && (p[1] == '2') && ((p[2] | 0x20) == 'e')) {
707
0
    *str += 3;
708
0
    *clen -= 3;
709
0
    return TRUE;
710
0
  }
711
0
  return FALSE;
712
0
}
713
714
0
#define ISSLASH(x) ((x) == '/')
715
716
/*
717
 * dedotdotify()
718
 *
719
 * This function gets a null-terminated path with dot and dotdot sequences
720
 * passed in and strips them off according to the rules in RFC 3986 section
721
 * 5.2.4.
722
 *
723
 * The function handles a path. It should not contain the query nor fragment.
724
 *
725
 * RETURNS
726
 *
727
 * Zero for success and 'out' set to an allocated dedotdotified string.
728
 *
729
 * @unittest 1395
730
 */
731
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp);
732
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp)
733
0
{
734
0
  struct dynbuf out;
735
0
  CURLcode result = CURLE_OK;
736
737
  /* variables for leading dot checks */
738
0
  const char *dinput = input;
739
0
  size_t dlen = clen;
740
741
0
  *outp = NULL;
742
  /* a single byte path cannot be cleaned up */
743
0
  if(clen < 2)
744
0
    return 0;
745
746
0
  curlx_dyn_init(&out, clen + 1);
747
748
  /* if the input buffer begins with a prefix of "../" or "./", then remove
749
     that prefix from the input buffer; otherwise, */
750
0
  if(is_dot(&dinput, &dlen)) {
751
0
    if(ISSLASH(*dinput)) {
752
      /* one dot followed by a slash */
753
0
      input = dinput + 1;
754
0
      clen = dlen - 1;
755
0
    }
756
757
    /* if the input buffer consists only of "." or "..", then remove
758
       that from the input buffer; otherwise, */
759
0
    else if(is_dot(&dinput, &dlen)) {
760
0
      if(!dlen)
761
        /* .. [end] */
762
0
        goto end;
763
0
      else if(ISSLASH(*dinput)) {
764
        /* ../ */
765
0
        input = dinput + 1;
766
0
        clen = dlen - 1;
767
0
      }
768
0
    }
769
0
  }
770
771
0
  while(clen && !result) { /* until end of path content */
772
0
    if(ISSLASH(*input)) {
773
0
      const char *p = &input[1];
774
0
      size_t blen = clen - 1;
775
      /* if the input buffer begins with a prefix of "/./" or "/.", where "."
776
         is a complete path segment, then replace that prefix with "/" in the
777
         input buffer; otherwise, */
778
0
      if(is_dot(&p, &blen)) {
779
0
        if(!blen) { /* /. */
780
0
          result = curlx_dyn_addn(&out, "/", 1);
781
0
          break;
782
0
        }
783
0
        else if(ISSLASH(*p)) { /* /./ */
784
0
          input = p;
785
0
          clen = blen;
786
0
          continue;
787
0
        }
788
789
        /* if the input buffer begins with a prefix of "/../" or "/..", where
790
           ".." is a complete path segment, then replace that prefix with "/"
791
           in the input buffer and remove the last segment and its preceding
792
           "/" (if any) from the output buffer; otherwise, */
793
0
        else if(is_dot(&p, &blen) && (ISSLASH(*p) || !blen)) {
794
          /* remove the last segment from the output buffer */
795
0
          size_t len = curlx_dyn_len(&out);
796
0
          if(len) {
797
0
            const char *ptr = curlx_dyn_ptr(&out);
798
0
            const char *last = memrchr(ptr, '/', len);
799
0
            if(last)
800
              /* trim the output at the slash */
801
0
              curlx_dyn_setlen(&out, last - ptr);
802
0
          }
803
804
0
          if(blen) { /* /../ */
805
0
            input = p;
806
0
            clen = blen;
807
0
            continue;
808
0
          }
809
0
          result = curlx_dyn_addn(&out, "/", 1);
810
0
          break;
811
0
        }
812
0
      }
813
0
    }
814
815
    /* move the first path segment in the input buffer to the end of the
816
       output buffer, including the initial "/" character (if any) and any
817
       subsequent characters up to, but not including, the next "/" character
818
       or the end of the input buffer. */
819
820
0
    result = curlx_dyn_addn(&out, input, 1);
821
0
    input++;
822
0
    clen--;
823
0
  }
824
0
end:
825
0
  if(!result) {
826
0
    if(curlx_dyn_len(&out))
827
0
      *outp = curlx_dyn_ptr(&out);
828
0
    else {
829
0
      *outp = curlx_strdup("");
830
0
      if(!*outp)
831
0
        return 1;
832
0
    }
833
0
  }
834
0
  return result ? 1 : 0; /* success */
835
0
}
836
837
/*
838
 * @unittest 1675
839
 */
840
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
841
                              const char **pathp, size_t *pathlenp);
842
UNITTEST CURLUcode parse_file(const char *url, size_t urllen, CURLU *u,
843
                              const char **pathp, size_t *pathlenp)
844
0
{
845
0
  const char *path;
846
0
  size_t pathlen;
847
848
0
  *pathp = NULL;
849
0
  *pathlenp = 0;
850
0
  if(urllen <= 6)
851
    /* file:/ is not enough to actually be a complete file: URL */
852
0
    return CURLUE_BAD_FILE_URL;
853
854
  /* path has been allocated large enough to hold this */
855
0
  path = &url[5];
856
0
  pathlen = urllen - 5;
857
858
  /* Extra handling URLs with an authority component (i.e. that start with
859
   * "file://")
860
   *
861
   * We allow omitted hostname (e.g. file:/<path>) -- valid according to
862
   * RFC 8089, but not the (current) WHAT-WG URL spec.
863
   */
864
0
  if(path[0] == '/' && path[1] == '/') {
865
    /* swallow the two slashes */
866
0
    const char *ptr = &path[2];
867
868
    /*
869
     * According to RFC 8089, a file: URL can be reliably dereferenced if:
870
     *
871
     *  o it has no/blank hostname, or
872
     *
873
     *  o the hostname matches "localhost" (case-insensitively), or
874
     *
875
     *  o the hostname is a FQDN that resolves to this machine, or
876
     *
877
     * For brevity, we only consider URLs with empty, "localhost", or
878
     * "127.0.0.1" hostnames as local, otherwise as an UNC String.
879
     *
880
     * Additionally, there is an exception for URLs with a Windows drive
881
     * letter in the authority (which was accidentally omitted from RFC 8089
882
     * Appendix E, but believe me, it was meant to be there. --MK)
883
     */
884
0
    if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
885
      /* the URL includes a hostname, it must match "localhost" or
886
         "127.0.0.1" to be valid */
887
0
      if(checkprefix("localhost/", ptr) ||
888
0
         checkprefix("127.0.0.1/", ptr)) {
889
0
        ptr += 9; /* now points to the slash after the host */
890
0
      }
891
0
      else
892
        /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
893
           none */
894
0
        return CURLUE_BAD_FILE_URL;
895
0
    }
896
897
0
    path = ptr;
898
0
    pathlen = urllen - (ptr - url);
899
0
  }
900
901
0
#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__)
902
  /* Do not allow Windows drive letters when not in Windows.
903
   * This catches both "file:/c:" and "file:c:" */
904
0
  if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
905
0
     STARTS_WITH_URL_DRIVE_PREFIX(path)) {
906
    /* File drive letters are only accepted in MS-DOS/Windows */
907
0
    return CURLUE_BAD_FILE_URL;
908
0
  }
909
#else
910
  /* If the path starts with a slash and a drive letter, ditch the slash */
911
  if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
912
    /* This cannot be done with strcpy, as the memory chunks overlap! */
913
    path++;
914
    pathlen--;
915
  }
916
#endif
917
0
  u->scheme = curlx_strdup("file");
918
0
  if(!u->scheme)
919
0
    return CURLUE_OUT_OF_MEMORY;
920
921
0
  *pathp = path;
922
0
  *pathlenp = pathlen;
923
0
  return CURLUE_OK;
924
0
}
925
926
static CURLUcode parse_scheme(const char *url, CURLU *u, char *schemebuf,
927
                              size_t schemelen, unsigned int flags,
928
                              const char **hostpp)
929
0
{
930
  /* clear path */
931
0
  const char *schemep = NULL;
932
933
0
  if(schemelen) {
934
0
    int i = 0;
935
0
    const char *p = &url[schemelen + 1];
936
0
    while((*p == '/') && (i < 4)) {
937
0
      p++;
938
0
      i++;
939
0
    }
940
941
0
    schemep = schemebuf;
942
0
    if(!Curl_get_scheme(schemep) &&
943
0
       !(flags & CURLU_NON_SUPPORT_SCHEME))
944
0
      return CURLUE_UNSUPPORTED_SCHEME;
945
946
0
    if((i < 1) || (i > 3))
947
      /* less than one or more than three slashes */
948
0
      return CURLUE_BAD_SLASHES;
949
950
0
    *hostpp = p; /* hostname starts here */
951
0
  }
952
0
  else {
953
    /* no scheme! */
954
955
0
    if(!(flags & (CURLU_DEFAULT_SCHEME | CURLU_GUESS_SCHEME)))
956
0
      return CURLUE_BAD_SCHEME;
957
958
0
    if(flags & CURLU_DEFAULT_SCHEME)
959
0
      schemep = DEFAULT_SCHEME;
960
961
    /*
962
     * The URL was badly formatted, let's try without scheme specified.
963
     */
964
0
    *hostpp = url;
965
0
  }
966
967
0
  if(schemep) {
968
0
    u->scheme = curlx_strdup(schemep);
969
0
    if(!u->scheme)
970
0
      return CURLUE_OUT_OF_MEMORY;
971
0
  }
972
0
  return CURLUE_OK;
973
0
}
974
975
static CURLUcode guess_scheme(CURLU *u, struct dynbuf *host)
976
0
{
977
0
  const char *hostname = curlx_dyn_ptr(host);
978
0
  const char *schemep = NULL;
979
  /* legacy curl-style guess based on hostname */
980
0
  if(checkprefix("ftp.", hostname))
981
0
    schemep = "ftp";
982
0
  else if(checkprefix("dict.", hostname))
983
0
    schemep = "dict";
984
0
  else if(checkprefix("ldap.", hostname))
985
0
    schemep = "ldap";
986
0
  else if(checkprefix("imap.", hostname))
987
0
    schemep = "imap";
988
0
  else if(checkprefix("smtp.", hostname))
989
0
    schemep = "smtp";
990
0
  else if(checkprefix("pop3.", hostname))
991
0
    schemep = "pop3";
992
0
  else
993
0
    schemep = "http";
994
995
0
  u->scheme = curlx_strdup(schemep);
996
0
  if(!u->scheme)
997
0
    return CURLUE_OUT_OF_MEMORY;
998
999
0
  u->guessed_scheme = TRUE;
1000
0
  return CURLUE_OK;
1001
0
}
1002
1003
static CURLUcode handle_fragment(CURLU *u, const char *fragment,
1004
                                 size_t fraglen, unsigned int flags)
1005
0
{
1006
0
  CURLUcode ures;
1007
0
  u->fragment_present = TRUE;
1008
0
  if(fraglen > 1) {
1009
    /* skip the leading '#' in the copy but include the terminating null */
1010
0
    if(flags & CURLU_URLENCODE) {
1011
0
      struct dynbuf enc;
1012
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1013
0
      ures = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, QUERY_NO);
1014
0
      if(ures)
1015
0
        return ures;
1016
0
      u->fragment = curlx_dyn_ptr(&enc);
1017
0
    }
1018
0
    else {
1019
0
      u->fragment = curlx_memdup0(fragment + 1, fraglen - 1);
1020
0
      if(!u->fragment)
1021
0
        return CURLUE_OUT_OF_MEMORY;
1022
0
    }
1023
0
  }
1024
0
  return CURLUE_OK;
1025
0
}
1026
1027
static CURLUcode handle_query(CURLU *u, const char *query,
1028
                              size_t qlen, unsigned int flags)
1029
0
{
1030
0
  u->query_present = TRUE;
1031
0
  if(qlen > 1) {
1032
0
    if(flags & CURLU_URLENCODE) {
1033
0
      struct dynbuf enc;
1034
0
      CURLUcode ures;
1035
0
      curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1036
      /* skip the leading question mark */
1037
0
      ures = urlencode_str(&enc, query + 1, qlen - 1, TRUE, QUERY_YES);
1038
0
      if(ures)
1039
0
        return ures;
1040
0
      u->query = curlx_dyn_ptr(&enc);
1041
0
    }
1042
0
    else {
1043
0
      u->query = curlx_memdup0(query + 1, qlen - 1);
1044
0
      if(!u->query)
1045
0
        return CURLUE_OUT_OF_MEMORY;
1046
0
    }
1047
0
  }
1048
0
  else {
1049
    /* single byte query */
1050
0
    u->query = curlx_strdup("");
1051
0
    if(!u->query)
1052
0
      return CURLUE_OUT_OF_MEMORY;
1053
0
  }
1054
0
  return CURLUE_OK;
1055
0
}
1056
1057
static CURLUcode handle_path(CURLU *u, const char *path,
1058
                             size_t pathlen, unsigned int flags,
1059
                             bool is_file)
1060
0
{
1061
0
  CURLUcode ures;
1062
0
  if(pathlen && (flags & CURLU_URLENCODE)) {
1063
0
    struct dynbuf enc;
1064
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1065
0
    ures = urlencode_str(&enc, path, pathlen, TRUE, QUERY_NO);
1066
0
    if(ures)
1067
0
      return ures;
1068
0
    pathlen = curlx_dyn_len(&enc);
1069
0
    path = u->path = curlx_dyn_ptr(&enc);
1070
0
  }
1071
1072
0
  if(pathlen >= (size_t)(1 + !is_file)) {
1073
    /* paths for file:// scheme can be one byte, others need to be two */
1074
0
    if(!u->path) {
1075
0
      u->path = curlx_memdup0(path, pathlen);
1076
0
      if(!u->path)
1077
0
        return CURLUE_OUT_OF_MEMORY;
1078
0
      path = u->path;
1079
0
    }
1080
0
    else if(flags & CURLU_URLENCODE)
1081
      /* it might have encoded more than the path so cut it */
1082
0
      u->path[pathlen] = 0;
1083
1084
0
    if(!(flags & CURLU_PATH_AS_IS)) {
1085
      /* remove ../ and ./ sequences according to RFC3986 */
1086
0
      char *dedot;
1087
0
      int err = dedotdotify(path, pathlen, &dedot);
1088
0
      if(err)
1089
0
        return CURLUE_OUT_OF_MEMORY;
1090
0
      if(dedot) {
1091
0
        curlx_free(u->path);
1092
0
        u->path = dedot;
1093
0
      }
1094
0
    }
1095
0
  }
1096
0
  return CURLUE_OK;
1097
0
}
1098
1099
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
1100
0
{
1101
0
  const char *path;
1102
0
  size_t pathlen;
1103
0
  char schemebuf[MAX_SCHEME_LEN + 1];
1104
0
  size_t schemelen = 0;
1105
0
  size_t urllen;
1106
0
  CURLUcode ures = CURLUE_OK;
1107
0
  struct dynbuf host;
1108
0
  bool is_file = FALSE;
1109
1110
0
  DEBUGASSERT(url);
1111
1112
0
  curlx_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
1113
1114
0
  ures = Curl_junkscan(url, &urllen, !!(flags & CURLU_ALLOW_SPACE));
1115
0
  if(ures)
1116
0
    goto fail;
1117
1118
0
  schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
1119
0
                                   flags & (CURLU_GUESS_SCHEME |
1120
0
                                            CURLU_DEFAULT_SCHEME));
1121
1122
  /* handle the file: scheme */
1123
0
  if(schemelen && !strcmp(schemebuf, "file")) {
1124
0
    is_file = TRUE;
1125
0
    ures = parse_file(url, urllen, u, &path, &pathlen);
1126
0
  }
1127
0
  else {
1128
0
    const char *hostp = NULL;
1129
0
    size_t hostlen;
1130
0
    ures = parse_scheme(url, u, schemebuf, schemelen, flags, &hostp);
1131
0
    if(ures)
1132
0
      goto fail;
1133
1134
    /* find the end of the hostname + port number */
1135
0
    hostlen = strcspn(hostp, "/?#");
1136
0
    path = &hostp[hostlen];
1137
1138
    /* this pathlen also contains the query and the fragment */
1139
0
    pathlen = urllen - (path - url);
1140
0
    if(hostlen) {
1141
0
      ures = parse_authority(u, hostp, hostlen, flags, &host,
1142
0
                             u->scheme != NULL);
1143
0
      if(!ures && (flags & CURLU_GUESS_SCHEME) && !u->scheme)
1144
0
        ures = guess_scheme(u, &host);
1145
0
    }
1146
0
    else if(flags & CURLU_NO_AUTHORITY) {
1147
      /* allowed to be empty. */
1148
0
      if(curlx_dyn_add(&host, ""))
1149
0
        ures = CURLUE_OUT_OF_MEMORY;
1150
0
    }
1151
0
    else
1152
0
      ures = CURLUE_NO_HOST;
1153
0
  }
1154
0
  if(!ures) {
1155
    /* The path might at this point contain a fragment and/or a query to
1156
       handle */
1157
0
    const char *fragment = strchr(path, '#');
1158
0
    if(fragment) {
1159
0
      size_t fraglen = pathlen - (fragment - path);
1160
0
      ures = handle_fragment(u, fragment, fraglen, flags);
1161
      /* after this, pathlen still contains the query */
1162
0
      pathlen -= fraglen;
1163
0
    }
1164
0
  }
1165
0
  if(!ures) {
1166
0
    const char *query = memchr(path, '?', pathlen);
1167
0
    if(query) {
1168
0
      size_t qlen = pathlen - (query - path);
1169
0
      ures = handle_query(u, query, qlen, flags);
1170
0
      pathlen -= qlen;
1171
0
    }
1172
0
  }
1173
0
  if(!ures)
1174
    /* the fragment and query parts are trimmed off from the path */
1175
0
    ures = handle_path(u, path, pathlen, flags, is_file);
1176
0
  if(!ures) {
1177
0
    u->host = curlx_dyn_ptr(&host);
1178
0
    return CURLUE_OK;
1179
0
  }
1180
0
fail:
1181
0
  curlx_dyn_free(&host);
1182
0
  free_urlhandle(u);
1183
0
  return ures;
1184
0
}
1185
1186
/*
1187
 * Parse the URL and, if successful, replace everything in the Curl_URL struct.
1188
 */
1189
static CURLUcode parseurl_and_replace(const char *url, CURLU *u,
1190
                                      unsigned int flags)
1191
0
{
1192
0
  CURLUcode ures;
1193
0
  CURLU tmpurl;
1194
0
  memset(&tmpurl, 0, sizeof(tmpurl));
1195
0
  ures = parseurl(url, &tmpurl, flags);
1196
0
  if(!ures) {
1197
0
    free_urlhandle(u);
1198
0
    *u = tmpurl;
1199
0
  }
1200
0
  return ures;
1201
0
}
1202
1203
/*
1204
 * Concatenate a relative URL onto a base URL making it absolute.
1205
 */
1206
static CURLUcode redirect_url(const char *base, const char *relurl,
1207
                              CURLU *u, unsigned int flags)
1208
0
{
1209
0
  struct dynbuf urlbuf;
1210
0
  bool host_changed = FALSE;
1211
0
  const char *useurl = relurl;
1212
0
  const char *cutoff = NULL;
1213
0
  size_t prelen;
1214
0
  CURLUcode uc;
1215
1216
  /* protsep points to the start of the hostname, after [scheme]:// */
1217
0
  const char *protsep = base + strlen(u->scheme) + 3;
1218
0
  DEBUGASSERT(base && relurl && u); /* all set here */
1219
0
  if(!base)
1220
0
    return CURLUE_MALFORMED_INPUT; /* should never happen */
1221
1222
  /* handle different relative URL types */
1223
0
  switch(relurl[0]) {
1224
0
  case '/':
1225
0
    if(relurl[1] == '/') {
1226
      /* protocol-relative URL: //example.com/path */
1227
0
      cutoff = protsep;
1228
0
      useurl = &relurl[2];
1229
0
      host_changed = TRUE;
1230
0
    }
1231
0
    else
1232
      /* absolute /path */
1233
0
      cutoff = strchr(protsep, '/');
1234
0
    break;
1235
1236
0
  case '#':
1237
    /* fragment-only change */
1238
0
    if(u->fragment)
1239
0
      cutoff = strchr(protsep, '#');
1240
0
    break;
1241
1242
0
  default:
1243
    /* path or query-only change */
1244
0
    if(u->query && u->query[0])
1245
      /* remove existing query */
1246
0
      cutoff = strchr(protsep, '?');
1247
0
    else if(u->fragment && u->fragment[0])
1248
      /* Remove existing fragment */
1249
0
      cutoff = strchr(protsep, '#');
1250
1251
0
    if(relurl[0] != '?') {
1252
      /* append a relative path after the last slash */
1253
0
      cutoff = memrchr(protsep, '/',
1254
0
                       cutoff ? (size_t)(cutoff - protsep) : strlen(protsep));
1255
0
      if(cutoff)
1256
0
        cutoff++; /* truncate after last slash */
1257
0
    }
1258
0
    break;
1259
0
  }
1260
1261
0
  prelen = cutoff ? (size_t)(cutoff - base) : strlen(base);
1262
1263
  /* build new URL */
1264
0
  curlx_dyn_init(&urlbuf, CURL_MAX_INPUT_LENGTH);
1265
1266
0
  if(!curlx_dyn_addn(&urlbuf, base, prelen) &&
1267
0
     !urlencode_str(&urlbuf, useurl, strlen(useurl), !host_changed,
1268
0
                    QUERY_NOT_YET)) {
1269
0
    uc = parseurl_and_replace(curlx_dyn_ptr(&urlbuf), u,
1270
0
                              flags & ~U_CURLU_PATH_AS_IS);
1271
0
  }
1272
0
  else
1273
0
    uc = CURLUE_OUT_OF_MEMORY;
1274
1275
0
  curlx_dyn_free(&urlbuf);
1276
0
  return uc;
1277
0
}
1278
1279
/*
1280
 */
1281
CURLU *curl_url(void)
1282
0
{
1283
0
  return curlx_calloc(1, sizeof(struct Curl_URL));
1284
0
}
1285
1286
void curl_url_cleanup(CURLU *u)
1287
0
{
1288
0
  if(u) {
1289
0
    free_urlhandle(u);
1290
0
    curlx_free(u);
1291
0
  }
1292
0
}
1293
1294
#define DUP(dest, src, name)                    \
1295
0
  do {                                          \
1296
0
    if((src)->name) {                           \
1297
0
      (dest)->name = curlx_strdup((src)->name); \
1298
0
      if(!(dest)->name)                         \
1299
0
        goto fail;                              \
1300
0
    }                                           \
1301
0
  } while(0)
1302
1303
CURLU *curl_url_dup(const CURLU *in)
1304
0
{
1305
0
  struct Curl_URL *u = curlx_calloc(1, sizeof(struct Curl_URL));
1306
0
  if(u) {
1307
0
    DUP(u, in, scheme);
1308
0
    DUP(u, in, user);
1309
0
    DUP(u, in, password);
1310
0
    DUP(u, in, options);
1311
0
    DUP(u, in, host);
1312
0
    DUP(u, in, port);
1313
0
    DUP(u, in, path);
1314
0
    DUP(u, in, query);
1315
0
    DUP(u, in, fragment);
1316
0
    DUP(u, in, zoneid);
1317
0
    u->portnum = in->portnum;
1318
0
    u->fragment_present = in->fragment_present;
1319
0
    u->query_present = in->query_present;
1320
0
  }
1321
0
  return u;
1322
0
fail:
1323
0
  curl_url_cleanup(u);
1324
0
  return NULL;
1325
0
}
1326
1327
#ifndef USE_IDN
1328
0
#define host_decode(x, y) CURLUE_LACKS_IDN
1329
0
#define host_encode(x, y) CURLUE_LACKS_IDN
1330
#else
1331
static CURLUcode host_decode(const char *host, char **allochost)
1332
{
1333
  CURLcode result = Curl_idn_decode(host, allochost);
1334
  if(result)
1335
    return (result == CURLE_OUT_OF_MEMORY) ?
1336
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1337
  return CURLUE_OK;
1338
}
1339
1340
static CURLUcode host_encode(const char *host, char **allochost)
1341
{
1342
  CURLcode result = Curl_idn_encode(host, allochost);
1343
  if(result)
1344
    return (result == CURLE_OUT_OF_MEMORY) ?
1345
      CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME;
1346
  return CURLUE_OK;
1347
}
1348
#endif
1349
1350
static CURLUcode urlget_format(const CURLU *u, CURLUPart what,
1351
                               const char *ptr, char **partp,
1352
                               bool plusdecode, unsigned int flags)
1353
0
{
1354
0
  CURLUcode uc = CURLUE_OK;
1355
0
  size_t partlen = strlen(ptr);
1356
0
  bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0;
1357
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1358
0
  bool punycode = (flags & CURLU_PUNYCODE) && (what == CURLUPART_HOST);
1359
0
  bool depunyfy = (flags & CURLU_PUNY2IDN) && (what == CURLUPART_HOST);
1360
0
  char *part = curlx_memdup0(ptr, partlen);
1361
0
  *partp = NULL;
1362
0
  if(!part)
1363
0
    return CURLUE_OUT_OF_MEMORY;
1364
0
  if(plusdecode) {
1365
    /* convert + to space */
1366
0
    char *plus = part;
1367
0
    size_t i = 0;
1368
0
    for(i = 0; i < partlen; ++plus, i++) {
1369
0
      if(*plus == '+')
1370
0
        *plus = ' ';
1371
0
    }
1372
0
  }
1373
0
  if(urldecode) {
1374
0
    char *decoded;
1375
0
    size_t dlen;
1376
    /* this unconditional rejection of control bytes is documented API
1377
       behavior */
1378
0
    CURLcode result = Curl_urldecode(part, partlen, &decoded, &dlen,
1379
0
                                     REJECT_CTRL);
1380
0
    curlx_free(part);
1381
0
    if(result)
1382
0
      return CURLUE_URLDECODE;
1383
0
    part = decoded;
1384
0
    partlen = dlen;
1385
0
  }
1386
0
  if(urlencode) {
1387
0
    struct dynbuf enc;
1388
0
    curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1389
0
    uc = urlencode_str(&enc, part, partlen, TRUE, what == CURLUPART_QUERY ?
1390
0
                       QUERY_YES : QUERY_NO);
1391
0
    curlx_free(part);
1392
0
    if(uc)
1393
0
      return uc;
1394
0
    part = curlx_dyn_ptr(&enc);
1395
0
  }
1396
0
  else if(punycode) {
1397
0
    if(!Curl_is_ASCII_name(u->host)) {
1398
0
      char *punyversion = NULL;
1399
0
      uc = host_decode(part, &punyversion);
1400
0
      curlx_free(part);
1401
0
      if(uc)
1402
0
        return uc;
1403
0
      part = punyversion;
1404
0
    }
1405
0
  }
1406
0
  else if(depunyfy) {
1407
0
    if(Curl_is_ASCII_name(u->host)) {
1408
0
      char *unpunified = NULL;
1409
0
      uc = host_encode(part, &unpunified);
1410
0
      curlx_free(part);
1411
0
      if(uc)
1412
0
        return uc;
1413
0
      part = unpunified;
1414
0
    }
1415
0
  }
1416
0
  *partp = part;
1417
0
  return CURLUE_OK;
1418
0
}
1419
1420
static CURLUcode urlget_url(const CURLU *u, char **part, unsigned int flags)
1421
0
{
1422
0
  char *url;
1423
0
  char *allochost = NULL;
1424
0
  const char *fragmentsep =
1425
0
    (u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY)) ?
1426
0
    "#" : "";
1427
0
  const char *querysep = ((u->query && u->query[0]) ||
1428
0
                          (u->query_present && flags & CURLU_GET_EMPTY)) ?
1429
0
    "?" : "";
1430
0
  char portbuf[7];
1431
0
  if(u->scheme && curl_strequal("file", u->scheme)) {
1432
0
    url = curl_maprintf("file://%s%s%s%s%s",
1433
0
                        u->path, querysep, u->query ? u->query : "",
1434
0
                        fragmentsep, u->fragment ? u->fragment : "");
1435
0
  }
1436
0
  else if(!u->host)
1437
0
    return CURLUE_NO_HOST;
1438
0
  else {
1439
0
    const char *scheme;
1440
0
    char *options = u->options;
1441
0
    char *port = u->port;
1442
0
    const struct Curl_scheme *h = NULL;
1443
0
    char schemebuf[MAX_SCHEME_LEN + 5];
1444
0
    if(u->scheme)
1445
0
      scheme = u->scheme;
1446
0
    else if(flags & CURLU_DEFAULT_SCHEME)
1447
0
      scheme = DEFAULT_SCHEME;
1448
0
    else
1449
0
      return CURLUE_NO_SCHEME;
1450
1451
0
    h = Curl_get_scheme(scheme);
1452
0
    if(!port && (flags & CURLU_DEFAULT_PORT)) {
1453
      /* there is no stored port number, but asked to deliver
1454
         a default one for the scheme */
1455
0
      if(h) {
1456
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1457
0
        port = portbuf;
1458
0
      }
1459
0
    }
1460
0
    else if(port) {
1461
      /* there is a stored port number, but asked to inhibit if it matches
1462
         the default one for the scheme */
1463
0
      if(h && (h->defport == u->portnum) &&
1464
0
         (flags & CURLU_NO_DEFAULT_PORT))
1465
0
        port = NULL;
1466
0
    }
1467
1468
0
    if(h && !(h->flags & PROTOPT_URLOPTIONS))
1469
0
      options = NULL;
1470
1471
0
    if(u->host[0] == '[') {
1472
0
      if(u->zoneid) {
1473
        /* make it '[ host %25 zoneid ]' */
1474
0
        struct dynbuf enc;
1475
0
        size_t hostlen = strlen(u->host);
1476
0
        curlx_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
1477
0
        if(curlx_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
1478
0
                          u->zoneid))
1479
0
          return CURLUE_OUT_OF_MEMORY;
1480
0
        allochost = curlx_dyn_ptr(&enc);
1481
0
      }
1482
0
    }
1483
0
    else if(flags & CURLU_URLENCODE) {
1484
0
      allochost = curl_easy_escape(NULL, u->host, 0);
1485
0
      if(!allochost)
1486
0
        return CURLUE_OUT_OF_MEMORY;
1487
0
    }
1488
0
    else if(flags & CURLU_PUNYCODE) {
1489
0
      if(!Curl_is_ASCII_name(u->host)) {
1490
0
        CURLUcode ret = host_decode(u->host, &allochost);
1491
0
        if(ret)
1492
0
          return ret;
1493
0
      }
1494
0
    }
1495
0
    else if(flags & CURLU_PUNY2IDN) {
1496
0
      if(Curl_is_ASCII_name(u->host)) {
1497
0
        CURLUcode ret = host_encode(u->host, &allochost);
1498
0
        if(ret)
1499
0
          return ret;
1500
0
      }
1501
0
    }
1502
1503
0
    if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme)
1504
0
      curl_msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme);
1505
0
    else
1506
0
      schemebuf[0] = 0;
1507
1508
0
    url = curl_maprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1509
0
                        schemebuf,
1510
0
                        u->user ? u->user : "",
1511
0
                        u->password ? ":" : "",
1512
0
                        u->password ? u->password : "",
1513
0
                        options ? ";" : "",
1514
0
                        options ? options : "",
1515
0
                        (u->user || u->password || options) ? "@" : "",
1516
0
                        allochost ? allochost : u->host,
1517
0
                        port ? ":" : "",
1518
0
                        port ? port : "",
1519
0
                        u->path ? u->path : "/",
1520
0
                        querysep,
1521
0
                        u->query ? u->query : "",
1522
0
                        fragmentsep,
1523
0
                        u->fragment ? u->fragment : "");
1524
0
    curlx_free(allochost);
1525
0
  }
1526
0
  if(!url)
1527
0
    return CURLUE_OUT_OF_MEMORY;
1528
0
  *part = url;
1529
0
  return CURLUE_OK;
1530
0
}
1531
1532
CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
1533
                       char **part, unsigned int flags)
1534
0
{
1535
0
  const char *ptr;
1536
0
  CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
1537
0
  char portbuf[7];
1538
0
  bool plusdecode = FALSE;
1539
0
  if(!u)
1540
0
    return CURLUE_BAD_HANDLE;
1541
0
  if(!part)
1542
0
    return CURLUE_BAD_PARTPOINTER;
1543
0
  *part = NULL;
1544
1545
0
  switch(what) {
1546
0
  case CURLUPART_SCHEME:
1547
0
    ptr = u->scheme;
1548
0
    ifmissing = CURLUE_NO_SCHEME;
1549
0
    flags &= ~U_CURLU_URLDECODE; /* never for schemes */
1550
0
    if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme)
1551
0
      return CURLUE_NO_SCHEME;
1552
0
    break;
1553
0
  case CURLUPART_USER:
1554
0
    ptr = u->user;
1555
0
    ifmissing = CURLUE_NO_USER;
1556
0
    break;
1557
0
  case CURLUPART_PASSWORD:
1558
0
    ptr = u->password;
1559
0
    ifmissing = CURLUE_NO_PASSWORD;
1560
0
    break;
1561
0
  case CURLUPART_OPTIONS:
1562
0
    ptr = u->options;
1563
0
    ifmissing = CURLUE_NO_OPTIONS;
1564
0
    break;
1565
0
  case CURLUPART_HOST:
1566
0
    ptr = u->host;
1567
0
    ifmissing = CURLUE_NO_HOST;
1568
0
    break;
1569
0
  case CURLUPART_ZONEID:
1570
0
    ptr = u->zoneid;
1571
0
    ifmissing = CURLUE_NO_ZONEID;
1572
0
    break;
1573
0
  case CURLUPART_PORT:
1574
0
    ptr = u->port;
1575
0
    ifmissing = CURLUE_NO_PORT;
1576
0
    flags &= ~U_CURLU_URLDECODE; /* never for port */
1577
0
    if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) {
1578
      /* there is no stored port number, but asked to deliver
1579
         a default one for the scheme */
1580
0
      const struct Curl_scheme *h = Curl_get_scheme(u->scheme);
1581
0
      if(h) {
1582
0
        curl_msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
1583
0
        ptr = portbuf;
1584
0
      }
1585
0
    }
1586
0
    else if(ptr && u->scheme) {
1587
      /* there is a stored port number, but ask to inhibit if
1588
         it matches the default one for the scheme */
1589
0
      const struct Curl_scheme *h = Curl_get_scheme(u->scheme);
1590
0
      if(h && (h->defport == u->portnum) &&
1591
0
         (flags & CURLU_NO_DEFAULT_PORT))
1592
0
        ptr = NULL;
1593
0
    }
1594
0
    break;
1595
0
  case CURLUPART_PATH:
1596
0
    ptr = u->path;
1597
0
    if(!ptr)
1598
0
      ptr = "/";
1599
0
    break;
1600
0
  case CURLUPART_QUERY:
1601
0
    ptr = u->query;
1602
0
    ifmissing = CURLUE_NO_QUERY;
1603
0
    plusdecode = flags & CURLU_URLDECODE;
1604
0
    if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY))
1605
      /* there was a blank query and the user do not ask for it */
1606
0
      ptr = NULL;
1607
0
    break;
1608
0
  case CURLUPART_FRAGMENT:
1609
0
    ptr = u->fragment;
1610
0
    ifmissing = CURLUE_NO_FRAGMENT;
1611
0
    if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY)
1612
      /* there was a blank fragment and the user asks for it */
1613
0
      ptr = "";
1614
0
    break;
1615
0
  case CURLUPART_URL:
1616
0
    return urlget_url(u, part, flags);
1617
0
  default:
1618
0
    ptr = NULL;
1619
0
    break;
1620
0
  }
1621
0
  if(ptr)
1622
0
    return urlget_format(u, what, ptr, part, plusdecode, flags);
1623
1624
0
  return ifmissing;
1625
0
}
1626
1627
static CURLUcode set_url_scheme(CURLU *u, const char *scheme,
1628
                                unsigned int flags)
1629
0
{
1630
0
  size_t plen = strlen(scheme);
1631
0
  const struct Curl_scheme *h = NULL;
1632
0
  if((plen > MAX_SCHEME_LEN) || (plen < 1))
1633
    /* too long or too short */
1634
0
    return CURLUE_BAD_SCHEME;
1635
  /* verify that it is a fine scheme */
1636
0
  h = Curl_get_scheme(scheme);
1637
0
  if(!(flags & CURLU_NON_SUPPORT_SCHEME) && (!h || !h->run))
1638
0
    return CURLUE_UNSUPPORTED_SCHEME;
1639
0
  if(!h) {
1640
0
    const char *s = scheme;
1641
0
    if(ISALPHA(*s)) {
1642
      /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
1643
0
      s++;
1644
0
      while(--plen) {
1645
0
        if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.'))
1646
0
          s++; /* fine */
1647
0
        else
1648
0
          return CURLUE_BAD_SCHEME;
1649
0
      }
1650
0
    }
1651
0
    else
1652
0
      return CURLUE_BAD_SCHEME;
1653
0
  }
1654
0
  u->guessed_scheme = FALSE;
1655
0
  return CURLUE_OK;
1656
0
}
1657
1658
static CURLUcode set_url_port(CURLU *u, const char *provided_port)
1659
0
{
1660
0
  char *tmp;
1661
0
  curl_off_t port;
1662
0
  if(!ISDIGIT(provided_port[0]))
1663
    /* not a number */
1664
0
    return CURLUE_BAD_PORT_NUMBER;
1665
0
  if(curlx_str_number(&provided_port, &port, 0xffff) || *provided_port)
1666
    /* weirdly provided number, not good! */
1667
0
    return CURLUE_BAD_PORT_NUMBER;
1668
0
  tmp = curl_maprintf("%" CURL_FORMAT_CURL_OFF_T, port);
1669
0
  if(!tmp)
1670
0
    return CURLUE_OUT_OF_MEMORY;
1671
0
  curlx_free(u->port);
1672
0
  u->port = tmp;
1673
0
  u->portnum = (unsigned short)port;
1674
0
  return CURLUE_OK;
1675
0
}
1676
1677
static CURLUcode set_url(CURLU *u, const char *url, size_t part_size,
1678
                         unsigned int flags)
1679
0
{
1680
  /*
1681
   * Allow a new URL to replace the existing (if any) contents.
1682
   *
1683
   * If the existing contents is enough for a URL, allow a relative URL to
1684
   * replace it.
1685
   */
1686
0
  CURLUcode uc;
1687
0
  char *oldurl = NULL;
1688
1689
0
  if(!part_size) {
1690
    /* a blank URL is not a valid URL unless we already have a complete one
1691
       and this is a redirect */
1692
0
    uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1693
0
    if(!uc) {
1694
      /* success, meaning the "" is a fine relative URL, but nothing
1695
         changes */
1696
0
      curlx_free(oldurl);
1697
0
      return CURLUE_OK;
1698
0
    }
1699
0
    if(uc == CURLUE_OUT_OF_MEMORY)
1700
0
      return uc;
1701
0
    return CURLUE_MALFORMED_INPUT;
1702
0
  }
1703
1704
  /* if the new URL is absolute replace the existing with the new. */
1705
0
  if(Curl_is_absolute_url(url, NULL, 0,
1706
0
                          flags & (CURLU_GUESS_SCHEME | CURLU_DEFAULT_SCHEME)))
1707
0
    return parseurl_and_replace(url, u, flags);
1708
1709
  /* if the old URL is incomplete (we cannot get an absolute URL in
1710
     'oldurl'), replace the existing with the new */
1711
0
  uc = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
1712
0
  if(uc == CURLUE_OUT_OF_MEMORY)
1713
0
    return uc;
1714
0
  else if(uc)
1715
0
    return parseurl_and_replace(url, u, flags);
1716
1717
0
  DEBUGASSERT(oldurl); /* it is set here */
1718
  /* apply the relative part to create a new URL */
1719
0
  uc = redirect_url(oldurl, url, u, flags);
1720
0
  curlx_free(oldurl);
1721
0
  return uc;
1722
0
}
1723
1724
static CURLUcode urlset_clear(CURLU *u, CURLUPart what)
1725
0
{
1726
0
  switch(what) {
1727
0
  case CURLUPART_URL:
1728
0
    free_urlhandle(u);
1729
0
    memset(u, 0, sizeof(struct Curl_URL));
1730
0
    break;
1731
0
  case CURLUPART_SCHEME:
1732
0
    curlx_safefree(u->scheme);
1733
0
    u->guessed_scheme = FALSE;
1734
0
    break;
1735
0
  case CURLUPART_USER:
1736
0
    curlx_safefree(u->user);
1737
0
    break;
1738
0
  case CURLUPART_PASSWORD:
1739
0
    curlx_safefree(u->password);
1740
0
    break;
1741
0
  case CURLUPART_OPTIONS:
1742
0
    curlx_safefree(u->options);
1743
0
    break;
1744
0
  case CURLUPART_HOST:
1745
0
    curlx_safefree(u->host);
1746
0
    break;
1747
0
  case CURLUPART_ZONEID:
1748
0
    curlx_safefree(u->zoneid);
1749
0
    break;
1750
0
  case CURLUPART_PORT:
1751
0
    u->portnum = 0;
1752
0
    curlx_safefree(u->port);
1753
0
    break;
1754
0
  case CURLUPART_PATH:
1755
0
    curlx_safefree(u->path);
1756
0
    break;
1757
0
  case CURLUPART_QUERY:
1758
0
    curlx_safefree(u->query);
1759
0
    u->query_present = FALSE;
1760
0
    break;
1761
0
  case CURLUPART_FRAGMENT:
1762
0
    curlx_safefree(u->fragment);
1763
0
    u->fragment_present = FALSE;
1764
0
    break;
1765
0
  default:
1766
0
    return CURLUE_UNKNOWN_PART;
1767
0
  }
1768
0
  return CURLUE_OK;
1769
0
}
1770
1771
static bool allowed_in_path(unsigned char x)
1772
0
{
1773
0
  switch(x) {
1774
0
  case '!':
1775
0
  case '$':
1776
0
  case '&':
1777
0
  case '\'':
1778
0
  case '(':
1779
0
  case ')':
1780
0
  case '{':
1781
0
  case '}':
1782
0
  case '[':
1783
0
  case ']':
1784
0
  case '*':
1785
0
  case '+':
1786
0
  case ',':
1787
0
  case ';':
1788
0
  case '=':
1789
0
  case ':':
1790
0
  case '@':
1791
0
  case '/':
1792
0
    return TRUE;
1793
0
  }
1794
0
  return FALSE;
1795
0
}
1796
1797
CURLUcode curl_url_set(CURLU *u, CURLUPart what,
1798
                       const char *part, unsigned int flags)
1799
0
{
1800
0
  char **storep = NULL;
1801
0
  bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0;
1802
0
  bool plusencode = FALSE;
1803
0
  bool pathmode = FALSE;
1804
0
  bool leadingslash = FALSE;
1805
0
  bool appendquery = FALSE;
1806
0
  bool equalsencode = FALSE;
1807
0
  size_t nalloc;
1808
1809
0
  if(!u)
1810
0
    return CURLUE_BAD_HANDLE;
1811
0
  if(!part)
1812
    /* setting a part to NULL clears it */
1813
0
    return urlset_clear(u, what);
1814
1815
0
  nalloc = strlen(part);
1816
0
  if(nalloc > CURL_MAX_INPUT_LENGTH)
1817
    /* excessive input length */
1818
0
    return CURLUE_MALFORMED_INPUT;
1819
1820
0
  switch(what) {
1821
0
  case CURLUPART_SCHEME: {
1822
0
    CURLUcode status = set_url_scheme(u, part, flags);
1823
0
    if(status)
1824
0
      return status;
1825
0
    storep = &u->scheme;
1826
0
    urlencode = FALSE; /* never */
1827
0
    break;
1828
0
  }
1829
0
  case CURLUPART_USER:
1830
0
    storep = &u->user;
1831
0
    break;
1832
0
  case CURLUPART_PASSWORD:
1833
0
    storep = &u->password;
1834
0
    break;
1835
0
  case CURLUPART_OPTIONS:
1836
0
    storep = &u->options;
1837
0
    break;
1838
0
  case CURLUPART_HOST:
1839
0
    storep = &u->host;
1840
0
    curlx_safefree(u->zoneid);
1841
0
    break;
1842
0
  case CURLUPART_ZONEID:
1843
0
    storep = &u->zoneid;
1844
0
    break;
1845
0
  case CURLUPART_PORT:
1846
0
    return set_url_port(u, part);
1847
0
  case CURLUPART_PATH:
1848
0
    pathmode = TRUE;
1849
0
    leadingslash = TRUE; /* enforce */
1850
0
    storep = &u->path;
1851
0
    break;
1852
0
  case CURLUPART_QUERY:
1853
0
    plusencode = urlencode;
1854
0
    appendquery = (flags & CURLU_APPENDQUERY) ? 1 : 0;
1855
0
    equalsencode = appendquery;
1856
0
    storep = &u->query;
1857
0
    u->query_present = TRUE;
1858
0
    break;
1859
0
  case CURLUPART_FRAGMENT:
1860
0
    storep = &u->fragment;
1861
0
    u->fragment_present = TRUE;
1862
0
    break;
1863
0
  case CURLUPART_URL:
1864
0
    return set_url(u, part, nalloc, flags);
1865
0
  default:
1866
0
    return CURLUE_UNKNOWN_PART;
1867
0
  }
1868
0
  DEBUGASSERT(storep);
1869
0
  {
1870
0
    const char *newp;
1871
0
    struct dynbuf enc;
1872
0
    curlx_dyn_init(&enc, (nalloc * 3) + 1 + leadingslash);
1873
1874
0
    if(leadingslash && (part[0] != '/')) {
1875
0
      CURLcode result = curlx_dyn_addn(&enc, "/", 1);
1876
0
      if(result)
1877
0
        return cc2cu(result);
1878
0
    }
1879
0
    if(urlencode) {
1880
0
      const unsigned char *i;
1881
1882
0
      for(i = (const unsigned char *)part; *i; i++) {
1883
0
        CURLcode result;
1884
0
        if((*i == ' ') && plusencode) {
1885
0
          result = curlx_dyn_addn(&enc, "+", 1);
1886
0
          if(result)
1887
0
            return CURLUE_OUT_OF_MEMORY;
1888
0
        }
1889
0
        else if(ISUNRESERVED(*i) ||
1890
0
                (pathmode && allowed_in_path(*i)) ||
1891
0
                ((*i == '=') && equalsencode)) {
1892
0
          if((*i == '=') && equalsencode)
1893
            /* only skip the first equals sign */
1894
0
            equalsencode = FALSE;
1895
0
          result = curlx_dyn_addn(&enc, i, 1);
1896
0
          if(result)
1897
0
            return cc2cu(result);
1898
0
        }
1899
0
        else {
1900
0
          unsigned char out[3] = { '%' };
1901
0
          Curl_hexbyte(&out[1], *i);
1902
0
          result = curlx_dyn_addn(&enc, out, 3);
1903
0
          if(result)
1904
0
            return cc2cu(result);
1905
0
        }
1906
0
      }
1907
0
    }
1908
0
    else {
1909
0
      char *p;
1910
0
      CURLcode result = curlx_dyn_add(&enc, part);
1911
0
      if(result)
1912
0
        return cc2cu(result);
1913
0
      p = curlx_dyn_ptr(&enc);
1914
0
      while(*p) {
1915
        /* make sure percent encoded are lower case */
1916
0
        if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
1917
0
           (ISUPPER(p[1]) || ISUPPER(p[2]))) {
1918
0
          p[1] = Curl_raw_tolower(p[1]);
1919
0
          p[2] = Curl_raw_tolower(p[2]);
1920
0
          p += 3;
1921
0
        }
1922
0
        else
1923
0
          p++;
1924
0
      }
1925
0
    }
1926
0
    newp = curlx_dyn_ptr(&enc);
1927
1928
0
    if(appendquery && newp) {
1929
      /* Append the 'newp' string onto the old query. Add a '&' separator if
1930
         none is present at the end of the existing query already */
1931
1932
0
      size_t querylen = u->query ? strlen(u->query) : 0;
1933
0
      bool addamperand = querylen && (u->query[querylen - 1] != '&');
1934
0
      if(querylen) {
1935
0
        struct dynbuf qbuf;
1936
0
        curlx_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH);
1937
1938
0
        if(curlx_dyn_addn(&qbuf, u->query, querylen)) /* add original query */
1939
0
          goto nomem;
1940
1941
0
        if(addamperand) {
1942
0
          if(curlx_dyn_addn(&qbuf, "&", 1))
1943
0
            goto nomem;
1944
0
        }
1945
0
        if(curlx_dyn_add(&qbuf, newp))
1946
0
          goto nomem;
1947
0
        curlx_dyn_free(&enc);
1948
0
        curlx_free(*storep);
1949
0
        *storep = curlx_dyn_ptr(&qbuf);
1950
0
        return CURLUE_OK;
1951
0
nomem:
1952
0
        curlx_dyn_free(&enc);
1953
0
        return CURLUE_OUT_OF_MEMORY;
1954
0
      }
1955
0
    }
1956
1957
0
    else if(what == CURLUPART_HOST) {
1958
0
      size_t n = curlx_dyn_len(&enc);
1959
0
      if(!n && (flags & CURLU_NO_AUTHORITY)) {
1960
        /* Skip hostname check, it is allowed to be empty. */
1961
0
      }
1962
0
      else {
1963
0
        bool bad = FALSE;
1964
0
        if(!n)
1965
0
          bad = TRUE; /* empty hostname is not okay */
1966
0
        else if(!urlencode) {
1967
          /* if the hostname part was not URL encoded here, it was set ready
1968
             URL encoded so we need to decode it to check */
1969
0
          size_t dlen;
1970
0
          char *decoded = NULL;
1971
0
          CURLcode result =
1972
0
            Curl_urldecode(newp, n, &decoded, &dlen, REJECT_CTRL);
1973
0
          if(result || hostname_check(u, decoded, dlen))
1974
0
            bad = TRUE;
1975
0
          curlx_free(decoded);
1976
0
        }
1977
0
        else if(hostname_check(u, (char *)CURL_UNCONST(newp), n))
1978
0
          bad = TRUE;
1979
0
        if(bad) {
1980
0
          curlx_dyn_free(&enc);
1981
0
          return CURLUE_BAD_HOSTNAME;
1982
0
        }
1983
0
      }
1984
0
    }
1985
1986
0
    curlx_free(*storep);
1987
0
    *storep = (char *)CURL_UNCONST(newp);
1988
0
  }
1989
0
  return CURLUE_OK;
1990
0
}
1991
1992
bool Curl_url_same_origin(CURLU *base, CURLU *href)
1993
0
{
1994
0
  const struct Curl_scheme *s = NULL;
1995
1996
  /* base must be an absolute URL */
1997
0
  if(!base->scheme || !base->host)
1998
0
    return FALSE;
1999
0
  if(href->scheme && !curl_strequal(base->scheme, href->scheme))
2000
0
    return FALSE;
2001
0
  if(href->host) {
2002
0
    if(!curl_strequal(base->host, href->host))
2003
0
      return FALSE;
2004
0
    if(!curl_strequal(base->port, href->port)) {
2005
      /* This may still match if only one has an explicit port
2006
       * and it is the default for the scheme. */
2007
0
      if(base->port && href->port)
2008
0
        return FALSE;
2009
2010
0
      s = Curl_get_scheme(base->scheme);
2011
0
      if(!s) /* Cannot match default port for unknown scheme */
2012
0
        return FALSE;
2013
2014
      /* The port which is set must be the default one */
2015
0
      if((base->port && (base->portnum != s->defport)) ||
2016
0
         (href->port && (href->portnum != s->defport)))
2017
0
        return FALSE;
2018
0
    }
2019
0
  }
2020
0
  else if(href->port) /* no host in href, then there must be no port */
2021
0
    return FALSE;
2022
0
  return TRUE;
2023
0
}