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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::collections::HashMap;
use std::{env, fs};
use std::io::{Error, ErrorKind, Write};
use std::path::PathBuf;
use std::str::Lines;
use chrono::{DateTime, Local};
use json::{JsonValue, object};
use log::{debug, error, warn};
use crate::base64::{decode};
use crate::config::Config;

/// 请求体
#[derive(Clone, Debug)]
pub struct Request {
    pub config: Config,
    /// 协议版本
    pub protocol: Protocol,
    /// 当前请求类型
    pub method: Method,
    /// 资源标识符
    pub uri: Uri,
    /// header信息
    pub header: Header,
    /// Cookie信息
    cookie: Cookie,
    /// 请求体
    pub body: Body,
    /// 认证信息
    authorization: Authorization,
    /// 处理时间 ms 毫秒
    pub handle_time: f64,
    /// 请求时间
    pub datetime: String,
    /// 客户端IP
    pub client_ip: String,
    /// 升级协议
    pub upgrade: Upgrade,
    /// 连接的持久性
    pub connection: Connection,
}
impl Request {
    pub fn new(data: Vec<u8>, config: Config) -> Result<Request, Error> {
        let text = unsafe { String::from_utf8_unchecked(data) };
        if config.is_debug {
            debug!("{}", text);
        }
        let lines = text.lines();


        // 请求行处理
        let (method, uri, protocol) = Request::get_request_line(lines.clone().next().unwrap())?;
        // Header处理
        let (header, cookie, body, authorization, upgrade, connection) = Request::get_header(lines.clone())?;

        let local: DateTime<Local> = Local::now();
        let datetime = local.format("%Y-%m-%d %H:%M:%S").to_string();

        Ok(Self {
            config,
            protocol,
            method,
            uri,
            header,
            cookie,
            body,
            authorization,
            handle_time: Default::default(),
            datetime,
            client_ip: "".to_string(),
            upgrade,
            connection,
        })
    }
    /// 获取请求行信息
    pub fn get_request_line(line: &str) -> Result<(Method, Uri, Protocol), Error> {
        let lines = line.split_whitespace().collect::<Vec<&str>>();
        if lines.len() != 3 {
            return Err(Error::new(ErrorKind::Other, "请求行错误"));
        }
        Ok((Method::from(lines[0]), Uri::from(lines[1]), Protocol::from(lines[2])))
    }
    fn get_header(mut data: Lines) -> Result<(Header, Cookie, Body, Authorization, Upgrade, Connection), Error> {
        let mut header = Header::default();
        let mut cookie = Cookie::default();
        let mut body = Body::default();
        let mut upgrade = Upgrade::Http;
        let mut authorization = Authorization::None;
        let mut connection = Connection::None;
        while let Some(text) = data.next() {
            let (key, value) = match text.trim().find(":") {
                None => continue,
                Some(e) => {
                    let key = text[..e].trim().to_lowercase().clone();
                    let value = text[e + 1..].trim().to_string();
                    (key, value)
                }
            };
            match key.as_str() {
                "content-type" => {
                    match value {
                        _ if value.contains("multipart/form-data") => {
                            let boundarys = value.split("boundary=").collect::<Vec<&str>>();
                            body.boundary = boundarys[1..].join("");
                            body.content_type = ContentType::from("multipart/form-data");
                            header.0.insert(key.leak(), "multipart/form-data");
                        }
                        _ => {
                            body.content_type = ContentType::from(value.as_str());
                            header.0.insert(key.leak(), &body.content_type.str());
                        }
                    }
                }
                "content-length" => {
                    body.content_length = value.to_string().parse::<usize>().unwrap_or(0);
                }
                "authorization" => {
                    authorization = Authorization::from(&*value);
                }
                "cookie" => {
                    let _ = value.split(";").collect::<Vec<&str>>().iter().map(|&x| {
                        match x.find("=") {
                            None => {}
                            Some(index) => {
                                let key = x[..index].trim().to_string();
                                let val = x[index + 1..].trim().to_string();
                                cookie.0.insert(key.leak(), val.leak());
                            }
                        };
                        ""
                    }).collect::<Vec<&str>>();
                }
                "upgrade" => {
                    upgrade = Upgrade::from(&*value);
                }
                "connection" => {
                    connection = Connection::from(&*value);
                }
                _ => { header.0.insert(key.leak(), &*value.leak()); }
            };
        }
        Ok((header, cookie, body, authorization, upgrade, connection))
    }
}
impl Default for Request {
    fn default() -> Self {
        Self {
            config: Default::default(),
            protocol: Protocol::None,
            method: Method::None,
            uri: Uri::default(),
            header: Header::default(),
            cookie: Cookie::default(),
            body: Body::default(),
            authorization: Authorization::None,
            handle_time: Default::default(),
            datetime: "".to_string(),
            client_ip: "".to_string(),
            upgrade: Upgrade::Http,
            connection: Connection::None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Header(pub(crate) HashMap<&'static str, &'static str>);
impl Default for Header {
    fn default() -> Self {
        Self(HashMap::new())
    }
}
#[derive(Debug, Clone)]
struct Cookie(HashMap<&'static str, &'static str>);
impl Default for Cookie {
    fn default() -> Self {
        Self(HashMap::new())
    }
}

/// HTTP协议版本
#[derive(Clone, Debug)]
pub enum Protocol {
    HTTP1_1,
    HTTP2,
    None,
}

impl Protocol {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "http/1.1" => Self::HTTP1_1,
            "http/2" => Self::HTTP2,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Protocol::HTTP1_1 => "HTTP/1.1",
            Protocol::HTTP2 => "HTTP/2",
            Protocol::None => ""
        }
    }
}


/// 请求方法
#[derive(Clone, Debug)]
pub enum Method {
    POST,
    GET,
    HEAD,
    PUT,
    DELETE,
    OPTIONS,
    PATCH,
    TRACE,
    None,
}

impl Method {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "post" => Self::POST,
            "get" => Self::GET,
            "head" => Self::HEAD,
            "put" => Self::PUT,
            "delete" => Self::DELETE,
            "options" => Self::OPTIONS,
            "patch" => Self::PATCH,
            "trace" => Self::TRACE,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Method::POST => "POST",
            Method::GET => "GET",
            Method::HEAD => "HEAD",
            Method::PUT => "PUT",
            Method::DELETE => "DELETE",
            Method::OPTIONS => "OPTIONS",
            Method::PATCH => "PATCH",
            Method::TRACE => "TRACE",
            Method::None => ""
        }
    }
}
/// 请求资源的路径
#[derive(Clone, Debug)]
pub struct Uri {
    pub url: String,
    pub query: HashMap<String, String>,
    pub fragment: String,
    pub path: String,
}
impl Uri {
    pub fn from(data: &str) -> Self {
        let mut uri = data.to_string();
        let fragment = match uri.rfind("#") {
            None => "".to_string(),
            Some(index) => {
                uri.drain(index..).collect::<String>()
            }
        };
        let query = match uri.rfind("?") {
            None => HashMap::new(),
            Some(index) => {
                let text = uri.drain(index..).collect::<String>();
                let text = text.trim_start_matches("?");
                let text = text.split("&").collect::<Vec<&str>>();
                let mut params = HashMap::new();
                for &item in text.iter() {
                    match item.find("=") {
                        None => continue,
                        Some(e) => {
                            let key = item[..e].to_string();
                            let value = item[e + 1..].to_string();
                            params.insert(Uri::decode(&*key).unwrap_or(key.to_string()), Uri::decode(&*value).unwrap_or(key.to_string()));
                        }
                    };
                }
                params
            }
        };
        Self { url: data.to_string(), query, fragment, path: uri.to_string() }
    }
    /// 解码
    pub fn decode(input: &str) -> Result<String, String> {
        let mut decoded = String::new();
        let bytes = input.as_bytes();
        let mut i = 0;

        while i < bytes.len() {
            if bytes[i] == b'%' {
                if i + 2 >= bytes.len() {
                    return Err("Incomplete percent-encoding".into());
                }
                let hex = &input[i + 1..i + 3];
                match u8::from_str_radix(hex, 16) {
                    Ok(byte) => decoded.push(byte as char),
                    Err(_) => return Err(format!("Invalid percent-encoding: %{}", hex)),
                }
                i += 3;
            } else if bytes[i] == b'+' {
                decoded.push(' ');
                i += 1;
            } else {
                decoded.push(bytes[i] as char);
                i += 1;
            }
        }

        Ok(decoded)
    }
}

impl Default for Uri {
    fn default() -> Self {
        Self {
            url: "".to_string(),
            query: Default::default(),
            fragment: "".to_string(),
            path: "".to_string(),
        }
    }
}

/// 内容类型
#[derive(Debug, Clone)]
pub enum ContentType {
    FormData,
    FormUrlencoded,
    Json,
    Xml,
    Javascript,
    Text,
    Html,
    Other(&'static str),
}
impl ContentType {
    pub fn from(name: &str) -> Self {
        match name {
            "multipart/form-data" => Self::FormData,
            "application/x-www-form-urlencoded" => Self::FormUrlencoded,
            "application/json" => Self::Json,
            "application/xml" | "text/xml" => Self::Xml,
            "application/javascript" => Self::Javascript,
            "text/html" => Self::Html,
            "text/plain" => Self::Text,
            _ => Self::Other(name.to_string().leak())
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Self::FormData => "multipart/form-data",
            Self::FormUrlencoded => "application/x-www-form-urlencoded",
            Self::Json => "application/json",
            Self::Xml => "application/xml",
            Self::Javascript => "application/javascript",
            Self::Text => "text/plain",
            Self::Html => "text/html",
            Self::Other(name) => name
        }
    }
}
/// 认证
#[derive(Clone, Debug)]
enum Authorization {
    Basic(String, String),
    Bearer(String),
    Digest(HashMap<String, String>),
    None,
}
impl Authorization {
    pub fn from(data: &str) -> Self {
        let authorization = data.split_whitespace().collect::<Vec<&str>>();
        let mode = authorization[0].to_lowercase();
        match mode.as_str() {
            "basic" => {
                match decode(&*authorization[1].to_string().clone()) {
                    Ok(decoded) => {
                        let text = String::from_utf8(decoded.clone()).unwrap();
                        let text: Vec<&str> = text.split(":").collect();
                        Self::Basic(text[0].to_string(), text[1].to_string())
                    }
                    Err(e) => {
                        error!("{}basic认证解码错误: {}",line!(),e);
                        Self::Basic("".to_string(), "".to_string())
                    }
                }
            }
            "bearer" => {
                Self::Bearer(authorization[1].to_string())
            }
            "digest" => {
                let text = authorization[1..].concat().clone();
                let text = text.split(",").collect::<Vec<&str>>();
                let mut params = HashMap::new();
                for item in text.iter() {
                    let index = match item.find("=") {
                        None => continue,
                        Some(e) => e,
                    };
                    let key = item[..index].to_string();
                    let value = item[index + 2..item.len() - 1].to_string();
                    params.insert(key, value);
                }

                Self::Digest(params)
            }
            _ => {
                warn!("未知认证模式: {}", mode);
                Self::None
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct Body {
    pub content_type: ContentType,
    pub boundary: String,
    pub content_length: usize,
    pub content: JsonValue,
}
impl Body {
    pub fn set_content(&mut self, data: Vec<u8>) {
        match self.content_type {
            ContentType::FormData => {
                let mut fields = object! {};
                let boundary_marker = format!("--{}", self.boundary);
                let text = unsafe { String::from_utf8_unchecked(data) };
                let parts = text.split(&boundary_marker).collect::<Vec<&str>>();
                for part in parts {
                    let part = part.trim();
                    if part.is_empty() || part == "--" {
                        continue; // 跳过无效部分
                    }
                    let mut headers_and_body = part.splitn(2, "\r\n\r\n");
                    if let (Some(headers), Some(body)) = (headers_and_body.next(), headers_and_body.next()) {
                        // 解析头部,查找 Content-Disposition
                        let headers = headers.split("\r\n");

                        for header in headers {
                            if header.starts_with("Content-Disposition:") {
                                if let Some(filename_start) = header.find("filename=\"") {
                                    let filename_len = filename_start + 10;
                                    let filename_end = header[filename_len..].find('"').unwrap() + filename_len;
                                    let filename = &header[filename_len..filename_end];

                                    if let Some(name_start) = header.find("name=\"") {
                                        let name_start = name_start + 6;
                                        let name_end = header[name_start..].find('"').unwrap() + name_start;
                                        let name = &header[name_start..name_end];

                                        // 获取系统临时目录
                                        let mut temp_dir = env::temp_dir();
                                        // 构造临时文件的完整路径
                                        temp_dir.push(filename);
                                        // 打开(创建)临时文件
                                        let mut temp_file = match fs::File::create(&temp_dir) {
                                            Ok(e) => e,
                                            Err(_) => continue
                                        };
                                        match temp_file.write(body.as_bytes()) {
                                            Ok(_) => {
                                                fields[name.to_string()] = object! {
                                                    name:filename,
                                                    file:temp_dir.to_str()
                                                };
                                            }
                                            Err(_) => {}
                                        };
                                    }
                                } else {
                                    if let Some(name_start) = header.find("name=\"") {
                                        let name_start = name_start + 6;
                                        let name_end = header[name_start..].find('"').unwrap() + name_start;
                                        let name = &header[name_start..name_end];
                                        fields[name.to_string()] = JsonValue::from(body);
                                    }
                                }
                            }
                        }
                    }
                }
                self.content = fields.into();
            }
            ContentType::FormUrlencoded => {
                let text = unsafe { String::from_utf8_unchecked(data) };
                let params = text.split("&").collect::<Vec<&str>>();
                let mut list = object! {};
                for param in params.iter() {
                    let t = param.split("=").collect::<Vec<&str>>().iter().map(|&x| { Uri::decode(x).unwrap_or(x.to_string()) }).collect::<Vec<String>>();
                    list[t[0].to_string()] = t[1].clone().into();
                }
                self.content = list;
            }
            ContentType::Json => {
                let text = unsafe { String::from_utf8_unchecked(data) };
                self.content = json::parse(text.as_str()).unwrap_or(object! {});
            }
            ContentType::Xml => {
                let text = unsafe { String::from_utf8_unchecked(data) };
                self.content = text.into();
            }
            ContentType::Html | ContentType::Text | ContentType::Javascript => {
                let text = unsafe { String::from_utf8_unchecked(data) };
                self.content = text.into();
            }
            ContentType::Other(name) => {
                match name {
                    "application/pdf" => {
                        let text = unsafe { String::from_utf8_unchecked(data) };
                        self.content = text.into();
                    }
                    _ => {
                        let text = unsafe { String::from_utf8_unchecked(data) };
                        self.content = text.into();
                    }
                }
            }
        }
    }
}

impl Default for Body {
    fn default() -> Self {
        Self {
            content_type: ContentType::Other("text/plain"),
            boundary: "".to_string(),
            content_length: 0,
            content: object! {},
        }
    }
}
/// 消息内容
#[derive(Clone, Debug)]
pub enum Content {
    FormUrlencoded(HashMap<String, String>),
    FormData(HashMap<String, FormData>),
    Json(JsonValue),
    Text(JsonValue),
    Xml(JsonValue),
    None,
}
impl Content {}
#[derive(Clone, Debug)]
pub enum FormData {
    File(String, PathBuf),
    Field(JsonValue),
}

#[derive(Clone, Debug)]
pub enum Upgrade {
    Websocket,
    Http,
}
impl Upgrade {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "websocket" => Self::Websocket,
            _ => Self::Http,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Self::Websocket => "websocket",
            Self::Http => "http"
        }
    }
}

#[derive(Clone, Debug)]
pub enum Connection {
    KeepAlive,
    Close,
    Upgrade,
    None,
}
impl Connection {
    pub fn from(value: &str) -> Self {
        match value.to_lowercase().as_str() {
            "upgrade" => Self::Upgrade,
            "keep-alive" => Self::KeepAlive,
            "close" => Self::Close,
            _ => Self::None,
        }
    }
}