1use std::io::{ErrorKind, Read, Write};
2use std::net::{TcpListener, TcpStream};
3use std::sync::Arc;
4use std::{fs, io, thread};
5use std::time::Duration;
6use json::{JsonValue, object};
7use log::info;
8use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
9use crate::body::Body;
10use crate::cors::Cors;
11use crate::header::Header;
12
13pub mod request;
14mod cors;
15pub mod header;
16pub mod body;
17
18#[derive(Clone, Debug)]
19pub struct WebConfig {
20 pub url: String,
21 pub domain: String,
23 pub public: String,
25 pub temp_dir: String,
27 cors: Cors,
28 ssl: bool,
29 ssl_privkey: String,
31 ssl_certs: String,
33}
34
35impl WebConfig {
36 pub fn default() -> Self {
38 Self {
39 url: "127.0.0.1:3535".to_string(),
40 domain: "127.0.0.1:3535".to_string(),
41 public: "./public".to_string(),
42 temp_dir: "./temp".to_string(),
43 cors: Cors {
44 allow_origin: "*".to_string(),
45 allow_methods: "GET,POST".to_string(),
46 allow_headers: "api,token,mode,content-type".to_string(),
47 allow_credentials: false,
48 max_age: 10000000,
49 },
50 ssl: false,
51 ssl_privkey: "".to_string(),
52 ssl_certs: "".to_string(),
53 }
54 }
55 pub fn load(data: JsonValue) -> Self {
57 let ssl = data["ssl"].as_bool().unwrap_or(false);
58 let domain = if ssl {
59 format!("https://{}", data["domain"].as_str().unwrap_or(""))
60 } else {
61 format!("http://{}", data["domain"].as_str().unwrap_or(""))
62 };
63 Self {
64 url: data["url"].to_string(),
65 domain,
66 public: data["public"].to_string(),
67 temp_dir: data["temp_dir"].to_string(),
68 cors: Cors::load(data["cors"].clone()),
69 ssl,
70 ssl_privkey: data["ssl_privkey"].to_string(),
71 ssl_certs: data["ssl_certs"].to_string(),
72 }
73 }
74 pub fn to_json(self) -> JsonValue {
75 let mut data = object! {};
76 data["url"] = self.url.into();
77 data["domain"] = self.domain.into();
78 data["public"] = self.public.into();
79 data["temp_dir"] = self.temp_dir.into();
80 data["ssl"] = self.ssl.into();
81 data["ssl_privkey"] = self.ssl_privkey.into();
82 data["ssl_certs"] = self.ssl_certs.into();
83 data["cors"] = self.cors.to_json();
84 data
85 }
86}
87
88pub struct WebService {}
89
90impl WebService {
91 pub fn bind(conf_path: &str, handle: fn(request: JsonValue) -> (i32, &'static str, JsonValue)) -> Result<(), io::Error> {
92 let conf = match fs::read_to_string(conf_path) {
93 Ok(content) => {
94 if content == "" {
95 return Err(io::Error::new(ErrorKind::BrokenPipe, "请配置配置文件参数"));
96 } else {
97 match json::parse(content.as_str()) {
98 Ok(e) => e,
99 Err(e) => {
100 return Err(io::Error::new(ErrorKind::BrokenPipe, e.to_string()));
101 }
102 }
103 }
104 }
105 Err(e) => {
106 if e.to_string().contains("No such file or directory") {
107 return Err(io::Error::new(ErrorKind::BrokenPipe, "请检查配置文件"));
108 }
109 return Err(io::Error::new(ErrorKind::BrokenPipe, e.to_string()));
110 }
111 };
112 let config = WebConfig::load(conf);
113
114 info!("web服务器启动 访问地址: {}",config.url);
115 info!("公共目录: {}", config.public);
116 info!("临时目录: {}", config.temp_dir);
117 info!("ssl开启: {}", config.ssl);
118 info!("根域名: {}", config.domain);
119
120 let acceptor = {
121 if config.ssl {
122 info!("privkey: {}", config.ssl_privkey.clone());
123 info!("certs: {}", config.ssl_certs.clone());
124 let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
125 acceptor.set_private_key_file(config.ssl_privkey.clone(), SslFiletype::PEM).unwrap();
126 acceptor.set_certificate_chain_file(config.ssl_certs.clone()).unwrap();
127 acceptor.check_private_key().unwrap();
128 Arc::new(acceptor.build())
129 } else {
130 Arc::new(SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap().build())
131 }
132 };
133 let config = config.clone();
134 loop {
135 let config = config.clone();
136 match TcpListener::bind(config.url.as_str().clone()) {
137 Ok(listener) => {
138 info!("服务启动成功");
139 for stream in listener.incoming() {
140 let header = Header { config: config.clone() };
141 let stream = stream.unwrap();
142 let acceptor = acceptor.clone();
143 thread::spawn(move || {
144 WebService::stream(stream.try_clone().unwrap(), acceptor.clone(), header.clone(), handle.clone());
145 });
146 }
147 }
148 Err(e) => {
149 info!("启动错误:{} 5秒后重启", e.to_string());
150 thread::sleep(Duration::from_secs(5));
151 }
152 }
153 }
154 }
155 pub fn stream(stream: TcpStream, acceptor: Arc<SslAcceptor>, header: Header, handle: fn(request: JsonValue) -> (i32, &'static str, JsonValue)) {
156 if header.config.ssl {
157 WebService::https(stream.try_clone().unwrap(), acceptor, header, handle);
158 } else {
159 WebService::http(stream.try_clone().unwrap(), header, handle);
160 }
161 }
162 pub fn http(mut stream: TcpStream, mut headers: Header, fun: fn(request: JsonValue) -> (i32, &'static str, JsonValue)) {
163 let client_ip = stream.local_addr().unwrap().clone();
164 let client_ip = client_ip.ip().to_string();
165
166
167 let mut buf = vec![];
168 let mut buffer = [0; 1024];
169 let mut count = 1024;
170 while count == 1024 {
171 count = stream.read(&mut buffer).unwrap();
172 buf = [buf, buffer[0..count].to_vec()].concat();
173 }
174 let data: String = buf.iter().map(|&c| c as char).collect();
175 let mut header = headers.def(data.clone());
176 header["client-ip"] = JsonValue::from(client_ip.clone());
177 let data_length = header["data-length"].as_usize().unwrap();
178 let body_length = header["content-length"].as_usize().unwrap();
179 let header_length = header["header-length"].as_usize().unwrap();
180 let mut mun = data_length - header_length;
181 while mun < body_length {
183 let mut buffer = [0; 1024];
184 let count = stream.read(&mut buffer).unwrap();
185 mun += count;
186 buf = [buf, buffer[0..count].to_vec()].concat();
187 };
188 let body = Body::def(header.clone(), buf[header_length..].to_owned().clone());
189 let (_, body) = request::Http::default(headers.config.cors.clone()).handle(header.clone(), body.clone(), fun);
190 stream.write_all(body.as_bytes()).unwrap();
191 stream.flush().unwrap();
192 }
193 pub fn https(stream: TcpStream, acceptor: Arc<SslAcceptor>, mut headers: Header, fun: fn(request: JsonValue) -> (i32, &'static str, JsonValue)) {
194 let client_ip = stream.local_addr().unwrap().clone();
195 let client_ip = client_ip.ip().to_string();
196
197 match acceptor.accept(stream) {
198 Ok(mut stream) => {
199 let mut buf = vec![];
200 let mut buffer = [0; 1024 * 10];
201 let mut count = 1024;
202 while count == 1024 {
203 count = stream.read(&mut buffer).unwrap();
204 buf = [buf, buffer[0..count].to_vec()].concat();
205 }
206 let data: String = buf.iter().map(|&c| c as char).collect();
207 let mut header = headers.def(data.clone());
208 header["client-ip"] = JsonValue::from(client_ip.clone());
209 let data_length = header["data-length"].as_usize().unwrap();
210 let body_length = header["content-length"].as_usize().unwrap();
211 let header_length = header["header-length"].as_usize().unwrap();
212 let mut mun = data_length - header_length;
213 while mun < body_length {
215 let mut buffer = [0; 1024];
216 let count = stream.read(&mut buffer).unwrap();
217 mun += count;
218 buf = [buf, buffer[0..count].to_vec()].concat();
219 };
220 let body = Body::def(header.clone(), buf[header_length..].to_owned().clone());
221 let (state, body) = request::Http::default(headers.config.cors.clone()).handle(header.clone(), body.clone(), fun);
222 if state {
223 stream.ssl_write(body.as_bytes()).unwrap();
224 stream.flush().unwrap();
225 }
226 }
227 Err(e) => {
228 info!("{}",e.to_string());
229 }
230 }
231 }
232}