asset.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{path::SafePathBuf, scope, webview::UriSchemeProtocolHandler};
  5. use http::{header::*, status::StatusCode, Request, Response};
  6. use http_range::HttpRange;
  7. use std::{borrow::Cow, io::SeekFrom};
  8. use tauri_utils::mime_type::MimeType;
  9. use tokio::fs::File;
  10. use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
  11. pub fn get(scope: scope::fs::Scope, window_origin: String) -> UriSchemeProtocolHandler {
  12. Box::new(
  13. move |request, responder| match get_response(request, &scope, &window_origin) {
  14. Ok(response) => responder.respond(response),
  15. Err(e) => responder.respond(
  16. http::Response::builder()
  17. .status(http::StatusCode::INTERNAL_SERVER_ERROR)
  18. .header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
  19. .header("Access-Control-Allow-Origin", &window_origin)
  20. .body(e.to_string().as_bytes().to_vec())
  21. .unwrap(),
  22. ),
  23. },
  24. )
  25. }
  26. fn get_response(
  27. request: Request<Vec<u8>>,
  28. scope: &scope::fs::Scope,
  29. window_origin: &str,
  30. ) -> Result<Response<Cow<'static, [u8]>>, Box<dyn std::error::Error>> {
  31. // skip leading `/`
  32. let path = percent_encoding::percent_decode(request.uri().path()[1..].as_bytes())
  33. .decode_utf8_lossy()
  34. .to_string();
  35. let mut resp = Response::builder().header("Access-Control-Allow-Origin", window_origin);
  36. if let Err(e) = SafePathBuf::new(path.clone().into()) {
  37. log::error!("asset protocol path \"{}\" is not valid: {}", path, e);
  38. return resp.status(403).body(Vec::new().into()).map_err(Into::into);
  39. }
  40. if !scope.is_allowed(&path) {
  41. log::error!("asset protocol not configured to allow the path: {}", path);
  42. return resp.status(403).body(Vec::new().into()).map_err(Into::into);
  43. }
  44. let (mut file, len, mime_type, read_bytes) = crate::async_runtime::safe_block_on(async move {
  45. let mut file = File::open(&path).await?;
  46. // get file length
  47. let len = {
  48. let old_pos = file.stream_position().await?;
  49. let len = file.seek(SeekFrom::End(0)).await?;
  50. file.seek(SeekFrom::Start(old_pos)).await?;
  51. len
  52. };
  53. // get file mime type
  54. let (mime_type, read_bytes) = {
  55. let nbytes = len.min(8192);
  56. let mut magic_buf = Vec::with_capacity(nbytes as usize);
  57. let old_pos = file.stream_position().await?;
  58. (&mut file).take(nbytes).read_to_end(&mut magic_buf).await?;
  59. file.seek(SeekFrom::Start(old_pos)).await?;
  60. (
  61. MimeType::parse(&magic_buf, &path),
  62. // return the `magic_bytes` if we read the whole file
  63. // to avoid reading it again later if this is not a range request
  64. if len < 8192 { Some(magic_buf) } else { None },
  65. )
  66. };
  67. Ok::<(File, u64, String, Option<Vec<u8>>), anyhow::Error>((file, len, mime_type, read_bytes))
  68. })?;
  69. resp = resp.header(CONTENT_TYPE, &mime_type);
  70. // handle 206 (partial range) http requests
  71. let response = if let Some(range_header) = request
  72. .headers()
  73. .get("range")
  74. .and_then(|r| r.to_str().map(|r| r.to_string()).ok())
  75. {
  76. resp = resp.header(ACCEPT_RANGES, "bytes");
  77. let not_satisfiable = || {
  78. Response::builder()
  79. .status(StatusCode::RANGE_NOT_SATISFIABLE)
  80. .header(CONTENT_RANGE, format!("bytes */{len}"))
  81. .body(vec![].into())
  82. .map_err(Into::into)
  83. };
  84. // parse range header
  85. let ranges = if let Ok(ranges) = HttpRange::parse(&range_header, len) {
  86. ranges
  87. .iter()
  88. // map the output to spec range <start-end>, example: 0-499
  89. .map(|r| (r.start, r.start + r.length - 1))
  90. .collect::<Vec<_>>()
  91. } else {
  92. return not_satisfiable();
  93. };
  94. /// The Maximum bytes we send in one range
  95. const MAX_LEN: u64 = 1000 * 1024;
  96. // single-part range header
  97. if ranges.len() == 1 {
  98. let &(start, mut end) = ranges.first().unwrap();
  99. // check if a range is not satisfiable
  100. //
  101. // this should be already taken care of by the range parsing library
  102. // but checking here again for extra assurance
  103. if start >= len || end >= len || end < start {
  104. return not_satisfiable();
  105. }
  106. // adjust end byte for MAX_LEN
  107. end = start + (end - start).min(len - start).min(MAX_LEN - 1);
  108. // calculate number of bytes needed to be read
  109. let nbytes = end + 1 - start;
  110. let buf = crate::async_runtime::safe_block_on(async move {
  111. let mut buf = Vec::with_capacity(nbytes as usize);
  112. file.seek(SeekFrom::Start(start)).await?;
  113. file.take(nbytes).read_to_end(&mut buf).await?;
  114. Ok::<Vec<u8>, anyhow::Error>(buf)
  115. })?;
  116. resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
  117. resp = resp.header(CONTENT_LENGTH, end + 1 - start);
  118. resp = resp.status(StatusCode::PARTIAL_CONTENT);
  119. resp.body(buf.into())
  120. } else {
  121. let ranges = ranges
  122. .iter()
  123. .filter_map(|&(start, mut end)| {
  124. // filter out unsatisfiable ranges
  125. //
  126. // this should be already taken care of by the range parsing library
  127. // but checking here again for extra assurance
  128. if start >= len || end >= len || end < start {
  129. None
  130. } else {
  131. // adjust end byte for MAX_LEN
  132. end = start + (end - start).min(len - start).min(MAX_LEN - 1);
  133. Some((start, end))
  134. }
  135. })
  136. .collect::<Vec<_>>();
  137. let boundary = random_boundary();
  138. let boundary_sep = format!("\r\n--{boundary}\r\n");
  139. let boundary_closer = format!("\r\n--{boundary}\r\n");
  140. resp = resp.header(
  141. CONTENT_TYPE,
  142. format!("multipart/byteranges; boundary={boundary}"),
  143. );
  144. let buf = crate::async_runtime::safe_block_on(async move {
  145. // multi-part range header
  146. let mut buf = Vec::new();
  147. for (end, start) in ranges {
  148. // a new range is being written, write the range boundary
  149. buf.write_all(boundary_sep.as_bytes()).await?;
  150. // write the needed headers `Content-Type` and `Content-Range`
  151. buf
  152. .write_all(format!("{CONTENT_TYPE}: {mime_type}\r\n").as_bytes())
  153. .await?;
  154. buf
  155. .write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())
  156. .await?;
  157. // write the separator to indicate the start of the range body
  158. buf.write_all("\r\n".as_bytes()).await?;
  159. // calculate number of bytes needed to be read
  160. let nbytes = end + 1 - start;
  161. let mut local_buf = Vec::with_capacity(nbytes as usize);
  162. file.seek(SeekFrom::Start(start)).await?;
  163. (&mut file).take(nbytes).read_to_end(&mut local_buf).await?;
  164. buf.extend_from_slice(&local_buf);
  165. }
  166. // all ranges have been written, write the closing boundary
  167. buf.write_all(boundary_closer.as_bytes()).await?;
  168. Ok::<Vec<u8>, anyhow::Error>(buf)
  169. })?;
  170. resp.body(buf.into())
  171. }
  172. } else {
  173. // avoid reading the file if we already read it
  174. // as part of mime type detection
  175. let buf = if let Some(b) = read_bytes {
  176. b
  177. } else {
  178. crate::async_runtime::safe_block_on(async move {
  179. let mut local_buf = Vec::with_capacity(len as usize);
  180. file.read_to_end(&mut local_buf).await?;
  181. Ok::<Vec<u8>, anyhow::Error>(local_buf)
  182. })?
  183. };
  184. resp = resp.header(CONTENT_LENGTH, len);
  185. resp.body(buf.into())
  186. };
  187. response.map_err(Into::into)
  188. }
  189. fn random_boundary() -> String {
  190. let mut x = [0_u8; 30];
  191. getrandom::getrandom(&mut x).expect("failed to get random bytes");
  192. (x[..])
  193. .iter()
  194. .map(|&x| format!("{x:x}"))
  195. .fold(String::new(), |mut a, x| {
  196. a.push_str(x.as_str());
  197. a
  198. })
  199. }