Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Partial Content Delivery (+tests) #98

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ pub use static_handler::Cache;

mod requested_path;
mod static_handler;
mod partial_file;
133 changes: 133 additions & 0 deletions src/partial_file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
use std::cmp;
use std::fs::File;
use iron::headers::{ByteRangeSpec, ContentLength, ContentRange, ContentRangeSpec};
use iron::response::{WriteBody, Response};
use iron::modifier::Modifier;
use iron::status::Status;
use std::io::{self, SeekFrom, Seek, Read, Write};
use std::path::Path;

pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}

pub struct PartialFile {
file: File,
range: PartialFileRange,
}

struct PartialContentBody {
pub file: File,
pub offset: u64,
pub len: u64,
}

impl PartialFile {
pub fn new<Range>(file: File, range: Range) -> PartialFile
where Range: Into<PartialFileRange> {
let range = range.into();
PartialFile {
file: file,
range: range,
}
}

/// Panics if the file doesn't exist
pub fn from_path<P: AsRef<Path>, Range>(path: P, range: Range) -> PartialFile

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a specific reason this doesn't return a Result<PartialFile, Std::io::Error>?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason was originally that the file existence was already checked beforehand everytime before this method was called (via metadata). However now that I think of it this is pretty racy: if the file is deleted between the check and the file being delivered (which is unlikely but can still happen), then it will panic.

It would be better to return a Result<_, io::Error> there indeed.

where Range: Into<PartialFileRange> {
let file = File::open(path.as_ref())
.expect(&format!("No such file: {}", path.as_ref().display()));
Self::new(file, range)
}
}

impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}

impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
// in the case no value is in "Range", return
// the whole file instead of panicking
// Note that an empty vec should never happen,
// but we can never be too sure
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}

impl Modifier<Response> for PartialFile {
#[inline]
fn modify(self, res: &mut Response) {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (self.range, file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,

};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
res.headers.set(ContentLength(content_len));
res.headers.set(content_range);
let partial_content = PartialContentBody {
file: self.file,
offset: range.0,
len: content_len,
};
res.status = Some(Status::PartialContent);
res.body = Some(Box::new(partial_content));
} else {
if let Some(file_length) = file_length {
res.headers.set(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
res.status = Some(Status::RangeNotSatisfiable);
}
}
}

impl WriteBody for PartialContentBody {
fn write_body(&mut self, res: &mut Write) -> io::Result<()> {
self.file.seek(SeekFrom::Start(self.offset))?;
let mut limiter = <File as Read>::by_ref(&mut self.file).take(self.len);
io::copy(&mut limiter, res).map(|_| ())
}
}
51 changes: 45 additions & 6 deletions src/static_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ use std::time::Duration;

use iron::prelude::*;
use iron::{Handler, Url, status};
use iron::headers::{AcceptRanges, RangeUnit, Range};
#[cfg(feature = "cache")]
use iron::modifier::Modifier;
use iron::modifiers::Redirect;
use iron::modifiers::{Header, Redirect};
use mount::OriginalUrl;
use requested_path::RequestedPath;
use url;

use partial_file::PartialFile;

/// The static file-serving `Handler`.
///
/// This handler serves files from a single filesystem path, which may be absolute or relative.
Expand Down Expand Up @@ -76,7 +79,17 @@ impl Static {
#[cfg(feature = "cache")]
fn try_cache<P: AsRef<Path>>(&self, req: &mut Request, path: P) -> IronResult<Response> {
match self.cache {
None => Ok(Response::with((status::Ok, path.as_ref()))),
None => {
let accept_range_header = Header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers.get::<Range>() {
None => Ok(Response::with((status::Ok, path.as_ref(), accept_range_header))),
Some(&Range::Bytes(ref v)) => {
let partial_file = PartialFile::from_path(path.as_ref(),v.clone());
Ok(Response::with((partial_file, accept_range_header)))
},
Some(_) => Ok(Response::with((status::RangeNotSatisfiable, accept_range_header))),
}
},
Some(ref cache) => cache.handle(req, path.as_ref()),
}
}
Expand Down Expand Up @@ -130,8 +143,27 @@ impl Handler for Static {
Some(path) => self.try_cache(req, path),
#[cfg(not(feature = "cache"))]
Some(path) => {
let path: &Path = &path;
Ok(Response::with((status::Ok, path)))
let accept_range_header = Header(AcceptRanges(vec![RangeUnit::Bytes]));
let range_req_header = req.headers.get::<Range>().map(|h|{
h.clone()
});
match range_req_header {
None => {
// deliver the whole file
let path: &Path = &path;
Ok(Response::with((status::Ok, path, accept_range_header)))
},
Some(range) => {
// try to deliver partial content
match range {
Range::Bytes(vec_range) => {
let partial_file = PartialFile::from_path(&path, vec_range);
Ok(Response::with((status::Ok, partial_file, accept_range_header)))
},
_ => Ok(Response::with(status::RangeNotSatisfiable))
}
}
}
},
}
}
Expand Down Expand Up @@ -190,7 +222,6 @@ impl Cache {
use iron::headers::{ContentLength, ContentType, ETag, EntityTag};
use iron::method::Method;
use iron::mime::{Mime, TopLevel, SubLevel};
use iron::modifiers::Header;

let seconds = self.duration.as_secs() as u32;
let cache = vec![CacheDirective::Public, CacheDirective::MaxAge(seconds)];
Expand All @@ -206,9 +237,17 @@ impl Cache {
};
Response::with((status::Ok, Header(cont_type), Header(ContentLength(metadata.len()))))
} else {
Response::with((status::Ok, path.as_ref()))
match req.headers.get::<Range>() {
None => Response::with((status::Ok, path.as_ref())),
Some(&Range::Bytes(ref v)) => {
let partial_file = PartialFile::from_path(path.as_ref(),v.clone());
Response::with(partial_file)
},
Some(_) => Response::with(status::RangeNotSatisfiable),
}
};

response.headers.set(AcceptRanges(vec![RangeUnit::Bytes]));
response.headers.set(CacheControl(cache));
response.headers.set(LastModified(HttpDate(time::at(modified))));
response.headers.set(ETag(EntityTag::weak(format!("{0:x}-{1:x}.{2:x}", size, modified.sec, modified.nsec))));
Expand Down
80 changes: 78 additions & 2 deletions tests/static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extern crate iron;
extern crate iron_test;
extern crate staticfile;

use iron::headers::{Headers, Location};
use iron::headers::{ByteRangeSpec, Headers, Location, Range};
use iron::status::Status;

use iron_test::{request, ProjectBuilder};
Expand Down Expand Up @@ -145,6 +145,82 @@ fn prevents_from_escaping_root() {
assert_eq!(str::from_utf8(&body).unwrap(), "this is file1");
},
Err(e) => panic!("{}", e)
}
}
}

#[test]
fn serves_partial_content_from_to() {
let p = ProjectBuilder::new("example").file("file1.html", "0123456789");
p.build();
let st = Static::new(p.root().clone());

// FromTo
let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::FromTo(2, 7)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::PartialContent));
let mut body = Vec::new();
res.body.unwrap().write_body(&mut body).unwrap();
assert_eq!(str::from_utf8(&body).unwrap(), "234567");

// Implicit end of range
let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::FromTo(5, 100)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::PartialContent));
let mut body = Vec::new();
res.body.unwrap().write_body(&mut body).unwrap();
assert_eq!(str::from_utf8(&body).unwrap(), "56789");

// Range out of bounds
let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::FromTo(11, 12)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::RangeNotSatisfiable));

// Backwards range
let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::FromTo(8, 5)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::Ok));
let mut body = Vec::new();
res.body.unwrap().write_body(&mut body).unwrap();
assert_eq!(str::from_utf8(&body).unwrap(), "0123456789");
}

#[test]
fn serves_partial_content_last() {
let p = ProjectBuilder::new("example").file("file1.html", "0123456789");
p.build();
let st = Static::new(p.root().clone());

let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::Last(3)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::PartialContent));

let mut body = Vec::new();
res.body.unwrap().write_body(&mut body).unwrap();
assert_eq!(str::from_utf8(&body).unwrap(), "789");
}

#[test]
fn serves_partial_content_all_from() {
let p = ProjectBuilder::new("example").file("file1.html", "0123456789");
p.build();
let st = Static::new(p.root().clone());

let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::AllFrom(5)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::PartialContent));
let mut body = Vec::new();
res.body.unwrap().write_body(&mut body).unwrap();
assert_eq!(str::from_utf8(&body).unwrap(), "56789");

// Range out of bounds
let mut headers = Headers::new();
headers.set(Range::Bytes(vec![ByteRangeSpec::AllFrom(11)]));
let res = request::get("http://localhost:3000/file1.html", headers, &st).unwrap();
assert_eq!(res.status, Some(Status::RangeNotSatisfiable));
}