scorpiox-bot-plugin-tetris-3d
←plugin_tetris_3d.cc
458 lines · 13 KBHEADBlameDownload
1/*
2 * plugin_tetris_3d - SCORPIOX BOT open-source 3D block game (clean room)
3 *
4 * A single dependency-free C99 binary that serves THREE modes:
5 * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6 * 2. ?action=scores | ?action=save_score | ?format=json -> JSON node API
7 * 3. GET (default) -> self-contained HTML game UI
8 *
9 * The game itself is a 3D block-stacking puzzle rendered by a small software
10 * 3D projector onto a 2D canvas. There is no WebGL requirement, no CDN, no
11 * third-party JavaScript and no runtime library beyond libc, so the UI works
12 * offline on every node and produces zero network requests.
13 *
14 * High scores are stored locally in a small JSON file inside the node plugin
15 * directory:
16 * POSIX ~/.scorpiox/plugins/.tetris_scores.json
17 * ($BOT_PLUGIN_DIR when set, /workspace/.scorpiox/plugins on BotCloud)
18 * Windows %LOCALAPPDATA%\scorpiox\plugins\.tetris_scores.json
19 * override SX_TETRIS_SCORES (full path, used by the test suite)
20 *
21 * Nothing else is read or written. There is no parameter anywhere in this
22 * file that can point it at another host.
23 *
24 * MIT License. Copyright (c) 2026 SCORPIOX INC.
25 */
26
27#if defined(_WIN32) && !defined(_WIN32_WINNT)
28# define _WIN32_WINNT 0x0601
29#endif
30
31#if !defined(_WIN32)
32# define _POSIX_C_SOURCE 200809L
33# define _DEFAULT_SOURCE 1
34# if defined(__APPLE__)
35# define _DARWIN_C_SOURCE 1
36# endif
37#endif
38
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <ctype.h>
43#include <time.h>
44#include <errno.h>
45
46#if defined(_WIN32)
47# define WIN32_LEAN_AND_MEAN
48# include <windows.h>
49# include <direct.h>
50# define SX_SEP '\\'
51#else
52# include <unistd.h>
53# include <sys/stat.h>
54# include <sys/types.h>
55# define SX_SEP '/'
56#endif
57
58#define PLUGIN_SLUG "tetris-3d"
59#define PLUGIN_ID "plugin_tetris_3d"
60#define PLUGIN_NAME "tetris"
61#define PLUGIN_DESC "3D block game"
62#define PLUGIN_VER "1.0.1"
63
64#define MAX_SCORES 10
65#define PATH_SZ 1024
66#define BODY_SZ 2048
67
68/* ------------------------------------------------------------------ */
69/* Small string helpers */
70/* ------------------------------------------------------------------ */
71
72static void str_copy(char *dst, size_t sz, const char *src)
73{
74 size_t i = 0;
75 if (!dst || sz == 0) return;
76 if (!src) { dst[0] = '\0'; return; }
77 while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
78 dst[i] = '\0';
79}
80
81static void url_decode(char *s)
82{
83 char *o = s;
84 if (!s) return;
85 while (*s) {
86 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
87 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
88 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
89 *o++ = (char)((hi << 4) | lo);
90 s += 3;
91 } else if (*s == '+') {
92 *o++ = ' ';
93 s++;
94 } else {
95 *o++ = *s++;
96 }
97 }
98 *o = '\0';
99}
100
101/* Read one query/body parameter, percent-decoded. Returns 1 when present. */
102static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
103{
104 size_t klen;
105 const char *p;
106
107 if (!out || outsz == 0) return 0;
108 out[0] = '\0';
109 if (!qs || !key) return 0;
110 klen = strlen(key);
111
112 for (p = qs; *p; ) {
113 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
114 const char *v = p + klen + 1;
115 size_t i = 0;
116 while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
117 out[i] = '\0';
118 url_decode(out);
119 return 1;
120 }
121 p = strchr(p, '&');
122 if (!p) break;
123 p++;
124 }
125 return 0;
126}
127
128/* ------------------------------------------------------------------ */
129/* Node security */
130/* ------------------------------------------------------------------ */
131
132/* Accept X-Bot-Password, Authorization: Bearer <pwd> or ?pwd=. The bot web
133 * frontend appends ?pwd= for iframes, so all three forms must work. When
134 * BOT_PASSWORD is unset the node is unauthenticated by configuration and the
135 * check is a no-op. --meta stays unauthenticated so discovery works. */
136static void require_node_auth(void)
137{
138 const char *np = getenv("BOT_PASSWORD");
139 const char *xp;
140 const char *auth;
141
142 if (!np || !*np) return;
143
144 xp = getenv("HTTP_X_BOT_PASSWORD");
145 if (xp && strcmp(xp, np) == 0) return;
146
147 auth = getenv("HTTP_AUTHORIZATION");
148 if (auth) {
149 while (*auth == ' ') auth++;
150 if (strncmp(auth, "Bearer ", 7) == 0) {
151 auth += 7;
152 while (*auth == ' ') auth++;
153 if (strcmp(auth, np) == 0) return;
154 }
155 }
156
157 {
158 char qpwd[256];
159 const char *qs = getenv("QUERY_STRING");
160 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return;
161 }
162
163 fputs("Status: 401 Unauthorized\r\n"
164 "Content-Type: application/json; charset=utf-8\r\n"
165 "Cache-Control: no-store\r\n\r\n"
166 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
167 exit(0);
168}
169
170/* ------------------------------------------------------------------ */
171/* Local high-score store */
172/* ------------------------------------------------------------------ */
173
174typedef struct {
175 long v[MAX_SCORES];
176 int n;
177} Scores;
178
179static void path_join(char *dst, size_t sz, const char *a, const char *b)
180{
181 if (!dst || sz == 0) return;
182 dst[0] = '\0';
183 if (!a || !b) return;
184 if (!*a) { str_copy(dst, sz, b); return; }
185 str_copy(dst, sz, a);
186 {
187 size_t l = strlen(dst);
188 if (l + 1 < sz) { dst[l] = SX_SEP; dst[l + 1] = '\0'; }
189 }
190 {
191 size_t l = strlen(dst);
192 size_t i = 0;
193 while (l + i + 1 < sz && b[i]) { dst[l + i] = b[i]; i++; }
194 dst[l + i] = '\0';
195 }
196}
197
198static void mkdir_one(const char *p)
199{
200#if defined(_WIN32)
201 _mkdir(p);
202#else
203 mkdir(p, 0700);
204#endif
205}
206
207/* Resolve <plugin dir>/.tetris_scores.json */
208static int scores_path(char *out, size_t sz)
209{
210 const char *env = getenv("SX_TETRIS_SCORES");
211 char dir[PATH_SZ];
212 const char *base;
213
214 if (env && *env) { str_copy(out, sz, env); return 1; }
215
216 base = getenv("BOT_PLUGIN_DIR");
217 if (base && *base) {
218 mkdir_one(base);
219 dir[0] = '\0';
220 str_copy(dir, sizeof dir, base);
221 } else {
222#if defined(_WIN32)
223 const char *la = getenv("LOCALAPPDATA");
224 if (la && *la) {
225 path_join(dir, sizeof dir, la, "scorpiox");
226 } else {
227 const char *up = getenv("USERPROFILE");
228 if (up && *up) {
229 path_join(dir, sizeof dir, up, ".scorpiox");
230 } else {
231 str_copy(dir, sizeof dir, ".");
232 }
233 }
234 mkdir_one(dir);
235 {
236 char tmp[PATH_SZ];
237 path_join(tmp, sizeof tmp, dir, "plugins");
238 str_copy(dir, sizeof dir, tmp);
239 mkdir_one(dir);
240 }
241#else
242 const char *home = getenv("HOME");
243# if defined(__APPLE__)
244 if (access("/workspace", W_OK) == 0) {
245 path_join(dir, sizeof dir, "/workspace/.scorpiox", "plugins");
246 } else
247# endif
248 if (home && *home) {
249 path_join(dir, sizeof dir, home, ".scorpiox");
250 mkdir_one(dir);
251 {
252 char tmp[PATH_SZ];
253 path_join(tmp, sizeof tmp, dir, "plugins");
254 str_copy(dir, sizeof dir, tmp);
255 }
256 mkdir_one(dir);
257 } else {
258 str_copy(dir, sizeof dir, ".");
259 }
260#endif
261 }
262 path_join(out, sz, dir, ".tetris_scores.json");
263 return 1;
264}
265
266static void scores_load(Scores *s)
267{
268 char path[PATH_SZ];
269 FILE *fp;
270 char buf[BODY_SZ];
271 size_t got;
272
273 memset(s, 0, sizeof *s);
274 if (!scores_path(path, sizeof path)) return;
275
276 fp = fopen(path, "rb");
277 if (!fp) return;
278 got = fread(buf, 1, sizeof buf - 1, fp);
279 fclose(fp);
280 buf[got] = '\0';
281
282 {
283 const char *p = strstr(buf, "\"scores\"");
284 if (!p) p = buf;
285 p = strchr(p, '[');
286 if (!p) return;
287 p++;
288 while (*p && s->n < MAX_SCORES) {
289 while (*p && !isdigit((unsigned char)*p) && *p != ']') p++;
290 if (!*p || *p == ']') break;
291 {
292 long v = strtol(p, NULL, 10);
293 if (v > 0) s->v[s->n++] = v;
294 while (*p && *p != ',' && *p != ']') p++;
295 if (*p == ',') p++;
296 }
297 }
298 }
299}
300
301static int scores_save(const Scores *s)
302{
303 char path[PATH_SZ];
304 FILE *fp;
305 int i;
306
307 if (!scores_path(path, sizeof path)) return 0;
308 fp = fopen(path, "wb");
309 if (!fp) return 0;
310 fputs("{\"scores\":[", fp);
311 for (i = 0; i < s->n; i++) {
312 if (i) fputc(',', fp);
313 fprintf(fp, "%ld", s->v[i]);
314 }
315 fputs("]}\n", fp);
316 fclose(fp);
317 return 1;
318}
319
320static void scores_add(Scores *s, long val)
321{
322 int i, pos;
323 if (val <= 0) return;
324 if (s->n < MAX_SCORES) {
325 pos = s->n++;
326 } else {
327 if (val <= s->v[MAX_SCORES - 1]) return;
328 pos = MAX_SCORES - 1;
329 }
330 for (i = pos; i > 0 && s->v[i - 1] < val; i--) s->v[i] = s->v[i - 1];
331 s->v[i] = val;
332}
333
334static void scores_print_json(const Scores *s)
335{
336 int i;
337 printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"highscore\":%ld,\"scores\":[",
338 PLUGIN_ID, PLUGIN_VER, s->n ? s->v[0] : 0L);
339 for (i = 0; i < s->n; i++) {
340 if (i) fputc(',', stdout);
341 printf("%ld", s->v[i]);
342 }
343 fputs("]}\n", stdout);
344}
345
346/* Read the POST body when the frontend actually sent one. Guarded on
347 * CONTENT_LENGTH so an inherited empty stdin never blocks the process. */
348static int read_body(char *out, size_t sz)
349{
350 const char *cl = getenv("CONTENT_LENGTH");
351 long len;
352 size_t got;
353
354 if (!out || sz == 0) return 0;
355 out[0] = '\0';
356 if (!cl || !*cl) return 0;
357 len = strtol(cl, NULL, 10);
358 if (len <= 0) return 0;
359 if ((size_t)len > sz - 1) len = (long)sz - 1;
360 got = fread(out, 1, (size_t)len, stdin);
361 out[got] = '\0';
362 return (int)got;
363}
364
365/* ------------------------------------------------------------------ */
366/* Modes */
367/* ------------------------------------------------------------------ */
368
369#include "ui_html.h"
370
371static const char *method(void)
372{
373 const char *m = getenv("REQUEST_METHOD");
374 return (m && *m) ? m : "GET";
375}
376
377int main(int argc, char **argv)
378{
379 const char *qs;
380 char action[64];
381 char valstr[64];
382 char body[BODY_SZ];
383 Scores scores;
384
385 /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */
386 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
387 printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC);
388 return 0;
389 }
390 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
391 printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
392 return 0;
393 }
394
395 require_node_auth();
396 qs = getenv("QUERY_STRING");
397 if (!qs) qs = "";
398
399 action[0] = '\0';
400 valstr[0] = '\0';
401 get_query_val(qs, "action", action, sizeof action);
402
403 /* 2. JSON API: ?action=..., ?format=json, or any POST with a body */
404 if (action[0] || strstr(qs, "format=json") || strncmp(method(), "POST", 4) == 0) {
405 char format[32];
406 format[0] = '\0';
407 get_query_val(qs, "format", format, sizeof format);
408
409 if (!action[0] && strncmp(method(), "POST", 4) == 0) str_copy(action, sizeof action, "save_score");
410 if (!action[0]) str_copy(action, sizeof action, "scores");
411
412 read_body(body, sizeof body);
413 if (!get_query_val(qs, "val", valstr, sizeof valstr) && body[0]) {
414 if (!get_query_val(body, "val", valstr, sizeof valstr))
415 (void)get_query_val(body, "score", valstr, sizeof valstr);
416 }
417 if (!valstr[0]) get_query_val(qs, "score", valstr, sizeof valstr);
418 if (!valstr[0] && body[0]) {
419 /* a bare numeric body is accepted too */
420 const char *p = body;
421 while (*p && !isdigit((unsigned char)*p) && *p != '-') p++;
422 if (*p) str_copy(valstr, sizeof valstr, p);
423 }
424
425 scores_load(&scores);
426
427 fputs("Content-Type: application/json; charset=utf-8\r\n"
428 "Cache-Control: no-store\r\n\r\n", stdout);
429
430 if (strcmp(action, "save_score") == 0) {
431 long v = strtol(valstr, NULL, 10);
432 if (v > 0) {
433 scores_add(&scores, v);
434 if (!scores_save(&scores))
435 printf("{\"ok\":false,\"error\":\"score_store_unwritable\",\"highscore\":%ld}\n",
436 scores.n ? scores.v[0] : 0L);
437 else
438 scores_print_json(&scores);
439 } else {
440 printf("{\"ok\":false,\"error\":\"invalid_score\"}\n");
441 }
442 return 0;
443 }
444 if (strcmp(action, "scores") == 0 || strcmp(action, "highscore") == 0 ||
445 strcmp(action, "leaderboard") == 0) {
446 scores_print_json(&scores);
447 return 0;
448 }
449 printf("{\"ok\":false,\"error\":\"unknown_action\"}\n");
450 return 0;
451 }
452
453 /* 3. HTML UI */
454 fputs("Content-Type: text/html; charset=utf-8\r\n"
455 "Cache-Control: no-store\r\n\r\n", stdout);
456 fputs(UI_HTML, stdout);
457 return 0;
458}