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