Files
curl-wasm/native/wasi_host.c
Sprite dba2cbcdca Make wasm2c native build portably discover runtime and OpenSSL
Add native/build_native.py to auto-discover WABT's wasm2c runtime headers and sources (wasm-rt.h, wasm-rt-*.c, and .inc files, with WASM2C_RUNTIME_DIR override) and OpenSSL flags across Linux distros and macOS, instead of assuming /usr/include/wasm-rt.h and -lwasm-rt-impl. Guard _DARWIN_C_SOURCE vs _POSIX_C_SOURCE in native/wasi_host.c, delegate just native to native/build_native.py, and document WASM2C_RUNTIME_DIR in README.md.
2026-11-20 00:22:20 +00:00

1827 lines
53 KiB
C

/*
* Native WASI 0.2 host shim for wasm2c-compiled curl-wasm.
* Implements the exact canonical-ABI core imports of curl.wat on POSIX + OpenSSL.
*/
#ifdef __APPLE__
#define _DARWIN_C_SOURCE
#else
#define _POSIX_C_SOURCE 200809L
#endif
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "curl_core.h"
#include "mem_mod.h"
/* ============================================================================
* Memory Helpers & Guest ABI Accessors
* ========================================================================== */
struct w2c_mem {
w2c_mem__mod* mod;
};
wasm_rt_memory_t* w2c_mem_memory(struct w2c_mem* m) {
return w2c_mem__mod_memory(m->mod);
}
u32 w2c_mem_alloc(struct w2c_mem* m, u32 size, u32 align) {
return w2c_mem__mod_alloc(m->mod, size, align);
}
u32 w2c_mem_heap_mark(struct w2c_mem* m) {
return w2c_mem__mod_heap_mark(m->mod);
}
void w2c_mem_heap_reset(struct w2c_mem* m, u32 mark) {
w2c_mem__mod_heap_reset(m->mod, mark);
}
u32 w2c_mem_realloc(struct w2c_mem* m, u32 old_p, u32 old_s, u32 align, u32 new_s) {
return w2c_mem__mod_realloc(m->mod, old_p, old_s, align, new_s);
}
/* ============================================================================
* WASI Resource Table & Data Structures
* ========================================================================== */
enum res_kind {
RES_NONE = 0,
RES_IO_ERROR,
RES_POLLABLE,
RES_INPUT_STREAM,
RES_OUTPUT_STREAM,
RES_DESCRIPTOR,
RES_FIELDS,
RES_REQUEST_OPTIONS,
RES_OUTGOING_REQUEST,
RES_OUTGOING_BODY,
RES_FIR,
RES_INCOMING_RESPONSE,
RES_INCOMING_BODY,
};
typedef struct {
enum res_kind kind;
void* ptr;
} res_entry_t;
typedef struct {
char* msg;
} io_error_t;
typedef struct {
char* name;
size_t name_len;
uint8_t* val;
size_t val_len;
} field_item_t;
typedef struct {
field_item_t* items;
size_t count;
size_t cap;
} fields_t;
typedef struct {
bool has_connect_timeout;
uint64_t connect_timeout_ns;
bool has_first_byte_timeout;
uint64_t first_byte_timeout_ns;
bool has_between_bytes_timeout;
uint64_t between_bytes_timeout_ns;
} req_options_t;
typedef struct {
uint8_t* buf;
size_t len;
size_t cap;
bool finished;
} out_body_t;
typedef struct {
char* method;
int scheme; /* 0 = HTTP, 1 = HTTPS */
char* authority;
char* path;
fields_t* headers;
out_body_t* body;
} out_req_t;
enum body_framing {
FRAMING_NONE = 0,
FRAMING_CONTENT_LENGTH,
FRAMING_CHUNKED,
FRAMING_EOF,
};
enum chunk_state {
CHUNK_SIZE = 0,
CHUNK_DATA,
CHUNK_CRLF,
CHUNK_TRAILERS,
CHUNK_DONE,
};
typedef struct {
int fd;
SSL_CTX* ssl_ctx;
SSL* ssl;
enum body_framing framing;
uint64_t content_remaining;
enum chunk_state chunk_st;
uint64_t chunk_rem;
uint8_t* buf;
size_t buf_pos;
size_t buf_len;
size_t buf_cap;
bool has_between_timeout;
uint64_t between_timeout_ns;
bool eof;
} http_reader_t;
typedef struct {
uint16_t status;
fields_t* headers;
http_reader_t* reader;
bool consumed;
} in_resp_t;
typedef struct {
http_reader_t* reader;
} in_body_t;
typedef struct {
out_req_t* req;
req_options_t* opts;
bool has_opts;
bool done;
bool is_err;
uint8_t err_code;
u32 resp_handle;
} fir_t;
enum stream_kind {
STREAM_FD = 0,
STREAM_OUT_BODY,
STREAM_HTTP_BODY,
};
typedef struct {
enum stream_kind kind;
int fd;
bool own_fd;
out_body_t* out_body;
http_reader_t* http_reader;
} wasi_stream_t;
typedef struct {
int fd;
bool own_fd;
} wasi_desc_t;
typedef struct {
u32 desc_handle;
char* path;
} preopen_t;
struct w2c_wasi {
w2c_mem__mod* mem;
int argc;
char** argv;
res_entry_t* res;
size_t res_cap;
u32 stdin_h;
u32 stdout_h;
u32 stderr_h;
bool preopens_init;
preopen_t preopens[2];
size_t preopen_cnt;
};
static inline uint8_t* mem_ptr(struct w2c_wasi* w, u32 off) {
return w2c_mem__mod_memory(w->mem)->data + off;
}
static inline size_t mem_sz(struct w2c_wasi* w) {
return (size_t)w2c_mem__mod_memory(w->mem)->size;
}
static inline void write_u8(struct w2c_wasi* w, u32 off, uint8_t v) {
if ((size_t)off + 1 <= mem_sz(w)) mem_ptr(w, off)[0] = v;
}
static inline void write_u32(struct w2c_wasi* w, u32 off, u32 v) {
if ((size_t)off + 4 <= mem_sz(w)) memcpy(mem_ptr(w, off), &v, 4);
}
static inline void write_u64(struct w2c_wasi* w, u32 off, u64 v) {
if ((size_t)off + 8 <= mem_sz(w)) memcpy(mem_ptr(w, off), &v, 8);
}
static u32 guest_alloc_copy(struct w2c_wasi* w, const void* src, size_t len) {
u32 gp = w2c_mem__mod_realloc(w->mem, 0, 0, 1, (u32)len);
if (len > 0 && src != NULL) {
memcpy(mem_ptr(w, gp), src, len);
}
return gp;
}
static char* dup_guest_cstr(struct w2c_wasi* w, u32 ptr, u32 len) {
char* s = (char*)malloc((size_t)len + 1);
if (!s) abort();
if (len > 0 && (size_t)ptr + len <= mem_sz(w)) {
memcpy(s, mem_ptr(w, ptr), len);
}
s[len] = '\0';
return s;
}
static u32 alloc_res(struct w2c_wasi* w, enum res_kind kind, void* ptr) {
for (size_t i = 1; i < w->res_cap; i++) {
if (w->res[i].kind == RES_NONE) {
w->res[i].kind = kind;
w->res[i].ptr = ptr;
return (u32)i;
}
}
size_t old_cap = w->res_cap;
size_t new_cap = old_cap ? old_cap * 2 : 64;
res_entry_t* nr = (res_entry_t*)realloc(w->res, new_cap * sizeof(res_entry_t));
if (!nr) abort();
memset(nr + old_cap, 0, (new_cap - old_cap) * sizeof(res_entry_t));
w->res = nr;
w->res_cap = new_cap;
size_t idx = old_cap == 0 ? 1 : old_cap;
w->res[idx].kind = kind;
w->res[idx].ptr = ptr;
return (u32)idx;
}
static void* get_res(struct w2c_wasi* w, u32 h, enum res_kind kind) {
if (h == 0 || (size_t)h >= w->res_cap) return NULL;
if (w->res[h].kind != kind) return NULL;
return w->res[h].ptr;
}
static void* take_res(struct w2c_wasi* w, u32 h, enum res_kind kind) {
if (h == 0 || (size_t)h >= w->res_cap) return NULL;
if (w->res[h].kind != kind) return NULL;
void* p = w->res[h].ptr;
w->res[h].kind = RES_NONE;
w->res[h].ptr = NULL;
return p;
}
static u32 make_io_err(struct w2c_wasi* w, const char* msg) {
io_error_t* e = (io_error_t*)malloc(sizeof(io_error_t));
e->msg = strdup(msg ? msg : "I/O error");
return alloc_res(w, RES_IO_ERROR, e);
}
static fields_t* fields_create(void) {
return (fields_t*)calloc(1, sizeof(fields_t));
}
static void fields_destroy(fields_t* f) {
if (!f) return;
for (size_t i = 0; i < f->count; i++) {
free(f->items[i].name);
free(f->items[i].val);
}
free(f->items);
free(f);
}
static fields_t* fields_clone(const fields_t* src) {
fields_t* dst = fields_create();
if (!src || src->count == 0) return dst;
dst->items = (field_item_t*)calloc(src->count, sizeof(field_item_t));
dst->cap = src->count;
dst->count = src->count;
for (size_t i = 0; i < src->count; i++) {
dst->items[i].name_len = src->items[i].name_len;
dst->items[i].name = (char*)malloc(src->items[i].name_len + 1);
memcpy(dst->items[i].name, src->items[i].name, src->items[i].name_len + 1);
dst->items[i].val_len = src->items[i].val_len;
dst->items[i].val = (uint8_t*)malloc(src->items[i].val_len + 1);
if (src->items[i].val_len > 0) {
memcpy(dst->items[i].val, src->items[i].val, src->items[i].val_len);
}
dst->items[i].val[src->items[i].val_len] = '\0';
}
return dst;
}
static void fields_push(fields_t* f, const char* name, size_t nlen, const uint8_t* val, size_t vlen) {
if (f->count == f->cap) {
size_t nc = f->cap ? f->cap * 2 : 16;
f->items = (field_item_t*)realloc(f->items, nc * sizeof(field_item_t));
f->cap = nc;
}
field_item_t* it = &f->items[f->count++];
it->name = (char*)malloc(nlen + 1);
memcpy(it->name, name, nlen);
it->name[nlen] = '\0';
it->name_len = nlen;
it->val = (uint8_t*)malloc(vlen + 1);
if (vlen > 0) memcpy(it->val, val, vlen);
it->val[vlen] = '\0';
it->val_len = vlen;
}
static bool ci_eq(const char* a, size_t alen, const char* b) {
size_t blen = strlen(b);
if (alen != blen) return false;
for (size_t i = 0; i < alen; i++) {
if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i])) return false;
}
return true;
}
static bool is_forbidden_req_header(const char* name, size_t nlen) {
return ci_eq(name, nlen, "host") ||
ci_eq(name, nlen, "connection") ||
ci_eq(name, nlen, "keep-alive") ||
ci_eq(name, nlen, "proxy-connection") ||
ci_eq(name, nlen, "transfer-encoding") ||
ci_eq(name, nlen, "upgrade") ||
ci_eq(name, nlen, "te");
}
static bool valid_header_name(const char* name, size_t len) {
if (len == 0) return false;
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)name[i];
if (c <= 32 || c >= 127 || c == ':') return false;
}
return true;
}
static bool valid_header_val(const uint8_t* val, size_t len) {
for (size_t i = 0; i < len; i++) {
if (val[i] == '\r' || val[i] == '\n' || val[i] == '\0') return false;
}
return true;
}
static void reader_destroy(http_reader_t* r) {
if (!r) return;
if (r->ssl) {
SSL_shutdown(r->ssl);
SSL_free(r->ssl);
}
if (r->ssl_ctx) SSL_CTX_free(r->ssl_ctx);
if (r->fd >= 0) close(r->fd);
free(r->buf);
free(r);
}
static void out_req_destroy(out_req_t* req) {
if (!req) return;
free(req->method);
free(req->authority);
free(req->path);
fields_destroy(req->headers);
if (req->body) {
free(req->body->buf);
free(req->body);
}
free(req);
}
/* ============================================================================
* Clocks & Timeouts
* ========================================================================== */
static uint64_t monotonic_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
}
u64 w2c_wasi_clock_now(struct w2c_wasi* w) {
(void)w;
return monotonic_ns();
}
/* ============================================================================
* CLI Environment & Stdio
* ========================================================================== */
void w2c_wasi_get_arguments(struct w2c_wasi* w, u32 retptr) {
u32 n = (u32)w->argc;
u32* ptrs = (u32*)calloc(n ? n : 1, sizeof(u32));
u32* lens = (u32*)calloc(n ? n : 1, sizeof(u32));
for (u32 i = 0; i < n; i++) {
size_t l = strlen(w->argv[i]);
lens[i] = (u32)l;
ptrs[i] = guest_alloc_copy(w, w->argv[i], l);
}
u32 arr_p = w2c_mem__mod_realloc(w->mem, 0, 0, 4, n * 8);
for (u32 i = 0; i < n; i++) {
write_u32(w, arr_p + i * 8, ptrs[i]);
write_u32(w, arr_p + i * 8 + 4, lens[i]);
}
write_u32(w, retptr, arr_p);
write_u32(w, retptr + 4, n);
free(ptrs);
free(lens);
}
static u32 make_stdio_stream(struct w2c_wasi* w, int fd, enum res_kind rk) {
wasi_stream_t* st = (wasi_stream_t*)calloc(1, sizeof(wasi_stream_t));
st->kind = STREAM_FD;
st->fd = fd;
st->own_fd = false;
return alloc_res(w, rk, st);
}
u32 w2c_wasi_get_stdin(struct w2c_wasi* w) {
if (!w->stdin_h) w->stdin_h = make_stdio_stream(w, STDIN_FILENO, RES_INPUT_STREAM);
return w->stdin_h;
}
u32 w2c_wasi_get_stdout(struct w2c_wasi* w) {
if (!w->stdout_h) w->stdout_h = make_stdio_stream(w, STDOUT_FILENO, RES_OUTPUT_STREAM);
return w->stdout_h;
}
u32 w2c_wasi_get_stderr(struct w2c_wasi* w) {
if (!w->stderr_h) w->stderr_h = make_stdio_stream(w, STDERR_FILENO, RES_OUTPUT_STREAM);
return w->stderr_h;
}
/* ============================================================================
* Filesystem Preopens & Descriptors
* ========================================================================== */
static uint8_t errno_to_wasi_fs(int err) {
switch (err) {
case EACCES: return 0;
case EAGAIN: return 1;
case EALREADY: return 2;
case EBADF: return 3;
case EBUSY: return 4;
case EDEADLK: return 5;
case EDQUOT: return 6;
case EEXIST: return 7;
case EFBIG: return 8;
case EILSEQ: return 9;
case EINPROGRESS: return 10;
case EINTR: return 11;
case EINVAL: return 12;
case EIO: return 13;
case EISDIR: return 14;
case ELOOP: return 15;
case EMLINK: return 16;
case EMSGSIZE: return 17;
case ENAMETOOLONG: return 18;
case ENODEV: return 19;
case ENOENT: return 20;
case ENOLCK: return 21;
case ENOMEM: return 22;
case ENOSPC: return 23;
case ENOTDIR: return 24;
case ENOTEMPTY: return 25;
case EPERM: return 31;
case EPIPE: return 32;
case EROFS: return 33;
case ESPIPE: return 34;
case ETXTBSY: return 35;
case EXDEV: return 36;
default: return 13;
}
}
void w2c_wasi_get_directories(struct w2c_wasi* w, u32 retptr) {
if (!w->preopens_init) {
w->preopens_init = true;
int cwd_fd = open(".", O_RDONLY | O_DIRECTORY);
if (cwd_fd >= 0) {
wasi_desc_t* d = (wasi_desc_t*)calloc(1, sizeof(wasi_desc_t));
d->fd = cwd_fd;
d->own_fd = false;
w->preopens[w->preopen_cnt].desc_handle = alloc_res(w, RES_DESCRIPTOR, d);
w->preopens[w->preopen_cnt].path = ".";
w->preopen_cnt++;
}
int root_fd = open("/", O_RDONLY | O_DIRECTORY);
if (root_fd >= 0) {
wasi_desc_t* d = (wasi_desc_t*)calloc(1, sizeof(wasi_desc_t));
d->fd = root_fd;
d->own_fd = false;
w->preopens[w->preopen_cnt].desc_handle = alloc_res(w, RES_DESCRIPTOR, d);
w->preopens[w->preopen_cnt].path = "/";
w->preopen_cnt++;
}
}
u32 cnt = (u32)w->preopen_cnt;
u32 ptrs[2] = {0, 0};
u32 lens[2] = {0, 0};
for (u32 i = 0; i < cnt; i++) {
lens[i] = (u32)strlen(w->preopens[i].path);
ptrs[i] = guest_alloc_copy(w, w->preopens[i].path, lens[i]);
}
u32 arr = w2c_mem__mod_realloc(w->mem, 0, 0, 4, cnt * 12);
for (u32 i = 0; i < cnt; i++) {
write_u32(w, arr + i * 12, w->preopens[i].desc_handle);
write_u32(w, arr + i * 12 + 4, ptrs[i]);
write_u32(w, arr + i * 12 + 8, lens[i]);
}
write_u32(w, retptr, arr);
write_u32(w, retptr + 4, cnt);
}
void w2c_wasi_desc_open_at(struct w2c_wasi* w, u32 dir_h, u32 path_flags, u32 path_p, u32 path_l,
u32 open_flags, u32 desc_flags, u32 retptr) {
wasi_desc_t* dir = (wasi_desc_t*)get_res(w, dir_h, RES_DESCRIPTOR);
if (!dir) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 3);
return;
}
char* path = dup_guest_cstr(w, path_p, path_l);
int flags = 0;
bool r = (desc_flags & 1) != 0;
bool wr = (desc_flags & 2) != 0;
if (r && wr) flags |= O_RDWR;
else if (wr) flags |= O_WRONLY;
else flags |= O_RDONLY;
if (open_flags & 1) flags |= O_CREAT;
if (open_flags & 2) flags |= O_DIRECTORY;
if (open_flags & 4) flags |= O_EXCL;
if (open_flags & 8) flags |= O_TRUNC;
if (!(path_flags & 1)) flags |= O_NOFOLLOW;
int fd = openat(dir->fd, path, flags, 0666);
free(path);
if (fd < 0) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, errno_to_wasi_fs(errno));
return;
}
wasi_desc_t* d = (wasi_desc_t*)calloc(1, sizeof(wasi_desc_t));
d->fd = fd;
d->own_fd = true;
u32 h = alloc_res(w, RES_DESCRIPTOR, d);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
void w2c_wasi_desc_read_via_stream(struct w2c_wasi* w, u32 fd_h, u64 offset, u32 retptr) {
wasi_desc_t* d = (wasi_desc_t*)get_res(w, fd_h, RES_DESCRIPTOR);
if (!d) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 3);
return;
}
int duped = dup(d->fd);
if (duped < 0) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, errno_to_wasi_fs(errno));
return;
}
if (offset > 0) (void)lseek(duped, (off_t)offset, SEEK_SET);
wasi_stream_t* st = (wasi_stream_t*)calloc(1, sizeof(wasi_stream_t));
st->kind = STREAM_FD;
st->fd = duped;
st->own_fd = true;
u32 h = alloc_res(w, RES_INPUT_STREAM, st);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
void w2c_wasi_desc_write_via_stream(struct w2c_wasi* w, u32 fd_h, u64 offset, u32 retptr) {
wasi_desc_t* d = (wasi_desc_t*)get_res(w, fd_h, RES_DESCRIPTOR);
if (!d) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 3);
return;
}
int duped = dup(d->fd);
if (duped < 0) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, errno_to_wasi_fs(errno));
return;
}
if (offset > 0) (void)lseek(duped, (off_t)offset, SEEK_SET);
wasi_stream_t* st = (wasi_stream_t*)calloc(1, sizeof(wasi_stream_t));
st->kind = STREAM_FD;
st->fd = duped;
st->own_fd = true;
u32 h = alloc_res(w, RES_OUTPUT_STREAM, st);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
/* ============================================================================
* Socket / TLS I/O & HTTP Framing Reader
* ========================================================================== */
static int wait_fd(int fd, short events, uint64_t deadline_ns, bool has_deadline) {
while (1) {
int timeout_ms = -1;
if (has_deadline) {
uint64_t now = monotonic_ns();
if (now >= deadline_ns) return 0; /* timeout */
uint64_t rem_ms = (deadline_ns - now + 999999ULL) / 1000000ULL;
timeout_ms = rem_ms > INT_MAX ? INT_MAX : (int)rem_ms;
}
struct pollfd pfd = {.fd = fd, .events = events, .revents = 0};
int r = poll(&pfd, 1, timeout_ms);
if (r < 0) {
if (errno == EINTR) continue;
return -1;
}
if (r == 0) return 0; /* timeout */
return 1;
}
}
/* Returns >0 bytes read, 0 EOF, -1 I/O error, -2 timeout */
static ssize_t reader_raw_read(http_reader_t* r, uint8_t* dst, size_t max_len,
bool has_timeout, uint64_t timeout_ns) {
bool has_dl = has_timeout;
uint64_t dl = has_dl ? (monotonic_ns() + timeout_ns) : 0;
while (1) {
if (r->ssl) {
int n = SSL_read(r->ssl, dst, (int)max_len);
if (n > 0) return n;
int err = SSL_get_error(r->ssl, n);
if (err == SSL_ERROR_ZERO_RETURN) return 0;
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
short ev = (err == SSL_ERROR_WANT_WRITE) ? POLLOUT : POLLIN;
int wr = wait_fd(r->fd, ev, dl, has_dl);
if (wr == 0) return -2;
if (wr < 0) return -1;
continue;
}
if (err == SSL_ERROR_SYSCALL && errno == 0 && n == 0) return 0;
return -1;
} else {
ssize_t n = recv(r->fd, dst, max_len, 0);
if (n > 0) return n;
if (n == 0) return 0;
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
int wr = wait_fd(r->fd, POLLIN, dl, has_dl);
if (wr == 0) return -2;
if (wr < 0) return -1;
continue;
}
return -1;
}
}
}
static void reader_compact(http_reader_t* r) {
if (r->buf_pos > 0) {
size_t rem = r->buf_len - r->buf_pos;
if (rem > 0) memmove(r->buf, r->buf + r->buf_pos, rem);
r->buf_len = rem;
r->buf_pos = 0;
}
}
/* Fill reader->buf with at least 1 more byte. Returns 1 ok, 0 EOF, -1 error, -2 timeout */
static int reader_fill(http_reader_t* r, bool has_to, uint64_t to_ns) {
reader_compact(r);
if (r->buf_cap - r->buf_len < 4096) {
size_t nc = r->buf_cap ? r->buf_cap * 2 : 16384;
if (nc < r->buf_len + 4096) nc = r->buf_len + 8192;
r->buf = (uint8_t*)realloc(r->buf, nc);
r->buf_cap = nc;
}
ssize_t n = reader_raw_read(r, r->buf + r->buf_len, r->buf_cap - r->buf_len, has_to, to_ns);
if (n > 0) {
r->buf_len += (size_t)n;
return 1;
}
return (int)n;
}
/* Read one line ending in \n into caller buffer; returns >=0 line len (excluding CRLF/LF), -1 err, -2 timeout, -3 EOF */
static ssize_t reader_read_line(http_reader_t* r, char* out, size_t max_out, bool has_to, uint64_t to_ns) {
while (1) {
for (size_t i = r->buf_pos; i < r->buf_len; i++) {
if (r->buf[i] == '\n') {
size_t line_len = i - r->buf_pos;
size_t copy_len = line_len;
if (copy_len > 0 && r->buf[i - 1] == '\r') copy_len--;
if (copy_len >= max_out) copy_len = max_out - 1;
memcpy(out, r->buf + r->buf_pos, copy_len);
out[copy_len] = '\0';
r->buf_pos = i + 1;
return (ssize_t)copy_len;
}
}
int f = reader_fill(r, has_to, to_ns);
if (f == 0) return -3;
if (f < 0) return f;
}
}
/* Read decoded body bytes. Returns >0 bytes, 0 EOF, -1 err, -2 timeout */
static ssize_t reader_read_body(http_reader_t* r, uint8_t* dst, size_t max_len) {
if (r->eof || r->framing == FRAMING_NONE) return 0;
if (r->framing == FRAMING_CONTENT_LENGTH) {
if (r->content_remaining == 0) {
r->eof = true;
return 0;
}
size_t want = max_len < r->content_remaining ? max_len : (size_t)r->content_remaining;
if (r->buf_pos < r->buf_len) {
size_t avail = r->buf_len - r->buf_pos;
size_t take = avail < want ? avail : want;
memcpy(dst, r->buf + r->buf_pos, take);
r->buf_pos += take;
r->content_remaining -= take;
return (ssize_t)take;
}
ssize_t n = reader_raw_read(r, dst, want, r->has_between_timeout, r->between_timeout_ns);
if (n > 0) {
r->content_remaining -= (size_t)n;
return n;
}
if (n == 0 && r->content_remaining > 0) return -1; /* truncated */
return n;
}
if (r->framing == FRAMING_EOF) {
if (r->buf_pos < r->buf_len) {
size_t avail = r->buf_len - r->buf_pos;
size_t take = avail < max_len ? avail : max_len;
memcpy(dst, r->buf + r->buf_pos, take);
r->buf_pos += take;
return (ssize_t)take;
}
ssize_t n = reader_raw_read(r, dst, max_len, r->has_between_timeout, r->between_timeout_ns);
if (n == 0) r->eof = true;
return n;
}
/* FRAMING_CHUNKED */
while (1) {
if (r->chunk_st == CHUNK_DONE) {
r->eof = true;
return 0;
}
if (r->chunk_st == CHUNK_SIZE) {
char line[256];
ssize_t ll = reader_read_line(r, line, sizeof(line), r->has_between_timeout, r->between_timeout_ns);
if (ll == -3) return -1;
if (ll < 0) return ll;
char* semi = strchr(line, ';');
if (semi) *semi = '\0';
if (line[0] == '\0') return -1;
char* endp = NULL;
unsigned long long csz = strtoull(line, &endp, 16);
while (*endp == ' ' || *endp == '\t') endp++;
if (*endp != '\0') return -1;
if (csz == 0) {
r->chunk_st = CHUNK_TRAILERS;
} else {
r->chunk_rem = (uint64_t)csz;
r->chunk_st = CHUNK_DATA;
}
continue;
}
if (r->chunk_st == CHUNK_DATA) {
if (r->chunk_rem == 0) {
r->chunk_st = CHUNK_CRLF;
continue;
}
size_t want = max_len < r->chunk_rem ? max_len : (size_t)r->chunk_rem;
if (r->buf_pos < r->buf_len) {
size_t avail = r->buf_len - r->buf_pos;
size_t take = avail < want ? avail : want;
memcpy(dst, r->buf + r->buf_pos, take);
r->buf_pos += take;
r->chunk_rem -= take;
if (r->chunk_rem == 0) r->chunk_st = CHUNK_CRLF;
return (ssize_t)take;
}
ssize_t n = reader_raw_read(r, dst, want, r->has_between_timeout, r->between_timeout_ns);
if (n == 0) return -1;
if (n < 0) return n;
r->chunk_rem -= (size_t)n;
if (r->chunk_rem == 0) r->chunk_st = CHUNK_CRLF;
return n;
}
if (r->chunk_st == CHUNK_CRLF) {
char line[16];
ssize_t ll = reader_read_line(r, line, sizeof(line), r->has_between_timeout, r->between_timeout_ns);
if (ll == -3) return -1;
if (ll < 0) return ll;
if (ll != 0) return -1;
r->chunk_st = CHUNK_SIZE;
continue;
}
if (r->chunk_st == CHUNK_TRAILERS) {
char line[1024];
ssize_t ll = reader_read_line(r, line, sizeof(line), r->has_between_timeout, r->between_timeout_ns);
if (ll == -3 || ll == 0) {
r->chunk_st = CHUNK_DONE;
r->eof = true;
return 0;
}
if (ll < 0) return ll;
continue;
}
}
}
/* ============================================================================
* Streams, Pollables, Errors
* ========================================================================== */
void w2c_wasi_err_to_debug_string(struct w2c_wasi* w, u32 err_h, u32 retptr) {
io_error_t* e = (io_error_t*)get_res(w, err_h, RES_IO_ERROR);
const char* msg = (e && e->msg) ? e->msg : "unknown error";
size_t len = strlen(msg);
u32 gp = guest_alloc_copy(w, msg, len);
write_u32(w, retptr, gp);
write_u32(w, retptr + 4, (u32)len);
}
void w2c_wasi_poll_block(struct w2c_wasi* w, u32 poll_h) {
(void)w;
(void)poll_h;
}
void w2c_wasi_out_check_write(struct w2c_wasi* w, u32 s_h, u32 retptr) {
wasi_stream_t* st = (wasi_stream_t*)get_res(w, s_h, RES_OUTPUT_STREAM);
memset(mem_ptr(w, retptr), 0, 16);
if (!st) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 8, 1); /* closed */
return;
}
write_u8(w, retptr, 0);
write_u64(w, retptr + 8, 65536ULL);
}
void w2c_wasi_out_write(struct w2c_wasi* w, u32 s_h, u32 ptr, u32 len, u32 retptr) {
wasi_stream_t* st = (wasi_stream_t*)get_res(w, s_h, RES_OUTPUT_STREAM);
if (!st) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 1);
return;
}
if ((size_t)ptr + len > mem_sz(w)) {
u32 eh = make_io_err(w, "out-of-bounds write");
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 0);
write_u32(w, retptr + 8, eh);
return;
}
const uint8_t* src = mem_ptr(w, ptr);
if (st->kind == STREAM_OUT_BODY) {
out_body_t* ob = st->out_body;
if (len > 0) {
if (ob->len + len > ob->cap) {
size_t nc = ob->cap ? ob->cap * 2 : 4096;
while (nc < ob->len + len) nc *= 2;
ob->buf = (uint8_t*)realloc(ob->buf, nc);
ob->cap = nc;
}
memcpy(ob->buf + ob->len, src, len);
ob->len += len;
}
write_u8(w, retptr, 0);
return;
}
size_t off = 0;
while (off < len) {
ssize_t n = write(st->fd, src + off, len - off);
if (n < 0) {
if (errno == EINTR) continue;
u32 eh = make_io_err(w, strerror(errno));
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 0);
write_u32(w, retptr + 8, eh);
return;
}
off += (size_t)n;
}
write_u8(w, retptr, 0);
}
void w2c_wasi_out_blocking_flush(struct w2c_wasi* w, u32 s_h, u32 retptr) {
(void)s_h;
write_u8(w, retptr, 0);
}
u32 w2c_wasi_out_subscribe(struct w2c_wasi* w, u32 s_h) {
(void)s_h;
return alloc_res(w, RES_POLLABLE, (void*)1);
}
void w2c_wasi_in_blocking_read(struct w2c_wasi* w, u32 s_h, u64 max_len, u32 retptr) {
wasi_stream_t* st = (wasi_stream_t*)get_res(w, s_h, RES_INPUT_STREAM);
if (!st) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 1); /* closed */
return;
}
size_t req = max_len > 65536ULL ? 65536 : (size_t)max_len;
if (req == 0) req = 1;
uint8_t* tmp = (uint8_t*)malloc(req);
ssize_t n = 0;
if (st->kind == STREAM_FD) {
while (1) {
n = read(st->fd, tmp, req);
if (n < 0 && errno == EINTR) continue;
break;
}
} else if (st->kind == STREAM_HTTP_BODY) {
n = reader_read_body(st->http_reader, tmp, req);
}
if (n == 0) {
free(tmp);
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 1); /* closed / EOF */
return;
}
if (n < 0) {
const char* msg = (n == -2) ? "read timeout" : strerror(errno);
free(tmp);
u32 eh = make_io_err(w, msg);
write_u8(w, retptr, 1);
write_u8(w, retptr + 4, 0);
write_u32(w, retptr + 8, eh);
return;
}
u32 gp = guest_alloc_copy(w, tmp, (size_t)n);
free(tmp);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, gp);
write_u32(w, retptr + 8, (u32)n);
}
/* ============================================================================
* HTTP Types: Fields, Requests, Options
* ========================================================================== */
u32 w2c_wasi_new_fields(struct w2c_wasi* w) {
return alloc_res(w, RES_FIELDS, fields_create());
}
void w2c_wasi_fields_append(struct w2c_wasi* w, u32 f_h, u32 kp, u32 kl, u32 vp, u32 vl, u32 retptr) {
fields_t* f = (fields_t*)get_res(w, f_h, RES_FIELDS);
if (!f) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 1, 2); /* immutable */
return;
}
char* name = dup_guest_cstr(w, kp, kl);
uint8_t* val = (uint8_t*)malloc(vl + 1);
if (vl > 0 && (size_t)vp + vl <= mem_sz(w)) memcpy(val, mem_ptr(w, vp), vl);
val[vl] = '\0';
if (is_forbidden_req_header(name, kl)) {
free(name);
free(val);
write_u8(w, retptr, 1);
write_u8(w, retptr + 1, 1); /* forbidden */
return;
}
if (!valid_header_name(name, kl) || !valid_header_val(val, vl)) {
free(name);
free(val);
write_u8(w, retptr, 1);
write_u8(w, retptr + 1, 0); /* invalid-syntax */
return;
}
fields_push(f, name, kl, val, vl);
free(name);
free(val);
write_u8(w, retptr, 0);
}
void w2c_wasi_fields_delete(struct w2c_wasi* w, u32 f_h, u32 kp, u32 kl, u32 retptr) {
fields_t* f = (fields_t*)get_res(w, f_h, RES_FIELDS);
if (!f) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 1, 2);
return;
}
char* name = dup_guest_cstr(w, kp, kl);
size_t out = 0;
for (size_t i = 0; i < f->count; i++) {
if (ci_eq(f->items[i].name, f->items[i].name_len, name)) {
free(f->items[i].name);
free(f->items[i].val);
} else {
f->items[out++] = f->items[i];
}
}
f->count = out;
free(name);
write_u8(w, retptr, 0);
}
void w2c_wasi_fields_set(struct w2c_wasi* w, u32 f_h, u32 kp, u32 kl, u32 lp, u32 ll, u32 retptr) {
w2c_wasi_fields_delete(w, f_h, kp, kl, retptr);
if (mem_ptr(w, retptr)[0] != 0) return;
for (u32 i = 0; i < ll; i++) {
u32 vp = 0, vl = 0;
memcpy(&vp, mem_ptr(w, lp + i * 8), 4);
memcpy(&vl, mem_ptr(w, lp + i * 8 + 4), 4);
w2c_wasi_fields_append(w, f_h, kp, kl, vp, vl, retptr);
if (mem_ptr(w, retptr)[0] != 0) return;
}
write_u8(w, retptr, 0);
}
void w2c_wasi_fields_entries(struct w2c_wasi* w, u32 f_h, u32 retptr) {
fields_t* f = (fields_t*)get_res(w, f_h, RES_FIELDS);
u32 cnt = f ? (u32)f->count : 0;
if (cnt == 0) {
u32 arr = w2c_mem__mod_realloc(w->mem, 0, 0, 4, 0);
write_u32(w, retptr, arr);
write_u32(w, retptr + 4, 0);
return;
}
u32* kps = (u32*)calloc(cnt, sizeof(u32));
u32* vps = (u32*)calloc(cnt, sizeof(u32));
for (u32 i = 0; i < cnt; i++) {
kps[i] = guest_alloc_copy(w, f->items[i].name, f->items[i].name_len);
vps[i] = guest_alloc_copy(w, f->items[i].val, f->items[i].val_len);
}
u32 arr = w2c_mem__mod_realloc(w->mem, 0, 0, 4, cnt * 16);
for (u32 i = 0; i < cnt; i++) {
write_u32(w, arr + i * 16, kps[i]);
write_u32(w, arr + i * 16 + 4, (u32)f->items[i].name_len);
write_u32(w, arr + i * 16 + 8, vps[i]);
write_u32(w, arr + i * 16 + 12, (u32)f->items[i].val_len);
}
write_u32(w, retptr, arr);
write_u32(w, retptr + 4, cnt);
free(kps);
free(vps);
}
u32 w2c_wasi_new_outgoing_request(struct w2c_wasi* w, u32 hdrs_h) {
fields_t* f = (fields_t*)take_res(w, hdrs_h, RES_FIELDS);
if (!f) f = fields_create();
out_req_t* req = (out_req_t*)calloc(1, sizeof(out_req_t));
req->method = strdup("GET");
req->scheme = 0;
req->headers = f;
return alloc_res(w, RES_OUTGOING_REQUEST, req);
}
u32 w2c_wasi_req_set_method(struct w2c_wasi* w, u32 req_h, u32 tag, u32 mp, u32 ml) {
out_req_t* req = (out_req_t*)get_res(w, req_h, RES_OUTGOING_REQUEST);
if (!req) return 1;
static const char* const std_methods[] = {
"GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"
};
free(req->method);
if (tag < 9) {
req->method = strdup(std_methods[tag]);
} else {
if (ml == 0) {
req->method = strdup("GET");
return 1;
}
req->method = dup_guest_cstr(w, mp, ml);
}
return 0;
}
u32 w2c_wasi_req_set_scheme(struct w2c_wasi* w, u32 req_h, u32 opt_tag, u32 scheme_tag, u32 sp, u32 sl) {
(void)sp;
(void)sl;
out_req_t* req = (out_req_t*)get_res(w, req_h, RES_OUTGOING_REQUEST);
if (!req) return 1;
if (opt_tag == 0) {
req->scheme = 0;
return 0;
}
if (scheme_tag == 0 || scheme_tag == 1) {
req->scheme = (int)scheme_tag;
return 0;
}
return 1;
}
u32 w2c_wasi_req_set_authority(struct w2c_wasi* w, u32 req_h, u32 opt_tag, u32 ap, u32 al) {
out_req_t* req = (out_req_t*)get_res(w, req_h, RES_OUTGOING_REQUEST);
if (!req) return 1;
free(req->authority);
req->authority = (opt_tag && al > 0) ? dup_guest_cstr(w, ap, al) : NULL;
return 0;
}
u32 w2c_wasi_req_set_path(struct w2c_wasi* w, u32 req_h, u32 opt_tag, u32 pp, u32 pl) {
out_req_t* req = (out_req_t*)get_res(w, req_h, RES_OUTGOING_REQUEST);
if (!req) return 1;
free(req->path);
req->path = (opt_tag && pl > 0) ? dup_guest_cstr(w, pp, pl) : strdup("/");
return 0;
}
void w2c_wasi_outgoing_request_body(struct w2c_wasi* w, u32 req_h, u32 retptr) {
out_req_t* req = (out_req_t*)get_res(w, req_h, RES_OUTGOING_REQUEST);
if (!req || req->body != NULL) {
write_u8(w, retptr, 1);
return;
}
out_body_t* ob = (out_body_t*)calloc(1, sizeof(out_body_t));
req->body = ob;
u32 h = alloc_res(w, RES_OUTGOING_BODY, ob);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
void w2c_wasi_outgoing_body_write(struct w2c_wasi* w, u32 ob_h, u32 retptr) {
out_body_t* ob = (out_body_t*)get_res(w, ob_h, RES_OUTGOING_BODY);
if (!ob) {
write_u8(w, retptr, 1);
return;
}
wasi_stream_t* st = (wasi_stream_t*)calloc(1, sizeof(wasi_stream_t));
st->kind = STREAM_OUT_BODY;
st->out_body = ob;
u32 h = alloc_res(w, RES_OUTPUT_STREAM, st);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
void w2c_wasi_outgoing_body_finish(struct w2c_wasi* w, u32 ob_h, u32 trailers_tag, u32 trailers_h, u32 retptr) {
out_body_t* ob = (out_body_t*)take_res(w, ob_h, RES_OUTGOING_BODY);
if (trailers_tag) {
fields_t* tr = (fields_t*)take_res(w, trailers_h, RES_FIELDS);
fields_destroy(tr);
}
if (ob) ob->finished = true;
write_u8(w, retptr, 0);
}
u32 w2c_wasi_new_request_options(struct w2c_wasi* w) {
req_options_t* ro = (req_options_t*)calloc(1, sizeof(req_options_t));
return alloc_res(w, RES_REQUEST_OPTIONS, ro);
}
u32 w2c_wasi_ro_set_connect_timeout(struct w2c_wasi* w, u32 ro_h, u32 opt_tag, u64 ns) {
req_options_t* ro = (req_options_t*)get_res(w, ro_h, RES_REQUEST_OPTIONS);
if (!ro) return 1;
ro->has_connect_timeout = (opt_tag != 0);
ro->connect_timeout_ns = ns;
return 0;
}
u32 w2c_wasi_ro_set_first_byte_timeout(struct w2c_wasi* w, u32 ro_h, u32 opt_tag, u64 ns) {
req_options_t* ro = (req_options_t*)get_res(w, ro_h, RES_REQUEST_OPTIONS);
if (!ro) return 1;
ro->has_first_byte_timeout = (opt_tag != 0);
ro->first_byte_timeout_ns = ns;
return 0;
}
u32 w2c_wasi_ro_set_between_bytes_timeout(struct w2c_wasi* w, u32 ro_h, u32 opt_tag, u64 ns) {
req_options_t* ro = (req_options_t*)get_res(w, ro_h, RES_REQUEST_OPTIONS);
if (!ro) return 1;
ro->has_between_bytes_timeout = (opt_tag != 0);
ro->between_bytes_timeout_ns = ns;
return 0;
}
/* ============================================================================
* HTTP/1.1 + OpenSSL Execution Engine
* ========================================================================== */
static bool parse_authority(const char* auth, int scheme, char* host_out, size_t host_cap, char* port_out, size_t port_cap) {
if (!auth || !*auth) return false;
const char* def_port = (scheme == 1) ? "443" : "80";
if (auth[0] == '[') {
const char* close_b = strchr(auth, ']');
if (!close_b) return false;
size_t hlen = (size_t)(close_b - (auth + 1));
if (hlen == 0 || hlen >= host_cap) return false;
memcpy(host_out, auth + 1, hlen);
host_out[hlen] = '\0';
if (close_b[1] == ':' && close_b[2] != '\0') {
snprintf(port_out, port_cap, "%s", close_b + 2);
} else {
snprintf(port_out, port_cap, "%s", def_port);
}
return true;
}
const char* colon = strrchr(auth, ':');
if (colon && colon[1] != '\0') {
size_t hlen = (size_t)(colon - auth);
if (hlen == 0 || hlen >= host_cap) return false;
memcpy(host_out, auth, hlen);
host_out[hlen] = '\0';
snprintf(port_out, port_cap, "%s", colon + 1);
return true;
}
if (strlen(auth) >= host_cap) return false;
snprintf(host_out, host_cap, "%s", auth);
snprintf(port_out, port_cap, "%s", def_port);
return true;
}
static int raw_write_all(int fd, SSL* ssl, const uint8_t* data, size_t len, bool has_to, uint64_t to_ns) {
size_t off = 0;
uint64_t dl = has_to ? (monotonic_ns() + to_ns) : 0;
while (off < len) {
if (ssl) {
int n = SSL_write(ssl, data + off, (int)(len - off));
if (n > 0) {
off += (size_t)n;
continue;
}
int err = SSL_get_error(ssl, n);
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
short ev = (err == SSL_ERROR_WANT_READ) ? POLLIN : POLLOUT;
int wr = wait_fd(fd, ev, dl, has_to);
if (wr == 0) return -2;
if (wr < 0) return -1;
continue;
}
return -1;
} else {
ssize_t n = send(fd, data + off, len - off, 0);
if (n > 0) {
off += (size_t)n;
continue;
}
if (n < 0 && errno == EINTR) continue;
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
int wr = wait_fd(fd, POLLOUT, dl, has_to);
if (wr == 0) return -2;
if (wr < 0) return -1;
continue;
}
return -1;
}
}
return 0;
}
static uint8_t execute_http(struct w2c_wasi* w, fir_t* fir) {
out_req_t* req = fir->req;
req_options_t* opts = fir->has_opts ? fir->opts : NULL;
char host[512], port[32];
if (!parse_authority(req->authority, req->scheme, host, sizeof(host), port, sizeof(port))) {
return 19; /* HTTP-request-URI-invalid */
}
struct addrinfo hints, *res = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, port, &hints, &res) != 0 || !res) {
return 1; /* DNS-error */
}
int fd = -1;
uint8_t last_conn_err = 7;
bool has_ct = opts && opts->has_connect_timeout;
uint64_t ct_dl = has_ct ? (monotonic_ns() + opts->connect_timeout_ns) : 0;
for (struct addrinfo* rp = res; rp != NULL; rp = rp->ai_next) {
int s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (s < 0) continue;
int fl = fcntl(s, F_GETFL, 0);
if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK);
int rc = connect(s, rp->ai_addr, rp->ai_addrlen);
if (rc == 0) {
fd = s;
break;
}
if (errno == EINPROGRESS) {
int wr = wait_fd(s, POLLOUT, ct_dl, has_ct);
if (wr == 0) {
close(s);
last_conn_err = 8; /* connection-timeout */
break;
}
if (wr > 0) {
int so_err = 0;
socklen_t slen = sizeof(so_err);
if (getsockopt(s, SOL_SOCKET, SO_ERROR, &so_err, &slen) == 0 && so_err == 0) {
fd = s;
break;
}
if (so_err == ECONNREFUSED) last_conn_err = 6;
}
} else if (errno == ECONNREFUSED) {
last_conn_err = 6; /* connection-refused */
}
close(s);
}
freeaddrinfo(res);
if (fd < 0) return last_conn_err;
SSL_CTX* ctx = NULL;
SSL* ssl = NULL;
if (req->scheme == 1) {
ctx = SSL_CTX_new(TLS_client_method());
if (!ctx) {
close(fd);
return 12; /* TLS-protocol-error */
}
SSL_CTX_set_default_verify_paths(ctx);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
ssl = SSL_new(ctx);
if (!ssl) {
SSL_CTX_free(ctx);
close(fd);
return 12;
}
SSL_set_fd(ssl, fd);
SSL_set_tlsext_host_name(ssl, host);
SSL_set1_host(ssl, host);
while (1) {
int cr = SSL_connect(ssl);
if (cr == 1) break;
int serr = SSL_get_error(ssl, cr);
if (serr == SSL_ERROR_WANT_READ || serr == SSL_ERROR_WANT_WRITE) {
short ev = (serr == SSL_ERROR_WANT_WRITE) ? POLLOUT : POLLIN;
int wr = wait_fd(fd, ev, ct_dl, has_ct);
if (wr == 0) {
SSL_free(ssl);
SSL_CTX_free(ctx);
close(fd);
return 8; /* connection-timeout */
}
if (wr < 0) {
SSL_free(ssl);
SSL_CTX_free(ctx);
close(fd);
return 12;
}
continue;
}
long vres = SSL_get_verify_result(ssl);
SSL_free(ssl);
SSL_CTX_free(ctx);
close(fd);
return (vres != X509_V_OK) ? 13 : 12;
}
}
/* Serialize HTTP/1.1 request headers */
size_t hdr_cap = 1024 + (req->headers ? req->headers->count * 128 : 0);
uint8_t* hdr_buf = (uint8_t*)malloc(hdr_cap);
size_t hdr_len = 0;
#define HDR_APPEND(ptr, n) do { \
size_t _n = (n); \
if (hdr_len + _n > hdr_cap) { \
while (hdr_cap < hdr_len + _n) hdr_cap *= 2; \
hdr_buf = (uint8_t*)realloc(hdr_buf, hdr_cap); \
} \
memcpy(hdr_buf + hdr_len, (ptr), _n); \
hdr_len += _n; \
} while (0)
const char* rpath = (req->path && req->path[0]) ? req->path : "/";
HDR_APPEND(req->method, strlen(req->method));
HDR_APPEND(" ", 1);
HDR_APPEND(rpath, strlen(rpath));
HDR_APPEND(" HTTP/1.1\r\nHost: ", 17);
HDR_APPEND(req->authority, strlen(req->authority));
HDR_APPEND("\r\nConnection: close\r\n", 21);
bool saw_cl = false;
if (req->headers) {
for (size_t i = 0; i < req->headers->count; i++) {
field_item_t* it = &req->headers->items[i];
if (ci_eq(it->name, it->name_len, "content-length")) saw_cl = true;
HDR_APPEND(it->name, it->name_len);
HDR_APPEND(": ", 2);
if (it->val_len > 0) HDR_APPEND(it->val, it->val_len);
HDR_APPEND("\r\n", 2);
}
}
if (req->body && !saw_cl) {
char cl_line[64];
int cl_n = snprintf(cl_line, sizeof(cl_line), "Content-Length: %zu\r\n", req->body->len);
HDR_APPEND(cl_line, (size_t)cl_n);
}
HDR_APPEND("\r\n", 2);
#undef HDR_APPEND
bool has_fb = opts && opts->has_first_byte_timeout;
uint64_t fb_ns = has_fb ? opts->first_byte_timeout_ns : 0;
int wr = raw_write_all(fd, ssl, hdr_buf, hdr_len, has_fb, fb_ns);
free(hdr_buf);
if (wr == 0 && req->body && req->body->len > 0) {
wr = raw_write_all(fd, ssl, req->body->buf, req->body->len, has_fb, fb_ns);
}
if (wr != 0) {
if (ssl) SSL_free(ssl);
if (ctx) SSL_CTX_free(ctx);
close(fd);
return (wr == -2) ? 10 : 7; /* connection-write-timeout / connection-terminated */
}
/* Create HTTP reader and read response head */
http_reader_t* r = (http_reader_t*)calloc(1, sizeof(http_reader_t));
r->fd = fd;
r->ssl_ctx = ctx;
r->ssl = ssl;
r->has_between_timeout = opts && opts->has_between_bytes_timeout;
r->between_timeout_ns = r->has_between_timeout ? opts->between_bytes_timeout_ns : 0;
/* Read until \r\n\r\n or \n\n */
size_t head_end = 0;
size_t body_start = 0;
bool found_head = false;
uint64_t head_dl = has_fb ? (monotonic_ns() + fb_ns) : 0;
while (!found_head) {
for (size_t i = 0; i + 3 < r->buf_len; i++) {
if (r->buf[i] == '\r' && r->buf[i + 1] == '\n' && r->buf[i + 2] == '\r' && r->buf[i + 3] == '\n') {
head_end = i + 2;
body_start = i + 4;
found_head = true;
break;
}
}
if (found_head) break;
/* Also handle bare \n\n if a server omits \r */
for (size_t i = 0; i + 1 < r->buf_len; i++) {
if (r->buf[i] == '\n' && r->buf[i + 1] == '\n') {
head_end = i + 1;
body_start = i + 2;
found_head = true;
break;
}
}
if (found_head) break;
uint64_t rem_to = 0;
if (has_fb) {
uint64_t now = monotonic_ns();
if (now >= head_dl) {
reader_destroy(r);
return 9; /* connection-read-timeout */
}
rem_to = head_dl - now;
}
int rf = reader_fill(r, has_fb, rem_to);
if (rf == 0) {
reader_destroy(r);
return 25; /* HTTP-response-incomplete */
}
if (rf == -2) {
reader_destroy(r);
return 9; /* connection-read-timeout */
}
if (rf < 0) {
reader_destroy(r);
return 7; /* connection-terminated */
}
}
/* Parse status line */
size_t pos = 0;
size_t line_end = pos;
while (line_end < head_end && r->buf[line_end] != '\n') line_end++;
size_t sl_len = line_end - pos;
if (sl_len > 0 && r->buf[pos + sl_len - 1] == '\r') sl_len--;
char* status_line = (char*)malloc(sl_len + 1);
memcpy(status_line, r->buf + pos, sl_len);
status_line[sl_len] = '\0';
const char* sp = strchr(status_line, ' ');
if (!sp) {
free(status_line);
reader_destroy(r);
return 35; /* HTTP-protocol-error */
}
while (*sp == ' ') sp++;
int status = atoi(sp);
free(status_line);
if (status < 100 || status > 999) {
reader_destroy(r);
return 35;
}
/* Parse response headers */
fields_t* rh = fields_create();
bool is_chunked = false;
bool has_cl = false;
uint64_t cl_val = 0;
pos = line_end + 1;
while (pos < head_end) {
line_end = pos;
while (line_end < head_end && r->buf[line_end] != '\n') line_end++;
size_t ll = line_end - pos;
if (ll > 0 && r->buf[pos + ll - 1] == '\r') ll--;
if (ll > 0) {
const uint8_t* line = r->buf + pos;
const uint8_t* colon = (const uint8_t*)memchr(line, ':', ll);
if (colon && colon > line) {
size_t klen = (size_t)(colon - line);
char* kbuf = (char*)malloc(klen + 1);
for (size_t j = 0; j < klen; j++) kbuf[j] = (char)tolower((unsigned char)line[j]);
kbuf[klen] = '\0';
const uint8_t* vstart = colon + 1;
size_t vlen = ll - klen - 1;
while (vlen > 0 && (*vstart == ' ' || *vstart == '\t')) {
vstart++;
vlen--;
}
while (vlen > 0 && (vstart[vlen - 1] == ' ' || vstart[vlen - 1] == '\t')) {
vlen--;
}
fields_push(rh, kbuf, klen, vstart, vlen);
if (strcmp(kbuf, "transfer-encoding") == 0) {
char* tmpv = (char*)malloc(vlen + 1);
for (size_t j = 0; j < vlen; j++) tmpv[j] = (char)tolower((unsigned char)vstart[j]);
tmpv[vlen] = '\0';
if (strstr(tmpv, "chunked") != NULL) is_chunked = true;
free(tmpv);
} else if (strcmp(kbuf, "content-length") == 0 && !has_cl) {
char* tmpv = (char*)malloc(vlen + 1);
memcpy(tmpv, vstart, vlen);
tmpv[vlen] = '\0';
cl_val = strtoull(tmpv, NULL, 10);
has_cl = true;
free(tmpv);
}
free(kbuf);
}
}
pos = line_end + 1;
}
r->buf_pos = body_start;
if (strcasecmp(req->method, "HEAD") == 0 || status == 204 || status == 304 || (status >= 100 && status < 200)) {
r->framing = FRAMING_NONE;
} else if (is_chunked) {
r->framing = FRAMING_CHUNKED;
r->chunk_st = CHUNK_SIZE;
} else if (has_cl) {
r->framing = FRAMING_CONTENT_LENGTH;
r->content_remaining = cl_val;
} else {
r->framing = FRAMING_EOF;
}
in_resp_t* resp = (in_resp_t*)calloc(1, sizeof(in_resp_t));
resp->status = (uint16_t)status;
resp->headers = rh;
resp->reader = r;
fir->resp_handle = alloc_res(w, RES_INCOMING_RESPONSE, resp);
return 0;
}
void w2c_wasi_http_handle(struct w2c_wasi* w, u32 req_h, u32 opt_tag, u32 opts_h, u32 retptr) {
out_req_t* req = (out_req_t*)take_res(w, req_h, RES_OUTGOING_REQUEST);
req_options_t* opts = NULL;
if (opt_tag) opts = (req_options_t*)take_res(w, opts_h, RES_REQUEST_OPTIONS);
if (!req) {
if (opts) free(opts);
memset(mem_ptr(w, retptr), 0, 40);
write_u8(w, retptr, 1);
write_u8(w, retptr + 8, 38); /* internal-error */
return;
}
fir_t* fir = (fir_t*)calloc(1, sizeof(fir_t));
fir->req = req;
fir->opts = opts;
fir->has_opts = (opts != NULL);
u32 fh = alloc_res(w, RES_FIR, fir);
memset(mem_ptr(w, retptr), 0, 40);
write_u8(w, retptr, 0);
write_u32(w, retptr + 8, fh);
}
u32 w2c_wasi_fir_subscribe(struct w2c_wasi* w, u32 fir_h) {
(void)fir_h;
return alloc_res(w, RES_POLLABLE, (void*)1);
}
void w2c_wasi_fir_get(struct w2c_wasi* w, u32 fir_h, u32 retptr) {
fir_t* fir = (fir_t*)get_res(w, fir_h, RES_FIR);
memset(mem_ptr(w, retptr), 0, 56);
if (!fir) {
write_u8(w, retptr, 1);
write_u8(w, retptr + 8, 1);
return;
}
if (!fir->done) {
fir->done = true;
uint8_t ec = execute_http(w, fir);
if (ec != 0) {
fir->is_err = true;
fir->err_code = ec;
}
}
write_u8(w, retptr, 1); /* Some */
write_u8(w, retptr + 8, 0); /* outer Ok */
if (fir->is_err) {
write_u8(w, retptr + 16, 1); /* inner Err */
write_u8(w, retptr + 24, fir->err_code);
} else {
write_u8(w, retptr + 16, 0); /* inner Ok */
write_u32(w, retptr + 24, fir->resp_handle);
}
}
u32 w2c_wasi_resp_status(struct w2c_wasi* w, u32 resp_h) {
in_resp_t* resp = (in_resp_t*)get_res(w, resp_h, RES_INCOMING_RESPONSE);
return resp ? (u32)resp->status : 0;
}
u32 w2c_wasi_resp_headers(struct w2c_wasi* w, u32 resp_h) {
in_resp_t* resp = (in_resp_t*)get_res(w, resp_h, RES_INCOMING_RESPONSE);
return alloc_res(w, RES_FIELDS, fields_clone(resp ? resp->headers : NULL));
}
void w2c_wasi_resp_consume(struct w2c_wasi* w, u32 resp_h, u32 retptr) {
in_resp_t* resp = (in_resp_t*)get_res(w, resp_h, RES_INCOMING_RESPONSE);
if (!resp || resp->consumed || !resp->reader) {
write_u8(w, retptr, 1);
return;
}
resp->consumed = true;
in_body_t* ib = (in_body_t*)calloc(1, sizeof(in_body_t));
ib->reader = resp->reader;
resp->reader = NULL;
u32 h = alloc_res(w, RES_INCOMING_BODY, ib);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
void w2c_wasi_body_stream(struct w2c_wasi* w, u32 ib_h, u32 retptr) {
in_body_t* ib = (in_body_t*)get_res(w, ib_h, RES_INCOMING_BODY);
if (!ib || !ib->reader) {
write_u8(w, retptr, 1);
return;
}
wasi_stream_t* st = (wasi_stream_t*)calloc(1, sizeof(wasi_stream_t));
st->kind = STREAM_HTTP_BODY;
st->http_reader = ib->reader;
ib->reader = NULL;
u32 h = alloc_res(w, RES_INPUT_STREAM, st);
write_u8(w, retptr, 0);
write_u32(w, retptr + 4, h);
}
/* ============================================================================
* Resource Drops
* ========================================================================== */
void w2c_wasi_drop_io_error(struct w2c_wasi* w, u32 h) {
io_error_t* e = (io_error_t*)take_res(w, h, RES_IO_ERROR);
if (e) {
free(e->msg);
free(e);
}
}
void w2c_wasi_drop_pollable(struct w2c_wasi* w, u32 h) {
(void)take_res(w, h, RES_POLLABLE);
}
static void drop_stream(struct w2c_wasi* w, u32 h, enum res_kind rk) {
wasi_stream_t* st = (wasi_stream_t*)take_res(w, h, rk);
if (!st) return;
if (st->kind == STREAM_FD && st->own_fd && st->fd >= 0) {
close(st->fd);
} else if (st->kind == STREAM_HTTP_BODY && st->http_reader) {
reader_destroy(st->http_reader);
}
free(st);
}
void w2c_wasi_drop_input_stream(struct w2c_wasi* w, u32 h) {
drop_stream(w, h, RES_INPUT_STREAM);
}
void w2c_wasi_drop_output_stream(struct w2c_wasi* w, u32 h) {
drop_stream(w, h, RES_OUTPUT_STREAM);
}
void w2c_wasi_drop_descriptor(struct w2c_wasi* w, u32 h) {
wasi_desc_t* d = (wasi_desc_t*)take_res(w, h, RES_DESCRIPTOR);
if (!d) return;
if (d->own_fd && d->fd >= 0) close(d->fd);
free(d);
}
void w2c_wasi_drop_fields(struct w2c_wasi* w, u32 h) {
fields_t* f = (fields_t*)take_res(w, h, RES_FIELDS);
fields_destroy(f);
}
void w2c_wasi_drop_outgoing_body(struct w2c_wasi* w, u32 h) {
(void)take_res(w, h, RES_OUTGOING_BODY);
}
void w2c_wasi_drop_outgoing_request(struct w2c_wasi* w, u32 h) {
out_req_t* req = (out_req_t*)take_res(w, h, RES_OUTGOING_REQUEST);
out_req_destroy(req);
}
void w2c_wasi_drop_request_options(struct w2c_wasi* w, u32 h) {
req_options_t* ro = (req_options_t*)take_res(w, h, RES_REQUEST_OPTIONS);
free(ro);
}
void w2c_wasi_drop_incoming_body(struct w2c_wasi* w, u32 h) {
in_body_t* ib = (in_body_t*)take_res(w, h, RES_INCOMING_BODY);
if (!ib) return;
if (ib->reader) reader_destroy(ib->reader);
free(ib);
}
void w2c_wasi_drop_incoming_response(struct w2c_wasi* w, u32 h) {
in_resp_t* resp = (in_resp_t*)take_res(w, h, RES_INCOMING_RESPONSE);
if (!resp) return;
fields_destroy(resp->headers);
if (resp->reader) reader_destroy(resp->reader);
free(resp);
}
void w2c_wasi_drop_fir(struct w2c_wasi* w, u32 h) {
fir_t* fir = (fir_t*)take_res(w, h, RES_FIR);
if (!fir) return;
out_req_destroy(fir->req);
free(fir->opts);
free(fir);
}
/* ============================================================================
* Native Entrypoint
* ========================================================================== */
int main(int argc, char** argv) {
signal(SIGPIPE, SIG_IGN);
wasm_rt_init();
w2c_mem__mod mem_inst;
wasm2c_mem__mod_instantiate(&mem_inst);
struct w2c_mem mem_env = {.mod = &mem_inst};
struct w2c_wasi wasi_env;
memset(&wasi_env, 0, sizeof(wasi_env));
wasi_env.mem = &mem_inst;
wasi_env.argc = argc;
wasi_env.argv = argv;
w2c_curl__core curl_inst;
wasm2c_curl__core_instantiate(&curl_inst, &mem_env, &wasi_env);
u32 rc = w2c_curl__core_run(&curl_inst);
/* Clean up any cached preopen directory fds and handle table */
for (size_t i = 0; i < wasi_env.preopen_cnt; i++) {
wasi_desc_t* d = (wasi_desc_t*)take_res(&wasi_env, wasi_env.preopens[i].desc_handle, RES_DESCRIPTOR);
if (d) {
if (d->fd >= 0) close(d->fd);
free(d);
}
}
free(wasi_env.res);
wasm2c_curl__core_free(&curl_inst);
wasm2c_mem__mod_free(&mem_inst);
wasm_rt_free();
return rc != 0 ? 1 : 0;
}