br_web_server/
lib.rs

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
mod base64;
mod client;
pub mod config;
mod encoding;
pub mod request;
pub mod response;
#[cfg(feature = "ws")]
pub mod websocket;

use crate::client::{Client, Scheme};
use crate::config::Config;
use crate::request::Request;
use crate::response::Response;
#[cfg(feature = "ws")]
use crate::websocket::{CloseCode, ErrorCode, Message, Websocket};
use log::{error, info, warn};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use std::io::{Error, ErrorKind};
use std::net::{IpAddr, SocketAddr, TcpListener};
use std::sync::Arc;
use std::time::{Duration};
use std::{io, thread};

/// 网络服务
#[derive(Clone, Debug)]
pub struct WebServer;

impl WebServer {
    #[cfg(feature = "service")]
    /// 后台服务器
    pub fn new_service(config: Config, factory: fn(config: Config) -> Box<dyn Handler>) {
        loop {
            match WebServer::service(config.clone(), factory) {
                Ok(_) => {}
                Err(e) => error!("{}[{}]: {}", file!(), line!(), e),
            };
            warn!("服务器 2秒后重启");
            thread::sleep(Duration::from_secs(2));
        }
    }
    #[cfg(feature = "service")]
    fn service(config: Config, factory: fn(config: Config) -> Box<dyn Handler>) -> io::Result<()> {
        info!("==================== 网络服务 服务信息 ====================");
        info!(
            "日志记录: {}",
            if config.is_save_log {
                "开启"
            } else {
                "关闭"
            }
        );
        info!(
            "调试模式: {}",
            if config.is_debug { "开启" } else { "关闭" }
        );
        info!("地    址: {}", format!("{}", config.host));
        info!("端 口 号: {}", format!("{}", config.port));
        info!(
            "服务地址: {}",
            format!(
                "{}://{}{}",
                if config.https { "https" } else { "http" },
                config.host,
                if config.port > 0 {
                    format!(":{}", config.port)
                } else {
                    "".to_string()
                }
            )
        );
        info!("根 目 录: {}", format!("{}", config.root_path));
        info!("访问目录: {}", format!("{}", config.public));
        info!("运行目录: {}", format!("{}", config.runtime));
        info!(
            "SSL/TLS: {}",
            format!("{}", if config.https { "开启" } else { "关闭" })
        );
        if config.https {
            info!("证书目录KEY: {}", format!("{:?}", config.tls.key));
            info!("证书目录PEM: {}", format!("{:?}", config.tls.certs));
        }

        let addrs = [SocketAddr::from((
            IpAddr::V4(config.host.parse().unwrap()),
            config.port,
        ))];
        let listener = TcpListener::bind(&addrs[..])?;
        info!("==================== 网络服务 启动成功 ====================");

        let acceptor = if config.https {
            let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
            if !config.tls.key.is_file() {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("private.key 不存在: {:?}", config.tls.key).as_str(),
                ));
            }
            if !config.tls.certs.is_file() {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("certificate.pem 不存在: {:?}", config.tls.certs).as_str(),
                ));
            }
            acceptor.set_private_key_file(config.tls.key.clone(), SslFiletype::PEM)?;
            acceptor.set_certificate_file(config.tls.certs.clone(), SslFiletype::PEM)?;
            Arc::new(acceptor.build())
        } else {
            Arc::new(SslAcceptor::mozilla_intermediate(SslMethod::tls())?.build())
        };

        for stream in listener.incoming() {
            match stream {
                Ok(stream) => {
                    let config_new = config.clone();
                    let acceptor = acceptor.clone();

                    thread::spawn(move || {
                        // 设置超时时间
                        if config_new.write_timeout > 0 {
                            stream
                                .set_write_timeout(Some(Duration::from_secs(
                                    config_new.write_timeout,
                                )))
                                .unwrap_or_default();
                        }
                        if config_new.read_timeout > 0 {
                            stream
                                .set_read_timeout(Some(Duration::from_secs(
                                    config_new.read_timeout,
                                )))
                                .unwrap_or_default();
                        }

                        // 获取请求客户端IP
                        let client_ip = stream.peer_addr().unwrap().ip().to_string();
                        // 获取服务端IP
                        let server_ip = stream.local_addr().unwrap().ip().to_string();

                        let scheme = match config_new.https {
                            true => match acceptor.accept(stream.try_clone().unwrap()) {
                                Ok(e) => Scheme::Https(e,client_ip.clone()),
                                Err(_) => return,
                            },
                            false => Scheme::Http(stream.try_clone().unwrap(),client_ip.clone()),
                        };

                        let client = Client {
                            config: config_new.clone(),
                            request: Request::default(),
                            response: Response::default(),
                            server_ip,
                            client_ip,
                            factory,
                        };
                        match client.handle_service(scheme) {
                            Ok(_) => {}
                            Err(e) => error!("{}", e),
                        };
                    });
                }
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    #[cfg(feature = "webpage")]
    /// 网页服务器
    pub fn new_webpage(config: Config, factory: fn(config: Config) -> Box<dyn Handler>) {
        loop {
            match WebServer::webpage(config.clone(), factory) {
                Ok(_) => {}
                Err(e) => error!("{}[{}]: {}", file!(), line!(), e),
            };
            warn!("服务器 2秒后重启");
            thread::sleep(Duration::from_secs(2));
        }
    }
    #[cfg(feature = "webpage")]
    fn webpage(config: Config, factory: fn(config: Config) -> Box<dyn Handler>) -> io::Result<()> {
        info!("==================== 网络服务 服务信息 ====================");
        info!(
            "日志记录: {}",
            if config.is_save_log {
                "开启"
            } else {
                "关闭"
            }
        );
        info!(
            "调试模式: {}",
            if config.is_debug { "开启" } else { "关闭" }
        );
        info!("地    址: {}", format!("{}", config.host));
        info!("端 口 号: {}", format!("{}", config.port));
        info!(
            "服务地址: {}",
            format!(
                "{}://{}{}",
                if config.https { "https" } else { "http" },
                config.host,
                if config.port > 0 {
                    format!(":{}", config.port)
                } else {
                    "".to_string()
                }
            )
        );
        info!("根 目 录: {}", format!("{}", config.root_path));
        info!("访问目录: {}", format!("{}", config.public));
        info!("运行目录: {}", format!("{}", config.runtime));
        info!("网页目录: {}", format!("{}", config.webpage));
        info!(
            "SSL/TLS: {}",
            format!("{}", if config.https { "开启" } else { "关闭" })
        );
        if config.https {
            info!("证书目录KEY: {}", format!("{:?}", config.tls.key));
            info!("证书目录PEM: {}", format!("{:?}", config.tls.certs));
        }

        let addrs = [SocketAddr::from((
            IpAddr::V4(config.host.parse().unwrap()),
            config.port,
        ))];
        let listener = TcpListener::bind(&addrs[..])?;
        info!("==================== 网络服务 启动成功 ====================");

        let acceptor = if config.https {
            let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
            if !config.tls.key.is_file() {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("private.key 不存在: {:?}", config.tls.key).as_str(),
                ));
            }
            if !config.tls.certs.is_file() {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("certificate.pem 不存在: {:?}", config.tls.certs).as_str(),
                ));
            }
            acceptor.set_private_key_file(config.tls.key.clone(), SslFiletype::PEM)?;
            acceptor.set_certificate_file(config.tls.certs.clone(), SslFiletype::PEM)?;
            Arc::new(acceptor.build())
        } else {
            Arc::new(SslAcceptor::mozilla_intermediate(SslMethod::tls())?.build())
        };

        for stream in listener.incoming() {
            match stream {
                Ok(stream) => {
                    let config_new = config.clone();
                    let acceptor = acceptor.clone();

                    thread::spawn(move || {
                        // 设置超时时间
                        if config_new.write_timeout > 0 {
                            stream
                                .set_write_timeout(Some(Duration::from_secs(
                                    config_new.write_timeout,
                                )))
                                .unwrap_or_default();
                        }
                        if config_new.read_timeout > 0 {
                            stream
                                .set_read_timeout(Some(Duration::from_secs(
                                    config_new.read_timeout,
                                )))
                                .unwrap_or_default();
                        }

                        // 获取请求客户端IP
                        let client_ip = stream.peer_addr().unwrap().to_string();
                        // 获取服务端IP
                        let server_ip = stream.local_addr().unwrap().to_string();

                        let scheme = match config_new.https {
                            true => match acceptor.accept(stream.try_clone().unwrap()) {
                                Ok(e) => Scheme::Https(e, client_ip.clone()),
                                Err(_) => return,
                            },
                            false => Scheme::Http(stream.try_clone().unwrap(), client_ip.clone()),
                        };
                        let client = Client {
                            config: config_new.clone(),
                            request: Request::default(),
                            response: Response::default(),
                            factory,
                            server_ip,
                            client_ip,
                        };
                        match client.handle_webpage(scheme) {
                            Ok(_) => {}
                            Err(e) => error!("{}", e),
                        };
                    });
                }
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }
}

pub trait Handler {
    /// 请求 处理
    #[cfg(any(feature = "webpage", feature = "service"))]
    fn on_request(&mut self, request: Request, response: Response) -> Response;
    #[cfg(any(feature = "webpage", feature = "service"))]
    /// 预检请求处理 OPTIONS
    fn on_options(&mut self, _request: Request, mut response: Response) -> Response {
        response.header("Access-Control-Allow-Origin", "*");
        // GET,POST,OPTIONS
        response.header("Access-Control-Allow-Methods", "*");
        // Content-Type, Authorization, X-Real-IP,X-Forwarded-For
        response.header("Access-Control-Allow-Headers", "*");
        response.header("Access-Control-Allow-Credentials", "true");
        response.header("Access-Control-Expose-Headers", "content-disposition");
        response.header("Access-Control-Max-Age", "0");
        response
    }
    #[cfg(any(feature = "service", feature = "webpage"))]
    /// 响应 处理
    fn on_response(&mut self, request: Request, mut response: Response) -> Response {
        if !response.config.origin.is_empty() {
            let origin = request.header.get("origin").unwrap_or(&"".into()).clone();
            if !origin.is_empty() && response.config.origin.contains(&origin.to_string().clone()) {
                response.header("Access-Control-Allow-Origin", origin.as_str().unwrap_or(""));
            }
        } else {
            response.header("Access-Control-Allow-Origin", "*");
        }
        response
    }
    #[cfg(feature = "ws")]
    /// 握手监听
    fn on_open(&mut self, _websocket: Websocket) -> io::Result<()> {
        Ok(())
    }
    #[cfg(feature = "ws")]
    /// 接收到消息
    fn on_message(&mut self, _msg: Message) -> io::Result<()> {
        Ok(())
    }
    #[cfg(feature = "ws")]
    /// 关闭监听
    fn on_close(&mut self, _code: CloseCode, _reason: &str) {}
    #[cfg(feature = "ws")]
    /// 错误监听
    fn on_error(&mut self, _err: ErrorCode) {}
    #[cfg(feature = "ws")]
    /// 关机监听
    fn on_shutdown(&mut self) {}
    #[cfg(feature = "ws")]
    /// ping
    fn on_ping(&mut self, _msg: Message) {}
    #[cfg(feature = "ws")]
    /// pong
    fn on_pong(&mut self, _msg: Message) {}
}