lib.rs 11 KB

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