Coverage Report

Created: 2025-07-11 06:33

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