-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
uri_string.erl
2879 lines (2540 loc) · 99.1 KB
/
uri_string.erl
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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2017-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
%% [RFC 3986, Chapter 2.2. Reserved Characters]
%%
%% reserved = gen-delims / sub-delims
%%
%% gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
%%
%% sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
%% / "*" / "+" / "," / ";" / "="
%%
%%
%% [RFC 3986, Chapter 2.3. Unreserved Characters]
%%
%% unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
%%
%%
%% [RFC 3986, Chapter 3. Syntax Components]
%%
%% The generic URI syntax consists of a hierarchical sequence of
%% components referred to as the scheme, authority, path, query, and
%% fragment.
%%
%% URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
%%
%% hier-part = "//" authority path-abempty
%% / path-absolute
%% / path-rootless
%% / path-empty
%%
%% The scheme and path components are required, though the path may be
%% empty (no characters). When authority is present, the path must
%% either be empty or begin with a slash ("/") character. When
%% authority is not present, the path cannot begin with two slash
%% characters ("//"). These restrictions result in five different ABNF
%% rules for a path (Section 3.3), only one of which will match any
%% given URI reference.
%%
%% The following are two example URIs and their component parts:
%%
%% foo://example.com:8042/over/there?name=ferret#nose
%% \_/ \______________/\_________/ \_________/ \__/
%% | | | | |
%% scheme authority path query fragment
%% | _____________________|__
%% / \ / \
%% urn:example:animal:ferret:nose
%%
%%
%% [RFC 3986, Chapter 3.1. Scheme]
%%
%% Each URI begins with a scheme name that refers to a specification for
%% assigning identifiers within that scheme.
%%
%% scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
%%
%%
%% [RFC 3986, Chapter 3.2. Authority]
%%
%% Many URI schemes include a hierarchical element for a naming
%% authority so that governance of the name space defined by the
%% remainder of the URI is delegated to that authority (which may, in
%% turn, delegate it further).
%%
%% authority = [ userinfo "@" ] host [ ":" port ]
%%
%%
%% [RFC 3986, Chapter 3.2.1. User Information]
%%
%% The userinfo subcomponent may consist of a user name and, optionally,
%% scheme-specific information about how to gain authorization to access
%% the resource. The user information, if present, is followed by a
%% commercial at-sign ("@") that delimits it from the host.
%%
%% userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
%%
%%
%% [RFC 3986, Chapter 3.2.2. Host]
%%
%% The host subcomponent of authority is identified by an IP literal
%% encapsulated within square brackets, an IPv4 address in dotted-
%% decimal form, or a registered name.
%%
%% host = IP-literal / IPv4address / reg-name
%%
%% IP-literal = "[" ( IPv6address / IPvFuture ) "]"
%%
%% IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
%%
%% IPv6address = 6( h16 ":" ) ls32
%% / "::" 5( h16 ":" ) ls32
%% / [ h16 ] "::" 4( h16 ":" ) ls32
%% / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
%% / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
%% / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
%% / [ *4( h16 ":" ) h16 ] "::" ls32
%% / [ *5( h16 ":" ) h16 ] "::" h16
%% / [ *6( h16 ":" ) h16 ] "::"
%%
%% ls32 = ( h16 ":" h16 ) / IPv4address
%% ; least-significant 32 bits of address
%%
%% h16 = 1*4HEXDIG
%% ; 16 bits of address represented in hexadecimal
%%
%% IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
%%
%% dec-octet = DIGIT ; 0-9
%% / %x31-39 DIGIT ; 10-99
%% / "1" 2DIGIT ; 100-199
%% / "2" %x30-34 DIGIT ; 200-249
%% / "25" %x30-35 ; 250-255
%%
%% reg-name = *( unreserved / pct-encoded / sub-delims )
%%
%%
%% [RFC 3986, Chapter 3.2.2. Port]
%%
%% The port subcomponent of authority is designated by an optional port
%% number in decimal following the host and delimited from it by a
%% single colon (":") character.
%%
%% port = *DIGIT
%%
%%
%% [RFC 3986, Chapter 3.3. Path]
%%
%% The path component contains data, usually organized in hierarchical
%% form, that, along with data in the non-hierarchical query component
%% (Section 3.4), serves to identify a resource within the scope of the
%% URI's scheme and naming authority (if any). The path is terminated
%% by the first question mark ("?") or number sign ("#") character, or
%% by the end of the URI.
%%
%% path = path-abempty ; begins with "/" or is empty
%% / path-absolute ; begins with "/" but not "//"
%% / path-noscheme ; begins with a non-colon segment
%% / path-rootless ; begins with a segment
%% / path-empty ; zero characters
%%
%% path-abempty = *( "/" segment )
%% path-absolute = "/" [ segment-nz *( "/" segment ) ]
%% path-noscheme = segment-nz-nc *( "/" segment )
%% path-rootless = segment-nz *( "/" segment )
%% path-empty = 0<pchar>
%% segment = *pchar
%% segment-nz = 1*pchar
%% segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
%% ; non-zero-length segment without any colon ":"
%%
%% pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
%%
%%
%% [RFC 3986, Chapter 3.4. Query]
%%
%% The query component contains non-hierarchical data that, along with
%% data in the path component (Section 3.3), serves to identify a
%% resource within the scope of the URI's scheme and naming authority
%% (if any). The query component is indicated by the first question
%% mark ("?") character and terminated by a number sign ("#") character
%% or by the end of the URI.
%%
%% query = *( pchar / "/" / "?" )
%%
%%
%% [RFC 3986, Chapter 3.5. Fragment]
%%
%% The fragment identifier component of a URI allows indirect
%% identification of a secondary resource by reference to a primary
%% resource and additional identifying information.
%%
%% fragment = *( pchar / "/" / "?" )
%%
%%
%% [RFC 3986, Chapter 4.1. URI Reference]
%%
%% URI-reference is used to denote the most common usage of a resource
%% identifier.
%%
%% URI-reference = URI / relative-ref
%%
%%
%% [RFC 3986, Chapter 4.2. Relative Reference]
%%
%% A relative reference takes advantage of the hierarchical syntax
%% (Section 1.2.3) to express a URI reference relative to the name space
%% of another hierarchical URI.
%%
%% relative-ref = relative-part [ "?" query ] [ "#" fragment ]
%%
%% relative-part = "//" authority path-abempty
%% / path-absolute
%% / path-noscheme
%% / path-empty
%%
%%
%% [RFC 3986, Chapter 4.3. Absolute URI]
%%
%% Some protocol elements allow only the absolute form of a URI without
%% a fragment identifier. For example, defining a base URI for later
%% use by relative references calls for an absolute-URI syntax rule that
%% does not allow a fragment.
%%
%% absolute-URI = scheme ":" hier-part [ "?" query ]
%%
-module(uri_string).
-moduledoc """
URI processing functions.
This module contains functions for parsing and handling URIs
([RFC 3986](https://www.ietf.org/rfc/rfc3986.txt)) and form-urlencoded query
strings ([HTML 5.2](https://www.w3.org/TR/html52/)).
Parsing and serializing non-UTF-8 form-urlencoded query strings are also
supported ([HTML 5.0](https://www.w3.org/TR/html50/)).
A URI is an identifier consisting of a sequence of characters matching the
syntax rule named _URI_ in [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt).
The generic URI syntax consists of a hierarchical sequence of components
referred to as the scheme, authority, path, query, and fragment:
```text
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
hier-part = "//" authority path-abempty
/ path-absolute
/ path-rootless
/ path-empty
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
authority = [ userinfo "@" ] host [ ":" port ]
userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
```
The interpretation of a URI depends only on the characters used and not on how
those characters are represented in a network protocol.
The functions implemented by this module cover the following use cases:
- Parsing URIs into its components and returing a map: `parse/1`
- Recomposing a map of URI components into a URI string: `recompose/1`
- Changing inbound binary and percent-encoding of URIs: `transcode/2`
- Transforming URIs into a normalized form: `normalize/1`, `normalize/2`
- Composing form-urlencoded query strings from a list of key-value pairs:
`compose_query/1`, `compose_query/2`
- Dissecting form-urlencoded query strings into a list of key-value pairs:
`dissect_query/1`
- Decoding percent-encoded triplets in URI map or a specific component of URI:
`percent_decode/1`
- Preparing and retrieving application specific data included in URI
components:
`quote/1`, `quote/2`, `unquote/1`
There are four different encodings present during the handling of URIs:
- Inbound binary encoding in binaries
- Inbound percent-encoding in lists and binaries
- Outbound binary encoding in binaries
- Outbound percent-encoding in lists and binaries
Functions with `t:uri_string/0` argument accept lists, binaries and mixed lists
(lists with binary elements) as input type. All of the functions but
[`transcode/2`](`transcode/2`) expects input as lists of unicode codepoints,
UTF-8 encoded binaries and UTF-8 percent-encoded URI parts ("%C3%B6" corresponds
to the unicode character "ö").
Unless otherwise specified the return value type and encoding are the same as
the input type and encoding. That is, binary input returns binary output, list
input returns a list output but mixed input returns list output.
In case of lists there is only percent-encoding. In binaries, however, both
binary encoding and percent-encoding shall be considered.
[`transcode/2`](`transcode/2`) provides the means to convert between the
supported encodings, it takes a `t:uri_string/0` and a list of options
specifying inbound and outbound encodings.
[RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) does not mandate any specific
character encoding and it is usually defined by the protocol or surrounding
text. This library takes the same assumption, binary and percent-encoding are
handled as one configuration unit, they cannot be set to different values.
Quoting functions are intended to be used by URI producing application during
component preparation or retrieval phase to avoid conflicts between data and
characters used in URI syntax. Quoting functions use percent encoding, but with
different rules than for example during execution of
[`recompose/1`](`recompose/1`). It is user responsibility to provide quoting
functions with application data only and using their output to combine an URI
component.
Quoting functions can for instance be used for constructing a path component
with a segment containing '/' character which should not collide with '/' used
as general delimiter in path component.
""".
-moduledoc(#{since => "OTP 21.0"}).
%%-------------------------------------------------------------------------
%% External API
%%-------------------------------------------------------------------------
-export([allowed_characters/0,
compose_query/1,
compose_query/2,
dissect_query/1,
normalize/1,
normalize/2,
percent_decode/1,
parse/1,
recompose/1,
resolve/2,
resolve/3,
transcode/2,
quote/1,
quote/2,
unquote/1]).
-export_type([error/0,
uri_map/0,
uri_string/0]).
%%-------------------------------------------------------------------------
%% Internal API
%%-------------------------------------------------------------------------
-export([is_host/1, is_path/1]). % suppress warnings
%%-------------------------------------------------------------------------
%% Macros
%%-------------------------------------------------------------------------
-define(CHAR(Char), <<Char/utf8>>).
-define(STRING_EMPTY, <<>>).
-define(STRING(MatchStr), <<MatchStr/binary>>).
-define(STRING_REST(MatchStr, Rest), <<MatchStr/utf8, Rest/binary>>).
-define(DEC2HEX(X),
if ((X) >= 0) andalso ((X) =< 9) -> (X) + $0;
((X) >= 10) andalso ((X) =< 15) -> (X) + $A - 10
end).
-define(HEX2DEC(X),
if ((X) >= $0) andalso ((X) =< $9) -> (X) - $0;
((X) >= $A) andalso ((X) =< $F) -> (X) - $A + 10;
((X) >= $a) andalso ((X) =< $f) -> (X) - $a + 10
end).
%%%=========================================================================
%%% API
%%%=========================================================================
%%-------------------------------------------------------------------------
%% URI compliant with RFC 3986
%% ASCII %x21 - %x7A ("!" - "z") except
%% %x34 " double quote
%% %x60 < less than
%% %x62 > greater than
%% %x92 \ backslash
%% %x94 ^ caret / circumflex
%% %x96 ` grave / accent
%%-------------------------------------------------------------------------
-doc """
List of unicode codepoints, a UTF-8 encoded binary, or a mix of the two,
representing an [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) compliant URI
(_percent-encoded form_). A URI is a sequence of characters from a very limited
set: the letters of the basic Latin alphabet, digits, and a few special
characters.
""".
-type uri_string() :: iodata().
-doc """
Error tuple indicating the type of error. Possible values of the second
component:
- `invalid_character`
- `invalid_encoding`
- `invalid_input`
- `invalid_map`
- `invalid_percent_encoding`
- `invalid_scheme`
- `invalid_uri`
- `invalid_utf8`
- `missing_value`
The third component is a term providing additional information about the cause
of the error.
""".
-type error() :: {error, atom(), term()}.
%%-------------------------------------------------------------------------
%% RFC 3986, Chapter 3. Syntax Components
%%-------------------------------------------------------------------------
-doc "Map holding the main components of a URI.".
-type uri_map() ::
#{fragment => unicode:chardata(),
host => unicode:chardata(),
path => unicode:chardata(),
port => non_neg_integer() | undefined,
query => unicode:chardata(),
scheme => unicode:chardata(),
userinfo => unicode:chardata()}.
%%-------------------------------------------------------------------------
%% Normalize URIs
%%-------------------------------------------------------------------------
-doc """
Transforms an `URI` into a normalized form using Syntax-Based Normalization as
defined by [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt).
This function implements case normalization, percent-encoding normalization,
path segment normalization and scheme based normalization for HTTP(S) with basic
support for FTP, SSH, SFTP and TFTP.
_Example:_
```erlang
1> uri_string:normalize("/a/b/c/./../../g").
"/a/g"
2> uri_string:normalize(<<"mid/content=5/../6">>).
<<"mid/6">>
3> uri_string:normalize("http://localhost:80").
"http://localhost/"
4> uri_string:normalize(#{scheme => "http",port => 80,path => "/a/b/c/./../../g",
4> host => "localhost-örebro"}).
"http://localhost-%C3%B6rebro/a/g"
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec normalize(URI) -> NormalizedURI when
URI :: uri_string() | uri_map(),
NormalizedURI :: uri_string()
| error().
normalize(URIMap) ->
normalize(URIMap, []).
-doc """
Same as [`normalize/1`](`normalize/1`) but with an additional `Options`
parameter, that controls whether the normalized URI shall be returned as an
uri_map().
There is one supported option: `return_map`.
_Example:_
```erlang
1> uri_string:normalize("/a/b/c/./../../g", [return_map]).
#{path => "/a/g"}
2> uri_string:normalize(<<"mid/content=5/../6">>, [return_map]).
#{path => <<"mid/6">>}
3> uri_string:normalize("http://localhost:80", [return_map]).
#{scheme => "http",path => "/",host => "localhost"}
4> uri_string:normalize(#{scheme => "http",port => 80,path => "/a/b/c/./../../g",
4> host => "localhost-örebro"}, [return_map]).
#{scheme => "http",path => "/a/g",host => "localhost-örebro"}
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec normalize(URI, Options) -> NormalizedURI when
URI :: uri_string() | uri_map(),
Options :: [return_map],
NormalizedURI :: uri_string() | uri_map()
| error().
normalize(URIMap, []) when is_map(URIMap) ->
try recompose(normalize_map(URIMap))
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
normalize(URIMap, [return_map]) when is_map(URIMap) ->
try normalize_map(URIMap)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
normalize(URIString, []) ->
case parse(URIString) of
Value when is_map(Value) ->
try recompose(normalize_map(Value))
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
Error ->
Error
end;
normalize(URIString, [return_map]) ->
case parse(URIString) of
Value when is_map(Value) ->
try normalize_map(Value)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
Error ->
Error
end.
%%-------------------------------------------------------------------------
%% Parse URIs
%%-------------------------------------------------------------------------
-doc """
Parses an [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) compliant
`t:uri_string/0` into a `t:uri_map/0`, that holds the parsed components of the
`URI`. If parsing fails, an error tuple is returned.
See also the opposite operation `recompose/1`.
_Example:_
```erlang
1> uri_string:parse("foo://user@example.com:8042/over/there?name=ferret#nose").
#{fragment => "nose",host => "example.com",
path => "/over/there",port => 8042,query => "name=ferret",
scheme => foo,userinfo => "user"}
2> uri_string:parse(<<"foo://user@example.com:8042/over/there?name=ferret">>).
#{host => <<"example.com">>,path => <<"/over/there">>,
port => 8042,query => <<"name=ferret">>,scheme => <<"foo">>,
userinfo => <<"user">>}
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec parse(URIString) -> URIMap when
URIString :: uri_string(),
URIMap :: uri_map()
| error().
parse(URIString) when is_binary(URIString) ->
try parse_uri_reference(URIString, #{})
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
parse(URIString) when is_list(URIString) ->
try
Binary = unicode:characters_to_binary(URIString),
Map = parse_uri_reference(Binary, #{}),
convert_mapfields_to_list(Map)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end.
%%-------------------------------------------------------------------------
%% Recompose URIs
%%-------------------------------------------------------------------------
-doc """
Creates an [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) compliant
`URIString` (percent-encoded), based on the components of `URIMap`. If the
`URIMap` is invalid, an error tuple is returned.
See also the opposite operation `parse/1`.
_Example:_
```erlang
1> URIMap = #{fragment => "nose", host => "example.com", path => "/over/there",
1> port => 8042, query => "name=ferret", scheme => "foo", userinfo => "user"}.
#{fragment => "nose",host => "example.com",
path => "/over/there",port => 8042,query => "name=ferret",
scheme => "foo",userinfo => "user"}
2> uri_string:recompose(URIMap).
"foo://example.com:8042/over/there?name=ferret#nose"
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec recompose(URIMap) -> URIString when
URIMap :: uri_map(),
URIString :: uri_string()
| error().
recompose(Map) ->
case is_valid_map(Map) of
false ->
{error, invalid_map, Map};
true ->
try
T0 = update_scheme(Map, empty),
T1 = update_userinfo(Map, T0),
T2 = update_host(Map, T1),
T3 = update_port(Map, T2),
T4 = update_path(Map, T3),
T5 = update_query(Map, T4),
update_fragment(Map, T5)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end
end.
%%-------------------------------------------------------------------------
%% Resolve URIs
%%-------------------------------------------------------------------------
-doc """
Convert a `RefURI` reference that might be relative to a given base URI into the
parsed components of the reference's target, which can then be recomposed to
form the target URI.
_Example:_
```erlang
1> uri_string:resolve("/abs/ol/ute", "http://localhost/a/b/c?q").
"http://localhost/abs/ol/ute"
2> uri_string:resolve("../relative", "http://localhost/a/b/c?q").
"http://localhost/a/relative"
3> uri_string:resolve("http://localhost/full", "http://localhost/a/b/c?q").
"http://localhost/full"
4> uri_string:resolve(#{path => "path", query => "xyz"}, "http://localhost/a/b/c?q").
"http://localhost/a/b/path?xyz"
```
""".
-doc(#{since => <<"OTP 22.3">>}).
-spec resolve(RefURI, BaseURI) -> TargetURI when
RefURI :: uri_string() | uri_map(),
BaseURI :: uri_string() | uri_map(),
TargetURI :: uri_string()
| error().
resolve(URIMap, BaseURIMap) ->
resolve(URIMap, BaseURIMap, []).
-doc """
Same as [`resolve/2`](`resolve/2`) but with an additional `Options` parameter,
that controls whether the target URI shall be returned as an uri_map(). There is
one supported option: `return_map`.
_Example:_
```erlang
1> uri_string:resolve("/abs/ol/ute", "http://localhost/a/b/c?q", [return_map]).
#{host => "localhost",path => "/abs/ol/ute",scheme => "http"}
2> uri_string:resolve(#{path => "/abs/ol/ute"}, #{scheme => "http",
2> host => "localhost", path => "/a/b/c?q"}, [return_map]).
#{host => "localhost",path => "/abs/ol/ute",scheme => "http"}
```
""".
-doc(#{since => <<"OTP 22.3">>}).
-spec resolve(RefURI, BaseURI, Options) -> TargetURI when
RefURI :: uri_string() | uri_map(),
BaseURI :: uri_string() | uri_map(),
Options :: [return_map],
TargetURI :: uri_string() | uri_map()
| error().
resolve(URIMap, BaseURIMap, Options) when is_map(URIMap) ->
case resolve_map(URIMap, BaseURIMap) of
TargetURIMap when is_map(TargetURIMap) ->
case Options of
[return_map] ->
TargetURIMap;
[] ->
recompose(TargetURIMap)
end;
Error ->
Error
end;
resolve(URIString, BaseURIMap, Options) ->
case parse(URIString) of
URIMap when is_map(URIMap) ->
resolve(URIMap, BaseURIMap, Options);
Error ->
Error
end.
%%-------------------------------------------------------------------------
%% Transcode URIs
%%-------------------------------------------------------------------------
-doc """
Transcodes an [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) compliant
`URIString`, where `Options` is a list of tagged tuples, specifying the inbound
(`in_encoding`) and outbound (`out_encoding`) encodings.
`in_encoding` and `out_encoding` specifies both binary encoding and percent-encoding
for the input and output data. Mixed encoding, where binary encoding is not the same as
percent-encoding, is not supported. If an argument is invalid, an error tuple is
returned.
_Example:_
```erlang
1> uri_string:transcode(<<"foo%00%00%00%F6bar"/utf32>>,
1> [{in_encoding, utf32},{out_encoding, utf8}]).
<<"foo%C3%B6bar"/utf8>>
2> uri_string:transcode("foo%F6bar", [{in_encoding, latin1},
2> {out_encoding, utf8}]).
"foo%C3%B6bar"
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec transcode(URIString, Options) -> Result when
URIString :: uri_string(),
Options :: [{in_encoding, unicode:encoding()}|{out_encoding, unicode:encoding()}],
Result :: uri_string()
| error().
transcode(URIString, Options) when is_binary(URIString) ->
try
InEnc = proplists:get_value(in_encoding, Options, utf8),
OutEnc = proplists:get_value(out_encoding, Options, utf8),
List = convert_to_list(URIString, InEnc),
Output = transcode(List, [], InEnc, OutEnc),
convert_to_binary(Output, utf8, OutEnc)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end;
transcode(URIString, Options) when is_list(URIString) ->
InEnc = proplists:get_value(in_encoding, Options, utf8),
OutEnc = proplists:get_value(out_encoding, Options, utf8),
Flattened = flatten_list(URIString, InEnc),
try transcode(Flattened, [], InEnc, OutEnc)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end.
%%-------------------------------------------------------------------------
%% Misc
%%-------------------------------------------------------------------------
-doc """
This is a utility function meant to be used in the shell for printing the
allowed characters in each major URI component, and also in the most important
characters sets.
Note that this function does not replace the ABNF rules defined by the standards,
these character sets are derived directly from those aformentioned rules. For more
information see the
[Uniform Resource Identifiers](uri_string_usage.md#percent_encoding) chapter in
stdlib's Users Guide.
""".
-doc(#{since => <<"OTP 23.2">>}).
-spec allowed_characters() -> [{atom(), list()}].
allowed_characters() ->
Input = lists:seq(0,127),
Scheme = lists:filter(fun is_scheme/1, Input),
UserInfo = lists:filter(fun is_userinfo/1, Input),
Host = lists:filter(fun is_host/1, Input),
IPv4 = lists:filter(fun is_ipv4/1, Input),
IPv6 = lists:filter(fun is_ipv6/1, Input),
RegName = lists:filter(fun is_reg_name/1, Input),
Path = lists:filter(fun is_path/1, Input),
Query = lists:filter(fun is_query/1, Input),
Fragment = lists:filter(fun is_fragment/1, Input),
Reserved = lists:filter(fun is_reserved/1, Input),
Unreserved = lists:filter(fun is_unreserved/1, Input),
[{scheme, Scheme},
{userinfo, UserInfo},
{host, Host},
{ipv4, IPv4},
{ipv6, IPv6},
{regname,RegName},
{path,Path},
{query, Query},
{fragment,Fragment},
{reserved, Reserved},
{unreserved, Unreserved}].
-doc """
Decodes all percent-encoded triplets in the input that can be both a
`t:uri_string/0` and a `t:uri_map/0`.
Note, that this function performs raw decoding and it shall be used on already
parsed URI components. Applying this function directly on a standard URI can
effectively change it.
If the input encoding is not UTF-8, an error tuple is returned.
_Example:_
```erlang
1> uri_string:percent_decode(#{host => "localhost-%C3%B6rebro",path => [],
1> scheme => "http"}).
#{host => "localhost-örebro",path => [],scheme => "http"}
2> uri_string:percent_decode(<<"%C3%B6rebro">>).
<<"örebro"/utf8>>
```
> #### Warning {: .warning }
>
> Using `uri_string:percent_decode/1` directly on a URI is not safe. This
> example shows, that after each consecutive application of the function the
> resulting URI will be changed. None of these URIs refer to the same resource.
>
> ```erlang
> 3> uri_string:percent_decode(<<"http://local%252Fhost/path">>).
> <<"http://local%2Fhost/path">>
> 4> uri_string:percent_decode(<<"http://local%2Fhost/path">>).
> <<"http://local/host/path">>
> ```
""".
-doc(#{since => <<"OTP 23.2">>}).
-spec percent_decode(URI) -> Result when
URI :: uri_string() | uri_map(),
Result :: uri_string() |
uri_map() |
{error, {invalid, {atom(), {term(), term()}}}}.
percent_decode(URIMap) when is_map(URIMap)->
Fun = fun (K,V) when K =:= userinfo; K =:= host; K =:= path;
K =:= query; K =:= fragment ->
case raw_decode(V) of
{error, Reason, Input} ->
throw({error, {invalid, {K, {Reason, Input}}}});
Else ->
Else
end;
%% Handle port and scheme
(_,V) ->
V
end,
try maps:map(Fun, URIMap)
catch throw:Return ->
Return
end;
percent_decode(URI) when is_list(URI) orelse
is_binary(URI) ->
raw_decode(URI).
-doc """
Replaces characters out of unreserved set with their percent encoded
equivalents.
Unreserved characters defined in
[RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) are not quoted.
_Example:_
```erlang
1> uri_string:quote("SomeId/04").
"SomeId%2F04"
2> uri_string:quote(<<"SomeId/04">>).
<<"SomeId%2F04">>
```
> #### Warning {: .warning }
>
> Function is not aware about any URI component context and should not be used
> on whole URI. If applied more than once on the same data, might produce
> unexpected results.
""".
-doc(#{since => <<"OTP 25.0">>}).
-spec quote(Data) -> QuotedData when
Data :: unicode:chardata(),
QuotedData :: unicode:chardata().
quote(D) ->
encode(D, fun is_unreserved/1).
-doc """
Same as [`quote/1`](`quote/1`), but `Safe` allows user to provide a list of
characters to be protected from encoding.
_Example:_
```erlang
1> uri_string:quote("SomeId/04", "/").
"SomeId/04"
2> uri_string:quote(<<"SomeId/04">>, "/").
<<"SomeId/04">>
```
> #### Warning {: .warning }
>
> Function is not aware about any URI component context and should not be used
> on whole URI. If applied more than once on the same data, might produce
> unexpected results.
""".
-doc(#{since => <<"OTP 25.0">>}).
-spec quote(Data, Safe) -> QuotedData when
Data :: unicode:chardata(),
Safe :: string(),
QuotedData :: unicode:chardata().
quote(D, Safe) ->
UnreservedOrSafe =
fun(C) ->
is_unreserved(C) orelse lists:member(C, Safe)
end,
encode(D, UnreservedOrSafe).
-doc """
Percent decode characters.
_Example:_
```erlang
1> uri_string:unquote("SomeId%2F04").
"SomeId/04"
2> uri_string:unquote(<<"SomeId%2F04">>).
<<"SomeId/04">>
```
> #### Warning {: .warning }
>
> Function is not aware about any URI component context and should not be used
> on whole URI. If applied more than once on the same data, might produce
> unexpected results.
""".
-doc(#{since => <<"OTP 25.0">>}).
-spec unquote(QuotedData) -> Data when
QuotedData :: unicode:chardata(),
Data :: unicode:chardata().
unquote(D) ->
raw_decode(D).
%%-------------------------------------------------------------------------
%% Functions for working with the query part of a URI as a list
%% of key/value pairs.
%% HTML 5.2 - 4.10.21.6 URL-encoded form data - WHATWG URL (10 Jan 2018) - UTF-8
%% HTML 5.0 - 4.10.22.6 URL-encoded form data - non UTF-8
%%-------------------------------------------------------------------------
%%-------------------------------------------------------------------------
%% Compose urlencoded query string from a list of unescaped key/value pairs.
%% (application/x-www-form-urlencoded encoding algorithm)
%%-------------------------------------------------------------------------
-doc """
Composes a form-urlencoded `QueryString` based on a `QueryList`, a list of
non-percent-encoded key-value pairs.
Form-urlencoding is defined in section 4.10.21.6 of the [HTML 5.2](https://www.w3.org/TR/html52/)
specification and in section 4.10.22.6 of the [HTML 5.0](https://www.w3.org/TR/html50/)
specification for non-UTF-8 encodings.
See also the opposite operation `dissect_query/1`.
_Example:_
```erlang
1> uri_string:compose_query([{"foo bar","1"},{"city","örebro"}]).
"foo+bar=1&city=%C3%B6rebro"
2> uri_string:compose_query([{<<"foo bar">>,<<"1">>},
2> {<<"city">>,<<"örebro"/utf8>>}]).
<<"foo+bar=1&city=%C3%B6rebro">>
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec compose_query(QueryList) -> QueryString when
QueryList :: [{unicode:chardata(), unicode:chardata() | true}],
QueryString :: uri_string()
| error().
compose_query(List) ->
compose_query(List, [{encoding, utf8}]).
-doc """
Same as [`compose_query/1`](`compose_query/1`) but with an additional `Options`
parameter, that controls the encoding ("charset") used by the encoding
algorithm.
There are two supported encodings: `utf8` (or `unicode`) and `latin1`.
Each character in the entry's name and value that cannot be expressed using the
selected character encoding, is replaced by a string consisting of a U+0026
AMPERSAND character (&), a "#" (U+0023) character, one or more ASCII digits
representing the Unicode code point of the character in base ten, and finally a
";" (U+003B) character.
Bytes that are out of the range 0x2A, 0x2D, 0x2E, 0x30 to 0x39, 0x41 to 0x5A,
0x5F, 0x61 to 0x7A, are percent-encoded (U+0025 PERCENT SIGN character (%)
followed by uppercase ASCII hex digits representing the hexadecimal value of the
byte).
See also the opposite operation `dissect_query/1`.
_Example:_
```erlang
1> uri_string:compose_query([{"foo bar","1"},{"city","örebro"}],
1> [{encoding, latin1}]).
"foo+bar=1&city=%F6rebro"
2> uri_string:compose_query([{<<"foo bar">>,<<"1">>},
2> {<<"city">>,<<"東京"/utf8>>}], [{encoding, latin1}]).
<<"foo+bar=1&city=%26%2326481%3B%26%2320140%3B">>
```
""".
-doc(#{since => <<"OTP 21.0">>}).
-spec compose_query(QueryList, Options) -> QueryString when
QueryList :: [{unicode:chardata(), unicode:chardata() | true}],
Options :: [{encoding, atom()}],
QueryString :: uri_string()
| error().
compose_query([],_Options) ->
[];
compose_query(List, Options) ->
try compose_query(List, Options, false, <<>>)
catch
throw:{error, Atom, RestData} -> {error, Atom, RestData}
end.