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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
pub use crate::r#struct::WasiHttp;
use crate::wasi::http::outgoing_handler::Host;
use crate::wasi::http::types::{Error, Host as TypesHost, Method, RequestOptions, Scheme};
use crate::wasi::io::streams::Host as StreamsHost;
use anyhow::anyhow;
use std::str;
use std::vec::Vec;
use wasmtime::{AsContext, AsContextMut, Caller, Extern, Memory};

const MEMORY: &str = "memory";

#[derive(Debug, thiserror::Error)]
enum HttpError {
    #[error("Memory not found")]
    MemoryNotFound,
    #[error("Memory access error")]
    MemoryAccessError(#[from] wasmtime::MemoryAccessError),
    #[error("Buffer too small")]
    BufferTooSmall,
    #[error("UTF-8 error")]
    Utf8Error(#[from] std::str::Utf8Error),
}

fn memory_get<T>(caller: &mut Caller<'_, T>) -> Result<Memory, HttpError> {
    if let Some(Extern::Memory(mem)) = caller.get_export(MEMORY) {
        Ok(mem)
    } else {
        Err(HttpError::MemoryNotFound)
    }
}

/// Get a slice of length `len` from `memory`, starting at `offset`.
/// This will return an `HttpError::BufferTooSmall` if the size of the
/// requested slice is larger than the memory size.
fn slice_from_memory(
    memory: &Memory,
    mut ctx: impl AsContextMut,
    offset: u32,
    len: u32,
) -> Result<Vec<u8>, HttpError> {
    let required_memory_size = offset.checked_add(len).ok_or(HttpError::BufferTooSmall)? as usize;

    if required_memory_size > memory.data_size(&mut ctx) {
        return Err(HttpError::BufferTooSmall);
    }

    let mut buf = vec![0u8; len as usize];
    memory.read(&mut ctx, offset as usize, buf.as_mut_slice())?;
    Ok(buf)
}

fn u32_from_memory(memory: &Memory, ctx: impl AsContextMut, ptr: u32) -> Result<u32, HttpError> {
    let slice = slice_from_memory(memory, ctx, ptr, 4)?;
    let mut dst = [0u8; 4];
    dst.clone_from_slice(&slice[0..4]);
    Ok(u32::from_le_bytes(dst))
}

/// Read a string of byte length `len` from `memory`, starting at `offset`.
fn string_from_memory(
    memory: &Memory,
    ctx: impl AsContextMut,
    offset: u32,
    len: u32,
) -> Result<String, HttpError> {
    let slice = slice_from_memory(memory, ctx, offset, len)?;
    Ok(std::str::from_utf8(&slice)?.to_string())
}

fn read_option_string(
    memory: &Memory,
    ctx: impl AsContextMut,
    is_some: i32,
    ptr: u32,
    len: u32,
) -> Result<Option<String>, HttpError> {
    if is_some == 1 {
        Ok(Some(string_from_memory(&memory, ctx, ptr, len)?))
    } else {
        Ok(None)
    }
}

fn allocate_guest_pointer<T>(caller: &mut Caller<'_, T>, size: u32) -> anyhow::Result<u32> {
    let realloc = caller
        .get_export("cabi_realloc")
        .ok_or_else(|| anyhow!("missing required export cabi_realloc"))?;
    let func = realloc
        .into_func()
        .ok_or_else(|| anyhow!("cabi_realloc must be a func"))?;
    let typed = func.typed::<(u32, u32, u32, u32), u32>(caller.as_context())?;
    Ok(typed.call(caller.as_context_mut(), (0, 0, 4, size))?)
}

fn u32_array_to_u8(arr: &[u32]) -> Vec<u8> {
    let mut result = std::vec::Vec::new();
    for val in arr.iter() {
        let bytes = val.to_le_bytes();
        for b in bytes.iter() {
            result.push(*b);
        }
    }
    result
}

pub fn add_component_to_linker<T>(
    linker: &mut wasmtime::Linker<T>,
    get_cx: impl Fn(&mut T) -> &mut WasiHttp + Send + Sync + Copy + 'static,
) -> anyhow::Result<()> {
    linker.func_wrap(
        "wasi:http/outgoing-handler",
        "handle",
        move |mut caller: Caller<'_, T>,
              request: u32,
              has_options: i32,
              has_timeout: i32,
              timeout_ms: u32,
              has_first_byte_timeout: i32,
              first_byte_timeout_ms: u32,
              has_between_bytes_timeout: i32,
              between_bytes_timeout_ms: u32|
              -> anyhow::Result<u32> {
            let options = if has_options == 1 {
                Some(RequestOptions {
                    connect_timeout_ms: if has_timeout == 1 {
                        Some(timeout_ms)
                    } else {
                        None
                    },
                    first_byte_timeout_ms: if has_first_byte_timeout == 1 {
                        Some(first_byte_timeout_ms)
                    } else {
                        None
                    },
                    between_bytes_timeout_ms: if has_between_bytes_timeout == 1 {
                        Some(between_bytes_timeout_ms)
                    } else {
                        None
                    },
                })
            } else {
                None
            };

            Ok(get_cx(caller.data_mut()).handle(request, options)?)
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "new-outgoing-request",
        move |mut caller: Caller<'_, T>,
              method: i32,
              method_ptr: i32,
              method_len: i32,
              path_is_some: i32,
              path_ptr: u32,
              path_len: u32,
              scheme_is_some: i32,
              scheme: i32,
              scheme_ptr: i32,
              scheme_len: i32,
              authority_is_some: i32,
              authority_ptr: u32,
              authority_len: u32,
              headers: u32|
              -> anyhow::Result<u32> {
            let memory = memory_get(&mut caller)?;
            let path = read_option_string(
                &memory,
                caller.as_context_mut(),
                path_is_some,
                path_ptr,
                path_len,
            )?;
            let authority = read_option_string(
                &memory,
                caller.as_context_mut(),
                authority_is_some,
                authority_ptr,
                authority_len,
            )?;

            let mut s = Scheme::Https;
            if scheme_is_some == 1 {
                s = match scheme {
                    0 => Scheme::Http,
                    1 => Scheme::Https,
                    _ => {
                        let value = string_from_memory(
                            &memory,
                            caller.as_context_mut(),
                            scheme_ptr.try_into()?,
                            scheme_len.try_into()?,
                        )?;
                        Scheme::Other(value)
                    }
                };
            }
            let m = match method {
                0 => Method::Get,
                1 => Method::Head,
                2 => Method::Post,
                3 => Method::Put,
                4 => Method::Delete,
                5 => Method::Connect,
                6 => Method::Options,
                7 => Method::Trace,
                8 => Method::Patch,
                _ => {
                    let value = string_from_memory(
                        &memory,
                        caller.as_context_mut(),
                        method_ptr.try_into()?,
                        method_len.try_into()?,
                    )?;
                    Method::Other(value)
                }
            };

            let ctx = get_cx(caller.data_mut());
            Ok(ctx.new_outgoing_request(m, path, Some(s), authority, headers)?)
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "incoming-response-status",
        move |mut caller: Caller<'_, T>, id: u32| -> anyhow::Result<u32> {
            let ctx = get_cx(caller.data_mut());
            Ok(ctx.incoming_response_status(id)?.into())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "drop-future-incoming-response",
        move |mut caller: Caller<'_, T>, future: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_future_incoming_response(future)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "future-incoming-response-get",
        move |mut caller: Caller<'_, T>, future: u32, ptr: i32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            let response = ctx.future_incoming_response_get(future)?.unwrap_or(Ok(0));

            let memory = memory_get(&mut caller)?;

            // First == is_some
            // Second == is_err
            // Third == {ok: is_err = false, tag: is_err = true}
            // Fourth == string ptr
            // Fifth == string len
            let result: [u32; 5] = match response {
                Ok(value) => [1, 0, value, 0, 0],
                Err(error) => {
                    let (tag, err_string) = match error {
                        Error::InvalidUrl(e) => (0u32, e),
                        Error::TimeoutError(e) => (1u32, e),
                        Error::ProtocolError(e) => (2u32, e),
                        Error::UnexpectedError(e) => (3u32, e),
                    };
                    let bytes = err_string.as_bytes();
                    let len = bytes.len().try_into().unwrap();
                    let ptr = allocate_guest_pointer(&mut caller, len)?;
                    memory.write(caller.as_context_mut(), ptr as _, bytes)?;
                    [1, 1, tag, ptr, len]
                }
            };
            let raw = u32_array_to_u8(&result);

            memory.write(caller.as_context_mut(), ptr as _, &raw)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "incoming-response-consume",
        move |mut caller: Caller<'_, T>, response: u32, ptr: i32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            let stream = ctx.incoming_response_consume(response)?.unwrap_or(0);

            let memory = memory_get(&mut caller).unwrap();

            // First == is_some
            // Second == stream_id
            let result: [u32; 2] = [0, stream];
            let raw = u32_array_to_u8(&result);

            memory.write(caller.as_context_mut(), ptr as _, &raw)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:io/poll",
        "drop-pollable",
        move |_caller: Caller<'_, T>, _a: i32| -> anyhow::Result<()> {
            anyhow::bail!("unimplemented")
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "drop-fields",
        move |mut caller: Caller<'_, T>, ptr: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_fields(ptr)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:io/streams",
        "drop-input-stream",
        move |mut caller: Caller<'_, T>, id: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_input_stream(id)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:io/streams",
        "drop-output-stream",
        move |mut caller: Caller<'_, T>, id: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_output_stream(id)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "outgoing-request-write",
        move |mut caller: Caller<'_, T>, request: u32, ptr: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            let stream = ctx
                .outgoing_request_write(request)?
                .map_err(|_| anyhow!("no outgoing stream present"))?;

            let memory = memory_get(&mut caller)?;
            // First == is_some
            // Second == stream_id
            let result: [u32; 2] = [0, stream];
            let raw = u32_array_to_u8(&result);

            memory.write(caller.as_context_mut(), ptr as _, &raw)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "drop-outgoing-request",
        move |mut caller: Caller<'_, T>, id: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_outgoing_request(id)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "drop-incoming-response",
        move |mut caller: Caller<'_, T>, id: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            ctx.drop_incoming_response(id)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "new-fields",
        move |mut caller: Caller<'_, T>, base_ptr: u32, len: u32| -> anyhow::Result<u32> {
            let memory = memory_get(&mut caller)?;

            let mut vec = Vec::new();
            let mut i = 0;
            // TODO: read this more efficiently as a single block.
            while i < len {
                let ptr = base_ptr + i * 16;
                let name_ptr = u32_from_memory(&memory, caller.as_context_mut(), ptr)?;
                let name_len = u32_from_memory(&memory, caller.as_context_mut(), ptr + 4)?;
                let value_ptr = u32_from_memory(&memory, caller.as_context_mut(), ptr + 8)?;
                let value_len = u32_from_memory(&memory, caller.as_context_mut(), ptr + 12)?;

                let name =
                    string_from_memory(&memory, caller.as_context_mut(), name_ptr, name_len)?;
                let value =
                    string_from_memory(&memory, caller.as_context_mut(), value_ptr, value_len)?;

                vec.push((name, value));
                i = i + 1;
            }

            let ctx = get_cx(caller.data_mut());
            Ok(ctx.new_fields(vec)?)
        },
    )?;
    linker.func_wrap(
        "wasi:io/streams",
        "read",
        move |mut caller: Caller<'_, T>, stream: u32, len: u64, ptr: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            let bytes_tuple = ctx.read(stream, len)??;
            let bytes = bytes_tuple.0;
            let done = match bytes_tuple.1 {
                true => 1,
                false => 0,
            };
            let body_len: u32 = bytes.len().try_into()?;
            let out_ptr = allocate_guest_pointer(&mut caller, body_len)?;
            let result: [u32; 4] = [0, out_ptr, body_len, done];
            let raw = u32_array_to_u8(&result);

            let memory = memory_get(&mut caller)?;
            memory.write(caller.as_context_mut(), out_ptr as _, &bytes)?;
            memory.write(caller.as_context_mut(), ptr as _, &raw)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:io/streams",
        "write",
        move |mut caller: Caller<'_, T>,
              stream: u32,
              body_ptr: u32,
              body_len: u32,
              ptr: u32|
              -> anyhow::Result<()> {
            let memory = memory_get(&mut caller)?;
            let body = string_from_memory(&memory, caller.as_context_mut(), body_ptr, body_len)?;

            let result: [u32; 3] = [0, 0, body_len];
            let raw = u32_array_to_u8(&result);

            let memory = memory_get(&mut caller)?;
            memory.write(caller.as_context_mut(), ptr as _, &raw)?;

            let ctx = get_cx(caller.data_mut());
            ctx.write(stream, body.as_bytes().to_vec())??;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "fields-entries",
        move |mut caller: Caller<'_, T>, fields: u32, out_ptr: u32| -> anyhow::Result<()> {
            let ctx = get_cx(caller.data_mut());
            let entries = ctx.fields_entries(fields)?;

            let header_len = entries.len();
            let tuple_ptr = allocate_guest_pointer(&mut caller, (16 * header_len).try_into()?)?;
            let mut ptr = tuple_ptr;
            for item in entries.iter() {
                let name = &item.0;
                let value = &item.1;
                let name_len: u32 = name.len().try_into()?;
                let value_len: u32 = value.len().try_into()?;

                let name_ptr = allocate_guest_pointer(&mut caller, name_len)?;
                let value_ptr = allocate_guest_pointer(&mut caller, value_len)?;

                let memory = memory_get(&mut caller)?;
                memory.write(caller.as_context_mut(), name_ptr as _, &name.as_bytes())?;
                memory.write(caller.as_context_mut(), value_ptr as _, value)?;

                let pair: [u32; 4] = [name_ptr, name_len, value_ptr, value_len];
                let raw_pair = u32_array_to_u8(&pair);
                memory.write(caller.as_context_mut(), ptr as _, &raw_pair)?;

                ptr = ptr + 16;
            }

            let memory = memory_get(&mut caller)?;
            let result: [u32; 2] = [tuple_ptr, header_len.try_into()?];
            let raw = u32_array_to_u8(&result);
            memory.write(caller.as_context_mut(), out_ptr as _, &raw)?;
            Ok(())
        },
    )?;
    linker.func_wrap(
        "wasi:http/types",
        "incoming-response-headers",
        move |mut caller: Caller<'_, T>, handle: u32| -> anyhow::Result<u32> {
            let ctx = get_cx(caller.data_mut());
            Ok(ctx.incoming_response_headers(handle)?)
        },
    )?;
    Ok(())
}