const MAX_FIELDS: usize = 64;
pub(crate) const MAX_REASON: usize = 200;
#[derive(Debug, Default, Clone)]
pub struct FormFields {
fields: Vec<(String, String)>,
}
impl FormFields {
pub fn parse(encoded: &str) -> Self {
let mut fields = Vec::new();
for pair in encoded.split('&') {
if pair.is_empty() || fields.len() >= MAX_FIELDS {
continue;
}
let (name, value) = match pair.split_once('=') {
Some((name, value)) => (name, value),
None => (pair, ""),
};
fields.push((decode(name), decode(value)));
}
Self { fields }
}
pub fn get(&self, name: &str) -> Option<&str> {
self.fields
.iter()
.find(|(field, _)| field == name)
.map(|(_, value)| value.as_str())
}
pub fn all<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
self.fields
.iter()
.filter(move |(field, _)| field == name)
.map(|(_, value)| value.as_str())
}
pub fn len(&self) -> usize {
self.fields.len()
}
pub fn is_empty(&self) -> bool {
self.fields.is_empty()
}
}
fn decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut index = 0;
while let Some(&byte) = bytes.get(index) {
match byte {
b'+' => {
out.push(b' ');
index += 1;
}
b'%' => {
let pair = bytes
.get(index + 1..index + 3)
.and_then(|pair| std::str::from_utf8(pair).ok())
.and_then(|pair| u8::from_str_radix(pair, 16).ok());
match pair {
Some(decoded) => {
out.push(decoded);
index += 3;
}
None => {
out.push(b'%');
index += 1;
}
}
}
other => {
out.push(other);
index += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
#[derive(Debug, Clone, Copy)]
pub struct InputRequest<'a> {
pub path: &'a str,
pub query: Option<&'a str>,
pub fields: &'a FormFields,
pub identity: Option<&'a str>,
pub peer: std::net::IpAddr,
}
#[derive(Debug, Clone)]
pub enum InputOutcome {
Render {
path: String,
query: Option<String>,
session: crate::session::SessionChange,
},
Rejected(String),
}
impl InputOutcome {
pub fn render(path: impl Into<String>) -> Self {
Self::Render {
path: path.into(),
query: None,
session: crate::session::SessionChange::none(),
}
}
pub fn render_query(path: impl Into<String>, query: impl Into<String>) -> Self {
Self::Render {
path: path.into(),
query: Some(query.into()),
session: crate::session::SessionChange::none(),
}
}
pub fn with_session(self, change: crate::session::SessionChange) -> Self {
match self {
Self::Render { path, query, .. } => Self::Render {
path,
query,
session: change,
},
rejected @ Self::Rejected(_) => rejected,
}
}
}
pub trait InputHandler: Send + Sync {
fn handle(&self, request: &InputRequest<'_>) -> InputOutcome;
}
pub(crate) fn short_reason(reason: &str) -> String {
if reason.chars().count() <= MAX_REASON {
return reason.to_string();
}
let kept: String = reason.chars().take(MAX_REASON - 1).collect();
format!("{kept}…")
}
pub(crate) fn split_query(action: &str) -> (&str, Option<&str>) {
match action.split_once('?') {
Some((path, query)) if !query.is_empty() => (path, Some(query)),
Some((path, _)) => (path, None),
None => (action, None),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_simple_submission() {
let fields = FormFields::parse("title=Hello&url=atp%3A%2F%2Fx.dust");
assert_eq!(fields.get("title"), Some("Hello"));
assert_eq!(fields.get("url"), Some("atp://x.dust"));
assert_eq!(fields.len(), 2);
}
#[test]
fn plus_is_a_space() {
let fields = FormFields::parse("q=hello+world");
assert_eq!(fields.get("q"), Some("hello world"));
}
#[test]
fn multibyte_escapes_reassemble() {
let fields = FormFields::parse("t=caf%C3%A9+%E2%98%85");
assert_eq!(fields.get("t"), Some("café ★"));
}
#[test]
fn duplicate_names_are_all_retained_in_order() {
let fields = FormFields::parse("tag=a&tag=b&tag=c");
assert_eq!(fields.all("tag").collect::<Vec<_>>(), ["a", "b", "c"]);
assert_eq!(fields.get("tag"), Some("a"), "get returns the first");
}
#[test]
fn malformed_input_decodes_as_far_as_it_can() {
let fields = FormFields::parse("bare&a=%zz&b=%&c=x");
assert_eq!(fields.get("bare"), Some(""), "no = means empty value");
assert_eq!(fields.get("a"), Some("%zz"), "not hex, so not an escape");
assert_eq!(fields.get("b"), Some("%"), "truncated escape");
assert_eq!(fields.get("c"), Some("x"));
}
#[test]
fn field_count_is_bounded() {
let encoded = (0..MAX_FIELDS * 4)
.map(|index| format!("f{index}=v"))
.collect::<Vec<_>>()
.join("&");
assert_eq!(FormFields::parse(&encoded).len(), MAX_FIELDS);
}
#[test]
fn an_empty_body_is_no_fields() {
assert!(FormFields::parse("").is_empty());
}
#[test]
fn an_over_long_reason_is_truncated() {
let short = "a title is required";
assert_eq!(short_reason(short), short);
let diagnostic = "could not send mail: transient error (421): 4.7.0 Try again \
later, closing connection. (EHLO) For more information, go to \
https://support.google.com/a/answer/3221692 \
5b1f17b1804b1-499c2fb02ecsm5772355e9.4 - gsmtp";
let trimmed = short_reason(diagnostic);
assert!(trimmed.chars().count() <= MAX_REASON);
assert!(trimmed.ends_with('…'), "{trimmed}");
}
#[test]
fn truncation_lands_on_a_character_boundary() {
let reason = "é".repeat(MAX_REASON * 2);
let trimmed = short_reason(&reason);
assert!(trimmed.chars().count() <= MAX_REASON);
assert!(trimmed.is_char_boundary(trimmed.len()));
}
#[test]
fn an_action_query_is_split_off() {
assert_eq!(split_query("/index?reply=12"), ("/index", Some("reply=12")));
assert_eq!(split_query("/index"), ("/index", None));
assert_eq!(split_query("/index?"), ("/index", None));
}
#[test]
fn a_refusal_cannot_carry_a_session() {
let outcome = InputOutcome::Rejected("nope".into())
.with_session(crate::session::SessionChange::set("t", "/", 1));
assert!(matches!(outcome, InputOutcome::Rejected(_)));
}
#[test]
fn a_session_attaches_to_an_acceptance() {
let outcome =
InputOutcome::render("/").with_session(crate::session::SessionChange::set("t", "/", 1));
match outcome {
InputOutcome::Render { session, .. } => assert!(!session.is_empty()),
other => panic!("expected Render, got {other:?}"),
}
}
#[test]
fn outcome_constructors_carry_the_query() {
match InputOutcome::render("/index") {
InputOutcome::Render { path, query, .. } => {
assert_eq!(path, "/index");
assert_eq!(query, None);
}
other => panic!("expected Render, got {other:?}"),
}
match InputOutcome::render_query("/index", "item=7") {
InputOutcome::Render { path, query, .. } => {
assert_eq!(path, "/index");
assert_eq!(query.as_deref(), Some("item=7"));
}
other => panic!("expected Render, got {other:?}"),
}
}
#[test]
fn hostile_values_are_delivered_verbatim() {
let hostile = r#"x" ][form action="/login"]"#;
let encoded = format!(
"title={}",
hostile
.bytes()
.map(|byte| format!("%{byte:02X}"))
.collect::<String>()
);
assert_eq!(FormFields::parse(&encoded).get("title"), Some(hostile));
}
}