lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 crate::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| {
  78. body.extend_from_slice(bytes);
  79. Ok(())
  80. })?;
  81. Ok((body, fragment))
  82. }
  83. }
  84. /// The URL’s fragment identifier (after `#`)
  85. pub struct FragmentIdentifier<'a>(&'a str);
  86. impl<'a> FragmentIdentifier<'a> {
  87. /// Like in a parsed URL
  88. pub fn to_percent_encoded(&self) -> String {
  89. let mut string = String::new();
  90. for byte in self.0.bytes() {
  91. match byte {
  92. // Ignore ASCII tabs or newlines like the URL parser would
  93. b'\t' | b'\n' | b'\r' => continue,
  94. // https://url.spec.whatwg.org/#fragment-percent-encode-set
  95. b'\0'..=b' ' | b'"' | b'<' | b'>' | b'`' | b'\x7F'..=b'\xFF' => {
  96. percent_encode(byte, &mut string)
  97. }
  98. // Printable ASCII
  99. _ => string.push(byte as char),
  100. }
  101. }
  102. string
  103. }
  104. }
  105. /// Similar to <https://url.spec.whatwg.org/#concept-basic-url-parser>
  106. /// followed by <https://url.spec.whatwg.org/#concept-url-serializer>
  107. ///
  108. /// * `None`: not a data URL.
  109. ///
  110. /// * `Some(s)`: sort of the result of serialization, except:
  111. ///
  112. /// - `data:` prefix removed
  113. /// - The fragment is included
  114. /// - Other components are **not** UTF-8 percent-encoded
  115. /// - ASCII tabs and newlines in the middle are **not** removed
  116. fn pretend_parse_data_url(input: &str) -> Option<&str> {
  117. // Trim C0 control or space
  118. let left_trimmed = input.trim_start_matches(|ch| ch <= ' ');
  119. let mut bytes = left_trimmed.bytes();
  120. {
  121. // Ignore ASCII tabs or newlines like the URL parser would
  122. let mut iter = bytes
  123. .by_ref()
  124. .filter(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r'));
  125. require!(iter.next()?.to_ascii_lowercase() == b'd');
  126. require!(iter.next()?.to_ascii_lowercase() == b'a');
  127. require!(iter.next()?.to_ascii_lowercase() == b't');
  128. require!(iter.next()?.to_ascii_lowercase() == b'a');
  129. require!(iter.next()? == b':');
  130. }
  131. let bytes_consumed = left_trimmed.len() - bytes.len();
  132. let after_colon = &left_trimmed[bytes_consumed..];
  133. // Trim C0 control or space
  134. Some(after_colon.trim_end_matches(|ch| ch <= ' '))
  135. }
  136. fn find_comma_before_fragment(after_colon: &str) -> Option<(&str, &str)> {
  137. for (i, byte) in after_colon.bytes().enumerate() {
  138. if byte == b',' {
  139. return Some((&after_colon[..i], &after_colon[i + 1..]));
  140. }
  141. if byte == b'#' {
  142. break;
  143. }
  144. }
  145. None
  146. }
  147. fn parse_header(from_colon_to_comma: &str) -> (mime::Mime, bool) {
  148. // "Strip leading and trailing ASCII whitespace"
  149. // \t, \n, and \r would have been filtered by the URL parser
  150. // \f percent-encoded by the URL parser
  151. // space is the only remaining ASCII whitespace
  152. let trimmed = from_colon_to_comma.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r'));
  153. let without_base64_suffix = remove_base64_suffix(trimmed);
  154. let base64 = without_base64_suffix.is_some();
  155. let mime_type = without_base64_suffix.unwrap_or(trimmed);
  156. let mut string = String::new();
  157. if mime_type.starts_with(';') {
  158. string.push_str("text/plain")
  159. }
  160. let mut in_query = false;
  161. for byte in mime_type.bytes() {
  162. match byte {
  163. // Ignore ASCII tabs or newlines like the URL parser would
  164. b'\t' | b'\n' | b'\r' => continue,
  165. // https://url.spec.whatwg.org/#c0-control-percent-encode-set
  166. b'\0'..=b'\x1F' | b'\x7F'..=b'\xFF' => percent_encode(byte, &mut string),
  167. // Bytes other than the C0 percent-encode set that are percent-encoded
  168. // by the URL parser in the query state.
  169. // '#' is also in that list but cannot occur here
  170. // since it indicates the start of the URL’s fragment.
  171. b' ' | b'"' | b'<' | b'>' if in_query => percent_encode(byte, &mut string),
  172. b'?' => {
  173. in_query = true;
  174. string.push('?')
  175. }
  176. // Printable ASCII
  177. _ => string.push(byte as char),
  178. }
  179. }
  180. // FIXME: does Mime::from_str match the MIME Sniffing Standard’s parsing algorithm?
  181. // <https://mimesniff.spec.whatwg.org/#parse-a-mime-type>
  182. let mime_type = string.parse().unwrap_or_else(|_| mime::Mime {
  183. type_: String::from("text"),
  184. subtype: String::from("plain"),
  185. parameters: vec![(String::from("charset"), String::from("US-ASCII"))],
  186. });
  187. (mime_type, base64)
  188. }
  189. /// None: no base64 suffix
  190. #[allow(clippy::skip_while_next)]
  191. fn remove_base64_suffix(s: &str) -> Option<&str> {
  192. let mut bytes = s.bytes();
  193. {
  194. // Ignore ASCII tabs or newlines like the URL parser would
  195. let iter = bytes
  196. .by_ref()
  197. .filter(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r'));
  198. // Search from the end
  199. let mut iter = iter.rev();
  200. require!(iter.next()? == b'4');
  201. require!(iter.next()? == b'6');
  202. require!(iter.next()?.to_ascii_lowercase() == b'e');
  203. require!(iter.next()?.to_ascii_lowercase() == b's');
  204. require!(iter.next()?.to_ascii_lowercase() == b'a');
  205. require!(iter.next()?.to_ascii_lowercase() == b'b');
  206. require!(iter.skip_while(|&byte| byte == b' ').next()? == b';');
  207. }
  208. Some(&s[..bytes.len()])
  209. }
  210. fn percent_encode(byte: u8, string: &mut String) {
  211. const HEX_UPPER: [u8; 16] = *b"0123456789ABCDEF";
  212. string.push('%');
  213. string.push(HEX_UPPER[(byte >> 4) as usize] as char);
  214. string.push(HEX_UPPER[(byte & 0x0f) as usize] as char);
  215. }
  216. /// This is <https://url.spec.whatwg.org/#string-percent-decode> while also:
  217. ///
  218. /// * Ignoring ASCII tab or newlines
  219. /// * Stopping at the first '#' (which indicates the start of the fragment)
  220. ///
  221. /// Anything that would have been UTF-8 percent-encoded by the URL parser
  222. /// would be percent-decoded here.
  223. /// We skip that round-trip and pass it through unchanged.
  224. fn decode_without_base64<F, E>(
  225. encoded_body_plus_fragment: &str,
  226. mut write_bytes: F,
  227. ) -> Result<Option<FragmentIdentifier<'_>>, E>
  228. where
  229. F: FnMut(&[u8]) -> Result<(), E>,
  230. {
  231. let bytes = encoded_body_plus_fragment.as_bytes();
  232. let mut slice_start = 0;
  233. for (i, &byte) in bytes.iter().enumerate() {
  234. // We only need to look for 5 different "special" byte values.
  235. // For everything else we make slices as large as possible, borrowing the input,
  236. // in order to make fewer write_all() calls.
  237. if matches!(byte, b'%' | b'#' | b'\t' | b'\n' | b'\r') {
  238. // Write everything (if anything) "non-special" we’ve accumulated
  239. // before this special byte
  240. if i > slice_start {
  241. write_bytes(&bytes[slice_start..i])?;
  242. }
  243. // Then deal with the special byte.
  244. match byte {
  245. b'%' => {
  246. let l = bytes.get(i + 2).and_then(|&b| (b as char).to_digit(16));
  247. let h = bytes.get(i + 1).and_then(|&b| (b as char).to_digit(16));
  248. if let (Some(h), Some(l)) = (h, l) {
  249. // '%' followed by two ASCII hex digits
  250. let one_byte = h as u8 * 0x10 + l as u8;
  251. write_bytes(&[one_byte])?;
  252. slice_start = i + 3;
  253. } else {
  254. // Do nothing. Leave slice_start unchanged.
  255. // The % sign will be part of the next slice.
  256. }
  257. }
  258. b'#' => {
  259. let fragment_start = i + 1;
  260. let fragment = &encoded_body_plus_fragment[fragment_start..];
  261. return Ok(Some(FragmentIdentifier(fragment)));
  262. }
  263. // Ignore over '\t' | '\n' | '\r'
  264. _ => slice_start = i + 1,
  265. }
  266. }
  267. }
  268. write_bytes(&bytes[slice_start..])?;
  269. Ok(None)
  270. }
  271. /// `decode_without_base64()` composed with
  272. /// <https://infra.spec.whatwg.org/#isomorphic-decode> composed with
  273. /// <https://infra.spec.whatwg.org/#forgiving-base64-decode>.
  274. fn decode_with_base64<F, E>(
  275. encoded_body_plus_fragment: &str,
  276. write_bytes: F,
  277. ) -> Result<Option<FragmentIdentifier<'_>>, forgiving_base64::DecodeError<E>>
  278. where
  279. F: FnMut(&[u8]) -> Result<(), E>,
  280. {
  281. let mut decoder = forgiving_base64::Decoder::new(write_bytes);
  282. let fragment = decode_without_base64(encoded_body_plus_fragment, |bytes| decoder.feed(bytes))?;
  283. decoder.finish()?;
  284. Ok(fragment)
  285. }