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
// TODO: make a web crawler example.

use std::cell::RefCell;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::io;
use std::mem;
use std::rc::Rc;

use crate::aio::handler::{
    Handler,
    Loop,
    Stream,
};
use crate::aio::net::{
    TcpConnection,
    TcpConnectionNotify,
};
use crate::aio::uhttp_uri::HttpUri;

use self::Msg::*;

fn deque_compare(buffer: &VecDeque<u8>, start: usize, len: usize, value: &[u8]) -> bool {
    if value.len() < len {
        return false;
    }
    let mut index = 0;
    for i in start..start + len {
        if buffer[i] != value[index] {
            return false;
        }
        index += 1;
    }
    true
}

fn parse_num(buffer: &VecDeque<u8>, start: usize, len: usize) -> Option<usize> {
    let mut result = 0;
    for i in start..start + len {
        if buffer[i] >= b'0' && buffer[i] <= b'9' {
            result *= 10;
            result += (buffer[i] - b'0') as usize;
        }
        else if result != 0 && buffer[i] != b' ' {
            return None;
        }
    }
    Some(result)
}

fn parse_headers(buffer: &VecDeque<u8>) -> Option<usize> {
    // TODO: parse other headers.
    let mut start = 0;
    for i in 0..buffer.len() {
        if buffer[i] == b'\n' {
            let text = b"Content-Length:";
            let end = start + text.len();
            if deque_compare(buffer, start, text.len(), text) {
                let num = parse_num(buffer, end, i - 1 - end); // - 1 to remove the \n.
                return num;
            }
            start = i + 1;
        }
    }
    None
}

fn remove_until_boundary(buffer: &mut VecDeque<u8>) {
    let mut index = buffer.len() - 1;
    for i in 0..buffer.len() {
        if i + 4 <= buffer.len() && deque_compare(&buffer, i, 4, b"\r\n\r\n") {
            index = i + 4;
            break;
        }
    }
    for _ in 0..index {
        buffer.pop_front();
    }
}

#[derive(Clone)]
struct Connection<HANDLER> {
    buffer: VecDeque<u8>,
    content_length: usize,
    handler: HANDLER,
    host: String,
    method: &'static str,
    path: String,
}

impl<HANDLER> Connection<HANDLER> {
    fn new(host: &str, handler: HANDLER, path: &str, method: &'static str) -> Self {
        Self {
            buffer: VecDeque::new(),
            content_length: 0,
            handler,
            host: host.to_string(),
            method,
            path: path.to_string(),
        }
    }
}

impl<HANDLER> TcpConnectionNotify for Connection<HANDLER>
where HANDLER: HttpHandler,
{
    fn connecting(&mut self, _connection: &mut TcpConnection, count: u32) {
        println!("Connecting. Attempt #{}", count);
    }

    fn connected(&mut self, connection: &mut TcpConnection) {
        if let Err(error) = connection.write(format!("{} {} HTTP/1.1\r\nHost: {}\r\n\r\n", self.method, self.path,
            self.host).into_bytes())
        {
            self.handler.error(error);
        }
    }

    fn error(&mut self, error: io::Error) {
        self.handler.error(error);
    }

    fn received(&mut self, connection: &mut TcpConnection, data: Vec<u8>) {
        self.buffer.extend(data);
        if self.content_length == 0 {
            match parse_headers(&self.buffer) {
                Some(content_length) => {
                    remove_until_boundary(&mut self.buffer);
                    self.content_length = content_length;
                },
                None => (), // Might find the content length in the next data.
            }
        }
        if self.buffer.len() >= self.content_length {
            let buffer = mem::replace(&mut self.buffer, VecDeque::new());
            self.handler.response(buffer.into());
            connection.dispose();
        }
    }
}

pub trait HttpHandler {
    fn response(&mut self, data: Vec<u8>);

    fn error(&mut self, _error: io::Error) {
    }
}

pub struct DefaultHttpHandler<ErrorMsg, MSG, SuccessMsg> {
    error_msg: ErrorMsg,
    stream: Stream<MSG>,
    success_msg: SuccessMsg,
}

impl<ErrorMsg, MSG, SuccessMsg> DefaultHttpHandler<ErrorMsg, MSG, SuccessMsg> {
    pub fn new(stream: &Stream<MSG>, success_msg: SuccessMsg, error_msg: ErrorMsg) -> Self {
        Self {
            error_msg,
            stream: stream.clone(),
            success_msg,
        }
    }
}

impl<ErrorMsg, MSG, SuccessMsg> HttpHandler for DefaultHttpHandler<ErrorMsg, MSG, SuccessMsg>
where MSG: Debug,
      ErrorMsg: Fn(io::Error) -> MSG,
      SuccessMsg: Fn(Vec<u8>) -> MSG,
{
    fn error(&mut self, error: io::Error) {
        self.stream.send((self.error_msg)(error));
    }

    fn response(&mut self, data: Vec<u8>) {
        self.stream.send((self.success_msg)(data));
    }
}

pub struct HttpHandlerIgnoreErr<MSG, SuccessMsg> {
    stream: Stream<MSG>,
    success_msg: SuccessMsg,
}

impl<MSG, SuccessMsg> HttpHandlerIgnoreErr<MSG, SuccessMsg> {
    pub fn new(stream: &Stream<MSG>, success_msg: SuccessMsg) -> Self {
        Self {
            stream: stream.clone(),
            success_msg,
        }
    }
}

impl<MSG, SuccessMsg> HttpHandler for HttpHandlerIgnoreErr<MSG, SuccessMsg>
where MSG: Debug,
      SuccessMsg: Fn(Vec<u8>) -> MSG,
{
    fn response(&mut self, data: Vec<u8>) {
        self.stream.send((self.success_msg)(data));
    }
}

pub struct Http {
}

impl Http {
    pub fn new() -> Self {
        Self {
        }
    }

    fn blocking<F: Fn(Rc<RefCell<io::Result<Vec<u8>>>>, &mut Loop) -> io::Result<()>>(&self, callback: F) -> io::Result<Vec<u8>> {
        let result = Rc::new(RefCell::new(Ok(vec![])));
        let mut event_loop = Loop::new()?;
        callback(result.clone(), &mut event_loop)?;
        event_loop.run()?;
        let mut result = result.borrow_mut();
        mem::replace(&mut *result, Ok(vec![]))
    }

    pub fn blocking_get(&self, uri: &str) -> io::Result<Vec<u8>> {
        self.blocking(|result, event_loop| {
            let stream = event_loop.spawn(BlockingHttpHandler::new(&event_loop, result));
            let http = Http::new();
            http.get(uri, event_loop, DefaultHttpHandler::new(&stream, HttpGet, HttpError))
                .map_err(|()| io::Error::new(io::ErrorKind::Other, ""))
        })
    }

    pub fn blocking_post(&self, uri: &str) -> io::Result<Vec<u8>> {
        self.blocking(|result, event_loop| {
            let stream = event_loop.spawn(BlockingHttpHandler::new(&event_loop, result));
            let http = Http::new();
            http.post(uri, event_loop, DefaultHttpHandler::new(&stream, HttpGet, HttpError))
                .map_err(|()| io::Error::new(io::ErrorKind::Other, ""))
        })
    }

    pub fn get<HANDLER>(&self, uri: &str, event_loop: &mut Loop, handler: HANDLER) -> Result<(), ()>
    where HANDLER: HttpHandler + 'static,
    {
        let uri = HttpUri::new(uri)?;
        TcpConnection::ip4(event_loop, uri.host, uri.port, Connection::new(uri.host, handler, uri.resource.path, "GET"));
        Ok(())
    }

    pub fn post<HANDLER>(&self, uri: &str, event_loop: &mut Loop, handler: HANDLER) -> Result<(), ()>
    where HANDLER: HttpHandler + 'static,
    {
        let uri = HttpUri::new(uri)?;
        TcpConnection::ip4(event_loop, uri.host, uri.port, Connection::new(uri.host, handler, uri.resource.path, "POST"));
        Ok(())
    }
}

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

#[derive(Debug)]
enum Msg {
    HttpGet(Vec<u8>),
    HttpError(io::Error),
}

struct BlockingHttpHandler {
    event_loop: Loop,
    result: Rc<RefCell<io::Result<Vec<u8>>>>,
}

impl BlockingHttpHandler {
    fn new(event_loop: &Loop, result: Rc<RefCell<io::Result<Vec<u8>>>>) -> Self {
        Self {
            event_loop: event_loop.clone(),
            result,
        }
    }
}

impl Handler for BlockingHttpHandler {
    type Msg = Msg;

    fn update(&mut self, _stream: &Stream<Msg>, msg: Self::Msg) {
        match msg {
            HttpGet(body) => {
                *self.result.borrow_mut() = Ok(body);
            },
            HttpError(error) => {
                *self.result.borrow_mut() = Err(error);
            },
        }
        self.event_loop.stop()
    }
}