1mod stream;
2pub mod config;
3pub mod request;
4pub mod response;
5pub mod websocket;
6#[cfg(feature = "pools")]
7mod pools;
8use crate::stream::{Scheme};
9use crate::config::{Config};
10use crate::request::{Request};
11use crate::response::Response;
12use crate::websocket::{CloseCode, ErrorCode, Message, Websocket};
13use log::{error, info, warn};
14#[cfg(feature = "https")]
15use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
16use std::io::{Error, Write};
17use std::net::{TcpListener};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration};
20use std::{io, thread};
21use std::fmt::Debug;
22use std::path::PathBuf;
23use flate2::Compression;
24use flate2::write::GzEncoder;
25use json::{object, JsonValue};
26
27#[derive(Clone, Debug)]
29pub struct WebServer;
30
31impl WebServer {
32 pub fn new_service(config: Config, factory: fn(out: Websocket) -> Box<dyn Handler>) {
34 loop {
35 match WebServer::service(config.clone(), factory) {
36 Ok(()) => {}
37 Err(e) => error!("服务器错误: {}[{}]: {}", file!(), line!(), e),
38 }
39 warn!("服务器 1秒后重启");
40 thread::sleep(Duration::from_secs(1));
41 }
42 }
43 fn service(config: Config, factory: fn(out: Websocket) -> Box<dyn Handler>) -> io::Result<()> {
44 info!("==================== 网络服务 服务信息 ====================");
45 info!("日志记录: {}",if config.log {"开启"} else {"关闭"});
46 info!("调试模式: {}",if config.debug { "开启" } else { "关闭" });
47 info!("监听地址: {}", config.host);
48 info!("服务地址: {}://{}",if config.https { "https" } else { "http" },config.host);
49 info!("根 目 录: {}", config.root_path.to_str().unwrap());
50 info!("访问目录: {}", config.public);
51 info!("运行目录: {}", config.runtime);
52 info!("SSL/TLS: {}",if config.https { "开启" } else { "关闭" });
53
54 if config.https {
55 info!("证书目录KEY: {:?}", config.tls.key);
56 info!("证书目录PEM: {:?}", config.tls.certs);
57 }
58
59 let listener = TcpListener::bind(config.host.clone())?;
60 info!("==================== 网络服务 启动成功 ====================");
61
62 #[cfg(feature = "https")] let acceptor = Self::ssl(config.clone())?;
63 #[cfg(feature = "pools")] let mut pool = pools::Pool::new(config.pools_max * 4);
64 for stream in listener.incoming() {
65 match stream {
66 Ok(stream) => {
67 let config_new = config.clone();
68 #[cfg(feature = "https")] let acceptor_new = acceptor.clone();
69 #[cfg(not(feature = "pools"))]
70 thread::spawn(move || -> io::Result<()> {
71 stream.set_nonblocking(false)?;
72 stream.set_read_timeout(Some(Duration::from_secs(30))).unwrap_or_default();
74 stream.set_write_timeout(Some(Duration::from_secs(30))).unwrap_or_default();
76 #[cfg(feature = "https")]
77 {
78 let scheme = if config_new.https {
79 match acceptor_new.accept(stream) {
80 Ok(e) => Scheme::Https(Arc::new(Mutex::new(e))),
81 Err(_) => return Err(Error::other("加载加密请求失败")),
82 }
83 } else {
84 Scheme::Http(Arc::new(Mutex::new(stream)))
85 };
86 }
87 #[cfg(not(feature = "https"))] let scheme = Scheme::Http(Arc::new(Mutex::new(stream)));
88
89 let mut request = Request::new(config_new.clone(), Arc::new(Mutex::new(scheme.clone())));
90 let response = match request.handle() {
91 Ok(()) => Response::new(request.clone(), factory),
92 Err(e) => {
93 return Err(Error::other(e.body.as_str()));
95 }
96 };
97 match response.handle() {
98 Ok(()) => {}
99 Err(e) => {
100 error!("发送错误失败2: {}",e.to_string());
101 return Err(Error::other(e));
102 }
103 };
104
105 match request.save_log() {
106 Ok(()) => {}
107 Err(_) => error!("日志记录错误")
108 }
109 Ok(())
110 });
111
112 #[cfg(feature = "pools")]
113 pool.execute(move || -> io::Result<()> {
114
115 stream.set_read_timeout(Some(Duration::from_secs(15))).unwrap_or_default();
117 stream.set_write_timeout(Some(Duration::from_secs(15))).unwrap_or_default();
119
120 let scheme = if config_new.https {
121 match acceptor_new.accept(stream) {
122 Ok(e) => Scheme::Https(Arc::new(Mutex::new(e))),
123 Err(_) => return Err(Error::other("加载加密请求失败")),
124 }
125 } else {
126 Scheme::Http(Arc::new(Mutex::new(stream)))
127 };
128 let mut request = Request::new(config_new.clone(), Arc::new(Mutex::new(scheme.clone())));
129 let request_req = request.handle();
130 let mut response = Response::new(request.clone(), factory);
131 match request_req {
132 Ok(()) => {}
133 Err(e) => return match response.status(e.code).txt(e.body.as_str()).send() {
134 Ok(()) => Ok(()),
135 Err(e) => Err(Error::other(e.body.as_str())),
136 }
137 };
138 response.handle()?;
139 match request.save_log() {
140 Ok(()) => {}
141 Err(_) => {
142 error!("日志记录错误");
143 }
144 }
145 Ok(())
146 });
147 }
148 Err(e) => return Err(e),
149 }
150 }
151 #[cfg(feature = "pools")]
152 pool.end();
153 Ok(())
154 }
155
156 #[cfg(feature = "https")]
157 fn ssl(config: Config) -> io::Result<Arc<SslAcceptor>> {
158 if config.https {
159 let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
160 if !config.tls.key.is_file() {
161 return Err(Error::other(
162 format!("private.key 不存在: {:?}", config.tls.key).as_str(),
163 ));
164 }
165 if !config.tls.certs.is_file() {
166 return Err(Error::other(
167 format!("certificate.pem 不存在: {:?}", config.tls.certs).as_str(),
168 ));
169 }
170 acceptor.set_private_key_file(config.tls.key.clone(), SslFiletype::PEM)?;
171 acceptor.set_certificate_file(config.tls.certs.clone(), SslFiletype::PEM)?;
172 Ok(Arc::new(acceptor.build()))
173 } else {
174 Ok(Arc::new(SslAcceptor::mozilla_intermediate(SslMethod::tls())?.build()))
175 }
176 }
177}
178
179pub trait HandlerClone {
180 fn clone_box(&self) -> Box<dyn Handler>;
181}
182
183impl<T> HandlerClone for T
185where
186 T: 'static + Handler + Clone,
187{
188 fn clone_box(&self) -> Box<dyn Handler> {
189 Box::new(self.clone())
190 }
191}
192
193impl Clone for Box<dyn Handler> {
195 fn clone(&self) -> Box<dyn Handler> {
196 self.clone_box()
197 }
198}
199pub trait Handler: Send + Sync + HandlerClone + Debug {
200 fn on_request(&mut self, _request: Request, _response: &mut Response);
202 fn on_options(&mut self, response: &mut Response) {
204 response.allow_origins = vec![];
205 response.allow_methods = vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"];
206 response.allow_headers = vec!["Authorization", "X-Forwarded-For", "X-Real-IP"];
207 response.header("Access-Control-Expose-Headers", "Content-Disposition");
208 response.header("Access-Control-Max-Age", 86400.to_string().as_str());
209 }
210 fn on_response(&mut self, response: &mut Response) {
212 if !response.headers.has_key("Access-Control-Allow-Origin") {
213 response.header("Access-Control-Allow-Origin", "*");
214 }
215 if !response.headers.has_key("Access-Control-Allow-Credentials") {
217 response.header("Access-Control-Allow-Credentials", "true");
218 }
219 }
224
225 fn on_frame(&mut self) -> Result<(), HttpError> {
226 Ok(())
227 }
228 fn on_open(&mut self) -> Result<(), HttpError> {
230 Ok(())
231 }
232 fn on_message(&mut self, _msg: Message) -> Result<(), HttpError> {
234 Ok(())
235 }
236 fn on_close(&mut self, _code: CloseCode, _reason: &str) {}
238 fn on_error(&mut self, _err: ErrorCode) {}
240 fn on_shutdown(&mut self) {}
242}
243
244
245#[derive(Clone, Debug)]
246pub enum Connection {
247 KeepAlive,
249 Close,
251 Other(String),
252}
253impl Connection {
254 fn from(value: &str) -> Self {
255 match value.to_lowercase().as_str() {
256 "keep-alive" => Self::KeepAlive,
257 "close" => Self::Close,
258 _ => Self::Other(value.to_string()),
259 }
260 }
261 pub fn str(&self) -> &str {
262 match self {
263 Connection::KeepAlive => "keep-alive",
264 Connection::Close => "close",
265 Connection::Other(name) => name
266 }
267 }
268}
269#[derive(Clone, Debug)]
270pub enum Upgrade {
271 Websocket,
272 Http,
273 H2c,
274 Other(String),
275}
276impl Upgrade {
277 fn from(name: &str) -> Self {
278 match name.to_lowercase().as_str() {
279 "websocket" => Upgrade::Websocket,
280 "http" => Upgrade::Http,
281 "h2c" => Upgrade::H2c,
282 _ => Upgrade::Other(name.to_lowercase().as_str().to_string()),
283 }
284 }
285 pub fn str(&self) -> &str {
286 match self {
287 Upgrade::Websocket => "websocket",
288 Upgrade::Http => "http",
289 Upgrade::H2c => "h2c",
290 Upgrade::Other(name) => name,
291 }
292 }
293}
294
295#[derive(Clone, Debug)]
297#[derive(Default)]
298pub struct Uri {
299 pub uri: String,
301 pub url: String,
303 pub query: String,
305 pub fragment: String,
307 pub path: String,
309 pub path_segments: Vec<String>,
311}
312impl Uri {
313 pub fn from(url: &str) -> Self {
314 let mut decoded_url = br_crypto::encoding::urlencoding_decode(url);
315 let fragment = match decoded_url.rfind('#') {
316 None => String::new(),
317 Some(index) => decoded_url.drain(index..).collect::<String>(),
318 };
319
320 let query = match decoded_url.rfind('?') {
321 None => String::new(),
322 Some(index) => decoded_url.drain(index..).collect::<String>().trim_start_matches("?").to_string(),
323 };
324
325 let path_segments = decoded_url.split("/").map(|x| x.to_string()).filter(|x| !x.is_empty()).collect::<Vec<String>>();
326 Self {
327 uri: decoded_url.clone(),
328 url: url.to_string(),
329 query,
330 fragment,
331 path: decoded_url.clone(),
332 path_segments,
333 }
334 }
335 pub fn get_query_params(&self) -> JsonValue {
337 let text = self.query.split('&').collect::<Vec<&str>>();
338 let mut params = object! {};
339 for item in text {
340 if let Some(index) = item.find('=') {
341 let key = item[..index].to_string();
342 let value = item[index + 1..].to_string();
343 let _ = params.insert(key.as_str(), value);
344 }
345 }
346 params
347 }
348 #[must_use]
349 pub fn to_json(&self) -> JsonValue {
350 object! {
351 url: self.url.clone(),
352 query: self.query.clone(),
353 fragment: self.fragment.clone(),
354 path: self.path.clone(),
355 path_segments: self.path_segments.clone()
356 }
357 }
358}
359
360
361#[derive(Clone, Debug)]
363pub enum Method {
364 POST,
366 GET,
368 HEAD,
370 PUT,
372 DELETE,
374 OPTIONS,
376 PATCH,
377 TRACE,
378 VIEW,
379 CONNECT,
380 PROPFIND,
381 PRI,
383 Other(String),
385}
386
387impl Method {
388 #[must_use]
389 pub fn from(name: &str) -> Self {
390 match name.to_lowercase().as_str() {
391 "post" => Self::POST,
392 "get" => Self::GET,
393 "head" => Self::HEAD,
394 "put" => Self::PUT,
395 "delete" => Self::DELETE,
396 "options" => Self::OPTIONS,
397 "patch" => Self::PATCH,
398 "trace" => Self::TRACE,
399 "view" => Self::VIEW,
400 "propfind" => Self::PROPFIND,
401 "connect" => Self::CONNECT,
402 "pri" => Self::PRI,
403 _ => Self::Other(name.to_string()),
404 }
405 }
406 pub fn str(&mut self) -> &str {
407 match self {
408 Method::POST => "POST",
409 Method::GET => "GET",
410 Method::HEAD => "HEAD",
411 Method::PUT => "PUT",
412 Method::DELETE => "DELETE",
413 Method::OPTIONS => "OPTIONS",
414 Method::PATCH => "PATCH",
415 Method::TRACE => "TRACE",
416 Method::VIEW => "VIEW",
417 Method::PROPFIND => "PROPFIND",
418 Method::PRI => "PRI",
419 Method::CONNECT => "CONNECT",
420 Method::Other(e) => e
421 }
422 }
423}
424
425#[derive(Debug, Clone)]
426pub struct HttpError {
427 pub code: u16,
428 pub body: String,
429}
430
431impl HttpError {
432 pub fn new(code: u16, body: &str) -> Self {
434 Self {
435 code,
436 body: body.to_string(),
437 }
438 }
439}
440#[derive(Debug, Clone)]
442pub enum ContentType {
443 FormData,
444 FormUrlencoded,
445 Json,
446 Xml,
447 Javascript,
448 Text,
449 Html,
450 Stream,
451 Other(String),
452}
453impl ContentType {
454 pub fn from(name: &str) -> Self {
455 match name {
456 "multipart/form-data" => Self::FormData,
457 "application/x-www-form-urlencoded" => Self::FormUrlencoded,
458 "application/json" => Self::Json,
459 "application/xml" | "text/xml" => Self::Xml,
460 "application/javascript" => Self::Javascript,
461 "application/octet-stream" => Self::Stream,
462 "text/html" => Self::Html,
463 "text/plain" => Self::Text,
464 _ => Self::Other(name.to_string()),
465 }
466 }
467 pub fn str(&self) -> &str {
468 match self {
469 ContentType::FormData => "multipart/form-data",
470 ContentType::FormUrlencoded => "application/x-www-form-urlencoded",
471 ContentType::Json => "application/json",
472 ContentType::Xml => "application/xml",
473 ContentType::Javascript => "application/javascript",
474 ContentType::Text => "text/plain",
475 ContentType::Html => "text/html",
476 ContentType::Other(name) => name.as_str(),
477 ContentType::Stream => "application/octet-stream"
478 }
479 }
480}
481#[derive(Clone, Debug)]
483pub enum Authorization {
484 Basic(String, String),
485 Bearer(String),
486 Digest(JsonValue),
487 Other(String),
488}
489impl Authorization {
490 #[must_use]
491 pub fn from(data: &str) -> Self {
492 let authorization = data.split_whitespace().collect::<Vec<&str>>();
493 let mode = authorization[0].to_lowercase();
494 match mode.as_str() {
495 "basic" => {
496 let text = br_crypto::base64::decode(&authorization[1].to_string().clone());
497 let text: Vec<&str> = text.split(':').collect();
498 Self::Basic(text[0].to_string(), text[1].to_string())
499 }
500 "bearer" => Self::Bearer(authorization[1].to_string()),
501 "digest" => {
502 let text = authorization[1..].concat().clone();
503 let text = text.split(',').collect::<Vec<&str>>();
504 let mut params = object! {};
505 for item in &text {
506 let Some(index) = item.find('=') else { continue };
507 let key = item[..index].to_string();
508 let value = item[index + 2..item.len() - 1].to_string();
509 let _ = params.insert(key.as_str(), value);
510 }
511 Self::Digest(params)
512 }
513 _ => Self::Other(data.to_string())
514 }
515 }
516 pub fn str(&mut self) -> JsonValue {
517 match self {
518 Authorization::Basic(key, value) => {
519 let mut data = object! {};
520 data[key.as_str()] = value.clone().into();
521 data
522 }
523 Authorization::Bearer(e) => e.clone().into(),
524 Authorization::Digest(e) => e.clone(),
525 Authorization::Other(name) => name.clone().into(),
526 }
527 }
528}
529#[derive(Clone, Debug)]
531pub enum Content {
532 FormUrlencoded(JsonValue),
533 FormData(JsonValue),
534 Json(JsonValue),
535 Text(JsonValue),
536 Xml(JsonValue),
537 None,
538}
539impl Content {}
540#[derive(Clone, Debug)]
541pub enum FormData {
542 File(String, PathBuf),
543 Field(JsonValue),
544}
545
546#[derive(Clone, Debug)]
548pub enum Language {
549 ZhCN,
550 ZhHans,
551 En,
552 Other(String),
553
554}
555impl Language {
556 #[must_use]
557 pub fn from(name: &str) -> Self {
558 let binding = name.split(',').collect::<Vec<&str>>()[0].trim().to_lowercase();
559 let name = binding.as_str();
560 match name {
561 "zh-cn" => Self::ZhCN,
562 "zh-hans" => Self::ZhHans,
563 "en" => Self::En,
564 _ => Self::Other(name.to_string()),
565 }
566 }
567 #[must_use]
568 pub fn str(&self) -> &str {
569 match self {
570 Language::ZhCN => "zh-CN",
571 Language::ZhHans => "zh-Hans",
572 Language::En => "en",
573 Language::Other(e) => e.as_str(),
574 }
575 }
576}
577
578
579#[derive(Clone, Debug)]
581pub enum Encoding {
582 Gzip,
583 Deflate,
584 Br,
585 Bzip2,
586 None,
587}
588impl Encoding {
589 #[must_use]
590 pub fn from(s: &str) -> Encoding {
591 match s.to_lowercase().as_str() {
592 x if x.contains("gzip") => Encoding::Gzip,
593 x if x.contains("deflate") => Encoding::Deflate,
594 x if x.contains("br") => Encoding::Br,
595 x if x.contains("bzip2") => Encoding::Bzip2,
596 _ => Encoding::None,
597 }
598 }
599 #[must_use]
600 pub fn str(&self) -> &str {
601 match self {
602 Encoding::Gzip => "gzip",
603 Encoding::Deflate => "deflate",
604 Encoding::Br => "br",
605 Encoding::None => "",
606 Encoding::Bzip2 => "bzip2",
607 }
608 }
609 pub fn compress(self, data: &[u8]) -> io::Result<Vec<u8>> {
610 match self {
611 Encoding::Gzip => {
612 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
613 encoder.write_all(data)?;
614 encoder.finish()
615 }
616 _ => Ok(data.to_vec()),
617 }
618 }
619}