forked from curl/curl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlapi.c
1974 lines (1793 loc) · 52.8 KB
/
urlapi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "urlapi-int.h"
#include "strcase.h"
#include "url.h"
#include "escape.h"
#include "curl_ctype.h"
#include "inet_pton.h"
#include "inet_ntop.h"
#include "strdup.h"
#include "idn.h"
#include "curl_memrchr.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/* MSDOS/Windows style drive prefix, eg c: in c:foo */
#define STARTS_WITH_DRIVE_PREFIX(str) \
((('a' <= str[0] && str[0] <= 'z') || \
('A' <= str[0] && str[0] <= 'Z')) && \
(str[1] == ':'))
/* MSDOS/Windows style drive prefix, optionally with
* a '|' instead of ':', followed by a slash or NUL */
#define STARTS_WITH_URL_DRIVE_PREFIX(str) \
((('a' <= (str)[0] && (str)[0] <= 'z') || \
('A' <= (str)[0] && (str)[0] <= 'Z')) && \
((str)[1] == ':' || (str)[1] == '|') && \
((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
/* scheme is not URL encoded, the longest libcurl supported ones are... */
#define MAX_SCHEME_LEN 40
/*
* If ENABLE_IPV6 is disabled, we still want to parse IPv6 addresses, so make
* sure we have _some_ value for AF_INET6 without polluting our fake value
* everywhere.
*/
#if !defined(ENABLE_IPV6) && !defined(AF_INET6)
#define AF_INET6 (AF_INET + 1)
#endif
/* Internal representation of CURLU. Point to URL-encoded strings. */
struct Curl_URL {
char *scheme;
char *user;
char *password;
char *options; /* IMAP only? */
char *host;
char *zoneid; /* for numerical IPv6 addresses */
char *port;
char *path;
char *query;
char *fragment;
long portnum; /* the numerical version */
};
#define DEFAULT_SCHEME "https"
static void free_urlhandle(struct Curl_URL *u)
{
free(u->scheme);
free(u->user);
free(u->password);
free(u->options);
free(u->host);
free(u->zoneid);
free(u->port);
free(u->path);
free(u->query);
free(u->fragment);
}
/*
* Find the separator at the end of the host name, or the '?' in cases like
* http://www.example.com?id=2380
*/
static const char *find_host_sep(const char *url)
{
const char *sep;
const char *query;
/* Find the start of the hostname */
sep = strstr(url, "//");
if(!sep)
sep = url;
else
sep += 2;
query = strchr(sep, '?');
sep = strchr(sep, '/');
if(!sep)
sep = url + strlen(url);
if(!query)
query = url + strlen(url);
return sep < query ? sep : query;
}
/* convert CURLcode to CURLUcode */
#define cc2cu(x) ((x) == CURLE_TOO_LARGE ? CURLUE_TOO_LARGE : \
CURLUE_OUT_OF_MEMORY)
/*
* Decide whether a character in a URL must be escaped.
*/
#define urlchar_needs_escaping(c) (!(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c)))
static const char hexdigits[] = "0123456789abcdef";
/* urlencode_str() writes data into an output dynbuf and URL-encodes the
* spaces in the source URL accordingly.
*
* URL encoding should be skipped for host names, otherwise IDN resolution
* will fail.
*/
static CURLUcode urlencode_str(struct dynbuf *o, const char *url,
size_t len, bool relative,
bool query)
{
/* we must add this with whitespace-replacing */
bool left = !query;
const unsigned char *iptr;
const unsigned char *host_sep = (const unsigned char *) url;
CURLcode result;
if(!relative)
host_sep = (const unsigned char *) find_host_sep(url);
for(iptr = (unsigned char *)url; /* read from here */
len; iptr++, len--) {
if(iptr < host_sep) {
result = Curl_dyn_addn(o, iptr, 1);
if(result)
return cc2cu(result);
continue;
}
if(*iptr == ' ') {
if(left)
result = Curl_dyn_addn(o, "%20", 3);
else
result = Curl_dyn_addn(o, "+", 1);
if(result)
return cc2cu(result);
continue;
}
if(*iptr == '?')
left = FALSE;
if(urlchar_needs_escaping(*iptr)) {
char out[3]={'%'};
out[1] = hexdigits[*iptr>>4];
out[2] = hexdigits[*iptr & 0xf];
result = Curl_dyn_addn(o, out, 3);
}
else
result = Curl_dyn_addn(o, iptr, 1);
if(result)
return cc2cu(result);
}
return CURLUE_OK;
}
/*
* Returns the length of the scheme if the given URL is absolute (as opposed
* to relative). Stores the scheme in the buffer if TRUE and 'buf' is
* non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set.
*
* If 'guess_scheme' is TRUE, it means the URL might be provided without
* scheme.
*/
size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen,
bool guess_scheme)
{
int i = 0;
DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
(void)buflen; /* only used in debug-builds */
if(buf)
buf[0] = 0; /* always leave a defined value in buf */
#ifdef _WIN32
if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url))
return 0;
#endif
if(ISALPHA(url[0]))
for(i = 1; i < MAX_SCHEME_LEN; ++i) {
char s = url[i];
if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') )) {
/* RFC 3986 3.1 explains:
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
*/
}
else {
break;
}
}
if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) {
/* If this does not guess scheme, the scheme always ends with the colon so
that this also detects data: URLs etc. In guessing mode, data: could
be the host name "data" with a specified port number. */
/* the length of the scheme is the name part only */
size_t len = i;
if(buf) {
buf[i] = 0;
while(i--) {
buf[i] = Curl_raw_tolower(url[i]);
}
}
return len;
}
return 0;
}
/*
* Concatenate a relative URL to a base URL making it absolute.
* URL-encodes any spaces.
* The returned pointer must be freed by the caller unless NULL
* (returns NULL on out of memory).
*
* Note that this function destroys the 'base' string.
*/
static CURLcode concat_url(char *base, const char *relurl, char **newurl)
{
/***
TRY to append this new path to the old URL
to the right of the host part. Oh crap, this is doomed to cause
problems in the future...
*/
struct dynbuf newest;
char *protsep;
char *pathsep;
bool host_changed = FALSE;
const char *useurl = relurl;
CURLcode result = CURLE_OK;
CURLUcode uc;
*newurl = NULL;
/* protsep points to the start of the host name */
protsep = strstr(base, "//");
if(!protsep)
protsep = base;
else
protsep += 2; /* pass the slashes */
if('/' != relurl[0]) {
int level = 0;
/* First we need to find out if there's a ?-letter in the URL,
and cut it and the right-side of that off */
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep = 0;
/* we have a relative path to append to the last slash if there's one
available, or if the new URL is just a query string (starts with a
'?') we append the new one at the end of the entire currently worked
out URL */
if(useurl[0] != '?') {
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep = 0;
}
/* Check if there's any slash after the host name, and if so, remember
that position instead */
pathsep = strchr(protsep, '/');
if(pathsep)
protsep = pathsep + 1;
else
protsep = NULL;
/* now deal with one "./" or any amount of "../" in the newurl
and act accordingly */
if((useurl[0] == '.') && (useurl[1] == '/'))
useurl += 2; /* just skip the "./" */
while((useurl[0] == '.') &&
(useurl[1] == '.') &&
(useurl[2] == '/')) {
level++;
useurl += 3; /* pass the "../" */
}
if(protsep) {
while(level--) {
/* cut off one more level from the right of the original URL */
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep = 0;
else {
*protsep = 0;
break;
}
}
}
}
else {
/* We got a new absolute path for this server */
if(relurl[1] == '/') {
/* the new URL starts with //, just keep the protocol part from the
original one */
*protsep = 0;
useurl = &relurl[2]; /* we keep the slashes from the original, so we
skip the new ones */
host_changed = TRUE;
}
else {
/* cut off the original URL from the first slash, or deal with URLs
without slash */
pathsep = strchr(protsep, '/');
if(pathsep) {
/* When people use badly formatted URLs, such as
"http://www.example.com?dir=/home/daniel" we must not use the first
slash, if there's a ?-letter before it! */
char *sep = strchr(protsep, '?');
if(sep && (sep < pathsep))
pathsep = sep;
*pathsep = 0;
}
else {
/* There was no slash. Now, since we might be operating on a badly
formatted URL, such as "http://www.example.com?id=2380" which
doesn't use a slash separator as it is supposed to, we need to check
for a ?-letter as well! */
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep = 0;
}
}
}
Curl_dyn_init(&newest, CURL_MAX_INPUT_LENGTH);
/* copy over the root url part */
result = Curl_dyn_add(&newest, base);
if(result)
return result;
/* check if we need to append a slash */
if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
;
else {
result = Curl_dyn_addn(&newest, "/", 1);
if(result)
return result;
}
/* then append the new piece on the right side */
uc = urlencode_str(&newest, useurl, strlen(useurl), !host_changed,
FALSE);
if(uc)
return (uc == CURLUE_TOO_LARGE) ? CURLE_TOO_LARGE : CURLE_OUT_OF_MEMORY;
*newurl = Curl_dyn_ptr(&newest);
return CURLE_OK;
}
/* scan for byte values <= 31, 127 and sometimes space */
static CURLUcode junkscan(const char *url, size_t *urllen, unsigned int flags)
{
static const char badbytes[]={
/* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x7f, 0x00 /* null-terminate */
};
size_t n = strlen(url);
size_t nfine;
if(n > CURL_MAX_INPUT_LENGTH)
/* excessive input length */
return CURLUE_MALFORMED_INPUT;
nfine = strcspn(url, badbytes);
if((nfine != n) ||
(!(flags & CURLU_ALLOW_SPACE) && strchr(url, ' ')))
return CURLUE_MALFORMED_INPUT;
*urllen = n;
return CURLUE_OK;
}
/*
* parse_hostname_login()
*
* Parse the login details (user name, password and options) from the URL and
* strip them out of the host name
*
*/
static CURLUcode parse_hostname_login(struct Curl_URL *u,
const char *login,
size_t len,
unsigned int flags,
size_t *offset) /* to the host name */
{
CURLUcode result = CURLUE_OK;
CURLcode ccode;
char *userp = NULL;
char *passwdp = NULL;
char *optionsp = NULL;
const struct Curl_handler *h = NULL;
/* At this point, we assume all the other special cases have been taken
* care of, so the host is at most
*
* [user[:password][;options]]@]hostname
*
* We need somewhere to put the embedded details, so do that first.
*/
char *ptr;
DEBUGASSERT(login);
*offset = 0;
ptr = memchr(login, '@', len);
if(!ptr)
goto out;
/* We will now try to extract the
* possible login information in a string like:
* ftp://user:password@ftp.my.site:8021/README */
ptr++;
/* if this is a known scheme, get some details */
if(u->scheme)
h = Curl_get_scheme_handler(u->scheme);
/* We could use the login information in the URL so extract it. Only parse
options if the handler says we should. Note that 'h' might be NULL! */
ccode = Curl_parse_login_details(login, ptr - login - 1,
&userp, &passwdp,
(h && (h->flags & PROTOPT_URLOPTIONS)) ?
&optionsp:NULL);
if(ccode) {
result = CURLUE_BAD_LOGIN;
goto out;
}
if(userp) {
if(flags & CURLU_DISALLOW_USER) {
/* Option DISALLOW_USER is set and url contains username. */
result = CURLUE_USER_NOT_ALLOWED;
goto out;
}
free(u->user);
u->user = userp;
}
if(passwdp) {
free(u->password);
u->password = passwdp;
}
if(optionsp) {
free(u->options);
u->options = optionsp;
}
/* the host name starts at this offset */
*offset = ptr - login;
return CURLUE_OK;
out:
free(userp);
free(passwdp);
free(optionsp);
u->user = NULL;
u->password = NULL;
u->options = NULL;
return result;
}
UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host,
bool has_scheme)
{
char *portptr;
char *hostname = Curl_dyn_ptr(host);
/*
* Find the end of an IPv6 address on the ']' ending bracket.
*/
if(hostname[0] == '[') {
portptr = strchr(hostname, ']');
if(!portptr)
return CURLUE_BAD_IPV6;
portptr++;
/* this is a RFC2732-style specified IP-address */
if(*portptr) {
if(*portptr != ':')
return CURLUE_BAD_PORT_NUMBER;
}
else
portptr = NULL;
}
else
portptr = strchr(hostname, ':');
if(portptr) {
char *rest = NULL;
long port;
size_t keep = portptr - hostname;
/* Browser behavior adaptation. If there's a colon with no digits after,
just cut off the name there which makes us ignore the colon and just
use the default port. Firefox, Chrome and Safari all do that.
Don't do it if the URL has no scheme, to make something that looks like
a scheme not work!
*/
Curl_dyn_setlen(host, keep);
portptr++;
if(!*portptr)
return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
if(!ISDIGIT(*portptr))
return CURLUE_BAD_PORT_NUMBER;
port = strtol(portptr, &rest, 10); /* Port number must be decimal */
if(port > 0xffff)
return CURLUE_BAD_PORT_NUMBER;
if(rest[0])
return CURLUE_BAD_PORT_NUMBER;
u->portnum = port;
/* generate a new port number string to get rid of leading zeroes etc */
free(u->port);
u->port = aprintf("%ld", port);
if(!u->port)
return CURLUE_OUT_OF_MEMORY;
}
return CURLUE_OK;
}
/* this assumes 'hostname' now starts with [ */
static CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname,
size_t hlen) /* length of hostname */
{
size_t len;
DEBUGASSERT(*hostname == '[');
if(hlen < 4) /* '[::]' is the shortest possible valid string */
return CURLUE_BAD_IPV6;
hostname++;
hlen -= 2;
/* only valid IPv6 letters are ok */
len = strspn(hostname, "0123456789abcdefABCDEF:.");
if(hlen != len) {
hlen = len;
if(hostname[len] == '%') {
/* this could now be '%[zone id]' */
char zoneid[16];
int i = 0;
char *h = &hostname[len + 1];
/* pass '25' if present and is a url encoded percent sign */
if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
h += 2;
while(*h && (*h != ']') && (i < 15))
zoneid[i++] = *h++;
if(!i || (']' != *h))
return CURLUE_BAD_IPV6;
zoneid[i] = 0;
u->zoneid = strdup(zoneid);
if(!u->zoneid)
return CURLUE_OUT_OF_MEMORY;
hostname[len] = ']'; /* insert end bracket */
hostname[len + 1] = 0; /* terminate the hostname */
}
else
return CURLUE_BAD_IPV6;
/* hostname is fine */
}
/* Check the IPv6 address. */
{
char dest[16]; /* fits a binary IPv6 address */
char norm[MAX_IPADR_LEN];
hostname[hlen] = 0; /* end the address there */
if(1 != Curl_inet_pton(AF_INET6, hostname, dest))
return CURLUE_BAD_IPV6;
/* check if it can be done shorter */
if(Curl_inet_ntop(AF_INET6, dest, norm, sizeof(norm)) &&
(strlen(norm) < hlen)) {
strcpy(hostname, norm);
hlen = strlen(norm);
hostname[hlen + 1] = 0;
}
hostname[hlen] = ']'; /* restore ending bracket */
}
return CURLUE_OK;
}
static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
size_t hlen) /* length of hostname */
{
size_t len;
DEBUGASSERT(hostname);
if(!hlen)
return CURLUE_NO_HOST;
else if(hostname[0] == '[')
return ipv6_parse(u, hostname, hlen);
else {
/* letters from the second string are not ok */
len = strcspn(hostname, " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%");
if(hlen != len)
/* hostname with bad content */
return CURLUE_BAD_HOSTNAME;
}
return CURLUE_OK;
}
/*
* Handle partial IPv4 numerical addresses and different bases, like
* '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc.
*
* If the given input string is syntactically wrong IPv4 or any part for
* example is too big, this function returns HOST_NAME.
*
* Output the "normalized" version of that input string in plain quad decimal
* integers.
*
* Returns the host type.
*/
#define HOST_ERROR -1 /* out of memory */
#define HOST_BAD -2 /* bad IPv4 address */
#define HOST_NAME 1
#define HOST_IPV4 2
#define HOST_IPV6 3
static int ipv4_normalize(struct dynbuf *host)
{
bool done = FALSE;
int n = 0;
const char *c = Curl_dyn_ptr(host);
unsigned long parts[4] = {0, 0, 0, 0};
CURLcode result = CURLE_OK;
if(*c == '[')
return HOST_IPV6;
while(!done) {
char *endp = NULL;
unsigned long l;
if(!ISDIGIT(*c))
/* most importantly this doesn't allow a leading plus or minus */
return HOST_NAME;
l = strtoul(c, &endp, 0);
parts[n] = l;
c = endp;
switch(*c) {
case '.':
if(n == 3)
return HOST_NAME;
n++;
c++;
break;
case '\0':
done = TRUE;
break;
default:
return HOST_NAME;
}
/* overflow */
if((l == ULONG_MAX) && (errno == ERANGE))
return HOST_NAME;
#if SIZEOF_LONG > 4
/* a value larger than 32 bits */
if(l > UINT_MAX)
return HOST_NAME;
#endif
}
switch(n) {
case 0: /* a -- 32 bits */
Curl_dyn_reset(host);
result = Curl_dyn_addf(host, "%u.%u.%u.%u",
(unsigned int)(parts[0] >> 24),
(unsigned int)((parts[0] >> 16) & 0xff),
(unsigned int)((parts[0] >> 8) & 0xff),
(unsigned int)(parts[0] & 0xff));
break;
case 1: /* a.b -- 8.24 bits */
if((parts[0] > 0xff) || (parts[1] > 0xffffff))
return HOST_NAME;
Curl_dyn_reset(host);
result = Curl_dyn_addf(host, "%u.%u.%u.%u",
(unsigned int)(parts[0]),
(unsigned int)((parts[1] >> 16) & 0xff),
(unsigned int)((parts[1] >> 8) & 0xff),
(unsigned int)(parts[1] & 0xff));
break;
case 2: /* a.b.c -- 8.8.16 bits */
if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
return HOST_NAME;
Curl_dyn_reset(host);
result = Curl_dyn_addf(host, "%u.%u.%u.%u",
(unsigned int)(parts[0]),
(unsigned int)(parts[1]),
(unsigned int)((parts[2] >> 8) & 0xff),
(unsigned int)(parts[2] & 0xff));
break;
case 3: /* a.b.c.d -- 8.8.8.8 bits */
if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
(parts[3] > 0xff))
return HOST_NAME;
Curl_dyn_reset(host);
result = Curl_dyn_addf(host, "%u.%u.%u.%u",
(unsigned int)(parts[0]),
(unsigned int)(parts[1]),
(unsigned int)(parts[2]),
(unsigned int)(parts[3]));
break;
}
if(result)
return HOST_ERROR;
return HOST_IPV4;
}
/* if necessary, replace the host content with a URL decoded version */
static CURLUcode urldecode_host(struct dynbuf *host)
{
char *per = NULL;
const char *hostname = Curl_dyn_ptr(host);
per = strchr(hostname, '%');
if(!per)
/* nothing to decode */
return CURLUE_OK;
else {
/* encoded */
size_t dlen;
char *decoded;
CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
REJECT_CTRL);
if(result)
return CURLUE_BAD_HOSTNAME;
Curl_dyn_reset(host);
result = Curl_dyn_addn(host, decoded, dlen);
free(decoded);
if(result)
return cc2cu(result);
}
return CURLUE_OK;
}
static CURLUcode parse_authority(struct Curl_URL *u,
const char *auth, size_t authlen,
unsigned int flags,
struct dynbuf *host,
bool has_scheme)
{
size_t offset;
CURLUcode uc;
CURLcode result;
/*
* Parse the login details and strip them out of the host name.
*/
uc = parse_hostname_login(u, auth, authlen, flags, &offset);
if(uc)
goto out;
result = Curl_dyn_addn(host, auth + offset, authlen - offset);
if(result) {
uc = cc2cu(result);
goto out;
}
uc = Curl_parse_port(u, host, has_scheme);
if(uc)
goto out;
if(!Curl_dyn_len(host))
return CURLUE_NO_HOST;
switch(ipv4_normalize(host)) {
case HOST_IPV4:
break;
case HOST_IPV6:
uc = ipv6_parse(u, Curl_dyn_ptr(host), Curl_dyn_len(host));
break;
case HOST_NAME:
uc = urldecode_host(host);
if(!uc)
uc = hostname_check(u, Curl_dyn_ptr(host), Curl_dyn_len(host));
break;
case HOST_ERROR:
uc = CURLUE_OUT_OF_MEMORY;
break;
case HOST_BAD:
default:
uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */
break;
}
out:
return uc;
}
CURLUcode Curl_url_set_authority(CURLU *u, const char *authority,
unsigned int flags)
{
CURLUcode result;
struct dynbuf host;
DEBUGASSERT(authority);
Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
result = parse_authority(u, authority, strlen(authority), flags,
&host, !!u->scheme);
if(result)
Curl_dyn_free(&host);
else {
free(u->host);
u->host = Curl_dyn_ptr(&host);
}
return result;
}
/*
* "Remove Dot Segments"
* https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
*/
/*
* dedotdotify()
* @unittest: 1395
*
* This function gets a null-terminated path with dot and dotdot sequences
* passed in and strips them off according to the rules in RFC 3986 section
* 5.2.4.
*
* The function handles a query part ('?' + stuff) appended but it expects
* that fragments ('#' + stuff) have already been cut off.
*
* RETURNS
*
* Zero for success and 'out' set to an allocated dedotdotified string.
*/
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp);
UNITTEST int dedotdotify(const char *input, size_t clen, char **outp)
{
char *outptr;
const char *endp = &input[clen];
char *out;
*outp = NULL;
/* the path always starts with a slash, and a slash has not dot */
if((clen < 2) || !memchr(input, '.', clen))
return 0;
out = malloc(clen + 1);
if(!out)
return 1; /* out of memory */
*out = 0; /* null-terminates, for inputs like "./" */
outptr = out;
do {
bool dotdot = TRUE;
if(*input == '.') {
/* A. If the input buffer begins with a prefix of "../" or "./", then
remove that prefix from the input buffer; otherwise, */
if(!strncmp("./", input, 2)) {
input += 2;
clen -= 2;
}
else if(!strncmp("../", input, 3)) {
input += 3;
clen -= 3;
}
/* D. if the input buffer consists only of "." or "..", then remove
that from the input buffer; otherwise, */
else if(!strcmp(".", input) || !strcmp("..", input) ||
!strncmp(".?", input, 2) || !strncmp("..?", input, 3)) {
*out = 0;
break;
}
else
dotdot = FALSE;
}
else if(*input == '/') {
/* B. if the input buffer begins with a prefix of "/./" or "/.", where
"." is a complete path segment, then replace that prefix with "/" in
the input buffer; otherwise, */
if(!strncmp("/./", input, 3)) {
input += 2;
clen -= 2;
}
else if(!strcmp("/.", input) || !strncmp("/.?", input, 3)) {
*outptr++ = '/';
*outptr = 0;
break;
}
/* C. if the input buffer begins with a prefix of "/../" or "/..",
where ".." is a complete path segment, then replace that prefix with
"/" in the input buffer and remove the last segment and its
preceding "/" (if any) from the output buffer; otherwise, */
else if(!strncmp("/../", input, 4)) {
input += 3;
clen -= 3;
/* remove the last segment from the output buffer */
while(outptr > out) {
outptr--;
if(*outptr == '/')
break;
}
*outptr = 0; /* null-terminate where it stops */
}
else if(!strcmp("/..", input) || !strncmp("/..?", input, 4)) {
/* remove the last segment from the output buffer */
while(outptr > out) {
outptr--;
if(*outptr == '/')
break;
}
*outptr++ = '/';
*outptr = 0; /* null-terminate where it stops */
break;
}
else
dotdot = FALSE;
}
else
dotdot = FALSE;
if(!dotdot) {
/* E. move the first path segment in the input buffer to the end of
the output buffer, including the initial "/" character (if any) and
any subsequent characters up to, but not including, the next "/"
character or the end of the input buffer. */
do {
*outptr++ = *input++;
clen--;
} while(*input && (*input != '/') && (*input != '?'));
*outptr = 0;
}
/* continue until end of path */
} while(input < endp);
*outp = out;
return 0; /* success */
}
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)