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
use std::string::FromUtf8Error;
use std::sync::Arc;

use crate::bindings::wasix_http_client_v1 as sys;
use crate::{capabilities::Capabilities, WasiRuntime};

use crate::{
    http::{DynHttpClient, HttpClientCapabilityV1},
    WasiEnv,
};

impl std::fmt::Display for sys::Method<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let v = match self {
            sys::Method::Get => "GET",
            sys::Method::Head => "HEAD",
            sys::Method::Post => "POST",
            sys::Method::Put => "PUT",
            sys::Method::Delete => "DELETE",
            sys::Method::Connect => "CONNECT",
            sys::Method::Options => "OPTIONS",
            sys::Method::Trace => "TRACE",
            sys::Method::Patch => "PATCH",
            sys::Method::Other(other) => *other,
        };
        write!(f, "{v}")
    }
}

pub struct WasixHttpClientImpl {
    cap: Capabilities,
    runtime: Arc<dyn WasiRuntime + Send + Sync>,
}

impl WasixHttpClientImpl {
    pub fn new(env: &WasiEnv) -> Self {
        Self {
            // TODO: Should be a shared reference
            // Currently this client would not adapt to changes in the capabilities.
            cap: env.capabilities.clone(),
            runtime: env.runtime.clone(),
        }
    }
}

#[derive(Debug)]
pub struct ClientImpl {
    client: DynHttpClient,
    capabilities: HttpClientCapabilityV1,
}

impl sys::WasixHttpClientV1 for WasixHttpClientImpl {
    type Client = ClientImpl;

    fn client_new(&mut self) -> Result<Self::Client, String> {
        let capabilities = if self.cap.insecure_allow_all {
            HttpClientCapabilityV1::new_allow_all()
        } else if !self.cap.http_client.is_deny_all() {
            self.cap.http_client.clone()
        } else {
            return Err("Permission denied - http client not enabled".to_string());
        };

        let client = self
            .runtime
            .http_client()
            .ok_or_else(|| "No http client available".to_string())?
            .clone();
        Ok(ClientImpl {
            client,
            capabilities,
        })
    }

    fn client_send(
        &mut self,
        self_: &Self::Client,
        request: sys::Request<'_>,
    ) -> Result<sys::Response, String> {
        let uri: http::Uri = request
            .url
            .parse()
            .map_err(|err| format!("Invalid request url: {err}"))?;
        let host = uri.host().unwrap_or_default();
        if !self_.capabilities.can_access_domain(host) {
            return Err(format!(
                "Permission denied: http capability not enabled for host '{host}'"
            ));
        }

        let headers = request
            .headers
            .into_iter()
            .map(|h| {
                let value = String::from_utf8(h.value.to_vec())?;
                Ok((h.key.to_string(), value))
            })
            .collect::<Result<Vec<_>, FromUtf8Error>>()
            .map_err(|_| "non-utf8 request header")?;

        // FIXME: stream body...

        let body = match request.body {
            Some(sys::BodyParam::Fd(_)) => {
                return Err("File descriptor bodies not supported yet".to_string());
            }
            Some(sys::BodyParam::Data(data)) => Some(data.to_vec()),
            None => None,
        };

        let req = crate::http::HttpRequest {
            url: request.url.to_string(),
            method: request.method.to_string(),
            headers,
            body,
            options: crate::http::HttpRequestOptions {
                gzip: false,
                cors_proxy: None,
            },
        };
        let f = self_.client.request(req);

        let res = self
            .runtime
            .task_manager()
            .block_on(f)
            .map_err(|e| e.to_string())?;

        let res_headers = res
            .headers
            .into_iter()
            .map(|(key, value)| sys::HeaderResult {
                key,
                value: value.into_bytes(),
            })
            .collect();

        let res_body = if let Some(b) = res.body {
            sys::BodyResult::Data(b)
        } else {
            sys::BodyResult::Data(Vec::new())
        };

        Ok({
            sys::Response {
                status: res.status,
                headers: res_headers,
                body: res_body,
                // TODO: provide redirect urls?
                redirect_urls: None,
            }
        })
    }
}