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
//! HTTP request type

use std::error::Error;
use std::io::ErrorKind;
use std::{env, error, fmt, fs, str};

use crate::Method;
use crate::Request;
use std::collections::HashMap;

/// Whenever an unsupported/invalid content type gets requested
#[derive(Debug)]
pub struct InvalidContentType(String);
impl error::Error for InvalidContentType {}

impl fmt::Display for InvalidContentType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Invalid Content Type: {}", self.0)
    }
}

impl From<&str> for InvalidContentType {
    fn from(content_type: &str) -> Self {
        InvalidContentType(content_type.to_string())
    }
}

#[derive(Hash, Eq, PartialEq, Copy, Clone)]
enum ContentType {
    CSS,
    HTML,
    GIF,
    PNG,
    JPEG,
    TEXT,
    SVG,
    XML,
    PDF,
    ICO,
}

impl ContentType {
    fn from_ext_str(ext: &str) -> Result<ContentType, InvalidContentType> {
        let content_types: HashMap<&str, ContentType> = [
            ("css", ContentType::CSS),
            ("gif", ContentType::GIF),
            ("htm", ContentType::HTML),
            ("html", ContentType::HTML),
            ("jpeg", ContentType::JPEG),
            ("jpg", ContentType::JPEG),
            ("png", ContentType::PNG),
            ("svg", ContentType::SVG),
            ("txt", ContentType::TEXT),
            ("xml", ContentType::XML),
            ("pdf", ContentType::PDF),
            ("ico", ContentType::ICO),
        ]
        .iter()
        .cloned()
        .collect();
        if let Some(content_type) = content_types.get(ext) {
            Ok(*content_type)
        } else {
            Err(InvalidContentType(ext.to_string()))
        }
    }

    fn as_str(&self) -> &str {
        let content_types: HashMap<ContentType, &str> = [
            (ContentType::CSS, "text/css"),
            (ContentType::GIF, "image/gif"),
            (ContentType::HTML, "text/html"),
            (ContentType::HTML, "text/html"),
            (ContentType::JPEG, "image/jpeg"),
            (ContentType::JPEG, "image/jpeg"),
            (ContentType::PNG, "image/png"),
            (ContentType::SVG, "image/svg+xml"),
            (ContentType::TEXT, "text/plain"),
            (ContentType::XML, "application/xml"),
            (ContentType::PDF, "application/pdf"),
            (ContentType::ICO, "image/x-icon"),
        ]
        .iter()
        .cloned()
        .collect();
        content_types.get(self).unwrap()
    }
}

#[derive(Default)]
pub struct Headers {
    content_type: Option<ContentType>,
}

impl Headers {
    /// Create new ResponseHeader
    /// By default the content_type is None
    pub fn new() -> Self {
        Headers { content_type: None }
    }
}

#[derive(Hash, Eq, PartialEq, Clone)]
#[allow(non_camel_case_types)]
enum StatusCode {
    CONTINUE,
    SWITCHING_PROTOCOLS,
    OK,
    CREATED,
    ACCEPTED,
    NON_AUTHORITATIVE_INFORMATION,
    NO_CONTENT,
    RESET_CONTENT,
    PARTIAL_CONTENT,
    MULTIPLE_CHOICES,
    MOVED_PERMANENTLY,
    FOUND,
    SEE_OTHER,
    NOT_MODIFIED,
    USE_PROXY,
    TEMPORARY_REDIRECT,
    BAD_REQUEST,
    UNAUTHORIZED,
    PAYMENT_REQUIRED,
    FORBIDDEN,
    NOT_FOUND,
    METHOD_NOT_ALLOWED,
    NOT_ACCEPTABLE,
    PROXY_AUTHENTICATION_REQUIRED,
    REQUEST_TIME_OUT,
    CONFLICT,
    GONE,
    LENGTH_REQUIRED,
    PRECONDITION_FAILED,
    REQUEST_ENTITY_TOO_LARGE,
    REQUEST_URI_TOO_LARGE,
    UNSUPPORTED_MEDIA_TYPE,
    REQUEST_RANGE_NOT_SATISFIABLE,
    EXPECTATION_FAILED,
    INTERNAL_SERVER_ERROR,
    NOT_IMPLEMENTED,
    BAD_GATEWAY,
    SERVICE_UNAVAILABLE,
    GATEWAY_TIME_OUT,
    HTTP_VERSION_NOT_SUPPORTED,
}

impl Default for StatusCode {
    fn default() -> Self {
        StatusCode::OK
    }
}

impl fmt::Display for StatusCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let codes: HashMap<StatusCode, i32> = [
            (StatusCode::CONTINUE, 100),
            (StatusCode::SWITCHING_PROTOCOLS, 101),
            (StatusCode::OK, 200),
            (StatusCode::CREATED, 201),
            (StatusCode::ACCEPTED, 202),
            (StatusCode::NON_AUTHORITATIVE_INFORMATION, 203),
            (StatusCode::NO_CONTENT, 204),
            (StatusCode::RESET_CONTENT, 205),
            (StatusCode::PARTIAL_CONTENT, 206),
            (StatusCode::MULTIPLE_CHOICES, 300),
            (StatusCode::MOVED_PERMANENTLY, 301),
            (StatusCode::FOUND, 302),
            (StatusCode::SEE_OTHER, 303),
            (StatusCode::NOT_MODIFIED, 304),
            (StatusCode::USE_PROXY, 305),
            (StatusCode::TEMPORARY_REDIRECT, 307),
            (StatusCode::BAD_REQUEST, 400),
            (StatusCode::UNAUTHORIZED, 401),
            (StatusCode::PAYMENT_REQUIRED, 402),
            (StatusCode::FORBIDDEN, 403),
            (StatusCode::NOT_FOUND, 404),
            (StatusCode::METHOD_NOT_ALLOWED, 405),
            (StatusCode::NOT_ACCEPTABLE, 406),
            (StatusCode::PROXY_AUTHENTICATION_REQUIRED, 407),
            (StatusCode::REQUEST_TIME_OUT, 408),
            (StatusCode::CONFLICT, 409),
            (StatusCode::GONE, 410),
            (StatusCode::LENGTH_REQUIRED, 411),
            (StatusCode::PRECONDITION_FAILED, 412),
            (StatusCode::REQUEST_ENTITY_TOO_LARGE, 413),
            (StatusCode::REQUEST_URI_TOO_LARGE, 414),
            (StatusCode::UNSUPPORTED_MEDIA_TYPE, 415),
            (StatusCode::REQUEST_RANGE_NOT_SATISFIABLE, 416),
            (StatusCode::EXPECTATION_FAILED, 417),
            (StatusCode::INTERNAL_SERVER_ERROR, 500),
            (StatusCode::NOT_IMPLEMENTED, 501),
            (StatusCode::BAD_GATEWAY, 502),
            (StatusCode::SERVICE_UNAVAILABLE, 503),
            (StatusCode::GATEWAY_TIME_OUT, 504),
            (StatusCode::HTTP_VERSION_NOT_SUPPORTED, 505),
        ]
        .iter()
        .cloned()
        .collect();
        write!(f, "{}", codes.get(self).unwrap())
    }
}

fn add_file(path: &str, head: bool) -> Result<Response, Box<dyn Error>> {
    let mut root = String::from("/var/www");

    if env::var("LINDA_ROOT").is_ok() {
        root = env::var("LINDA_ROOT").unwrap();
    };

    let mut path = path.to_string();
    if path == "/" {
        path.push_str("index.html");
    }
    path = format!("{}{}", root, path);

    let contents = fs::read(&path);

    let mut response = Response::new();

    match contents {
        Ok(contents) => {
            // check if method type is not HEAD
            if !head {
                response.body = Some(contents);
            }

            // Get file extension
            let ext = path.split('.').last().unwrap_or("");
            response.headers.content_type = Some(ContentType::from_ext_str(ext)?);

            Ok(response)
        }
        Err(e) => {
            response.status = match e.kind() {
                ErrorKind::NotFound => {
                    // Set response body to 404.html if file not found
                    // check if method type is not HEAD
                    if !head {
                        response.body =
                            Some(fs::read(format!("{}/404.html", root)).unwrap_or_else(|_| vec![]));
                        response.headers.content_type = Some(ContentType::HTML);
                    }
                    StatusCode::NOT_FOUND
                }
                ErrorKind::PermissionDenied => StatusCode::FORBIDDEN,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            };
            Ok(response)
        }
    }
}

/// Process Request, returning a Response
///
/// # Error
///
/// Should not error, except for rare cases when the URI string is not valid UTF-8
pub fn response(request: &Request) -> Result<Response, Box<dyn Error>> {
    match *request.method() {
        Method::GET => add_file(
            request.uri().to_str().expect("Invalid file URI UTF8"),
            false,
        ),
        Method::HEAD => add_file(request.uri().to_str().expect("Invalid file URI UTF8"), true),
        _ => {
            let mut response = Response::new();
            response.status = StatusCode::NOT_IMPLEMENTED;
            Ok(response)
        }
    }
}

/// HTTP Response
///
/// Response = Status-Line
///           *(( general-header
///           | response-header
///           | entity-header ) CRLF)
///             CRLF
///           [ message-body ]
#[derive(Default)]
pub struct Response {
    status: StatusCode,
    body: Option<Vec<u8>>,
    headers: Headers,
}

impl Response {
    /// Creates a new Response object with defaults:
    /// StatusCode::OK
    /// body: None
    /// empty Headers
    pub fn new() -> Self {
        Response {
            status: StatusCode::OK,
            body: None,
            headers: Headers::new(),
        }
    }

    /// Format Response object and return it as a Vec of bytes to write to a buffer
    pub fn format_response(&mut self) -> Vec<u8> {
        // Append Status-Line
        // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
        let mut result = format!("HTTP/1.1 {}\r\n", self.status);

        // Append Content-Type entity-header
        if let Some(content_type) = &self.headers.content_type {
            result = format!("{}Content-type: {}\r\n\r\n", result, content_type.as_str());
        }

        // Append body (if file)
        let mut bytes = result.as_bytes().to_vec();
        if self.body.is_some() {
            let body = self.body.as_mut().unwrap();

            bytes.append(body);
        }

        bytes
    }
}

impl fmt::Display for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
        writeln!(f, "HTTP/1.1 {}", self.status)
    }
}