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
mod indexing;
mod ranges;
mod auth;
pub use auth::AuthConfig;

use std::collections::HashMap;
use std::fs::{self, File, OpenOptions};
use std::io::{stdout, BufReader, ErrorKind::*, Read, Seek, SeekFrom, Write};
use std::ops::{DerefMut, Range};
use std::path::Path;
use std::sync::Mutex;

use crate::request::{HttpRequest, RequestMethod};
use crate::Result;
use self::indexing::index_of;
use self::ranges::get_range_for;

use mime::Mime;

/// HandlerFunc trait
///
/// Represents a function that handles an [HttpRequest]
/// It receives a mutable reference to an [HttpRequest] and returns a [Result]<()>
pub trait HandlerFunc : Fn(&mut HttpRequest) -> Result<()> + Send + Sync + 'static { }
impl<T> HandlerFunc for T
where T: Fn(&mut HttpRequest) -> Result<()>  + Send + Sync + 'static { }

/// Interceptor trait
///
/// Represents a function that "intercepts" a request.
/// It can change it's state or log it's output.
pub trait Interceptor: Fn(&mut HttpRequest) + Send + Sync + 'static { }
impl<T> Interceptor for T
where T: Fn(&mut HttpRequest) + Send + Sync + 'static { }

pub type HandlerTable = HashMap<RequestMethod,HashMap<String,Box<dyn HandlerFunc>>>;

/// Handler
///
/// Matches [requests](HttpRequest) by their method and url, and
/// executes different handler functions for them.
///
/// # Example
/// ```
/// use http_srv::request::handler::{self,*};
/// use http_srv::request::RequestMethod;
///
/// let mut handler = Handler::new();
/// handler.get("/", |req| {
///     req.respond_buf(b"Hello world! :)")
/// });
/// handler.add_default(RequestMethod::GET, handler::cat_handler);
/// handler.post_interceptor(handler::log_stdout);
/// ```
pub struct Handler {
    handlers: HandlerTable,
    defaults: HashMap<RequestMethod,Box<dyn HandlerFunc>>,
    pre_interceptors: Vec<Box<dyn Interceptor>>,
    post_interceptors: Vec<Box<dyn Interceptor>>,
}

impl Handler {
    pub fn new() -> Self {
        Self { handlers: HashMap::new(), defaults: HashMap::new(),
               pre_interceptors: Vec::new(), post_interceptors: Vec::new() }
    }
    /// Shortcut for [add](Handler::add)([RequestMethod::GET], ...)
    #[inline]
    pub fn get(&mut self, url: &str, f: impl HandlerFunc) {
        self.add(RequestMethod::GET,url,f);
    }
    /// Shortcut for [add](Handler::add)([RequestMethod::POST], ...)
    #[inline]
    pub fn post(&mut self, url: &str, f: impl HandlerFunc) {
        self.add(RequestMethod::POST,url,f);
    }
    /// Shortcut for [add](Handler::add)([RequestMethod::DELETE], ...)
    #[inline]
    pub fn delete(&mut self, url: &str, f: impl HandlerFunc) {
        self.add(RequestMethod::DELETE,url,f);
    }
    /// Shortcut for [add](Handler::add)([RequestMethod::HEAD], ...)
    #[inline]
    pub fn head(&mut self, url: &str, f: impl HandlerFunc) {
        self.add(RequestMethod::HEAD,url,f);
    }
    /// Adds a handler for a request type
    ///
    /// - method: HTTP [method](RequestMethod) to match
    /// - url: URL for the handler
    /// - f: [Handler](HandlerFunc) for the request
    ///
    pub fn add(&mut self, method: RequestMethod, url: &str, f: impl HandlerFunc) {
        if !self.handlers.contains_key(&method) {
            self.handlers.insert(method, HashMap::new());
        }
        let map = self.handlers.get_mut(&method).unwrap();
        map.insert(url.to_string(), Box::new(f));
    }
    /// Adds a default handler for all requests of a certain type
    ///
    /// - method: HTTP [method](RequestMethod) to match
    /// - f: [Handler](HandlerFunc) for the requests
    ///
    #[inline]
    pub fn add_default(&mut self, method: RequestMethod, f: impl HandlerFunc) {
        self.defaults.insert(method, Box::new(f));
    }
    /// Add a function to run before the request is processed
    #[inline]
    pub fn pre_interceptor(&mut self, f: impl Interceptor) {
        self.pre_interceptors.push(Box::new(f));
    }
    /// Add a function to run after the request is processed
    #[inline]
    pub fn post_interceptor(&mut self, f: impl Interceptor) {
        self.post_interceptors.push(Box::new(f));
    }
    /// Get the handler for a certain method and url
    pub fn get_handler(&self, method: &RequestMethod, url: &str) -> Option<&impl HandlerFunc> {
        match self.handlers.get(method) {
            Some(map) => map.get(url).or_else(|| self.defaults.get(method)),
            None => self.defaults.get(method),
        }
    }
    /// Handles a request if it finds a [HandlerFunc] for it.
    /// Else, it returns a 403 FORBIDDEN response
    pub fn handle(&self, req: &mut HttpRequest) -> Result<()> {
        self.pre_interceptors.iter().for_each(|f| f(req));
        let ret = match self.get_handler(req.method(), req.url()) {
            Some(handler) => handler(req).or_else(|err| {
                eprintln!("ERROR: {err}");
                req.server_error()
            }),
            None => req.forbidden(),
        };
        self.post_interceptors.iter().for_each(|f| f(req));
        ret
    }
}

impl Default for Handler {
    /// Default Handler
    ///
    /// # Pre Interceptors
    ///  - [suffix_html]
    ///  - Set Header: "Accept-Ranges: bytes"
    ///
    /// # Handler Functions
    /// - [GET](RequestMethod::GET): [cat_handler]
    /// - [POST](RequestMethod::POST): [post_handler]
    /// - [DELETE](RequestMethod::DELETE): [delete_handler]
    /// - [HEAD](RequestMethod::HEAD): [head_handler]
    ///
    /// - [GET](RequestMethod::GET) "/": [index_handler]
    /// - [HEAD](RequestMethod::HEAD) "/": [index_handler]
    ///
    /// # Post Interceptors
    ///  - [log_stdout]
    ///
    fn default() -> Self {
        let mut handler = Self::new();
        handler.pre_interceptor(suffix_html);
        handler.pre_interceptor(|req| {
            req.set_header("Accept-Ranges", "bytes");
        });

        handler.add_default(RequestMethod::GET, cat_handler);
        handler.add_default(RequestMethod::POST, post_handler);
        handler.add_default(RequestMethod::DELETE, delete_handler);
        handler.add_default(RequestMethod::HEAD, head_handler);

        handler.get("/", index_handler);
        handler.head("/", index_handler);

        handler.post_interceptor(log_stdout);
        handler
    }
}

fn head_headers(req: &mut HttpRequest) -> Result<Option<Range<u64>>> {
    let filename = req.filename()?;
    if dir_exists(&filename) {
        return Ok(None);
    }
    match File::open(&filename) {
        Ok(file) => {
            if let Ok(mime) = Mime::from_filename(&filename) {
                req.set_header("Content-Type", mime.to_string());
            }
            let metadata = file.metadata()?;
            let len = metadata.len();
            if metadata.is_file() {
                req.set_header("Content-Length", len.to_string());
            }
            let Some(range) = req.header("Range") else { return Ok(None); };
            let range = get_range_for(range, len)?;
            if range.end > len || range.end <= range.start {
                req.set_status(416);
            } else {
                req.set_status(206);
                req.set_header("Content-Length", (range.end - range.start).to_string());
                req.set_header("Content-Range", &format!("bytes {}-{}/{}", range.start, range.end - 1, len));
            }
            return Ok(Some(range));
        },
        Err(err) => {
            let status = match err.kind() {
                PermissionDenied => 403,
                _ => 404,
            };
            req.set_status(status);
        }
    };
    Ok(None)
}

/// Returns the headers that would be sent by a [GET](RequestType::GET)
/// [request](HttpRequest), with an empty body.
pub fn head_handler(req: &mut HttpRequest) -> Result<()> {
    head_headers(req)?;
    let filename = req.filename()?;
    let len =
    if req.status().is_http_err() {
        req.error_page().len()
    } else if dir_exists(&filename) {
        index_of(&filename)?.len()
    } else { 0 };

    if len > 0 {
        req.set_header("Content-Length", len.to_string());
    }
    req.respond()
}

/// Returns the file, or an index of the directory.
pub fn cat_handler(req: &mut HttpRequest) -> Result<()> {
    let range = head_headers(req)?;
    if req.status().is_http_err()  {
        return req.respond_error_page();
    };
    let filename = req.filename()?;
    if dir_exists(&filename) {
        let page = index_of(&filename)?;
        return req.respond_buf(page.as_bytes());
    }
    let mut file = File::open(req.filename()?)?;
    match range {
        Some(range) => {
            file.seek(SeekFrom::Start(range.start))?;
            let mut reader = BufReader::new(file)
                                       .take(range.end - range.start);
            req.respond_reader(&mut reader)
        },
        None => {
            let mut reader = BufReader::new(file);
            req.respond_reader(&mut reader)
        }
    }
}

/// Save the data of the request to the url
pub fn post_handler(req: &mut HttpRequest) -> Result<()> {
    let filename = req.filename()?;
    match File::create(&filename) {
        Ok(mut file) => {
            req.read_data(&mut file)?;
            req.ok()
        },
        Err(err) => {
            println!("Error opening {}: {err}", &filename);
            match err.kind() {
                PermissionDenied => req.forbidden(),
                _ => req.not_found(),
            }
        }
    }
}

/// Delete the filename
pub fn delete_handler(req: &mut HttpRequest) -> Result<()> {
    match fs::remove_file(req.filename()?) {
       Ok(_) => req.ok(),
       Err(err) =>
           match err.kind() {
                PermissionDenied => req.forbidden(),
                _ => req.not_found(),
           }
    }
}

fn file_exists(filename: &str) -> bool {
    Path::new(filename).is_file()
}

fn dir_exists(filename: &str) -> bool {
    Path::new(filename).is_dir()
}

/// Appends a suffix to the url
///
/// If the requested url doesn't exists, try to
/// append a suffix ('.html', '.php'), and if it
/// exists, modify the url.
pub fn suffix_html(req: &mut HttpRequest) {
    if file_exists(&req.url()[1..]) { return; }
    for suffix in [".html",".php"] {
        let mut filename = req.url().to_owned();
        filename.push_str(suffix);
        if file_exists(&filename[1..]) {
            req.set_url(filename);
            break;
        }
    }
}

#[inline(always)]
fn log(w: &mut dyn Write, req: &HttpRequest) {
    write!(w, "{} {} {} {}\n", req.method(), req.url(), req.status(), req.status_msg()).unwrap();
}

/// Log the [request](HttpRequest) to stdout
pub fn log_stdout(req: &mut HttpRequest) {
    log(&mut stdout(), req);
}

/// Log the [request](HttpRequest) to a file
///
/// The file is appended to, or created if it doesn't exists
pub fn log_file(filename: &str) -> impl Interceptor {
    let file = OpenOptions::new()
                .append(true)
                .create(true)
                .open(filename)
                .unwrap_or_else(|_| panic!("Error creating file: {filename}"));
    let file = Mutex::new(file);
    move |req| {
        let mut file = file.lock().unwrap();
        log(file.deref_mut(), req);
    }
}

pub fn index_handler(req: &mut HttpRequest) -> Result<()> {
        if file_exists("index.html") {
            req.set_url("/index.html".to_owned());
        }
        cat_handler(req)
}

trait IsOk {
    fn is_http_ok(&self) -> bool;
    fn is_http_err(&self) -> bool;
}

impl IsOk for u16 {
    fn is_http_ok(&self) -> bool {
        (200..300).contains(self)
    }
    fn is_http_err(&self) -> bool {
        !self.is_http_ok()
    }
}