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
use crate::config::OctaneConfig;
use crate::file_handler::FileHandler;
use crate::responder::StatusCode;
use crate::responder::{BoxReader, Response};
use std::error;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::marker::Unpin;
use std::path::PathBuf;
use tokio::io::{copy, AsyncRead, AsyncWrite, AsyncWriteExt};

/// The Error structure holds the kind of error code and
/// the location of the custom 404 file, if given by the user
/// and manages sending errors on internal http errors and other instances
/// will send with blank content if no 404 file is found or will send the
/// 404 file directly if given.
///
/// You will not have to use this manually, to send errors on your own, you
/// can do so by just specifying the error code and the content like
/// `res.status(status_code).send("")`.
pub struct Error {
    kind: StatusCode,
    file_404: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Custom error type for invalid paths
pub struct InvalidPathError;
#[derive(Debug, Clone, PartialEq, Eq)]
// Custom error type for invalid SSL certificates
pub struct InvalidCertError;

impl Error {
    pub async fn err<S>(
        status_code: StatusCode,
        config: &OctaneConfig,
        stream: S,
    ) -> Result<(), Box<dyn error::Error>>
    where
        S: AsyncRead + AsyncWrite + Unpin,
    {
        Error {
            kind: status_code,
            file_404: config.file_404.as_ref().map(|e| e.to_path_buf()),
        }
        .send(stream)
        .await
    }
    async fn send<S>(self, mut stream: S) -> Result<(), Box<dyn error::Error>>
    where
        S: AsyncRead + AsyncWrite + Unpin,
    {
        let mut res = Response::new_from_slice(b"");
        if self.kind == StatusCode::NotFound {
            if let Some(file_404) = self.file_404 {
                let file = FileHandler::handle_file(&file_404)?;
                res = Response::new(
                    Box::new(file.file) as BoxReader,
                    Some(file.meta.len() as usize),
                );
                res.status(self.kind)
                    .default_headers()
                    .set("Content-Type", "text/html");
            } else {
                res.status(self.kind);
            }
        }
        let mut response = res.get_data();
        stream.write_all(response.0.as_bytes()).await?;
        copy(&mut response.1, &mut stream).await?;
        Ok(())
    }
}

impl Display for InvalidPathError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        // TODO: make more informative
        write!(f, "Invalid path error")
    }
}

impl error::Error for InvalidPathError {}