OXYGENHUB
# 8fd33bc520f9 retro-remote-debug-controller / core / retro_control.c
27.5 KiB · C · last changed feat: contract 0.6 — GET/POST /perf, the performance metrics (budget, current frame, windows, zones, raw frames since one, a platform section) and their settings, and /status.capabilities; backend callbacks get_perf and set_perf return allocated JSON (#6) 25 days ago source blame history raw
961b3c61 Andy McCall 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>
346ca3ee Andy McCall ↶ 26
#include <limits.h>
961b3c61 Andy McCall 27
#include <signal.h>
28
#include <sys/socket.h>
29
#include <netinet/in.h>
30
#include <arpa/inet.h>
31
32
#ifndef MSG_NOSIGNAL
33
#define MSG_NOSIGNAL 0
34
#endif
35
36
#define MEM_CAP (1u << 20)   /* /mem hard cap: 1 MiB per request */
37
38
static const retro_control_backend_t *g_be = NULL;
39
static int       g_listen_fd = -1;
40
static pthread_t g_thread;
41
42
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
43
static pthread_cond_t  g_cv   = PTHREAD_COND_INITIALIZER;
44
45
/* run control: -1 free-run, 0 halted, >0 run this many frames then halt */
46
static long g_frames_to_run = -1;
47
static int  g_step_waiting  = 0;
48
674b8447 Andy McCall ↶ 49
/* single-slot marshalled request. */
50
typedef enum { REQ_NONE = 0, REQ_MEM, REQ_REGS, REQ_SHOT, REQ_KEY, REQ_RESET,
bed0f1e5 Andy McCall ↶ 51
               REQ_WRITE, REQ_AUDIO, REQ_PTR_SET, REQ_PTR_GET,
8fd33bc5 Andy McCall ↶ 52
               REQ_PAD_SET, REQ_PAD_GET, REQ_PERF_GET, REQ_PERF_SET } req_t;
961b3c61 Andy McCall 53
static volatile req_t g_req = REQ_NONE;
54
static uint32_t g_req_addr, g_req_len;
55
static int32_t  g_req_bank;
674b8447 Andy McCall ↶ 56
static const uint8_t *g_write_data;   /* POST /mem body (HTTP-thread owned) */
689a9ccb Andy McCall ↶ 57
static int      g_key_is_text;   /* 1 => g_key_value is a char code point */
58
static uint32_t g_key_value;
59
static int      g_key_action;    /* retro_key_action_t */
346ca3ee Andy McCall ↶ 60
static int      g_ptr_absolute;  /* 1 => (x,y) absolute; 0 => relative deltas */
61
static int32_t  g_ptr_x, g_ptr_y;
62
static int      g_ptr_buttons;   /* button bitmask, or -1 = leave unchanged */
bed0f1e5 Andy McCall ↶ 63
static int      g_pad_index;     /* which pad (0-based) */
64
static int      g_pad_buttons;   /* held mask, or -1 = leave unchanged */
65
static int      g_pad_connected; /* 1 plug, 0 unplug, -1 = unchanged */
674b8447 Andy McCall ↶ 66
static char     g_resp_extra[64];     /* extra response header line, or "" */
8fd33bc5 Andy McCall ↶ 67
static char     g_perf_query[1024];   /* GET /perf's query string (0.6) */
68
static const char *g_perf_body;       /* POST /perf's body, NUL-terminated (HTTP-thread owned) */
961b3c61 Andy McCall 69
70
static uint8_t    *g_resp_body  = NULL;
71
static size_t      g_resp_len   = 0;
72
static int         g_resp_status = 200;
73
static const char *g_resp_ctype = "application/octet-stream";
74
static int         g_resp_ready = 0;
75
76
/* ---- emulator-thread side ------------------------------------------------ */
77
78
static void build_ppm(void)
79
{
80
    retro_framebuffer_t fb;
81
    memset(&fb, 0, sizeof fb);
82
    g_be->get_framebuffer(&fb);
83
    int w = fb.width, h = fb.height;
84
    int bpp = (fb.fmt == RETRO_PIX_RGB888) ? 3 : 4;
85
86
    char hdr[64];
87
    int hl = snprintf(hdr, sizeof hdr, "P6\n%d %d\n255\n", w, h);
88
    size_t total = (size_t)hl + (size_t)3 * w * h;
89
    uint8_t *out = (uint8_t *)malloc(total ? total : 1);
90
    if (!out) { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 500; return; }
91
92
    memcpy(out, hdr, hl);
93
    uint8_t *p = out + hl;
94
    const uint8_t *s = fb.pixels;
95
    for (int i = 0; i < w * h; i++) {
96
        const uint8_t *px = s + (size_t)i * bpp;
97
        if (fb.fmt == RETRO_PIX_BGRA8888) {
98
            p[0] = px[2]; p[1] = px[1]; p[2] = px[0];
99
        } else {                       /* RGB888 / RGBA8888 */
100
            p[0] = px[0]; p[1] = px[1]; p[2] = px[2];
101
        }
102
        p += 3;
103
    }
104
    g_resp_body = out;
105
    g_resp_len = total;
106
    g_resp_status = 200;
107
    g_resp_ctype = "image/x-portable-pixmap";
108
}
109
674b8447 Andy McCall ↶ 110
#define AUDIO_MAX_SAMPLES (1u << 18)   /* drain cap: 256K int16 (~2.7 s stereo @48.8k) */
111
112
static void le16(uint8_t *p, uint16_t v) { p[0] = v; p[1] = v >> 8; }
113
static void le32(uint8_t *p, uint32_t v) { p[0] = v; p[1] = v >> 8; p[2] = v >> 16; p[3] = v >> 24; }
114
115
/* Drain the backend's audio ring and wrap it as a canonical PCM WAV. */
116
static void build_wav(void)
117
{
118
    static int16_t samp[AUDIO_MAX_SAMPLES];
119
    int rate = 48000, channels = 1;
120
    uint32_t dropped = 0;
121
    uint32_t n = g_be->capture_audio(samp, AUDIO_MAX_SAMPLES, &rate, &channels, &dropped);
122
    if (channels < 1) channels = 1;
123
    if (rate < 1) rate = 1;
124
125
    uint32_t data_bytes = n * 2;               /* int16 samples */
126
    uint32_t total = 44 + data_bytes;
127
    uint8_t *out = (uint8_t *)malloc(total);
128
    if (!out) { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 500; return; }
129
130
    uint32_t byte_rate = (uint32_t)rate * channels * 2;
131
    memcpy(out, "RIFF", 4);       le32(out + 4, 36 + data_bytes);
132
    memcpy(out + 8, "WAVE", 4);
133
    memcpy(out + 12, "fmt ", 4);  le32(out + 16, 16);
134
    le16(out + 20, 1);            le16(out + 22, (uint16_t)channels);
135
    le32(out + 24, (uint32_t)rate);
136
    le32(out + 28, byte_rate);    le16(out + 32, (uint16_t)(channels * 2));
137
    le16(out + 34, 16);
138
    memcpy(out + 36, "data", 4);  le32(out + 40, data_bytes);
139
    memcpy(out + 44, samp, data_bytes);
140
141
    g_resp_body = out; g_resp_len = total; g_resp_status = 200;
142
    g_resp_ctype = "audio/wav";
143
    snprintf(g_resp_extra, sizeof g_resp_extra,
144
             "X-Rrdc-Audio-Dropped: %u\r\n", (unsigned)dropped);
145
}
146
961b3c61 Andy McCall 147
void retro_control_service(void)
148
{
149
    if (!g_be || g_req == REQ_NONE) return;   /* cheap unlocked fast-path */
150
151
    pthread_mutex_lock(&g_lock);
674b8447 Andy McCall ↶ 152
    g_resp_extra[0] = 0;
961b3c61 Andy McCall 153
    switch (g_req) {
154
    case REQ_MEM: {
155
        uint32_t len = g_req_len > MEM_CAP ? MEM_CAP : g_req_len;
156
        uint8_t *buf = (uint8_t *)malloc(len ? len : 1);
157
        uint32_t got = 0;
158
        if (buf && g_be->read_mem) got = g_be->read_mem(g_req_addr, g_req_bank, len, buf, len);
159
        g_resp_body = buf; g_resp_len = got;
160
        g_resp_status = g_be->read_mem ? 200 : 501;
161
        g_resp_ctype = "application/octet-stream";
162
        break;
163
    }
164
    case REQ_REGS: {
165
        char *buf = (char *)malloc(1024);
166
        if (buf && g_be->get_regs_json) { g_be->get_regs_json(buf, 1024); }
167
        else if (buf) { buf[0] = 0; }
168
        g_resp_body = (uint8_t *)buf; g_resp_len = buf ? strlen(buf) : 0;
169
        g_resp_status = g_be->get_regs_json ? 200 : 501;
170
        g_resp_ctype = "application/json";
171
        break;
172
    }
173
    case REQ_SHOT:
174
        if (g_be->get_framebuffer) build_ppm();
175
        else { g_resp_body = NULL; g_resp_len = 0; g_resp_status = 501; }
176
        break;
689a9ccb Andy McCall ↶ 177
    case REQ_KEY: {
178
        const char *json;
179
        if (!g_be->inject_key) {
180
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
181
        } else if (g_be->inject_key(g_key_is_text, g_key_value, g_key_action)) {
182
            json = "{\"injected\":true}"; g_resp_status = 200;
183
        } else {
184
            json = "{\"error\":\"unmapped key\"}"; g_resp_status = 400;
185
        }
186
        size_t l = strlen(json);
187
        uint8_t *b = (uint8_t *)malloc(l + 1);
188
        if (b) memcpy(b, json, l + 1);
189
        g_resp_body = b; g_resp_len = b ? l : 0;
190
        g_resp_ctype = "application/json";
191
        break;
192
    }
193
    case REQ_RESET: {
194
        const char *json;
195
        if (g_be->reset) { g_be->reset(); json = "{\"reset\":true}"; g_resp_status = 200; }
196
        else { json = "{\"error\":\"not implemented\"}"; g_resp_status = 501; }
197
        size_t l = strlen(json);
198
        uint8_t *b = (uint8_t *)malloc(l + 1);
199
        if (b) memcpy(b, json, l + 1);
200
        g_resp_body = b; g_resp_len = b ? l : 0;
674b8447 Andy McCall ↶ 201
        g_resp_ctype = "application/json";
202
        break;
203
    }
204
    case REQ_WRITE: {
205
        const char *json; char *b;
206
        if (!g_be->write_mem) {
207
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
208
            size_t l = strlen(json); b = (char *)malloc(l + 1);
209
            if (b) memcpy(b, json, l + 1);
210
            g_resp_len = b ? l : 0;
211
        } else {
212
            uint32_t wrote = g_be->write_mem(g_req_addr, g_req_bank, g_req_len, g_write_data);
213
            b = (char *)malloc(48);
214
            g_resp_len = b ? (size_t)snprintf(b, 48, "{\"written\":%u}", (unsigned)wrote) : 0;
215
            g_resp_status = 200;
216
        }
217
        g_resp_body = (uint8_t *)b;
689a9ccb Andy McCall ↶ 218
        g_resp_ctype = "application/json";
219
        break;
220
    }
674b8447 Andy McCall ↶ 221
    case REQ_AUDIO:
222
        if (g_be->capture_audio) build_wav();
223
        else {
224
            const char *json = "{\"error\":\"not implemented\"}";
225
            size_t l = strlen(json); uint8_t *b = (uint8_t *)malloc(l + 1);
226
            if (b) memcpy(b, json, l + 1);
227
            g_resp_body = b; g_resp_len = b ? l : 0; g_resp_status = 501;
228
            g_resp_ctype = "application/json";
229
        }
230
        break;
346ca3ee Andy McCall ↶ 231
    case REQ_PTR_SET: {
232
        const char *json;
233
        if (!g_be->set_pointer) {
234
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
235
        } else if (g_be->set_pointer(g_ptr_absolute, g_ptr_x, g_ptr_y, g_ptr_buttons)) {
236
            json = "{\"injected\":true}"; g_resp_status = 200;
237
        } else {
238
            json = "{\"error\":\"no pointer\"}"; g_resp_status = 400;
239
        }
240
        size_t l = strlen(json);
241
        uint8_t *b = (uint8_t *)malloc(l + 1);
242
        if (b) memcpy(b, json, l + 1);
243
        g_resp_body = b; g_resp_len = b ? l : 0;
244
        g_resp_ctype = "application/json";
245
        break;
246
    }
247
    case REQ_PTR_GET: {
248
        char *b;
249
        if (!g_be->get_pointer) {
250
            const char *json = "{\"error\":\"not implemented\"}";
251
            size_t l = strlen(json); b = (char *)malloc(l + 1);
252
            if (b) memcpy(b, json, l + 1);
253
            g_resp_len = b ? l : 0; g_resp_status = 501;
254
        } else {
255
            int32_t x = 0, y = 0; int buttons = 0;
256
            int ok = g_be->get_pointer(&x, &y, &buttons);
257
            b = (char *)malloc(96);
258
            if (!b) { g_resp_len = 0; g_resp_status = 500; }
259
            else if (ok) {
260
                g_resp_len = (size_t)snprintf(b, 96,
261
                    "{\"x\":%ld,\"y\":%ld,\"buttons\":%d}",
262
                    (long)x, (long)y, buttons);
263
                g_resp_status = 200;
264
            } else {
265
                g_resp_len = (size_t)snprintf(b, 96, "{\"error\":\"no pointer\"}");
266
                g_resp_status = 400;
267
            }
268
        }
269
        g_resp_body = (uint8_t *)b;
270
        g_resp_ctype = "application/json";
271
        break;
272
    }
bed0f1e5 Andy McCall ↶ 273
    case REQ_PAD_SET: {
274
        const char *json;
275
        if (!g_be->set_pad) {
276
            json = "{\"error\":\"not implemented\"}"; g_resp_status = 501;
277
        } else if (g_be->set_pad(g_pad_index, g_pad_buttons, g_pad_connected)) {
278
            json = "{\"injected\":true}"; g_resp_status = 200;
279
        } else {
280
            json = "{\"error\":\"no controller\"}"; g_resp_status = 400;
281
        }
282
        size_t l = strlen(json);
283
        uint8_t *b = (uint8_t *)malloc(l + 1);
284
        if (b) memcpy(b, json, l + 1);
285
        g_resp_body = b; g_resp_len = b ? l : 0;
286
        g_resp_ctype = "application/json";
287
        break;
288
    }
289
    case REQ_PAD_GET: {
290
        char *b;
291
        if (!g_be->get_pad) {
292
            const char *json = "{\"error\":\"not implemented\"}";
293
            size_t l = strlen(json); b = (char *)malloc(l + 1);
294
            if (b) memcpy(b, json, l + 1);
295
            g_resp_len = b ? l : 0; g_resp_status = 501;
296
        } else {
297
            int buttons = 0, connected = 0;
298
            int ok = g_be->get_pad(g_pad_index, &buttons, &connected);
299
            b = (char *)malloc(96);
300
            if (!b) { g_resp_len = 0; g_resp_status = 500; }
301
            else if (ok) {
302
                g_resp_len = (size_t)snprintf(b, 96,
303
                    "{\"index\":%d,\"connected\":%s,\"buttons\":%d}",
304
                    g_pad_index, connected ? "true" : "false", buttons);
305
                g_resp_status = 200;
306
            } else {
307
                g_resp_len = (size_t)snprintf(b, 96,
308
                    "{\"error\":\"no controller\"}");
309
                g_resp_status = 400;
310
            }
311
        }
312
        g_resp_body = (uint8_t *)b;
313
        g_resp_ctype = "application/json";
314
        break;
315
    }
8fd33bc5 Andy McCall ↶ 316
    case REQ_PERF_GET:
317
    case REQ_PERF_SET: {
318
        char *b = NULL;
319
        int st = 200;
320
        int have = (g_req == REQ_PERF_GET) ? g_be->get_perf != NULL : g_be->set_perf != NULL;
321
        if (!have) {
322
            st = 501;
323
        } else if (g_req == REQ_PERF_GET) {
324
            b = g_be->get_perf(g_perf_query);
325
        } else {
326
            b = g_be->set_perf(g_perf_body ? g_perf_body : "", &st);
327
            if (st != 200 && st != 400) st = 400;
328
        }
329
        if (!b) {                             /* not implemented, or the backend failed */
330
            const char *json = (st == 501) ? "{\"error\":\"not implemented\"}"
331
                                           : "{\"error\":\"perf failed\"}";
332
            if (st != 501) st = 500;
333
            size_t l = strlen(json);
334
            b = (char *)malloc(l + 1);
335
            if (b) memcpy(b, json, l + 1);
336
        }
337
        g_resp_body = (uint8_t *)b; g_resp_len = b ? strlen(b) : 0;
338
        g_resp_status = st;
339
        g_resp_ctype = "application/json";
340
        break;
341
    }
961b3c61 Andy McCall 342
    default: break;
343
    }
344
    g_req = REQ_NONE;
345
    g_resp_ready = 1;
346
    pthread_cond_broadcast(&g_cv);
347
    pthread_mutex_unlock(&g_lock);
348
}
349
350
int retro_control_running(void)
351
{
352
    if (!g_be) return 1;
353
    pthread_mutex_lock(&g_lock);
354
    long f = g_frames_to_run;
355
    pthread_mutex_unlock(&g_lock);
356
    return f != 0;
357
}
358
359
void retro_control_on_frame(void)
360
{
361
    if (!g_be) return;
362
    pthread_mutex_lock(&g_lock);
363
    if (g_frames_to_run > 0) {
364
        g_frames_to_run--;
365
        if (g_frames_to_run == 0 && g_step_waiting) {
366
            g_step_waiting = 0;
367
            g_resp_ready = 1;
368
            pthread_cond_broadcast(&g_cv);
369
        }
370
    }
371
    pthread_mutex_unlock(&g_lock);
372
}
373
374
/* ---- server-thread side -------------------------------------------------- */
375
376
static void write_all(int fd, const void *buf, size_t len)
377
{
378
    const char *p = (const char *)buf;
379
    while (len) {
380
        ssize_t w = send(fd, p, len, MSG_NOSIGNAL);
381
        if (w <= 0) return;
382
        p += w; len -= (size_t)w;
383
    }
384
}
385
674b8447 Andy McCall ↶ 386
/* `extra`, if non-NULL, is a complete header line ("Name: value\r\n"). */
961b3c61 Andy McCall 387
static void send_http(int fd, int status, const char *ctype,
674b8447 Andy McCall ↶ 388
                      const uint8_t *body, size_t len, const char *extra)
961b3c61 Andy McCall 389
{
390
    const char *reason =
391
        status == 200 ? "OK" :
392
        status == 400 ? "Bad Request" :
393
        status == 404 ? "Not Found" :
394
        status == 405 ? "Method Not Allowed" :
8fd33bc5 Andy McCall ↶ 395
        status == 500 ? "Internal Server Error" :
961b3c61 Andy McCall 396
        status == 501 ? "Not Implemented" : "Error";
674b8447 Andy McCall ↶ 397
    char hdr[320];
961b3c61 Andy McCall 398
    int hl = snprintf(hdr, sizeof hdr,
399
        "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
674b8447 Andy McCall ↶ 400
        "Connection: close\r\nAccess-Control-Allow-Origin: *\r\n%s\r\n",
401
        status, reason, ctype, len, extra ? extra : "");
961b3c61 Andy McCall 402
    write_all(fd, hdr, hl);
403
    if (body && len) write_all(fd, body, len);
404
}
405
406
static void send_json(int fd, int status, const char *json)
407
{
674b8447 Andy McCall ↶ 408
    send_http(fd, status, "application/json", (const uint8_t *)json, strlen(json), NULL);
961b3c61 Andy McCall 409
}
410
411
/* value of query key, decimal or 0x-hex (strtol base 0); def if absent. */
412
static long query_long(const char *q, const char *key, long def)
413
{
414
    size_t kl = strlen(key);
415
    const char *p = q;
416
    while (p && *p) {
417
        if (!strncmp(p, key, kl) && p[kl] == '=')
418
            return strtol(p + kl + 1, NULL, 0);
419
        p = strchr(p, '&');
420
        if (p) p++;
421
    }
422
    return def;
423
}
424
689a9ccb Andy McCall ↶ 425
/* copy the value of query key into out (NUL-terminated, truncated to cap).
426
 * Returns 1 if the key was present, 0 otherwise. */
427
static int query_str(const char *q, const char *key, char *out, size_t cap)
428
{
429
    size_t kl = strlen(key);
430
    const char *p = q;
431
    while (p && *p) {
432
        if (!strncmp(p, key, kl) && p[kl] == '=') {
433
            const char *v = p + kl + 1;
434
            const char *e = strchr(v, '&');
435
            size_t n = e ? (size_t)(e - v) : strlen(v);
436
            if (n >= cap) n = cap - 1;
437
            memcpy(out, v, n);
438
            out[n] = 0;
439
            return 1;
440
        }
441
        p = strchr(p, '&');
442
        if (p) p++;
443
    }
444
    if (cap) out[0] = 0;
445
    return 0;
446
}
447
961b3c61 Andy McCall 448
/* marshal a read to the emulator thread, wait, send the response. */
449
static void do_marshalled(int fd, req_t r)
450
{
451
    pthread_mutex_lock(&g_lock);
452
    g_resp_ready = 0; g_resp_body = NULL; g_resp_len = 0;
453
    g_req = r;
454
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
455
    uint8_t *body = g_resp_body; size_t len = g_resp_len;
456
    int st = g_resp_status; const char *ct = g_resp_ctype;
674b8447 Andy McCall ↶ 457
    char extra[64]; memcpy(extra, g_resp_extra, sizeof extra);
961b3c61 Andy McCall 458
    g_resp_body = NULL;
459
    pthread_mutex_unlock(&g_lock);
460
674b8447 Andy McCall ↶ 461
    send_http(fd, st, ct, body, len, extra[0] ? extra : NULL);
961b3c61 Andy McCall 462
    free(body);
463
}
464
465
static void do_status(int fd)
466
{
467
    pthread_mutex_lock(&g_lock);
468
    long f = g_frames_to_run;
469
    pthread_mutex_unlock(&g_lock);
470
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
674b8447 Andy McCall ↶ 471
    /* Advertise the highest level whose defining callbacks are all present. */
8fd33bc5 Andy McCall ↶ 472
    const int perf = g_be->get_perf && g_be->set_perf;
674b8447 Andy McCall ↶ 473
    const char *contract =
8fd33bc5 Andy McCall ↶ 474
        (g_be->inject_key && g_be->write_mem && g_be->capture_audio &&
475
         g_be->set_pointer && g_be->get_pointer &&
476
         g_be->set_pad && g_be->get_pad && perf) ? "0.6.0" :
346ca3ee Andy McCall ↶ 477
        (g_be->inject_key && g_be->write_mem && g_be->capture_audio &&
bed0f1e5 Andy McCall ↶ 478
         g_be->set_pointer && g_be->get_pointer &&
479
         g_be->set_pad && g_be->get_pad) ? "0.5.0" :
480
        (g_be->inject_key && g_be->write_mem && g_be->capture_audio &&
346ca3ee Andy McCall ↶ 481
         g_be->set_pointer && g_be->get_pointer) ? "0.4.0" :
674b8447 Andy McCall ↶ 482
        (g_be->inject_key && g_be->write_mem && g_be->capture_audio) ? "0.3.0" :
483
        g_be->inject_key ? "0.2.0" : "0.1.0";
8fd33bc5 Andy McCall ↶ 484
    /* 0.6: each endpoint group the backend serves, whatever level it reaches. */
485
    char caps[160];
486
    snprintf(caps, sizeof caps, "\"mem\",\"regs\",\"screenshot\",\"step\"%s%s%s%s%s%s%s",
487
        g_be->inject_key ? ",\"key\"" : "",
488
        g_be->reset ? ",\"reset\"" : "",
489
        g_be->write_mem ? ",\"mem-write\"" : "",
490
        g_be->capture_audio ? ",\"audio\"" : "",
491
        (g_be->set_pointer && g_be->get_pointer) ? ",\"pointer\"" : "",
492
        (g_be->set_pad && g_be->get_pad) ? ",\"pad\"" : "",
493
        perf ? ",\"perf\"" : "");
494
    char buf[512];
961b3c61 Andy McCall 495
    snprintf(buf, sizeof buf,
496
        "{\"contract\":\"%s\",\"emulator\":\"%s\",\"platform\":\"%s\","
8fd33bc5 Andy McCall ↶ 497
        "\"frame\":%llu,\"paused\":%s,\"running\":true,\"capabilities\":[%s]}",
689a9ccb Andy McCall ↶ 498
        contract,
961b3c61 Andy McCall 499
        g_be->emulator ? g_be->emulator : "",
500
        g_be->platform ? g_be->platform : "",
8fd33bc5 Andy McCall ↶ 501
        fc, (f == 0) ? "true" : "false", caps);
961b3c61 Andy McCall 502
    send_json(fd, 200, buf);
503
}
504
505
static void do_step(int fd, const char *query)
506
{
507
    long n = query_long(query, "frames", 1);
508
    if (n < 1) n = 1;
509
    pthread_mutex_lock(&g_lock);
510
    g_frames_to_run = n;
511
    g_step_waiting = 1;
512
    g_resp_ready = 0;
513
    while (!g_resp_ready) pthread_cond_wait(&g_cv, &g_lock);
514
    pthread_mutex_unlock(&g_lock);
515
516
    unsigned long long fc = g_be->get_frame_count ? g_be->get_frame_count() : 0;
517
    char buf[64];
518
    snprintf(buf, sizeof buf, "{\"frame\":%llu}", fc);
519
    send_json(fd, 200, buf);
520
}
521
522
static void do_setrun(int fd, long v, int paused)
523
{
524
    pthread_mutex_lock(&g_lock);
525
    g_frames_to_run = v;
526
    pthread_mutex_unlock(&g_lock);
527
    send_json(fd, 200, paused ? "{\"paused\":true}" : "{\"paused\":false}");
528
}
674b8447 Andy McCall ↶ 529
530
/* Read a request body (POST /mem). `req`/`n` = what handle_conn already recv'd
531
 * (headers + maybe some body); reads the rest per Content-Length. Returns a
532
 * malloc'd buffer of *out_len bytes (caller frees), capped at MEM_CAP. */
533
static uint8_t *read_body(int fd, char *req, size_t n, size_t *out_len)
534
{
535
    *out_len = 0;
536
    char *hdr_end = strstr(req, "\r\n\r\n");
537
    if (!hdr_end) return NULL;
538
    char *body_start = hdr_end + 4;
539
540
    long clen = 0;
541
    char *cl = strstr(req, "Content-Length:");
542
    if (!cl) cl = strstr(req, "content-length:");
543
    if (cl) clen = strtol(cl + 15, NULL, 10);
544
    if (clen < 0) clen = 0;
545
    if (clen > (long)MEM_CAP) clen = (long)MEM_CAP;
961b3c61 Andy McCall 546
674b8447 Andy McCall ↶ 547
    uint8_t *body = (uint8_t *)malloc((size_t)clen ? (size_t)clen : 1);
548
    if (!body) return NULL;
549
550
    size_t have = (size_t)(req + n - body_start);
551
    if (have > (size_t)clen) have = (size_t)clen;
552
    memcpy(body, body_start, have);
553
    size_t got = have;
554
    while (got < (size_t)clen) {
555
        ssize_t r = recv(fd, body + got, (size_t)clen - got, 0);
556
        if (r <= 0) break;
557
        got += (size_t)r;
558
    }
559
    *out_len = got;
560
    return body;
561
}
562
961b3c61 Andy McCall 563
static void handle_conn(int fd)
564
{
565
    char req[2048];
566
    size_t n = 0;
567
    while (n < sizeof(req) - 1) {
568
        ssize_t r = recv(fd, req + n, sizeof(req) - 1 - n, 0);
569
        if (r <= 0) break;
570
        n += (size_t)r;
571
        if (strstr(req, "\r\n\r\n")) break;
572
    }
573
    req[n] = 0;
574
575
    char method[8] = {0}, target[1024] = {0};
576
    if (sscanf(req, "%7s %1023s", method, target) != 2) {
577
        send_json(fd, 400, "{\"error\":\"bad request\"}");
578
        return;
579
    }
580
    char *q = strchr(target, '?');
581
    const char *query = "";
582
    if (q) { *q = 0; query = q + 1; }
583
    int is_post = !strcmp(method, "POST");
584
585
    if (!strcmp(target, "/status"))          { do_status(fd); return; }
586
    if (!strcmp(target, "/regs"))            { do_marshalled(fd, REQ_REGS); return; }
587
    if (!strcmp(target, "/screenshot"))      { do_marshalled(fd, REQ_SHOT); return; }
674b8447 Andy McCall ↶ 588
    if (!strcmp(target, "/audio"))           { do_marshalled(fd, REQ_AUDIO); return; }
961b3c61 Andy McCall 589
    if (!strcmp(target, "/mem")) {
590
        g_req_addr = (uint32_t)query_long(query, "addr", 0);
591
        g_req_bank = (int32_t)query_long(query, "bank", -1);
674b8447 Andy McCall ↶ 592
        if (is_post) {                        /* 0.3: write / poke */
593
            size_t blen = 0;
594
            uint8_t *body = read_body(fd, req, n, &blen);
595
            g_req_len = (uint32_t)blen;
596
            g_write_data = body;
597
            do_marshalled(fd, REQ_WRITE);
598
            free(body);
599
        } else {                              /* read */
600
            g_req_len = (uint32_t)query_long(query, "len", 0);
601
            do_marshalled(fd, REQ_MEM);
602
        }
961b3c61 Andy McCall 603
        return;
604
    }
605
    if (!strcmp(target, "/step")) {
606
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
607
        do_step(fd, query); return;
608
    }
609
    if (!strcmp(target, "/pause")) {
610
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
611
        do_setrun(fd, 0, 1); return;
612
    }
613
    if (!strcmp(target, "/resume")) {
614
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
615
        do_setrun(fd, -1, 0); return;
689a9ccb Andy McCall ↶ 616
    }
617
    if (!strcmp(target, "/key")) {
618
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
619
        char text[8];
620
        long code = query_long(query, "code", -1);
621
        long down = query_long(query, "down", -1);
622
        if (query_str(query, "text", text, sizeof text) && text[0]) {
623
            g_key_is_text = 1; g_key_value = (uint32_t)(unsigned char)text[0];
624
        } else if (code >= 0) {
625
            g_key_is_text = 0; g_key_value = (uint32_t)code;
626
        } else {
627
            send_json(fd, 400, "{\"error\":\"key needs text= or code=\"}"); return;
628
        }
629
        g_key_action = (down < 0) ? RETRO_KEY_TAP
630
                     : (down != 0) ? RETRO_KEY_DOWN : RETRO_KEY_UP;
631
        do_marshalled(fd, REQ_KEY);
632
        return;
633
    }
634
    if (!strcmp(target, "/reset")) {
635
        if (!is_post) { send_json(fd, 405, "{\"error\":\"POST only\"}"); return; }
636
        do_marshalled(fd, REQ_RESET);
346ca3ee Andy McCall ↶ 637
        return;
638
    }
639
    if (!strcmp(target, "/pointer")) {
640
        if (is_post) {                        /* 0.4: move/click the pointer */
641
            long x  = query_long(query, "x",  LONG_MIN);
642
            long y  = query_long(query, "y",  LONG_MIN);
643
            long dx = query_long(query, "dx", LONG_MIN);
644
            long dy = query_long(query, "dy", LONG_MIN);
645
            if (x != LONG_MIN && y != LONG_MIN) {
646
                g_ptr_absolute = 1; g_ptr_x = (int32_t)x; g_ptr_y = (int32_t)y;
647
            } else if (dx != LONG_MIN || dy != LONG_MIN) {
648
                g_ptr_absolute = 0;
649
                g_ptr_x = (int32_t)(dx == LONG_MIN ? 0 : dx);
650
                g_ptr_y = (int32_t)(dy == LONG_MIN ? 0 : dy);
651
            } else {
652
                send_json(fd, 400, "{\"error\":\"pointer needs x&y or dx&dy\"}"); return;
653
            }
654
            g_ptr_buttons = (int)query_long(query, "buttons", -1);   /* -1 = unchanged */
655
            do_marshalled(fd, REQ_PTR_SET);
656
        } else {                              /* 0.4: read back the pointer */
657
            do_marshalled(fd, REQ_PTR_GET);
bed0f1e5 Andy McCall ↶ 658
        }
659
        return;
660
    }
661
    if (!strcmp(target, "/pad")) {
662
        g_pad_index = (int)query_long(query, "index", 0);
663
        if (is_post) {                        /* 0.5: present / set a pad */
664
            g_pad_buttons = (int)query_long(query, "buttons", -1);
665
            /* `connected` defaults to plugging it in whenever buttons were
666
             * given -- injecting a press on an absent pad is never what the
667
             * caller meant -- and to leaving it alone otherwise. */
668
            g_pad_connected = (int)query_long(query, "connected",
669
                                              g_pad_buttons >= 0 ? 1 : -1);
670
            do_marshalled(fd, REQ_PAD_SET);
671
        } else {                              /* 0.5: read a pad back */
672
            do_marshalled(fd, REQ_PAD_GET);
8fd33bc5 Andy McCall ↶ 673
        }
674
        return;
675
    }
676
    if (!strcmp(target, "/perf")) {           /* 0.6: performance metrics */
677
        if (is_post) {
678
            size_t blen = 0;
679
            uint8_t *body = read_body(fd, req, n, &blen);
680
            char *text = (char *)malloc(blen + 1);
681
            if (!text) { free(body); send_json(fd, 500, "{\"error\":\"out of memory\"}"); return; }
682
            if (body && blen) memcpy(text, body, blen);
683
            text[blen] = 0;
684
            free(body);
685
            g_perf_body = text;
686
            do_marshalled(fd, REQ_PERF_SET);
687
            g_perf_body = NULL;
688
            free(text);
689
        } else {
690
            snprintf(g_perf_query, sizeof g_perf_query, "%s", query);
691
            do_marshalled(fd, REQ_PERF_GET);
346ca3ee Andy McCall ↶ 692
        }
689a9ccb Andy McCall ↶ 693
        return;
961b3c61 Andy McCall 694
    }
695
    send_json(fd, 404, "{\"error\":\"not found\"}");
696
}
697
698
static void *server_main(void *arg)
699
{
700
    (void)arg;
701
    for (;;) {
702
        int fd = accept(g_listen_fd, NULL, NULL);
703
        if (fd < 0) {
704
            if (errno == EINTR) continue;
705
            break;
706
        }
707
        handle_conn(fd);
708
        close(fd);
709
    }
710
    return NULL;
711
}
712
713
int retro_control_start(int port, const retro_control_backend_t *backend)
714
{
715
    g_be = backend;
716
    signal(SIGPIPE, SIG_IGN);
717
718
    int fd = socket(AF_INET, SOCK_STREAM, 0);
719
    if (fd < 0) return -1;
720
    int one = 1;
721
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
722
723
    struct sockaddr_in addr;
724
    memset(&addr, 0, sizeof addr);
725
    addr.sin_family = AF_INET;
726
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);   /* 127.0.0.1 only */
727
    addr.sin_port = htons((uint16_t)port);
728
    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
729
        fprintf(stderr, "[retro_control] bind 127.0.0.1:%d failed: %s\n",
730
                port, strerror(errno));
731
        close(fd);
732
        return -1;
733
    }
734
    if (listen(fd, 4) < 0) { close(fd); return -1; }
735
736
    g_listen_fd = fd;
737
    if (pthread_create(&g_thread, NULL, server_main, NULL) != 0) {
738
        close(fd); g_listen_fd = -1; return -1;
739
    }
740
    pthread_detach(g_thread);
741
    fprintf(stderr, "[retro_control] listening on 127.0.0.1:%d (contract %s)\n",
742
            port, RETRO_CONTROL_CONTRACT);
743
    return 0;
744
}
745
746
void retro_control_stop(void)
747
{
748
    if (g_listen_fd >= 0) { close(g_listen_fd); g_listen_fd = -1; }
749
}
750
751
#endif /* !_WIN32 */