use super::*;
impl Debug for AllowOrigin {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Any => f.write_str(DEBUG_ALLOW_ORIGIN_ANY),
Self::Exact(set) => f.debug_tuple(DEBUG_ALLOW_ORIGIN_EXACT).field(set).finish(),
Self::Suffix(list) => f
.debug_tuple(DEBUG_ALLOW_ORIGIN_SUFFIX)
.field(list)
.finish(),
Self::Custom(_) => f.write_str(DEBUG_ALLOW_ORIGIN_CUSTOM),
}
}
}
impl AllowOrigin {
pub fn exact<I, S>(origins: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
for origin in origins {
let normalized: String = origin.as_ref().trim().to_ascii_lowercase();
if !normalized.is_empty() {
set.insert(normalized);
}
}
Self::Exact(set)
}
pub fn suffix<I, S>(suffixes: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let list: Vec<String> = suffixes
.into_iter()
.map(|item: S| item.as_ref().trim().to_ascii_lowercase())
.filter(|item: &String| !item.is_empty())
.collect();
Self::Suffix(list)
}
pub fn custom<F>(predicate: F) -> Self
where
F: Fn(&str) -> bool + Send + Sync + 'static,
{
Self::Custom(Arc::new(predicate))
}
#[inline]
pub fn is_allowed(&self, origin: &str) -> bool {
let trimmed: &str = origin.trim();
if trimmed.is_empty() {
return false;
}
match self {
Self::Any => true,
Self::Exact(set) => {
if set.contains(trimmed) {
return true;
}
let bytes: &[u8] = trimmed.as_bytes();
if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
return false;
}
if bytes.len() <= ORIGIN_LOWER_STACK_CAP {
let mut stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
let mut i: usize = 0;
while i < bytes.len() {
stack[i] = bytes[i].to_ascii_lowercase();
i += 1;
}
if let Ok(lower) = from_utf8(&stack[..bytes.len()]) {
return set.contains(lower);
}
}
set.contains(&trimmed.to_ascii_lowercase())
}
Self::Suffix(suffixes) => {
let host: &str = extract_origin_host(trimmed);
if host.is_empty() {
return false;
}
suffixes.iter().any(|suffix: &String| {
if let Some(bare) = suffix.strip_prefix('.') {
host.eq_ignore_ascii_case(bare)
|| ends_with_ignore_ascii_case(host, suffix.as_str())
} else {
host.eq_ignore_ascii_case(suffix.as_str())
}
})
}
Self::Custom(matcher) => matcher(trimmed),
}
}
}
impl Default for CorsConfig {
fn default() -> Self {
Self {
allow_origin: AllowOrigin::Any,
allow_methods: DEFAULT_ALLOWED_METHODS
.iter()
.map(|method: &&str| (*method).to_owned())
.collect(),
allow_headers: DEFAULT_ALLOWED_HEADERS
.iter()
.map(|header: &&str| (*header).to_owned())
.collect(),
expose_headers: Vec::new(),
allow_credentials: false,
max_age_secs: Some(DEFAULT_CORS_MAX_AGE_SECS),
allow_private_network: false,
}
}
}
impl CorsConfig {
pub fn permissive() -> Self {
Self {
allow_origin: AllowOrigin::Any,
allow_methods: DEFAULT_ALLOWED_METHODS
.iter()
.map(|method: &&str| (*method).to_owned())
.collect(),
allow_headers: vec![CORS_WILDCARD.to_owned()],
expose_headers: Vec::new(),
allow_credentials: false,
max_age_secs: Some(DEFAULT_CORS_MAX_AGE_SECS),
allow_private_network: false,
}
}
pub fn strict<I, S>(origins: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
Self::default().with_allow_origin(AllowOrigin::exact(origins))
}
pub fn with_allow_origin(mut self, allow_origin: AllowOrigin) -> Self {
self.set_allow_origin(allow_origin);
self
}
pub fn with_allow_methods<I, S>(mut self, methods: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_allow_methods(methods.into_iter().map(Into::into).collect());
self
}
pub fn with_allow_headers<I, S>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_allow_headers(headers.into_iter().map(Into::into).collect());
self
}
pub fn with_expose_headers<I, S>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_expose_headers(headers.into_iter().map(Into::into).collect());
self
}
pub fn with_allow_credentials(mut self, allow_credentials: bool) -> Self {
self.set_allow_credentials(allow_credentials);
self
}
pub fn with_max_age_secs(mut self, max_age_secs: Option<u64>) -> Self {
self.set_max_age_secs(max_age_secs);
self
}
pub fn with_allow_private_network(mut self, allow_private_network: bool) -> Self {
self.set_allow_private_network(allow_private_network);
self
}
}
impl CompiledCors {
pub fn compile(config: CorsConfig) -> Self {
let exact_small: Option<Box<[String]>> = match config.get_allow_origin() {
AllowOrigin::Exact(set) if set.len() <= CORS_SMALL_EXACT_LIMIT => {
let items: Vec<String> = set.iter().cloned().collect();
Some(items.into_boxed_slice())
}
_ => None,
};
let is_any_wildcard: bool = matches!(config.get_allow_origin(), AllowOrigin::Any)
&& !config.get_allow_credentials();
let raw_methods: String = config.get_allow_methods().join(COMMA_SPACE);
let methods_header: String = if is_valid_cors_header_value(&raw_methods) {
raw_methods
} else {
String::new()
};
let mirror_headers: bool = should_mirror_request_headers(config.get_allow_headers());
let headers_header: Option<String> = if mirror_headers {
None
} else {
let joined: String = config.get_allow_headers().join(COMMA_SPACE);
if is_valid_cors_header_value(&joined) {
Some(joined)
} else {
None
}
};
let expose_header: Option<String> = if config.get_expose_headers().is_empty() {
None
} else {
let joined: String = config.get_expose_headers().join(COMMA_SPACE);
if is_valid_cors_header_value(&joined) {
Some(joined)
} else {
None
}
};
let max_age_header: Option<String> = config
.try_get_max_age_secs()
.map(|secs: u64| secs.to_string());
let vary_origin: bool = !is_any_wildcard;
let mut preflight_lines: Vec<u8> = Vec::with_capacity(256);
if config.get_allow_credentials() {
preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_CREDENTIALS.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
preflight_lines.extend_from_slice(HEADER_VALUE_TRUE.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
}
if !methods_header.is_empty() {
preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_METHODS.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
preflight_lines.extend_from_slice(methods_header.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
}
if let Some(ref fixed_headers) = headers_header {
preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_HEADERS.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
preflight_lines.extend_from_slice(fixed_headers.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
}
if let Some(ref max_age) = max_age_header {
preflight_lines.extend_from_slice(ACCESS_CONTROL_MAX_AGE.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
preflight_lines.extend_from_slice(max_age.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
}
preflight_lines.extend_from_slice(VARY.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
let preflight_vary: &str = if vary_origin {
VARY_PREFLIGHT_WITH_ORIGIN
} else {
VARY_PREFLIGHT_WITHOUT_ORIGIN
};
preflight_lines.extend_from_slice(preflight_vary.as_bytes());
preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
Self {
config,
exact_small,
is_any_wildcard,
methods_header,
mirror_headers,
headers_header,
expose_header,
max_age_header,
preflight_static_lines: preflight_lines.into_boxed_slice(),
vary_origin,
}
}
#[inline(always)]
pub fn get_config(&self) -> &CorsConfig {
&self.config
}
#[inline]
pub fn resolve_origin<'a>(&self, origin: &'a str) -> Option<&'a str> {
let Self {
config,
exact_small,
is_any_wildcard,
..
} = self;
let trimmed: &'a str = origin.trim();
if trimmed.is_empty() {
return None;
}
if *is_any_wildcard {
return Some(CORS_WILDCARD);
}
if let Some(small) = exact_small {
let t_len: usize = trimmed.len();
for allowed in small.iter() {
if allowed.len() == t_len && allowed.eq_ignore_ascii_case(trimmed) {
return Some(trimmed);
}
}
return None;
}
if !config.get_allow_origin().is_allowed(trimmed) {
return None;
}
Some(trimmed)
}
pub fn apply_request(&self, ctx: &mut Context) -> bool {
let Self {
config,
methods_header,
mirror_headers,
headers_header,
expose_header,
max_age_header,
vary_origin,
..
} = self;
let allow_credentials: bool = config.get_allow_credentials();
let Some(origin) = request_header_back(ctx.get_request(), ORIGIN) else {
return false;
};
let Some(allow_origin_val) = self.resolve_origin(origin) else {
return false;
};
let is_wildcard: bool = allow_origin_val == CORS_WILDCARD;
let mut origin_stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
let mut origin_stack_len: usize = 0;
let mut origin_heap: Option<String> = None;
if !is_wildcard {
let raw_bytes: &[u8] = allow_origin_val.as_bytes();
if raw_bytes.len() <= ORIGIN_LOWER_STACK_CAP {
origin_stack[..raw_bytes.len()].copy_from_slice(raw_bytes);
origin_stack_len = raw_bytes.len();
} else {
origin_heap = Some(allow_origin_val.to_owned());
}
}
let req: &Request = ctx.get_request();
let is_preflight: bool = req.get_method().is_options()
&& req
.get_headers()
.contains_key(ACCESS_CONTROL_REQUEST_METHOD);
let req_headers: Option<String> = if is_preflight && *mirror_headers {
request_header_back(req, ACCESS_CONTROL_REQUEST_HEADERS).map(str::to_owned)
} else {
None
};
let wants_private_net: bool = is_preflight
&& config.get_allow_private_network()
&& request_header_back(req, ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK)
.is_some_and(|val: &str| val.trim().eq_ignore_ascii_case(HEADER_VALUE_TRUE));
let allow_origin_str: &str = if is_wildcard {
CORS_WILDCARD
} else if let Some(ref owned) = origin_heap {
owned.as_str()
} else {
from_utf8(&origin_stack[..origin_stack_len]).unwrap_or_default()
};
let response: &mut Response = ctx.get_mut_response();
if response.get_headers().is_empty() {
let headers: &mut ResponseHeaders = response.get_mut_headers();
if is_preflight {
let mut cap: usize = 2;
if allow_credentials {
cap += 1;
}
if !methods_header.is_empty() {
cap += 1;
}
if headers_header.is_some() || req_headers.is_some() {
cap += 1;
}
if max_age_header.is_some() {
cap += 1;
}
if wants_private_net {
cap += 1;
}
headers.reserve(cap);
if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
}
if allow_credentials {
insert_fresh_header(
headers,
ACCESS_CONTROL_ALLOW_CREDENTIALS,
HEADER_VALUE_TRUE,
);
}
if !methods_header.is_empty() {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_METHODS, methods_header);
}
if let Some(fixed_headers) = headers_header {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_HEADERS, fixed_headers);
} else if let Some(requested) = req_headers
&& is_valid_cors_header_value(&requested)
{
headers.insert(
ACCESS_CONTROL_ALLOW_HEADERS.to_owned(),
VecDeque::from([requested]),
);
}
if let Some(max_age) = max_age_header {
insert_fresh_header(headers, ACCESS_CONTROL_MAX_AGE, max_age);
}
if wants_private_net {
insert_fresh_header(
headers,
ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK,
HEADER_VALUE_TRUE,
);
}
let preflight_vary: &str = if *vary_origin {
VARY_PREFLIGHT_WITH_ORIGIN
} else {
VARY_PREFLIGHT_WITHOUT_ORIGIN
};
insert_fresh_header(headers, VARY, preflight_vary);
response
.set_status_code(HttpStatus::NoContent.code())
.set_body(&[] as &[u8]);
return true;
}
let mut cap: usize = 1;
if allow_credentials {
cap += 1;
}
if *vary_origin {
cap += 1;
}
if expose_header.is_some() {
cap += 1;
}
headers.reserve(cap);
if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
}
if allow_credentials {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
}
if *vary_origin {
insert_fresh_header(headers, VARY, VARY_ORIGIN);
}
if let Some(expose) = expose_header {
insert_fresh_header(headers, ACCESS_CONTROL_EXPOSE_HEADERS, expose);
}
return false;
}
response.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
if allow_credentials {
response.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
}
if is_preflight {
if !methods_header.is_empty() {
response.set_header(ACCESS_CONTROL_ALLOW_METHODS, methods_header);
}
if let Some(fixed_headers) = headers_header {
response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, fixed_headers);
} else if let Some(requested) = req_headers {
response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, requested);
}
if let Some(max_age) = max_age_header {
response.set_header(ACCESS_CONTROL_MAX_AGE, max_age);
}
if wants_private_net {
response.set_header(ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK, HEADER_VALUE_TRUE);
}
if !response.has_header(VARY) {
let preflight_vary: &str = if *vary_origin {
VARY_PREFLIGHT_WITH_ORIGIN
} else {
VARY_PREFLIGHT_WITHOUT_ORIGIN
};
response.set_header(VARY, preflight_vary);
} else {
if *vary_origin {
merge_vary_header(response, VARY_ORIGIN);
}
merge_vary_header(response, VARY_PREFLIGHT_METHOD);
merge_vary_header(response, VARY_PREFLIGHT_HEADERS);
}
response
.set_status_code(HttpStatus::NoContent.code())
.set_body(&[] as &[u8]);
return true;
}
if *vary_origin {
merge_vary_header(response, VARY_ORIGIN);
}
if let Some(expose) = expose_header {
response.set_header(ACCESS_CONTROL_EXPOSE_HEADERS, expose);
}
false
}
#[inline]
pub fn ensure_response_headers(&self, ctx: &mut Context) {
if ctx.get_response().has_header(ACCESS_CONTROL_ALLOW_ORIGIN) {
return;
}
let Self {
config,
expose_header,
vary_origin,
..
} = self;
let allow_credentials: bool = config.get_allow_credentials();
let Some(origin) = request_header_back(ctx.get_request(), ORIGIN) else {
return;
};
let Some(allow_origin_val) = self.resolve_origin(origin) else {
return;
};
let is_wildcard: bool = allow_origin_val == CORS_WILDCARD;
let mut origin_stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
let mut origin_stack_len: usize = 0;
let mut origin_heap: Option<String> = None;
if !is_wildcard {
let raw_bytes: &[u8] = allow_origin_val.as_bytes();
if raw_bytes.len() <= ORIGIN_LOWER_STACK_CAP {
origin_stack[..raw_bytes.len()].copy_from_slice(raw_bytes);
origin_stack_len = raw_bytes.len();
} else {
origin_heap = Some(allow_origin_val.to_owned());
}
}
let allow_origin_str: &str = if is_wildcard {
CORS_WILDCARD
} else if let Some(ref owned) = origin_heap {
owned.as_str()
} else {
from_utf8(&origin_stack[..origin_stack_len]).unwrap_or_default()
};
let response: &mut Response = ctx.get_mut_response();
if response.get_headers().is_empty() {
let headers: &mut ResponseHeaders = response.get_mut_headers();
let mut cap: usize = 1;
if *vary_origin {
cap += 1;
}
if allow_credentials {
cap += 1;
}
if expose_header.is_some() {
cap += 1;
}
headers.reserve(cap);
if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
}
if *vary_origin {
insert_fresh_header(headers, VARY, VARY_ORIGIN);
}
if allow_credentials {
insert_fresh_header(headers, ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
}
if let Some(expose) = expose_header {
insert_fresh_header(headers, ACCESS_CONTROL_EXPOSE_HEADERS, expose);
}
return;
}
response.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
if *vary_origin {
merge_vary_header(response, VARY_ORIGIN);
}
if allow_credentials {
response.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
}
if let Some(expose) = expose_header {
response.set_header(ACCESS_CONTROL_EXPOSE_HEADERS, expose);
}
}
pub(crate) async fn try_send_fast_preflight(
&self,
stream: &mut Stream,
ctx: &Context,
) -> Option<bool> {
let Self {
config,
mirror_headers,
preflight_static_lines,
..
} = self;
let req: &Request = ctx.get_request();
if !req.get_method().is_options()
|| !req.get_version().is_http1_1()
|| !ctx.get_response().get_headers().is_empty()
|| !req
.get_headers()
.contains_key(ACCESS_CONTROL_REQUEST_METHOD)
{
return None;
}
let origin: &str = request_header_back(req, ORIGIN)?;
let allow_origin_val: &str = self.resolve_origin(origin)?;
if allow_origin_val != CORS_WILDCARD && !is_valid_cors_header_value(allow_origin_val) {
return Some(false);
}
let mirrored_headers: Option<&str> = if *mirror_headers {
request_header_back(req, ACCESS_CONTROL_REQUEST_HEADERS)
.filter(|v: &&str| is_valid_cors_header_value(v))
} else {
None
};
let wants_private_net: bool = config.get_allow_private_network()
&& request_header_back(req, ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK)
.is_some_and(|val: &str| val.trim().eq_ignore_ascii_case(HEADER_VALUE_TRUE));
let mut total_len: usize = PREFLIGHT_WIRE_STATUS_ORIGIN.len()
+ allow_origin_val.len()
+ PREFLIGHT_WIRE_CRLF.len()
+ preflight_static_lines.len()
+ PREFLIGHT_WIRE_CRLF.len();
if let Some(mh) = mirrored_headers {
total_len += PREFLIGHT_WIRE_ALLOW_HEADERS.len() + mh.len() + PREFLIGHT_WIRE_CRLF.len();
}
if wants_private_net {
total_len += PREFLIGHT_WIRE_PRIVATE_NET.len();
}
if total_len <= PREFLIGHT_WIRE_STACK_CAP {
let mut stack: [u8; PREFLIGHT_WIRE_STACK_CAP] = [0u8; PREFLIGHT_WIRE_STACK_CAP];
let mut pos: usize = 0;
stack[pos..pos + PREFLIGHT_WIRE_STATUS_ORIGIN.len()]
.copy_from_slice(PREFLIGHT_WIRE_STATUS_ORIGIN);
pos += PREFLIGHT_WIRE_STATUS_ORIGIN.len();
let orig_b: &[u8] = allow_origin_val.as_bytes();
stack[pos..pos + orig_b.len()].copy_from_slice(orig_b);
pos += orig_b.len();
stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
pos += PREFLIGHT_WIRE_CRLF.len();
stack[pos..pos + preflight_static_lines.len()].copy_from_slice(preflight_static_lines);
pos += preflight_static_lines.len();
if let Some(mh) = mirrored_headers {
stack[pos..pos + PREFLIGHT_WIRE_ALLOW_HEADERS.len()]
.copy_from_slice(PREFLIGHT_WIRE_ALLOW_HEADERS);
pos += PREFLIGHT_WIRE_ALLOW_HEADERS.len();
let mh_b: &[u8] = mh.as_bytes();
stack[pos..pos + mh_b.len()].copy_from_slice(mh_b);
pos += mh_b.len();
stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
pos += PREFLIGHT_WIRE_CRLF.len();
}
if wants_private_net {
stack[pos..pos + PREFLIGHT_WIRE_PRIVATE_NET.len()]
.copy_from_slice(PREFLIGHT_WIRE_PRIVATE_NET);
pos += PREFLIGHT_WIRE_PRIVATE_NET.len();
}
stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
pos += PREFLIGHT_WIRE_CRLF.len();
let _: Result<(), ResponseError> = stream.try_send(&stack[..pos]).await;
return Some(true);
}
let mut wire: Vec<u8> = Vec::with_capacity(total_len);
wire.extend_from_slice(PREFLIGHT_WIRE_STATUS_ORIGIN);
wire.extend_from_slice(allow_origin_val.as_bytes());
wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
wire.extend_from_slice(preflight_static_lines);
if let Some(mh) = mirrored_headers {
wire.extend_from_slice(PREFLIGHT_WIRE_ALLOW_HEADERS);
wire.extend_from_slice(mh.as_bytes());
wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
}
if wants_private_net {
wire.extend_from_slice(PREFLIGHT_WIRE_PRIVATE_NET);
}
wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
Some(true)
}
}
impl CorsPlugin {
pub fn init(config: CorsConfig) -> &'static Self {
CORS_PLUGIN.get_or_init(|| Self {
compiled: CompiledCors::compile(config),
})
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
CORS_PLUGIN.get()
}
#[inline(always)]
pub fn get_compiled(&self) -> &CompiledCors {
&self.compiled
}
}
impl ServerHook for CorsRequestHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = CorsPlugin::get() else {
return Status::Continue;
};
let compiled: &CompiledCors = plugin.get_compiled();
if compiled.try_send_fast_preflight(stream, ctx).await == Some(true) {
return Status::Reject;
}
if compiled.apply_request(ctx) {
let wire: Vec<u8> = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
return Status::Reject;
}
Status::Continue
}
}
impl ServerHook for CorsResponseHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = CorsPlugin::get() else {
return Status::Continue;
};
plugin.get_compiled().ensure_response_headers(ctx);
Status::Continue
}
}