use std::net::SocketAddr;
use std::sync::Arc;
use http_body_util::BodyExt as _;
use http_body_util::combinators::BoxBody;
use hyper::Request;
use hyper::body::Bytes;
pub(crate) type IncomingBody = BoxBody<Bytes, Box<dyn std::error::Error + Send + Sync>>;
use mlua::{ExternalResult, LuaSerdeExt, UserData, UserDataFields, UserDataMethods};
use serde_json::Value as SerdeValue;
mod body;
mod fresh;
#[cfg(test)]
mod tests;
pub(crate) use body::BodyGuards;
use body::{LimitedBody, StalledBody};
pub use fresh::is_fresh;
pub(crate) struct LuaRequest {
pub(crate) peer_addr: SocketAddr,
pub(crate) tls: bool,
pub(crate) req: Request<IncomingBody>,
pub(crate) params: Vec<(String, String)>,
pub(crate) id: Arc<str>,
pub(crate) limits: FormLimits,
pub(crate) cached_form: Option<Vec<(String, String)>>,
pub(crate) body_limit: u64,
pub(crate) cached_body: Option<Bytes>,
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) body_consumed: bool,
pub(crate) valid: Option<mlua::Table>,
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) spool_dir: Option<std::path::PathBuf>,
}
#[derive(Debug, Clone)]
pub(crate) struct FormLimits {
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) max_parts: usize,
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) max_field_bytes: u64,
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) max_file_bytes: u64,
#[cfg_attr(not(feature = "multipart"), allow(dead_code))]
pub(crate) upload_root: Option<std::sync::Arc<std::path::PathBuf>>,
}
impl Default for FormLimits {
fn default() -> Self {
let defaults = crate::config::LimitsConfig::default();
Self {
max_parts: defaults.max_form_parts,
max_field_bytes: defaults.max_field_bytes,
max_file_bytes: defaults.max_file_bytes,
upload_root: None,
}
}
}
impl LuaRequest {
async fn whole_body(&mut self) -> mlua::Result<Bytes> {
if let Some(cached) = &self.cached_body {
return Ok(cached.clone());
}
let body = self
.req
.body_mut()
.collect()
.await
.into_lua_err()?
.to_bytes();
self.cached_body = Some(body.clone());
Ok(body)
}
pub(crate) fn synthetic(
req: Request<IncomingBody>,
peer_addr: SocketAddr,
id: Arc<str>,
) -> Self {
Self {
peer_addr,
tls: false,
req,
params: Vec::new(),
id,
limits: Default::default(),
cached_form: None,
body_limit: u64::MAX,
cached_body: None,
body_consumed: false,
valid: None,
spool_dir: None,
}
}
pub(crate) fn guard_body(
&mut self,
limit: u64,
stall: Option<std::time::Duration>,
) -> BodyGuards {
let guards = BodyGuards(Arc::new(body::BodyFlags::default()));
self.body_limit = limit;
let inner = std::mem::take(self.req.body_mut());
let limited = LimitedBody {
inner,
limit,
read: 0,
flags: guards.0.clone(),
};
*self.req.body_mut() = match stall {
Some(budget) => StalledBody {
inner: limited.boxed(),
budget,
deadline: None,
flags: guards.0.clone(),
}
.boxed(),
None => limited.boxed(),
};
guards
}
pub(crate) fn discard_body(&mut self) {
*self.req.body_mut() = BoxBody::default();
}
}
fn clamp_want(want: usize, limit: u64) -> usize {
let ceiling = usize::try_from(limit.saturating_add(1)).unwrap_or(usize::MAX);
want.min(ceiling)
}
impl UserData for LuaRequest {
fn add_fields<'lua, F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("remote_addr", |_, req| Ok(req.peer_addr.to_string()));
fields.add_field_method_get("method", |_, req| Ok(req.req.method().to_string()));
fields.add_field_method_get("path", |_, req| Ok(req.req.uri().path().to_string()));
fields.add_field_method_get("query", |lua, req| {
let table = lua.create_table()?;
if let Some(query) = req.req.uri().query() {
for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
table.set(k.as_ref(), v.as_ref())?;
}
}
Ok(table)
});
fields.add_field_method_get("id", |lua, req| lua.create_string(&*req.id));
fields.add_field_method_get("params", |lua, req| {
let table = lua.create_table()?;
for (k, v) in &req.params {
table.set(k.as_str(), v.as_str())?;
}
Ok(table)
});
fields.add_field_method_get("uri", |lua, req| {
let table = lua.create_table()?;
let uri = req.req.uri();
let scheme = match uri.scheme_str() {
Some(scheme) => scheme,
None if req.tls => "https",
None => "http",
};
let authority = uri.authority().cloned().or_else(|| {
req.req
.headers()
.get(hyper::header::HOST)?
.to_str()
.ok()?
.parse::<hyper::http::uri::Authority>()
.ok()
});
let default_port = if scheme == "https" { 443 } else { 80 };
table.set("scheme", scheme)?;
table.set("host", authority.as_ref().map_or("", |a| a.host()))?;
table.set(
"port",
authority
.as_ref()
.map_or(0, |a| a.port_u16().unwrap_or(default_port)),
)?;
table.set("path", uri.path())?;
table.set("authority", authority.as_ref().map_or("", |a| a.as_str()))?;
table.set("query", uri.query().unwrap_or_default())?;
Ok(table)
});
fields.add_field_method_get("headers", |lua, req| {
let headers = req.req.headers();
let table = lua.create_table()?;
for (k, v) in headers.iter() {
table.set(k.as_str(), v.to_str().unwrap_or_default())?;
}
Ok(table)
});
fields.add_field_method_get("valid", |_, req| Ok(req.valid.clone()));
fields.add_field_method_get("cookies", |_, req| {
let header = req
.req
.headers()
.get_all(hyper::header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.collect::<Vec<_>>()
.join("; ");
Ok(nitr_std::RequestCookies::parse(&header))
});
}
fn add_methods<'lua, M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_method("accepts", |_, req, offers: mlua::Variadic<String>| {
let accept = req
.req
.headers()
.get(hyper::header::ACCEPT)
.and_then(|v| v.to_str().ok())
.unwrap_or("*/*");
let refs: Vec<&str> = offers.iter().map(String::as_str).collect();
Ok(nitr_std::best_match(accept, &refs).map(|i| offers[i].clone()))
});
methods.add_async_method_mut("read", |lua, mut req, n: Option<i64>| async move {
let body_limit = req.body_limit;
let reader = req.req.body_mut();
let Some(want) = n else {
while let Some(frame) = reader.frame().await {
if let Some(bytes) = frame.into_lua_err()?.data_ref() {
return Some(lua.create_string(bytes)).transpose();
}
}
return Ok(None);
};
if want < 0 {
return Err(mlua::Error::RuntimeError(format!(
"req:read(n) requires a non-negative size, got {want}"
)));
}
let want = clamp_want(usize::try_from(want).unwrap_or(usize::MAX), body_limit);
let mut buf = Vec::new();
while buf.len() < want {
let Some(frame) = reader.frame().await else {
break;
};
if let Some(bytes) = frame.into_lua_err()?.data_ref() {
buf.extend_from_slice(bytes);
}
}
if buf.is_empty() {
return Ok(None);
}
Some(lua.create_string(buf)).transpose()
});
methods.add_async_method_mut("form", |lua, mut req, ()| async move {
if req.cached_form.is_none() {
let body = req.whole_body().await?;
req.cached_form = Some(
url::form_urlencoded::parse(&body)
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect(),
);
}
let table = lua.create_table()?;
for (k, v) in req.cached_form.as_deref().unwrap_or_default() {
table.set(k.as_str(), v.as_str())?;
}
Ok(table)
});
#[cfg(feature = "multipart")]
methods.add_async_method_mut("multipart", |lua, mut req, cb: mlua::Function| async move {
if req.body_consumed {
return Err(mlua::Error::RuntimeError(
"req:multipart() cannot run on a route whose `input` already consumed the \
body: read the validated files from req.valid instead"
.into(),
));
}
let content_type = req
.req
.headers()
.get(hyper::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let boundary = crate::multipart::boundary(content_type.as_deref())?;
let limits = req.limits.clone();
let body = std::mem::take(req.req.body_mut());
let mut parser = multer::Multipart::new(body.into_data_stream(), boundary);
let mut count = 0usize;
loop {
let Some(field) = parser.next_field().await.into_lua_err()? else {
break;
};
count += 1;
if count > limits.max_parts {
return Err(crate::multipart::too_many_parts(limits.max_parts));
}
let part = lua.create_userdata(crate::multipart::LuaPart::new(
field,
limits.max_field_bytes,
limits.max_file_bytes,
limits.upload_root.clone(),
))?;
let outcome = cb.call_async::<()>(&part).await;
if let Ok(part) = part.borrow::<crate::multipart::LuaPart>()
&& let Some(mut field) = part.reclaim()
{
while field.chunk().await.into_lua_err()?.is_some() {}
}
outcome?;
}
Ok(count)
});
methods.add_method(
"fresh",
|_, req, (etag, last_modified): (Option<String>, Option<i64>)| {
Ok(is_fresh(req.req.headers(), etag.as_deref(), last_modified))
},
);
methods.add_async_method_mut("text", |lua, mut req, ()| async move {
lua.create_string(req.whole_body().await?)
});
methods.add_async_method_mut("json", |lua, mut req, ()| async move {
let buf = req.whole_body().await?;
if buf.is_empty() {
return Err(mlua::Error::external(
"Unexpected end of JSON input, probably request body is empty or already consumed",
));
}
let json = serde_json::from_slice::<SerdeValue>(&buf).into_lua_err()?;
lua.to_value(&json)
});
}
}