1 // Written in the D programming language.
4 * Encode and decode Uniform Resource Identifiers (URIs).
5 * URIs are used in internet transfer protocols.
6 * Valid URI characters consist of letters, digits,
7 * and the characters $(B ;/?:@&=+$,-_.!~*'())
8 * Reserved URI characters are $(B ;/?:@&=+$,)
9 * Escape sequences consist of $(B %) followed by two hex digits.
12 * $(LINK2 http://www.ietf.org/rfc/rfc3986.txt, RFC 3986)<br>
13 * $(LINK2 http://en.wikipedia.org/wiki/Uniform_resource_identifier, Wikipedia)
14 * Copyright: Copyright Digital Mars 2000 - 2009.
15 * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
16 * Authors: $(HTTP digitalmars.com, Walter Bright)
17 * Source: $(PHOBOSSRC std/_uri.d)
19 /* Copyright Digital Mars 2000 - 2009.
20 * Distributed under the Boost Software License, Version 1.0.
21 * (See accompanying file LICENSE_1_0.txt or copy at
22 * http://www.boost.org/LICENSE_1_0.txt)
26 //debug=uri; // uncomment to turn on debugging writefln's
27 debug(uri
) import std
.stdio
;
28 import std
.traits
: isSomeChar
;
30 /** This Exception is thrown if something goes wrong when encoding or
33 class URIException
: Exception
35 import std
.exception
: basicExceptionCtors
;
36 mixin basicExceptionCtors
;
45 URI_Hash
= 0x10, // '#'
48 private immutable char[16] hex2ascii
= "0123456789ABCDEF";
50 private immutable ubyte[128] uri_flags
= // indexed by character
54 // Compile time initialize
55 uflags
['#'] |
= URI_Hash
;
57 foreach (c
; 'A' .. 'Z' + 1)
59 uflags
[c
] |
= URI_Alpha
;
60 uflags
[c
+ 0x20] |
= URI_Alpha
; // lowercase letters
62 foreach (c
; '0' .. '9' + 1) uflags
[c
] |
= URI_Digit
;
63 foreach (c
; ";/?:@&=+$,") uflags
[c
] |
= URI_Reserved
;
64 foreach (c
; "-_.!~*'()") uflags
[c
] |
= URI_Mark
;
68 private string
URI_Encode(dstring
str, uint unescapedSet
)
70 import core
.exception
: OutOfMemoryError
;
71 import core
.stdc
.stdlib
: alloca
;
79 char[50] buffer
= void;
82 uint Rsize
; // alloc'd size
84 immutable len
= str.length
;
87 Rsize
= buffer
.length
;
90 for (k
= 0; k
!= len
; k
++)
93 // if (C in unescapedSet)
94 if (C
< uri_flags
.length
&& uri_flags
[C
] & unescapedSet
)
103 R2
= (new char[Rsize
]).ptr
;
107 R2
= cast(char *) alloca(Rsize
* char.sizeof
);
109 throw new OutOfMemoryError("Alloca failure");
111 R2
[0 .. Rlen
] = R
[0 .. Rlen
];
114 R
[Rlen
] = cast(char) C
;
124 // Transform V into octets
127 Octet
[0] = cast(char) V
;
132 Octet
[0] = cast(char)(0xC0 |
(V
>> 6));
133 Octet
[1] = cast(char)(0x80 |
(V
& 0x3F));
136 else if (V
<= 0xFFFF)
138 Octet
[0] = cast(char)(0xE0 |
(V
>> 12));
139 Octet
[1] = cast(char)(0x80 |
((V
>> 6) & 0x3F));
140 Octet
[2] = cast(char)(0x80 |
(V
& 0x3F));
143 else if (V
<= 0x1FFFFF)
145 Octet
[0] = cast(char)(0xF0 |
(V
>> 18));
146 Octet
[1] = cast(char)(0x80 |
((V
>> 12) & 0x3F));
147 Octet
[2] = cast(char)(0x80 |
((V
>> 6) & 0x3F));
148 Octet
[3] = cast(char)(0x80 |
(V
& 0x3F));
153 throw new URIException("Undefined UTF-32 code point");
156 if (Rlen
+ L
* 3 > Rsize
)
160 Rsize
= 2 * (Rlen
+ L
* 3);
163 R2
= (new char[Rsize
]).ptr
;
167 R2
= cast(char *) alloca(Rsize
* char.sizeof
);
169 throw new OutOfMemoryError("Alloca failure");
171 R2
[0 .. Rlen
] = R
[0 .. Rlen
];
175 for (j
= 0; j
< L
; j
++)
178 R
[Rlen
+ 1] = hex2ascii
[Octet
[j
] >> 4];
179 R
[Rlen
+ 2] = hex2ascii
[Octet
[j
] & 15];
186 return R
[0 .. Rlen
].idup
;
189 private uint ascii2hex(dchar c
) @nogc @safe pure nothrow
191 return (c
<= '9') ? c
- '0' :
192 (c
<= 'F') ? c
- 'A' + 10 :
196 private dstring
URI_Decode(Char
)(in Char
[] uri
, uint reservedSet
)
199 import core
.exception
: OutOfMemoryError
;
200 import core
.stdc
.stdlib
: alloca
;
201 import std
.ascii
: isHexDigit
;
208 // Result array, allocated on stack
212 immutable len
= uri
.length
;
215 // Preallocate result buffer R guaranteed to be large enough for result
217 if (Rsize
> 1024 / dchar.sizeof
)
219 R
= (new dchar[Rsize
]).ptr
;
223 R
= cast(dchar *) alloca(Rsize
* dchar.sizeof
);
225 throw new OutOfMemoryError("Alloca failure");
229 for (k
= 0; k
!= len
; k
++)
243 throw new URIException("Unexpected end of URI");
244 if (!isHexDigit(s
[k
+ 1]) ||
!isHexDigit(s
[k
+ 2]))
245 throw new URIException("Expected two hexadecimal digits after '%'");
246 B
= cast(char)((ascii2hex(s
[k
+ 1]) << 4) + ascii2hex(s
[k
+ 2]));
259 throw new URIException("UTF-32 code point size too large");
260 if (((B
<< n
) & 0x80) == 0)
263 throw new URIException("UTF-32 code point size too small");
268 // Pick off (7 - n) significant bits of B from first byte of octet
269 V
= B
& ((1 << (7 - n
)) - 1); // (!!!)
271 if (k
+ (3 * (n
- 1)) >= len
)
272 throw new URIException("UTF-32 unaligned String");
273 for (j
= 1; j
!= n
; j
++)
277 throw new URIException("Expected: '%'");
278 if (!isHexDigit(s
[k
+ 1]) ||
!isHexDigit(s
[k
+ 2]))
279 throw new URIException("Expected two hexadecimal digits after '%'");
280 B
= cast(char)((ascii2hex(s
[k
+ 1]) << 4) + ascii2hex(s
[k
+ 2]));
281 if ((B
& 0xC0) != 0x80)
282 throw new URIException("Incorrect UTF-32 multi-byte sequence");
284 V
= (V
<< 6) |
(B
& 0x3F);
287 throw new URIException("Unknown UTF-32 code point");
290 if (C
< uri_flags
.length
&& uri_flags
[C
] & reservedSet
)
292 // R ~= s[start .. k + 1];
293 immutable width
= (k
+ 1) - start
;
294 for (int ii
= 0; ii
< width
; ii
++)
295 R
[Rlen
+ ii
] = s
[start
+ ii
];
304 assert(Rlen
<= Rsize
); // enforce our preallocation size guarantee
306 // Copy array on stack to array in memory
307 return R
[0 .. Rlen
].idup
;
310 /*************************************
311 * Decodes the URI string encodedURI into a UTF-8 string and returns it.
312 * Escape sequences that resolve to reserved URI characters are not replaced.
313 * Escape sequences that resolve to the '#' character are not replaced.
316 string
decode(Char
)(in Char
[] encodedURI
)
319 import std
.algorithm
.iteration
: each
;
320 import std
.utf
: encode
;
321 auto s
= URI_Decode(encodedURI
, URI_Reserved | URI_Hash
);
323 s
.each
!(c
=> encode(r
, c
));
327 /*******************************
328 * Decodes the URI string encodedURI into a UTF-8 string and returns it. All
329 * escape sequences are decoded.
332 string
decodeComponent(Char
)(in Char
[] encodedURIComponent
)
335 import std
.algorithm
.iteration
: each
;
336 import std
.utf
: encode
;
337 auto s
= URI_Decode(encodedURIComponent
, 0);
339 s
.each
!(c
=> encode(r
, c
));
343 /*****************************
344 * Encodes the UTF-8 string uri into a URI and returns that URI. Any character
345 * not a valid URI character is escaped. The '#' character is not escaped.
348 string
encode(Char
)(in Char
[] uri
)
351 import std
.utf
: toUTF32
;
352 auto s
= toUTF32(uri
);
353 return URI_Encode(s
, URI_Reserved | URI_Hash | URI_Alpha | URI_Digit | URI_Mark
);
356 /********************************
357 * Encodes the UTF-8 string uriComponent into a URI and returns that URI.
358 * Any character not a letter, digit, or one of -_.!~*'() is escaped.
361 string
encodeComponent(Char
)(in Char
[] uriComponent
)
364 import std
.utf
: toUTF32
;
365 auto s
= toUTF32(uriComponent
);
366 return URI_Encode(s
, URI_Alpha | URI_Digit | URI_Mark
);
369 /* Encode associative array using www-form-urlencoding
372 * values = an associative array containing the values to be encoded.
375 * A string encoded using www-form-urlencoding.
377 package string
urlEncode(in string
[string
] values
)
379 if (values
.length
== 0)
382 import std
.array
: Appender
;
383 import std
.format
: formattedWrite
;
386 enc
.reserve(values
.length
* 128);
389 foreach (k
, v
; values
)
393 formattedWrite(enc
, "%s=%s", encodeComponent(k
), encodeComponent(v
));
401 // @system because urlEncode -> encodeComponent -> URI_Encode
402 // URI_Encode uses alloca and pointer slicing
404 assert(urlEncode(a
) == "");
405 assert(urlEncode(["name1" : "value1"]) == "name1=value1");
406 auto enc
= urlEncode(["name1" : "value1", "name2" : "value2"]);
407 assert(enc
== "name1=value1&name2=value2" || enc
== "name2=value2&name1=value1");
410 /***************************
411 * Does string s[] start with a URL?
414 * len it does, and s[0 .. len] is the slice of s[] that is that URL
417 ptrdiff_t
uriLength(Char
)(in Char
[] s
)
420 /* Must start with one of:
425 import std
.ascii
: isAlphaNum
;
426 import std
.uni
: icmp
;
433 if (s
.length
> 7 && icmp(s
[0 .. 7], "http://") == 0)
439 if (s
.length
> 8 && icmp(s
[0 .. 8], "https://") == 0)
446 for (; i
< s
.length
; i
++)
451 if (c
== '-' || c
== '_' || c
== '?' ||
452 c
== '=' || c
== '%' || c
== '&' ||
453 c
== '/' || c
== '+' || c
== '#' ||
454 c
== '~' || c
== '$')
472 string s1
= "http://www.digitalmars.com/~fred/fredsRX.html#foo end!";
473 assert(uriLength(s1
) == 49);
474 string s2
= "no uri here";
475 assert(uriLength(s2
) == -1);
476 assert(uriLength("issue 14924") < 0);
480 /***************************
481 * Does string s[] start with an email address?
484 * len it does, and s[0 .. i] is the slice of s[] that is that email address
488 ptrdiff_t
emailLength(Char
)(in Char
[] s
)
491 import std
.ascii
: isAlpha
, isAlphaNum
;
505 if (c
== '-' || c
== '_' || c
== '.')
513 /* Now do the part past the '@'
516 for (; i
< s
.length
; i
++)
521 if (c
== '-' || c
== '_')
530 if (!lastdot ||
(i
- lastdot
!= 3 && i
- lastdot
!= 4))
539 string s1
= "my.e-mail@www.example-domain.com with garbage added";
540 assert(emailLength(s1
) == 32);
541 string s2
= "no email address here";
542 assert(emailLength(s2
) == -1);
543 assert(emailLength("issue 14924") < 0);
549 //@system because of encode -> URI_Encode
550 debug(uri
) writeln("uri.encodeURI.unittest");
552 string source
= "http://www.digitalmars.com/~fred/fred's RX.html#foo";
553 string target
= "http://www.digitalmars.com/~fred/fred's%20RX.html#foo";
555 auto result
= encode(source
);
556 debug(uri
) writefln("result = '%s'", result
);
557 assert(result
== target
);
558 result
= decode(target
);
559 debug(uri
) writefln("result = '%s'", result
);
560 assert(result
== source
);
562 result
= encode(decode("%E3%81%82%E3%81%82"));
563 assert(result
== "%E3%81%82%E3%81%82");
565 result
= encodeComponent("c++");
566 assert(result
== "c%2B%2B");
568 auto str = new char[10_000_000];
570 result
= encodeComponent(str);
571 foreach (char c
; result
)
574 result
= decode("%41%42%43");
575 debug(uri
) writeln(result
);
577 import std
.meta
: AliasSeq
;
578 foreach (StringType
; AliasSeq
!(char[], wchar[], dchar[], string
, wstring
, dstring
))
580 import std
.conv
: to
;
581 StringType decoded1
= source
.to
!StringType
;
582 string encoded1
= encode(decoded1
);
583 assert(decoded1
== source
.to
!StringType
); // check that `decoded1` wasn't changed
584 assert(encoded1
== target
);
585 assert(decoded1
== decode(encoded1
).to
!StringType
);
587 StringType encoded2
= target
.to
!StringType
;
588 string decoded2
= decode(encoded2
);
589 assert(encoded2
== target
.to
!StringType
); // check that `encoded2` wasn't changed
590 assert(decoded2
== source
);
591 assert(encoded2
== encode(decoded2
).to
!StringType
);