/* (Triforce) The control bridge: HOS_CONTROL= lets a tool on the same PC (a test, a script, a coding agent) drive the running game and read its state over a local socket, instead of a file the game polls (HOS_INPUT_LIVE) and its log scraped for the frame rate and draw counts. This comment and the commands below are the protocol; scripts/triforce_ctl.py is a client (python -I scripts/triforce_ctl.py --help). Off unless HOS_CONTROL is set: without it nothing listens and every hook returns at once. Local only, this user only. Linux: a Unix domain socket at that path, made 0600 (the umask around bind too), in a folder that must be this user's and writable by no one else, never over an existing file that is not a socket, and a client of another user is turned away (SO_PEERCRED). Windows: a named pipe (\\.\pipe\; a name without the prefix gets it), PIPE_REJECT_REMOTE_CLIENTS (no client from another PC), FILE_FLAG_FIRST_PIPE_INSTANCE, its DACL the current user's alone (and the game's own AppContainer's when it runs in one). There is no TCP and nothing is sent off the PC. The guest's memory is read or written only with a second opt-in, HOS_CONTROL_MEM (ro, rw); anything else leaves it off. Newline-delimited JSON: one request object a line ({"id": ..., "cmd": "status", ...}), one reply a line with the id given back, and the current frame (the game's presents so far) in every reply. A few clients at a time. A thread of its own does the socket's I/O and parses; what touches the game is applied where the game does it: presses in the controller's read (nn_hid.c read_input, hos_control_input), shots at a present on the renderer's thread (gpu/vk/vk_replay.cpp shot_ask), the Insert menu's settings through its own setter. The game never waits for the bridge: the controller's read takes one short lock that the bridge never holds over I/O. Commands: status, press, stick, sequence, release, shot, wait, option_get, option_set, saves, teleport and age (OoT), subscribe, unsubscribe, quit, relaunch, and guest memory (mem_read, mem_read_many, mem_write) when HOS_CONTROL_MEM allows it. Inputs are timed in frames, from the first controller read after the request. The state (intro, menu, loading, play) is a guess from the draws a frame, as test scripts made it from the log: ~2 draws at the intro, 15-70 in menus, ~5 while loading, hundreds in play. tests/control_test.c builds this file with a fake game (HOS_CONTROL_NO_GAME) and drives it over a real socket. */ #include "control.h" #include #include #include #include #include #include #include #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include #include #else #include #include #include #include #include #include #include #include #include #include #endif #define CTL_LINE_MAX 65536 /* a request longer than this is refused (too_long) */ #define CTL_OUT_MAX (8u << 20) /* a client that reads nothing while this much waits for it is let go */ #define CTL_CONNS HOS_CONTROL_OOT_CLIENTS #define CTL_PENDING 64 #define CTL_INPUTS 256 #define CTL_LOG_RING 256 #define CTL_NODES 1024 #define CTL_MEM 8 #define CTL_MEM_RANGES 64 #define CTL_MEM_CAP (1u << 20) /* 1 MB a request */ #define CTL_TICK_MS 4 volatile int hos_control_on; /* ---- the platform: a lock, a thread, a clock ---- */ #ifdef _WIN32 typedef SRWLOCK ctl_mutex; #define CTL_MUTEX_INIT SRWLOCK_INIT static void ctl_lock(ctl_mutex *m) { AcquireSRWLockExclusive(m); } static void ctl_unlock(ctl_mutex *m) { ReleaseSRWLockExclusive(m); } static int64_t ctl_now_ns(void) { static LARGE_INTEGER f; LARGE_INTEGER c; if (!f.QuadPart) QueryPerformanceFrequency(&f); QueryPerformanceCounter(&c); return (int64_t)((double)c.QuadPart * 1e9 / (double)f.QuadPart); } #else typedef pthread_mutex_t ctl_mutex; #define CTL_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER static void ctl_lock(ctl_mutex *m) { pthread_mutex_lock(m); } static void ctl_unlock(ctl_mutex *m) { pthread_mutex_unlock(m); } static int64_t ctl_now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (int64_t)t.tv_sec * 1000000000 + t.tv_nsec; } #endif /* ---- a growing text buffer, and JSON written into it ---- */ typedef struct { char *p; size_t n, cap; int failed; } Buf; static void buf_put(Buf *b, const char *s, size_t n) { if (b->failed) return; if (b->n + n + 1 > b->cap) { size_t cap = b->cap ? b->cap : 256; while (b->n + n + 1 > cap) cap *= 2; char *p = (char *)realloc(b->p, cap); if (!p) { b->failed = 1; return; } b->p = p, b->cap = cap; } memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; } static void buf_puts(Buf *b, const char *s) { buf_put(b, s, strlen(s)); } static void buf_printf(Buf *b, const char *fmt, ...) { char tmp[512]; va_list ap; va_start(ap, fmt); const int n = vsnprintf(tmp, sizeof tmp, fmt, ap); va_end(ap); if (n > 0) buf_put(b, tmp, (size_t)n < sizeof tmp ? (size_t)n : sizeof tmp - 1); } static void buf_str(Buf *b, const char *s) { /* a JSON string */ buf_put(b, "\"", 1); for (const unsigned char *q = (const unsigned char *)s; *q; q++) { if (*q == '"' || *q == '\\') { char e[2] = {'\\', (char)*q}; buf_put(b, e, 2); } else if (*q == '\n') buf_put(b, "\\n", 2); else if (*q == '\r') buf_put(b, "\\r", 2); else if (*q == '\t') buf_put(b, "\\t", 2); else if (*q < 0x20) buf_printf(b, "\\u%04x", *q); else buf_put(b, (const char *)q, 1); } buf_put(b, "\"", 1); } static void buf_free(Buf *b) { free(b->p); memset(b, 0, sizeof *b); } /* ---- JSON read: a request parsed into nodes; strings decoded into a copy of the line ---- */ enum { J_NULL, J_FALSE, J_TRUE, J_NUM, J_STR, J_ARR, J_OBJ }; typedef struct { int type; const char *key; const char *s; double num; int first, next; } JNode; typedef struct { JNode n[CTL_NODES]; int count; const char *p, *end; char *out; /* the decoded strings (never longer than the text they come from) */ const char *err; } JDoc; static void j_space(JDoc *d) { while (d->p < d->end && (*d->p == ' ' || *d->p == '\t' || *d->p == '\r' || *d->p == '\n')) d->p++; } static const char *j_string(JDoc *d) { /* at the opening quote: the decoded string, or NULL */ char *start = d->out; d->p++; while (d->p < d->end && *d->p != '"') { unsigned char c = (unsigned char)*d->p++; if (c < 0x20) return d->err = "a control character in a string", NULL; if (c != '\\') { *d->out++ = (char)c; continue; } if (d->p >= d->end) break; c = (unsigned char)*d->p++; switch (c) { case '"': case '\\': case '/': *d->out++ = (char)c; break; case 'b': *d->out++ = '\b'; break; case 'f': *d->out++ = '\f'; break; case 'n': *d->out++ = '\n'; break; case 'r': *d->out++ = '\r'; break; case 't': *d->out++ = '\t'; break; case 'u': { if (d->end - d->p < 4) return d->err = "a short \\u escape", NULL; unsigned v = 0; for (int i = 0; i < 4; i++) { const char h = *d->p++; v = v * 16 + (unsigned)(h >= '0' && h <= '9' ? h - '0' : h >= 'a' && h <= 'f' ? h - 'a' + 10 : h >= 'A' && h <= 'F' ? h - 'A' + 10 : 99); if (v > 0xFFFF) return d->err = "a bad \\u escape", NULL; } /* (UTF-8; a surrogate half stays as it is written, three bytes: the bridge has no use for such names) */ if (v == 0) return d->err = "a NUL in a string", NULL; if (v < 0x80) *d->out++ = (char)v; else if (v < 0x800) *d->out++ = (char)(0xC0 | v >> 6), *d->out++ = (char)(0x80 | (v & 0x3F)); else *d->out++ = (char)(0xE0 | v >> 12), *d->out++ = (char)(0x80 | (v >> 6 & 0x3F)), *d->out++ = (char)(0x80 | (v & 0x3F)); break; } default: return d->err = "a bad escape in a string", NULL; } } if (d->p >= d->end) return d->err = "a string without its end", NULL; d->p++; *d->out++ = 0; return start; } static int j_value(JDoc *d, int depth) { j_space(d); if (d->p >= d->end) return d->err = "the text ends early", -1; if (depth > 32) return d->err = "nested too deep", -1; if (d->count >= CTL_NODES) return d->err = "too many values", -1; const int at = d->count++; JNode *n = &d->n[at]; memset(n, 0, sizeof *n); n->first = n->next = -1; const char c = *d->p; if (c == '{' || c == '[') { n->type = c == '{' ? J_OBJ : J_ARR; d->p++; j_space(d); int last = -1; if (d->p < d->end && *d->p == (c == '{' ? '}' : ']')) { d->p++; return at; } for (;;) { const char *key = NULL; if (c == '{') { j_space(d); if (d->p >= d->end || *d->p != '"') return d->err = "an object key is not a string", -1; if (!(key = j_string(d))) return -1; j_space(d); if (d->p >= d->end || *d->p != ':') return d->err = "no ':' after a key", -1; d->p++; } const int v = j_value(d, depth + 1); if (v < 0) return -1; d->n[v].key = key; if (last < 0) d->n[at].first = v; else d->n[last].next = v; last = v; j_space(d); if (d->p < d->end && *d->p == ',') { d->p++; continue; } if (d->p < d->end && *d->p == (c == '{' ? '}' : ']')) { d->p++; return at; } return d->err = c == '{' ? "no ',' or '}' in an object" : "no ',' or ']' in an array", -1; } } if (c == '"') { n->type = J_STR; return (n->s = j_string(d)) ? at : -1; } if (c == '-' || (c >= '0' && c <= '9')) { char tmp[64]; size_t len = 0; while (d->p + len < d->end && len < sizeof tmp - 1 && strchr("+-.eE0123456789", d->p[len])) len++; memcpy(tmp, d->p, len); tmp[len] = 0; char *e; n->num = strtod(tmp, &e); if (e != tmp + len || !isfinite(n->num)) return d->err = "a bad number", -1; n->type = J_NUM; d->p += len; return at; } static const struct { const char *word; int type; } words[] = {{"true", J_TRUE}, {"false", J_FALSE}, {"null", J_NULL}}; for (int i = 0; i < 3; i++) { const size_t len = strlen(words[i].word); if ((size_t)(d->end - d->p) >= len && !memcmp(d->p, words[i].word, len)) { n->type = words[i].type; d->p += len; return at; } } return d->err = "not JSON", -1; } /* The line parsed into d (out: a buffer at least as long as the line). The root, or -1 with d->err */ static int j_parse(JDoc *d, const char *text, size_t len, char *out) { d->count = 0, d->p = text, d->end = text + len, d->out = out, d->err = NULL; const int root = j_value(d, 0); if (root < 0) return -1; j_space(d); if (d->p != d->end) return d->err = "text after the value", -1; return root; } static const JNode *j_get(const JDoc *d, int obj, const char *key) { if (obj < 0 || d->n[obj].type != J_OBJ) return NULL; for (int i = d->n[obj].first; i >= 0; i = d->n[i].next) if (!strcmp(d->n[i].key, key)) return &d->n[i]; return NULL; } static int j_index(const JDoc *d, const JNode *n) { return (int)(n - d->n); } /* a value written again as JSON (the request's id, given back as it came) */ static void j_write(Buf *b, const JDoc *d, int i) { const JNode *n = &d->n[i]; switch (n->type) { case J_NULL: buf_puts(b, "null"); break; case J_FALSE: buf_puts(b, "false"); break; case J_TRUE: buf_puts(b, "true"); break; case J_NUM: if (n->num == floor(n->num) && fabs(n->num) < 9e15) buf_printf(b, "%lld", (long long)n->num); else buf_printf(b, "%.17g", n->num); break; case J_STR: buf_str(b, n->s); break; default: { buf_puts(b, n->type == J_OBJ ? "{" : "["); for (int k = n->first; k >= 0; k = d->n[k].next) { if (k != n->first) buf_puts(b, ","); if (n->type == J_OBJ) buf_str(b, d->n[k].key), buf_puts(b, ":"); j_write(b, d, k); } buf_puts(b, n->type == J_OBJ ? "}" : "]"); } } } /* ---- the bridge's state ---- */ typedef struct Conn { int used, gen; #ifdef _WIN32 HANDLE pipe; OVERLAPPED rov; char rbuf[4096]; int reading; #else int fd; #endif char *in; size_t in_n; int discarding; /* (the rest of a line that was too long) */ Buf out; int closing; int eof; /* (the client shut its sending side: no more requests; the connection lasts until its replies are out) */ /* subscribe */ int sub_on, sub_present, sub_state, sub_log, sub_map, sub_oot; int64_t sub_every, sub_next; char sub_id[256], sub_filter[256]; unsigned log_seen; /* (the log ring's count it has seen) */ } Conn; enum { P_INPUT = 1, P_WAIT, P_SHOT, P_MEM, P_TELEPORT, P_STATUS }; enum { W_FRAME = 1, W_STATE, W_LOADING_START, W_LOADING_END, W_CHANGE, W_MAP }; typedef struct { int used, conn, gen, kind; char id[256]; /* the request's id as JSON */ int64_t deadline, issued_frame; int group; /* P_INPUT: its inputs */ int wait, from_changes; int64_t target; char state[16], map[80]; int token; char path[1100]; /* P_SHOT (its result: G.shots), P_MEM */ int mem_slot; /* P_MEM */ int dest; /* P_TELEPORT: the destination (token: the game's ticket); -1 the age switch's */ int adult_to; /* P_TELEPORT for the age switch: 1 to the adult, 0 to the child */ uint64_t sample_ticket; /* P_STATUS: coalesced next-Link-update snapshot */ } Pending; typedef struct { int used, group, exclusive, stick_set; int conn, conn_gen, waited; /* the client that sent it; waited: a request waits for its end (else it is freed then) */ int64_t at, frames, start; /* start: -1 until the first controller read after the request */ uint64_t buttons; int32_t stick[4]; } Input; static const char *const STATES[] = {"boot", "intro", "menu", "loading", "play", "unknown"}; enum { S_BOOT, S_INTRO, S_MENU, S_LOADING, S_PLAY, S_UNKNOWN }; typedef struct { int used, token, write, base64, nranges, done, ok; uint64_t addr[CTL_MEM_RANGES], size[CTL_MEM_RANGES], total; uint8_t *buf; /* read: filled on the game thread; write: the bytes to write */ char err[160]; } MemReq; static struct { const HosControlGame *game; int mem_level; /* 0 off, 1 ro, 2 rw (HOS_CONTROL_MEM) */ MemReq mems[CTL_MEM]; char path[1024], base_dir[1040], shots_dir[1060]; /* base_dir: relative shot paths and shots/ (with its separator) */ ctl_mutex mu; /* inputs, memory requests, shot results: the controller's read and the shot writer take it */ Input inputs[CTL_INPUTS]; struct { int token, done, ok; int64_t present; } shots[CTL_PENDING]; /* (by the shot's pending slot; G.mu) */ int next_group, next_token, shot_count; Conn conns[CTL_CONNS]; int conn_gen; Pending pending[CTL_PENDING]; /* the frame, the rate, the state (the bridge's thread only) */ int64_t started_ns, frame, last_frame_ns, last_frame_seen; struct { int64_t t, frame, replayed, draws; } samples[16]; int nsamples, sample_at; int64_t next_sample; double fps, draws; int have_draws, state, candidate, candidate_n, seen_menu, state_changes, loading_ends, loading_starts; int width, height; int64_t replayed; /* the renderer's presents (shots count in these) */ char map[80]; /* the map the game is in, the last one known ("" before any); map_changes: how often it changed */ int map_changes; /* log lines for subscribers (any thread writes; the bridge's thread reads) */ ctl_mutex log_mu; char log_ring[CTL_LOG_RING][400]; unsigned log_count; volatile int log_wanted; } G = {.mu = CTL_MUTEX_INIT, .log_mu = CTL_MUTEX_INIT}; static void ctl_log(const char *fmt, ...) { char line[600]; va_list ap; va_start(ap, fmt); vsnprintf(line, sizeof line, fmt, ap); va_end(ap); if (G.game && G.game->log) G.game->log(line); } /* HOS_CONTROL_MEM: -1 a value that is not one, 0 none/empty, 1 ro (reads), 2 rw (reads and writes). ro: r, read; rw: readwrite; the canonical names and the aliases, case does not matter */ int hos_control_mem_level(const char *v) { if (!v || !*v) return 0; char w[16]; size_t n = 0; for (; v[n] && n + 1 < sizeof w; n++) w[n] = (char)tolower((unsigned char)v[n]); if (v[n]) return -1; /* longer than any name */ w[n] = 0; if (!strcmp(w, "ro") || !strcmp(w, "r") || !strcmp(w, "read")) return 1; if (!strcmp(w, "rw") || !strcmp(w, "readwrite")) return 2; return -1; } /* (the game thread, each controller read) the queued memory reads and writes, done where the game runs so a read is one frame's memory and a write lands between frames. Each is bounded first (hos_mem_region through the game): out of range is an error, never a fault */ static void mem_service(void) { uint64_t wrote_at[CTL_MEM], wrote_n[CTL_MEM]; int nwrote = 0; ctl_lock(&G.mu); for (int i = 0; i < CTL_MEM; i++) { MemReq *m = &G.mems[i]; if (!m->used || m->done) continue; m->ok = 1; for (int r = 0; r < m->nranges && m->ok; r++) if (!G.game->mem_region(m->addr[r], m->size[r])) { m->ok = 0; snprintf(m->err, sizeof m->err, "%#llx..%#llx is not mapped guest memory", (unsigned long long)m->addr[r], (unsigned long long)(m->addr[r] + m->size[r])); } if (m->ok) { if (m->write) { G.game->mem_write(m->addr[0], m->buf, m->size[0]); wrote_at[nwrote] = m->addr[0], wrote_n[nwrote++] = m->size[0]; } else { uint64_t off = 0; for (int r = 0; r < m->nranges; r++) { G.game->mem_read(m->addr[r], m->buf + off, m->size[r]); off += m->size[r]; } } } m->done = 1; } ctl_unlock(&G.mu); for (int i = 0; i < nwrote; i++) /* (logged after the lock: the log may wait for its file) */ ctl_log("control: wrote %llu bytes to guest %#llx", (unsigned long long)wrote_n[i], (unsigned long long)wrote_at[i]); } /* ---- the controller's read (nn_hid.c read_input, the game's thread) ---- */ int hos_control_input(uint64_t *buttons, int32_t stick[4]) { if (!hos_control_on) return 0; if (G.mem_level) mem_service(); const int64_t frame = G.game->frame(); int exclusive = 0; ctl_lock(&G.mu); for (int i = 0; i < CTL_INPUTS; i++) { Input *in = &G.inputs[i]; if (!in->used) continue; if (in->start < 0) in->start = frame + in->at; const int64_t end = in->start + in->frames; if (frame >= in->start && frame < end) { *buttons |= in->buttons; for (int k = 0; k < 4; k++) if (in->stick_set >> k & 1) stick[k] = in->stick[k]; } if (in->exclusive && frame < end) exclusive = 1; } ctl_unlock(&G.mu); return exclusive; } /* ---- log lines (hos_log, any thread) ---- */ void hos_control_log(const char *line) { if (!hos_control_on || !G.log_wanted) return; ctl_lock(&G.log_mu); char *slot = G.log_ring[G.log_count % CTL_LOG_RING]; snprintf(slot, sizeof G.log_ring[0], "%s", line); size_t n = strlen(slot); while (n && (slot[n - 1] == '\n' || slot[n - 1] == '\r')) slot[--n] = 0; G.log_count++; ctl_unlock(&G.log_mu); } /* ---- the frame rate, draws a frame, and the state guessed from them (the bridge's thread, every tick) ---- */ static int classify(double draws) { return draws < 11 ? (G.seen_menu ? S_LOADING : S_INTRO) : draws < 150 ? S_MENU : S_PLAY; } static void stats_tick(int64_t now) { const int64_t frame = G.game->frame(); if (frame != G.last_frame_seen) G.last_frame_seen = frame, G.last_frame_ns = now; G.frame = frame; if (now < G.next_sample) return; G.next_sample = now + 100000000; int64_t replayed = frame, draws = 0; int w = 0, h = 0; G.have_draws = G.game->frame_info && G.game->frame_info(&replayed, &draws, &w, &h); if (G.have_draws) G.width = w, G.height = h, G.replayed = replayed; char map[sizeof G.map]; if (G.game->map && G.game->map(map, sizeof map) && strcmp(map, G.map)) { for (int i = 0; i < CTL_CONNS; i++) { /* subscribers: the new map */ Conn *c = &G.conns[i]; if (!c->used || c->closing || !c->sub_on || !c->sub_map) continue; buf_printf(&c->out, "{\"event\":\"map\",\"sub\":%s,\"frame\":%lld,\"map\":", c->sub_id, (long long)frame); buf_str(&c->out, map); buf_puts(&c->out, ",\"from\":"); if (G.map[0]) buf_str(&c->out, G.map); else buf_puts(&c->out, "null"); buf_puts(&c->out, "}\n"); } memcpy(G.map, map, sizeof G.map); G.map_changes++; } const int at = G.sample_at; G.samples[at].t = now, G.samples[at].frame = frame, G.samples[at].replayed = replayed, G.samples[at].draws = draws; G.sample_at = (at + 1) % 16; if (G.nsamples < 16) G.nsamples++; /* (the rate over the last second; the draws a frame over the last ~300 ms) */ const int back_rate = G.nsamples > 10 ? 10 : G.nsamples - 1, back_draws = G.nsamples > 3 ? 3 : G.nsamples - 1; if (back_rate > 0) { const int o = (at - back_rate + 16) % 16; const double secs = (now - G.samples[o].t) / 1e9; if (secs > 0) G.fps = (frame - G.samples[o].frame) / secs; } if (back_draws > 0 && G.have_draws) { const int o = (at - back_draws + 16) % 16; const int64_t frames = replayed - G.samples[o].replayed; if (frames > 0) G.draws = (double)(draws - G.samples[o].draws) / (double)frames; } int next = G.state; if (frame == 0) next = S_BOOT; else if (!G.have_draws) next = S_UNKNOWN; else { /* (a new state holds for three samples, 300 ms, before it is taken: a frame or two of a menu over the game is no change. From boot the first one counts at once) */ const int c = classify(G.draws); if (c == G.candidate) G.candidate_n++; else G.candidate = c, G.candidate_n = 1; if (G.state == S_BOOT || G.state == S_UNKNOWN || G.candidate_n >= 3) next = c; } if (next != G.state) { const int from = G.state; if (next == S_MENU || next == S_PLAY) G.seen_menu = 1; if (next == S_LOADING) G.loading_starts++; if (from == S_LOADING) G.loading_ends++; G.state = next; G.state_changes++; /* subscribers: the change */ for (int i = 0; i < CTL_CONNS; i++) { Conn *c = &G.conns[i]; if (!c->used || c->closing || !c->sub_on || !c->sub_state) continue; buf_printf(&c->out, "{\"event\":\"state\",\"sub\":%s,\"frame\":%lld,\"state\":\"%s\",\"from\":\"%s\",\"draws\":%.1f}\n", c->sub_id, (long long)frame, STATES[next], STATES[from], G.draws); } ctl_log("control: state %s -> %s at frame %lld (%.1f draws a frame)", STATES[from], STATES[next], (long long)frame, G.draws); } } /* ---- replies ---- */ static Conn *conn_of(int index, int gen) { if (index < 0 || index >= CTL_CONNS) return NULL; Conn *c = &G.conns[index]; return c->used && c->gen == gen && !c->closing ? c : NULL; } static void reply_start(Buf *b, const char *id, int ok) { buf_printf(b, "{\"id\":%s,\"ok\":%s,\"frame\":%lld", id, ok ? "true" : "false", (long long)G.frame); } static void reply_end(Conn *c, Buf *b) { buf_puts(b, "}\n"); if (c && !b->failed) buf_put(&c->out, b->p, b->n); buf_free(b); } static void reply_error(Conn *c, const char *id, const char *code, const char *fmt, ...) { char msg[400]; va_list ap; va_start(ap, fmt); vsnprintf(msg, sizeof msg, fmt, ap); va_end(ap); Buf b = {0}; reply_start(&b, id, 0); buf_puts(&b, ",\"error\":"); buf_str(&b, code); buf_puts(&b, ",\"message\":"); buf_str(&b, msg); reply_end(c, &b); } static void reply_ok(Conn *c, const char *id) { Buf b = {0}; reply_start(&b, id, 1); reply_end(c, &b); } /* ---- arguments ---- */ /* a JSON number as a whole number, held to +-2^62 first (a double past int64_t's range is undefined to convert) */ static int64_t whole(double v) { return v != v ? 0 : v > 4.6e18 ? (int64_t)4.6e18 : v < -4.6e18 ? -(int64_t)4.6e18 : (int64_t)v; } static double num_arg(const JDoc *d, int req, const char *key, double otherwise, int *bad) { const JNode *n = j_get(d, req, key); if (!n || n->type == J_NULL) return otherwise; if (n->type == J_TRUE || n->type == J_FALSE) return n->type == J_TRUE; if (n->type != J_NUM) { *bad = 1; return otherwise; } return n->num; } static const char *str_arg(const JDoc *d, int req, const char *key) { const JNode *n = j_get(d, req, key); return n && n->type == J_STR ? n->s : NULL; } static int bool_arg(const JDoc *d, int req, const char *key, int otherwise) { const JNode *n = j_get(d, req, key); return !n ? otherwise : n->type == J_TRUE ? 1 : n->type == J_FALSE || n->type == J_NULL ? 0 : n->type == J_NUM ? n->num != 0 : otherwise; } /* the timeout in seconds (default, at most an hour) as a deadline */ static int64_t deadline_arg(const JDoc *d, int req, double fallback, int *bad) { double s = num_arg(d, req, "timeout", fallback, bad); if (s < 0) *bad = 1; if (s > 3600) s = 3600; return ctl_now_ns() + (int64_t)(s * 1e9); } /* ---- inputs: buttons by the names HOS_INPUT_SCRIPT uses (nn_hid.c), the Switch's bit order (vk_api.h HOS_SW_*) ---- */ static const struct { const char *name; int bit, axis, dir; } NAMES[] = { {"A", 0, 0, 0}, {"B", 1, 0, 0}, {"X", 2, 0, 0}, {"Y", 3, 0, 0}, {"LS", 4, 0, 0}, {"RS", 5, 0, 0}, {"L", 6, 0, 0}, {"R", 7, 0, 0}, {"ZL", 8, 0, 0}, {"ZR", 9, 0, 0}, {"PLUS", 10, 0, 0}, {"MINUS", 11, 0, 0}, {"LEFT", 12, 0, 0}, {"UP", 13, 0, 0}, {"RIGHT", 14, 0, 0}, {"DOWN", 15, 0, 0}, {"LUP", -1, 1, 1}, {"LDOWN", -1, 1, -1}, {"LLEFT", -1, 0, -1}, {"LRIGHT", -1, 0, 1}, {"RUP", -1, 3, 1}, {"RDOWN", -1, 3, -1}, {"RLEFT", -1, 2, -1}, {"RRIGHT", -1, 2, 1}}; /* One token of a button list into in: a button, a stick direction, or LX=/LY=/RX=/RY=<-32767..32767>. 0: not one */ static int input_token(Input *in, const char *s, size_t n) { char t[24]; if (n == 0 || n >= sizeof t) return 0; for (size_t i = 0; i < n; i++) t[i] = (char)toupper((unsigned char)s[i]); t[n] = 0; for (unsigned i = 0; i < sizeof NAMES / sizeof *NAMES; i++) { if (strcmp(t, NAMES[i].name)) continue; if (NAMES[i].bit >= 0) in->buttons |= 1ULL << NAMES[i].bit; else in->stick[NAMES[i].axis] = NAMES[i].dir * 32767, in->stick_set |= 1 << NAMES[i].axis; return 1; } if (n >= 4 && (t[0] == 'L' || t[0] == 'R') && (t[1] == 'X' || t[1] == 'Y') && t[2] == '=') { char *e; long v = strtol(t + 3, &e, 10); if (*e) return 0; v = v < -32767 ? -32767 : v > 32767 ? 32767 : v; const int axis = (t[0] == 'L' ? 0 : 2) + (t[1] == 'Y'); in->stick[axis] = (int32_t)v, in->stick_set |= 1 << axis; return 1; } return 0; } /* "A+B" (or "A B"): 0 with the bad token in err */ static int input_names(Input *in, const char *s, char *err, size_t cap) { while (*s) { while (*s == '+' || *s == ' ') s++; const size_t n = strcspn(s, "+ "); if (!n) break; if (!input_token(in, s, n)) { snprintf(err, cap, "not a button: %.*s", (int)(n < 40 ? n : 40), s); return 0; } s += n; } return 1; } static int32_t axis_value(double v) { v = v < -1 ? -1 : v > 1 ? 1 : v; return (int32_t)lround(v * 32767); } /* One step of press, stick or sequence (its keys: buttons, frames, at, stick + x/y, lx ly rx ry) into in */ static int input_from(const JDoc *d, int obj, Input *in, int64_t default_frames, char *err, size_t cap) { memset(in, 0, sizeof *in); int bad = 0; const JNode *b = j_get(d, obj, "buttons"); if (!b) b = j_get(d, obj, "button"); if (b && b->type == J_STR && !input_names(in, b->s, err, cap)) return 0; if (b && b->type == J_ARR) for (int k = b->first; k >= 0; k = d->n[k].next) if (d->n[k].type != J_STR || !input_names(in, d->n[k].s, err, cap)) { if (!*err) snprintf(err, cap, "buttons: a list of names"); return 0; } if (b && b->type != J_STR && b->type != J_ARR && b->type != J_NULL) return snprintf(err, cap, "buttons: a name or a list of names"), 0; const char *which = str_arg(d, obj, "stick"); const JNode *x = j_get(d, obj, "x"), *y = j_get(d, obj, "y"); if (which || x || y) { const int r = which && (which[0] == 'R' || which[0] == 'r'); if (which && !r && which[0] != 'L' && which[0] != 'l') return snprintf(err, cap, "stick: L or R"), 0; const int ax = r ? 2 : 0; in->stick[ax] = axis_value(num_arg(d, obj, "x", 0, &bad)); in->stick[ax + 1] = axis_value(num_arg(d, obj, "y", 0, &bad)); in->stick_set |= 3 << ax; } static const char *const axes[4] = {"lx", "ly", "rx", "ry"}; for (int k = 0; k < 4; k++) if (j_get(d, obj, axes[k])) in->stick[k] = axis_value(num_arg(d, obj, axes[k], 0, &bad)), in->stick_set |= 1 << k; in->frames = whole(num_arg(d, obj, "frames", (double)default_frames, &bad)); in->at = whole(num_arg(d, obj, "at", 0, &bad)); if (bad) return snprintf(err, cap, "frames, at, x, y: numbers"), 0; if (in->frames < 1 || in->frames > 216000) return snprintf(err, cap, "frames: 1 to 216000"), 0; if (in->at < 0 || in->at > 216000) return snprintf(err, cap, "at: 0 to 216000 frames"), 0; if (!in->buttons && !in->stick_set) return snprintf(err, cap, "nothing to press: buttons, or a stick"), 0; return 1; } /* HOS_INPUT_SCRIPT's syntax, ":