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
use std::error::Error;
use std::fmt;
use tokio::prelude::*;

/// The Protocol Version of the taskserver protocol
#[derive(Debug, PartialEq, Clone)]
pub enum RequestProtocol {
    /// the currently only supported version
    V1,
}

/// The group containing the headers relevant for authentication
#[derive(Debug, PartialEq)]
pub struct RequestAuthHeader<'a> {
    /// Users org
    pub org: &'a str,
    /// username
    pub user: &'a str,
    /// key (the password equivalent for task)
    pub key: &'a str,
}

/// The Subtype. Currently only makes sense in the context of the sync request
#[derive(Debug, PartialEq, Clone)]
pub enum RequestSubtype {
    Init,
}

/// The Request type. Contains all valid requests the client can send.
#[derive(Debug, PartialEq, Clone)]
pub enum RequestType {
    Statistics,
    Sync,
}

/// Type safe header struct.
/// The relevant headers will be present as fields on the [RequestHeaders](struct.RequestHeaders.html) struct
#[derive(Debug, PartialEq, Clone)]
pub enum RequestHeader<'a> {
    Client(&'a str),
    Org(&'a str),
    User(&'a str),
    Key(&'a str),
    Protocol(RequestProtocol),
    Type(RequestType),
    Other(&'a str),
    Subtype(RequestSubtype),
}

/// Group containing the most necessary headers. All fields here are required
#[derive(Debug, PartialEq)]
pub struct RequestHeaders<'a> {
    pub protocol: RequestProtocol,
    pub client: &'a str,
    pub request_type: RequestType,
    pub request_subtype: Option<RequestSubtype>,
    pub auth: RequestAuthHeader<'a>,
}

/// Parsed Request.
#[derive(PartialEq)]
pub struct Request<'a, P> {
    pub headers: RequestHeaders<'a>,
    pub raw_headers: Vec<RequestHeader<'a>>,
    /// this field usually contains an iterator yielding the lines of the payload, but Request needs the type Parameter because of Limitations of impl Trait
    pub payload: P,
}

/// Request parsing Errors
#[derive(Debug)]
pub enum RequestError {
    /// Raised when a header is malformed
    InvalidHeader(String),
    /// Raised with the protocol name of the missing header.
    MissingHeader(String),
    /// Raised when reading the Request fails
    IOError(tokio::io::Error),
    /// Raised when the Request payload is not valid utf-8
    EncodingError(std::str::Utf8Error),
    MissingSyncKey,
    /// Raised when the Request is not valid but none of the Other cases is applicable
    InvalidRequest(String),
}

impl fmt::Display for RequestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", &self)
    }
}
impl Error for RequestError {}

impl From<tokio::io::Error> for RequestError {
    fn from(e: tokio::io::Error) -> Self {
        RequestError::IOError(e)
    }
}
impl From<std::str::Utf8Error> for RequestError {
    fn from(e: std::str::Utf8Error) -> Self {
        RequestError::EncodingError(e)
    }
}

/// parses the header into the typesafe struct
fn parse_header(raw: &str) -> Result<RequestHeader<'_>, RequestError> {
    let mut s = raw.split(": ");
    fn make_err(r: &str) -> RequestError {
        RequestError::InvalidHeader(r.into())
    }
    let name = s.next().ok_or_else(|| make_err(raw))?;
    let value = s.next().ok_or_else(|| make_err(raw))?;
    if s.next().is_some() {
        return Err(make_err(raw));
    }

    let v = match name {
        "client" => RequestHeader::Client(value),
        "org" => RequestHeader::Org(value),
        "user" => RequestHeader::User(value),
        "key" => RequestHeader::Key(value),
        "protocol" => match value {
            "v1" => RequestHeader::Protocol(RequestProtocol::V1),
            _ => return Err(make_err(raw)),
        },
        "type" => match value {
            "sync" => RequestHeader::Type(RequestType::Sync),
            "statistics" => RequestHeader::Type(RequestType::Statistics),
            _ => return Err(make_err(raw)),
        },
        "subtype" => match value {
            "init" => RequestHeader::Subtype(RequestSubtype::Init),
            _ => return Err(make_err(raw)),
        },
        _ => RequestHeader::Other(value),
    };
    Ok(v)
}

/// splits the request string into headers (everything until the first empty line)
/// and payload (everything after)
/// Then assembles the Request struct while validating the existence of all required headers
pub fn parse_request(req: &str) -> Result<Request<'_, impl Iterator<Item = &str>>, RequestError> {
    let mut lines = req.lines();

    let mut protocol = None;
    let mut request_type = None;
    let mut request_subtype = None;
    let mut client = None;
    let mut auth_org = None;
    let mut auth_user = None;
    let mut auth_key = None;
    let mut raw_headers = Vec::new();
    for line in &mut lines {
        // the empty line marks the end of the headers and the beginning of the payload
        if line.is_empty() {
            break;
        }

        let header = parse_header(line)?;
        match &header {
            RequestHeader::Protocol(p) => protocol = Some(p.clone()),
            RequestHeader::Type(t) => request_type = Some(t.clone()),
            RequestHeader::Subtype(t) => request_subtype = Some(t.clone()),
            RequestHeader::Client(c) => client = Some(*c),
            RequestHeader::Org(o) => auth_org = Some(*o),
            RequestHeader::User(u) => auth_user = Some(*u),
            RequestHeader::Key(k) => auth_key = Some(*k),
            _ => {}
        }
        raw_headers.push(header);
    }

    let parsed_header = match (
        protocol,
        request_type,
        client,
        auth_org,
        auth_user,
        auth_key,
    ) {
        (None, _, _, _, _, _) => Err(RequestError::MissingHeader("protocol".into())),
        (_, None, _, _, _, _) => Err(RequestError::MissingHeader("type".into())),
        (_, _, None, _, _, _) => Err(RequestError::MissingHeader("client".into())),
        (_, _, _, None, _, _) => Err(RequestError::MissingHeader("org".into())),
        (_, _, _, _, None, _) => Err(RequestError::MissingHeader("user".into())),
        (_, _, _, _, _, None) => Err(RequestError::MissingHeader("key".into())),
        (Some(protocol), Some(request_type), Some(client), Some(org), Some(user), Some(key)) => {
            Ok(Request {
                headers: RequestHeaders {
                    protocol,
                    client,
                    request_type,
                    request_subtype,
                    auth: RequestAuthHeader { org, user, key },
                },
                raw_headers,
                payload: lines.filter(|a| !a.is_empty()),
            })
        }
    }?;

    Ok(parsed_header)
}

/// reads the entire request into the provided buffer
pub async fn get_request_data<R>(buf: &mut Vec<u8>, mut con: R) -> Result<(), RequestError>
where
    R: AsyncRead + Unpin,
{
    let len = con.read_u32().await?;
    let len = (len as usize) - std::mem::size_of::<u32>();

    buf.clear();
    let capacity = buf.capacity();
    if capacity < len {
        buf.reserve_exact(len - buf.capacity());
    }

    // this is only valid because u8 does not have a drop implementation
    unsafe {
        buf.set_len(len);
    }
    con.read_exact(buf).await?;

    Ok(())
}