2021-11-19 15:04:12 +01:00
|
|
|
use std::{
|
2021-11-22 02:19:09 +01:00
|
|
|
fmt,
|
|
|
|
fs::Metadata,
|
2021-11-19 15:04:12 +01:00
|
|
|
io,
|
|
|
|
ops::{Deref, DerefMut},
|
|
|
|
path::{Path, PathBuf},
|
|
|
|
time::{SystemTime, UNIX_EPOCH},
|
|
|
|
};
|
2019-03-06 07:10:08 +01:00
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
use std::os::unix::fs::MetadataExt;
|
|
|
|
|
2021-11-19 15:04:12 +01:00
|
|
|
use actix_http::body::AnyBody;
|
|
|
|
use actix_service::{Service, ServiceFactory};
|
2020-09-21 00:18:25 +02:00
|
|
|
use actix_web::{
|
2021-11-19 15:04:12 +01:00
|
|
|
dev::{
|
|
|
|
AppService, BodyEncoding, HttpServiceFactory, ResourceDef, ServiceRequest,
|
|
|
|
ServiceResponse, SizedStream,
|
|
|
|
},
|
2020-09-21 00:18:25 +02:00
|
|
|
http::{
|
|
|
|
header::{
|
2021-02-12 00:03:17 +01:00
|
|
|
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
2020-09-21 00:18:25 +02:00
|
|
|
},
|
|
|
|
ContentEncoding, StatusCode,
|
|
|
|
},
|
2021-04-19 00:34:51 +02:00
|
|
|
Error, HttpMessage, HttpRequest, HttpResponse, Responder,
|
2019-03-25 21:43:02 +01:00
|
|
|
};
|
2020-09-21 00:18:25 +02:00
|
|
|
use bitflags::bitflags;
|
2021-11-22 02:19:09 +01:00
|
|
|
use futures_core::future::LocalBoxFuture;
|
2020-09-21 00:18:25 +02:00
|
|
|
use mime_guess::from_path;
|
2019-03-06 07:10:08 +01:00
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
use crate::{encoding::equiv_utf8_text, range::HttpRange};
|
2019-03-06 07:10:08 +01:00
|
|
|
|
2019-03-25 21:02:37 +01:00
|
|
|
bitflags! {
|
2019-07-20 07:43:49 +02:00
|
|
|
pub(crate) struct Flags: u8 {
|
2020-10-06 22:56:28 +02:00
|
|
|
const ETAG = 0b0000_0001;
|
|
|
|
const LAST_MD = 0b0000_0010;
|
2019-07-20 07:43:49 +02:00
|
|
|
const CONTENT_DISPOSITION = 0b0000_0100;
|
2020-10-06 22:56:28 +02:00
|
|
|
const PREFER_UTF8 = 0b0000_1000;
|
2019-03-25 21:02:37 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Flags {
|
|
|
|
fn default() -> Self {
|
2020-10-06 22:56:28 +02:00
|
|
|
Flags::from_bits_truncate(0b0000_0111)
|
2019-03-25 21:02:37 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
/// A file with an associated name.
|
2021-04-19 00:34:51 +02:00
|
|
|
///
|
|
|
|
/// `NamedFile` can be registered as services:
|
|
|
|
/// ```
|
|
|
|
/// use actix_web::App;
|
|
|
|
/// use actix_files::NamedFile;
|
|
|
|
///
|
2021-11-22 02:19:09 +01:00
|
|
|
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
/// let file = NamedFile::open_async("./static/index.html").await?;
|
|
|
|
/// let app = App::new().service(file);
|
2021-04-19 00:34:51 +02:00
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// They can also be returned from handlers:
|
|
|
|
/// ```
|
|
|
|
/// use actix_web::{Responder, get};
|
|
|
|
/// use actix_files::NamedFile;
|
|
|
|
///
|
|
|
|
/// #[get("/")]
|
|
|
|
/// async fn index() -> impl Responder {
|
2021-11-22 02:19:09 +01:00
|
|
|
/// NamedFile::open_async("./static/index.html").await
|
2021-04-19 00:34:51 +02:00
|
|
|
/// }
|
|
|
|
/// ```
|
2019-03-25 21:02:37 +01:00
|
|
|
pub struct NamedFile {
|
2019-03-06 07:10:08 +01:00
|
|
|
path: PathBuf,
|
|
|
|
file: File,
|
2019-07-20 07:43:49 +02:00
|
|
|
modified: Option<SystemTime>,
|
|
|
|
pub(crate) md: Metadata,
|
|
|
|
pub(crate) flags: Flags,
|
|
|
|
pub(crate) status_code: StatusCode,
|
2019-03-06 07:10:08 +01:00
|
|
|
pub(crate) content_type: mime::Mime,
|
|
|
|
pub(crate) content_disposition: header::ContentDisposition,
|
2019-04-01 03:19:18 +02:00
|
|
|
pub(crate) encoding: Option<ContentEncoding>,
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
impl fmt::Debug for NamedFile {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
f.debug_struct("NamedFile")
|
|
|
|
.field("path", &self.path)
|
|
|
|
.field(
|
|
|
|
"file",
|
|
|
|
#[cfg(feature = "experimental-io-uring")]
|
|
|
|
{
|
|
|
|
&"tokio_uring::File"
|
|
|
|
},
|
|
|
|
#[cfg(not(feature = "experimental-io-uring"))]
|
|
|
|
{
|
|
|
|
&self.file
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.field("modified", &self.modified)
|
|
|
|
.field("md", &self.md)
|
|
|
|
.field("flags", &self.flags)
|
|
|
|
.field("status_code", &self.status_code)
|
|
|
|
.field("content_type", &self.content_type)
|
|
|
|
.field("content_disposition", &self.content_disposition)
|
|
|
|
.field("encoding", &self.encoding)
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(feature = "experimental-io-uring"))]
|
|
|
|
pub(crate) use std::fs::File;
|
|
|
|
#[cfg(feature = "experimental-io-uring")]
|
|
|
|
pub(crate) use tokio_uring::fs::File;
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
impl NamedFile {
|
|
|
|
/// Creates an instance from a previously opened file.
|
|
|
|
///
|
|
|
|
/// The given `path` need not exist and is only used to determine the `ContentType` and
|
|
|
|
/// `ContentDisposition` headers.
|
|
|
|
///
|
|
|
|
/// # Examples
|
2021-11-22 02:19:09 +01:00
|
|
|
/// ```ignore
|
2019-03-25 01:00:59 +01:00
|
|
|
/// use actix_files::NamedFile;
|
2019-03-06 07:10:08 +01:00
|
|
|
/// use std::io::{self, Write};
|
|
|
|
/// use std::env;
|
|
|
|
/// use std::fs::File;
|
|
|
|
///
|
|
|
|
/// fn main() -> io::Result<()> {
|
|
|
|
/// let mut file = File::create("foo.txt")?;
|
|
|
|
/// file.write_all(b"Hello, world!")?;
|
|
|
|
/// let named_file = NamedFile::from_file(file, "bar.txt")?;
|
2019-05-05 04:51:00 +02:00
|
|
|
/// # std::fs::remove_file("foo.txt");
|
2019-03-06 07:10:08 +01:00
|
|
|
/// Ok(())
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn from_file<P: AsRef<Path>>(file: File, path: P) -> io::Result<NamedFile> {
|
|
|
|
let path = path.as_ref().to_path_buf();
|
|
|
|
|
|
|
|
// Get the name of the file and use it to construct default Content-Type
|
|
|
|
// and Content-Disposition values
|
|
|
|
let (content_type, content_disposition) = {
|
|
|
|
let filename = match path.file_name() {
|
|
|
|
Some(name) => name.to_string_lossy(),
|
|
|
|
None => {
|
|
|
|
return Err(io::Error::new(
|
|
|
|
io::ErrorKind::InvalidInput,
|
|
|
|
"Provided path has no filename",
|
|
|
|
));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-08-11 22:43:29 +02:00
|
|
|
let ct = from_path(&path).first_or_octet_stream();
|
2020-10-06 22:56:28 +02:00
|
|
|
|
2020-07-22 01:28:33 +02:00
|
|
|
let disposition = match ct.type_() {
|
2019-03-25 21:02:37 +01:00
|
|
|
mime::IMAGE | mime::TEXT | mime::VIDEO => DispositionType::Inline,
|
2021-06-16 21:33:22 +02:00
|
|
|
mime::APPLICATION => match ct.subtype() {
|
|
|
|
mime::JAVASCRIPT | mime::JSON => DispositionType::Inline,
|
|
|
|
name if name == "wasm" => DispositionType::Inline,
|
|
|
|
_ => DispositionType::Attachment,
|
|
|
|
},
|
2019-03-25 21:02:37 +01:00
|
|
|
_ => DispositionType::Attachment,
|
|
|
|
};
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-06 15:08:37 +01:00
|
|
|
let mut parameters =
|
|
|
|
vec![DispositionParam::Filename(String::from(filename.as_ref()))];
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-06 15:08:37 +01:00
|
|
|
if !filename.is_ascii() {
|
|
|
|
parameters.push(DispositionParam::FilenameExt(ExtendedValue {
|
|
|
|
charset: Charset::Ext(String::from("UTF-8")),
|
|
|
|
language_tag: None,
|
|
|
|
value: filename.into_owned().into_bytes(),
|
|
|
|
}))
|
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
let cd = ContentDisposition {
|
2020-07-22 01:28:33 +02:00
|
|
|
disposition,
|
|
|
|
parameters,
|
2019-03-06 07:10:08 +01:00
|
|
|
};
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
(ct, cd)
|
|
|
|
};
|
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
let md = {
|
|
|
|
#[cfg(not(feature = "experimental-io-uring"))]
|
|
|
|
{
|
|
|
|
file.metadata()?
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "experimental-io-uring")]
|
|
|
|
{
|
|
|
|
use std::os::unix::prelude::{AsRawFd, FromRawFd};
|
|
|
|
|
|
|
|
let fd = file.as_raw_fd();
|
|
|
|
|
|
|
|
// SAFETY: fd is borrowed and lives longer than the unsafe block
|
|
|
|
unsafe {
|
|
|
|
let file = std::fs::File::from_raw_fd(fd);
|
|
|
|
let md = file.metadata();
|
|
|
|
// SAFETY: forget the fd before exiting block in success or error case but don't
|
|
|
|
// run destructor (that would close file handle)
|
|
|
|
std::mem::forget(file);
|
|
|
|
md?
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
let modified = md.modified().ok();
|
|
|
|
let encoding = None;
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
Ok(NamedFile {
|
|
|
|
path,
|
|
|
|
file,
|
|
|
|
content_type,
|
|
|
|
content_disposition,
|
|
|
|
md,
|
|
|
|
modified,
|
|
|
|
encoding,
|
|
|
|
status_code: StatusCode::OK,
|
2019-03-25 21:02:37 +01:00
|
|
|
flags: Flags::default(),
|
2019-03-06 07:10:08 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
#[cfg(not(feature = "experimental-io-uring"))]
|
2019-03-25 21:02:37 +01:00
|
|
|
/// Attempts to open a file in read-only mode.
|
2019-03-06 07:10:08 +01:00
|
|
|
///
|
|
|
|
/// # Examples
|
2021-03-25 09:45:52 +01:00
|
|
|
/// ```
|
2019-03-25 21:02:37 +01:00
|
|
|
/// use actix_files::NamedFile;
|
|
|
|
/// let file = NamedFile::open("foo.txt");
|
2019-03-06 07:10:08 +01:00
|
|
|
/// ```
|
2019-03-25 21:02:37 +01:00
|
|
|
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> {
|
2021-11-22 02:19:09 +01:00
|
|
|
let file = File::open(&path)?;
|
|
|
|
Self::from_file(file, path)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Attempts to open a file asynchronously in read-only mode.
|
|
|
|
///
|
|
|
|
/// When the `experimental-io-uring` crate feature is enabled, this will be async.
|
|
|
|
/// Otherwise, it will be just like [`open`][Self::open].
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// use actix_files::NamedFile;
|
|
|
|
/// # async fn open() {
|
|
|
|
/// let file = NamedFile::open_async("foo.txt").await.unwrap();
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
pub async fn open_async<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> {
|
|
|
|
let file = {
|
|
|
|
#[cfg(not(feature = "experimental-io-uring"))]
|
|
|
|
{
|
|
|
|
File::open(&path)?
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "experimental-io-uring")]
|
|
|
|
{
|
|
|
|
File::open(&path).await?
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Self::from_file(file, path)
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns reference to the underlying `File` object.
|
|
|
|
#[inline]
|
|
|
|
pub fn file(&self) -> &File {
|
|
|
|
&self.file
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieve the path of this file.
|
|
|
|
///
|
|
|
|
/// # Examples
|
2021-03-25 09:45:52 +01:00
|
|
|
/// ```
|
2019-03-06 07:10:08 +01:00
|
|
|
/// # use std::io;
|
2019-03-25 01:00:59 +01:00
|
|
|
/// use actix_files::NamedFile;
|
2019-03-06 07:10:08 +01:00
|
|
|
///
|
2021-11-22 02:19:09 +01:00
|
|
|
/// # async fn path() -> io::Result<()> {
|
|
|
|
/// let file = NamedFile::open_async("test.txt").await?;
|
2019-03-06 07:10:08 +01:00
|
|
|
/// assert_eq!(file.path().as_os_str(), "foo.txt");
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn path(&self) -> &Path {
|
|
|
|
self.path.as_path()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set response **Status Code**
|
|
|
|
pub fn set_status_code(mut self, status: StatusCode) -> Self {
|
|
|
|
self.status_code = status;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the MIME Content-Type for serving this file. By default
|
|
|
|
/// the Content-Type is inferred from the filename extension.
|
|
|
|
#[inline]
|
|
|
|
pub fn set_content_type(mut self, mime_type: mime::Mime) -> Self {
|
|
|
|
self.content_type = mime_type;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the Content-Disposition for serving this file. This allows
|
|
|
|
/// changing the inline/attachment disposition as well as the filename
|
2021-06-16 21:33:22 +02:00
|
|
|
/// sent to the peer.
|
|
|
|
///
|
|
|
|
/// By default the disposition is `inline` for `text/*`, `image/*`, `video/*` and
|
|
|
|
/// `application/{javascript, json, wasm}` mime types, and `attachment` otherwise,
|
|
|
|
/// and the filename is taken from the path provided in the `open` method
|
2019-07-20 07:43:49 +02:00
|
|
|
/// after converting it to UTF-8 using.
|
2020-11-11 00:54:38 +01:00
|
|
|
/// [`std::ffi::OsStr::to_string_lossy`]
|
2019-03-06 07:10:08 +01:00
|
|
|
#[inline]
|
|
|
|
pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
|
|
|
|
self.content_disposition = cd;
|
2019-07-20 07:43:49 +02:00
|
|
|
self.flags.insert(Flags::CONTENT_DISPOSITION);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Disable `Content-Disposition` header.
|
|
|
|
///
|
|
|
|
/// By default Content-Disposition` header is enabled.
|
|
|
|
#[inline]
|
|
|
|
pub fn disable_content_disposition(mut self) -> Self {
|
|
|
|
self.flags.remove(Flags::CONTENT_DISPOSITION);
|
2019-03-06 07:10:08 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set content encoding for serving this file
|
2021-06-10 16:38:35 +02:00
|
|
|
///
|
|
|
|
/// Must be used with [`actix_web::middleware::Compress`] to take effect.
|
2019-03-06 07:10:08 +01:00
|
|
|
#[inline]
|
|
|
|
pub fn set_content_encoding(mut self, enc: ContentEncoding) -> Self {
|
|
|
|
self.encoding = Some(enc);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
/// Specifies whether to use ETag or not.
|
2019-03-25 21:02:37 +01:00
|
|
|
///
|
2020-10-06 22:56:28 +02:00
|
|
|
/// Default is true.
|
|
|
|
#[inline]
|
2019-03-25 21:02:37 +01:00
|
|
|
pub fn use_etag(mut self, value: bool) -> Self {
|
|
|
|
self.flags.set(Flags::ETAG, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
/// Specifies whether to use Last-Modified or not.
|
2019-03-25 21:02:37 +01:00
|
|
|
///
|
2020-10-06 22:56:28 +02:00
|
|
|
/// Default is true.
|
|
|
|
#[inline]
|
2019-03-25 21:02:37 +01:00
|
|
|
pub fn use_last_modified(mut self, value: bool) -> Self {
|
|
|
|
self.flags.set(Flags::LAST_MD, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
/// Specifies whether text responses should signal a UTF-8 encoding.
|
|
|
|
///
|
|
|
|
/// Default is false (but will default to true in a future version).
|
|
|
|
#[inline]
|
|
|
|
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
|
|
|
self.flags.set(Flags::PREFER_UTF8, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
pub(crate) fn etag(&self) -> Option<header::EntityTag> {
|
|
|
|
// This etag format is similar to Apache's.
|
|
|
|
self.modified.as_ref().map(|mtime| {
|
|
|
|
let ino = {
|
|
|
|
#[cfg(unix)]
|
|
|
|
{
|
|
|
|
self.md.ino()
|
|
|
|
}
|
|
|
|
#[cfg(not(unix))]
|
|
|
|
{
|
|
|
|
0
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let dur = mtime
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.expect("modification time must be after epoch");
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
header::EntityTag::strong(format!(
|
|
|
|
"{:x}:{:x}:{:x}:{:x}",
|
|
|
|
ino,
|
|
|
|
self.md.len(),
|
|
|
|
dur.as_secs(),
|
|
|
|
dur.subsec_nanos()
|
|
|
|
))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn last_modified(&self) -> Option<header::HttpDate> {
|
|
|
|
self.modified.map(|mtime| mtime.into())
|
|
|
|
}
|
|
|
|
|
2020-09-21 00:18:25 +02:00
|
|
|
/// Creates an `HttpResponse` with file as a streaming body.
|
2021-01-08 23:17:19 +01:00
|
|
|
pub fn into_response(self, req: &HttpRequest) -> HttpResponse {
|
2019-03-06 07:10:08 +01:00
|
|
|
if self.status_code != StatusCode::OK {
|
2020-10-06 22:56:28 +02:00
|
|
|
let mut res = HttpResponse::build(self.status_code);
|
|
|
|
|
|
|
|
if self.flags.contains(Flags::PREFER_UTF8) {
|
|
|
|
let ct = equiv_utf8_text(self.content_type.clone());
|
2021-01-15 03:11:10 +01:00
|
|
|
res.insert_header((header::CONTENT_TYPE, ct.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
} else {
|
2021-01-15 03:11:10 +01:00
|
|
|
res.insert_header((header::CONTENT_TYPE, self.content_type.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
if self.flags.contains(Flags::CONTENT_DISPOSITION) {
|
2021-01-15 03:11:10 +01:00
|
|
|
res.insert_header((
|
2020-10-06 22:56:28 +02:00
|
|
|
header::CONTENT_DISPOSITION,
|
|
|
|
self.content_disposition.to_string(),
|
2021-01-15 03:11:10 +01:00
|
|
|
));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-04-04 23:00:56 +02:00
|
|
|
if let Some(current_encoding) = self.encoding {
|
2020-10-06 22:56:28 +02:00
|
|
|
res.encoding(current_encoding);
|
2019-04-04 23:00:56 +02:00
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
let reader = super::chunked::new_chunked_read(self.md.len(), 0, self.file);
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2021-01-08 23:17:19 +01:00
|
|
|
return res.streaming(reader);
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2019-03-25 21:43:02 +01:00
|
|
|
let etag = if self.flags.contains(Flags::ETAG) {
|
|
|
|
self.etag()
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-25 21:02:37 +01:00
|
|
|
let last_modified = if self.flags.contains(Flags::LAST_MD) {
|
2019-03-06 07:10:08 +01:00
|
|
|
self.last_modified()
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
// check preconditions
|
|
|
|
let precondition_failed = if !any_match(etag.as_ref(), req) {
|
|
|
|
true
|
|
|
|
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
|
|
|
(last_modified, req.get_header())
|
|
|
|
{
|
2021-06-26 16:33:43 +02:00
|
|
|
let t1: SystemTime = (*m).into();
|
|
|
|
let t2: SystemTime = (*since).into();
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-05-23 06:21:12 +02:00
|
|
|
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
2021-01-11 19:18:23 +01:00
|
|
|
(Ok(t1), Ok(t2)) => t1.as_secs() > t2.as_secs(),
|
2019-05-23 06:21:12 +02:00
|
|
|
_ => false,
|
|
|
|
}
|
2019-03-06 07:10:08 +01:00
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
|
|
|
|
// check last modified
|
|
|
|
let not_modified = if !none_match(etag.as_ref(), req) {
|
|
|
|
true
|
2020-09-21 00:18:25 +02:00
|
|
|
} else if req.headers().contains_key(header::IF_NONE_MATCH) {
|
2019-03-06 07:10:08 +01:00
|
|
|
false
|
|
|
|
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
|
|
|
(last_modified, req.get_header())
|
|
|
|
{
|
2021-06-26 16:33:43 +02:00
|
|
|
let t1: SystemTime = (*m).into();
|
|
|
|
let t2: SystemTime = (*since).into();
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-05-23 06:21:12 +02:00
|
|
|
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
2021-01-11 19:18:23 +01:00
|
|
|
(Ok(t1), Ok(t2)) => t1.as_secs() <= t2.as_secs(),
|
2019-05-23 06:21:12 +02:00
|
|
|
_ => false,
|
|
|
|
}
|
2019-03-06 07:10:08 +01:00
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut resp = HttpResponse::build(self.status_code);
|
2020-10-06 22:56:28 +02:00
|
|
|
|
|
|
|
if self.flags.contains(Flags::PREFER_UTF8) {
|
|
|
|
let ct = equiv_utf8_text(self.content_type.clone());
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((header::CONTENT_TYPE, ct.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
} else {
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((header::CONTENT_TYPE, self.content_type.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if self.flags.contains(Flags::CONTENT_DISPOSITION) {
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((
|
2020-10-06 22:56:28 +02:00
|
|
|
header::CONTENT_DISPOSITION,
|
|
|
|
self.content_disposition.to_string(),
|
2021-01-15 03:11:10 +01:00
|
|
|
));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-03-27 19:29:31 +01:00
|
|
|
// default compressing
|
|
|
|
if let Some(current_encoding) = self.encoding {
|
2019-12-18 04:30:14 +01:00
|
|
|
resp.encoding(current_encoding);
|
2019-03-27 19:29:31 +01:00
|
|
|
}
|
2019-03-06 07:10:08 +01:00
|
|
|
|
2020-10-06 22:56:28 +02:00
|
|
|
if let Some(lm) = last_modified {
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((header::LAST_MODIFIED, lm.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(etag) = etag {
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((header::ETAG, etag.to_string()));
|
2020-10-06 22:56:28 +02:00
|
|
|
}
|
2019-03-06 07:10:08 +01:00
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((header::ACCEPT_RANGES, "bytes"));
|
2019-03-06 07:10:08 +01:00
|
|
|
|
|
|
|
let mut length = self.md.len();
|
|
|
|
let mut offset = 0;
|
|
|
|
|
|
|
|
// check for range header
|
2020-09-21 00:18:25 +02:00
|
|
|
if let Some(ranges) = req.headers().get(header::RANGE) {
|
|
|
|
if let Ok(ranges_header) = ranges.to_str() {
|
|
|
|
if let Ok(ranges) = HttpRange::parse(ranges_header, length) {
|
|
|
|
length = ranges[0].length;
|
|
|
|
offset = ranges[0].start;
|
|
|
|
|
2019-12-18 04:30:14 +01:00
|
|
|
resp.encoding(ContentEncoding::Identity);
|
2021-01-15 03:11:10 +01:00
|
|
|
resp.insert_header((
|
2019-03-06 07:10:08 +01:00
|
|
|
header::CONTENT_RANGE,
|
2021-02-12 00:03:17 +01:00
|
|
|
format!("bytes {}-{}/{}", offset, offset + length - 1, self.md.len()),
|
2021-01-15 03:11:10 +01:00
|
|
|
));
|
2019-03-06 07:10:08 +01:00
|
|
|
} else {
|
2021-02-12 00:03:17 +01:00
|
|
|
resp.insert_header((header::CONTENT_RANGE, format!("bytes */{}", length)));
|
2021-01-08 23:17:19 +01:00
|
|
|
return resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish();
|
2019-03-06 07:10:08 +01:00
|
|
|
};
|
|
|
|
} else {
|
2021-01-08 23:17:19 +01:00
|
|
|
return resp.status(StatusCode::BAD_REQUEST).finish();
|
2019-03-06 07:10:08 +01:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
if precondition_failed {
|
2021-01-08 23:17:19 +01:00
|
|
|
return resp.status(StatusCode::PRECONDITION_FAILED).finish();
|
2019-03-06 07:10:08 +01:00
|
|
|
} else if not_modified {
|
2021-11-19 15:04:12 +01:00
|
|
|
return resp.status(StatusCode::NOT_MODIFIED).body(AnyBody::None);
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
let reader = super::chunked::new_chunked_read(length, offset, self.file);
|
2020-05-17 23:54:42 +02:00
|
|
|
|
2019-06-13 11:27:21 +02:00
|
|
|
if offset != 0 || length != self.md.len() {
|
2020-05-17 23:54:42 +02:00
|
|
|
resp.status(StatusCode::PARTIAL_CONTENT);
|
2019-11-21 06:31:31 +01:00
|
|
|
}
|
2020-05-17 23:54:42 +02:00
|
|
|
|
2021-01-08 23:17:19 +01:00
|
|
|
resp.body(SizedStream::new(length, reader))
|
2019-11-21 06:31:31 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if `req` has no `If-Match` header or one which matches `etag`.
|
|
|
|
fn any_match(etag: Option<&header::EntityTag>, req: &HttpRequest) -> bool {
|
|
|
|
match req.get_header::<header::IfMatch>() {
|
|
|
|
None | Some(header::IfMatch::Any) => true,
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
Some(header::IfMatch::Items(ref items)) => {
|
|
|
|
if let Some(some_etag) = etag {
|
|
|
|
for item in items {
|
|
|
|
if item.strong_eq(some_etag) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if `req` doesn't have an `If-None-Match` header matching `req`.
|
|
|
|
fn none_match(etag: Option<&header::EntityTag>, req: &HttpRequest) -> bool {
|
|
|
|
match req.get_header::<header::IfNoneMatch>() {
|
|
|
|
Some(header::IfNoneMatch::Any) => false,
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
Some(header::IfNoneMatch::Items(ref items)) => {
|
|
|
|
if let Some(some_etag) = etag {
|
|
|
|
for item in items {
|
|
|
|
if item.weak_eq(some_etag) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
true
|
|
|
|
}
|
2020-09-21 00:18:25 +02:00
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
None => true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-22 02:19:09 +01:00
|
|
|
impl Deref for NamedFile {
|
|
|
|
type Target = File;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.file
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for NamedFile {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
&mut self.file
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 06:31:31 +01:00
|
|
|
impl Responder for NamedFile {
|
2021-01-08 23:17:19 +01:00
|
|
|
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
|
|
|
|
self.into_response(req)
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
}
|
2021-04-19 00:34:51 +02:00
|
|
|
|
|
|
|
impl ServiceFactory<ServiceRequest> for NamedFile {
|
|
|
|
type Response = ServiceResponse;
|
|
|
|
type Error = Error;
|
|
|
|
type Config = ();
|
|
|
|
type Service = NamedFileService;
|
2021-11-22 02:19:09 +01:00
|
|
|
type InitError = ();
|
|
|
|
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
2021-04-19 00:34:51 +02:00
|
|
|
|
|
|
|
fn new_service(&self, _: ()) -> Self::Future {
|
2021-11-22 02:19:09 +01:00
|
|
|
let service = NamedFileService {
|
2021-04-19 00:34:51 +02:00
|
|
|
path: self.path.clone(),
|
2021-11-22 02:19:09 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
Box::pin(async move { Ok(service) })
|
2021-04-19 00:34:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct NamedFileService {
|
|
|
|
path: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Service<ServiceRequest> for NamedFileService {
|
|
|
|
type Response = ServiceResponse;
|
|
|
|
type Error = Error;
|
2021-11-22 02:19:09 +01:00
|
|
|
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
2021-04-19 00:34:51 +02:00
|
|
|
|
|
|
|
actix_service::always_ready!();
|
|
|
|
|
|
|
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
|
|
|
let (req, _) = req.into_parts();
|
2021-11-22 02:19:09 +01:00
|
|
|
|
|
|
|
let path = self.path.clone();
|
|
|
|
Box::pin(async move {
|
|
|
|
let file = NamedFile::open_async(path).await?;
|
|
|
|
let res = file.into_response(&req);
|
|
|
|
Ok(ServiceResponse::new(req, res))
|
|
|
|
})
|
2021-04-19 00:34:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HttpServiceFactory for NamedFile {
|
|
|
|
fn register(self, config: &mut AppService) {
|
|
|
|
config.register_service(
|
|
|
|
ResourceDef::root_prefix(self.path.to_string_lossy().as_ref()),
|
|
|
|
None,
|
|
|
|
self,
|
|
|
|
None,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|