lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //! Processing of `data:` URLs according to the Fetch Standard:
  2. //! <https://fetch.spec.whatwg.org/#data-urls>
  3. //! but starting from a string rather than a parsed URL to avoid extra copies.
  4. //!
  5. //! ```rust
  6. //! use data_url::{DataUrl, mime};
  7. //!
  8. //! let url = DataUrl::process("data:,Hello%20World!").unwrap();
  9. //! let (body, fragment) = url.decode_to_vec().unwrap();
  10. //!
  11. //! assert_eq!(url.mime_type().type_, "text");
  12. //! assert_eq!(url.mime_type().subtype, "plain");
  13. //! assert_eq!(url.mime_type().get_parameter("charset"), Some("US-ASCII"));
  14. //! assert_eq!(body, b"Hello World!");
  15. //! assert!(fragment.is_none());
  16. //! ```
  17. #[macro_use]
  18. extern crate matches;
  19. macro_rules! require {
  20. ($condition: expr) => {
  21. if !$condition {
  22. return None;
  23. }
  24. };
  25. }
  26. pub mod forgiving_base64;
  27. pub mod mime;
  28. pub struct DataUrl<'a> {
  29. mime_type: mime::Mime,
  30. base64: bool,
  31. encoded_body_plus_fragment: &'a str,
  32. }
  33. #[derive(Debug)]
  34. pub enum DataUrlError {
  35. NotADataUrl,
  36. NoComma,
  37. }
  38. impl<'a> DataUrl<'a> {
  39. /// <https://fetch.spec.whatwg.org/#data-url-processor>
  40. /// but starting from a string rather than a parsed `Url`, to avoid extra string copies.
  41. pub fn process(input: &'a str) -> Result<Self, DataUrlError> {
  42. use DataUrlError::*;
  43. let after_colon = pretend_parse_data_url(input).ok_or(NotADataUrl)?;
  44. let (from_colon_to_comma, encoded_body_plus_fragment) =
  45. find_comma_before_fragment(after_colon).ok_or(NoComma)?;
  46. let (mime_type, base64) = parse_header(from_colon_to_comma);
  47. Ok(DataUrl {
  48. mime_type,
  49. base64,
  50. encoded_body_plus_fragment,
  51. })
  52. }
  53. pub fn mime_type(&self) -> &mime::Mime {
  54. &self.mime_type
  55. }
  56. /// Streaming-decode the data URL’s body to `write_body_bytes`,
  57. /// and return the URL’s fragment identifier if it has one.
  58. pub fn decode<F, E>(
  59. &self,
  60. write_body_bytes: F,
  61. ) -> Result<Option<FragmentIdentifier<'a>>, forgiving_base64::DecodeError<E>>
  62. where
  63. F: FnMut(&[u8]) -> Result<(), E>,
  64. {
  65. if self.base64 {
  66. decode_with_base64(self.encoded_body_plus_fragment, write_body_bytes)
  67. } else {
  68. decode_without_base64(self.encoded_body_plus_fragment, write_body_bytes)
  69. .map_err(forgiving_base64::DecodeError::WriteError)
  70. }
  71. }
  72. /// Return the decoded body, and the URL’s fragment identifier if it has one.
  73. pub fn decode_to_vec(
  74. &self,
  75. ) -> Result<(Vec<u8>, Option<FragmentIdentifier<'a>>), forgiving_base64::InvalidBase64> {
  76. let mut body = Vec::new();
  77. let fragment = self.decode(|bytes| Ok(body.extend_from_slice(bytes)))?;
  78. Ok((body, fragment))
  79. }
  80. }
  81. /// The URL’s fragment identifier (after `#`)
  82. pub struct FragmentIdentifier<'a>(&'a str);
  83. impl<'a> FragmentIdentifier<'a> {
  84. /// Like in a parsed URL
  85. pub fn to_percent_encoded(&self) -> String {
  86. let mut string = String::new();
  87. for byte in self.0.bytes() {
  88. match byte {
  89. // Ignore ASCII tabs or newlines like the URL parser would
  90. b'\t' | b'\n' | b'\r' => continue,
  91. // Fragment encode set
  92. b'\0'...b' ' | b'"' | b'<' | b'>' | b'`' | b'\x7F'...b'\xFF' => {
  93. percent_encode(byte, &mut string)
  94. }
  95. // Printable ASCII
  96. _ => string.push(byte as char),
  97. }
  98. }
  99. string
  100. }
  101. }
  102. /// Similar to <https://url.spec.whatwg.org/#concept-basic-url-parser>
  103. /// followed by <https://url.spec.whatwg.org/#concept-url-serializer>
  104. ///
  105. /// * `None`: not a data URL.
  106. ///
  107. /// * `Some(s)`: sort of the result of serialization, except:
  108. ///
  109. /// - `data:` prefix removed
  110. /// - The fragment is included
  111. /// - Other components are **not** UTF-8 percent-encoded
  112. /// - ASCII tabs and newlines in the middle are **not** removed
  113. fn pretend_parse_data_url(input: &str) -> Option<&str> {
  114. // Trim C0 control or space
  115. let left_trimmed = input.trim_start_matches(|ch| ch <= ' ');
  116. let mut bytes = left_trimmed.bytes();
  117. {
  118. // Ignore ASCII tabs or newlines like the URL parser would
  119. let mut iter = bytes
  120. .by_ref()
  121. .filter(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r'));
  122. require!(iter.next()?.to_ascii_lowercase() == b'd');
  123. require!(iter.next()?.to_ascii_lowercase() == b'a');
  124. require!(iter.next()?.to_ascii_lowercase() == b't');
  125. require!(iter.next()?.to_ascii_lowercase() == b'a');
  126. require!(iter.next()? == b':');
  127. }
  128. let bytes_consumed = left_trimmed.len() - bytes.len();
  129. let after_colon = &left_trimmed[bytes_consumed..];
  130. // Trim C0 control or space
  131. Some(after_colon.trim_end_matches(|ch| ch <= ' '))
  132. }
  133. fn find_comma_before_fragment(after_colon: &str) -> Option<(&str, &str)> {
  134. for (i, byte) in after_colon.bytes().enumerate() {
  135. if byte == b',' {
  136. return Some((&after_colon[..i], &after_colon[i + 1..]));
  137. }
  138. if byte == b'#' {
  139. break;
  140. }
  141. }
  142. None
  143. }
  144. fn parse_header(from_colon_to_comma: &str) -> (mime::Mime, bool) {
  145. // "Strip leading and trailing ASCII whitespace"
  146. // \t, \n, and \r would have been filtered by the URL parser
  147. // \f percent-encoded by the URL parser
  148. // space is the only remaining ASCII whitespace
  149. let trimmed = from_colon_to_comma.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r'));
  150. let without_base64_suffix = remove_base64_suffix(trimmed);
  151. let base64 = without_base64_suffix.is_some();
  152. let mime_type = without_base64_suffix.unwrap_or(trimmed);
  153. let mut string = String::new();
  154. if mime_type.starts_with(';') {
  155. string.push_str("text/plain")
  156. }
  157. let mut in_query = false;
  158. for byte in mime_type.bytes() {
  159. match byte {
  160. // Ignore ASCII tabs or newlines like the URL parser would
  161. b'\t' | b'\n' | b'\r' => continue,
  162. // C0 encode set
  163. b'\0'...b'\x1F' | b'\x7F'...b'\xFF' => percent_encode(byte, &mut string),
  164. // Bytes other than the C0 encode set that are percent-encoded
  165. // by the URL parser in the query state.
  166. // '#' is also in that list but cannot occur here
  167. // since it indicates the start of the URL’s fragment.
  168. b' ' | b'"' | b'<' | b'>' if in_query => percent_encode(byte, &mut string),
  169. b'?' => {
  170. in_query = true;
  171. string.push('?')
  172. }
  173. // Printable ASCII
  174. _ => string.push(byte as char),
  175. }
  176. }
  177. // FIXME: does Mime::from_str match the MIME Sniffing Standard’s parsing algorithm?
  178. // <https://mimesniff.spec.whatwg.org/#parse-a-mime-type>
  179. let mime_type = string.parse().unwrap_or_else(|_| mime::Mime {
  180. type_: String::from("text"),
  181. subtype: String::from("plain"),
  182. parameters: vec![(String::from("charset"), String::from("US-ASCII"))],
  183. });
  184. (mime_type, base64)
  185. }
  186. /// None: no base64 suffix
  187. fn remove_base64_suffix(s: &str) -> Option<&str> {
  188. let mut bytes = s.bytes();
  189. {
  190. // Ignore ASCII tabs or newlines like the URL parser would
  191. let iter = bytes
  192. .by_ref()
  193. .filter(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r'));
  194. // Search from the end
  195. let mut iter = iter.rev();
  196. require!(iter.next()? == b'4');
  197. require!(iter.next()? == b'6');
  198. require!(iter.next()?.to_ascii_lowercase() == b'e');
  199. require!(iter.next()?.to_ascii_lowercase() == b's');
  200. require!(iter.next()?.to_ascii_lowercase() == b'a');
  201. require!(iter.next()?.to_ascii_lowercase() == b'b');
  202. require!(iter.skip_while(|&byte| byte == b' ').next()? == b';');
  203. }
  204. Some(&s[..bytes.len()])
  205. }
  206. fn percent_encode(byte: u8, string: &mut String) {
  207. const HEX_UPPER: [u8; 16] = *b"0123456789ABCDEF";
  208. string.push('%');
  209. string.push(HEX_UPPER[(byte >> 4) as usize] as char);
  210. string.push(HEX_UPPER[(byte & 0x0f) as usize] as char);
  211. }
  212. /// This is <https://url.spec.whatwg.org/#string-percent-decode> while also:
  213. ///
  214. /// * Ignoring ASCII tab or newlines
  215. /// * Stopping at the first '#' (which indicates the start of the fragment)
  216. ///
  217. /// Anything that would have been UTF-8 percent-encoded by the URL parser
  218. /// would be percent-decoded here.
  219. /// We skip that round-trip and pass it through unchanged.
  220. fn decode_without_base64<F, E>(
  221. encoded_body_plus_fragment: &str,
  222. mut write_bytes: F,
  223. ) -> Result<Option<FragmentIdentifier>, E>
  224. where
  225. F: FnMut(&[u8]) -> Result<(), E>,
  226. {
  227. let bytes = encoded_body_plus_fragment.as_bytes();
  228. let mut slice_start = 0;
  229. for (i, &byte) in bytes.iter().enumerate() {
  230. // We only need to look for 5 different "special" byte values.
  231. // For everything else we make slices as large as possible, borrowing the input,
  232. // in order to make fewer write_all() calls.
  233. if matches!(byte, b'%' | b'#' | b'\t' | b'\n' | b'\r') {
  234. // Write everything (if anything) "non-special" we’ve accumulated
  235. // before this special byte
  236. if i > slice_start {
  237. write_bytes(&bytes[slice_start..i])?;
  238. }
  239. // Then deal with the special byte.
  240. match byte {
  241. b'%' => {
  242. let l = bytes.get(i + 2).and_then(|&b| (b as char).to_digit(16));
  243. let h = bytes.get(i + 1).and_then(|&b| (b as char).to_digit(16));
  244. if let (Some(h), Some(l)) = (h, l) {
  245. // '%' followed by two ASCII hex digits
  246. let one_byte = h as u8 * 0x10 + l as u8;
  247. write_bytes(&[one_byte])?;
  248. slice_start = i + 3;
  249. } else {
  250. // Do nothing. Leave slice_start unchanged.
  251. // The % sign will be part of the next slice.
  252. }
  253. }
  254. b'#' => {
  255. let fragment_start = i + 1;
  256. let fragment = &encoded_body_plus_fragment[fragment_start..];
  257. return Ok(Some(FragmentIdentifier(fragment)));
  258. }
  259. // Ignore over '\t' | '\n' | '\r'
  260. _ => slice_start = i + 1,
  261. }
  262. }
  263. }
  264. write_bytes(&bytes[slice_start..])?;
  265. Ok(None)
  266. }
  267. /// `decode_without_base64()` composed with
  268. /// <https://infra.spec.whatwg.org/#isomorphic-decode> composed with
  269. /// <https://infra.spec.whatwg.org/#forgiving-base64-decode>.
  270. fn decode_with_base64<F, E>(
  271. encoded_body_plus_fragment: &str,
  272. write_bytes: F,
  273. ) -> Result<Option<FragmentIdentifier>, forgiving_base64::DecodeError<E>>
  274. where
  275. F: FnMut(&[u8]) -> Result<(), E>,
  276. {
  277. let mut decoder = forgiving_base64::Decoder::new(write_bytes);
  278. let fragment = decode_without_base64(encoded_body_plus_fragment, |bytes| decoder.feed(bytes))?;
  279. decoder.finish()?;
  280. Ok(fragment)
  281. }