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
use std::{
    collections::HashMap,
    ops::Deref,
    sync::{Arc, OnceLock},
};

use crate::request::Request;
pub use dyn_clone::DynClone;
use std::fmt::Debug;

#[cfg(feature = "ssl")]
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

use crate::response::Response;

use rusty_pool::{Builder, ThreadPool};

#[cfg(not(feature = "async"))]
use std::net::{Incoming, TcpListener};

#[cfg(not(feature = "async"))]
use crate::http::start_http;

#[cfg(feature = "async")]
use tokio::net::TcpListener;

#[cfg(feature = "async")]
use crate::async_http::start_http;

use std::sync::Mutex;

#[cfg(test)]
use std::any::Any;

type RouteVec = Vec<Box<dyn Route>>;

pub static PRE_MIDDLEWARE_CONST: OnceLock<Box<dyn FnMut(&mut Request) + Send + Sync>> =
    OnceLock::new();

pub static POST_MIDDLEWARE_CONST: OnceLock<Box<dyn FnMut(&mut Request) + Send + Sync>> =
    OnceLock::new();

#[derive(Clone, Copy, Debug)]
pub enum Method {
    GET,
    POST,
}

pub trait ToResponse: DynClone + Sync + Send {
    fn to_res(&self, res: Request) -> Response;
}

pub trait Route: DynClone + Sync + Send + ToResponse {
    fn get_path(&self) -> &str;
    fn get_method(&self) -> Method;
    fn wildcard(&self) -> Option<String>;
    fn clone_dyn(&self) -> Box<dyn Route>;

    #[cfg(test)]
    fn any(&self) -> &dyn Any;
}

impl Clone for Box<dyn Route> {
    fn clone(&self) -> Self {
        self.clone_dyn()
    }
}

pub struct HttpListener {
    pub(crate) socket: TcpListener,
    pub config: Config,
    pub pool: ThreadPool,
    pub use_pool: bool,
    #[cfg(feature = "ssl")]
    pub ssl_acpt: Option<Arc<SslAcceptor>>,
}

impl HttpListener {
    pub fn new<P: Into<TcpListener>>(socket: P, config: Config) -> HttpListener {
        #[cfg(feature = "log")]
        log::debug!("Using {} threads", num_cpus::get());

        if config.ssl {
            #[cfg(feature = "ssl")]
            let ssl_acpt = Some(build_https(
                config.ssl_chain.clone().unwrap(),
                config.ssl_priv.clone().unwrap(),
            ));
            HttpListener {
                socket: socket.into(),
                config,
                pool: ThreadPool::default(),
                #[cfg(feature = "ssl")]
                ssl_acpt,
                use_pool: true,
            }
        } else {
            HttpListener {
                socket: socket.into(),
                config,
                pool: ThreadPool::default(),
                #[cfg(feature = "ssl")]
                ssl_acpt: None,
                use_pool: true,
            }
        }
    }

    pub fn threads(mut self, threads: usize) -> Self {
        let pool = Builder::new().core_size(threads).build();

        self.pool = pool;
        self
    }

    pub fn use_tp(mut self, r: bool) -> Self {
        self.use_pool = r;
        self
    }

    #[cfg(not(feature = "async"))]
    pub fn start(self) {
        let conf_clone = self.config.clone();
        start_http(self, conf_clone);
    }

    #[cfg(feature = "async")]
    pub async fn start(self) {
        start_http(self).await;
    }

    #[cfg(not(feature = "async"))]
    pub fn get_stream(&self) -> Incoming<'_> {
        self.socket.incoming()
    }
}

#[derive(Clone)]
pub struct Routes {
    routes: RouteVec,
}

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

    pub fn get_stream(self) -> RouteVec {
        self.routes
    }
}

#[derive(Clone)]
pub struct Config {
    mount_point: Option<String>,
    get_routes: Option<HashMap<String, Box<dyn Route>>>,
    post_routes: Option<HashMap<String, Box<dyn Route>>>,
    debug: bool,
    pub ssl: bool,
    ssl_chain: Option<String>,
    ssl_priv: Option<String>,
    headers: Option<HashMap<String, String>>,
    br: bool,
    gzip: bool,
    spa: bool,
    http2: bool,
    response_middleware: Option<Arc<Mutex<dyn FnMut(&mut Response) + Send + Sync>>>,
    request_middleware: Option<Arc<Mutex<dyn FnMut(&mut Request) + Send + Sync>>>,
}

impl Default for Config {
    fn default() -> Self {
        Config::new()
    }
}

impl Config {
    /// Generates default settings (which don't work by itself)
    ///
    /// Chain with mount_point or routes
    ///
    /// ### Example:
    /// ```ignore
    /// use tinyhttp::prelude::*;
    ///
    /// #[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);

        #[cfg(feature = "log")]
        log::info!("tinyhttp version: {}", env!("CARGO_PKG_VERSION"));

        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,
            spa: false,
            http2: false,
            request_middleware: None,
            response_middleware: None,
        }
    }

    /// 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::prelude::*;
    ///
    ///
    /// #[get("/test")]
    /// fn get_test() -> &'static str {
    ///   "Hello, World!"
    /// }
    ///
    /// #[post("/test")]
    /// fn post_test() -> Vec<u8> {
    ///   b"Hello, Post!".to_vec()
    /// }
    ///
    /// 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 = HashMap::new();
        let mut post_routes = HashMap::new();
        let routes = routes.get_stream();

        for route in routes {
            match route.get_method() {
                Method::GET => {
                    #[cfg(feature = "log")]
                    log::info!("GET Route init!: {}", &route.get_path());

                    get_routes.insert(route.get_path().to_string(), route);
                }
                Method::POST => {
                    #[cfg(feature = "log")]
                    log::info!("POST Route init!: {}", &route.get_path());
                    post_routes.insert(route.get_path().to_string(), route);
                }
            }
        }
        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(mut self, headers: Vec<String>) -> Self {
        let mut hash_map: HashMap<String, String> = HashMap::new();
        for i in headers {
            let mut split = i.split_inclusive(": ");
            hash_map.insert(
                split.next().unwrap().to_string(),
                split.next().unwrap().to_string() + "\r\n",
            );
        }

        self.headers = Some(hash_map);
        self
    }

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

    pub fn spa(mut self, res: bool) -> Self {
        self.spa = res;
        self
    }

    /// Enables gzip compression
    pub fn gzip(mut self, res: bool) -> Self {
        self.gzip = res;
        self
    }

    pub fn http2(mut self, res: bool) -> Self {
        self.http2 = res;
        self
    }

    pub fn request_middleware<F: FnMut(&mut Request) + Send + Sync + 'static>(
        mut self,
        middleware_fn: F,
    ) -> Self {
        self.request_middleware = Some(Arc::new(Mutex::new(middleware_fn)));
        self
    }

    pub fn response_middleware<F: FnMut(&mut Response) + Send + Sync + 'static>(
        mut self,
        middleware_fn: F,
    ) -> Self {
        self.response_middleware = Some(Arc::new(Mutex::new(middleware_fn)));
        self
    }

    pub fn get_headers(&self) -> Option<&HashMap<String, String>> {
        self.headers.as_ref()
    }
    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.as_ref()
    }
    pub fn get_routes(&self, req_path: &str) -> Option<&dyn Route> {
        let req_path = if req_path.ends_with('/') && req_path.matches('/').count() > 1 {
            let mut chars = req_path.chars();
            chars.next_back();
            chars.as_str()
        } else {
            req_path
        };

        #[cfg(feature = "log")]
        log::trace!("get_routes -> new_path: {}", &req_path);

        let routes = self.get_routes.as_ref()?;

        if let Some(route) = routes.get(req_path) {
            return Some(route.deref());
        }

        if let Some((_, wildcard_route)) = routes
            .iter()
            .find(|(path, route)| req_path.starts_with(*path) && route.wildcard().is_some())
        {
            return Some(wildcard_route.deref());
        }

        None
    }

    pub fn post_routes(&self, req_path: &str) -> Option<&dyn Route> {
        #[cfg(feature = "log")]
        log::trace!("post_routes -> path: {}", req_path);

        let req_path = if req_path.ends_with('/') && req_path.matches('/').count() > 1 {
            let mut chars = req_path.chars();
            chars.next_back();
            chars.as_str()
        } else {
            req_path
        };

        #[cfg(feature = "log")]
        log::trace!("get_routes -> new_path: {}", &req_path);

        let routes = self.post_routes.as_ref()?;

        if let Some(route) = routes.get(req_path) {
            return Some(route.deref());
        }

        if let Some((_, wildcard_route)) = routes
            .iter()
            .find(|(path, route)| req_path.starts_with(*path) && route.wildcard().is_some())
        {
            return Some(wildcard_route.deref());
        }

        None
    }

    pub fn get_spa(&self) -> bool {
        self.spa
    }

    #[allow(dead_code)]
    pub(crate) fn get_request_middleware(
        &self,
    ) -> Option<Arc<Mutex<dyn FnMut(&mut Request) + Send + Sync>>> {
        if let Some(s) = &self.request_middleware {
            Some(Arc::clone(s))
        } else {
            None
        }
    }

    #[allow(dead_code)]
    pub(crate) fn get_response_middleware(
        &self,
    ) -> Option<Arc<Mutex<dyn FnMut(&mut Response) + Send + Sync>>> {
        if let Some(s) = &self.response_middleware {
            Some(Arc::clone(s))
        } else {
            None
        }
    }
}

#[cfg(feature = "ssl")]
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())
}