Files
chandra/remote/web.c
T
nandiandClaude Opus 5.5 0356413bb2
CI / test (push) Failing after 1m7s
Remote: forward the physical keyboard and hide the phone OSK while typing
The web UI now sends key events without opening the KB bar, and releases
held keys on blur, hide or disconnect. The first remote keystroke (web or
VNC) turns the on-screen keyboard off; it comes back when the last typing
client disconnects, unless the user toggled it by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:27:17 -08:00

860 lines
27 KiB
C

#include "remote_internal.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <turbojpeg.h>
#include <unistd.h>
static int write_all_fd(int fd, const void *buf, size_t len) {
const uint8_t *p = (const uint8_t *)buf;
size_t done = 0;
while (done < len) {
ssize_t w = send(fd, p + done, len - done, MSG_NOSIGNAL);
if (w < 0) {
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
struct pollfd pfd = { .fd = fd, .events = POLLOUT };
if (poll(&pfd, 1, 5000) <= 0) return -1;
continue;
}
return -1;
}
if (w == 0) return -1;
done += (size_t)w;
}
return 0;
}
static void http_send(int fd, const char *status, const char *ctype, const char *extra_hdr,
const void *body, size_t blen) {
char hdr[1024];
int n = snprintf(hdr, sizeof hdr,
"HTTP/1.1 %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %zu\r\n"
"Cache-Control: no-store\r\n"
"Connection: close\r\n"
"%s\r\n",
status, ctype, blen, extra_hdr ? extra_hdr : "");
if (n > 0) write_all_fd(fd, hdr, (size_t)n);
if (blen > 0) write_all_fd(fd, body, blen);
}
static int serve_static(int fd, const char *web_dir, const char *name, const char *ctype) {
char path[600];
snprintf(path, sizeof path, "%s/%s", web_dir, name);
int f = open(path, O_RDONLY | O_CLOEXEC);
if (f < 0) {
const char *msg = "Not found";
http_send(fd, "404 Not Found", "text/plain", NULL, msg, strlen(msg));
return -1;
}
struct stat st;
if (fstat(f, &st) < 0 || st.st_size < 0 || st.st_size > 2 * 1024 * 1024) {
close(f);
const char *msg = "Error reading file";
http_send(fd, "500 Internal Server Error", "text/plain", NULL, msg, strlen(msg));
return -1;
}
size_t len = (size_t)st.st_size;
uint8_t *buf = len ? malloc(len) : NULL;
if (len && !buf) { close(f); return -1; }
size_t got = 0;
while (got < len) {
ssize_t r = read(f, buf + got, len - got);
if (r <= 0) break;
got += (size_t)r;
}
close(f);
http_send(fd, "200 OK", ctype, NULL, buf, got);
free(buf);
return 0;
}
/* Extract a JSON string value for key `"key":"..."` safely (handles escapes). */
static int json_get_str(const char *json, const char *key, char *out, size_t cap) {
char pat[64];
snprintf(pat, sizeof pat, "\"%s\"", key);
const char *p = json;
while ((p = strstr(p, pat)) != NULL) {
const char *q = p + strlen(pat);
while (*q && isspace((unsigned char)*q)) q++;
if (*q != ':') { p++; continue; }
q++;
while (*q && isspace((unsigned char)*q)) q++;
if (*q != '"') return 0;
q++;
size_t o = 0;
while (*q && *q != '"') {
char ch = *q++;
if (ch == '\\' && *q) {
char esc = *q++;
if (esc == 'n') ch = '\n';
else if (esc == 'r') ch = '\r';
else if (esc == 't') ch = '\t';
else ch = esc;
}
if (o + 1 < cap) out[o++] = ch;
}
out[o] = 0;
return *q == '"';
}
return 0;
}
static int json_get_int(const char *json, const char *key, long *out) {
char pat[64];
snprintf(pat, sizeof pat, "\"%s\"", key);
const char *p = json;
while ((p = strstr(p, pat)) != NULL) {
const char *q = p + strlen(pat);
while (*q && isspace((unsigned char)*q)) q++;
if (*q != ':') { p++; continue; }
q++;
while (*q && isspace((unsigned char)*q)) q++;
if (*q != '-' && !isdigit((unsigned char)*q)) return 0;
char *endp = NULL;
long v = strtol(q, &endp, 10);
if (endp == q) return 0;
*out = v;
return 1;
}
return 0;
}
static const char *find_header(const char *hdrs, const char *name, char *val, size_t cap) {
size_t nlen = strlen(name);
const char *line = strstr(hdrs, "\r\n");
if (!line) return NULL;
line += 2;
while (*line && !(line[0] == '\r' && line[1] == '\n')) {
const char *eol = strstr(line, "\r\n");
const char *next = eol ? eol + 2 : NULL;
if (!eol) eol = line + strlen(line);
if (strncasecmp(line, name, nlen) == 0 && line[nlen] == ':') {
const char *v = line + nlen + 1;
while (v < eol && (*v == ' ' || *v == '\t')) v++;
const char *ve = eol;
while (ve > v && (ve[-1] == ' ' || ve[-1] == '\t')) ve--;
size_t l = (size_t)(ve - v);
if (l >= cap) l = cap - 1;
memcpy(val, v, l);
val[l] = 0;
return val;
}
if (!next) break;
line = next;
}
return NULL;
}
static int extract_cookie_token(const char *cookie, char *out, size_t cap) {
if (!cookie) return 0;
const char *p = cookie;
while ((p = strstr(p, "chandra_remote=")) != NULL) {
p += 15;
const char *e = p;
while (*e && *e != ';' && !isspace((unsigned char)*e)) e++;
size_t l = (size_t)(e - p);
if (l > 0 && l < cap) {
memcpy(out, p, l);
out[l] = 0;
return 1;
}
}
return 0;
}
static int extract_query_token(const char *target, char *out, size_t cap) {
const char *q = strchr(target, '?');
if (!q) return 0;
q++;
const char *p = strstr(q, "token=");
if (!p) return 0;
p += 6;
const char *e = p;
while (*e && *e != '&' && *e != ' ') e++;
size_t l = (size_t)(e - p);
if (l == 0 || l >= cap) return 0;
memcpy(out, p, l);
out[l] = 0;
return 1;
}
static int ws_send_frame(int fd, uint8_t opcode, const void *data, size_t len) {
uint8_t hdr[10];
size_t hlen = 2;
hdr[0] = (uint8_t)(0x80u | (opcode & 0x0Fu));
if (len <= 125) {
hdr[1] = (uint8_t)len;
} else if (len <= 65535) {
hdr[1] = 126;
hdr[2] = (uint8_t)(len >> 8);
hdr[3] = (uint8_t)len;
hlen = 4;
} else {
hdr[1] = 127;
uint64_t l64 = (uint64_t)len;
for (int i = 0; i < 8; i++) hdr[2 + i] = (uint8_t)(l64 >> ((7 - i) * 8));
hlen = 10;
}
if (write_all_fd(fd, hdr, hlen) < 0) return -1;
if (len > 0 && write_all_fd(fd, data, len) < 0) return -1;
return 0;
}
static int ws_send_text(int fd, const char *s) {
return ws_send_frame(fd, 0x01u, s, strlen(s));
}
/* Validate allowlisted `ctl` commands exposed to the mobile Web UI. */
static int ctl_command_allowed(const char *cmd) {
if (strcmp(cmd, "refresh") == 0 || strcmp(cmd, "status") == 0) return 1;
if (strncmp(cmd, "rotate ", 7) == 0) {
const char *a = cmd + 7;
return !strcmp(a, "cw") || !strcmp(a, "ccw") || !strcmp(a, "flip") ||
!strcmp(a, "0") || !strcmp(a, "90") || !strcmp(a, "180") || !strcmp(a, "270");
}
if (strncmp(cmd, "screen ", 7) == 0) {
const char *a = cmd + 7;
return !strcmp(a, "on") || !strcmp(a, "off") || !strcmp(a, "toggle");
}
if (strncmp(cmd, "osk ", 4) == 0) {
const char *a = cmd + 4;
return !strcmp(a, "on") || !strcmp(a, "off") || !strcmp(a, "toggle");
}
if (strncmp(cmd, "shortcut ", 9) == 0) {
const char *a = cmd + 9;
return !strcmp(a, "launcher") || !strcmp(a, "overview") || !strcmp(a, "show-desktop");
}
if (strncmp(cmd, "brightness ", 11) == 0) {
char *endp = NULL;
long v = strtol(cmd + 11, &endp, 10);
return endp && *endp == 0 && v >= 5 && v <= 100;
}
return 0;
}
static int parse_status_json(const char *reply, char *out, size_t cap) {
unsigned int w = 0, h = 0;
int rot = 0, bri = -1, px = 0, py = 0, osk = 0;
char scr[16] = "on";
const char *p = strstr(reply, "ok ");
if (!p) return -1;
if (sscanf(p, "ok %ux%u rot=%d screen=%15s brightness=%d ptr=%d,%d osk=%d",
&w, &h, &rot, scr, &bri, &px, &py, &osk) < 4) {
return -1;
}
snprintf(out, cap,
"{\"t\":\"status\",\"w\":%u,\"h\":%u,\"rot\":%d,\"screen\":\"%s\",\"brightness\":%d,\"osk\":%d}",
w, h, rot, scr, bri, osk);
return 0;
}
typedef struct {
int fd;
RemoteApp *app;
uint32_t held_mods;
uint32_t mod_keys_mask;
uint32_t down_ev[16];
int down_ev_len;
int osk_suppressed;
uint32_t acked_id;
uint32_t next_frame_id;
int quality;
int max_fps;
char last_status_json[256];
} WsState;
static void ws_send_status(WsState *ws) {
char reply[256], js[256];
if (ctl_cmd(&ws->app->ctl, "status", reply, sizeof reply) == 0 &&
parse_status_json(reply, js, sizeof js) == 0) {
if (strcmp(js, ws->last_status_json) != 0) {
snprintf(ws->last_status_json, sizeof ws->last_status_json, "%s", js);
ws_send_text(ws->fd, js);
}
}
}
static uint32_t ws_mods_from_mask(uint32_t m) {
return ((m & 0x03u) ? 1u : 0u) |
((m & 0x0Cu) ? 4u : 0u) |
((m & 0x30u) ? 8u : 0u) |
((m & 0xC0u) ? 64u : 0u);
}
static int ws_mod_evdev_bit(uint32_t ev) {
switch (ev) {
case 42u: return 0;
case 54u: return 1;
case 29u: return 2;
case 97u: return 3;
case 56u: return 4;
case 100u: return 5;
case 125u: return 6;
case 126u: return 7;
default: return -1;
}
}
static void ws_release_all(WsState *ws) {
char cmd[64];
for (int i = 0; i < ws->down_ev_len; i++) {
snprintf(cmd, sizeof cmd, "input-key %u 0", ws->down_ev[i]);
ctl_fire(&ws->app->ctl, cmd);
}
ws->down_ev_len = 0;
static const uint32_t mod_evdevs[8] = { 42u, 54u, 29u, 97u, 56u, 100u, 125u, 126u };
for (int i = 0; i < 8; i++) {
if (ws->mod_keys_mask & (1u << i)) {
snprintf(cmd, sizeof cmd, "input-key %u 0", mod_evdevs[i]);
ctl_fire(&ws->app->ctl, cmd);
}
}
int had_mods = (ws->mod_keys_mask != 0 || ws->held_mods != 0);
ws->mod_keys_mask = 0;
ws->held_mods = 0;
if (had_mods) ctl_fire(&ws->app->ctl, "input-mods 0 0 0 0");
}
static void ws_note_key_activity(WsState *ws) {
if (!ws->osk_suppressed) {
remote_osk_suppress_acquire(ws->app, &ws->osk_suppressed);
ws->last_status_json[0] = 0;
ws_send_status(ws);
}
}
static void ws_handle_text(WsState *ws, const char *msg) {
char type[32] = {0};
if (!json_get_str(msg, "t", type, sizeof type)) return;
if (strcmp(type, "ack") == 0) {
long id = 0;
if (json_get_int(msg, "id", &id) && id >= 0 && (uint32_t)id > ws->acked_id) {
ws->acked_id = (uint32_t)id;
}
return;
}
if (strcmp(type, "ptr") == 0) {
long x = 0, y = 0;
if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) {
char cmd[64];
snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y);
ctl_fire(&ws->app->ctl, cmd);
}
return;
}
if (strcmp(type, "btn") == 0) {
long b = 1, d = 0;
if (json_get_int(msg, "b", &b) && json_get_int(msg, "d", &d)) {
unsigned int code = (b == 3) ? 273u : (b == 2) ? 274u : 272u;
char cmd[64];
snprintf(cmd, sizeof cmd, "input-btn %u %d", code, d ? 1 : 0);
ctl_fire(&ws->app->ctl, cmd);
}
return;
}
if (strcmp(type, "tap") == 0) {
long x = 0, y = 0, b = 1;
if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) {
json_get_int(msg, "b", &b);
unsigned int code = (b == 3) ? 273u : (b == 2) ? 274u : 272u;
char cmd[64];
snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y);
ctl_fire(&ws->app->ctl, cmd);
snprintf(cmd, sizeof cmd, "input-btn %u 1", code);
ctl_fire(&ws->app->ctl, cmd);
snprintf(cmd, sizeof cmd, "input-btn %u 0", code);
ctl_fire(&ws->app->ctl, cmd);
}
return;
}
if (strcmp(type, "scroll") == 0) {
long x = 0, y = 0, dx = 0, dy = 0;
if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) {
json_get_int(msg, "dx", &dx);
json_get_int(msg, "dy", &dy);
char cmd[64];
snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y);
ctl_fire(&ws->app->ctl, cmd);
if (dy != 0) {
snprintf(cmd, sizeof cmd, "input-scroll 0 %ld 0", dy);
ctl_fire(&ws->app->ctl, cmd);
}
if (dx != 0) {
snprintf(cmd, sizeof cmd, "input-scroll 1 %ld 0", dx);
ctl_fire(&ws->app->ctl, cmd);
}
}
return;
}
if (strcmp(type, "release") == 0) {
ws_release_all(ws);
return;
}
if (strcmp(type, "ktap") == 0) {
long code = 0, mods = 0;
if (json_get_int(msg, "c", &code) && code > 0) {
ws_note_key_activity(ws);
json_get_int(msg, "m", &mods);
char cmd[64];
snprintf(cmd, sizeof cmd, "input-key-tap %ld %ld", code, mods);
ctl_fire(&ws->app->ctl, cmd);
}
return;
}
if (strcmp(type, "key") == 0) {
long sym = 0, down = 1;
if (!json_get_int(msg, "k", &sym)) return;
json_get_int(msg, "d", &down);
if (down) ws_note_key_activity(ws);
uint32_t ev = 0, uc = 0;
int sh = 0, mod_bit = 0;
if (!keysym_to_evdev((uint32_t)sym, &ev, &sh, &mod_bit, &uc)) return;
if (uc != 0) {
if (down) remote_send_codepoint(&ws->app->ctl, uc);
return;
}
if (mod_bit == 2) { /* CapsLock */
char cmd[64];
snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down ? 1 : 0);
ctl_fire(&ws->app->ctl, cmd);
return;
}
if (mod_bit) {
int bit = ws_mod_evdev_bit(ev);
if (bit >= 0) {
if (down) ws->mod_keys_mask |= (1u << bit);
else ws->mod_keys_mask &= ~(1u << bit);
}
ws->held_mods = ws_mods_from_mask(ws->mod_keys_mask);
char cmd[64];
snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", ws->held_mods);
ctl_fire(&ws->app->ctl, cmd);
snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down ? 1 : 0);
ctl_fire(&ws->app->ctl, cmd);
} else if (ev) {
if (down) {
int found = 0;
for (int i = 0; i < ws->down_ev_len; i++) {
if (ws->down_ev[i] == ev) { found = 1; break; }
}
if (!found && ws->down_ev_len < 16) ws->down_ev[ws->down_ev_len++] = ev;
} else {
for (int i = 0; i < ws->down_ev_len; i++) {
if (ws->down_ev[i] == ev) {
for (int j = i + 1; j < ws->down_ev_len; j++) ws->down_ev[j - 1] = ws->down_ev[j];
ws->down_ev_len--;
break;
}
}
}
uint32_t em = (sym > 0x20 && sym <= 0x7E && (ws->held_mods & ~1u) == 0)
? (sh ? 1u : 0u)
: (ws->held_mods | (sh ? 1u : 0u));
char cmd[64];
if (em != ws->held_mods) {
snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", em);
ctl_fire(&ws->app->ctl, cmd);
}
snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down ? 1 : 0);
ctl_fire(&ws->app->ctl, cmd);
if (em != ws->held_mods) {
snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", ws->held_mods);
ctl_fire(&ws->app->ctl, cmd);
}
}
return;
}
if (strcmp(type, "text") == 0) {
char txt[1024] = {0};
if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) {
ws_note_key_activity(ws);
remote_send_utf8_text(&ws->app->ctl, txt);
}
return;
}
if (strcmp(type, "clip") == 0) {
char txt[2048] = {0};
if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) {
size_t n = strlen(txt);
char *cmd = malloc(16 + n * 2 + 1);
if (cmd) {
memcpy(cmd, "clipboard-set ", 14);
hex_encode((const uint8_t *)txt, n, cmd + 14);
ctl_fire(&ws->app->ctl, cmd);
free(cmd);
}
}
return;
}
if (strcmp(type, "ctl") == 0) {
char cstr[128] = {0};
if (json_get_str(msg, "cmd", cstr, sizeof cstr) && ctl_command_allowed(cstr)) {
if (strncmp(cstr, "osk ", 4) == 0) {
remote_osk_manual_override(ws->app);
ws->osk_suppressed = 1;
}
ctl_fire(&ws->app->ctl, cstr);
ws->last_status_json[0] = 0;
ws_send_status(ws);
}
return;
}
if (strcmp(type, "cfg") == 0) {
long q = 0, fps = 0;
if (json_get_int(msg, "q", &q)) {
ws->quality = q < 20 ? 20 : (q > 95 ? 95 : (int)q);
}
if (json_get_int(msg, "fps", &fps)) {
ws->max_fps = fps < 5 ? 5 : (fps > 60 ? 60 : (int)fps);
}
}
}
static void ws_loop(RemoteApp *app, int fd) {
WsState ws;
memset(&ws, 0, sizeof ws);
ws.fd = fd;
ws.app = app;
ws.next_frame_id = 1;
pthread_mutex_lock(&app->cfg_mu);
ws.quality = app->cfg.jpeg_quality;
ws.max_fps = app->cfg.max_fps;
pthread_mutex_unlock(&app->cfg_mu);
FbReader fb;
fb_reader_init(&fb, app->shm_path);
fb_reader_ping(&fb);
ctl_fire(&app->ctl, "refresh");
tjhandle tj = tjInitCompress();
uint8_t *scratch = NULL, *frame_pkt = NULL;
size_t scratch_cap = 0, pkt_cap = 0;
uint8_t *rx = malloc(65536);
size_t rx_len = 0, rx_cap = 65536;
if (!rx) goto out;
uint64_t last_seq = 0, last_send_ms = 0, last_ping = 0, last_status_ms = 0;
uint32_t last_w = 0, last_h = 0;
ws_send_status(&ws);
while (*app->running) {
uint64_t now = remote_now_ms();
if (now - last_ping >= 250) {
fb_reader_ping(&fb);
last_ping = now;
}
if (now - last_status_ms >= 2000) {
ws_send_status(&ws);
last_status_ms = now;
}
struct pollfd pfd = { .fd = fd, .events = POLLIN };
int pr = poll(&pfd, 1, 16);
if (pr < 0) {
if (errno == EINTR) continue;
break;
}
if (pr > 0) {
if (pfd.revents & (POLLHUP | POLLERR)) break;
if (pfd.revents & POLLIN) {
if (rx_len == rx_cap) {
if (rx_cap >= 1024 * 1024) break;
uint8_t *nrx = realloc(rx, rx_cap * 2);
if (!nrx) break;
rx = nrx;
rx_cap *= 2;
}
ssize_t r = recv(fd, rx + rx_len, rx_cap - rx_len, 0);
if (r <= 0) break;
rx_len += (size_t)r;
while (rx_len >= 2) {
uint8_t b0 = rx[0], b1 = rx[1];
uint8_t op = (uint8_t)(b0 & 0x0Fu);
int masked = (b1 & 0x80u) != 0;
uint64_t plen = (uint64_t)(b1 & 0x7Fu);
size_t pos = 2;
if (plen == 126) {
if (rx_len < 4) break;
plen = ((uint64_t)rx[2] << 8) | rx[3];
pos = 4;
} else if (plen == 127) {
if (rx_len < 10) break;
plen = 0;
for (int i = 0; i < 8; i++) plen = (plen << 8) | rx[2 + i];
pos = 10;
}
if (plen > 512u * 1024u) { rx_len = 0; goto out; }
size_t mlen = masked ? 4 : 0;
if (rx_len < pos + mlen + (size_t)plen) break;
uint8_t mask[4] = {0};
if (masked) memcpy(mask, rx + pos, 4);
uint8_t *payload = rx + pos + mlen;
if (masked) {
for (size_t i = 0; i < (size_t)plen; i++) payload[i] ^= mask[i & 3u];
}
if (op == 0x08u) { /* Close */
ws_send_frame(fd, 0x08u, NULL, 0);
goto out;
} else if (op == 0x09u) { /* Ping */
ws_send_frame(fd, 0x0Au, payload, (size_t)plen);
} else if (op == 0x01u) { /* Text */
char *tmsg = malloc((size_t)plen + 1);
if (tmsg) {
memcpy(tmsg, payload, (size_t)plen);
tmsg[plen] = 0;
ws_handle_text(&ws, tmsg);
free(tmsg);
}
}
size_t total = pos + mlen + (size_t)plen;
memmove(rx, rx + total, rx_len - total);
rx_len -= total;
}
}
}
uint32_t sent_so_far = ws.next_frame_id - 1;
uint32_t in_flight = sent_so_far > ws.acked_id ? sent_so_far - ws.acked_id : 0;
if (in_flight >= 2) continue;
now = remote_now_ms();
uint64_t min_gap = (uint64_t)(1000 / (ws.max_fps > 0 ? ws.max_fps : 30));
if (last_seq != 0 && now - last_send_ms < min_gap) continue;
int full = 0, x0 = 0, y0 = 0, x1 = 0, y1 = 0;
uint32_t fb_w = 0, fb_h = 0;
uint64_t new_seq = 0;
int got = fb_reader_grab(&fb, last_seq, last_w, last_h,
&full, &fb_w, &fb_h, &x0, &y0, &x1, &y1, &new_seq,
&scratch, &scratch_cap);
if (got <= 0) continue;
if (full || fb_w != last_w || fb_h != last_h) {
x0 = 0; y0 = 0; x1 = (int)fb_w; y1 = (int)fb_h;
full = 1;
}
int rw = x1 - x0;
int rh = y1 - y0;
if (rw <= 0 || rh <= 0) {
last_seq = new_seq;
last_w = fb_w;
last_h = fb_h;
continue;
}
if (!tj) break;
const uint8_t *ptr = scratch + ((size_t)y0 * (size_t)fb_w + (size_t)x0) * 4;
unsigned char *jbuf = NULL;
unsigned long jsz = 0;
if (tjCompress2(tj, ptr, rw, (int)fb_w * 4, rh, TJPF_RGBX, &jbuf, &jsz, TJSAMP_420,
ws.quality, TJFLAG_FASTDCT) != 0 || !jbuf || jsz == 0) {
if (jbuf) tjFree(jbuf);
continue;
}
size_t need = 18 + (size_t)jsz;
if (need > pkt_cap) {
uint8_t *np = realloc(frame_pkt, need);
if (!np) { tjFree(jbuf); break; }
frame_pkt = np;
pkt_cap = need;
}
uint32_t fid = ws.next_frame_id++;
frame_pkt[0] = 1;
frame_pkt[1] = full ? 1 : 0;
frame_pkt[2] = (uint8_t)(x0 >> 8); frame_pkt[3] = (uint8_t)x0;
frame_pkt[4] = (uint8_t)(y0 >> 8); frame_pkt[5] = (uint8_t)y0;
frame_pkt[6] = (uint8_t)(rw >> 8); frame_pkt[7] = (uint8_t)rw;
frame_pkt[8] = (uint8_t)(rh >> 8); frame_pkt[9] = (uint8_t)rh;
frame_pkt[10] = (uint8_t)(fb_w >> 8); frame_pkt[11] = (uint8_t)fb_w;
frame_pkt[12] = (uint8_t)(fb_h >> 8); frame_pkt[13] = (uint8_t)fb_h;
frame_pkt[14] = (uint8_t)(fid >> 24);
frame_pkt[15] = (uint8_t)(fid >> 16);
frame_pkt[16] = (uint8_t)(fid >> 8);
frame_pkt[17] = (uint8_t)fid;
memcpy(frame_pkt + 18, jbuf, (size_t)jsz);
tjFree(jbuf);
if (ws_send_frame(fd, 0x02u, frame_pkt, need) < 0) break;
last_seq = new_seq;
last_w = fb_w;
last_h = fb_h;
last_send_ms = now;
}
out:
ws_release_all(&ws);
remote_osk_suppress_release(app, &ws.osk_suppressed);
if (tj) tjDestroy(tj);
fb_reader_close(&fb);
free(scratch);
free(frame_pkt);
free(rx);
}
void web_handle_client(RemoteApp *app, int fd) {
char buf[16384];
size_t len = 0;
char *hdr_end = NULL;
while (len + 1 < sizeof buf) {
struct pollfd pfd = { .fd = fd, .events = POLLIN };
if (poll(&pfd, 1, 5000) <= 0) { close(fd); return; }
ssize_t r = recv(fd, buf + len, sizeof buf - 1 - len, 0);
if (r <= 0) { close(fd); return; }
len += (size_t)r;
buf[len] = 0;
hdr_end = strstr(buf, "\r\n\r\n");
if (hdr_end) break;
}
if (!hdr_end) {
const char *m = "Header too large";
http_send(fd, "431 Request Header Fields Too Large", "text/plain", NULL, m, strlen(m));
close(fd);
return;
}
*hdr_end = 0;
char *body = hdr_end + 4;
size_t body_have = len - (size_t)(body - buf);
char method[16] = {0}, target[512] = {0};
if (sscanf(buf, "%15s %511s", method, target) != 2) {
const char *m = "Bad Request";
http_send(fd, "400 Bad Request", "text/plain", NULL, m, strlen(m));
close(fd);
return;
}
char path[512];
snprintf(path, sizeof path, "%s", target);
char *q = strchr(path, '?');
if (q) *q = 0;
RemoteConfig cfg;
pthread_mutex_lock(&app->cfg_mu);
cfg = app->cfg;
pthread_mutex_unlock(&app->cfg_mu);
if (strcmp(method, "GET") == 0 && (strcmp(path, "/") == 0 || strcmp(path, "/index.html") == 0)) {
serve_static(fd, app->web_dir, "index.html", "text/html; charset=utf-8");
close(fd);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(path, "/manifest.json") == 0) {
serve_static(fd, app->web_dir, "manifest.json", "application/manifest+json; charset=utf-8");
close(fd);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(path, "/icon.svg") == 0) {
serve_static(fd, app->web_dir, "icon.svg", "image/svg+xml");
close(fd);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(path, "/api/info") == 0) {
char js[128];
snprintf(js, sizeof js, "{\"name\":\"Chandra\",\"auth_required\":%s,\"version\":1}",
cfg.auth_mode == REMOTE_AUTH_NONE ? "false" : "true");
http_send(fd, "200 OK", "application/json", NULL, js, strlen(js));
close(fd);
return;
}
if (strcmp(method, "POST") == 0 && strcmp(path, "/api/login") == 0) {
char cl_str[32] = {0};
long cl = 0;
if (find_header(buf, "Content-Length", cl_str, sizeof cl_str)) {
cl = strtol(cl_str, NULL, 10);
}
if (cl < 0 || cl > 4096) {
const char *m = "{\"ok\":false}";
http_send(fd, "400 Bad Request", "application/json", NULL, m, strlen(m));
close(fd);
return;
}
char post[4097];
size_t copy = body_have > (size_t)cl ? (size_t)cl : body_have;
memcpy(post, body, copy);
while (copy < (size_t)cl) {
struct pollfd pfd = { .fd = fd, .events = POLLIN };
if (poll(&pfd, 1, 3000) <= 0) break;
ssize_t r = recv(fd, post + copy, (size_t)cl - copy, 0);
if (r <= 0) break;
copy += (size_t)r;
}
post[copy] = 0;
if (cfg.auth_mode == REMOTE_AUTH_NONE) {
const char *ok = "{\"ok\":true,\"token\":\"\"}";
http_send(fd, "200 OK", "application/json", NULL, ok, strlen(ok));
close(fd);
return;
}
char pass[128] = {0};
if (!json_get_str(post, "password", pass, sizeof pass) ||
!remote_ct_equal(app->hmac_key, pass, cfg.password)) {
const char *err = "{\"ok\":false,\"error\":\"Invalid password\"}";
http_send(fd, "401 Unauthorized", "application/json", NULL, err, strlen(err));
close(fd);
return;
}
char tok[160], ckhdr[256], ok[256];
web_token_sign(app->hmac_key, (uint64_t)time(NULL), tok, sizeof tok);
snprintf(ckhdr, sizeof ckhdr, "Set-Cookie: chandra_remote=%s; HttpOnly; SameSite=Lax; Path=/\r\n", tok);
snprintf(ok, sizeof ok, "{\"ok\":true,\"token\":\"%s\"}", tok);
http_send(fd, "200 OK", "application/json", ckhdr, ok, strlen(ok));
close(fd);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(path, "/ws") == 0) {
if (cfg.auth_mode != REMOTE_AUTH_NONE) {
char tok[160] = {0}, cookie[1024] = {0};
int ok = extract_query_token(target, tok, sizeof tok);
if (!ok && find_header(buf, "Cookie", cookie, sizeof cookie)) {
ok = extract_cookie_token(cookie, tok, sizeof tok);
}
if (!ok || !web_token_verify(app->hmac_key, tok, (uint64_t)time(NULL))) {
const char *m = "Unauthorized";
http_send(fd, "401 Unauthorized", "text/plain", NULL, m, strlen(m));
close(fd);
return;
}
}
char upg[64] = {0}, wskey[128] = {0}, accept[64] = {0};
if (!find_header(buf, "Upgrade", upg, sizeof upg) || strcasecmp(upg, "websocket") != 0 ||
!find_header(buf, "Sec-WebSocket-Key", wskey, sizeof wskey) ||
ws_compute_accept(wskey, accept, sizeof accept) < 0) {
const char *m = "Bad WebSocket Request";
http_send(fd, "400 Bad Request", "text/plain", NULL, m, strlen(m));
close(fd);
return;
}
char resp[256];
int n = snprintf(resp, sizeof resp,
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n\r\n",
accept);
if (n > 0 && write_all_fd(fd, resp, (size_t)n) == 0) {
ws_loop(app, fd);
}
close(fd);
return;
}
const char *m = "Not Found";
http_send(fd, "404 Not Found", "text/plain", NULL, m, strlen(m));
close(fd);
}