1 // Copyright 2013-2016 The rust-url developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 //! URLs use special characters to indicate the parts of the request.
10 //! For example, a `?` question mark marks the end of a path and the start of a query string.
11 //! In order for that character to exist inside a path, it needs to be encoded differently.
12 //!
13 //! Percent encoding replaces reserved characters with the `%` escape character
14 //! followed by a byte value as two hexadecimal digits.
15 //! For example, an ASCII space is replaced with `%20`.
16 //!
17 //! When encoding, the set of characters that can (and should, for readability) be left alone
18 //! depends on the context.
19 //! The `?` question mark mentioned above is not a separator when used literally
20 //! inside of a query string, and therefore does not need to be encoded.
21 //! The [`AsciiSet`] parameter of [`percent_encode`] and [`utf8_percent_encode`]
22 //! lets callers configure this.
23 //!
24 //! This crate deliberately does not provide many different sets.
25 //! Users should consider in what context the encoded string will be used,
26 //! read relevant specifications, and define their own set.
27 //! This is done by using the `add` method of an existing set.
28 //!
29 //! # Examples
30 //!
31 //! ```
32 //! use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
33 //!
34 //! /// https://url.spec.whatwg.org/#fragment-percent-encode-set
35 //! const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
36 //!
37 //! assert_eq!(utf8_percent_encode("foo <bar>", FRAGMENT).to_string(), "foo%20%3Cbar%3E");
38 //! ```
39 #![no_std]
40 
41 // For forwards compatibility
42 #[cfg(feature = "std")]
43 extern crate std as _;
44 
45 #[cfg(feature = "alloc")]
46 extern crate alloc;
47 
48 #[cfg(android_dylib)]
49 extern crate std;
50 
51 #[cfg(feature = "alloc")]
52 use alloc::{
53     borrow::{Cow, ToOwned},
54     string::String,
55     vec::Vec,
56 };
57 use core::{fmt, mem, slice, str};
58 
59 /// Represents a set of characters or bytes in the ASCII range.
60 ///
61 /// This is used in [`percent_encode`] and [`utf8_percent_encode`].
62 /// This is similar to [percent-encode sets](https://url.spec.whatwg.org/#percent-encoded-bytes).
63 ///
64 /// Use the `add` method of an existing set to define a new set. For example:
65 ///
66 /// ```
67 /// use percent_encoding::{AsciiSet, CONTROLS};
68 ///
69 /// /// https://url.spec.whatwg.org/#fragment-percent-encode-set
70 /// const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
71 /// ```
72 pub struct AsciiSet {
73     mask: [Chunk; ASCII_RANGE_LEN / BITS_PER_CHUNK],
74 }
75 
76 type Chunk = u32;
77 
78 const ASCII_RANGE_LEN: usize = 0x80;
79 
80 const BITS_PER_CHUNK: usize = 8 * mem::size_of::<Chunk>();
81 
82 impl AsciiSet {
83     /// Called with UTF-8 bytes rather than code points.
84     /// Not used for non-ASCII bytes.
contains(&self, byte: u8) -> bool85     const fn contains(&self, byte: u8) -> bool {
86         let chunk = self.mask[byte as usize / BITS_PER_CHUNK];
87         let mask = 1 << (byte as usize % BITS_PER_CHUNK);
88         (chunk & mask) != 0
89     }
90 
should_percent_encode(&self, byte: u8) -> bool91     fn should_percent_encode(&self, byte: u8) -> bool {
92         !byte.is_ascii() || self.contains(byte)
93     }
94 
add(&self, byte: u8) -> Self95     pub const fn add(&self, byte: u8) -> Self {
96         let mut mask = self.mask;
97         mask[byte as usize / BITS_PER_CHUNK] |= 1 << (byte as usize % BITS_PER_CHUNK);
98         AsciiSet { mask }
99     }
100 
remove(&self, byte: u8) -> Self101     pub const fn remove(&self, byte: u8) -> Self {
102         let mut mask = self.mask;
103         mask[byte as usize / BITS_PER_CHUNK] &= !(1 << (byte as usize % BITS_PER_CHUNK));
104         AsciiSet { mask }
105     }
106 }
107 
108 /// The set of 0x00 to 0x1F (C0 controls), and 0x7F (DEL).
109 ///
110 /// Note that this includes the newline and tab characters, but not the space 0x20.
111 ///
112 /// <https://url.spec.whatwg.org/#c0-control-percent-encode-set>
113 pub const CONTROLS: &AsciiSet = &AsciiSet {
114     mask: [
115         !0_u32, // C0: 0x00 to 0x1F (32 bits set)
116         0,
117         0,
118         1 << (0x7F_u32 % 32), // DEL: 0x7F (one bit set)
119     ],
120 };
121 
122 macro_rules! static_assert {
123     ($( $bool: expr, )+) => {
124         fn _static_assert() {
125             $(
126                 let _ = mem::transmute::<[u8; $bool as usize], u8>;
127             )+
128         }
129     }
130 }
131 
132 static_assert! {
133     CONTROLS.contains(0x00),
134     CONTROLS.contains(0x1F),
135     !CONTROLS.contains(0x20),
136     !CONTROLS.contains(0x7E),
137     CONTROLS.contains(0x7F),
138 }
139 
140 /// Everything that is not an ASCII letter or digit.
141 ///
142 /// This is probably more eager than necessary in any context.
143 pub const NON_ALPHANUMERIC: &AsciiSet = &CONTROLS
144     .add(b' ')
145     .add(b'!')
146     .add(b'"')
147     .add(b'#')
148     .add(b'$')
149     .add(b'%')
150     .add(b'&')
151     .add(b'\'')
152     .add(b'(')
153     .add(b')')
154     .add(b'*')
155     .add(b'+')
156     .add(b',')
157     .add(b'-')
158     .add(b'.')
159     .add(b'/')
160     .add(b':')
161     .add(b';')
162     .add(b'<')
163     .add(b'=')
164     .add(b'>')
165     .add(b'?')
166     .add(b'@')
167     .add(b'[')
168     .add(b'\\')
169     .add(b']')
170     .add(b'^')
171     .add(b'_')
172     .add(b'`')
173     .add(b'{')
174     .add(b'|')
175     .add(b'}')
176     .add(b'~');
177 
178 /// Return the percent-encoding of the given byte.
179 ///
180 /// This is unconditional, unlike `percent_encode()` which has an `AsciiSet` parameter.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use percent_encoding::percent_encode_byte;
186 ///
187 /// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
188 ///            "%66%6F%6F%20%62%61%72");
189 /// ```
190 #[inline]
percent_encode_byte(byte: u8) -> &'static str191 pub fn percent_encode_byte(byte: u8) -> &'static str {
192     static ENC_TABLE: &[u8; 768] = b"\
193       %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
194       %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
195       %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
196       %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
197       %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
198       %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
199       %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
200       %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
201       %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
202       %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
203       %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
204       %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
205       %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
206       %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
207       %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
208       %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
209       ";
210 
211     let index = usize::from(byte) * 3;
212     // SAFETY: ENC_TABLE is ascii-only, so any subset if it should be
213     // ascii-only too, which is valid utf8.
214     unsafe { str::from_utf8_unchecked(&ENC_TABLE[index..index + 3]) }
215 }
216 
217 /// Percent-encode the given bytes with the given set.
218 ///
219 /// Non-ASCII bytes and bytes in `ascii_set` are encoded.
220 ///
221 /// The return type:
222 ///
223 /// * Implements `Iterator<Item = &str>` and therefore has a `.collect::<String>()` method,
224 /// * Implements `Display` and therefore has a `.to_string()` method,
225 /// * Implements `Into<Cow<str>>` borrowing `input` when none of its bytes are encoded.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
231 ///
232 /// assert_eq!(percent_encode(b"foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
233 /// ```
234 #[inline]
percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a>235 pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
236     PercentEncode {
237         bytes: input,
238         ascii_set,
239     }
240 }
241 
242 /// Percent-encode the UTF-8 encoding of the given string.
243 ///
244 /// See [`percent_encode`] regarding the return type.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
250 ///
251 /// assert_eq!(utf8_percent_encode("foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
252 /// ```
253 #[inline]
utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a>254 pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
255     percent_encode(input.as_bytes(), ascii_set)
256 }
257 
258 /// The return type of [`percent_encode`] and [`utf8_percent_encode`].
259 #[derive(Clone)]
260 pub struct PercentEncode<'a> {
261     bytes: &'a [u8],
262     ascii_set: &'static AsciiSet,
263 }
264 
265 impl<'a> Iterator for PercentEncode<'a> {
266     type Item = &'a str;
267 
next(&mut self) -> Option<&'a str>268     fn next(&mut self) -> Option<&'a str> {
269         if let Some((&first_byte, remaining)) = self.bytes.split_first() {
270             if self.ascii_set.should_percent_encode(first_byte) {
271                 self.bytes = remaining;
272                 Some(percent_encode_byte(first_byte))
273             } else {
274                 // The unsafe blocks here are appropriate because the bytes are
275                 // confirmed as a subset of UTF-8 in should_percent_encode.
276                 for (i, &byte) in remaining.iter().enumerate() {
277                     if self.ascii_set.should_percent_encode(byte) {
278                         // 1 for first_byte + i for previous iterations of this loop
279                         let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
280                         self.bytes = remaining;
281                         return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
282                     }
283                 }
284                 let unchanged_slice = self.bytes;
285                 self.bytes = &[][..];
286                 Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
287             }
288         } else {
289             None
290         }
291     }
292 
size_hint(&self) -> (usize, Option<usize>)293     fn size_hint(&self) -> (usize, Option<usize>) {
294         if self.bytes.is_empty() {
295             (0, Some(0))
296         } else {
297             (1, Some(self.bytes.len()))
298         }
299     }
300 }
301 
302 impl<'a> fmt::Display for PercentEncode<'a> {
fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result303     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304         for c in (*self).clone() {
305             formatter.write_str(c)?
306         }
307         Ok(())
308     }
309 }
310 
311 #[cfg(feature = "alloc")]
312 impl<'a> From<PercentEncode<'a>> for Cow<'a, str> {
from(mut iter: PercentEncode<'a>) -> Self313     fn from(mut iter: PercentEncode<'a>) -> Self {
314         match iter.next() {
315             None => "".into(),
316             Some(first) => match iter.next() {
317                 None => first.into(),
318                 Some(second) => {
319                     let mut string = first.to_owned();
320                     string.push_str(second);
321                     string.extend(iter);
322                     string.into()
323                 }
324             },
325         }
326     }
327 }
328 
329 /// Percent-decode the given string.
330 ///
331 /// <https://url.spec.whatwg.org/#string-percent-decode>
332 ///
333 /// See [`percent_decode`] regarding the return type.
334 #[inline]
percent_decode_str(input: &str) -> PercentDecode<'_>335 pub fn percent_decode_str(input: &str) -> PercentDecode<'_> {
336     percent_decode(input.as_bytes())
337 }
338 
339 /// Percent-decode the given bytes.
340 ///
341 /// <https://url.spec.whatwg.org/#percent-decode>
342 ///
343 /// Any sequence of `%` followed by two hexadecimal digits is decoded.
344 /// The return type:
345 ///
346 /// * Implements `Into<Cow<u8>>` borrowing `input` when it contains no percent-encoded sequence,
347 /// * Implements `Iterator<Item = u8>` and therefore has a `.collect::<Vec<u8>>()` method,
348 /// * Has `decode_utf8()` and `decode_utf8_lossy()` methods.
349 ///
350 /// # Examples
351 ///
352 /// ```
353 /// use percent_encoding::percent_decode;
354 ///
355 /// assert_eq!(percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
356 /// ```
357 #[inline]
percent_decode(input: &[u8]) -> PercentDecode<'_>358 pub fn percent_decode(input: &[u8]) -> PercentDecode<'_> {
359     PercentDecode {
360         bytes: input.iter(),
361     }
362 }
363 
364 /// The return type of [`percent_decode`].
365 #[derive(Clone, Debug)]
366 pub struct PercentDecode<'a> {
367     bytes: slice::Iter<'a, u8>,
368 }
369 
after_percent_sign(iter: &mut slice::Iter<'_, u8>) -> Option<u8>370 fn after_percent_sign(iter: &mut slice::Iter<'_, u8>) -> Option<u8> {
371     let mut cloned_iter = iter.clone();
372     let h = char::from(*cloned_iter.next()?).to_digit(16)?;
373     let l = char::from(*cloned_iter.next()?).to_digit(16)?;
374     *iter = cloned_iter;
375     Some(h as u8 * 0x10 + l as u8)
376 }
377 
378 impl<'a> Iterator for PercentDecode<'a> {
379     type Item = u8;
380 
next(&mut self) -> Option<u8>381     fn next(&mut self) -> Option<u8> {
382         self.bytes.next().map(|&byte| {
383             if byte == b'%' {
384                 after_percent_sign(&mut self.bytes).unwrap_or(byte)
385             } else {
386                 byte
387             }
388         })
389     }
390 
size_hint(&self) -> (usize, Option<usize>)391     fn size_hint(&self) -> (usize, Option<usize>) {
392         let bytes = self.bytes.len();
393         ((bytes + 2) / 3, Some(bytes))
394     }
395 }
396 
397 #[cfg(feature = "alloc")]
398 impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
from(iter: PercentDecode<'a>) -> Self399     fn from(iter: PercentDecode<'a>) -> Self {
400         match iter.if_any() {
401             Some(vec) => Cow::Owned(vec),
402             None => Cow::Borrowed(iter.bytes.as_slice()),
403         }
404     }
405 }
406 
407 impl<'a> PercentDecode<'a> {
408     /// If the percent-decoding is different from the input, return it as a new bytes vector.
409     #[cfg(feature = "alloc")]
if_any(&self) -> Option<Vec<u8>>410     fn if_any(&self) -> Option<Vec<u8>> {
411         let mut bytes_iter = self.bytes.clone();
412         while bytes_iter.any(|&b| b == b'%') {
413             if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
414                 let initial_bytes = self.bytes.as_slice();
415                 let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
416                 let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
417                 decoded.push(decoded_byte);
418                 decoded.extend(PercentDecode { bytes: bytes_iter });
419                 return Some(decoded);
420             }
421         }
422         // Nothing to decode
423         None
424     }
425 
426     /// Decode the result of percent-decoding as UTF-8.
427     ///
428     /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
429     #[cfg(feature = "alloc")]
decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error>430     pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
431         match self.clone().into() {
432             Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
433                 Ok(s) => Ok(s.into()),
434                 Err(e) => Err(e),
435             },
436             Cow::Owned(bytes) => match String::from_utf8(bytes) {
437                 Ok(s) => Ok(s.into()),
438                 Err(e) => Err(e.utf8_error()),
439             },
440         }
441     }
442 
443     /// Decode the result of percent-decoding as UTF-8, lossily.
444     ///
445     /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
446     /// the replacement character.
447     #[cfg(feature = "alloc")]
decode_utf8_lossy(self) -> Cow<'a, str>448     pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
449         decode_utf8_lossy(self.clone().into())
450     }
451 }
452 
453 #[cfg(feature = "alloc")]
decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str>454 fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
455     // Note: This function is duplicated in `form_urlencoded/src/query_encoding.rs`.
456     match input {
457         Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
458         Cow::Owned(bytes) => {
459             match String::from_utf8_lossy(&bytes) {
460                 Cow::Borrowed(utf8) => {
461                     // If from_utf8_lossy returns a Cow::Borrowed, then we can
462                     // be sure our original bytes were valid UTF-8. This is because
463                     // if the bytes were invalid UTF-8 from_utf8_lossy would have
464                     // to allocate a new owned string to back the Cow so it could
465                     // replace invalid bytes with a placeholder.
466 
467                     // First we do a debug_assert to confirm our description above.
468                     let raw_utf8: *const [u8] = utf8.as_bytes();
469                     debug_assert!(raw_utf8 == &*bytes as *const [u8]);
470 
471                     // Given we know the original input bytes are valid UTF-8,
472                     // and we have ownership of those bytes, we re-use them and
473                     // return a Cow::Owned here.
474                     Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
475                 }
476                 Cow::Owned(s) => Cow::Owned(s),
477             }
478         }
479     }
480 }
481