use super::*;
impl Default for EtagConfig {
fn default() -> Self {
Self {
strength: EtagStrength::Strong,
min_body_bytes: DEFAULT_MIN_ETAG_BYTES,
exempt_prefixes: Vec::new(),
enforce_if_match: true,
}
}
}
impl EtagConfig {
pub fn with_strength(mut self, strength: EtagStrength) -> Self {
self.set_strength(strength);
self
}
pub fn with_min_body_bytes(mut self, min_bytes: usize) -> Self {
self.set_min_body_bytes(min_bytes);
self
}
pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
self
}
}
impl EtagPlugin {
pub fn new(config: EtagConfig, validator: Option<Arc<dyn EtagValidator>>) -> Self {
let exempt_prefixes: Box<[String]> = config
.get_exempt_prefixes()
.iter()
.filter(|p: &&String| !p.trim().is_empty())
.map(|p: &String| normalize_prefix(p))
.collect::<Vec<String>>()
.into_boxed_slice();
let mut r412: Response = Response::default();
r412.set_status_code(HttpStatus::PreconditionFailed.code())
.set_header(CONTENT_TYPE, DEFAULT_PRECONDITION_CONTENT_TYPE)
.set_body(DEFAULT_PRECONDITION_BODY);
let precondition_failed_wire: Vec<u8> = r412.build();
Self {
config,
exempt_prefixes,
validator,
precondition_failed_wire,
}
}
pub fn init(config: EtagConfig) -> &'static Self {
ETAG_PLUGIN.get_or_init(|| Self::new(config, None))
}
pub fn init_with_validator(
config: EtagConfig,
validator: Arc<dyn EtagValidator>,
) -> &'static Self {
ETAG_PLUGIN.get_or_init(|| Self::new(config, Some(validator)))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
ETAG_PLUGIN.get()
}
#[inline]
pub fn check_if_match(&self, request: &Request) -> bool {
let Self {
config,
exempt_prefixes,
validator,
..
} = self;
if !config.get_enforce_if_match() {
return true;
}
let Some(val_impl) = validator else {
return true;
};
let method: &Method = request.get_method();
if method.is_get() || method.is_head() || method.is_options() {
return true;
}
if exempt_prefixes
.iter()
.any(|p: &String| path_matches_prefix(request.get_path(), p))
{
return true;
}
let Some(if_match_val) = request
.get_headers()
.get(IF_MATCH)
.and_then(|vals: &VecDeque<String>| vals.back())
else {
return true;
};
let current: Option<String> = val_impl.current_etag(request);
matches_if_match_strong(if_match_val, current.as_deref())
}
#[inline]
pub fn apply_response(&self, ctx: &mut Context) -> bool {
let Self {
config,
exempt_prefixes,
..
} = self;
let request: &Request = ctx.get_request();
let method: &Method = request.get_method();
if !method.is_get() && !method.is_head() {
return false;
}
if exempt_prefixes
.iter()
.any(|p: &String| path_matches_prefix(request.get_path(), p))
{
return false;
}
let response: &Response = ctx.get_response();
let status: usize = response.get_status_code();
if !(200..300).contains(&status) || status_has_no_body(status) {
return false;
}
let existing_tag: Option<&str> = response
.get_headers()
.get(ETAG)
.and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
let matched: bool = if let Some(tag) = existing_tag {
request.matches_if_none_match(tag)
} else {
let body: &[u8] = response.get_body();
if body.len() < config.get_min_body_bytes() {
return false;
}
let digest: u64 = hash_entity_bytes(body);
match config.get_strength() {
EtagStrength::Strong => {
let buf: [u8; 18] = format_strong_etag_stack(digest);
let tag: &str = from_utf8(&buf).unwrap_or_default();
let is_match: bool = request.matches_if_none_match(tag);
ctx.get_mut_response().set_header(ETAG, tag);
is_match
}
EtagStrength::Weak => {
let buf: [u8; 20] = format_weak_etag_stack(digest);
let tag: &str = from_utf8(&buf).unwrap_or_default();
let is_match: bool = request.matches_if_none_match(tag);
ctx.get_mut_response().set_header(ETAG, tag);
is_match
}
}
};
if matched {
let resp: &mut Response = ctx.get_mut_response();
resp.set_status_code(HttpStatus::NotModified.code());
resp.get_mut_body().clear();
return true;
}
false
}
}
impl ServerHook for EtagRequestHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = EtagPlugin::get() else {
return Status::Continue;
};
if !plugin.check_if_match(ctx.get_request()) {
let EtagPlugin {
precondition_failed_wire,
..
} = plugin;
let _: Result<(), ResponseError> = stream.try_send(precondition_failed_wire).await;
return Status::Reject;
}
Status::Continue
}
}
impl ServerHook for EtagResponseHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = EtagPlugin::get() else {
return Status::Continue;
};
let _: bool = plugin.apply_response(ctx);
Status::Continue
}
}