Skip to content
Merged
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
3 changes: 2 additions & 1 deletion docs/runtime/http/routing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ Bun.serve({
- **Last-Modified support** - Uses file modification time for `If-Modified-Since` headers
- **If-Modified-Since** - Returns `304 Not Modified` when file hasn't changed since client's cached version
- **Range request support** - Automatically handles partial content requests with `Content-Range` headers
- **If-Range** - Sends the full file instead of a `206` when the `If-Range` validator is not the response's strong `ETag` or its exact `Last-Modified`
- **Streaming transfers** - Uses buffered reader with backpressure handling for efficient memory usage
- **Memory efficient** - Only buffers small chunks during transfer, not entire file
- **Best for**: Large files, dynamic content, user uploads, files that change frequently
Expand Down Expand Up @@ -219,7 +220,7 @@ Directory routes share the response path with file routes:

- **Content-Type** is set from the file extension.
- **Last-Modified** and a weak `ETag` (`W/"<size>-<mtime>"`) are sent on every response, and `If-Modified-Since` / `If-None-Match` are honored with `304 Not Modified`.
- **Range requests** are supported with `Accept-Ranges: bytes` and `Content-Range`.
- **Range requests** are supported with `Accept-Ranges: bytes` and `Content-Range`. `If-Range` is honored with the `Last-Modified` date. The `ETag` is weak, so it never matches `If-Range`, and the response is the full file.
- A request that resolves to a directory without a trailing `/` receives a `301` redirect to the trailing-slash URL. With the trailing slash, Bun serves `index.html` from that directory.
- Missing files return `404`.

Expand Down
15 changes: 15 additions & 0 deletions src/http_types/ETag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ pub fn if_match(
false
}

/// RFC 9110 §13.1.5: evaluate an `If-Range` entity-tag using the strong
/// comparison (§8.8.3.2), so a weak tag on either side never matches. `false`
/// means ignore `Range` and send the whole representation.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn if_range(
// Stored `ETag` header, `None` when the representation has none.
etag: Option<&[u8]>,
// `If-Range` header
if_range: &[u8],
) -> bool {
let Some(etag) = etag else { return false };
let ours = parse(etag);
let theirs = parse(if_range);
!ours.is_weak && !theirs.is_weak && ours.tag == theirs.tag
}

pub fn if_none_match(
// "ETag" header
etag: &[u8],
Expand Down
13 changes: 4 additions & 9 deletions src/runtime/server/DirectoryRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,21 +157,16 @@ impl DirectoryRoute {

let mut etag_buf = [0u8; 40];
let etag = format_weak_etag(&mut etag_buf, size, last_modified_ms);
let last_modified_ms = (last_modified_ms > 0).then_some(last_modified_ms);

let range = if method == Method::GET || method == Method::HEAD {
RangeRequest::from_request(&req, size)
RangeRequest::from_request(&req, size, Some(etag), last_modified_ms)
} else {
RangeRequest::Result::None
};

let status_code = status_for_preconditions(
&req,
method,
200,
Some(etag),
(last_modified_ms > 0).then_some(last_modified_ms),
range,
);
let status_code =
status_for_preconditions(&req, method, 200, Some(etag), last_modified_ms, range);

req.set_yield(false);
write_any_status(resp, status_code);
Expand Down
29 changes: 16 additions & 13 deletions src/runtime/server/FileRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,19 @@ impl FileRoute {
return Serve::Done;
}

let etag = self.headers.get(b"etag").filter(|v| !v.is_empty());
let last_modified_ms = if req.header(b"if-modified-since").is_some()
|| req.header(b"if-unmodified-since").is_some()
|| req.header(b"if-range").is_some()
{
let Ok(lmd) = self.last_modified_date() else {
return Serve::Done;
Comment thread
robobun marked this conversation as resolved.
Resolved
};
lmd
} else {
None
};

// Range applies to the slice the route was configured with, not the
// underlying file: a Bun.file(p).slice(a,b) route exposes only [a,b).
// RFC 9110 §14.2: Range is only defined for GET (HEAD mirrors GET's
Expand All @@ -373,22 +386,11 @@ impl FileRoute {
&& self.status_code == 200
&& !self.has_content_range_header
{
RangeRequest::from_request(req, size)
RangeRequest::from_request(req, size, etag, last_modified_ms)
} else {
RangeRequest::Result::None
};

let etag = self.headers.get(b"etag").filter(|v| !v.is_empty());
let last_modified_ms = if req.header(b"if-modified-since").is_some()
|| req.header(b"if-unmodified-since").is_some()
{
let Ok(lmd) = self.last_modified_date() else {
return Serve::Done;
};
lmd
} else {
None
};
let status_code =
status_for_preconditions(req, method, self.status_code, etag, last_modified_ms, range);

Expand Down Expand Up @@ -480,7 +482,8 @@ impl Drop for FileRoute {
/// Order: (1) If-Match, else (2) If-Unmodified-Since; then (3) If-None-Match,
/// else (4) If-Modified-Since. Steps 1/2 yield 412 on failure and must run
/// before steps 3/4 can yield 304. Preconditions only apply when the selected
/// representation would otherwise be 200 (§13.1.1).
/// representation would otherwise be 200 (§13.1.1). Step 5, If-Range, is
/// already applied to `range` by `RangeRequest::from_request`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn status_for_preconditions(
req: &AnyRequest,
method: Method,
Expand Down
61 changes: 59 additions & 2 deletions src/runtime/server/RangeRequest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! (serve full body) rather than 416, matching common static-server behavior.

use bun_core::strings;
use bun_http_types::ETag;
use bun_uws::AnyRequest;

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
Expand Down Expand Up @@ -124,13 +125,28 @@ pub(crate) fn parse(header: &[u8], total: u64) -> Result {
parse_raw(header).resolve(total)
}

/// Resolve the request's `Range` against `total`. `etag` and
/// `last_modified_ms` are the validators of the representation being served:
/// an `If-Range` that does not match them turns the `Range` off.
Comment thread
robobun marked this conversation as resolved.
Resolved
// `bun_uws::AnyRequest::header` borrows `&self` and returns `&[u8]` tied to
// it, so take `&AnyRequest` here.
pub(crate) fn from_request(req: &AnyRequest, total: u64) -> Result {
pub(crate) fn from_request(
req: &AnyRequest,
total: u64,
etag: Option<&[u8]>,
last_modified_ms: Option<u64>,
) -> Result {
let Some(h) = req.header(b"range") else {
return Result::None;
};
parse(h, total)
let range = parse(h, total);
if range != Result::None
&& let Some(if_range) = req.header(b"if-range")
&& !if_range_matches(if_range, etag, last_modified_ms)
{
return Result::None;
}
range
}

pub(crate) fn raw_from_request(req: &AnyRequest) -> Raw {
Expand All @@ -140,6 +156,47 @@ pub(crate) fn raw_from_request(req: &AnyRequest) -> Raw {
parse_raw(h)
}

/// The `If-Range` header, copied out of the uWS request buffer for a request
/// context that learns the response's validators after the request is gone.
/// `None` without a usable `Range`: there is nothing for it to guard.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn if_range_from_request(req: &AnyRequest, range: Raw) -> Option<Box<[u8]>> {
if range == Raw::None {
return None;
}
req.header(b"if-range").map(Box::from)
}

/// RFC 9110 §13.1.5: whether the `If-Range` validator matches the selected
/// representation. `false` means the client's partial copy is of another
/// version, so the server ignores `Range` and sends the full 200 body.
///
/// An entity-tag matches by strong comparison. An HTTP-date matches only the
/// exact `Last-Modified`, not an older or a newer one.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn if_range_matches(
if_range: &[u8],
etag: Option<&[u8]>,
last_modified_ms: Option<u64>,
) -> bool {
// An entity-tag (`"..."` or `W/"..."`) has a DQUOTE in its first three
// bytes; an HTTP-date has none.
Comment thread
robobun marked this conversation as resolved.
Resolved
if strings::contains_char(&if_range[..if_range.len().min(3)], b'"') {
return ETag::if_range(etag, if_range);
}
let Some(last_modified_ms) = last_modified_ms else {
return false;
};
// An HTTP-date is GMT, but `parse_http_date` is `Date.parse`: it reads a
// date with no zone (the obsolete asctime form) in the server's local time.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !if_range.ends_with(b"GMT") {
return false;
}
let Some(date_ms) = crate::jsc_hooks::parse_http_date(if_range) else {
return false;
};
Comment thread
robobun marked this conversation as resolved.
Resolved
// `Last-Modified` is second-granular on the wire.
last_modified_ms / 1000 == date_ms / 1000
}

/// Max bytes a `Content-Range: bytes ...` value can occupy: `"bytes "` (6) +
Comment thread
robobun marked this conversation as resolved.
Resolved
/// three `u64::MAX` (20 each) + `'-'` + `'/'` = 68. 96 leaves slack.
pub(crate) const CONTENT_RANGE_BUF: usize = 96;
Expand Down
30 changes: 29 additions & 1 deletion src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,9 @@ pub struct RequestContext<

pub(crate) sendfile: Cell<SendfileContext>,
pub(crate) range: RangeRequest::Raw,
/// The request's `If-Range`, kept until `do_sendfile` can compare it with
/// the validators on the handler's Response. `None` when `range` is.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) if_range: Option<Box<[u8]>>,

pub(crate) request_body_readable_stream_ref: JsCell<readable_stream::Strong>,
/// Owning `+1` handle into the per-VM `Body::Value` hive pool. Shared with
Expand Down Expand Up @@ -225,6 +228,7 @@ where
core::mem::size_of::<Self>()
+ self.request_body_buf.get().capacity()
+ self.response_buf_owned.get().capacity()
+ self.if_range.as_deref().map_or(0, <[u8]>::len)
+ self.blob.get().memory_cost()
}

Expand Down Expand Up @@ -1411,6 +1415,9 @@ where
let resolved_method = method
.or_else(|| Method::which(Self::req_method(req)))
.unwrap_or(Method::GET);
let any_req = Self::any_request(req);
let range = RangeRequest::raw_from_request(&any_req);
let if_range = RangeRequest::if_range_from_request(&any_req, range);
let slot: *mut Self = this.as_mut_ptr();
// SAFETY: writing to MaybeUninit slot
unsafe {
Expand All @@ -1423,7 +1430,8 @@ where
NonNull::new(server).map(|p| bun_ptr::BackRef::from_raw_mut(p.as_ptr())),
),
defer_deinit_until_callback_completes: Cell::new(should_deinit_context),
range: RangeRequest::raw_from_request(&Self::any_request(req)),
range,
if_range,
request_weakref: JsCell::new(request::WeakRef::EMPTY),
signal: Cell::new(None),
cookies: JsCell::new(None),
Expand Down Expand Up @@ -1758,6 +1766,25 @@ where
true
}

/// RFC 9110 §13.1.5 for a file body from a handler. The only validators
/// are the `ETag` and `Last-Modified` the handler put on its Response (Bun
/// adds none here), so without them an `If-Range` never matches.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn if_range_matches_response(&self) -> bool {
let Some(if_range) = self.if_range.as_deref() else {
return true;
};
let Some(headers) = self.response_mut().and_then(|r| r.get_init_headers_mut()) else {
return false;
};
let etag = headers
.fast_get(jsc::HTTPHeaderName::ETag)
.map(|v| v.to_utf8().into_owned());
let last_modified_ms = headers
.fast_get(jsc::HTTPHeaderName::LastModified)
.and_then(|v| crate::jsc_hooks::parse_http_date(v.to_utf8().slice()));
RangeRequest::if_range_matches(if_range, etag.as_deref(), last_modified_ms)
}

pub(crate) fn do_sendfile(&self, blob: Blob) {
if self.is_aborted_or_ended() {
return;
Expand Down Expand Up @@ -1911,6 +1938,7 @@ where
&& !user_handles_range
&& is_whole_file
&& self.range != RangeRequest::Raw::None
&& self.if_range_matches_response()
{
match self.range.resolve(stat_size) {
RangeRequest::Result::None => {}
Expand Down
Loading
Loading