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
use std::{
    net::{Incoming, TcpListener},
    sync::Arc,
};

use crate::{http::start_http, request::Request, thread_pool::ThreadPool};
pub use dyn_clone::DynClone;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

#[derive(Clone, Copy)]
pub enum Method {
    GET,
    POST,
}
pub trait Route: DynClone {
    fn get_path(&self) -> &str;
    fn get_method(&self) -> Method;
    fn get_body(&self) -> Vec<u8>;
    fn post_body(&self) -> fn(Request) -> Vec<u8>;
}

pub struct HttpListener {
    socket: TcpListener,
    pub config: Config,
    pub pool: ThreadPool,
    pub ssl_acpt: Option<Arc<SslAcceptor>>,
}

impl HttpListener {
    pub fn new(socket: TcpListener, config: Config) -> HttpListener {
        if config.ssl.clone() {
            let ssl_acpt = Some(build_https(
                config.ssl_chain.clone().unwrap(),
                config.ssl_priv.clone().unwrap(),
            ));
            return HttpListener {
                socket,
                config,
                pool: ThreadPool::new(4),
                ssl_acpt,
            };
        } else {
            return HttpListener {
                socket,
                config,
                pool: ThreadPool::new(4),
                ssl_acpt: None,
            };
        }
    }

    pub fn start(self) {
        start_http(self)
    }

    pub fn get_stream(&self) -> Incoming<'_> {
        self.socket.incoming()
    }
}

pub struct Routes {
    routes: Vec<Box<dyn Route>>,
}

impl Routes {
    pub fn new<R: Into<Vec<Box<dyn Route>>>>(routes: R) -> Routes {
        let routes = routes.into();
        Routes { routes }
    }

    pub fn get_stream(self) -> Vec<Box<dyn Route>> {
        self.routes
    }
}

#[derive(Clone)]
pub struct Config {
    mount_point: Option<String>,
    get_routes: Option<Vec<(String, Vec<u8>)>>,
    post_routes: Option<Vec<(String, fn(Request) -> Vec<u8>)>>,
    debug: bool,
    pub ssl: bool,
    ssl_chain: Option<String>,
    ssl_priv: Option<String>,
    headers: Option<Vec<String>>,
    br: bool,
    gzip: bool,
}

impl Config {
    /// Generates default settings (which don't work by itself)
    ///
    /// Chain with mount_point or routes
    ///
    /// ### Example:
    /// ```ignore
    /// use tinyhttp::config::*;
    /// use tinyhttp::tinyhttp_codegen::*;
    ///
    /// #[get("/test")]
    /// fn get_test() -> String {
    ///   String::from("Hello, there!\n")
    /// }
    ///
    /// let routes = Routes::new(vec![get_test()]);
    /// let routes_config = Config::new().routes(routes);
    /// /// or
    /// let mount_config = Config::new().mount_point(".");
    /// ```

    pub fn new() -> Config {
        //assert!(routes.len() > 0);

        simple_logger::SimpleLogger::new()
            .with_level(log::LevelFilter::Warn)
            .env()
            .init()
            .unwrap();
        Config {
            mount_point: None,
            get_routes: None,
            post_routes: None,
            debug: false,
            ssl: false,
            ssl_chain: None,
            ssl_priv: None,
            headers: None,
            gzip: false,
            br: false,
        }
    }

    /// A mount point that will be searched when a request isn't defined with a get or post route
    ///
    /// ### Example:
    /// ```ignore
    /// let config = Config::new().mount_point(".")
    /// /// if index.html exists in current directory, it will be returned if "/" or "/index.html" is requested.
    /// ```

    pub fn mount_point<P: Into<String>>(mut self, path: P) -> Self {
        self.mount_point = Some(path.into());
        self
    }

    /// Add routes with a Route member
    ///
    /// ### Example:
    /// ```ignore
    /// use tinyhttp::config::*;
    /// use tinyhttp::tinyhttp_codegen::*;
    ///
    ///
    /// #[get("/test")]
    /// fn get_test() -> &'static str {
    ///   "Hello, World!"
    /// }
    ///
    /// #[post("/test")]
    /// fn post_test(body: Vec<u8>) -> Vec<u8> {
    ///   "Hello, Post!".into()
    /// }
    ///
    /// fn main() {
    ///   let socket = TcpListener::new(":::80").unwrap();
    ///   let routes = Routes::new(vec![get_test(), post_test()]);
    ///   let config = Config::new().routes(routes);
    ///   let http = HttpListener::new(socket, config);
    ///
    ///   http.start();
    /// }
    /// ```

    pub fn routes(mut self, routes: Routes) -> Self {
        let mut get_routes: Vec<(String, Vec<u8>)> = vec![];
        let mut post_routes: Vec<(String, fn(Request) -> Vec<u8>)> = vec![];
        let routes = routes.get_stream();

        for route in routes {
            let clone = dyn_clone::clone_box(&*route);
            match route.get_method() {
                Method::GET => {
                    log::info!("Added GET route: {}", route.get_path());
                    get_routes.push((clone.get_path().to_string(), clone.get_body()));
                }
                Method::POST => {
                    log::info!("Added POST route: {}", route.get_path());
                    post_routes.push((clone.get_path().to_string(), clone.post_body()));
                }
            }
        }
        if !get_routes.is_empty() {
            self.get_routes = Some(get_routes);
        } else {
            self.get_routes = None;
        }

        if !post_routes.is_empty() {
            self.post_routes = Some(post_routes);
        } else {
            self.post_routes = None;
        }

        self
    }

    /// Enables SSL
    ///
    /// ### Example:
    /// ```ignore
    /// let config = Config::new().ssl("./fullchain.pem", "./privkey.pem");
    /// ```
    /// This will only accept HTTPS connections

    pub fn ssl(mut self, ssl_chain: String, ssl_priv: String) -> Self {
        self.ssl_chain = Some(ssl_chain);
        self.ssl_priv = Some(ssl_priv);
        self.ssl = true;
        self
    }
    pub fn debug(mut self) -> Self {
        self.debug = true;
        self
    }

    /// Define custom headers
    ///
    /// ```ignore
    /// let config = Config::new().headers(vec!["Access-Control-Allow-Origin: *".into()]);
    /// ```
    pub fn headers<P: Into<Vec<String>>>(mut self, headers: P) -> Self {
        self.headers = Some(headers.into());
        self
    }

    /// DOES NOT WORK!
    /// Enables brotli compression
    pub fn br(mut self, res: bool) -> Self {
        self.br = res;
        self
    }

    /// Enables gzip compression
    pub fn gzip(mut self, res: bool) -> Self {
        self.gzip = res;
        self
    }
    pub fn get_headers(&self) -> Option<Vec<String>> {
        match self.headers.clone() {
            Some(vec) => Some(vec),
            None => None,
        }
    }
    pub fn get_br(&self) -> bool {
        self.br
    }
    pub fn get_gzip(&self) -> bool {
        self.gzip
    }
    pub fn get_debug(&self) -> bool {
        self.debug
    }
    pub fn get_mount(&self) -> Option<String> {
        self.mount_point.clone()
    }
    pub fn get_routes(&self, path: String) -> Option<(String, Vec<u8>)> {
        match self.get_routes.clone() {
            Some(vec) => {
                for i in vec {
                    if self.get_debug() {
                        log::info!("Route found: {}", i.0);
                    }
                    if i.0 == path {
                        return Some(i);
                    } else {
                        return None;
                    }
                }
            }
            None => return None,
        }
        None
    }

    pub fn post_routes(&self) -> Option<Vec<(String, fn(Request) -> Vec<u8>)>> {
        self.post_routes.clone()
    }
}

pub fn build_https(chain: String, private: String) -> Arc<SslAcceptor> {
    let mut acceptor = SslAcceptor::mozilla_modern_v5(SslMethod::tls()).unwrap();
    acceptor.set_certificate_chain_file(chain).unwrap();
    acceptor
        .set_private_key_file(private, SslFiletype::PEM)
        .unwrap();
    acceptor.check_private_key().unwrap();
    Arc::new(acceptor.build())
}