1use crate::{parse_content_type_header_value, split_boundary, Authorization, Connection, ContentType, Encoding, HttpError, Language, Method, Protocol, Upgrade, Uri};
2use crate::config::{Config};
3use chrono::{DateTime, Local};
4use json::{array, object, JsonValue};
5use log::{info};
6use std::io::{Write};
7use std::path::{Path};
8use std::{env, fs, io, thread};
9use std::cmp::PartialEq;
10use std::fs::OpenOptions;
11use std::sync::{Arc, Mutex};
12use std::time::Instant;
13use crate::stream::{Scheme};
14
15#[derive(Clone, Debug)]
17pub struct Request {
18 pub config: Config,
19 pub header_line: String,
21 pub protocol: Protocol,
23 pub method: Method,
25 pub uri: Uri,
27 pub origin: String,
29 pub header: JsonValue,
31 pub cookie: JsonValue,
33 pub query: JsonValue,
35 pub params: JsonValue,
37 pub authorization: Authorization,
39 pub handle_time: f64,
41 pub datetime: String,
43 pub timestamp: i64,
45 pub client_ip: String,
47 pub proxy_ip: String,
49 pub server_ip: String,
51 pub upgrade: Upgrade,
53 pub connection: Connection,
55 pub accept_encoding: Encoding,
57 start_time: Instant,
59 pub body_data: Vec<u8>,
61 content_length: usize,
63 pub content_type: ContentType,
65 boundary: String,
67 pub scheme: Arc<Mutex<Scheme>>,
68 pub accept_language: Language,
70}
71
72
73impl Request {
74 pub fn new(config: Config, scheme: Arc<Mutex<Scheme>>) -> Self {
75
76 let client_ip = scheme.lock().unwrap().client_ip();
78 let server_ip = scheme.lock().unwrap().server_ip();
80 let local: DateTime<Local> = Local::now();
81 Self {
82 config,
83 header_line: String::new(),
84 protocol: Protocol::Other(String::new()),
85 method: Method::Other(String::new()),
86 uri: Uri::default(),
87 origin: String::new(),
88 header: object! {},
89 cookie: object! {},
90 query: object! {},
91 params: object! {},
92 authorization: Authorization::Other(String::new()),
93 handle_time: 0.0,
94 scheme,
95 start_time: Instant::now(),
96 datetime: local.format("%Y-%m-%d %H:%M:%S").to_string(),
97 timestamp: local.timestamp(),
98 client_ip,
99 server_ip,
100 proxy_ip: String::new(),
101 upgrade: Upgrade::Other(String::new()),
102 connection: Connection::Other(String::new()),
103 accept_encoding: Encoding::None,
104 body_data: vec![],
105 content_length: 0,
106 content_type: ContentType::Other(String::new()),
107 boundary: String::new(),
108 accept_language: Language::ZhCN,
109 }
110 }
111
112 pub fn handle(&mut self) -> Result<(), HttpError> {
113 let mut data = vec![];
114 {
116 self.scheme.lock().unwrap().read(&mut data)?;
117 if let Some(pos) = data.windows(2).position(|window| window == [13, 10]) {
118 let header_data = data.drain(..pos).collect::<Vec<u8>>();
119 let header_data = String::from_utf8_lossy(header_data.as_slice());
120 data.drain(..2);
121 self.handle_header_line(header_data.trim())?;
122 } else {
123 return Err(HttpError::new(400, "请求行错误"));
124 }
125 }
126
127 match &self.protocol {
129 Protocol::HTTP1_0 | Protocol::HTTP1_1 => {
130 {
132 loop {
133 if let Some(pos) = data.windows(4).position(|window| window == [13, 10, 13, 10]) {
134 self.handle_header(data.drain(..pos).collect::<Vec<u8>>())?;
135 data.drain(..4);
136 self.body_data = data;
137 break;
138 }
139 self.scheme.lock().unwrap().read(&mut data)?;
140 }
141 }
142 {
144 if self.content_length > 0 {
145 loop {
146 if self.body_data.len() >= self.content_length {
147 break;
148 }
149 self.scheme.lock().unwrap().read(&mut self.body_data)?;
150 }
151 self.handle_body(self.body_data.clone())?;
152 }
153 }
154 self.handle_time = self.start_time.elapsed().as_micros() as f64 / 1000.0;
155 }
156 Protocol::HTTP2 => {
157 let header = data.drain(..8).collect::<Vec<u8>>();
158 if header.ne(b"\r\nSM\r\n\r\n") {
159 return Err(HttpError::new(400, "HTTP2格式错误"));
160 }
161 self.scheme.lock().unwrap().http2_send_server_settings()?;
162
163 let scheme_arc = self.scheme.clone();
164 let mut scheme = scheme_arc.lock().unwrap();
165
166 scheme.http2_handle_header(&mut data, self)?;
167 self.body_data = scheme.http2_handle_body(&mut data, self.clone())?;
168 self.handle_body(self.body_data.clone())?;
169 self.handle_time = self.start_time.elapsed().as_micros() as f64 / 1000.0;
170 }
171 Protocol::HTTP3 => return Err(HttpError::new(500, format!("未支持: HTTP3 {:?}", self.protocol).as_str())),
172 Protocol::Other(e) => return Err(HttpError::new(500, format!("未支持: Other {e} {:?}", self.protocol).as_str())),
173 }
174 Ok(())
175 }
176 pub fn handle_header_line(&mut self, line: &str) -> Result<(), HttpError> {
178 self.header_line = br_crypto::encoding::urlencoding_decode(line);
179 if self.header_line.is_empty() {
180 return Err(HttpError::new(400, "请求行错误"));
181 }
182 let mut it = self.header_line.split_whitespace();
183 let method = it.next();
184 let target = it.next();
185 let version = it.next();
186
187 self.protocol = match version {
189 None => return Err(HttpError::new(400, "协议版本错误")),
190 Some(e) => Protocol::from(e)
191 };
192 match &self.protocol {
194 Protocol::HTTP1_0 => {
195 self.method = match method {
196 None => return Err(HttpError::new(400, "HTTP10请求类型错误")),
197 Some(e) => Method::from(e)
198 };
199 self.uri = match target {
200 None => return Err(HttpError::new(400, "HTTP10请求资源错误")),
201 Some(e) => Uri::from(e)
202 };
203 self.query = self.uri.get_query_params();
204 }
205 Protocol::HTTP1_1 => {
206 self.method = match method {
207 None => return Err(HttpError::new(400, "HTTP11请求类型错误")),
208 Some(e) => Method::from(e)
209 };
210 self.uri = match target {
211 None => return Err(HttpError::new(400, "HTTP11请求资源错误")),
212 Some(e) => Uri::from(e)
213 };
214 self.query = self.uri.get_query_params();
215 }
216 Protocol::HTTP2 => {}
217 Protocol::HTTP3 => return Err(HttpError::new(400, format!("{:?}协议暂未实现", self.protocol).as_str())),
218 Protocol::Other(name) => return Err(HttpError::new(400, format!("{name}协议暂未实现").as_str())),
219 }
220 Ok(())
221 }
222 pub fn handle_header(&mut self, data: Vec<u8>) -> Result<(), HttpError> {
223 let headers = String::from_utf8_lossy(data.as_slice());
224 if self.config.debug {
225 info!("\r\n=================请求头 {:?}=================\r\n{}\r\n{headers}\r\n========================================",thread::current().id(),self.header_line);
226 }
227 match &self.protocol {
228 Protocol::HTTP1_0 => {
229 for item in headers.lines() {
230 self.header_line_set(item)?;
231 }
232 }
233 Protocol::HTTP1_1 => {
234 for item in headers.lines() {
235 self.header_line_set(item)?;
236 }
237 if !self.header.has_key("host") {
238 return Err(HttpError::new(400, "请求头错误"));
239 }
240 }
241 Protocol::HTTP2 => {
242 return Err(HttpError::new(400, "HTTP2格式错误"));
243 }
244 Protocol::HTTP3 => return Err(HttpError::new(400, "暂时未开放")),
245 Protocol::Other(name) => {
246 return Err(HttpError::new(400, format!("未知协议格式: {}", name).as_str()));
247 }
248 }
249 Ok(())
250 }
251
252 fn header_line_set(&mut self, line: &str) -> Result<(), HttpError> {
253 match line.trim().find(":") {
254 None => return Err(HttpError::new(400, format!("请求头[{line}]错误").as_str())),
255 Some(e) => {
256 let key = line[..e].trim().to_lowercase().clone();
257 let value = line[e + 1..].trim();
258 self.set_header(key.as_str(), value)?;
259 }
260 }
261 Ok(())
262 }
263 pub fn set_header(&mut self, key: &str, value: &str) -> Result<(), HttpError> {
264 self.header[key] = value.into();
265 if value.len() > 8192 {
266 return Err(HttpError::new(400, "header longer than 8192 characters"));
267 }
268 match key {
269 "origin" => self.origin = value.to_string(),
270 "content-type" => {
271 let (mime, params) = parse_content_type_header_value(value);
272 if !mime.is_empty() {
273 if mime == "multipart/form-data" {
274 if let Some(b) = params.get("boundary") {
276 self.boundary = b.to_string();
277 } else {
278 let lower = value.to_lowercase();
280 if let Some(pos) = lower.find("boundary=") {
281 let raw = &value[pos + "boundary=".len()..];
282 let raw = raw.split(';').next().unwrap_or(raw).trim();
283 let raw = raw.trim_matches('"');
284 self.boundary = raw.to_string();
285 }
286 }
287 self.content_type = ContentType::from("multipart/form-data");
288 } else {
289 self.content_type = ContentType::from(mime.as_str());
291 }
292 }
293 self.header[key] = self.content_type.str().into();
294 }
295 "content-length" => self.content_length = value.parse::<usize>().unwrap_or(0),
296 "accept-language" => self.accept_language = Language::from(value),
297 "authorization" => self.authorization = Authorization::from(value),
298 "upgrade" => self.upgrade = Upgrade::from(value),
299 "connection" => self.connection = Connection::from(value),
300 "accept-encoding" => self.accept_encoding = Encoding::from(value),
301 "cookie" => {
302 let _ = value.split(';').collect::<Vec<&str>>().iter().map(|&x| {
303 match x.find('=') {
304 None => {}
305 Some(index) => {
306 let key = x[..index].trim().to_string();
307 let val = x[index + 1..].trim().to_string();
308 let _ = self.cookie.insert(key.as_str(), val);
309 }
310 }
311 ""
312 }).collect::<Vec<&str>>();
313 }
314 "x-forwarded-for" => self.proxy_ip = value.to_string(),
315 "x-real-ip" => self.client_ip = value.to_string(),
316 _ => {}
317 }
318
319 Ok(())
320 }
321 pub fn handle_body(&mut self, data: Vec<u8>) -> Result<(), HttpError> {
322 if self.config.debug {
323 info!("\r\n=================请求体 {:?}=================\r\n长度: {}\r\n========================================",thread::current().id(),self.content_length);
324 }
325 if data.len() != self.content_length {
326 return Err(HttpError::new(400, format!("Content-Length mismatch: header={}, actual={}", self.content_length, data.len()).as_str()));
327 }
328 if self.content_length == 0 {
329 return Ok(());
330 }
331 match &self.content_type {
332 ContentType::FormData => {
333 let parts = match split_boundary(data, &self.boundary) {
334 Ok(e) => e,
335 Err(_) => return Err(HttpError::new(400, "Invalid boundary marker"))
336 };
337 let mut fields = object! {};
338
339 for part in parts {
340 let (header, body) = match part.windows(b"\r\n\r\n".len()).position(|window| window == b"\r\n\r\n") {
341 None => continue,
342 Some(e) => {
343 let header = part[..e].to_vec();
344 let body = part[e + 4..].to_vec();
345 let body = body[..body.len() - 2].to_vec();
346 (header, body)
347 }
348 };
349 let headers = String::from_utf8_lossy(header.as_slice());
350 let mut field_name = "";
351 let mut filename = "";
352 let mut content_type = ContentType::Other("".to_string());
353
354 for header in headers.lines() {
355 if header.to_lowercase().starts_with("content-disposition:") {
356 match header.find("filename=\"") {
357 None => {}
358 Some(filename_start) => {
359 let filename_len = filename_start + 10;
360 let filename_end = header[filename_len..].find('"').unwrap() + filename_len;
361 filename = &header[filename_len..filename_end];
362 }
363 }
364 match header.find("name=\"") {
365 None => {}
366 Some(name_start) => {
367 let name_start = name_start + 6;
368 let name_end = header[name_start..].find('"').unwrap() + name_start;
369 field_name = &header[name_start..name_end];
370 }
371 }
372 }
373 if header.to_lowercase().starts_with("content-type:") {
374 content_type = ContentType::from(header.to_lowercase().trim_start_matches("content-type:").trim());
375 }
376 }
377
378 if filename.is_empty() {
379 let text = String::from_utf8_lossy(body.as_slice());
380 fields[field_name.to_string()] = JsonValue::from(text.into_owned());
381 continue;
382 }
383 let extension = Path::new(filename).extension().and_then(|ext| ext.to_str()); let suffix = extension.unwrap_or("txt");
385 let filename = if extension.is_none() {
386 format!("{filename}.txt")
387 } else {
388 filename.to_string()
389 };
390
391 let mut temp_dir = env::temp_dir();
392 temp_dir.push(filename.clone());
393 let Ok(mut temp_file) = fs::File::create(&temp_dir) else { continue };
394 if temp_file.write(body.as_slice()).is_ok() {
395 if fields[field_name.to_string()].is_empty() {
396 fields[field_name.to_string()] = array![];
397 }
398 fields[field_name.to_string()].push(object! {
399 id:br_crypto::sha256::encrypt_hex(&body.clone()),
400 name:filename,
401 suffix:suffix,
402 size:body.len(),
403 type:content_type.str(),
404 file:temp_dir.to_str()
405 }).unwrap();
406 }
407 }
408 self.params = fields;
409 }
410 ContentType::FormUrlencoded => {
411 let input = String::from_utf8_lossy(&data);
412 let mut list = object! {};
413 for pair in input.split('&') {
414 if let Some((key, val)) = pair.split_once('=') {
415 let key = br_crypto::encoding::urlencoding_decode(key);
416 let val = br_crypto::encoding::urlencoding_decode(val);
417 let _ = list.insert(key.as_str(), val);
418 }
419 }
420 self.params = list;
421 }
422 ContentType::Json => {
423 let text = String::from_utf8_lossy(data.as_slice());
424 self.params = json::parse(text.into_owned().as_str()).unwrap_or(object! {});
425 }
426 ContentType::Xml | ContentType::Html | ContentType::Text | ContentType::Javascript => {
427 let text = String::from_utf8_lossy(data.as_slice());
428 self.params = text.into_owned().into();
429 }
430 ContentType::Other(_) => {}
431 ContentType::Stream => {}
432 }
433 Ok(())
434 }
435 pub fn save_log(&mut self) -> io::Result<()> {
437 if !self.config.log {
438 return Ok(());
439 }
440 let local: DateTime<Local> = Local::now();
441 let time_dir = local.format("%Y-%m-%d-%H").to_string();
442 let time_dir = time_dir.split('-').collect::<Vec<&str>>();
443
444 let mut res = self.config.root_path.join(self.config.runtime.clone()).join("log");
445 for item in &time_dir {
446 res.push(item);
447 }
448 fs::create_dir_all(res.parent().unwrap())?;
449 let log_file = format!("{}.log", res.to_str().unwrap());
450 let mut file = OpenOptions::new()
451 .append(true) .create(true) .open(log_file)?;
455 let data = format!(
456 "[{}] {} ClientIP: {} {} {} ContentLength: {} ContentType: {} Time: {:?} Thread: {:?}\r\n",
457 self.datetime,
458 self.protocol.str(),
459 self.client_ip,
460 self.method.str(),
461 self.uri.url,
462 self.content_length,
463 self.content_type.clone().str(),
464 self.handle_time,
465 thread::current().id()
466 );
467 file.write_all(data.as_bytes())?;
468 Ok(())
469 }
470}
471