use std::convert::Infallible;
use http_body_util::{BodyExt as _, Empty, Full, combinators::BoxBody};
use hyper::body::Bytes;
use hyper::{Response, StatusCode, header};
use mlua::{LuaString, Table as LuaTable, Value as LuaValue};
use super::HttpResponse;
use nitr_core::{Error, Result};
pub(crate) fn empty_response(status: StatusCode) -> Result<HttpResponse> {
Ok(Response::builder()
.status(status)
.body(Empty::<Bytes>::new().boxed())?)
}
pub(crate) fn wants_json(headers: &hyper::HeaderMap) -> bool {
headers
.get(header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|accept| accept.contains("application/json"))
}
pub(crate) fn rejection(
status: StatusCode,
code: &'static str,
retry_after: Option<u64>,
wants_json: bool,
) -> Result<HttpResponse> {
let message = status.canonical_reason().unwrap_or("Error");
let mut resp = if wants_json {
let mut body = serde_json::json!({ "code": code, "message": message });
if let Some(secs) = retry_after {
body["retry_after"] = serde_json::Value::from(secs);
}
let bytes = serde_json::to_vec(&body).map_err(|err| Error::Script(err.to_string()))?;
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "application/json")
.body(Full::new(Bytes::from(bytes)).boxed())?
} else {
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(Full::new(Bytes::from_static(message.as_bytes())).boxed())?
};
if let Some(secs) = retry_after
&& let Ok(value) = header::HeaderValue::from_str(&secs.to_string())
{
resp.headers_mut().insert(header::RETRY_AFTER, value);
}
Ok(resp)
}
pub(crate) fn rate_limited(retry_after: u64, wants_json: bool) -> Result<HttpResponse> {
rejection(
StatusCode::TOO_MANY_REQUESTS,
"RATE_LIMITED",
Some(retry_after),
wants_json,
)
}
pub(crate) fn plain_response(status: StatusCode, body: &'static str) -> Result<HttpResponse> {
Ok(Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(Full::new(Bytes::from_static(body.as_bytes())).boxed())?)
}
pub(super) fn to_response(lua_resp: LuaTable) -> Result<HttpResponse> {
let body = lua_resp.raw_get::<Option<LuaString>>("body")?;
let len = body.as_ref().map_or(0, |b| b.as_bytes().len());
let body = body
.map(|b| Full::new(Bytes::copy_from_slice(&b.as_bytes())).boxed())
.unwrap_or_else(|| Empty::<Bytes>::new().boxed());
let resp = build_response(&lua_resp, body)?;
reject_forbidden_body(resp.status(), len)?;
Ok(resp)
}
fn reject_forbidden_body(status: StatusCode, len: usize) -> Result {
if len == 0 {
return Ok(());
}
if status == StatusCode::NO_CONTENT
|| status == StatusCode::NOT_MODIFIED
|| status.is_informational()
{
return Err(Error::Script(format!(
"a {status} response must not carry a body ({len} bytes given): \
the status says there is nothing to read, and a client that \
believes it would parse the body as the next response"
)));
}
Ok(())
}
pub(crate) fn build_response(
lua_resp: &LuaTable,
body: BoxBody<Bytes, Infallible>,
) -> Result<HttpResponse> {
use hyper::header::{HeaderName, HeaderValue};
let status = lua_resp
.raw_get::<Option<u16>>("status")?
.unwrap_or(hyper::StatusCode::OK.as_u16());
let mut resp = Response::builder().status(status).body(body)?;
if let Some(headers) = lua_resp.raw_get::<Option<LuaTable>>("headers")? {
let map = resp.headers_mut();
let invalid_value = |name: &HeaderName| {
mlua::Error::RuntimeError(format!("invalid value for header `{name}`"))
};
headers.for_each(|name: LuaString, value: LuaValue| {
let name = HeaderName::from_bytes(&name.as_bytes()).map_err(|_| {
mlua::Error::RuntimeError(format!("invalid header name `{}`", name.display()))
})?;
match value {
LuaValue::String(v) => {
let v =
HeaderValue::from_bytes(&v.as_bytes()).map_err(|_| invalid_value(&name))?;
map.append(name, v);
}
LuaValue::Integer(v) => {
map.append(name, HeaderValue::from(v));
}
LuaValue::Table(values) => {
for v in values.sequence_values::<LuaString>() {
let v = HeaderValue::from_bytes(&v?.as_bytes())
.map_err(|_| invalid_value(&name))?;
map.append(name.clone(), v);
}
}
other => {
return Err(mlua::Error::RuntimeError(format!(
"invalid value type `{}` for header `{name}`: \
expected a string, an integer or an array of strings",
other.type_name()
)));
}
}
Ok(())
})?;
}
match lua_resp.raw_get::<LuaValue>("cookies")? {
LuaValue::Nil => {}
LuaValue::UserData(ud) => {
let cookies = ud.borrow::<nitr_std::ResponseCookies>().map_err(|_| {
Error::Script("the response `cookies` field is not a cookie builder".into())
})?;
for value in cookies.values() {
let value = HeaderValue::from_str(&value).map_err(|_| {
let name = value.split('=').next().unwrap_or_default();
Error::Script(format!(
"invalid Set-Cookie value for cookie `{name}` (a control character \
in one of its attributes?)"
))
})?;
resp.headers_mut().append(hyper::header::SET_COOKIE, value);
}
}
other => {
return Err(Error::Script(format!(
"invalid `cookies` field of type `{}` in the response table",
other.type_name()
)));
}
}
Ok(resp)
}