Skip to main content

hammer/
http.rs

1//! HTTP requests, through Extism's `http_request`. Hammer allows only the hosts the manifest names
2//! under `permissions.http`, which the user approves at install; a request to any other ends the call.
3
4use serde::Serialize;
5use std::collections::BTreeMap;
6
7#[link(wasm_import_module = "extism:host/env")]
8unsafe extern "C" {
9    fn http_request(request: u64, body: u64) -> u64;
10    fn http_status_code() -> i32;
11}
12
13pub struct Response {
14    pub status: u16,
15    pub body: Vec<u8>,
16}
17
18impl Response {
19    pub fn is_success(&self) -> bool {
20        (200..300).contains(&self.status)
21    }
22}
23
24/// Sends a request and waits for its response. A response of any status is Ok. A request Hammer
25/// refuses, such as to a host the manifest does not name, or one with no response, such as on a
26/// network that is down, ends the call with Hammer's error rather than returning.
27pub fn request(method: &str, url: &str, headers: &[(&str, &str)], body: Option<&[u8]>) -> crate::Result<Response> {
28    #[derive(Serialize)]
29    struct Request<'a> {
30        url: &'a str,
31        method: &'a str,
32        headers: BTreeMap<&'a str, &'a str>,
33    }
34    let request = Request { url, method, headers: headers.iter().copied().collect() };
35    let request = crate::to_kernel(&serde_json::to_vec(&request)?);
36    let body = body.filter(|it| !it.is_empty()).map_or(0, crate::to_kernel);
37    let reply = unsafe { http_request(request, body) };
38    let status = unsafe { http_status_code() };
39    unsafe {
40        crate::free(request);
41        if body != 0 {
42            crate::free(body);
43        }
44    }
45    let body = if reply == 0 { Vec::new() } else { crate::from_kernel(reply) };
46    if reply != 0 {
47        unsafe { crate::free(reply) };
48    }
49    match u16::try_from(status) {
50        Ok(status) if status > 0 => Ok(Response { status, body }),
51        _ => Err(format!("No response from {url}").into()),
52    }
53}
54
55/// `application/x-www-form-urlencoded` form data from its fields.
56pub fn form(fields: &[(&str, &str)]) -> String {
57    fields.iter().map(|(name, value)| format!("{}={}", encode(name), encode(value))).collect::<Vec<_>>().join("&")
58}
59
60fn encode(text: &str) -> String {
61    let mut encoded = String::with_capacity(text.len());
62    for byte in text.bytes() {
63        match byte {
64            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'*' => encoded.push(byte as char),
65            b' ' => encoded.push('+'),
66            _ => encoded.push_str(&format!("%{byte:02X}")),
67        }
68    }
69    encoded
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn form_encodes_reserved_and_non_ascii() {
78        assert_eq!(form(&[("text", "a b&c=d"), ("x", "é")]), "text=a+b%26c%3Dd&x=%C3%A9");
79    }
80}