-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathurl.c
More file actions
2563 lines (2177 loc) · 73.9 KB
/
Copy pathurl.c
File metadata and controls
2563 lines (2177 loc) · 73.9 KB
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
/* URL handling.
Copyright (C) 1996-2011, 2015, 2018-2022 Free Software Foundation,
Inc.
This file is part of GNU Wget.
GNU Wget is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
GNU Wget is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7
If you modify this program, or any covered work, by linking or
combining it with the OpenSSL project's OpenSSL library (or a
modified version of that library), containing parts covered by the
terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
grants you additional permission to convey the resulting work.
Corresponding Source for a non-source form of such a combination
shall include the source code for the parts of OpenSSL used as well
as that of the covered work. */
#include "wget.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include "utils.h"
#include "url.h"
#include "host.h" /* for is_valid_ipv6_address */
#include "c-strcase.h"
#include "c-ctype.h"
#ifdef HAVE_ICONV
# include <iconv.h>
#endif
#include <langinfo.h>
#ifdef __VMS
#include "vms.h"
#endif /* def __VMS */
#ifdef TESTING
#include "../tests/unit-tests.h"
#endif
enum {
scm_disabled = 1, /* for https when OpenSSL fails to init. */
scm_has_params = 2, /* whether scheme has ;params */
scm_has_query = 4, /* whether scheme has ?query */
scm_has_fragment = 8 /* whether scheme has #fragment */
};
struct scheme_data
{
/* Short name of the scheme, such as "http" or "ftp". */
const char *name;
/* Leading string that identifies the scheme, such as "https://". */
const char *leading_string;
/* Default port of the scheme when none is specified. */
int default_port;
/* Various flags. */
int flags;
};
/* Supported schemes: */
static struct scheme_data supported_schemes[] =
{
{ "http", "http://", DEFAULT_HTTP_PORT, scm_has_query|scm_has_fragment },
#ifdef HAVE_SSL
{ "https", "https://", DEFAULT_HTTPS_PORT, scm_has_query|scm_has_fragment },
#endif
{ "ftp", "ftp://", DEFAULT_FTP_PORT, scm_has_params|scm_has_fragment },
#ifdef HAVE_SSL
/*
* Explicit FTPS uses the same port as FTP.
* Implicit FTPS has its own port (990), but it is disabled by default.
*/
{ "ftps", "ftps://", DEFAULT_FTP_PORT, scm_has_params|scm_has_fragment },
#endif
/* SCHEME_INVALID */
{ NULL, NULL, -1, 0 }
};
/* Forward declarations: */
static bool path_simplify (enum url_scheme, char *);
/* Support for escaping and unescaping of URL strings. */
/* Table of "reserved" and "unsafe" characters. Those terms are
rfc1738-speak, as such largely obsoleted by rfc2396 and later
specs, but the general idea remains.
A reserved character is the one that you can't decode without
changing the meaning of the URL. For example, you can't decode
"/foo/%2f/bar" into "/foo///bar" because the number and contents of
path components is different. Non-reserved characters can be
changed, so "/foo/%78/bar" is safe to change to "/foo/x/bar". The
unsafe characters are loosely based on rfc1738, plus "$" and ",",
as recommended by rfc2396, and minus "~", which is very frequently
used (and sometimes unrecognized as %7E by broken servers).
An unsafe character is the one that should be encoded when URLs are
placed in foreign environments. E.g. space and newline are unsafe
in HTTP contexts because HTTP uses them as separator and line
terminator, so they must be encoded to %20 and %0A respectively.
"*" is unsafe in shell context, etc.
We determine whether a character is unsafe through static table
lookup. This code assumes ASCII character set and 8-bit chars. */
enum {
/* rfc1738 reserved chars + "$" and ",". */
urlchr_reserved = 1,
/* rfc1738 unsafe chars, plus non-printables. */
urlchr_unsafe = 2
};
#define urlchr_test(c, mask) (urlchr_table[(unsigned char)(c)] & (mask))
#define URL_RESERVED_CHAR(c) urlchr_test(c, urlchr_reserved)
#define URL_UNSAFE_CHAR(c) urlchr_test(c, urlchr_unsafe)
/* Shorthands for the table: */
#define R urlchr_reserved
#define U urlchr_unsafe
#define RU R|U
static const unsigned char urlchr_table[256] =
{
U, U, U, U, U, U, U, U, /* NUL SOH STX ETX EOT ENQ ACK BEL */
U, U, U, U, U, U, U, U, /* BS HT LF VT FF CR SO SI */
U, U, U, U, U, U, U, U, /* DLE DC1 DC2 DC3 DC4 NAK SYN ETB */
U, U, U, U, U, U, U, U, /* CAN EM SUB ESC FS GS RS US */
U, 0, U, RU, R, U, R, 0, /* SP ! " # $ % & ' */
0, 0, 0, R, R, 0, 0, R, /* ( ) * + , - . / */
0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 4 5 6 7 */
0, 0, RU, R, U, R, U, R, /* 8 9 : ; < = > ? */
RU, 0, 0, 0, 0, 0, 0, 0, /* @ A B C D E F G */
0, 0, 0, 0, 0, 0, 0, 0, /* H I J K L M N O */
0, 0, 0, 0, 0, 0, 0, 0, /* P Q R S T U V W */
0, 0, 0, RU, U, RU, U, 0, /* X Y Z [ \ ] ^ _ */
U, 0, 0, 0, 0, 0, 0, 0, /* ` a b c d e f g */
0, 0, 0, 0, 0, 0, 0, 0, /* h i j k l m n o */
0, 0, 0, 0, 0, 0, 0, 0, /* p q r s t u v w */
0, 0, 0, U, U, U, 0, U, /* x y z { | } ~ DEL */
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
};
#undef R
#undef U
#undef RU
static void
url_unescape_1 (char *s, unsigned char mask)
{
unsigned char *t = (unsigned char *) s; /* t - tortoise */
unsigned char *h = (unsigned char *) s; /* h - hare */
for (; *h; h++, t++)
{
if (*h != '%')
{
copychar:
*t = *h;
}
else
{
unsigned char c;
/* Do nothing if '%' is not followed by two hex digits. */
if (!h[1] || !h[2] || !(c_isxdigit (h[1]) && c_isxdigit (h[2])))
goto copychar;
c = X2DIGITS_TO_NUM (h[1], h[2]);
if (urlchr_test(c, mask))
goto copychar;
/* Don't unescape %00 because there is no way to insert it
into a C string without effectively truncating it. */
if (c == '\0')
goto copychar;
*t = c;
h += 2;
}
}
*t = '\0';
}
/* URL-unescape the string S.
This is done by transforming the sequences "%HH" to the character
represented by the hexadecimal digits HH. If % is not followed by
two hexadecimal digits, it is inserted literally.
The transformation is done in place. If you need the original
string intact, make a copy before calling this function. */
void
url_unescape (char *s)
{
url_unescape_1 (s, 0);
}
/* URL-unescape the string S.
This functions behaves identically as url_unescape(), but does not
convert characters from "reserved". In other words, it only converts
"unsafe" characters. */
void
url_unescape_except_reserved (char *s)
{
url_unescape_1 (s, urlchr_reserved);
}
/* The core of url_escape_* functions. Escapes the characters that
match the provided mask in urlchr_table.
If ALLOW_PASSTHROUGH is true, a string with no unsafe chars will be
returned unchanged. If ALLOW_PASSTHROUGH is false, a freshly
allocated string will be returned in all cases. */
static char *
url_escape_1 (const char *s, unsigned char mask, bool allow_passthrough)
{
const char *p1;
char *p2, *newstr;
int newlen;
int addition = 0;
for (p1 = s; *p1; p1++)
if (urlchr_test (*p1, mask))
addition += 2; /* Two more characters (hex digits) */
if (!addition)
return allow_passthrough ? (char *)s : xstrdup (s);
newlen = (p1 - s) + addition;
newstr = xmalloc (newlen + 1);
p1 = s;
p2 = newstr;
while (*p1)
{
/* Quote the characters that match the test mask. */
if (urlchr_test (*p1, mask))
{
unsigned char c = *p1++;
*p2++ = '%';
*p2++ = XNUM_TO_DIGIT (c >> 4);
*p2++ = XNUM_TO_DIGIT (c & 0xf);
}
else
*p2++ = *p1++;
}
assert (p2 - newstr == newlen);
*p2 = '\0';
return newstr;
}
/* URL-escape the unsafe characters (see urlchr_table) in a given
string, returning a freshly allocated string. */
char *
url_escape (const char *s)
{
return url_escape_1 (s, urlchr_unsafe, false);
}
/* URL-escape the unsafe and reserved characters (see urlchr_table) in
a given string, returning a freshly allocated string. */
char *
url_escape_unsafe_and_reserved (const char *s)
{
return url_escape_1 (s, urlchr_unsafe|urlchr_reserved, false);
}
/* URL-escape the unsafe characters (see urlchr_table) in a given
string. If no characters are unsafe, S is returned. */
static char *
url_escape_allow_passthrough (const char *s)
{
return url_escape_1 (s, urlchr_unsafe, true);
}
/* Decide whether the char at position P needs to be encoded. (It is
not enough to pass a single char *P because the function may need
to inspect the surrounding context.)
Return true if the char should be escaped as %XX, false otherwise. */
static inline bool
char_needs_escaping (const char *p)
{
if (*p == '%')
{
if (c_isxdigit (*(p + 1)) && c_isxdigit (*(p + 2)))
return false;
else
/* Garbled %.. sequence: encode `%'. */
return true;
}
else if (URL_UNSAFE_CHAR (*p) && !URL_RESERVED_CHAR (*p))
return true;
else
return false;
}
/* Translate a %-escaped (but possibly non-conformant) input string S
into a %-escaped (and conformant) output string. If no characters
are encoded or decoded, return the same string S; otherwise, return
a freshly allocated string with the new contents.
After a URL has been run through this function, the protocols that
use `%' as the quote character can use the resulting string as-is,
while those that don't can use url_unescape to get to the intended
data. This function is stable: once the input is transformed,
further transformations of the result yield the same output.
Let's discuss why this function is needed.
Imagine Wget is asked to retrieve `http://abc.xyz/abc def'. Since
a raw space character would mess up the HTTP request, it needs to
be quoted, like this:
GET /abc%20def HTTP/1.0
It would appear that the unsafe chars need to be quoted, for
example with url_escape. But what if we're requested to download
`abc%20def'? url_escape transforms "%" to "%25", which would leave
us with `abc%2520def'. This is incorrect -- since %-escapes are
part of URL syntax, "%20" is the correct way to denote a literal
space on the Wget command line. This leads to the conclusion that
in that case Wget should not call url_escape, but leave the `%20'
as is. This is clearly contradictory, but it only gets worse.
What if the requested URI is `abc%20 def'? If we call url_escape,
we end up with `/abc%2520%20def', which is almost certainly not
intended. If we don't call url_escape, we are left with the
embedded space and cannot complete the request. What the user
meant was for Wget to request `/abc%20%20def', and this is where
reencode_escapes kicks in.
Wget used to solve this by first decoding %-quotes, and then
encoding all the "unsafe" characters found in the resulting string.
This was wrong because it didn't preserve certain URL special
(reserved) characters. For instance, URI containing "a%2B+b" (0x2b
== '+') would get translated to "a%2B%2Bb" or "a++b" depending on
whether we considered `+' reserved (it is). One of these results
is inevitable because by the second step we would lose information
on whether the `+' was originally encoded or not. Both results
were wrong because in CGI parameters + means space, while %2B means
literal plus. reencode_escapes correctly translates the above to
"a%2B+b", i.e. returns the original string.
This function uses a modified version of the algorithm originally
proposed by Anon Sricharoenchai:
* Encode all "unsafe" characters, except those that are also
"reserved", to %XX. See urlchr_table for which characters are
unsafe and reserved.
* Encode the "%" characters not followed by two hex digits to
"%25".
* Pass through all other characters and %XX escapes as-is. (Up to
Wget 1.10 this decoded %XX escapes corresponding to "safe"
characters, but that was obtrusive and broke some servers.)
Anon's test case:
"http://abc.xyz/%20%3F%%36%31%25aa% a?a=%61+a%2Ba&b=b%26c%3Dc"
->
"http://abc.xyz/%20%3F%25%36%31%25aa%25%20a?a=%61+a%2Ba&b=b%26c%3Dc"
Simpler test cases:
"foo bar" -> "foo%20bar"
"foo%20bar" -> "foo%20bar"
"foo %20bar" -> "foo%20%20bar"
"foo%%20bar" -> "foo%25%20bar" (0x25 == '%')
"foo%25%20bar" -> "foo%25%20bar"
"foo%2%20bar" -> "foo%252%20bar"
"foo+bar" -> "foo+bar" (plus is reserved!)
"foo%2b+bar" -> "foo%2b+bar" */
static char *
reencode_escapes (const char *s)
{
const char *p1;
char *newstr, *p2;
int oldlen, newlen;
int encode_count = 0;
/* First pass: inspect the string to see if there's anything to do,
and to calculate the new length. */
for (p1 = s; *p1; p1++)
if (char_needs_escaping (p1))
++encode_count;
if (!encode_count)
/* The string is good as it is. */
return (char *) s; /* C const model sucks. */
oldlen = p1 - s;
/* Each encoding adds two characters (hex digits). */
newlen = oldlen + 2 * encode_count;
newstr = xmalloc (newlen + 1);
/* Second pass: copy the string to the destination address, encoding
chars when needed. */
p1 = s;
p2 = newstr;
while (*p1)
if (char_needs_escaping (p1))
{
unsigned char c = *p1++;
*p2++ = '%';
*p2++ = XNUM_TO_DIGIT (c >> 4);
*p2++ = XNUM_TO_DIGIT (c & 0xf);
}
else
*p2++ = *p1++;
*p2 = '\0';
assert (p2 - newstr == newlen);
return newstr;
}
/* Returns the scheme type if the scheme is supported, or
SCHEME_INVALID if not. */
enum url_scheme
url_scheme (const char *url)
{
int i;
for (i = 0; supported_schemes[i].leading_string; i++)
if (0 == c_strncasecmp (url, supported_schemes[i].leading_string,
strlen (supported_schemes[i].leading_string)))
{
if (!(supported_schemes[i].flags & scm_disabled))
return (enum url_scheme) i;
else
return SCHEME_INVALID;
}
return SCHEME_INVALID;
}
#define SCHEME_CHAR(ch) (c_isalnum (ch) || (ch) == '-' || (ch) == '+')
/* Return 1 if the URL begins with any "scheme", 0 otherwise. As
currently implemented, it returns true if URL begins with
[-+a-zA-Z0-9]+: . */
bool
url_has_scheme (const char *url)
{
const char *p = url;
/* The first char must be a scheme char. */
if (!*p || !SCHEME_CHAR (*p))
return false;
++p;
/* Followed by 0 or more scheme chars. */
while (*p && SCHEME_CHAR (*p))
++p;
/* Terminated by ':'. */
return *p == ':';
}
bool
url_valid_scheme (const char *url)
{
enum url_scheme scheme = url_scheme (url);
return scheme != SCHEME_INVALID;
}
int
scheme_default_port (enum url_scheme scheme)
{
return supported_schemes[scheme].default_port;
}
void
scheme_disable (enum url_scheme scheme)
{
supported_schemes[scheme].flags |= scm_disabled;
}
const char *
scheme_leading_string (enum url_scheme scheme)
{
return supported_schemes[scheme].leading_string;
}
/* Skip the username and password, if present in the URL. The
function should *not* be called with the complete URL, but with the
portion after the scheme.
If no username and password are found, return URL. */
static const char *
url_skip_credentials (const char *url)
{
/*
* This whole file implements https://www.rfc-editor.org/rfc/rfc2396 .
* RFC 2396 is outdated since 2005 and needs a rewrite or a thorough re-visit.
*
* The RFC says
* server = [ [ userinfo "@" ] hostport ]
* userinfo = *( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," )
* unreserved = alphanum | mark
* mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
*/
static const char *allowed = "-_.!~*'();:&=+$,";
for (const char *p = url; *p; p++)
{
if (c_isalnum(*p))
continue;
if (strchr(allowed, *p))
continue;
if (*p == '%' && c_isxdigit(p[1]) && c_isxdigit(p[2]))
{
p += 2;
continue;
}
if (*p == '@')
return p + 1;
break;
}
return url;
}
/* Parse credentials contained in [BEG, END). The region is expected
to have come from a URL and is unescaped. */
static bool
parse_credentials (const char *beg, const char *end, char **user, char **passwd)
{
char *colon;
const char *userend;
if (beg == end)
return false; /* empty user name */
colon = memchr (beg, ':', end - beg);
if (colon == beg)
return false; /* again empty user name */
if (colon)
{
*passwd = strdupdelim (colon + 1, end);
userend = colon;
url_unescape (*passwd);
}
else
{
*passwd = NULL;
userend = end;
}
*user = strdupdelim (beg, userend);
url_unescape (*user);
return true;
}
/* Used by main.c: detect URLs written using the "shorthand" URL forms
originally popularized by Netscape and NcFTP. HTTP shorthands look
like this:
www.foo.com[:port]/dir/file -> http://www.foo.com[:port]/dir/file
www.foo.com[:port] -> http://www.foo.com[:port]
FTP shorthands look like this:
foo.bar.com:dir/file -> ftp://foo.bar.com/dir/file
foo.bar.com:/absdir/file -> ftp://foo.bar.com//absdir/file
If the URL needs not or cannot be rewritten, return NULL. */
char *
rewrite_shorthand_url (const char *url)
{
const char *p;
char *ret;
if (url_scheme (url) != SCHEME_INVALID)
return NULL;
/* Look for a ':' or '/'. The former signifies NcFTP syntax, the
latter Netscape. */
p = strpbrk (url, ":/");
if (p == url)
return NULL;
/* If we're looking at "://", it means the URL uses a scheme we
don't support, which may include "https" when compiled without
SSL support. Don't bogusly rewrite such URLs. */
if (p && p[0] == ':' && p[1] == '/' && p[2] == '/')
return NULL;
if (p && *p == ':')
{
/* Colon indicates ftp, as in foo.bar.com:path. Check for
special case of http port number ("localhost:10000"). */
int digits = strspn (p + 1, "0123456789");
if (digits && (p[1 + digits] == '/' || p[1 + digits] == '\0'))
goto http;
/* Turn "foo.bar.com:path" to "ftp://foo.bar.com/path". */
if ((ret = aprintf ("ftp://%s", url)) != NULL)
ret[6 + (p - url)] = '/';
}
else
{
http:
/* Just prepend "http://" to URL. */
ret = aprintf ("http://%s", url);
}
return ret;
}
static void split_path (const char *, char **, char **);
/* Like strpbrk, with the exception that it returns the pointer to the
terminating zero (end-of-string aka "eos") if no matching character
is found. */
static inline char *
strpbrk_or_eos (const char *s, const char *accept)
{
char *p = strpbrk (s, accept);
if (!p)
p = strchr (s, '\0');
return p;
}
/* Turn STR into lowercase; return true if a character was actually
changed. */
static bool
lowercase_str (char *str)
{
bool changed = false;
for (; *str; str++)
if (c_isupper (*str))
{
changed = true;
*str = c_tolower (*str);
}
return changed;
}
static const char *
init_seps (enum url_scheme scheme)
{
static char seps[8] = ":/";
char *p = seps + 2;
int flags = supported_schemes[scheme].flags;
if (flags & scm_has_params)
*p++ = ';';
if (flags & scm_has_query)
*p++ = '?';
if (flags & scm_has_fragment)
*p++ = '#';
*p = '\0';
return seps;
}
static const char *parse_errors[] = {
#define PE_NO_ERROR 0
N_("No error"),
#define PE_UNSUPPORTED_SCHEME 1
N_("Unsupported scheme %s"), /* support for format token only here */
#define PE_MISSING_SCHEME 2
N_("Scheme missing"),
#define PE_INVALID_HOST_NAME 3
N_("Invalid host name"),
#define PE_BAD_PORT_NUMBER 4
N_("Bad port number"),
#define PE_INVALID_USER_NAME 5
N_("Invalid user name"),
#define PE_UNTERMINATED_IPV6_ADDRESS 6
N_("Unterminated IPv6 numeric address"),
#define PE_IPV6_NOT_SUPPORTED 7
N_("IPv6 addresses not supported"),
#define PE_INVALID_IPV6_ADDRESS 8
N_("Invalid IPv6 numeric address")
};
/* Parse a URL.
Return a new struct url if successful, NULL on error. In case of
error, and if ERROR is not NULL, also set *ERROR to the appropriate
error code. */
struct url *
url_parse (const char *url, int *error, struct iri *iri, bool percent_encode)
{
struct url *u;
const char *p;
bool path_modified, host_modified;
enum url_scheme scheme;
const char *seps;
const char *uname_b, *uname_e;
const char *host_b, *host_e;
const char *path_b, *path_e;
const char *params_b, *params_e;
const char *query_b, *query_e;
const char *fragment_b, *fragment_e;
int port;
char *user = NULL, *passwd = NULL;
const char *url_encoded = NULL;
int error_code;
scheme = url_scheme (url);
if (scheme == SCHEME_INVALID)
{
if (url_has_scheme (url))
error_code = PE_UNSUPPORTED_SCHEME;
else
error_code = PE_MISSING_SCHEME;
goto error;
}
url_encoded = url;
if (iri && iri->utf8_encode)
{
char *new_url = NULL;
iri->utf8_encode = remote_to_utf8 (iri, iri->orig_url ? iri->orig_url : url, &new_url);
if (!iri->utf8_encode)
new_url = NULL;
else
{
xfree (iri->orig_url);
iri->orig_url = xstrdup (url);
url_encoded = reencode_escapes (new_url);
if (url_encoded != new_url)
xfree (new_url);
percent_encode = false;
}
}
if (percent_encode)
url_encoded = reencode_escapes (url);
p = url_encoded;
p += strlen (supported_schemes[scheme].leading_string);
uname_b = p;
p = url_skip_credentials (p);
uname_e = p;
/* scheme://user:pass@host[:port]... */
/* ^ */
/* We attempt to break down the URL into the components path,
params, query, and fragment. They are ordered like this:
scheme://host[:port][/path][;params][?query][#fragment] */
path_b = path_e = NULL;
params_b = params_e = NULL;
query_b = query_e = NULL;
fragment_b = fragment_e = NULL;
/* Initialize separators for optional parts of URL, depending on the
scheme. For example, FTP has params, and HTTP and HTTPS have
query string and fragment. */
seps = init_seps (scheme);
host_b = p;
if (*p == '[')
{
/* Handle IPv6 address inside square brackets. Ideally we'd
just look for the terminating ']', but rfc2732 mandates
rejecting invalid IPv6 addresses. */
/* The address begins after '['. */
host_b = p + 1;
host_e = strchr (host_b, ']');
if (!host_e)
{
error_code = PE_UNTERMINATED_IPV6_ADDRESS;
goto error;
}
#ifdef ENABLE_IPV6
/* Check if the IPv6 address is valid. */
if (!is_valid_ipv6_address(host_b, host_e))
{
error_code = PE_INVALID_IPV6_ADDRESS;
goto error;
}
/* Continue parsing after the closing ']'. */
p = host_e + 1;
#else
error_code = PE_IPV6_NOT_SUPPORTED;
goto error;
#endif
/* The closing bracket must be followed by a separator or by the
null char. */
/* http://[::1]... */
/* ^ */
if (!strchr (seps, *p))
{
/* Trailing garbage after []-delimited IPv6 address. */
error_code = PE_INVALID_HOST_NAME;
goto error;
}
}
else
{
p = strpbrk_or_eos (p, seps);
host_e = p;
}
++seps; /* advance to '/' */
if (host_b == host_e)
{
error_code = PE_INVALID_HOST_NAME;
goto error;
}
port = scheme_default_port (scheme);
if (*p == ':')
{
const char *port_b, *port_e, *pp;
/* scheme://host:port/tralala */
/* ^ */
++p;
port_b = p;
p = strpbrk_or_eos (p, seps);
port_e = p;
/* Allow empty port, as per rfc2396. */
if (port_b != port_e)
for (port = 0, pp = port_b; pp < port_e; pp++)
{
if (!c_isdigit (*pp))
{
/* http://host:12randomgarbage/blah */
/* ^ */
error_code = PE_BAD_PORT_NUMBER;
goto error;
}
port = 10 * port + (*pp - '0');
/* Check for too large port numbers here, before we have
a chance to overflow on bogus port values. */
if (port > 0xffff)
{
error_code = PE_BAD_PORT_NUMBER;
goto error;
}
}
}
/* Advance to the first separator *after* '/' (either ';' or '?',
depending on the scheme). */
++seps;
/* Get the optional parts of URL, each part being delimited by
current location and the position of the next separator. */
#define GET_URL_PART(sepchar, var) do { \
if (*p == sepchar) \
var##_b = ++p, var##_e = p = strpbrk_or_eos (p, seps); \
++seps; \
} while (0)
GET_URL_PART ('/', path);
if (supported_schemes[scheme].flags & scm_has_params)
GET_URL_PART (';', params);
if (supported_schemes[scheme].flags & scm_has_query)
GET_URL_PART ('?', query);
if (supported_schemes[scheme].flags & scm_has_fragment)
GET_URL_PART ('#', fragment);
#undef GET_URL_PART
assert (*p == 0);
if (uname_b != uname_e)
{
/* http://user:pass@host */
/* ^ ^ */
/* uname_b uname_e */
if (!parse_credentials (uname_b, uname_e - 1, &user, &passwd))
{
error_code = PE_INVALID_USER_NAME;
goto error;
}
}
u = xnew0 (struct url);
u->scheme = scheme;
u->host = strdupdelim (host_b, host_e);
u->port = port;
u->user = user;
u->passwd = passwd;
u->path = strdupdelim (path_b, path_e);
path_modified = path_simplify (scheme, u->path);
split_path (u->path, &u->dir, &u->file);
host_modified = lowercase_str (u->host);
/* Decode %HH sequences in host name. This is important not so much
to support %HH sequences in host names (which other browser
don't), but to support binary characters (which will have been
converted to %HH by reencode_escapes). */
if (strchr (u->host, '%'))
{
url_unescape (u->host);
host_modified = true;
/* check for invalid control characters in host name */
for (p = u->host; *p; p++)
{
if (c_iscntrl(*p))
{
url_free(u);
error_code = PE_INVALID_HOST_NAME;
goto error;
}
}
/* Apply IDNA regardless of iri->utf8_encode status */
if (opt.enable_iri && iri)
{
char *new = idn_encode (iri, u->host);
if (new)
{
xfree (u->host);
u->host = new;
host_modified = true;
}
}
}
if (params_b)
u->params = strdupdelim (params_b, params_e);
if (query_b)
u->query = strdupdelim (query_b, query_e);
if (fragment_b)
u->fragment = strdupdelim (fragment_b, fragment_e);
if (opt.enable_iri || path_modified || u->fragment || host_modified || path_b == path_e)
{
/* If we suspect that a transformation has rendered what
url_string might return different from URL_ENCODED, rebuild
u->url using url_string. */
u->url = url_string (u, URL_AUTH_SHOW);
if (url_encoded != url)
xfree (url_encoded);
}
else
{
if (url_encoded == url)
u->url = xstrdup (url);
else