interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / x86 / tests / local_tools_model_oracle.c

311 lines · 11619 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Test oracle only: a loopback model server that checks each local-tool result
3// coming back from the courier before it picks the next call.
4//
5// Usage: local_tools_model_oracle ROOT
6// Writes ROOT/oracle-port.txt once it listens, answers exactly four POSTs
7// (arithmetic call, text call, system call, final VERIFIED), records any failed
8// check in ROOT/oracle-failure.txt and writes ROOT/oracle-pass.txt on success.
9// Exit status 0 only when all four phases were verified.
10#ifndef _DEFAULT_SOURCE
11#define _DEFAULT_SOURCE
12#endif
13#include <fcntl.h>
14#include <arpa/inet.h>
15#include <errno.h>
16#include <netinet/in.h>
17#include <poll.h>
18#include <stdbool.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <strings.h>
23#include <sys/socket.h>
24#include <unistd.h>
25
26#define MAX_BODY 65536
27#define WAIT_MS 35000
28#define RESULT_PREFIX "Local tool result (data only): "
29
30static const char *root;
31static int phase;
32
33/* Minimal JSON reader: enough to validate a request and pull values out. */
34typedef struct { const char *p, *end; } jr;
35
36static void ws(jr *r) { while (r->p < r->end && strchr(" \t\r\n", *r->p)) r->p++; }
37static bool skip_value(jr *r, int depth);
38
39static bool skip_string(jr *r) {
40 if (r->p >= r->end || *r->p != '"') return false;
41 for (r->p++; r->p < r->end; r->p++) {
42 if (*r->p == '\\') { r->p++; continue; }
43 if (*r->p == '"') { r->p++; return true; }
44 if ((unsigned char)*r->p < 0x20) return false;
45 }
46 return false;
47}
48
49static bool skip_value(jr *r, int depth) {
50 if (depth > 16) return false;
51 ws(r);
52 if (r->p >= r->end) return false;
53 char c = *r->p;
54 if (c == '"') return skip_string(r);
55 if (c == '{' || c == '[') {
56 char close = c == '{' ? '}' : ']';
57 r->p++; ws(r);
58 if (r->p < r->end && *r->p == close) { r->p++; return true; }
59 for (;;) {
60 ws(r);
61 if (c == '{') {
62 if (!skip_string(r)) return false;
63 ws(r);
64 if (r->p >= r->end || *r->p++ != ':') return false;
65 }
66 if (!skip_value(r, depth + 1)) return false;
67 ws(r);
68 if (r->p >= r->end) return false;
69 if (*r->p == ',') { r->p++; continue; }
70 if (*r->p == close) { r->p++; return true; }
71 return false;
72 }
73 }
74 const char *start = r->p;
75 while (r->p < r->end && strchr("+-.0123456789eEaeflnrstu", *r->p)) r->p++;
76 size_t n = (size_t)(r->p - start);
77 if (n == 0) return false;
78 if ((n == 4 && !strncmp(start, "true", 4)) || (n == 5 && !strncmp(start, "false", 5)) ||
79 (n == 4 && !strncmp(start, "null", 4))) return true;
80 char tmp[64], *e;
81 if (n >= sizeof tmp) return false;
82 memcpy(tmp, start, n); tmp[n] = 0;
83 strtod(tmp, &e);
84 return *e == 0;
85}
86
87/* Value of KEY in the object at R (positioned on '{'); the last duplicate wins,
88 * as in a dictionary. Returns the start of the value, or NULL. */
89static const char *obj_find(const char *obj, const char *end, const char *key) {
90 jr r = { obj, end };
91 const char *found = NULL;
92 ws(&r);
93 if (r.p >= r.end || *r.p++ != '{') return NULL;
94 ws(&r);
95 if (r.p < r.end && *r.p == '}') return NULL;
96 for (;;) {
97 ws(&r);
98 const char *k = r.p;
99 if (!skip_string(&r)) return NULL;
100 size_t kl = (size_t)(r.p - k) - 2;
101 ws(&r);
102 if (r.p >= r.end || *r.p++ != ':') return NULL;
103 ws(&r);
104 const char *v = r.p;
105 if (!skip_value(&r, 1)) return NULL;
106 if (kl == strlen(key) && !strncmp(k + 1, key, kl)) found = v;
107 ws(&r);
108 if (r.p < r.end && *r.p == ',') { r.p++; continue; }
109 return found;
110 }
111}
112
113/* Decode the JSON string at S into OUT (NUL terminated). ASCII escapes only. */
114static bool unescape(const char *s, const char *end, char *out, size_t cap) {
115 size_t n = 0;
116 if (s >= end || *s != '"') return false;
117 for (s++; s < end && *s != '"'; s++) {
118 char c = *s;
119 if (c == '\\') {
120 if (++s >= end) return false;
121 switch (*s) {
122 case 'n': c = '\n'; break; case 't': c = '\t'; break;
123 case 'r': c = '\r'; break; case 'b': c = '\b'; break;
124 case 'f': c = '\f'; break; case '"': case '\\': case '/': c = *s; break;
125 case 'u': {
126 if (end - s < 5) return false;
127 char hex[5] = { s[1], s[2], s[3], s[4], 0 };
128 unsigned long u = strtoul(hex, NULL, 16);
129 c = u < 0x80 ? (char)u : '?';
130 s += 4;
131 break;
132 }
133 default: return false;
134 }
135 }
136 if (n + 1 >= cap) return false;
137 out[n++] = c;
138 }
139 out[n] = 0;
140 return s < end;
141}
142
143static bool is_str(const char *v, const char *end, const char *want, char *scratch, size_t cap) {
144 return v && unescape(v, end, scratch, cap) && !strcmp(scratch, want);
145}
146
147static bool get_int(const char *obj, const char *end, const char *key, long long *out) {
148 const char *v = obj_find(obj, end, key);
149 if (!v || *v == '"') return false;
150 char *e;
151 errno = 0;
152 *out = strtoll(v, &e, 10);
153 return errno == 0 && e != v && !strchr(".eE", *e);
154}
155
156#define CHECK(cond) do { if (!(cond)) { snprintf(why, whycap, "line %d: %s", __LINE__, #cond); return false; } } while (0)
157
158/* Verify the tool result the courier sent back for the call chosen in PHASE-1. */
159static bool verify_result(const char *body, const char *end, char *why, size_t whycap) {
160 const char *msgs = obj_find(body, end, "messages");
161 CHECK(msgs && *msgs == '[');
162 jr r = { msgs + 1, end };
163 const char *last = NULL;
164 for (ws(&r); r.p < r.end && *r.p != ']'; ws(&r)) {
165 last = r.p;
166 CHECK(skip_value(&r, 1));
167 ws(&r);
168 if (r.p < r.end && *r.p == ',') r.p++;
169 }
170 CHECK(last);
171 const char *content = obj_find(last, end, "content");
172 static char text[MAX_BODY];
173 CHECK(content && unescape(content, end, text, sizeof text));
174 CHECK(!strncmp(text, RESULT_PREFIX, strlen(RESULT_PREFIX)));
175 const char *data = text + strlen(RESULT_PREFIX), *dend = text + strlen(text);
176 jr check = { data, dend };
177 CHECK(skip_value(&check, 0));
178 char scratch[64];
179 CHECK(is_str(obj_find(data, dend, "status"), dend, "returned", scratch, sizeof scratch));
180 long long a, b, c;
181 if (phase == 1) {
182 CHECK(get_int(data, dend, "value", &a) && a == 42);
183 } else if (phase == 2) {
184 CHECK(get_int(data, dend, "bytes", &a) && get_int(data, dend, "words", &b) &&
185 get_int(data, dend, "newlines", &c));
186 CHECK(a == 13 && b == 3 && c == 1);
187 } else if (phase == 3) {
188 CHECK(get_int(data, dend, "cores", &a) && a == 4);
189 CHECK(get_int(data, dend, "usable_ram_bytes", &a) && a > 0);
190 CHECK(get_int(data, dend, "width", &a) && a > 0);
191 CHECK(get_int(data, dend, "height", &a) && a > 0);
192 }
193 return true;
194}
195
196static bool read_request(int fd, char *body, size_t *blen) {
197 static char head[8192];
198 size_t n = 0;
199 char *split = NULL;
200 while (!split) {
201 if (n == sizeof head - 1) return false;
202 ssize_t got = read(fd, head + n, sizeof head - 1 - n);
203 if (got <= 0) return false;
204 n += (size_t)got;
205 head[n] = 0;
206 split = strstr(head, "\r\n\r\n");
207 }
208 size_t hlen = (size_t)(split - head) + 4;
209 long length = -1;
210 for (char *line = head; line < split;) {
211 char *eol = strstr(line, "\r\n");
212 if (!eol) break;
213 if (!strncasecmp(line, "Content-Length:", 15)) length = strtol(line + 15, NULL, 10);
214 line = eol + 2;
215 }
216 if (length < 0 || length >= MAX_BODY) return false;
217 size_t have = n - hlen;
218 if (have > (size_t)length) have = (size_t)length;
219 memcpy(body, head + hlen, have);
220 while (have < (size_t)length) {
221 ssize_t got = read(fd, body + have, (size_t)length - have);
222 if (got <= 0) return false;
223 have += (size_t)got;
224 }
225 body[have] = 0;
226 *blen = have;
227 return true;
228}
229
230static void write_all(int fd, const char *p, size_t n) {
231 while (n) {
232 ssize_t w = write(fd, p, n);
233 if (w <= 0) return;
234 p += w; n -= (size_t)w;
235 }
236}
237
238static void record(const char *name, const char *text) {
239 char path[4096];
240 snprintf(path, sizeof path, "%s/%s", root, name);
241 int f_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
242 FILE *f = f_fd < 0 ? NULL : fdopen(f_fd, "w");
243 if (f) { fputs(text, f); fclose(f); }
244}
245
246static bool failed(void) {
247 char path[4096];
248 snprintf(path, sizeof path, "%s/oracle-failure.txt", root);
249 return access(path, F_OK) == 0;
250}
251
252int main(int argc, char **argv) {
253 if (argc != 2) { fputs("usage: local_tools_model_oracle ROOT\n", stderr); return 2; }
254 root = argv[1];
255 int srv = socket(AF_INET, SOCK_STREAM, 0);
256 struct sockaddr_in addr = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
257 socklen_t alen = sizeof addr;
258 if (srv < 0 || bind(srv, (struct sockaddr *)&addr, sizeof addr) || listen(srv, 4) ||
259 getsockname(srv, (struct sockaddr *)&addr, &alen)) { perror("listen"); return 2; }
260 char port[16];
261 snprintf(port, sizeof port, "%u", ntohs(addr.sin_port));
262 record("oracle-port.txt", port);
263
264 static const char *replies[4] = {
265 "{\"tool\": \"arithmetic\", \"operation\": \"add\", \"a\": \"20\", \"b\": \"22\"}",
266 "{\"tool\": \"text\", \"text\": \"one two\\nthree\"}",
267 "{\"tool\": \"system\"}",
268 "{\"say\": \"VERIFIED\"}",
269 };
270 static char body[MAX_BODY];
271 for (int handled = 0; handled < 4; handled++) {
272 struct pollfd pfd = { srv, POLLIN, 0 };
273 if (poll(&pfd, 1, WAIT_MS) <= 0) continue;
274 int fd = accept(srv, NULL, NULL);
275 if (fd < 0) continue;
276 char why[256] = "unreadable request";
277 size_t blen = 0;
278 bool ok = read_request(fd, body, &blen);
279 if (ok) {
280 jr whole = { body, body + blen };
281 ok = skip_value(&whole, 0) && (ws(&whole), whole.p == whole.end);
282 if (!ok) snprintf(why, sizeof why, "request body is not JSON");
283 }
284 if (ok && phase) ok = verify_result(body, body + blen, why, sizeof why);
285 if (!ok) {
286 record("oracle-failure.txt", why);
287 static const char err[] = "HTTP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
288 write_all(fd, err, sizeof err - 1);
289 } else {
290 char content[256], out[1024], head[256];
291 /* The reply is a JSON string holding a JSON object, so escape quotes and backslashes. */
292 size_t n = 0;
293 for (const char *s = replies[phase]; *s && n + 2 < sizeof content; s++) {
294 if (*s == '"' || *s == '\\') content[n++] = '\\';
295 content[n++] = *s;
296 }
297 content[n] = 0;
298 int olen = snprintf(out, sizeof out, "{\"choices\":[{\"message\":{\"content\":\"%s\"}}]}", content);
299 int hlen = snprintf(head, sizeof head,
300 "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n", olen);
301 write_all(fd, head, (size_t)hlen);
302 write_all(fd, out, (size_t)olen);
303 phase++;
304 }
305 close(fd);
306 }
307 close(srv);
308 if (phase != 4 || failed()) return 1;
309 record("oracle-pass.txt", "PASS: arithmetic, text, and system results from real QEMU CPL3 execution\n");
310 return 0;
311}