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
use std::io::{Read, Write};

use lunatic::net::{TcpStream, TlsStream};
use serde::{Deserialize, Serialize};
use url::Url;

use crate::error::Kind;

#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum HttpStream {
    Tcp(TcpStream),
    Tls(TlsStream),
}

impl HttpStream {
    pub fn connect(url: Url) -> crate::Result<HttpStream> {
        let protocol = url.scheme();
        if protocol == "https" {
            let conn_str = format!("{}", url.host().unwrap());
            return match TlsStream::connect(&conn_str, url.port().unwrap_or(443).into()) {
                Ok(stream) => Ok(HttpStream::Tls(stream)),
                Err(e) => {
                    lunatic_log::error!("Failed to connect via TLS {:?}", e);
                    Err(crate::Error::new(
                        Kind::Builder,
                        Some("Failed to connect".to_string()),
                    ))
                }
            };
        }
        let conn_str = format!("{}:{}", url.host().unwrap(), url.port().unwrap_or(80));
        lunatic_log::debug!("Connecting {:?} | {:?}", protocol, conn_str);
        match TcpStream::connect(conn_str) {
            Ok(stream) => Ok(HttpStream::Tcp(stream)),
            Err(e) => {
                lunatic_log::error!("Failed to connect via TCP {:?}", e);
                Err(crate::Error::new(
                    Kind::Builder,
                    Some("Failed to connect".to_string()),
                ))
            }
        }
    }
}

impl Read for HttpStream {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            HttpStream::Tcp(stream) => stream.read(buf),
            HttpStream::Tls(stream) => stream.read(buf),
        }
    }
}

impl Write for HttpStream {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            HttpStream::Tcp(stream) => stream.write(buf),
            HttpStream::Tls(stream) => stream.write(buf),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            HttpStream::Tcp(stream) => stream.flush(),
            HttpStream::Tls(stream) => stream.flush(),
        }
    }
}