487 lines
20 KiB
Rust
487 lines
20 KiB
Rust
//! The host's HTTP side (`docs/PROTOCOL.md` section 1): strict parsing of an incoming `GET` request head and its
|
|
//! query into a typed [`Route`], and the XML answers ([`answer`]).
|
|
//!
|
|
//! Every request is hostile input. Caps are checked before anything is allocated: the head
|
|
//! ([`MAX_HEAD_BYTES`]), the target ([`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`]), the number of parameters
|
|
//! ([`MAX_PARAMS`]) and each name and value ([`MAX_PARAM_NAME_BYTES`], [`MAX_PARAM_VALUE_BYTES`]), then each typed
|
|
//! field's own limit. A request never carries a body; a `Content-Length` other than 0 or any `Transfer-Encoding` is
|
|
//! refused.
|
|
//!
|
|
//! Callers whose HTTP server already split the head (TLS front end, an HTTP library) pass the request target to
|
|
//! [`parse_target`]; callers reading the raw TCP stream cut the head with [`find_head_end`] and pass it to
|
|
//! [`parse_request_head`].
|
|
|
|
use crate::host::pairing::{PairPhase, PairRequest};
|
|
use crate::http::check_unique_id;
|
|
use crate::keys::RIKEY_LEN;
|
|
use crate::pairing::SALT_LEN;
|
|
use crate::util::{cap, hex_decode, hex_digit, malformed, parse_dec, parse_u32, percent_encode};
|
|
use crate::{Error, Result, SessionKeys};
|
|
|
|
pub mod answer;
|
|
|
|
pub use answer::{HostInfo, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, resume_xml, server_info_xml};
|
|
|
|
/// Maximum size of a request head (request line, headers and the empty line), in bytes.
|
|
pub const MAX_HEAD_BYTES: usize = 64 * 1024;
|
|
/// Maximum number of header lines.
|
|
pub const MAX_HEADERS: usize = 64;
|
|
/// Maximum length of the path (before `?`), in bytes.
|
|
pub const MAX_PATH_BYTES: usize = 256;
|
|
/// Maximum length of the query (after `?`), in bytes. Room for a phase-1 `clientcert` at its cap.
|
|
pub const MAX_QUERY_BYTES: usize = 40 * 1024;
|
|
/// Maximum number of query parameters.
|
|
pub const MAX_PARAMS: usize = 32;
|
|
/// Maximum length of a parameter name, in bytes.
|
|
pub const MAX_PARAM_NAME_BYTES: usize = 64;
|
|
/// Maximum length of one parameter value as sent (percent-encoded), in bytes: a hex `clientcert` at
|
|
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`].
|
|
pub const MAX_PARAM_VALUE_BYTES: usize = 2 * crate::pairing::identity::MAX_CERT_PEM_BYTES;
|
|
/// Maximum length of a hex value other than `clientcert`, in characters (16 bytes of secret plus an RSA-8192
|
|
/// signature).
|
|
pub const MAX_HEX_VALUE_CHARS: usize = 2 * (crate::pairing::SECRET_LEN + crate::pairing::MAX_SIGNATURE_BYTES);
|
|
/// Maximum length of `devicename`, in bytes.
|
|
pub const MAX_DEVICE_NAME_BYTES: usize = crate::host::pairing::MAX_PAIR_DEVICE_NAME_BYTES;
|
|
/// Largest width or height accepted in `mode`.
|
|
pub const MAX_MODE_DIMENSION: u32 = 16_384;
|
|
/// Largest frame rate accepted in `mode`.
|
|
pub const MAX_MODE_FPS: u32 = 1000;
|
|
|
|
/// A stream mode, `mode=<width>x<height>x<fps>`.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub struct DisplayMode {
|
|
/// Width in pixels, 1..=[`MAX_MODE_DIMENSION`].
|
|
pub width: u32,
|
|
/// Height in pixels, 1..=[`MAX_MODE_DIMENSION`].
|
|
pub height: u32,
|
|
/// Frames per second, 1..=[`MAX_MODE_FPS`].
|
|
pub fps: u32,
|
|
}
|
|
|
|
/// `GET /launch` (`docs/PROTOCOL.md` 1.4).
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct LaunchRequest {
|
|
/// `appid`.
|
|
pub app_id: u32,
|
|
/// `mode`.
|
|
pub mode: DisplayMode,
|
|
/// `rikey` and `rikeyid`.
|
|
pub keys: SessionKeys,
|
|
/// `hdrMode`, if sent.
|
|
pub hdr: Option<bool>,
|
|
/// `surroundAudioInfo`, if sent: `(channel_mask << 16) | channel_count`.
|
|
pub surround_audio_info: Option<u32>,
|
|
}
|
|
|
|
/// `GET /resume` (`docs/PROTOCOL.md` 1.4): fresh keys; the launch parameters only if the client repeats them.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct ResumeRequest {
|
|
/// `rikey` and `rikeyid`.
|
|
pub keys: SessionKeys,
|
|
/// `appid`, if sent.
|
|
pub app_id: Option<u32>,
|
|
/// `mode`, if sent.
|
|
pub mode: Option<DisplayMode>,
|
|
/// `hdrMode`, if sent.
|
|
pub hdr: Option<bool>,
|
|
/// `surroundAudioInfo`, if sent.
|
|
pub surround_audio_info: Option<u32>,
|
|
}
|
|
|
|
/// What the request asks for.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum Route {
|
|
/// `/serverinfo` (HTTP or HTTPS).
|
|
ServerInfo,
|
|
/// `/applist` (HTTPS).
|
|
AppList,
|
|
/// `/launch` (HTTPS).
|
|
Launch(LaunchRequest),
|
|
/// `/resume` (HTTPS).
|
|
Resume(ResumeRequest),
|
|
/// `/cancel` (HTTPS).
|
|
Cancel,
|
|
/// `/pair` (phases 1-4 over HTTP, phase 5 over HTTPS); feed it to [`crate::host::pairing::HostPairingSession`].
|
|
Pair(PairRequest),
|
|
/// `/unpair` (HTTPS).
|
|
Unpair,
|
|
/// `/appasset` (HTTPS): box art of one app.
|
|
AppAsset {
|
|
/// `appid`.
|
|
app_id: u32,
|
|
},
|
|
/// Any other path (answer 404). The path as sent, never decoded, never used to open anything.
|
|
Unknown {
|
|
/// The path.
|
|
path: String,
|
|
},
|
|
}
|
|
|
|
/// One parsed request.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct HostRequest {
|
|
/// The route and its typed parameters.
|
|
pub route: Route,
|
|
/// `uniqueid`, if sent (required for `/pair`).
|
|
pub unique_id: Option<String>,
|
|
/// Parameters this parser does not know, decoded, in order: kept for logs so black-box clients can be measured
|
|
/// (`docs/PROTOCOL.md` UNKNOWN U4). Never used to decide anything.
|
|
pub other_params: Vec<(String, String)>,
|
|
}
|
|
|
|
/// The empty line that ends a head.
|
|
const HEAD_END: &[u8] = b"\r\n\r\n";
|
|
|
|
/// Finds the end of a request head in the bytes read so far: `Some(len)` (the head is `buf[..len]`, ending in the
|
|
/// empty line) or `None` (read more).
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] when no head end is within the first [`MAX_HEAD_BYTES`] (so a buffer of that size without
|
|
/// one is refused: the head could only end past the cap).
|
|
pub fn find_head_end(buf: &[u8]) -> Result<Option<usize>> {
|
|
let window = buf.get(..MAX_HEAD_BYTES).unwrap_or(buf);
|
|
if let Some(at) = window.windows(HEAD_END.len()).position(|w| w == HEAD_END) {
|
|
return Ok(Some(at + HEAD_END.len()));
|
|
}
|
|
if buf.len() >= MAX_HEAD_BYTES {
|
|
return Err(Error::TooLarge { what: "http request head", max: MAX_HEAD_BYTES, actual: buf.len() });
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
/// RFC 9110 `tchar`.
|
|
fn is_token(b: u8) -> bool {
|
|
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
|
|
}
|
|
|
|
/// Parses one complete request head (`GET <target> HTTP/1.1`, headers, the empty line, nothing after it).
|
|
///
|
|
/// Only visible ASCII, space and tab are accepted inside lines, every line ends in CRLF, header lines are never
|
|
/// folded, and header names are tokens. Headers are otherwise ignored (the host needs none of them), except that a
|
|
/// `Content-Length` other than `0` or any `Transfer-Encoding` is refused: a `GET` here never carries a body.
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] over [`MAX_HEAD_BYTES`], [`MAX_HEADERS`] or a target cap, [`Error::Unsupported`] for a
|
|
/// method other than `GET`, [`Error::Malformed`] for anything else that is not a strict HTTP/1.x head or a valid
|
|
/// target (see [`parse_target`]).
|
|
pub fn parse_request_head(head: &[u8]) -> Result<HostRequest> {
|
|
cap("http request head", MAX_HEAD_BYTES, head.len())?;
|
|
let end = head.windows(HEAD_END.len()).position(|w| w == HEAD_END).ok_or(malformed("http head: no empty line"))?;
|
|
if end + HEAD_END.len() != head.len() {
|
|
return Err(malformed("http head: bytes after the empty line"));
|
|
}
|
|
if !head.iter().all(|&b| matches!(b, b' '..=b'~' | b'\t' | b'\r' | b'\n')) {
|
|
return Err(malformed("http head: a byte that is not visible ASCII"));
|
|
}
|
|
let text = core::str::from_utf8(head.get(..end).unwrap_or(&[])).map_err(|_| malformed("http head: not ASCII"))?;
|
|
let mut lines = text.split("\r\n");
|
|
let request_line = lines.next().unwrap_or("");
|
|
if request_line.contains(['\r', '\n']) {
|
|
return Err(malformed("http head: bare CR or LF"));
|
|
}
|
|
let mut parts = request_line.split(' ');
|
|
let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next())
|
|
else {
|
|
return Err(malformed("http request line"));
|
|
};
|
|
if method.is_empty() || !method.bytes().all(is_token) || target.is_empty() {
|
|
return Err(malformed("http request line"));
|
|
}
|
|
if version != "HTTP/1.1" && version != "HTTP/1.0" {
|
|
return Err(malformed("http version"));
|
|
}
|
|
if method != "GET" {
|
|
return Err(Error::Unsupported { what: "http method other than GET" });
|
|
}
|
|
let mut count = 0usize;
|
|
let mut content_length = false;
|
|
for line in lines {
|
|
count += 1;
|
|
cap("http headers", MAX_HEADERS, count)?;
|
|
if line.contains(['\r', '\n']) {
|
|
return Err(malformed("http head: bare CR or LF"));
|
|
}
|
|
if line.starts_with([' ', '\t']) {
|
|
return Err(malformed("http head: folded header line"));
|
|
}
|
|
let (name, value) = line.split_once(':').ok_or(malformed("http header without :"))?;
|
|
if name.is_empty() || !name.bytes().all(is_token) {
|
|
return Err(malformed("http header name"));
|
|
}
|
|
let value = value.trim_matches([' ', '\t']);
|
|
if name.eq_ignore_ascii_case("content-length") {
|
|
if content_length || value != "0" {
|
|
return Err(malformed("http head: a body on a GET"));
|
|
}
|
|
content_length = true;
|
|
} else if name.eq_ignore_ascii_case("transfer-encoding") {
|
|
return Err(malformed("http head: a body on a GET"));
|
|
}
|
|
}
|
|
parse_target(target)
|
|
}
|
|
|
|
/// The parsed parameters; typed fields are taken out one by one, the rest stays for [`HostRequest::other_params`].
|
|
struct Params(Vec<(String, String)>);
|
|
|
|
impl Params {
|
|
fn take(&mut self, name: &str) -> Option<String> {
|
|
let at = self.0.iter().position(|(n, _)| n == name)?;
|
|
Some(self.0.remove(at).1)
|
|
}
|
|
|
|
fn require(&mut self, name: &str, what: &'static str) -> Result<String> {
|
|
self.take(name).ok_or(malformed(what))
|
|
}
|
|
}
|
|
|
|
/// `<width>x<height>x<fps>`, each strict decimal and in range.
|
|
fn parse_mode(s: &str) -> Result<DisplayMode> {
|
|
let mut parts = s.split('x');
|
|
let (Some(w), Some(h), Some(f), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
|
|
return Err(malformed("mode"));
|
|
};
|
|
let (width, height, fps) = (parse_u32("mode", w)?, parse_u32("mode", h)?, parse_u32("mode", f)?);
|
|
let dims = 1..=MAX_MODE_DIMENSION;
|
|
if !dims.contains(&width) || !dims.contains(&height) || !(1..=MAX_MODE_FPS).contains(&fps) {
|
|
return Err(malformed("mode out of range"));
|
|
}
|
|
Ok(DisplayMode { width, height, fps })
|
|
}
|
|
|
|
/// `rikeyid`: unsigned decimal, or a negative 32-bit decimal read as its two's complement (tolerated: a client
|
|
/// may print the id as a signed integer; the bytes on the wire are the same).
|
|
fn parse_rikeyid(s: &str) -> Result<u32> {
|
|
match s.strip_prefix('-') {
|
|
Some(digits) => {
|
|
let v = parse_dec("rikeyid", digits)?;
|
|
if v == 0 || v > 1 << 31 {
|
|
return Err(malformed("rikeyid"));
|
|
}
|
|
Ok(0u32.wrapping_sub(u32::try_from(v).map_err(|_| malformed("rikeyid"))?))
|
|
}
|
|
None => parse_u32("rikeyid", s),
|
|
}
|
|
}
|
|
|
|
/// `rikey` (exactly 32 hex digits) and `rikeyid`, both required.
|
|
fn parse_keys(p: &mut Params) -> Result<SessionKeys> {
|
|
let rikey = p.require("rikey", "no rikey")?;
|
|
if rikey.len() != 2 * RIKEY_LEN {
|
|
return Err(malformed("rikey"));
|
|
}
|
|
let bytes = hex_decode("rikey", &rikey)?;
|
|
let rikey = crate::util::array::<RIKEY_LEN>("rikey", &bytes, 0)?;
|
|
let rikeyid = parse_rikeyid(&p.require("rikeyid", "no rikeyid")?)?;
|
|
Ok(SessionKeys { rikey, rikeyid })
|
|
}
|
|
|
|
fn parse_flag(what: &'static str, s: &str) -> Result<bool> {
|
|
match s {
|
|
"0" => Ok(false),
|
|
"1" => Ok(true),
|
|
_ => Err(malformed(what)),
|
|
}
|
|
}
|
|
|
|
/// `hdrMode` and `surroundAudioInfo`, both optional.
|
|
fn parse_stream_options(p: &mut Params) -> Result<(Option<bool>, Option<u32>)> {
|
|
let hdr = p.take("hdrMode").map(|v| parse_flag("hdrMode", &v)).transpose()?;
|
|
let audio = p.take("surroundAudioInfo").map(|v| parse_u32("surroundAudioInfo", &v)).transpose()?;
|
|
Ok((hdr, audio))
|
|
}
|
|
|
|
fn parse_launch(p: &mut Params) -> Result<LaunchRequest> {
|
|
let app_id = parse_u32("appid", &p.require("appid", "no appid")?)?;
|
|
let mode = parse_mode(&p.require("mode", "no mode")?)?;
|
|
let keys = parse_keys(p)?;
|
|
let (hdr, surround_audio_info) = parse_stream_options(p)?;
|
|
Ok(LaunchRequest { app_id, mode, keys, hdr, surround_audio_info })
|
|
}
|
|
|
|
fn parse_resume(p: &mut Params) -> Result<ResumeRequest> {
|
|
let keys = parse_keys(p)?;
|
|
let app_id = p.take("appid").map(|v| parse_u32("appid", &v)).transpose()?;
|
|
let mode = p.take("mode").map(|v| parse_mode(&v)).transpose()?;
|
|
let (hdr, surround_audio_info) = parse_stream_options(p)?;
|
|
Ok(ResumeRequest { keys, app_id, mode, hdr, surround_audio_info })
|
|
}
|
|
|
|
/// A non-empty hex value of at most `max` characters.
|
|
fn pair_hex(what: &'static str, s: &str, max: usize) -> Result<Vec<u8>> {
|
|
cap(what, max, s.len())?;
|
|
if s.is_empty() {
|
|
return Err(malformed(what));
|
|
}
|
|
hex_decode(what, s)
|
|
}
|
|
|
|
/// The phase of a `/pair` request (`docs/PROTOCOL.md` 1.5): `phrase=getservercert` (with `salt` and `clientcert`),
|
|
/// `phrase=pairchallenge`, or exactly one of `clientchallenge`, `serverchallengeresp`, `clientpairingsecret`.
|
|
fn parse_pair(p: &mut Params, unique_id: Option<&str>) -> Result<PairRequest> {
|
|
let unique_id = unique_id.ok_or(malformed("pair: no uniqueid"))?.to_owned();
|
|
let device_name = match p.take("devicename") {
|
|
Some(d) => {
|
|
cap("devicename", MAX_DEVICE_NAME_BYTES, d.len())?;
|
|
Some(d).filter(|d| !d.is_empty())
|
|
}
|
|
None => None,
|
|
};
|
|
let phrase = p.take("phrase");
|
|
let salt = p.take("salt");
|
|
let cert = p.take("clientcert");
|
|
let challenge = p.take("clientchallenge");
|
|
let response = p.take("serverchallengeresp");
|
|
let secret = p.take("clientpairingsecret");
|
|
let phase = match (phrase.as_deref(), challenge, response, secret) {
|
|
(Some("getservercert"), None, None, None) => {
|
|
let salt = salt.ok_or(malformed("pair: no salt"))?;
|
|
if salt.len() != 2 * SALT_LEN {
|
|
return Err(malformed("pair: salt"));
|
|
}
|
|
let salt = crate::util::array::<SALT_LEN>("pair: salt", &hex_decode("pair: salt", &salt)?, 0)?;
|
|
let cert = cert.ok_or(malformed("pair: no clientcert"))?;
|
|
let client_cert_pem = pair_hex("pair: clientcert", &cert, MAX_PARAM_VALUE_BYTES)?;
|
|
return Ok(PairRequest {
|
|
unique_id,
|
|
device_name,
|
|
phase: PairPhase::GetServerCert { salt, client_cert_pem },
|
|
});
|
|
}
|
|
(Some("pairchallenge"), None, None, None) => PairPhase::PairChallenge,
|
|
(None, Some(v), None, None) => {
|
|
PairPhase::ClientChallenge(pair_hex("clientchallenge", &v, MAX_HEX_VALUE_CHARS)?)
|
|
}
|
|
(None, None, Some(v), None) => {
|
|
PairPhase::ServerChallengeResp(pair_hex("serverchallengeresp", &v, MAX_HEX_VALUE_CHARS)?)
|
|
}
|
|
(None, None, None, Some(v)) => {
|
|
PairPhase::ClientPairingSecret(pair_hex("clientpairingsecret", &v, MAX_HEX_VALUE_CHARS)?)
|
|
}
|
|
_ => return Err(malformed("pair: not exactly one known phase")),
|
|
};
|
|
if salt.is_some() || cert.is_some() {
|
|
return Err(malformed("pair: salt or clientcert outside getservercert"));
|
|
}
|
|
Ok(PairRequest { unique_id, device_name, phase })
|
|
}
|
|
|
|
/// Parses a request target (`/path?query`) into a typed request.
|
|
///
|
|
/// The path is matched exactly (case-sensitive, never decoded); an unknown path is [`Route::Unknown`]. The target
|
|
/// must be visible ASCII without a fragment. `uniqueid` is checked wherever it appears (letters, digits, `-`, `_`,
|
|
/// at most [`crate::http::MAX_UNIQUE_ID_BYTES`]).
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] over [`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`] or a parameter cap, [`Error::Malformed`] for a
|
|
/// bad character, a bad or repeated parameter, or a missing or bad required parameter of a known route.
|
|
pub fn parse_target(target: &str) -> Result<HostRequest> {
|
|
let (path, query) = match target.split_once('?') {
|
|
Some((path, query)) => (path, query),
|
|
None => (target, ""),
|
|
};
|
|
cap("http path", MAX_PATH_BYTES, path.len())?;
|
|
cap("http query", MAX_QUERY_BYTES, query.len())?;
|
|
if !path.starts_with('/') {
|
|
return Err(malformed("http target: not a path"));
|
|
}
|
|
if !target.bytes().all(|b| b.is_ascii_graphic() && b != b'#') {
|
|
return Err(malformed("http target: a character outside visible ASCII, or a fragment"));
|
|
}
|
|
let mut p = Params(parse_query(query)?);
|
|
let unique_id = p.take("uniqueid");
|
|
if let Some(u) = &unique_id {
|
|
check_unique_id(u)?;
|
|
}
|
|
let route = match path {
|
|
"/serverinfo" => Route::ServerInfo,
|
|
"/applist" => Route::AppList,
|
|
"/launch" => Route::Launch(parse_launch(&mut p)?),
|
|
"/resume" => Route::Resume(parse_resume(&mut p)?),
|
|
"/cancel" => Route::Cancel,
|
|
"/pair" => Route::Pair(parse_pair(&mut p, unique_id.as_deref())?),
|
|
"/unpair" => Route::Unpair,
|
|
"/appasset" => Route::AppAsset { app_id: parse_u32("appid", &p.require("appid", "no appid")?)? },
|
|
_ => Route::Unknown { path: path.to_owned() },
|
|
};
|
|
Ok(HostRequest { route, unique_id, other_params: p.0 })
|
|
}
|
|
|
|
/// One percent-decoded value: `%XX` (either case), `+` as a space, other visible ASCII as itself; UTF-8 without
|
|
/// control characters.
|
|
fn percent_decode(value: &str) -> Result<String> {
|
|
let b = value.as_bytes();
|
|
let mut out = Vec::with_capacity(b.len());
|
|
let mut i = 0;
|
|
while let Some(&c) = b.get(i) {
|
|
match c {
|
|
b'%' => {
|
|
let hi = b.get(i + 1).copied().and_then(hex_digit);
|
|
let lo = b.get(i + 2).copied().and_then(hex_digit);
|
|
let (Some(hi), Some(lo)) = (hi, lo) else { return Err(malformed("query: bad % escape")) };
|
|
out.push((hi << 4) | lo);
|
|
i += 3;
|
|
}
|
|
b'+' => {
|
|
out.push(b' ');
|
|
i += 1;
|
|
}
|
|
b'!'..=b'~' => {
|
|
out.push(c);
|
|
i += 1;
|
|
}
|
|
_ => return Err(malformed("query: a raw character outside visible ASCII")),
|
|
}
|
|
}
|
|
let s = String::from_utf8(out).map_err(|_| malformed("query: value is not UTF-8"))?;
|
|
if s.chars().any(char::is_control) {
|
|
return Err(malformed("query: control character in a value"));
|
|
}
|
|
Ok(s)
|
|
}
|
|
|
|
/// Parses a query string (without `?`) into decoded `(name, value)` pairs, in order. Names are taken as sent
|
|
/// (letters, digits, `_`, `-`, `.`); values are percent-decoded (`+` is a space) and must be UTF-8 without control
|
|
/// characters. Empty segments (`a=1&&b=2`) are skipped; a repeated name is refused.
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] over [`MAX_QUERY_BYTES`], [`MAX_PARAMS`], [`MAX_PARAM_NAME_BYTES`] or
|
|
/// [`MAX_PARAM_VALUE_BYTES`]; [`Error::Malformed`] otherwise.
|
|
pub fn parse_query(query: &str) -> Result<Vec<(String, String)>> {
|
|
cap("http query", MAX_QUERY_BYTES, query.len())?;
|
|
let segments = || query.split('&').filter(|s| !s.is_empty());
|
|
let count = segments().count();
|
|
cap("http query parameters", MAX_PARAMS, count)?;
|
|
let mut out: Vec<(String, String)> = Vec::with_capacity(count);
|
|
for segment in segments() {
|
|
let (name, value) = segment.split_once('=').unwrap_or((segment, ""));
|
|
cap("http parameter name", MAX_PARAM_NAME_BYTES, name.len())?;
|
|
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) {
|
|
return Err(malformed("query: parameter name"));
|
|
}
|
|
cap("http parameter value", MAX_PARAM_VALUE_BYTES, value.len())?;
|
|
if out.iter().any(|(n, _)| n == name) {
|
|
return Err(malformed("query: repeated parameter"));
|
|
}
|
|
let value = percent_decode(value)?;
|
|
out.push((name.to_owned(), value));
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Encodes `(name, value)` pairs as a query string (without `?`): values percent-encoded except RFC 3986 unreserved
|
|
/// characters, names as given. The inverse of [`parse_query`] for valid names and values.
|
|
#[must_use]
|
|
pub fn encode_query(params: &[(&str, &str)]) -> String {
|
|
let mut out = String::new();
|
|
for (i, (name, value)) in params.iter().enumerate() {
|
|
if i > 0 {
|
|
out.push('&');
|
|
}
|
|
out.push_str(name);
|
|
out.push('=');
|
|
out.push_str(&percent_encode(value));
|
|
}
|
|
out
|
|
}
|