OXYGENHUB
# 45a475bb3fa8 retro-remote-debug-controller / core / retro_control.c
15.0 KiB · C · last changed client+server: URL-encode key text so it round-trips any character 3 months ago source blame history raw
1
/* retro_control.c — portable emulator control server. See retro_control.h
2
 * and ../SPEC.md. POSIX (Linux/macOS); on Windows the entry points are no-ops.
3
 *
4
 * One accept thread, one request in flight at a time. State reads are marshalled
5
 * to the emulator thread via retro_control_service() so they observe a
6
 * consistent machine; /step is driven cooperatively by retro_control_on_frame().
7
 */
8
#include "retro_control.h"
9
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include <string.h>
13
14
#if defined(_WIN32)
15
/* No server on Windows for now — stub out so the fork still builds. */
16
int  retro_control_start(int port, const retro_control_backend_t *b) { (void)port; (void)b; return -1; }
17
void retro_control_service(void) {}
18
int  retro_control_running(void) { return 1; }
19
void retro_control_on_frame(void) {}
20
void retro_control_stop(void) {}
21
#else
22
23
#include <pthread.h>
24
#include <unistd.h>
25
#include <errno.h>
26
#include <signal.h>
27
#include <sys/socket.h>
28
#include <netinet/in.h>
29
#include <arpa/inet.h>
30
31
#ifndef MSG_NOSIGNAL
32
#define MSG_NOSIGNAL 0
33
#endif
34
35
#define MEM_CAP (1u << 20)   /* /mem hard cap: 1 MiB per request */
36
37
static const retro_control_backend_t *g_be = NULL;
38
static int       g_listen_fd = -1;
39
static pthread_t g_thread;
40
41
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
42
static pthread_cond_t  g_cv   = PTHREAD_COND_INITIALIZER;
43
44
/* run control: -1 free-run, 0 halted, >0 run this many frames then halt */
45
static long g_frames_to_run = -1;
46
static int  g_step_waiting  = 0;
47
48
/* single-slot marshalled request (mem / regs / screenshot / key / reset) */
49
typedef enum { REQ_NONE = 0, REQ_MEM, REQ_REGS, REQ_SHOT, REQ_KEY, REQ_RESET } req_t;
50
static volatile req_t g_req = REQ_NONE;
51
static uint32_t g_req_addr, g_req_len;
52
static int32_t  g_req_bank;
53
static int      g_key_is_text;   /* 1 => g_key_value is a char code point */
54
static uint32_t g_key_value;
55
static int      g_key_action;    /* retro_key_action_t */
56
57
static uint8_t    *g_resp_body  = NULL;
58
static size_t      g_resp_len   = 0;
59
static int         g_resp_status = 200;
60
static const char *g_resp_ctype = "application/octet-stream";
61
static int         g_resp_ready = 0;
62
63
/* ---- emulator-thread side ------------------------------------------------ */
64
65
static void build_ppm(void)
66
{
67
    retro_framebuffer_t fb;
68
    memset(&fb, 0, sizeof fb);
69
    g_be->get_framebuffer(&fb);
70
    int w = fb.width, h = fb.height;
71
    int bpp = (fb.fmt == RETRO_PIX_RGB888) ? 3 : 4;
72
73
    char hdr[64];
74
    int hl = snprintf(hdr, sizeof hdr, "P6\n%d %d\n255\n", w, h);
75
    size_t total = (size_t)hl + (size_t)3 * w * h;
76
    uint8_t *out = (uint8_t *)malloc(total ? total : 1);
77
    if (!out) { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 500; return; }
78
79
    memcpy(out, hdr, hl);
80
    uint8_t *p = out + hl;
81
    const uint8_t *s = fb.pixels;
82
    for (int i = 0; i < w * h; i++) {
83
        const uint8_t *px = s + (size_t)i * bpp;
84
        if (fb.fmt == RETRO_PIX_BGRA8888) {
85
            p[0] = px[2]; p[1] = px[1]; p[2] = px[0];
86
        } else {                       /* RGB888 / RGBA8888 */
87
            p[0] = px[0]; p[1] = px[1]; p[2] = px[2];
88
        }
89
        p += 3;
90
    }
91
    g_resp_body = out;
92
    g_resp_len = total;
93
    g_resp_status = 200;
94
    g_resp_ctype = "image/x-portable-pixmap";
95
}
96
97
void retro_control_service(void)
98
{
99
    if (!g_be || g_req == REQ_NONE) return;   /* cheap unlocked fast-path */
100
101
    pthread_mutex_lock(&g_lock);
102
    switch (g_req) {
103
    case REQ_MEM: {
104
        uint32_t len = g_req_len > MEM_CAP ? MEM_CAP : g_req_len;
105
        uint8_t *buf = (uint8_t *)malloc(len ? len : 1);
106
        uint32_t got = 0;
107
        if (buf && g_be->read_mem) got = g_be->read_mem(g_req_addr, g_req_bank, len, buf, len);
108
        g_resp_body = buf; g_resp_len = got;
109
        g_resp_status = g_be->read_mem ? 200 : 501;
110
        g_resp_ctype = "application/octet-stream";
111
        break;
112
    }
113
    case REQ_REGS: {
114
        char *buf = (char *)malloc(1024);
115
        if (buf && g_be->get_regs_json) { g_be->get_regs_json(buf, 1024); }
116
        else if (buf) { buf[0] = 0; }
117
        g_resp_body = (uint8_t *)buf; g_resp_len = buf ? strlen(buf) : 0;
118
        g_resp_status = g_be->get_regs_json ? 200 : 501;
119
        g_resp_ctype = "application/json";
120
        break;
121
    }
122
    case REQ_SHOT:
123
        if (g_be->get_framebuffer) build_ppm();
124
        else { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 501; }
125
        break;
126
    case REQ_KEY: {
127
        const char *json;
128
        if (!g_be->inject_key) {
129
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
130
        } else if (g_be->inject_key(g_key_is_text, g_key_value, g_key_action)) {
131
            json = "{\"injected\":true}"; g_resp_status = 200;
132
        } else {
133
            json = "{\"error\":\"unmapped key\"}"; g_resp_status = 400;
134
        }
135
        size_t l = strlen(json);
136
        uint8_t *b = (uint8_t *)malloc(l + 1);
137
        if (b) memcpy(b, json, l + 1);
138
        g_resp_body = b; g_resp_len = b ? l : 0;
139
        g_resp_ctype = "application/json";
140
        break;
141
    }
142
    case REQ_RESET: {
143
        const char *json;
144
        if (g_be->reset) { g_be->reset(); json = "{\"reset\":true}"; g_resp_status = 200; }
145
        else { json = "{\"error\":\"not implemented\"}"; g_resp_status = 501; }
146
        size_t l = strlen(json);
147
        uint8_t *b = (uint8_t *)malloc(l + 1);
148
        if (b) memcpy(b, json, l + 1);
149
        g_resp_body = b; g_resp_len = b ? l : 0;
150
        g_resp_ctype = "application/json";
151
        break;
152
    }
153
    default: break;
154
    }
155
    g_req = REQ_NONE;
156
    g_resp_ready = 1;
157
    pthread_cond_broadcast(&g_cv);
158
    pthread_mutex_unlock(&g_lock);
159
}
160
161
int retro_control_running(void)
162
{
163
    if (!g_be) return 1;
164
    pthread_mutex_lock(&g_lock);
165
    long f = g_frames_to_run;
166
    pthread_mutex_unlock(&g_lock);
167
    return f != 0;
168
}
169
170
void retro_control_on_frame(void)
171
{
172
    if (!g_be) return;
173
    pthread_mutex_lock(&g_lock);
174
    if (g_frames_to_run > 0) {
175
        g_frames_to_run--;
176
        if (g_frames_to_run == 0 && g_step_waiting) {
177
            g_step_waiting = 0;
178
            g_resp_ready = 1;
179
            pthread_cond_broadcast(&g_cv);
180
        }
181
    }
182
    pthread_mutex_unlock(&g_lock);
183
}
184
185
/* ---- server-thread side -------------------------------------------------- */
186
187
static void write_all(int fd, const void *buf, size_t len)
188
{
189
    const char *p = (const char *)buf;
190
    while (len) {
191
        ssize_t w = send(fd, p, len, MSG_NOSIGNAL);
192
        if (w <= 0) return;
193
        p += w; len -= (size_t)w;
194
    }
195
}
196
197
static void send_http(int fd, int status, const char *ctype,
198
                      const uint8_t *body, size_t len)
199
{
200
    const char *reason =
201
        status == 200 ? "OK" :
202
        status == 400 ? "Bad Request" :
203
        status == 404 ? "Not Found" :
204
        status == 405 ? "Method Not Allowed" :
205
        status == 501 ? "Not Implemented" : "Error";
206
    char hdr[256];
207
    int hl = snprintf(hdr, sizeof hdr,
208
        "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
209
        "Connection: close\r\nAccess-Control-Allow-Origin: *\r\n\r\n",
210
        status, reason, ctype, len);
211
    write_all(fd, hdr, hl);
212
    if (body && len) write_all(fd, body, len);
213
}
214
215
static void send_json(int fd, int status, const char *json)
216
{
217
    send_http(fd, status, "application/json", (const uint8_t *)json, strlen(json));
218
}
219
220
/* value of query key, decimal or 0x-hex (strtol base 0); def if absent. */
221
static long query_long(const char *q, const char *key, long def)
222
{
223
    size_t kl = strlen(key);
224
    const char *p = q;
225
    while (p && *p) {
226
        if (!strncmp(p, key, kl) && p[kl] == '=')
227
            return strtol(p + kl + 1, NULL, 0);
228
        p = strchr(p, '&');
229
        if (p) p++;
230
    }
231
    return def;
232
}
233
234
/* one hex nibble, or -1. */
235
static int hex_nibble(int c)
236
{
237
    if (c >= '0' && c <= '9') return c - '0';
238
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
239
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
240
    return -1;
241
}
242
243
/* copy the value of query key into out (NUL-terminated, truncated to cap),
244
 * percent-decoding it (form-urlencoded: %XX -> byte, '+' -> space). Numeric
245
 * params are read with query_long straight off the raw query, so only string
246
 * values (e.g. text=) are decoded here. Returns 1 if the key was present. */
247
static int query_str(const char *q, const char *key, char *out, size_t cap)
248
{
249
    size_t kl = strlen(key);
250
    const char *p = q;
251
    while (p && *p) {
252
        if (!strncmp(p, key, kl) && p[kl] == '=') {
253
            const char *v = p + kl + 1;
254
            const char *e = strchr(v, '&');
255
            const char *end = e ? e : v + strlen(v);
256
            size_t w = 0;
257
            for (const char *r = v; r < end && w + 1 < cap; ) {
258
                int hi, lo;
259
                if (r[0] == '%' && r + 2 < end &&
260
                    (hi = hex_nibble(r[1])) >= 0 && (lo = hex_nibble(r[2])) >= 0) {
261
                    out[w++] = (char)((hi << 4) | lo);
262
                    r += 3;
263
                } else if (r[0] == '+') {
264
                    out[w++] = ' ';
265
                    r += 1;
266
                } else {
267
                    out[w++] = *r++;
268
                }
269
            }
270
            out[w] = 0;
271
            return 1;
272
        }
273
        p = strchr(p, '&');
274
        if (p) p++;
275
    }
276
    if (cap) out[0] = 0;
277
    return 0;
278
}
279
280
/* marshal a read to the emulator thread, wait, send the response. */
281
static void do_marshalled(int fd, req_t r)
282
{
283
    pthread_mutex_lock(&g_lock);
284
    g_resp_ready = 0; g_resp_body = NULL; g_resp_len = 0;
285
    g_req = r;
286
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
287
    uint8_t *body = g_resp_body; size_t len = g_resp_len;
288
    int st = g_resp_status; const char *ct = g_resp_ctype;
289
    g_resp_body = NULL;
290
    pthread_mutex_unlock(&g_lock);
291
292
    send_http(fd, st, ct, body, len);
293
    free(body);
294
}
295
296
static void do_status(int fd)
297
{
298
    pthread_mutex_lock(&g_lock);
299
    long f = g_frames_to_run;
300
    pthread_mutex_unlock(&g_lock);
301
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
302
    /* Advertise 0.2 only when the backend actually offers input injection. */
303
    const char *contract = g_be->inject_key ? "0.2.0" : "0.1.0";
304
    char buf[320];
305
    snprintf(buf, sizeof buf,
306
        "{\"contract\":\"%s\",\"emulator\":\"%s\",\"platform\":\"%s\","
307
        "\"frame\":%llu,\"paused\":%s,\"running\":true}",
308
        contract,
309
        g_be->emulator ? g_be->emulator : "",
310
        g_be->platform ? g_be->platform : "",
311
        fc, (f == 0) ? "true" : "false");
312
    send_json(fd, 200, buf);
313
}
314
315
static void do_step(int fd, const char *query)
316
{
317
    long n = query_long(query, "frames", 1);
318
    if (n < 1) n = 1;
319
    pthread_mutex_lock(&g_lock);
320
    g_frames_to_run = n;
321
    g_step_waiting = 1;
322
    g_resp_ready = 0;
323
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
324
    pthread_mutex_unlock(&g_lock);
325
326
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
327
    char buf[64];
328
    snprintf(buf, sizeof buf, "{\"frame\":%llu}", fc);
329
    send_json(fd, 200, buf);
330
}
331
332
static void do_setrun(int fd, long v, int paused)
333
{
334
    pthread_mutex_lock(&g_lock);
335
    g_frames_to_run = v;
336
    pthread_mutex_unlock(&g_lock);
337
    send_json(fd, 200, paused ? "{\"paused\":true}" : "{\"paused\":false}");
338
}
339
340
static void handle_conn(int fd)
341
{
342
    char req[2048];
343
    size_t n = 0;
344
    while (n < sizeof(req) - 1) {
345
        ssize_t r = recv(fd, req + n, sizeof(req) - 1 - n, 0);
346
        if (r <= 0) break;
347
        n += (size_t)r;
348
        if (strstr(req, "\r\n\r\n")) break;
349
    }
350
    req[n] = 0;
351
352
    char method[8] = {0}, target[1024] = {0};
353
    if (sscanf(req, "%7s %1023s", method, target) != 2) {
354
        send_json(fd, 400, "{\"error\":\"bad request\"}");
355
        return;
356
    }
357
    char *q = strchr(target, '?');
358
    const char *query = "";
359
    if (q) { *q = 0; query = q + 1; }
360
    int is_post = !strcmp(method, "POST");
361
362
    if (!strcmp(target, "/status"))          { do_status(fd); return; }
363
    if (!strcmp(target, "/regs"))            { do_marshalled(fd, REQ_REGS); return; }
364
    if (!strcmp(target, "/screenshot"))      { do_marshalled(fd, REQ_SHOT); return; }
365
    if (!strcmp(target, "/mem")) {
366
        g_req_addr = (uint32_t)query_long(query, "addr", 0);
367
        g_req_len  = (uint32_t)query_long(query, "len", 0);
368
        g_req_bank = (int32_t)query_long(query, "bank", -1);
369
        do_marshalled(fd, REQ_MEM);
370
        return;
371
    }
372
    if (!strcmp(target, "/step")) {
373
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
374
        do_step(fd, query); return;
375
    }
376
    if (!strcmp(target, "/pause")) {
377
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
378
        do_setrun(fd, 0, 1); return;
379
    }
380
    if (!strcmp(target, "/resume")) {
381
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
382
        do_setrun(fd, -1, 0); return;
383
    }
384
    if (!strcmp(target, "/key")) {
385
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
386
        char text[8];
387
        long code = query_long(query, "code", -1);
388
        long down = query_long(query, "down", -1);
389
        if (query_str(query, "text", text, sizeof text) && text[0]) {
390
            g_key_is_text = 1; g_key_value = (uint32_t)(unsigned char)text[0];
391
        } else if (code >= 0) {
392
            g_key_is_text = 0; g_key_value = (uint32_t)code;
393
        } else {
394
            send_json(fd, 400, "{\"error\":\"key needs text= or code=\"}"); return;
395
        }
396
        g_key_action = (down < 0) ? RETRO_KEY_TAP
397
                     : (down != 0) ? RETRO_KEY_DOWN : RETRO_KEY_UP;
398
        do_marshalled(fd, REQ_KEY);
399
        return;
400
    }
401
    if (!strcmp(target, "/reset")) {
402
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
403
        do_marshalled(fd, REQ_RESET);
404
        return;
405
    }
406
    send_json(fd, 404, "{\"error\":\"not found\"}");
407
}
408
409
static void *server_main(void *arg)
410
{
411
    (void)arg;
412
    for (;;) {
413
        int fd = accept(g_listen_fd, NULL, NULL);
414
        if (fd < 0) {
415
            if (errno == EINTR) continue;
416
            break;
417
        }
418
        handle_conn(fd);
419
        close(fd);
420
    }
421
    return NULL;
422
}
423
424
int retro_control_start(int port, const retro_control_backend_t *backend)
425
{
426
    g_be = backend;
427
    signal(SIGPIPE, SIG_IGN);
428
429
    int fd = socket(AF_INET, SOCK_STREAM, 0);
430
    if (fd < 0) return -1;
431
    int one = 1;
432
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
433
434
    struct sockaddr_in addr;
435
    memset(&addr, 0, sizeof addr);
436
    addr.sin_family = AF_INET;
437
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);   /* 127.0.0.1 only */
438
    addr.sin_port = htons((uint16_t)port);
439
    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
440
        fprintf(stderr, "[retro_control] bind 127.0.0.1:%d failed: %s\n",
441
                port, strerror(errno));
442
        close(fd);
443
        return -1;
444
    }
445
    if (listen(fd, 4) < 0) { close(fd); return -1; }
446
447
    g_listen_fd = fd;
448
    if (pthread_create(&g_thread, NULL, server_main, NULL) != 0) {
449
        close(fd); g_listen_fd = -1; return -1;
450
    }
451
    pthread_detach(g_thread);
452
    fprintf(stderr, "[retro_control] listening on 127.0.0.1:%d (contract %s)\n",
453
            port, RETRO_CONTROL_CONTRACT);
454
    return 0;
455
}
456
457
void retro_control_stop(void)
458
{
459
    if (g_listen_fd >= 0) { close(g_listen_fd); g_listen_fd = -1; }
460
}
461
462
#endif /* !_WIN32 */