1use crate::{Error, Result, client::Request, http1::Header};
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Part {
22 name: String,
23 filename: Option<String>,
24 content_type: Option<String>,
25 body: Vec<u8>,
26}
27impl Part {
28 pub fn text(name: impl Into<String>, value: impl Into<String>) -> Self {
30 Self {
31 name: name.into(),
32 filename: None,
33 content_type: None,
34 body: value.into().into_bytes(),
35 }
36 }
37 pub fn file(name: impl Into<String>, filename: impl Into<String>, bytes: Vec<u8>) -> Self {
39 Self {
40 name: name.into(),
41 filename: Some(filename.into()),
42 content_type: None,
43 body: bytes,
44 }
45 }
46 pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
47 self.content_type = Some(content_type.into());
48 self
49 }
50 fn media_type(&self) -> Option<&str> {
51 match (&self.content_type, &self.filename) {
52 (Some(content_type), _) => Some(content_type),
53 (None, Some(_)) => Some("application/octet-stream"),
54 (None, None) => None,
55 }
56 }
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct Form {
62 parts: Vec<Part>,
63}
64impl Form {
65 pub fn new() -> Self {
66 Self::default()
67 }
68 pub fn text(self, name: impl Into<String>, value: impl Into<String>) -> Self {
69 self.part(Part::text(name, value))
70 }
71 pub fn file(
72 self,
73 name: impl Into<String>,
74 filename: impl Into<String>,
75 bytes: Vec<u8>,
76 ) -> Self {
77 self.part(Part::file(name, filename, bytes))
78 }
79 pub fn part(mut self, part: Part) -> Self {
80 self.parts.push(part);
81 self
82 }
83 pub fn parts(&self) -> &[Part] {
84 &self.parts
85 }
86 pub fn encode(&self, entropy: [u8; 16]) -> Result<Encoded> {
94 for part in &self.parts {
95 if part
96 .media_type()
97 .is_some_and(|t| t.bytes().any(|b| b.is_ascii_control()))
98 {
99 return Err(Error::new(
100 "UND_ERR_INVALID_ARG",
101 "invalid multipart content type",
102 ));
103 }
104 }
105 let names: Vec<_> = self
106 .parts
107 .iter()
108 .map(|p| (escape(&p.name), p.filename.as_deref().map(escape)))
109 .collect();
110 let boundary = self.boundary(entropy, &names);
111 let mut body = Vec::with_capacity(
114 self.parts
115 .iter()
116 .zip(&names)
117 .map(|(part, (name, filename))| {
118 part.body.len()
119 + name.len()
120 + filename.as_ref().map_or(0, String::len)
121 + part.media_type().map_or(0, str::len)
122 + boundary.len()
123 + 128
124 })
125 .sum::<usize>()
126 + boundary.len()
127 + 6,
128 );
129 for (part, (name, filename)) in self.parts.iter().zip(&names) {
130 body.extend_from_slice(b"--");
131 body.extend_from_slice(boundary.as_bytes());
132 body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
133 body.extend_from_slice(name.as_bytes());
134 body.push(b'"');
135 if let Some(filename) = filename {
136 body.extend_from_slice(b"; filename=\"");
137 body.extend_from_slice(filename.as_bytes());
138 body.push(b'"');
139 }
140 if let Some(media_type) = part.media_type() {
141 body.extend_from_slice(b"\r\nContent-Type: ");
142 body.extend_from_slice(media_type.as_bytes());
143 }
144 body.extend_from_slice(b"\r\n\r\n");
145 body.extend_from_slice(&part.body);
146 body.extend_from_slice(b"\r\n");
147 }
148 body.extend_from_slice(b"--");
149 body.extend_from_slice(boundary.as_bytes());
150 body.extend_from_slice(b"--\r\n");
151 Ok(Encoded { boundary, body })
152 }
153 fn boundary(&self, entropy: [u8; 16], names: &[(String, Option<String>)]) -> String {
158 let entropy = u128::from_le_bytes(entropy);
159 let (low, high) = (entropy as u64, (entropy >> 64) as u64);
160 let mut index = 0u64;
161 loop {
162 let boundary = candidate(low, high, index);
163 let needle = boundary.as_bytes();
164 let collides = self
165 .parts
166 .iter()
167 .zip(names)
168 .any(|(part, (name, filename))| {
169 [
170 Some(part.body.as_slice()),
171 Some(name.as_bytes()),
172 filename.as_deref().map(str::as_bytes),
173 part.media_type().map(str::as_bytes),
174 ]
175 .into_iter()
176 .flatten()
177 .any(|bytes| contains(bytes, needle))
178 });
179 if !collides {
180 return boundary;
181 }
182 index += 1;
183 }
184 }
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Encoded {
190 pub boundary: String,
191 pub body: Vec<u8>,
192}
193impl Encoded {
194 pub fn content_type(&self) -> String {
196 format!("multipart/form-data; boundary={}", self.boundary)
197 }
198 pub fn apply(self, request: &mut Request) {
200 let content_type = self.content_type();
201 request
202 .headers
203 .retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
204 request
205 .headers
206 .push(Header::new("content-type", content_type));
207 request.body = self.body;
208 }
209}
210
211const PREFIX: &str = "turnloop-";
214const BOUNDARY_LEN: usize = PREFIX.len() + 32;
215
216fn candidate(low: u64, high: u64, index: u64) -> String {
217 const GAMMA: u64 = 0x9e37_79b9_7f4a_7c15;
220 let first = mix(low.wrapping_add(index.wrapping_mul(GAMMA)));
221 let second = mix(high ^ first);
222 let mut boundary = String::with_capacity(BOUNDARY_LEN);
223 boundary.push_str(PREFIX);
224 for word in [first, second] {
225 for shift in (0..16).rev() {
226 let digit = ((word >> (shift * 4)) & 15) as u8;
227 boundary.push(char::from(if digit < 10 {
228 b'0' + digit
229 } else {
230 b'a' + digit - 10
231 }));
232 }
233 }
234 boundary
235}
236
237fn mix(mut z: u64) -> u64 {
238 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
239 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
240 z ^ (z >> 31)
241}
242
243fn contains(haystack: &[u8], needle: &[u8]) -> bool {
244 haystack
245 .windows(needle.len())
246 .any(|window| window == needle)
247}
248
249fn escape(value: &str) -> String {
251 let mut escaped = String::with_capacity(value.len());
252 for c in value.chars() {
253 match c {
254 '"' => escaped.push_str("%22"),
255 '\r' => escaped.push_str("%0D"),
256 '\n' => escaped.push_str("%0A"),
257 c => escaped.push(c),
258 }
259 }
260 escaped
261}