Echo Server
To an Internet Computer app, incoming HTTP requests appear as a Candid blob. This echo server responds to an HTTP request by showing the blob in hex:
The source:
#define WASM_IMPORT(m,n) __attribute__((import_module(m))) __attribute__((import_name(n)));
#define WASM_EXPORT(n) asm(n) __attribute__((visibility("default")))
typedef unsigned u32;
u32 arg_size(void) WASM_IMPORT("ic0", "msg_arg_data_size");
void arg_copy(void *, u32, u32) WASM_IMPORT("ic0", "msg_arg_data_copy");
void reply_append(void *, u32) WASM_IMPORT("ic0", "msg_reply_data_append");
void reply(void) WASM_IMPORT("ic0", "msg_reply");
char hexdig(u32 i) { return i < 10 ? i + '0' : i + 'a' - 10; }
void go() WASM_EXPORT("canister_query http_request");
void go() {
enum { max = 16384 };
unsigned char buf[max];
u32 sz = arg_size();
sz = sz > max ? max : sz;
arg_copy(buf, 0, sz);
char msg[max*2 + 32];
char *p = msg;
u32 i;
for (i = 0; i < sz; i++) {
*p++ = hexdig(buf[i] / 16);
*p++ = hexdig(buf[i] % 16);
}
char hdr[] = "DIDL\x03\x6c\x03"
"\xa2\xf5\xed\x88\x04\x01"
"\xc6\xa4\xa1\x98\x06\x02"
"\x9a\xa1\xb2\xf9\x0c\x7a\x6d"
"\x7b\x6d\x6f\x01\x00";
char ftr[] = "\x00\xc8\x00";
reply_append(hdr, sizeof(hdr) - 1);
char leb[5];
u32 n = 2*sz;
for (i = 0; i < 4; i++) {
leb[i] = (n & 127) | 128;
n >>= 7;
}
leb[i] = n;
reply_append(leb, 5);
reply_append(msg, 2*sz);
reply_append(ftr, sizeof(ftr) - 1);
reply();
}
To compile:
$ clang --target=wasm32 -c echo.c $ wasm-ld --export-dynamic --allow-undefined --no-entry -o echo.wasm echo.c
To deploy:
$ touch nothing
$ echo '{"canisters":{"echo":{"type":"custom","candid":"nothing","wasm":"echo.wasm","build":""}}}' > dfx.json
$ dfx deploy