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
use crate::{HttpMethod, HttpVersion};
use std::collections::HashMap;
use std::convert::TryFrom;

#[allow(dead_code)]
#[derive(Debug, Clone)]
/// Represents http request
pub struct Request {
    method: HttpMethod,
    path: String,
    http_version: HttpVersion,
    headers: HashMap<String, String>,
    pub cookies: Option<HashMap<String, String>>,
    pub params: HashMap<String, String>,
    pub query: HashMap<String, String>,
    body: String,
}

// Access to fields
impl Request {
    #[inline]
    pub fn get_method(&self) -> HttpMethod {
        self.method
    }

    #[inline]
    pub fn get_path(&self) -> String {
        self.path.clone()
    }

    #[inline]
    pub fn get_http_version(&self) -> HttpVersion {
        self.http_version
    }

    #[inline]
    pub fn get_body(&self) -> String {
        self.body.clone()
    }

    #[inline]
    pub fn header(&self, key: &str) -> Option<&String> {
        self.headers.get(&key.to_string().to_lowercase())
    }

    #[inline]
    pub fn cookie(&self, key: &str) -> Option<&String> {
        let cookies = self.cookies.as_ref()?;
        cookies.get(&key.to_string())
    }
}

impl TryFrom<String> for Request {
    type Error = ();

    fn try_from(req: String) -> Result<Self, Self::Error> {
        if let Some([info, headers, body]) = split_http_request(req) {
            let info: Vec<&str> = info.split(' ').collect();
            let query = get_query(info[1]);

            if info.len() != 3 {
                return Err(());
            }

            let method = info[0].parse::<HttpMethod>();

            if method.is_err() {
                return Err(());
            }

            let http_version = http_ver(info[2]);
            if http_version.is_none() {
                return Err(());
            }

            let headers = if let Some(headers) = parse_headers(headers) {
                headers
            } else {
                return Err(());
            };

            Ok(Self {
                method: method.unwrap(),
                path: info[1].to_string(),
                http_version: http_version.unwrap(),
                cookies: parse_cookies(headers.get("cookie")),
                headers,
                params: HashMap::new(),
                query,
                body,
            })
        } else {
            Err(())
        }
    }
}

fn split_http_request(req: String) -> Option<[String; 3]> {
    let mut lines = req.lines();
    let info = lines.next()?;
    let mut headers = String::new();

    while let Some(header) = lines.next() {
        if header == "" {
            break;
        }

        headers.push_str(format!("{}\r\n", header).as_str());
    }

    let body: String = lines.collect();

    Some([info.into(), headers, body])
}

fn parse_headers(headers: String) -> Option<HashMap<String, String>> {
    fn parse_header(s: String) -> Option<(String, String)> {
        let mut s = s.chars();
        let mut key = String::new();
        let mut next_char = 0 as char;

        while next_char != ':' {
            next_char = s.next()?;

            if next_char != ':' {
                key.push(next_char);
            }
        }

        s.next();

        Some((key.to_lowercase(), s.collect()))
    }

    let mut map = HashMap::new();

    for line in headers.lines() {
        let data = parse_header(line.to_string());

        data.as_ref()?;

        let data = data.unwrap();

        map.insert(data.0, data.1);
    }

    Some(map)
}

fn http_ver(s: &str) -> Option<HttpVersion> {
    match s {
        "HTTP/1.0" => Some(HttpVersion::Ver1),
        "HTTP/1.1" => Some(HttpVersion::Ver11),
        "HTTP/2.0" => Some(HttpVersion::Ver2),
        _ => None,
    }
}

fn get_query(path: &str) -> HashMap<String, String> {
    let query: Vec<&str> = path.split('?').collect();

    if query.len() == 1 {
        return HashMap::new();
    }

    x_www_form_urlencoded(query[1])
}

fn parse_cookies(cookies: Option<&String>) -> Option<HashMap<String, String>> {
    fn parse_cookie<'a>(cookie: &'a str) -> Option<[&'a str; 2]> {
        let cookie = cookie
            .split('=')
            .take(2)
            .map(|s| s.trim())
            .collect::<Vec<&'a str>>();

        Some([cookie.get(0)?, cookie.get(1)?])
    }

    let cookies = cookies?
        .split(';')
        .map(|el| parse_cookie(el))
        .collect::<Vec<_>>();

    let mut cookie_map = HashMap::new();

    for cookie in cookies {
        let [name, value] = cookie?;

        cookie_map.insert(name.to_string(), value.to_string());
    }

    Some(cookie_map)
}

pub fn x_www_form_urlencoded(path: &str) -> HashMap<String, String> {
    let mut ret = HashMap::new();

    for el in path.split('&') {
        let parameter = el.split('=').collect::<Vec<&str>>();
        ret.insert(parameter[0].to_string(), parameter[1].to_string());
    }

    ret
}