1 //! The multipart parser of the OpenAI compatibility routes.2 //!3 //! The transport hands the web one body, either in memory or as a spooled4 //! file. This module cuts that body into fields without holding a file field in5 //! memory: a field that has a filename goes to its own unlinked temporary file,6 //! and a text field is capped. The parser knows no OpenAI names; the adapter7 //! decides which field is a model, a prompt, or an image.8 //!9 //! Only the two OpenAI multipart routes call this module. The native API takes10 //! JSON and blob addresses (spec section 9.2).11 12 use std::fmt;13 use std::fs::File;14 use std::io::{self, BufRead, Write};15 use std::os::unix::fs::OpenOptionsExt;16 use std::sync::atomic::{AtomicU64, Ordering};17 18 /// The largest text field that the parser buffers. A text field above this is19 /// not a prompt; it is a file that the client forgot to name.20 const MAX_TEXT: usize = 1 << 20;21 22 /// The largest one header line, including its line ending.23 const MAX_HEADER: usize = 8 << 10;24 25 /// The largest header block of one part.26 const MAX_HEADERS: usize = 64 << 10;27 28 /// The longest boundary that RFC 2046 allows.29 const MAX_BOUNDARY: usize = 70;30 31 /// Why a multipart body is not a set of fields.32 #[derive(Debug)]33 pub enum MultipartError {34 /// The request is not `multipart/form-data` with a boundary.35 ContentType(String),36 /// A delimiter or a line ending is missing or malformed.37 Boundary(String),38 /// A header is missing or malformed.39 Header(String),40 /// A text field is not UTF-8, or is above [`MAX_TEXT`].41 Field(String),42 /// The reader failed.43 Io(io::Error),44 }45 46 impl fmt::Display for MultipartError {47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {48 match self {49 MultipartError::ContentType(why) => write!(f, "multipart content type: {why}"),50 MultipartError::Boundary(why) => write!(f, "multipart boundary: {why}"),51 MultipartError::Header(why) => write!(f, "multipart header: {why}"),52 MultipartError::Field(why) => write!(f, "multipart field: {why}"),53 MultipartError::Io(why) => write!(f, "multipart io: {why}"),54 }55 }56 }57 58 impl std::error::Error for MultipartError {}59 60 impl From<io::Error> for MultipartError {61 fn from(why: io::Error) -> MultipartError {62 MultipartError::Io(why)63 }64 }65 66 /// One field of a multipart body.67 #[derive(Debug)]68 pub struct Field {69 /// The form name from `Content-Disposition`.70 pub name: String,71 /// The client filename, when the field is a file.72 pub filename: Option<String>,73 /// The declared media type, when the client named one.74 pub mime: Option<String>,75 /// The bytes, inline or behind a descriptor.76 pub body: FieldBody,77 }78 79 /// Where the bytes of one field are.80 #[derive(Debug)]81 pub enum FieldBody {82 /// A text field. It is UTF-8 and at most [`MAX_TEXT`] bytes.83 Text(String),84 /// A file field, in an unlinked temporary file.85 File(Uploaded),86 }87 88 /// A file field and the length that the parser wrote.89 #[derive(Debug)]90 pub struct Uploaded {91 /// The descriptor. It has no name in the filesystem.92 pub file: File,93 /// The bytes written.94 pub len: u64,95 }96 97 /// Parses a multipart body.98 ///99 /// `content_type` is the request header. `reader` is the body, and it may be a100 /// slice or a spooled request. The parser stops at the closing delimiter; an101 /// epilogue is ignored.102 pub fn parse<R: BufRead>(content_type: &str, reader: &mut R) -> Result<Vec<Field>, MultipartError> {103 let boundary = boundary(content_type)?;104 let mut source = Source::new(reader);105 let mut delimiter = b"--".to_vec();106 delimiter.extend_from_slice(&boundary);107 let mut closing = delimiter.clone();108 closing.extend_from_slice(b"--");109 110 let first_line = source.line(MAX_HEADER)?;111 let first = strip_line(&first_line);112 if first == closing {113 return Ok(Vec::new());114 }115 if first != delimiter {116 return Err(MultipartError::Boundary(117 "the body does not start with the boundary".to_string(),118 ));119 }120 121 let mut fields = Vec::new();122 loop {123 let headers = read_headers(&mut source)?;124 let (name, filename) = disposition(&headers)?;125 let mime = headers.get("content-type").map(|value| value.to_string());126 let mut sink = if filename.is_some() {127 Sink::File {128 file: temp_file()?,129 len: 0,130 }131 } else {132 Sink::Text(Vec::new())133 };134 135 let mut body_delimiter = b"\r\n".to_vec();136 body_delimiter.extend_from_slice(&delimiter);137 source.body(&body_delimiter, &mut sink)?;138 139 let end = source.take(2)?;140 let body = match sink {141 Sink::Text(bytes) => FieldBody::Text(142 String::from_utf8(bytes)143 .map_err(|_| MultipartError::Field(format!("field {name} is not UTF-8")))?,144 ),145 Sink::File { file, len } => FieldBody::File(Uploaded { file, len }),146 };147 fields.push(Field {148 name,149 filename,150 mime,151 body,152 });153 154 match end.as_slice() {155 b"\r\n" => {}156 b"--" => return Ok(fields),157 _ => {158 return Err(MultipartError::Boundary(159 "the boundary is not followed by CRLF or --".to_string(),160 ));161 }162 }163 }164 }165 166 /// The boundary token of a `multipart/form-data` content type.167 fn boundary(content_type: &str) -> Result<Vec<u8>, MultipartError> {168 let mut pieces = content_type.split(';');169 let kind = pieces.next().unwrap_or_default().trim();170 if !kind.eq_ignore_ascii_case("multipart/form-data") {171 return Err(MultipartError::ContentType(172 "the media type is not multipart/form-data".to_string(),173 ));174 }175 for piece in pieces {176 let Some((name, value)) = piece.split_once('=') else {177 continue;178 };179 if !name.trim().eq_ignore_ascii_case("boundary") {180 continue;181 }182 let value = unquote(value.trim());183 if value.is_empty() || value.len() > MAX_BOUNDARY {184 return Err(MultipartError::ContentType(185 "the boundary is empty or too long".to_string(),186 ));187 }188 if value.contains(['\r', '\n']) {189 return Err(MultipartError::ContentType(190 "the boundary contains a line ending".to_string(),191 ));192 }193 return Ok(value.into_bytes());194 }195 Err(MultipartError::ContentType(196 "the content type has no boundary".to_string(),197 ))198 }199 200 /// Strips one pair of quotes and the backslash escapes inside them.201 fn unquote(value: &str) -> String {202 let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) else {203 return value.to_string();204 };205 let mut out = String::with_capacity(inner.len());206 let mut escaped = false;207 for ch in inner.chars() {208 if escaped {209 out.push(ch);210 escaped = false;211 } else if ch == '\\' {212 escaped = true;213 } else {214 out.push(ch);215 }216 }217 out218 }219 220 fn read_headers<R: BufRead>(221 source: &mut Source<R>,222 ) -> Result<std::collections::BTreeMap<String, String>, MultipartError> {223 let mut headers = std::collections::BTreeMap::new();224 let mut bytes = 0usize;225 loop {226 let line = source.line(MAX_HEADER)?;227 bytes += line.len();228 if bytes > MAX_HEADERS {229 return Err(MultipartError::Header(230 "the header block is too large".to_string(),231 ));232 }233 let line = strip_line(&line);234 if line.is_empty() {235 return Ok(headers);236 }237 let line = std::str::from_utf8(line)238 .map_err(|_| MultipartError::Header("a header is not UTF-8".to_string()))?;239 let Some((name, value)) = line.split_once(':') else {240 return Err(MultipartError::Header("a header has no colon".to_string()));241 };242 let name = name.trim().to_ascii_lowercase();243 if name.is_empty() {244 return Err(MultipartError::Header("a header has no name".to_string()));245 }246 headers.insert(name, value.trim().to_string());247 }248 }249 250 /// The form name and optional filename of the `Content-Disposition` header.251 fn disposition(252 headers: &std::collections::BTreeMap<String, String>,253 ) -> Result<(String, Option<String>), MultipartError> {254 let value = headers255 .get("content-disposition")256 .ok_or_else(|| MultipartError::Header("a part has no content disposition".to_string()))?;257 let mut pieces = split_quoted(value);258 let Some(kind) = pieces.next() else {259 return Err(MultipartError::Header(260 "the content disposition is empty".to_string(),261 ));262 };263 if !kind.trim().eq_ignore_ascii_case("form-data") {264 return Err(MultipartError::Header(265 "the content disposition is not form-data".to_string(),266 ));267 }268 let mut name = None;269 let mut filename = None;270 for piece in pieces {271 let Some((key, value)) = piece.split_once('=') else {272 continue;273 };274 let key = key.trim();275 let value = unquote(value.trim());276 if key.eq_ignore_ascii_case("name") {277 name = Some(value);278 } else if key.eq_ignore_ascii_case("filename") {279 filename = Some(value);280 }281 }282 let name = name283 .ok_or_else(|| MultipartError::Header("the content disposition has no name".to_string()))?;284 Ok((name, filename))285 }286 287 /// Splits on semicolons that are outside quotes.288 fn split_quoted(value: &str) -> impl Iterator<Item = &str> {289 let mut pieces = Vec::new();290 let mut start = 0usize;291 let mut quoted = false;292 let mut escaped = false;293 for (index, ch) in value.char_indices() {294 if escaped {295 escaped = false;296 continue;297 }298 match ch {299 '\\' if quoted => escaped = true,300 '"' => quoted = !quoted,301 ';' if !quoted => {302 pieces.push(&value[start..index]);303 start = index + 1;304 }305 _ => {}306 }307 }308 pieces.push(&value[start..]);309 pieces.into_iter()310 }311 312 /// A buffered source that can hand bytes back without a seek.313 struct Source<'a, R: BufRead> {314 reader: &'a mut R,315 buffer: Vec<u8>,316 }317 318 impl<'a, R: BufRead> Source<'a, R> {319 fn new(reader: &'a mut R) -> Source<'a, R> {320 Source {321 reader,322 buffer: Vec::new(),323 }324 }325 326 /// Appends one chunk of the reader. Returns zero at end of file.327 fn more(&mut self) -> Result<usize, MultipartError> {328 let available = self.reader.fill_buf()?;329 let len = available.len();330 self.buffer.extend_from_slice(available);331 self.reader.consume(len);332 Ok(len)333 }334 335 /// The bytes that are ready, or an empty slice at end of file.336 fn fill(&mut self) -> Result<&[u8], MultipartError> {337 if self.buffer.is_empty() {338 self.more()?;339 }340 Ok(&self.buffer)341 }342 343 fn consume(&mut self, len: usize) {344 self.buffer.drain(..len.min(self.buffer.len()));345 }346 347 /// One line with its ending, or the last bytes at end of file.348 fn line(&mut self, max: usize) -> Result<Vec<u8>, MultipartError> {349 let mut line = Vec::new();350 loop {351 let chunk = self.fill()?;352 if chunk.is_empty() {353 break;354 }355 if let Some(index) = chunk.iter().position(|byte| *byte == b'\n') {356 line.extend_from_slice(&chunk[..=index]);357 self.consume(index + 1);358 break;359 }360 let len = chunk.len();361 line.extend_from_slice(chunk);362 self.consume(len);363 if line.len() > max {364 return Err(MultipartError::Header("a line is too large".to_string()));365 }366 }367 if line.len() > max {368 return Err(MultipartError::Header("a line is too large".to_string()));369 }370 Ok(line)371 }372 373 fn take(&mut self, len: usize) -> Result<Vec<u8>, MultipartError> {374 let mut out = Vec::with_capacity(len);375 while out.len() < len {376 let chunk = self.fill()?;377 if chunk.is_empty() {378 return Err(MultipartError::Boundary(379 "the body ended before the boundary".to_string(),380 ));381 }382 let want = (len - out.len()).min(chunk.len());383 out.extend_from_slice(&chunk[..want]);384 self.consume(want);385 }386 Ok(out)387 }388 389 /// Writes everything before `delimiter` and consumes the delimiter.390 fn body(&mut self, delimiter: &[u8], sink: &mut Sink) -> Result<(), MultipartError> {391 loop {392 if self.buffer.is_empty() && self.more()? == 0 {393 return Err(MultipartError::Boundary(394 "the body ended before the boundary".to_string(),395 ));396 }397 if let Some(index) = find(&self.buffer, delimiter) {398 sink.write(&self.buffer[..index])?;399 self.consume(index + delimiter.len());400 return Ok(());401 }402 let keep = delimiter.len().saturating_sub(1);403 let len = self.buffer.len();404 if len > keep {405 let write = len - keep;406 sink.write(&self.buffer[..write])?;407 self.consume(write);408 }409 // The last `keep` bytes can be the start of the delimiter, so they410 // stay in the source until the next read.411 if self.more()? == 0 {412 return Err(MultipartError::Boundary(413 "the body ended before the boundary".to_string(),414 ));415 }416 }417 }418 }419 420 fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {421 if needle.is_empty() || haystack.len() < needle.len() {422 return None;423 }424 haystack425 .windows(needle.len())426 .position(|window| window == needle)427 }428 429 /// Where one field's bytes go while the parser reads them.430 enum Sink {431 Text(Vec<u8>),432 File { file: File, len: u64 },433 }434 435 impl Sink {436 fn write(&mut self, bytes: &[u8]) -> Result<(), MultipartError> {437 match self {438 Sink::Text(text) => {439 if text.len().saturating_add(bytes.len()) > MAX_TEXT {440 return Err(MultipartError::Field(441 "a text field is too large".to_string(),442 ));443 }444 text.extend_from_slice(bytes);445 }446 Sink::File { file, len } => {447 file.write_all(bytes)?;448 *len = len.saturating_add(bytes.len() as u64);449 }450 }451 Ok(())452 }453 }454 455 /// An unlinked temporary file for one uploaded part.456 fn temp_file() -> Result<File, MultipartError> {457 static NEXT: AtomicU64 = AtomicU64::new(1);458 let name = format!(459 "inf3r-multipart-{}-{}",460 std::process::id(),461 NEXT.fetch_add(1, Ordering::Relaxed)462 );463 let path = std::env::temp_dir().join(name);464 let file = std::fs::OpenOptions::new()465 .create_new(true)466 .read(true)467 .write(true)468 .mode(0o600)469 .open(&path)?;470 let _ = std::fs::remove_file(&path);471 Ok(file)472 }473 474 /// One line without its line ending.475 fn strip_line(line: &[u8]) -> &[u8] {476 let line = line.strip_suffix(b"\n").unwrap_or(line);477 line.strip_suffix(b"\r").unwrap_or(line)478 }479 480 #[cfg(test)]481 mod tests {482 use super::*;483 use std::io::{BufReader, Cursor};484 485 fn parse_body(486 content_type: &str,487 body: &[u8],488 capacity: usize,489 ) -> Result<Vec<Field>, MultipartError> {490 let mut reader = BufReader::with_capacity(capacity, Cursor::new(body.to_vec()));491 parse(content_type, &mut reader)492 }493 494 fn form() -> &'static str {495 "multipart/form-data; boundary=b0undary"496 }497 498 #[test]499 fn a_text_field_a_file_field_and_a_quoted_filename_parse() {500 let body = b"--b0undary\r\n\501 Content-Disposition: form-data; name=\"model\"\r\n\r\n\502 echo\r\n\503 --b0undary\r\n\504 Content-Disposition: form-data; name=\"file\"; filename=\"a;b.png\"\r\n\505 Content-Type: image/png\r\n\r\n\506 \x00\x01\x02\r\n\507 --b0undary--\r\n";508 let fields = parse_body(form(), body, 3).expect("multipart");509 510 assert_eq!(fields.len(), 2);511 assert_eq!(fields[0].name, "model");512 let FieldBody::Text(text) = &fields[0].body else {513 panic!("the model is not text");514 };515 assert_eq!(text, "echo");516 assert_eq!(fields[1].filename.as_deref(), Some("a;b.png"));517 assert_eq!(fields[1].mime.as_deref(), Some("image/png"));518 let FieldBody::File(file) = &fields[1].body else {519 panic!("the file is not a file");520 };521 assert_eq!(file.len, 3);522 }523 524 #[test]525 fn a_delimiter_prefix_inside_a_field_is_not_a_boundary() {526 let body = b"--b0undary\r\n\527 Content-Disposition: form-data; name=\"prompt\"\r\n\r\n\528 a\r\n--b0undar\r\n\529 --b0undary--\r\n";530 let fields = parse_body(form(), body, 5).expect("multipart");531 532 let FieldBody::Text(text) = &fields[0].body else {533 panic!("the prompt is not text");534 };535 assert_eq!(text, "a\r\n--b0undar");536 }537 538 #[test]539 fn a_body_without_a_closing_boundary_is_refused() {540 let body = b"--b0undary\r\n\541 Content-Disposition: form-data; name=\"model\"\r\n\r\n\542 echo\r\n";543 let error = parse_body(form(), body, 4).expect_err("no closing boundary");544 assert!(error.to_string().contains("boundary"), "{error}");545 }546 547 #[test]548 fn a_text_field_above_the_cap_is_refused() {549 let mut body = b"--b0undary\r\n\550 Content-Disposition: form-data; name=\"prompt\"\r\n\r\n"551 .to_vec();552 body.extend(std::iter::repeat_n(b'a', MAX_TEXT + 1));553 body.extend_from_slice(b"\r\n--b0undary--\r\n");554 let error = parse_body(form(), &body, 64 << 10).expect_err("too large");555 assert!(error.to_string().contains("too large"), "{error}");556 }557 }