use std::{
collections::VecDeque,
path::Path,
pin::Pin,
task::{Context, Poll},
};
use http::{
HeaderMap, HeaderValue,
header::{CONTENT_DISPOSITION, CONTENT_TYPE},
};
use http_body::{Body as _, Frame};
use mime::Mime;
use crate::{Body, Bytes, Error, Result};
pub struct Multipart {
parts: Vec<(String, Part)>,
}
pub struct Part {
content: Content,
file_name: Option<String>,
media_type: Option<String>,
headers: HeaderMap,
}
enum Content {
Text(String),
Bytes(Bytes),
Body(Body),
}
struct StreamPart {
prefix: Bytes,
body: Body,
}
struct PreparedPart {
prefix: Bytes,
content: PreparedContent,
}
enum PreparedContent {
Buffered(Bytes),
Streaming(Body),
}
struct MultipartStream {
parts: VecDeque<StreamPart>,
current: Option<Body>,
tail: Option<Bytes>,
failed: bool,
}
impl Multipart {
#[must_use]
pub const fn new() -> Self {
Self { parts: Vec::new() }
}
#[must_use]
pub fn text(self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.part(name, Part::text(value))
}
#[must_use]
pub fn part(mut self, name: impl Into<String>, part: Part) -> Self {
self.parts.push((name.into(), part));
self
}
pub(crate) fn into_body(self) -> Result<(Body, HeaderValue)> {
if self.parts.is_empty() {
return Err(Error::request("multipart body requires at least one part"));
}
let boundary = boundary();
let content_type = content_type(&boundary)?;
let parts = self
.parts
.into_iter()
.map(|(name, part)| part.into_prepared(&boundary, &name))
.collect::<Result<Vec<_>>>()?;
if parts
.iter()
.all(|part| matches!(part.content, PreparedContent::Buffered(_)))
{
return Ok((Body::from(encode_buffered(parts, &boundary)), content_type));
}
let length = encoded_length(&parts, &boundary);
let parts = parts
.into_iter()
.map(PreparedPart::into_streaming)
.collect::<VecDeque<_>>();
let body = Body::from_http_body(
MultipartStream {
parts,
current: None,
tail: Some(Bytes::from(format!("--{boundary}--\r\n"))),
failed: false,
},
|error| error,
);
let body = match length {
Some(length) => body.validate_length(length),
None => body,
};
Ok((body, content_type))
}
}
impl Default for Multipart {
fn default() -> Self {
Self::new()
}
}
impl Part {
#[must_use]
pub fn text(value: impl Into<String>) -> Self {
Self::new(Content::Text(value.into()))
}
#[must_use]
pub fn bytes(value: impl Into<Bytes>) -> Self {
Self::new(Content::Bytes(value.into()))
}
#[must_use]
pub fn body(body: Body) -> Self {
Self::new(Content::Body(body))
}
pub async fn file(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let file = async_fs::File::open(path)
.await
.map_err(|_| Error::request("multipart file could not be opened"))?;
let length = file
.metadata()
.await
.map_err(|_| Error::request("multipart file metadata could not be read"))?
.len();
let mut part = Self::body(Body::reader_with_length(file, length));
if let Some(file_name) = path.file_name().and_then(|name| name.to_str()) {
part.file_name = Some(file_name.to_owned());
}
Ok(part)
}
#[must_use]
pub fn file_name(mut self, value: impl Into<String>) -> Self {
self.file_name = Some(value.into());
self
}
#[must_use]
pub fn media_type(mut self, value: impl Into<String>) -> Self {
self.media_type = Some(value.into());
self
}
#[must_use]
pub fn headers(mut self, headers: HeaderMap) -> Self {
self.headers = headers;
self
}
fn new(content: Content) -> Self {
Self {
content,
file_name: None,
media_type: None,
headers: HeaderMap::new(),
}
}
fn into_prepared(self, boundary: &str, name: &str) -> Result<PreparedPart> {
let Part {
content,
file_name,
media_type,
headers,
} = self;
let prefix = part_prefix(
boundary,
name,
file_name.as_deref(),
media_type.as_deref(),
&headers,
)?;
let content = match content {
Content::Text(text) => PreparedContent::Buffered(Bytes::from(text.into_bytes())),
Content::Bytes(bytes) => PreparedContent::Buffered(bytes),
Content::Body(body) => match body.into_buffered_bytes() {
Ok(bytes) => PreparedContent::Buffered(bytes),
Err(body) => PreparedContent::Streaming(body),
},
};
Ok(PreparedPart { prefix, content })
}
}
impl PreparedPart {
fn into_streaming(self) -> StreamPart {
let body = match self.content {
PreparedContent::Buffered(bytes) => Body::from(bytes),
PreparedContent::Streaming(body) => body,
};
StreamPart {
prefix: self.prefix,
body,
}
}
}
impl http_body::Body for MultipartStream {
type Data = Bytes;
type Error = Error;
fn poll_frame(
self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>>>> {
let this = self.get_mut();
if this.failed {
return Poll::Ready(None);
}
loop {
if let Some(body) = &mut this.current {
match Pin::new(body).poll_frame(context) {
Poll::Ready(Some(Ok(frame))) => {
if let Ok(data) = frame.into_data()
&& !data.is_empty()
{
return Poll::Ready(Some(Ok(Frame::data(data))));
}
}
Poll::Ready(Some(Err(error))) => {
this.failed = true;
return Poll::Ready(Some(Err(error)));
}
Poll::Ready(None) => {
this.current = None;
return Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(b"\r\n")))));
}
Poll::Pending => return Poll::Pending,
}
continue;
}
if let Some(part) = this.parts.pop_front() {
this.current = Some(part.body);
return Poll::Ready(Some(Ok(Frame::data(part.prefix))));
}
return Poll::Ready(this.tail.take().map(|tail| Ok(Frame::data(tail))));
}
}
fn is_end_stream(&self) -> bool {
self.failed || (self.parts.is_empty() && self.current.is_none() && self.tail.is_none())
}
}
fn boundary() -> String {
format!("tez-{:016x}{:016x}", fastrand::u64(..), fastrand::u64(..))
}
fn content_type(boundary: &str) -> Result<HeaderValue> {
format!("multipart/form-data; boundary={boundary}")
.parse()
.map_err(|_| Error::request("multipart content type is invalid"))
}
fn encode_buffered(parts: Vec<PreparedPart>, boundary: &str) -> Bytes {
let capacity = encoded_length(&parts, boundary)
.and_then(|length| usize::try_from(length).ok())
.unwrap_or_default();
let mut body = Vec::with_capacity(capacity);
for part in parts {
body.extend_from_slice(&part.prefix);
let PreparedContent::Buffered(content) = part.content else {
unreachable!("buffered multipart parts must contain buffered data");
};
body.extend_from_slice(&content);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
Bytes::from(body)
}
fn encoded_length(parts: &[PreparedPart], boundary: &str) -> Option<u64> {
let mut length = u64::try_from(boundary.len() + 6).ok()?;
for part in parts {
length = length.checked_add(u64::try_from(part.prefix.len()).ok()?)?;
length = length.checked_add(match &part.content {
PreparedContent::Buffered(bytes) => u64::try_from(bytes.len()).ok()?,
PreparedContent::Streaming(body) => body.size_hint().exact()?,
})?;
length = length.checked_add(2)?;
}
Some(length)
}
fn part_prefix(
boundary: &str,
name: &str,
file_name: Option<&str>,
media_type: Option<&str>,
headers: &HeaderMap,
) -> Result<Bytes> {
if headers.contains_key(CONTENT_DISPOSITION) || headers.contains_key(CONTENT_TYPE) {
return Err(Error::request("multipart part contains a reserved header"));
}
let name = quoted(name, "multipart field name is invalid")?;
let file_name = file_name
.map(|file_name| quoted(file_name, "multipart part file name is invalid"))
.transpose()?;
if let Some(media_type) = media_type {
media_type
.parse::<Mime>()
.map_err(|_| Error::request("multipart part media type is invalid"))?;
}
let mut prefix =
format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"").into_bytes();
if let Some(file_name) = file_name {
prefix.extend_from_slice(format!("; filename=\"{file_name}\"").as_bytes());
}
prefix.extend_from_slice(b"\r\n");
if let Some(media_type) = media_type {
prefix.extend_from_slice(b"Content-Type: ");
prefix.extend_from_slice(media_type.as_bytes());
prefix.extend_from_slice(b"\r\n");
}
for name in headers.keys() {
for value in headers.get_all(name) {
prefix.extend_from_slice(name.as_str().as_bytes());
prefix.extend_from_slice(b": ");
prefix.extend_from_slice(value.as_bytes());
prefix.extend_from_slice(b"\r\n");
}
}
prefix.extend_from_slice(b"\r\n");
Ok(Bytes::from(prefix))
}
fn quoted(value: &str, error: &'static str) -> Result<String> {
if value.bytes().any(|byte| byte.is_ascii_control()) {
return Err(Error::request(error));
}
let mut quoted = String::with_capacity(value.len());
for character in value.chars() {
if matches!(character, '"' | '\\') {
quoted.push('\\');
}
quoted.push(character);
}
Ok(quoted)
}