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
use anyhow::Error;
use bytes::Bytes;
use http::{self, header::HeaderName, HeaderMap, HeaderValue, Request, StatusCode};
use std::str::FromStr;

#[allow(dead_code)]
#[allow(clippy::mut_from_ref)]
#[allow(clippy::too_many_arguments)]
pub(crate) mod raw;

/// HTTP errors
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
    #[error("Invalid handle")]
    InvalidHandle,
    #[error("Memory not found")]
    MemoryNotFound,
    #[error("Memory access error")]
    MemoryAccessError,
    #[error("Buffer too small")]
    BufferTooSmall,
    #[error("Header not found")]
    HeaderNotFound,
    #[error("UTF-8 error")]
    Utf8Error,
    #[error("Destination not allowed")]
    DestinationNotAllowed,
    #[error("Invalid method")]
    InvalidMethod,
    #[error("Invalid encoding")]
    InvalidEncoding,
    #[error("Invalid URL")]
    InvalidUrl,
    #[error("HTTP error")]
    RequestError,
    #[error("Runtime error")]
    RuntimeError,
    #[error("Too many sessions")]
    TooManySessions,
    #[error("Unknown WASI error")]
    UnknownError,
}

// TODO(@radu-matei)
//
// This error is not really used in the public API.
impl From<raw::Error> for HttpError {
    fn from(e: raw::Error) -> Self {
        match e {
            raw::Error::WasiError(errno) => match errno {
                1 => HttpError::InvalidHandle,
                2 => HttpError::MemoryNotFound,
                3 => HttpError::MemoryAccessError,
                4 => HttpError::BufferTooSmall,
                5 => HttpError::HeaderNotFound,
                6 => HttpError::Utf8Error,
                7 => HttpError::DestinationNotAllowed,
                8 => HttpError::InvalidMethod,
                9 => HttpError::InvalidEncoding,
                10 => HttpError::InvalidUrl,
                11 => HttpError::RequestError,
                12 => HttpError::RuntimeError,
                13 => HttpError::TooManySessions,

                _ => HttpError::UnknownError,
            },
        }
    }
}

/// An HTTP response
pub struct Response {
    handle: raw::ResponseHandle,
    pub status_code: StatusCode,
}

/// Automatically call `close` to remove the current handle
/// when the response object goes out of scope.
impl Drop for Response {
    fn drop(&mut self) {
        raw::close(self.handle).unwrap();
    }
}

impl Response {
    /// Read a response body in a streaming fashion.
    /// `buf` is an arbitrary large buffer, that may be partially filled after each call.
    /// The function returns the actual number of bytes that were written, and `0`
    /// when the end of the stream has been reached.
    pub fn body_read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let read = raw::body_read(self.handle, buf.as_mut_ptr(), buf.len())?;
        Ok(read)
    }

    /// Read the entire body until the end of the stream.
    pub fn body_read_all(&mut self) -> Result<Vec<u8>, Error> {
        // TODO(@radu-matei)
        //
        // Do we want to have configurable chunk sizes?
        let mut chunk = [0u8; 4096];
        let mut v = vec![];
        loop {
            let read = self.body_read(&mut chunk)?;
            if read == 0 {
                return Ok(v);
            }
            v.extend_from_slice(&chunk[0..read]);
        }
    }

    /// Get the value of the `name` header.
    /// Returns `HttpError::HeaderNotFound` if no such header was found.
    pub fn header_get(&self, name: String) -> Result<String, Error> {
        let name = name;

        // Set the initial capacity of the expected header value to 4 kilobytes.
        // If the response value size is larger, double the capacity and
        // attempt to read again, but only until reaching 64 kilobytes.
        //
        // This is to avoid a potentially malicious web server from returning a
        // response header that would make the guest allocate all of its possible
        // memory.
        // The maximum is set to 64 kilobytes, as it is usually the maximum value
        // known servers will allow until returning 413 Entity Too Large.
        let mut capacity = 4 * 1024;
        let max_capacity: usize = 64 * 1024;

        loop {
            let mut buf = vec![0u8; capacity];
            match raw::header_get(
                self.handle,
                name.as_ptr(),
                name.len(),
                buf.as_mut_ptr(),
                buf.len(),
            ) {
                Ok(written) => {
                    buf.truncate(written);
                    return Ok(String::from_utf8(buf)?);
                }
                Err(e) => match Into::<HttpError>::into(e) {
                    HttpError::BufferTooSmall => {
                        if capacity < max_capacity {
                            capacity *= 2;
                            continue;
                        } else {
                            return Err(e.into());
                        }
                    }
                    _ => return Err(e.into()),
                },
            };
        }
    }

    /// Get the entire response header map for a given request.
    // If clients know the specific header key, they should use
    // `header_get` to avoid allocating memory for the entire
    // header map.
    pub fn headers_get_all(&self) -> Result<HeaderMap, Error> {
        // The fixed capacity for the header map is 64 kilobytes.
        // If a server sends a header map that is larger than this,
        // the client will return an error.
        // The same note applies - most known servers will limit
        // response headers to 64 kilobytes at most before returning
        // 413 Entity Too Large.
        //
        // It might make sense to increase the size here in the same
        // way it is done in `header_get`, if there are valid use
        // cases where it is required.
        let capacity = 64 * 1024;
        let mut buf = vec![0u8; capacity];

        match raw::headers_get_all(self.handle, buf.as_mut_ptr(), buf.len()) {
            Ok(written) => {
                buf.truncate(written);
                let str = String::from_utf8(buf)?;
                Ok(string_to_header_map(&str)?)
            }
            Err(e) => Err(e.into()),
        }
    }
}

/// Send an HTTP request.
/// The function returns a `Response` object, that includes the status,
/// as well as methods to access the headers and the body.
#[tracing::instrument]
pub fn request(req: Request<Option<Bytes>>) -> Result<Response, Error> {
    let url = req.uri().to_string();
    tracing::debug!(%url, headers = ?req.headers(), "performing http request using wasmtime function");

    let headers = header_map_to_string(req.headers())?;
    let method = req.method().as_str().to_string();
    let body = match req.body() {
        None => Default::default(),
        Some(body) => body.as_ref(),
    };
    let (status_code, handle) = raw::req(
        url.as_ptr(),
        url.len(),
        method.as_ptr(),
        method.len(),
        headers.as_ptr(),
        headers.len(),
        body.as_ptr(),
        body.len(),
    )?;
    Ok(Response {
        handle,
        status_code: StatusCode::from_u16(status_code)?,
    })
}

/// Encode a header map as a string.
pub fn header_map_to_string(hm: &HeaderMap) -> Result<String, Error> {
    let mut res = String::new();
    for (name, value) in hm
        .iter()
        .map(|(name, value)| (name.as_str(), std::str::from_utf8(value.as_bytes())))
    {
        let value = value?;
        anyhow::ensure!(
            !name
                .chars()
                .any(|x| x.is_control() || "(),/:;<=>?@[\\]{}".contains(x)),
            "Invalid header name"
        );
        anyhow::ensure!(
            !value.chars().any(|x| x.is_control()),
            "Invalid header value"
        );
        res.push_str(&format!("{}:{}\n", name, value));
    }
    Ok(res)
}

/// Decode a header map from a string.
pub fn string_to_header_map(s: &str) -> Result<HeaderMap, Error> {
    let mut headers = HeaderMap::new();
    for entry in s.lines() {
        let mut parts = entry.splitn(2, ':');
        #[allow(clippy::or_fun_call)]
        let k = parts.next().ok_or(anyhow::format_err!(
            "Invalid serialized header: [{}]",
            entry
        ))?;
        let v = parts.next().unwrap();
        headers.insert(HeaderName::from_str(k)?, HeaderValue::from_str(v)?);
    }
    Ok(headers)
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::{HeaderMap, HeaderValue};

    #[test]
    fn test_header_map_to_string() {
        let mut hm = HeaderMap::new();
        hm.insert("custom-header", HeaderValue::from_static("custom-value"));
        hm.insert("custom-header2", HeaderValue::from_static("custom-value2"));
        let str = header_map_to_string(&hm).unwrap();
        assert_eq!(
            "custom-header:custom-value\ncustom-header2:custom-value2\n",
            str
        );
    }
}