create-cgull 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,230 @@
1
+ // The cgull shim: runs a WASI (preview1) module as a CGI script. Each
2
+ // request gets a fresh instance, with the request as environment variables
3
+ // and stdin; the response is parsed from stdout. Only the few WASI calls a
4
+ // CGI program needs are real; anything else the module imports answers
5
+ // ENOSYS.
6
+
7
+ const ESUCCESS = 0;
8
+ const EBADF = 8;
9
+ const ENOSYS = 52;
10
+ const ESPIPE = 70;
11
+
12
+ class Exit {
13
+ constructor(code) {
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ const encoder = new TextEncoder();
19
+
20
+ // Worker vars and secrets are strings; bindings (KV, D1, ...) are not.
21
+ export function stringVars(env = {}) {
22
+ return Object.fromEntries(Object.entries(env).filter(([, v]) => typeof v === "string"));
23
+ }
24
+
25
+ export async function runCgi(module, request, vars = {}) {
26
+ const body = new Uint8Array(await request.arrayBuffer());
27
+ const env = { ...vars, ...cgiEnv(request, body.length) };
28
+ let result;
29
+ try {
30
+ result = run(module, env, body);
31
+ } catch (e) {
32
+ // A trap: abort(), a failed assert(), a bad memory access.
33
+ console.error(`cgull: the program crashed: ${e}`);
34
+ return new Response("Internal Server Error\n", { status: 500 });
35
+ }
36
+ const { stdout, stderr, code } = result;
37
+ if (stderr.length) console.log(new TextDecoder().decode(stderr).trimEnd());
38
+ if (code !== 0) {
39
+ console.error(`cgull: the program exited with status ${code}`);
40
+ return new Response("Internal Server Error\n", { status: 500 });
41
+ }
42
+ return parseResponse(stdout);
43
+ }
44
+
45
+ function decodePath(path) {
46
+ try {
47
+ return decodeURIComponent(path);
48
+ } catch {
49
+ return path;
50
+ }
51
+ }
52
+
53
+ export function cgiEnv(request, contentLength) {
54
+ const url = new URL(request.url);
55
+ const env = {
56
+ GATEWAY_INTERFACE: "CGI/1.1",
57
+ SERVER_PROTOCOL: "HTTP/1.1",
58
+ SERVER_SOFTWARE: "cgull",
59
+ SERVER_NAME: url.hostname,
60
+ SERVER_PORT: url.port || (url.protocol === "https:" ? "443" : "80"),
61
+ REQUEST_METHOD: request.method,
62
+ REQUEST_URI: url.pathname + url.search,
63
+ SCRIPT_NAME: "",
64
+ PATH_INFO: decodePath(url.pathname),
65
+ QUERY_STRING: url.search.slice(1),
66
+ REMOTE_ADDR: request.headers.get("cf-connecting-ip") ?? "",
67
+ HTTPS: url.protocol === "https:" ? "on" : "off",
68
+ };
69
+ if (contentLength) env.CONTENT_LENGTH = String(contentLength);
70
+ for (const [name, value] of request.headers) {
71
+ const key = name.toUpperCase().replaceAll("-", "_");
72
+ if (key === "CONTENT_TYPE") env.CONTENT_TYPE = value;
73
+ else if (key !== "CONTENT_LENGTH") env["HTTP_" + key] = value;
74
+ }
75
+ return env;
76
+ }
77
+
78
+ function run(module, env, stdin) {
79
+ const environ = Object.entries(env).map(([k, v]) => encoder.encode(`${k}=${v}\0`));
80
+ const out = { 1: [], 2: [] };
81
+ let stdinPos = 0;
82
+ let memory;
83
+ const view = () => new DataView(memory.buffer);
84
+ const bytes = () => new Uint8Array(memory.buffer);
85
+
86
+ const wasi = {
87
+ environ_sizes_get(countPtr, sizePtr) {
88
+ view().setUint32(countPtr, environ.length, true);
89
+ view().setUint32(sizePtr, environ.reduce((n, e) => n + e.length, 0), true);
90
+ return ESUCCESS;
91
+ },
92
+ environ_get(ptrsPtr, bufPtr) {
93
+ for (const [i, e] of environ.entries()) {
94
+ view().setUint32(ptrsPtr + i * 4, bufPtr, true);
95
+ bytes().set(e, bufPtr);
96
+ bufPtr += e.length;
97
+ }
98
+ return ESUCCESS;
99
+ },
100
+ args_sizes_get(countPtr, sizePtr) {
101
+ view().setUint32(countPtr, 0, true);
102
+ view().setUint32(sizePtr, 0, true);
103
+ return ESUCCESS;
104
+ },
105
+ args_get() {
106
+ return ESUCCESS;
107
+ },
108
+ fd_write(fd, iovs, iovsLen, nwrittenPtr) {
109
+ if (!out[fd]) return EBADF;
110
+ let n = 0;
111
+ for (let i = 0; i < iovsLen; i++) {
112
+ const ptr = view().getUint32(iovs + i * 8, true);
113
+ const len = view().getUint32(iovs + i * 8 + 4, true);
114
+ out[fd].push(bytes().slice(ptr, ptr + len));
115
+ n += len;
116
+ }
117
+ view().setUint32(nwrittenPtr, n, true);
118
+ return ESUCCESS;
119
+ },
120
+ fd_read(fd, iovs, iovsLen, nreadPtr) {
121
+ if (fd !== 0) return EBADF;
122
+ let n = 0;
123
+ for (let i = 0; i < iovsLen && stdinPos < stdin.length; i++) {
124
+ const ptr = view().getUint32(iovs + i * 8, true);
125
+ const len = view().getUint32(iovs + i * 8 + 4, true);
126
+ const chunk = stdin.subarray(stdinPos, stdinPos + len);
127
+ bytes().set(chunk, ptr);
128
+ stdinPos += chunk.length;
129
+ n += chunk.length;
130
+ }
131
+ view().setUint32(nreadPtr, n, true);
132
+ return ESUCCESS;
133
+ },
134
+ fd_fdstat_get(fd, statPtr) {
135
+ if (fd > 2) return EBADF;
136
+ // A character device with every right; libc only checks the type.
137
+ bytes().fill(0, statPtr, statPtr + 24);
138
+ view().setUint8(statPtr, 2);
139
+ view().setBigUint64(statPtr + 8, 0xffffffffffffffffn, true);
140
+ view().setBigUint64(statPtr + 16, 0xffffffffffffffffn, true);
141
+ return ESUCCESS;
142
+ },
143
+ fd_seek() {
144
+ return ESPIPE;
145
+ },
146
+ fd_close() {
147
+ return ESUCCESS;
148
+ },
149
+ fd_prestat_get() {
150
+ return EBADF; // no preopened directories
151
+ },
152
+ clock_time_get(_id, _precision, timePtr) {
153
+ view().setBigUint64(timePtr, BigInt(Date.now()) * 1000000n, true);
154
+ return ESUCCESS;
155
+ },
156
+ random_get(ptr, len) {
157
+ crypto.getRandomValues(bytes().subarray(ptr, ptr + len));
158
+ return ESUCCESS;
159
+ },
160
+ proc_exit(code) {
161
+ throw new Exit(code);
162
+ },
163
+ };
164
+
165
+ const imports = {};
166
+ for (const imp of WebAssembly.Module.imports(module)) {
167
+ if (imp.kind !== "function") continue;
168
+ const ns = (imports[imp.module] ??= {});
169
+ ns[imp.name] = imp.module === "wasi_snapshot_preview1" && wasi[imp.name]
170
+ ? wasi[imp.name]
171
+ : () => ENOSYS;
172
+ }
173
+
174
+ const instance = new WebAssembly.Instance(module, imports);
175
+ memory = instance.exports.memory;
176
+ let code = 0;
177
+ try {
178
+ instance.exports._start();
179
+ } catch (e) {
180
+ if (!(e instanceof Exit)) throw e;
181
+ code = e.code;
182
+ }
183
+ return { stdout: concat(out[1]), stderr: concat(out[2]), code };
184
+ }
185
+
186
+ function concat(chunks) {
187
+ const all = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
188
+ let pos = 0;
189
+ for (const c of chunks) {
190
+ all.set(c, pos);
191
+ pos += c.length;
192
+ }
193
+ return all;
194
+ }
195
+
196
+ // Splits CGI output into headers and body. A "Status:" header sets the
197
+ // status; a Location with no Status is a redirect.
198
+ export function parseResponse(stdout) {
199
+ let end = -1;
200
+ let sep = 0;
201
+ for (let i = 0; i < stdout.length; i++) {
202
+ if (stdout[i] !== 10) continue;
203
+ if (stdout[i + 1] === 10) { end = i; sep = 2; break; }
204
+ if (stdout[i + 1] === 13 && stdout[i + 2] === 10) { end = i; sep = 3; break; }
205
+ }
206
+ if (end < 0) {
207
+ console.error("cgull: the program wrote no header block");
208
+ return new Response("Internal Server Error\n", { status: 500 });
209
+ }
210
+ const head = new TextDecoder().decode(stdout.subarray(0, end));
211
+ const headers = new Headers();
212
+ let status = 200;
213
+ let statusText = "";
214
+ for (const line of head.split(/\r?\n/)) {
215
+ const colon = line.indexOf(":");
216
+ if (colon < 0) continue;
217
+ const name = line.slice(0, colon).trim();
218
+ const value = line.slice(colon + 1).trim();
219
+ if (name.toLowerCase() === "status") {
220
+ status = parseInt(value, 10);
221
+ statusText = value.replace(/^\d+\s*/, "");
222
+ } else {
223
+ headers.append(name, value);
224
+ }
225
+ }
226
+ if (headers.has("location") && !/^status:/im.test(head)) status = 302;
227
+ const body = stdout.subarray(end + sep);
228
+ const nullBody = status === 204 || status === 304 || status < 200;
229
+ return new Response(nullBody ? null : body, { status, statusText, headers });
230
+ }
@@ -0,0 +1,11 @@
1
+ # {{NAME}}
2
+
3
+ A Cloudflare Worker in C, made with cgull. The app is `src/main.c`; the
4
+ API is in `node_modules/cgull/runtime/cgull.h`.
5
+
6
+ ```sh
7
+ npm install
8
+ npx cgull run -i /hello/you # one request, no server
9
+ npm run dev # http://localhost:8787
10
+ npm run deploy
11
+ ```
@@ -0,0 +1,3 @@
1
+ node_modules/
2
+ build/
3
+ .wrangler/
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "{{NAME}}",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "build": "cgull build",
7
+ "dev": "cgull dev",
8
+ "deploy": "cgull deploy"
9
+ },
10
+ "devDependencies": {
11
+ "create-cgull": "{{CGULL_DEP}}",
12
+ "wrangler": "^4.0.0"
13
+ }
14
+ }
@@ -0,0 +1,2 @@
1
+ body { font: 17px/1.5 system-ui, sans-serif; max-width: 36em; margin: 2em auto; padding: 0 1em; }
2
+ input, button { font: inherit; }
@@ -0,0 +1,49 @@
1
+ #include <cgull.h>
2
+ #include <time.h>
3
+
4
+ static void page_start(cg_res *res, const char *title) {
5
+ cg_printf(res,
6
+ "<!doctype html><meta name=viewport content=\"width=device-width\">"
7
+ "<link rel=stylesheet href=/style.css><title>%s</title>",
8
+ cg_esc(title));
9
+ }
10
+
11
+ static void index_page(cg_req *req, cg_res *res) {
12
+ page_start(res, "{{NAME}}");
13
+ cg_printf(res,
14
+ "<h1>Hello from C</h1>"
15
+ "<p>%s is a Cloudflare Worker written in C.</p>"
16
+ "<form method=post action=/greet>"
17
+ "<input name=name placeholder=\"Your name\"> <button>Greet me</button></form>"
18
+ "<ul><li><a href=/hello/world>/hello/:name</a></li>"
19
+ "<li><a href=\"/api/time?tz=UTC\">/api/time</a></li></ul>",
20
+ cg_esc(cg_env("SITE_NAME")));
21
+ }
22
+
23
+ static void hello(cg_req *req, cg_res *res) {
24
+ page_start(res, "Hello");
25
+ cg_printf(res, "<h1>Hello, %s!</h1><p><a href=/>Back</a></p>", cg_esc(cg_param(req, "name")));
26
+ }
27
+
28
+ // A form post, answered with a redirect so reloading doesn't resubmit.
29
+ static void greet(cg_req *req, cg_res *res) {
30
+ const char *name = cg_form(req, "name");
31
+ if (!name || !*name) {
32
+ cg_redirect(res, 303, "/");
33
+ return;
34
+ }
35
+ cg_redirect(res, 303, cg_sprintf("/hello/%s", cg_url_encode(name)));
36
+ }
37
+
38
+ static void api_time(cg_req *req, cg_res *res) {
39
+ cg_json(res, 200, cg_sprintf("{\"now\":%lld,\"tz\":%s}", (long long)time(NULL),
40
+ cg_json_str(cg_query(req, "tz"))));
41
+ }
42
+
43
+ int main(void) {
44
+ cg_get("/", index_page);
45
+ cg_get("/hello/:name", hello);
46
+ cg_post("/greet", greet);
47
+ cg_get("/api/time", api_time);
48
+ return cg_run();
49
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "{{NAME}}",
3
+ // build/worker.js is generated by `cgull build`, which runs before
4
+ // every dev reload and deploy.
5
+ "main": "build/worker.js",
6
+ "compatibility_date": "{{DATE}}",
7
+ "build": { "command": "npx cgull build", "watch_dir": "src" },
8
+ // Files in public/ are served directly; other paths reach the C code.
9
+ "assets": { "directory": "public" },
10
+ // Read in C with cg_env("SITE_NAME").
11
+ "vars": { "SITE_NAME": "{{NAME}}" }
12
+ }