1use crate::{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 t = value.split_whitespace().collect::<Vec<&str>>();
272 if !t.is_empty() {
273 match t[0] {
274 _ if t[0].contains("multipart/form-data") => {
275 self.boundary = t[1].trim().trim_start_matches("boundary=").to_string();
276 self.content_type = ContentType::from("multipart/form-data");
277 }
278 _ => {
279 self.content_type = ContentType::from(t[0].trim_end_matches(";"));
280 }
281 }
282 }
283 self.header[key] = self.content_type.str().into();
284 }
285 "content-length" => self.content_length = value.parse::<usize>().unwrap_or(0),
286 "accept-language" => self.accept_language = Language::from(value),
287 "authorization" => self.authorization = Authorization::from(value),
288 "upgrade" => self.upgrade = Upgrade::from(value),
289 "connection" => self.connection = Connection::from(value),
290 "accept-encoding" => self.accept_encoding = Encoding::from(value),
291 "cookie" => {
292 let _ = value.split(';').collect::<Vec<&str>>().iter().map(|&x| {
293 match x.find('=') {
294 None => {}
295 Some(index) => {
296 let key = x[..index].trim().to_string();
297 let val = x[index + 1..].trim().to_string();
298 let _ = self.cookie.insert(key.as_str(), val);
299 }
300 }
301 ""
302 }).collect::<Vec<&str>>();
303 }
304 "x-forwarded-for" => self.proxy_ip = value.to_string(),
305 "x-real-ip" => self.client_ip = value.to_string(),
306 _ => {}
307 }
308
309 Ok(())
310 }
311 pub fn handle_body(&mut self, data: Vec<u8>) -> Result<(), HttpError> {
312 if self.config.debug {
313 info!("\r\n=================请求体 {:?}=================\r\n长度: {}\r\n========================================",thread::current().id(),self.content_length);
314 }
315 if data.len() != self.content_length {
316 return Err(HttpError::new(400, format!("Content-Length mismatch: header={}, actual={}", self.content_length, data.len()).as_str()));
317 }
318 if self.content_length == 0 {
319 return Ok(());
320 }
321 match &self.content_type {
322 ContentType::FormData => {
323 let parts = match split_boundary(data, &self.boundary) {
324 Ok(e) => e,
325 Err(_) => return Err(HttpError::new(400, "Invalid boundary marker"))
326 };
327 let mut fields = object! {};
328
329 for part in parts {
330 let (header, body) = match part.windows(b"\r\n\r\n".len()).position(|window| window == b"\r\n\r\n") {
331 None => continue,
332 Some(e) => {
333 let header = part[..e].to_vec();
334 let body = part[e + 4..].to_vec();
335 let body = body[..body.len() - 2].to_vec();
336 (header, body)
337 }
338 };
339 let headers = String::from_utf8_lossy(header.as_slice());
340 let mut field_name = "";
341 let mut filename = "";
342 let mut content_type = ContentType::Other("".to_string());
343
344 for header in headers.lines() {
345 if header.to_lowercase().starts_with("content-disposition:") {
346 match header.find("filename=\"") {
347 None => {}
348 Some(filename_start) => {
349 let filename_len = filename_start + 10;
350 let filename_end = header[filename_len..].find('"').unwrap() + filename_len;
351 filename = &header[filename_len..filename_end];
352 }
353 }
354 match header.find("name=\"") {
355 None => {}
356 Some(name_start) => {
357 let name_start = name_start + 6;
358 let name_end = header[name_start..].find('"').unwrap() + name_start;
359 field_name = &header[name_start..name_end];
360 }
361 }
362 }
363 if header.to_lowercase().starts_with("content-type:") {
364 content_type = ContentType::from(header.to_lowercase().trim_start_matches("content-type:").trim());
365 }
366 }
367
368 if filename.is_empty() {
369 let text = String::from_utf8_lossy(body.as_slice());
370 fields[field_name.to_string()] = JsonValue::from(text.into_owned());
371 continue;
372 }
373 let extension = Path::new(filename).extension().and_then(|ext| ext.to_str()); let suffix = extension.unwrap_or("txt");
375 let filename = if extension.is_none() {
376 format!("{filename}.txt")
377 } else {
378 filename.to_string()
379 };
380
381 let mut temp_dir = env::temp_dir();
382 temp_dir.push(filename.clone());
383 let Ok(mut temp_file) = fs::File::create(&temp_dir) else { continue };
384 if temp_file.write(body.as_slice()).is_ok() {
385 if fields[field_name.to_string()].is_empty() {
386 fields[field_name.to_string()] = array![];
387 }
388 fields[field_name.to_string()].push(object! {
389 id:br_crypto::sha256::encrypt_hex(&body.clone()),
390 name:filename,
391 suffix:suffix,
392 size:body.len(),
393 type:content_type.str(),
394 file:temp_dir.to_str()
395 }).unwrap();
396 }
397 }
398 self.params = fields;
399 }
400 ContentType::FormUrlencoded => {
401 let input = String::from_utf8_lossy(&data);
402 let mut list = object! {};
403 for pair in input.split('&') {
404 if let Some((key, val)) = pair.split_once('=') {
405 let key = br_crypto::encoding::urlencoding_decode(key);
406 let val = br_crypto::encoding::urlencoding_decode(val);
407 let _ = list.insert(key.as_str(), val);
408 }
409 }
410 self.params = list;
411 }
412 ContentType::Json => {
413 let text = String::from_utf8_lossy(data.as_slice());
414 self.params = json::parse(text.into_owned().as_str()).unwrap_or(object! {});
415 }
416 ContentType::Xml | ContentType::Html | ContentType::Text | ContentType::Javascript => {
417 let text = String::from_utf8_lossy(data.as_slice());
418 self.params = text.into_owned().into();
419 }
420 ContentType::Other(_) => {}
421 ContentType::Stream => {}
422 }
423 Ok(())
424 }
425 pub fn save_log(&mut self) -> io::Result<()> {
427 if !self.config.log {
428 return Ok(());
429 }
430 let local: DateTime<Local> = Local::now();
431 let time_dir = local.format("%Y-%m-%d-%H").to_string();
432 let time_dir = time_dir.split('-').collect::<Vec<&str>>();
433
434 let mut res = self.config.root_path.join(self.config.runtime.clone()).join("log");
435 for item in &time_dir {
436 res.push(item);
437 }
438 fs::create_dir_all(res.parent().unwrap())?;
439 let log_file = format!("{}.log", res.to_str().unwrap());
440 let mut file = OpenOptions::new()
441 .append(true) .create(true) .open(log_file)?;
445 let data = format!(
446 "[{}] {} ClientIP: {} {} {} ContentLength: {} ContentType: {} Time: {:?} Thread: {:?}\r\n",
447 self.datetime,
448 self.protocol.str(),
449 self.client_ip,
450 self.method.str(),
451 self.uri.url,
452 self.content_length,
453 self.content_type.clone().str(),
454 self.handle_time,
455 thread::current().id()
456 );
457 file.write_all(data.as_bytes())?;
458 Ok(())
459 }
460}
461