-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rs
More file actions
453 lines (397 loc) · 15.5 KB
/
parser.rs
File metadata and controls
453 lines (397 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use crate::prelude::*;
use std::time::{Duration, Instant};
struct BoundarySearcher {
pattern: Vec<u8>,
skip_table: [usize; 256],
}
impl BoundarySearcher {
fn new(pattern: Vec<u8>) -> Self {
let pattern_len = pattern.len();
let mut skip_table = [pattern_len; 256];
// Build skip table (all except last character)
for i in 0..pattern_len.saturating_sub(1) {
skip_table[pattern[i] as usize] = pattern_len - 1 - i;
}
Self {
pattern,
skip_table,
}
}
// Search from start position, returns position if found
fn search(&self, haystack: &[u8], start: usize) -> Option<usize> {
let pattern_len = self.pattern.len();
let haystack_len = haystack.len();
if start + pattern_len > haystack_len {
return None;
}
let mut pos = start;
let search_end = haystack_len - pattern_len;
while pos <= search_end {
// Check if pattern matches at current position
let mut matches = true;
for i in 0..pattern_len {
if haystack[pos + i] != self.pattern[i] {
matches = false;
break;
}
}
if matches {
return Some(pos);
}
// Skip ahead using bad character rule
let last_char = haystack[pos + pattern_len - 1];
pos += self.skip_table[last_char as usize];
}
None
}
}
pub fn parse_request_headers(headers_data: &[u8]) -> Result<HttpRequest, String> {
let headers_str = str::from_utf8(headers_data).map_err(|_| "Invalid UTF-8 in headers")?;
let mut lines = headers_str.lines();
let request_line = lines.next().ok_or("Empty request")?;
let mut request = parse_request_line(request_line)?;
let mut current_header_name: Option<String> = None;
let mut current_header_value = String::new();
for line in lines {
if line.trim().is_empty() {
if let Some(name) = current_header_name.take() {
request
.headers
.insert(name, current_header_value.trim().to_string());
current_header_value.clear();
}
continue;
}
if line.starts_with(' ') || line.starts_with('\t') {
if current_header_name.is_some() {
current_header_value.push(' ');
current_header_value.push_str(line.trim());
} else {
return Err(format!("Invalid continuation line: {}", line));
}
} else {
if let Some(name) = current_header_name.take() {
request
.headers
.insert(name, current_header_value.trim().to_string());
current_header_value.clear();
}
parse_header_line(line, &mut current_header_name, &mut current_header_value)?;
}
}
if let Some(name) = current_header_name.take() {
request
.headers
.insert(name, current_header_value.trim().to_string());
}
if !request.headers.contains_key("host") {
return Err("Missing Host header".to_string());
}
Ok(HttpRequest::new(
request.method,
request.uri,
request.version,
request.headers,
))
}
pub fn parse_multipart_body(body: &[u8], content_type: &str) -> Result<Vec<MultipartPart>, String> {
let start_time = Instant::now();
let timeout = Duration::from_secs(10);
let boundary = extract_boundary(content_type)?;
let initial_boundary = format!("--{}", boundary).into_bytes();
let boundary_pattern = format!("\r\n--{}", boundary).into_bytes();
let end_boundary = format!("\r\n--{}--", boundary).into_bytes();
let boundary_searcher = BoundarySearcher::new(boundary_pattern.clone());
let end_searcher = BoundarySearcher::new(end_boundary.clone());
let mut parts = Vec::new();
println!("Parsing multipart body with boundary: {}", boundary);
println!("Body length: {}", body.len());
if body.is_empty() {
println!("Empty body received");
return Err("Empty multipart body".to_string());
}
if start_time.elapsed() > timeout {
println!("Timeout during multipart parsing setup");
return Err("Timeout during multipart parsing setup".to_string());
}
if !body.starts_with(&initial_boundary) {
println!("Missing initial boundary: expected --{}", boundary);
return Err(format!("Missing initial boundary: expected --{}", boundary));
}
let mut current_pos = initial_boundary.len();
if current_pos + 2 > body.len() || &body[current_pos..current_pos + 2] != b"\r\n" {
println!(
"Invalid data after initial boundary at pos {}: {:?}",
current_pos,
&body[current_pos..(current_pos + 10).min(body.len())]
);
return Err("Invalid data after initial boundary".to_string());
}
current_pos += 2;
let time = Instant::now();
loop {
if start_time.elapsed() > timeout {
println!("Timeout during multipart parsing loop at pos {}", current_pos);
return Err("Timeout during multipart parsing loop".to_string());
}
if current_pos >= body.len() {
break;
}
// Search for boundaries efficiently (single pass)
let end_boundary_pos = end_searcher.search(body, current_pos);
let next_boundary_pos = boundary_searcher.search(body, current_pos);
// Determine which boundary comes first
let (part_end, is_final, boundary_len) = match (next_boundary_pos, end_boundary_pos) {
(Some(next), Some(end)) if end <= next => {
println!("Found end boundary at position {}", end);
(end, true, end_boundary.len())
}
(Some(next), _) => {
println!("Found next boundary at position {}", next);
(next, false, boundary_pattern.len())
}
(None, Some(end)) => {
println!("Found end boundary at position {}", end);
(end, true, end_boundary.len())
}
(None, None) => {
println!(
"No closing boundary found at pos {}: searching in {:?}",
current_pos,
String::from_utf8_lossy(&body[current_pos..(current_pos + 100).min(body.len())])
);
return Err("No closing boundary found".to_string());
}
};
let part_data = &body[current_pos..part_end];
println!(
"Processing part data (len={}): {:?}",
part_data.len(),
String::from_utf8_lossy(&part_data[..(100).min(part_data.len())])
);
// Find headers end efficiently
let headers_end = find_double_crlf(part_data).ok_or_else(|| {
println!(
"Invalid part headers at pos {}: {:?}",
current_pos,
String::from_utf8_lossy(&part_data[..(100).min(part_data.len())])
);
"Invalid part headers"
})?;
let headers_str = std::str::from_utf8(&part_data[..headers_end]).map_err(|e| {
println!("Invalid UTF-8 in part headers: {}", e);
format!("Invalid UTF-8 in part headers: {}", e)
})?;
println!("Part headers (raw):\n{}", headers_str);
let mut part = MultipartPart {
name: String::new(),
filename: None,
content_type: None,
data: Vec::new(),
};
// Parse headers
let header_lines = headers_str
.split("\r\n")
.filter(|line| !line.trim().is_empty());
for header in header_lines {
println!("Processing header: '{}'", header);
match parse_part_header(header) {
Ok(Some((name, value))) => {
println!("Parsed header: {}: {}", name, value);
match name.to_lowercase().as_str() {
"content-disposition" => {
if let Some(name_val) = extract_disposition_param(&value, "name") {
println!("Set part.name: {}", name_val);
part.name = name_val;
}
if let Some(filename_val) = extract_disposition_param(&value, "filename") {
println!("Set part.filename: {}", filename_val);
part.filename = Some(filename_val);
}
}
"content-type" => {
println!("Set part.content_type: {}", value);
part.content_type = Some(value.to_string());
}
_ => println!("Ignoring unknown header: {}: {}", name, value),
}
}
Ok(None) => println!("Skipped header with no colon: '{}'", header),
Err(e) => println!("Failed to parse header '{}': {}", header, e),
}
}
if part.name.is_empty() {
println!(
"Missing name in Content-Disposition for part at pos {}",
current_pos
);
return Err("Missing name in Content-Disposition".to_string());
}
let mut part_data_slice = &part_data[headers_end..];
// Remove trailing CRLF before boundary
if part_data_slice.ends_with(b"\r\n") {
part_data_slice = &part_data_slice[..part_data_slice.len() - 2];
}
part.data = part_data_slice.to_vec();
let part_name = part.name.clone();
let part_filename = part.filename.clone();
let part_data_len = part.data.len();
parts.push(part);
println!(
"Added part: name={}, filename={:?}, data_len={}",
part_name, part_filename, part_data_len
);
if is_final {
println!("Reached end boundary, stopping parse");
break;
}
// Move past the boundary
current_pos = part_end + boundary_len;
// Expect CRLF after boundary
if current_pos + 2 <= body.len() && &body[current_pos..current_pos + 2] == b"\r\n" {
current_pos += 2;
println!("Advanced past CRLF after boundary, now at pos {}", current_pos);
} else if current_pos >= body.len() {
println!("Reached end of body at pos {}", current_pos);
break;
} else {
println!(
"Invalid data after boundary at pos {}: {:?}",
current_pos,
&body[current_pos..(current_pos + 10).min(body.len())]
);
return Err("Invalid data after boundary".to_string());
}
}
let time2 = Instant::now();
println!("{:?}", time2.duration_since(time));
if parts.is_empty() {
println!("No valid parts found in multipart data");
return Err("No valid parts found in multipart data".to_string());
}
println!("Successfully parsed {} parts", parts.len());
Ok(parts)
}
fn extract_boundary(content_type: &str) -> Result<String, String> {
let parts: Vec<&str> = content_type.split(';').map(|s| s.trim()).collect();
for part in parts {
if let Some(boundary) = part.strip_prefix("boundary=") {
let boundary = boundary.trim_matches('"').to_string();
if boundary.is_empty() {
return Err("Empty boundary in Content-Type".to_string());
}
println!("Extracted boundary: {}", boundary);
return Ok(boundary);
}
}
Err("No boundary found in Content-Type".to_string())
}
fn extract_disposition_param(disposition: &str, param: &str) -> Option<String> {
let param_prefix = format!("{}=\"", param);
let start = disposition.find(¶m_prefix)?;
let value_start = start + param_prefix.len();
let value_end = disposition[value_start..]
.find('"')
.map(|pos| pos + value_start)
.unwrap_or(disposition.len());
let value = disposition[value_start..value_end].trim().to_string();
if value.is_empty() {
println!(
"Empty value for param {} in disposition: '{}'",
param, disposition
);
None
} else {
println!("Extracted {}: '{}'", param, value);
Some(value)
}
}
fn parse_part_header(header: &str) -> Result<Option<(String, String)>, String> {
let header = header.trim();
if header.is_empty() {
println!("Skipping empty header");
return Ok(None);
}
if let Some(colon_pos) = header.find(':') {
let name = header[..colon_pos].trim().to_lowercase();
let value = header[colon_pos + 1..].trim();
if name.is_empty() {
println!("Empty header name in: '{}'", header);
return Err("Empty header name in multipart part".to_string());
}
Ok(Some((name, value.to_string())))
} else {
println!("No colon found in header: '{}'", header);
Ok(None)
}
}
fn parse_request_line(line: &str) -> Result<HttpRequest, String> {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() != 3 {
return Err("Invalid request line format".to_string());
}
let method = parts[0].to_uppercase();
let mut uri = parts[1].to_string();
let version = parts[2].to_string();
// Handle absolute URI
if uri.starts_with("http://") || uri.starts_with("https://") {
let pos = uri.find("://").unwrap_or_default();
let after_scheme = &uri[pos + 3..];
// Ensure there is a host part
if after_scheme.is_empty() || after_scheme.starts_with('/') {
return Err("Malformed absolute URI: missing host".to_string());
}
if let Some(slash_pos) = after_scheme.find('/') {
uri = after_scheme[slash_pos..].to_string();
} else {
uri = "/".to_string();
}
}
match method.as_str() {
"GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH" => {}
_ => {
return Err(format!("Unsupported HTTP method: {}", method));
}
}
if version != "HTTP/1.1" {
return Err(format!("Only HTTP/1.1 is supported, got: {}", version));
}
Ok(HttpRequest::new(method, uri, version, HashMap::new()))
}
fn parse_header_line(
line: &str,
header_name: &mut Option<String>,
header_value: &mut String,
) -> Result<(), String> {
if let Some(colon_pos) = line.find(':') {
let name = line[..colon_pos].trim().to_lowercase();
let value = line[colon_pos + 1..].trim();
if name.is_empty() {
return Err("Empty header name".to_string());
}
*header_name = Some(name);
*header_value = value.to_string();
Ok(())
} else {
Err(format!("Invalid header format: {}", line))
}
}
fn find_double_crlf(data: &[u8]) -> Option<usize> {
if data.len() < 4 {
return None;
}
let mut i = 0;
let end = data.len() - 3;
while i <= end {
// Check for \r\n\r\n pattern
if data[i] == b'\r'
&& data[i + 1] == b'\n'
&& data[i + 2] == b'\r'
&& data[i + 3] == b'\n'
{
return Some(i + 4);
}
i += 1;
}
None
}