lib.rs 11 KB

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