Remote: paste the phone clipboard, including images, on the desktop
CI / test (push) Failing after 1m2s
CI / test (push) Failing after 1m2s
- Web UI: Ctrl+V, Ctrl+Shift+V, Shift+Insert (Cmd+V on Mac) and a Paste button send the phone clipboard (text or PNG, up to 16 MB) to the desktop over POST /api/clipboard - chandra-remote passes clipboard data to the compositor in a sealed memfd (clipboard-set-fd), replacing the 4 KB hex clipboard-set line - Compositor: new clipboard-status and input-paste commands; text is typed into the launcher, password dialog and shell popups, otherwise the paste chord is sent (Ctrl+Shift+V in terminals) - Paste data is captured when a paste starts, so a clipboard change mid-transfer can't corrupt it - VNC clipboard text limit raised from 4 KB to 1 MB - Upload endpoints are authorized with the same token check as /ws; the no-header cross-site case is refused with 403
This commit is contained in:
1 parent
8a6d19d16f
commit
d2e00b4658
11 files changed
+853
-68
No files matched your search
+66
-5
@@ -1,3 +1,4 @@
|
||||
#define _GNU_SOURCE /* memfd_create, file seals */
|
||||
#include "remote_internal.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
@@ -121,7 +122,8 @@ void ctl_close(CtlConn *c) {
|
||||
pthread_mutex_unlock(&c->mu);
|
||||
}
|
||||
|
||||
static int ctl_once_locked(CtlConn *c, const char *line, char *reply, size_t reply_cap) {
|
||||
/* `send_fd` (-1 for none) goes along with the first bytes of the line as SCM_RIGHTS. */
|
||||
static int ctl_once_locked(CtlConn *c, const char *line, int send_fd, char *reply, size_t reply_cap) {
|
||||
if (c->fd < 0) {
|
||||
uint64_t now = remote_now_ms();
|
||||
if (now - c->last_try_ms < 250) return -1;
|
||||
@@ -136,7 +138,26 @@ static int ctl_once_locked(CtlConn *c, const char *line, char *reply, size_t rep
|
||||
msg[l] = '\n';
|
||||
size_t sent = 0;
|
||||
while (sent < l + 1) {
|
||||
ssize_t w = send(c->fd, msg + sent, l + 1 - sent, MSG_NOSIGNAL);
|
||||
struct iovec iov = { .iov_base = msg + sent, .iov_len = l + 1 - sent };
|
||||
struct msghdr mh;
|
||||
memset(&mh, 0, sizeof mh);
|
||||
mh.msg_iov = &iov;
|
||||
mh.msg_iovlen = 1;
|
||||
union {
|
||||
struct cmsghdr align;
|
||||
char buf[CMSG_SPACE(sizeof(int))];
|
||||
} cm;
|
||||
if (send_fd >= 0 && sent == 0) {
|
||||
memset(&cm, 0, sizeof cm);
|
||||
mh.msg_control = cm.buf;
|
||||
mh.msg_controllen = sizeof cm.buf;
|
||||
struct cmsghdr *ch = CMSG_FIRSTHDR(&mh);
|
||||
ch->cmsg_level = SOL_SOCKET;
|
||||
ch->cmsg_type = SCM_RIGHTS;
|
||||
ch->cmsg_len = CMSG_LEN(sizeof(int));
|
||||
memcpy(CMSG_DATA(ch), &send_fd, sizeof(int));
|
||||
}
|
||||
ssize_t w = sendmsg(c->fd, &mh, MSG_NOSIGNAL);
|
||||
if (w <= 0) {
|
||||
free(msg);
|
||||
close(c->fd);
|
||||
@@ -188,21 +209,61 @@ static int ctl_once_locked(CtlConn *c, const char *line, char *reply, size_t rep
|
||||
return ok;
|
||||
}
|
||||
|
||||
int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap) {
|
||||
static int ctl_cmd_fd(CtlConn *c, const char *line, int send_fd, char *reply, size_t reply_cap) {
|
||||
pthread_mutex_lock(&c->mu);
|
||||
int r = ctl_once_locked(c, line, reply, reply_cap);
|
||||
int r = ctl_once_locked(c, line, send_fd, reply, reply_cap);
|
||||
if (r < 0) {
|
||||
c->last_try_ms = 0;
|
||||
r = ctl_once_locked(c, line, reply, reply_cap);
|
||||
r = ctl_once_locked(c, line, send_fd, reply, reply_cap);
|
||||
}
|
||||
pthread_mutex_unlock(&c->mu);
|
||||
return r;
|
||||
}
|
||||
|
||||
int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap) {
|
||||
return ctl_cmd_fd(c, line, -1, reply, reply_cap);
|
||||
}
|
||||
|
||||
int ctl_fire(CtlConn *c, const char *line) {
|
||||
return ctl_cmd(c, line, NULL, 0);
|
||||
}
|
||||
|
||||
static int parse_serial(const char *reply, unsigned long *serial) {
|
||||
unsigned long s = 0;
|
||||
if (sscanf(reply, "ok serial=%lu", &s) != 1) return -1;
|
||||
if (serial) *serial = s;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int remote_clipboard_serial(CtlConn *c, unsigned long *serial) {
|
||||
char reply[64] = {0};
|
||||
if (ctl_cmd(c, "clipboard-status", reply, sizeof reply) != 0) return -1;
|
||||
return parse_serial(reply, serial);
|
||||
}
|
||||
|
||||
/* A control line holds at most 4 KB, so the data goes in a sealed memfd passed along with it. */
|
||||
int remote_clipboard_set(CtlConn *c, const char *mime, const void *data, size_t len,
|
||||
unsigned long *serial) {
|
||||
if (len == 0 || len > REMOTE_CLIPBOARD_MAX) return -1;
|
||||
int fd = memfd_create("chandra-remote-clipboard", MFD_CLOEXEC | MFD_ALLOW_SEALING);
|
||||
if (fd < 0) return -1;
|
||||
const uint8_t *p = data;
|
||||
size_t done = 0;
|
||||
while (done < len) {
|
||||
ssize_t w = write(fd, p + done, len - done);
|
||||
if (w < 0 && errno == EINTR) continue;
|
||||
if (w <= 0) { close(fd); return -1; }
|
||||
done += (size_t)w;
|
||||
}
|
||||
fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL);
|
||||
char cmd[96], reply[128] = {0};
|
||||
snprintf(cmd, sizeof cmd, "clipboard-set-fd %s %zu", mime, len);
|
||||
int r = ctl_cmd_fd(c, cmd, fd, reply, sizeof reply);
|
||||
close(fd);
|
||||
if (r != 0) return -1;
|
||||
return parse_serial(reply, serial);
|
||||
}
|
||||
|
||||
void remote_osk_suppress_acquire(RemoteApp *app, int *client_flag) {
|
||||
if (*client_flag) return;
|
||||
pthread_mutex_lock(&app->osk_mu);
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
#include "chandra_fb_shm.h"
|
||||
|
||||
#define REMOTE_CLIPBOARD_MAX (16u * 1024u * 1024u)
|
||||
|
||||
#define REMOTE_AUTH_NONE 0
|
||||
#define REMOTE_AUTH_PASSWORD 1
|
||||
|
||||
@@ -78,6 +80,12 @@ void ctl_init(CtlConn *c, const char *sock_path);
|
||||
void ctl_close(CtlConn *c);
|
||||
int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap);
|
||||
int ctl_fire(CtlConn *c, const char *line);
|
||||
/* Put `len` bytes on the phone's clipboard as `mime` ("text/plain" or "image/png"); the new
|
||||
clipboard serial goes to `serial` (may be NULL). 0, or -1 when the compositor refused. */
|
||||
int remote_clipboard_set(CtlConn *c, const char *mime, const void *data, size_t len,
|
||||
unsigned long *serial);
|
||||
/* Current clipboard serial: it changes whenever something is put on the clipboard. */
|
||||
int remote_clipboard_serial(CtlConn *c, unsigned long *serial);
|
||||
void remote_osk_suppress_acquire(RemoteApp *app, int *client_flag);
|
||||
void remote_osk_suppress_release(RemoteApp *app, int *client_flag);
|
||||
void remote_osk_manual_override(RemoteApp *app);
|
||||
|
||||
+2
-11
@@ -571,7 +571,7 @@ static int rfb_handle_message(RfbClient *c) {
|
||||
uint8_t hdr[7];
|
||||
if (read_exact(c->fd, hdr, 7) < 0) return -1;
|
||||
uint32_t len = get_be32(hdr + 3);
|
||||
uint32_t take = len > 32768u ? 32768u : len;
|
||||
uint32_t take = len > 1024u * 1024u ? 1024u * 1024u : len;
|
||||
uint8_t *txt = take ? malloc(take) : NULL;
|
||||
if (take && !txt) return -1;
|
||||
if (take && read_exact(c->fd, txt, take) < 0) { free(txt); return -1; }
|
||||
@@ -582,16 +582,7 @@ static int rfb_handle_message(RfbClient *c) {
|
||||
if (read_exact(c->fd, drain, chunk) < 0) { free(txt); return -1; }
|
||||
rem -= (uint32_t)chunk;
|
||||
}
|
||||
if (take > 0) {
|
||||
size_t clen = take > 4096u ? 4096u : take;
|
||||
char *cmd = malloc(16 + clen * 2 + 1);
|
||||
if (cmd) {
|
||||
memcpy(cmd, "clipboard-set ", 14);
|
||||
hex_encode(txt, clen, cmd + 14);
|
||||
ctl_fire(&c->app->ctl, cmd);
|
||||
free(cmd);
|
||||
}
|
||||
}
|
||||
if (take > 0) remote_clipboard_set(&c->app->ctl, "text/plain", txt, take, NULL);
|
||||
free(txt);
|
||||
break;
|
||||
}
|
||||
|
||||
+72
-2
@@ -199,6 +199,8 @@ class MockCtlServer:
|
||||
self.screen = "on"
|
||||
self.brightness = 75
|
||||
self.osk = 1
|
||||
self.clip_serial = 0
|
||||
self.clips = [] # (mime, bytes) put on the clipboard
|
||||
self.th = threading.Thread(target=self._serve, daemon=True)
|
||||
self.th.start()
|
||||
|
||||
@@ -215,11 +217,13 @@ class MockCtlServer:
|
||||
|
||||
def _client(self, conn: socket.socket):
|
||||
buf = b""
|
||||
files = []
|
||||
while self.running:
|
||||
try:
|
||||
data = conn.recv(4096)
|
||||
data, fds, _, _ = socket.recv_fds(conn, 4096, 4)
|
||||
except OSError:
|
||||
break
|
||||
files += fds
|
||||
if not data:
|
||||
break
|
||||
buf += data
|
||||
@@ -244,6 +248,15 @@ class MockCtlServer:
|
||||
elif cmd == "osk on":
|
||||
self.osk = 1
|
||||
rep = "ok on\n"
|
||||
elif cmd == "clipboard-status":
|
||||
rep = f"ok serial={self.clip_serial}\n"
|
||||
elif cmd.startswith("clipboard-set-fd "):
|
||||
_, mime, size = cmd.split(" ")
|
||||
fd = files.pop(0)
|
||||
self.clips.append((mime, os.pread(fd, int(size) + 1, 0)))
|
||||
os.close(fd)
|
||||
self.clip_serial += 1
|
||||
rep = f"ok serial={self.clip_serial}\n"
|
||||
elif cmd == "osk toggle":
|
||||
self.osk = 0 if self.osk else 1
|
||||
rep = f"ok {'on' if self.osk else 'off'}\n"
|
||||
@@ -523,7 +536,7 @@ class RemoteTests(unittest.TestCase):
|
||||
self.assertIn("input-scroll 0 -30 -1", cmds)
|
||||
self.assertIn("input-key 30 1", cmds)
|
||||
self.assertIn("input-text c3a9", cmds)
|
||||
self.assertIn("clipboard-set " + cut.hex(), cmds)
|
||||
self.assertEqual(self.ctl.clips, [("text/plain", cut)])
|
||||
|
||||
def test_03_vnc_password_and_zlib(self):
|
||||
self.shm.write_frame(64, 48, lambda x, y: (10, 200, 220))
|
||||
@@ -761,6 +774,63 @@ class RemoteTests(unittest.TestCase):
|
||||
time.sleep(0.15)
|
||||
self.assertEqual(self.ctl.osk, 1)
|
||||
|
||||
def clip_request(self, method, body=None, headers=None):
|
||||
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5)
|
||||
c.request(method, "/api/clipboard", body=body, headers=headers or {})
|
||||
r = c.getresponse()
|
||||
out = r.status, json.loads(r.read())
|
||||
c.close()
|
||||
return out
|
||||
|
||||
def test_07_clipboard_upload_and_paste(self):
|
||||
self.shm.write_frame(64, 48, lambda x, y: (1, 2, 3))
|
||||
self.start_daemon(auth="none")
|
||||
png = b"\x89PNG\r\n\x1a\n" + os.urandom(3 * 1024 * 1024)
|
||||
own = {"X-Chandra-Remote": "1"}
|
||||
self.assertEqual(self.clip_request("GET"), (200, {"ok": True, "serial": 0}))
|
||||
st, d = self.clip_request("POST", png, {**own, "Content-Type": "image/png"})
|
||||
self.assertEqual((st, d), (200, {"ok": True, "serial": 1}))
|
||||
text = "líne 1\nline 2 \"q\" \x1b\n".encode() * 500
|
||||
st, d = self.clip_request("POST", text, {**own, "Content-Type": "text/plain;charset=utf-8"})
|
||||
self.assertEqual((st, d), (200, {"ok": True, "serial": 2}))
|
||||
self.assertEqual(self.ctl.clips, [("image/png", png), ("text/plain", text)])
|
||||
|
||||
# Refused: no own-page header (cross-site), other types, not a PNG, empty, too large.
|
||||
self.assertEqual(self.clip_request("POST", b"x", {"Content-Type": "text/plain"})[0], 403)
|
||||
self.assertEqual(self.clip_request("POST", b"x", {**own, "Content-Type": "text/html"})[0], 415)
|
||||
self.assertEqual(self.clip_request("POST", b"not a png", {**own, "Content-Type": "image/png"})[0], 400)
|
||||
self.assertEqual(self.clip_request("POST", b"", {**own, "Content-Type": "text/plain"})[0], 400)
|
||||
big = {**own, "Content-Type": "image/png", "Content-Length": str(16 * 1024 * 1024 + 1)}
|
||||
self.assertEqual(self.clip_request("POST", None, big)[0], 413)
|
||||
self.assertEqual(len(self.ctl.clips), 2)
|
||||
|
||||
ws, status_line, _, _ = ws_connect("127.0.0.1", self.web_port)
|
||||
self.assertIn("101", status_line)
|
||||
ws_send_text(ws, json.dumps({"t": "paste", "c": 47, "m": 5}))
|
||||
ws_send_text(ws, json.dumps({"t": "paste"}))
|
||||
ws_send_text(ws, json.dumps({"t": "clip", "s": "z" * 5000}))
|
||||
deadline = time.time() + 3.0
|
||||
while time.time() < deadline and len(self.ctl.clips) < 3:
|
||||
time.sleep(0.02)
|
||||
self.assertIn("input-paste 47 5", self.ctl.commands)
|
||||
self.assertIn("input-paste", self.ctl.commands)
|
||||
self.assertEqual(self.ctl.clips[2], ("text/plain", b"z" * 5000))
|
||||
ws.close()
|
||||
|
||||
def test_08_clipboard_needs_login(self):
|
||||
self.start_daemon(auth="password", password="TestPass99")
|
||||
hdr = {"X-Chandra-Remote": "1", "Content-Type": "text/plain"}
|
||||
self.assertEqual(self.clip_request("GET")[0], 401)
|
||||
self.assertEqual(self.clip_request("POST", b"x", hdr)[0], 401)
|
||||
self.assertEqual(self.clip_request("POST", b"x", {**hdr, "Authorization": "Bearer 1.abc"})[0], 401)
|
||||
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5)
|
||||
c.request("POST", "/api/login", body=json.dumps({"password": "TestPass99"}))
|
||||
tok = json.loads(c.getresponse().read())["token"]
|
||||
c.close()
|
||||
self.assertEqual(self.clip_request("POST", b"x", {**hdr, "Authorization": "Bearer " + tok})[0], 200)
|
||||
self.assertEqual(self.clip_request("POST", b"y", {**hdr, "Cookie": "chandra_remote=" + tok})[0], 200)
|
||||
self.assertEqual(self.ctl.clips, [("text/plain", b"x"), ("text/plain", b"y")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+125
-24
@@ -190,6 +190,22 @@ static int extract_query_token(const char *target, char *out, size_t cap) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Whether the request carries a valid login token (?token=, Authorization: Bearer, or cookie). */
|
||||
static int web_authorized(RemoteApp *app, const RemoteConfig *cfg, const char *target, const char *hdrs) {
|
||||
if (cfg->auth_mode == REMOTE_AUTH_NONE) return 1;
|
||||
char tok[160] = {0}, val[1024] = {0};
|
||||
int ok = extract_query_token(target, tok, sizeof tok);
|
||||
if (!ok && find_header(hdrs, "Authorization", val, sizeof val) &&
|
||||
strncasecmp(val, "Bearer ", 7) == 0 && strlen(val + 7) < sizeof tok) {
|
||||
snprintf(tok, sizeof tok, "%.*s", (int)sizeof tok - 1, val + 7);
|
||||
ok = tok[0] != 0;
|
||||
}
|
||||
if (!ok && find_header(hdrs, "Cookie", val, sizeof val)) {
|
||||
ok = extract_cookie_token(val, tok, sizeof tok);
|
||||
}
|
||||
return ok && web_token_verify(app->hmac_key, tok, (uint64_t)time(NULL));
|
||||
}
|
||||
|
||||
static int ws_send_frame(int fd, uint8_t opcode, const void *data, size_t len) {
|
||||
uint8_t hdr[10];
|
||||
size_t hlen = 2;
|
||||
@@ -478,25 +494,32 @@ static void ws_handle_text(WsState *ws, const char *msg) {
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "text") == 0) {
|
||||
char txt[1024] = {0};
|
||||
if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) {
|
||||
size_t cap = strlen(msg) + 1;
|
||||
char *txt = malloc(cap);
|
||||
if (txt && json_get_str(msg, "s", txt, cap) && txt[0]) {
|
||||
ws_note_key_activity(ws);
|
||||
remote_send_utf8_text(&ws->app->ctl, txt);
|
||||
}
|
||||
free(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);
|
||||
}
|
||||
size_t cap = strlen(msg) + 1;
|
||||
char *txt = malloc(cap);
|
||||
if (txt && json_get_str(msg, "s", txt, cap) && txt[0]) {
|
||||
remote_clipboard_set(&ws->app->ctl, "text/plain", txt, strlen(txt), NULL);
|
||||
}
|
||||
free(txt);
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "paste") == 0) { /* paste the phone's clipboard, by the given chord or the app's usual one */
|
||||
long code = 0, mods = 0;
|
||||
char cmd[64] = "input-paste";
|
||||
if (json_get_int(msg, "c", &code) && code > 0 && json_get_int(msg, "m", &mods) && mods >= 0) {
|
||||
snprintf(cmd, sizeof cmd, "input-paste %ld %ld", code, mods);
|
||||
}
|
||||
ws_note_key_activity(ws);
|
||||
ctl_fire(&ws->app->ctl, cmd);
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "ctl") == 0) {
|
||||
@@ -523,6 +546,81 @@ static void ws_handle_text(WsState *ws, const char *msg) {
|
||||
}
|
||||
}
|
||||
|
||||
/* GET /api/clipboard: the clipboard serial. POST: put the body (text/plain or image/png) on the
|
||||
phone's clipboard. Both answer {"ok":true,"serial":N}. `body`/`have`: what was read already. */
|
||||
static void web_clipboard(RemoteApp *app, int fd, const char *method, const char *hdrs,
|
||||
const char *body, size_t have) {
|
||||
char val[128] = {0}, js[96];
|
||||
const char *status = "400 Bad Request", *err = "Bad request";
|
||||
uint8_t *data = NULL;
|
||||
unsigned long serial = 0;
|
||||
if (strcmp(method, "GET") == 0) {
|
||||
if (remote_clipboard_serial(&app->ctl, &serial) == 0) goto ok;
|
||||
status = "502 Bad Gateway";
|
||||
err = "The desktop did not answer";
|
||||
goto fail;
|
||||
}
|
||||
/* A page from elsewhere can't set this header without a CORS preflight, which is refused. */
|
||||
if (!find_header(hdrs, "X-Chandra-Remote", val, sizeof val)) {
|
||||
status = "403 Forbidden";
|
||||
err = "Forbidden";
|
||||
goto fail;
|
||||
}
|
||||
const char *mime = NULL;
|
||||
if (find_header(hdrs, "Content-Type", val, sizeof val)) {
|
||||
val[strcspn(val, "; \t")] = 0;
|
||||
if (strcasecmp(val, "text/plain") == 0) mime = "text/plain";
|
||||
else if (strcasecmp(val, "image/png") == 0) mime = "image/png";
|
||||
}
|
||||
if (!mime) {
|
||||
status = "415 Unsupported Media Type";
|
||||
err = "Only text and PNG images can be pasted";
|
||||
goto fail;
|
||||
}
|
||||
char *endp = NULL;
|
||||
if (!find_header(hdrs, "Content-Length", val, sizeof val) || !isdigit((unsigned char)val[0])) goto fail;
|
||||
unsigned long long cl = strtoull(val, &endp, 10);
|
||||
if (*endp || cl == 0) goto fail;
|
||||
if (cl > REMOTE_CLIPBOARD_MAX) {
|
||||
status = "413 Content Too Large";
|
||||
err = "Too large (16 MB at most)";
|
||||
goto fail;
|
||||
}
|
||||
size_t len = (size_t)cl;
|
||||
data = malloc(len);
|
||||
if (!data) goto fail;
|
||||
if (have > len) have = len;
|
||||
memcpy(data, body, have);
|
||||
uint64_t deadline = remote_now_ms() + 60000;
|
||||
while (have < len) {
|
||||
struct pollfd pfd = { .fd = fd, .events = POLLIN };
|
||||
if (remote_now_ms() > deadline || poll(&pfd, 1, 10000) <= 0) goto fail;
|
||||
ssize_t r = recv(fd, data + have, len - have, 0);
|
||||
if (r < 0 && errno == EINTR) continue;
|
||||
if (r <= 0) goto fail;
|
||||
have += (size_t)r;
|
||||
}
|
||||
static const uint8_t png_magic[8] = { 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n' };
|
||||
if (strcmp(mime, "image/png") == 0 && (len < 8 || memcmp(data, png_magic, 8) != 0)) {
|
||||
err = "Not a PNG image";
|
||||
goto fail;
|
||||
}
|
||||
if (remote_clipboard_set(&app->ctl, mime, data, len, &serial) != 0) {
|
||||
status = "502 Bad Gateway";
|
||||
err = "The desktop did not take the clipboard";
|
||||
goto fail;
|
||||
}
|
||||
ok:
|
||||
free(data);
|
||||
snprintf(js, sizeof js, "{\"ok\":true,\"serial\":%lu}", serial);
|
||||
http_send(fd, "200 OK", "application/json", NULL, js, strlen(js));
|
||||
return;
|
||||
fail:
|
||||
free(data);
|
||||
snprintf(js, sizeof js, "{\"ok\":false,\"error\":\"%s\"}", err);
|
||||
http_send(fd, status, "application/json", NULL, js, strlen(js));
|
||||
}
|
||||
|
||||
static void ws_loop(RemoteApp *app, int fd) {
|
||||
WsState ws;
|
||||
memset(&ws, 0, sizeof ws);
|
||||
@@ -816,19 +914,22 @@ void web_handle_client(RemoteApp *app, int fd) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (strcmp(path, "/api/clipboard") == 0 && (!strcmp(method, "GET") || !strcmp(method, "POST"))) {
|
||||
if (!web_authorized(app, &cfg, target, buf)) {
|
||||
const char *m = "{\"ok\":false,\"error\":\"Unauthorized\"}";
|
||||
http_send(fd, "401 Unauthorized", "application/json", NULL, m, strlen(m));
|
||||
} else {
|
||||
web_clipboard(app, fd, method, buf, body, body_have);
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (!web_authorized(app, &cfg, target, buf)) {
|
||||
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 ||
|
||||
|
||||
+292
-8
@@ -87,6 +87,20 @@
|
||||
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
|
||||
opacity: 0; border: 0; padding: 0; font-size: 16px;
|
||||
}
|
||||
#pasteSink {
|
||||
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
|
||||
overflow: hidden; opacity: 0; outline: 0;
|
||||
user-select: text; -webkit-user-select: text;
|
||||
}
|
||||
#toast {
|
||||
position: fixed; left: 50%; bottom: calc(64px + env(safe-area-inset-bottom));
|
||||
transform: translateX(-50%); z-index: 40; display: none;
|
||||
max-width: calc(100vw - 32px); padding: 8px 14px; border-radius: 999px;
|
||||
background: var(--panel); border: 1px solid var(--border);
|
||||
font-size: 13px; pointer-events: none;
|
||||
}
|
||||
#toast.open { display: block; }
|
||||
#toast.err { border-color: var(--err); }
|
||||
#loginMask {
|
||||
position: fixed; inset: 0; z-index: 50; display: none;
|
||||
align-items: center; justify-content: center; padding: 20px;
|
||||
@@ -142,6 +156,7 @@
|
||||
</div>
|
||||
<div class="row">
|
||||
<button id="clipBtn" class="btn">Send Clipboard</button>
|
||||
<button id="imgBtn" class="btn">Paste Image…</button>
|
||||
<button id="fsBtn" class="btn">Fullscreen</button>
|
||||
<button class="btn" data-ctl="refresh">Redraw</button>
|
||||
</div>
|
||||
@@ -169,6 +184,9 @@
|
||||
<button id="kbHideBtn" class="btn">Done</button>
|
||||
</div>
|
||||
<input id="kbdInput" type="text" value=" " autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
|
||||
<div id="pasteSink" contenteditable="true" inputmode="none" tabindex="-1" aria-hidden="true"></div>
|
||||
<input id="imgInput" type="file" accept="image/*" hidden>
|
||||
<div id="toast" role="status"></div>
|
||||
|
||||
<div id="loginMask">
|
||||
<form id="loginForm" class="card">
|
||||
@@ -202,6 +220,9 @@
|
||||
const loginForm = document.getElementById('loginForm');
|
||||
const passInput = document.getElementById('passInput');
|
||||
const loginErr = document.getElementById('loginErr');
|
||||
const pasteSink = document.getElementById('pasteSink');
|
||||
const imgInput = document.getElementById('imgInput');
|
||||
const toastEl = document.getElementById('toast');
|
||||
|
||||
let ws = null;
|
||||
let token = localStorage.getItem('chandra_remote_token') || '';
|
||||
@@ -214,7 +235,20 @@
|
||||
let keyHandled = false;
|
||||
let lastPtrSent = 0;
|
||||
|
||||
/* While a paste is uploading, typing waits for it, so "Ctrl+V, Enter" arrives in that order. */
|
||||
const HELD_WHILE_PASTING = new Set(['key', 'ktap', 'text', 'release']);
|
||||
let pastesInFlight = 0;
|
||||
let heldMessages = [];
|
||||
|
||||
function sendJson(obj) {
|
||||
if (pastesInFlight > 0 && HELD_WHILE_PASTING.has(obj.t)) {
|
||||
heldMessages.push(obj);
|
||||
return;
|
||||
}
|
||||
sendNow(obj);
|
||||
}
|
||||
|
||||
function sendNow(obj) {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(obj));
|
||||
}
|
||||
@@ -308,6 +342,7 @@
|
||||
|
||||
sock.onopen = () => {
|
||||
setStatusDot('ok', 'Connected');
|
||||
noteClipboardBase();
|
||||
loginMask.classList.remove('open');
|
||||
};
|
||||
sock.onmessage = (ev) => {
|
||||
@@ -572,6 +607,7 @@
|
||||
if (loginMask.classList.contains('open')) return;
|
||||
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
|
||||
if (e.isComposing || e.key === 'Unidentified' || e.key === 'Process' || e.key === 'Dead') return;
|
||||
if (beginKeyPaste(e)) return;
|
||||
const sym = eventToKeysym(e);
|
||||
if (sym !== null) {
|
||||
e.preventDefault();
|
||||
@@ -599,10 +635,241 @@
|
||||
});
|
||||
|
||||
window.addEventListener('blur', releaseAllKeys);
|
||||
window.addEventListener('focus', noteClipboardBase);
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) releaseAllKeys();
|
||||
else noteClipboardBase();
|
||||
});
|
||||
|
||||
/* ---- Paste: this device's clipboard (text or image) into the phone ----
|
||||
The paste keys put the local clipboard on the phone's, then send the same keys there. The
|
||||
clipboard comes from the browser's paste event, which needs no permission and works over
|
||||
plain HTTP. Something copied on the phone since this page was focused is newer than the
|
||||
local clipboard, and is pasted as it is. */
|
||||
const PASTE_MAX = 16 * 1024 * 1024;
|
||||
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || '');
|
||||
let clipBase = null; /* phone clipboard serial when this page was last focused */
|
||||
let clipLastSig = null; /* the local clipboard last sent, or passed over for the phone's */
|
||||
let pasteChain = Promise.resolve();
|
||||
let keyPaste = null; /* paste keys pressed, paste event not seen yet */
|
||||
let keyPasteMissed = 0; /* when the last one was given up on */
|
||||
let toastTimer = null;
|
||||
|
||||
function toast(msg, isErr) {
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.classList.toggle('err', !!isErr);
|
||||
toastEl.classList.add('open');
|
||||
toastTimer = setTimeout(() => toastEl.classList.remove('open'), isErr ? 5000 : 1800);
|
||||
}
|
||||
|
||||
async function clipboardApi(method, type, body) {
|
||||
const headers = { 'X-Chandra-Remote': '1' };
|
||||
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||||
if (type) headers['Content-Type'] = type;
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), method === 'GET' ? 4000 : 45000);
|
||||
try {
|
||||
const r = await fetch('/api/clipboard', { method, headers, body, cache: 'no-store', signal: ctl.signal });
|
||||
const d = await r.json();
|
||||
if (!r.ok || !d.ok) throw new Error(d.error || ('HTTP ' + r.status));
|
||||
return d.serial;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function noteClipboardBase() {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
pasteChain = pasteChain.then(async () => {
|
||||
try {
|
||||
const s = await clipboardApi('GET');
|
||||
if (clipBase !== null && s < clipBase) clipLastSig = null; /* the desktop restarted */
|
||||
clipBase = s;
|
||||
} catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
/* {type, blob, text, sig} of some text or an image file; images become PNG. */
|
||||
async function makePayload(text, image) {
|
||||
let blob, type;
|
||||
if (image) {
|
||||
type = 'image/png';
|
||||
blob = image;
|
||||
if (image.type !== 'image/png') {
|
||||
let bmp;
|
||||
try {
|
||||
bmp = await createImageBitmap(image);
|
||||
} catch (_) {
|
||||
throw new Error('This image format can\'t be read');
|
||||
}
|
||||
const cv = document.createElement('canvas');
|
||||
cv.width = bmp.width;
|
||||
cv.height = bmp.height;
|
||||
cv.getContext('2d').drawImage(bmp, 0, 0);
|
||||
bmp.close();
|
||||
blob = await new Promise(res => cv.toBlob(res, 'image/png'));
|
||||
if (!blob) throw new Error('This image is too big');
|
||||
}
|
||||
} else {
|
||||
type = 'text/plain';
|
||||
blob = new Blob([text.replace(/\r\n?/g, '\n')], { type });
|
||||
}
|
||||
if (blob.size > PASTE_MAX) throw new Error('Too large to paste (16 MB at most)');
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < bytes.length; i++) h = Math.imul(h ^ bytes[i], 0x01000193);
|
||||
return { type, blob, text, sig: type + ':' + bytes.length + ':' + (h >>> 0) };
|
||||
}
|
||||
|
||||
/* Send it to the phone's clipboard, unless (not `force`) the phone's own is the one to paste. */
|
||||
async function syncClipboard(p, force) {
|
||||
if (!force) {
|
||||
if (p.sig === clipLastSig) return false;
|
||||
if (clipBase !== null && await clipboardApi('GET') !== clipBase) {
|
||||
clipLastSig = p.sig;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
clipBase = await clipboardApi('POST', p.type, p.blob);
|
||||
clipLastSig = p.sig;
|
||||
if (p.type === 'image/png') {
|
||||
const kb = p.blob.size / 1024;
|
||||
toast('Image sent (' + (kb < 1024 ? Math.ceil(kb) + ' KB' : (kb / 1024).toFixed(1) + ' MB') + ')');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function holdTyping() { pastesInFlight++; }
|
||||
function releaseTyping() {
|
||||
if (--pastesInFlight > 0) return;
|
||||
const queue = heldMessages;
|
||||
heldMessages = [];
|
||||
queue.forEach(sendNow);
|
||||
}
|
||||
|
||||
/* Paste text or an image. `chord` is {c, m} (evdev code, modifiers), or null for whatever the
|
||||
focused app uses. Typing must be held by the caller; it is released here. */
|
||||
function runPaste(text, image, chord, force) {
|
||||
pasteChain = pasteChain.then(async () => {
|
||||
let p = null;
|
||||
try {
|
||||
if (text || image) {
|
||||
p = await makePayload(text, image);
|
||||
await syncClipboard(p, force);
|
||||
}
|
||||
sendNow(chord ? { t: 'paste', c: chord.c, m: chord.m } : { t: 'paste' });
|
||||
} catch (err) {
|
||||
/* Never paste what was on the phone's clipboard before in its place. */
|
||||
toast('Paste failed: ' + (err.name === 'AbortError' ? 'timed out' : err.message), true);
|
||||
} finally {
|
||||
releaseTyping();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function pasteChord(e) {
|
||||
if (e.altKey) return null;
|
||||
const isV = e.key.toLowerCase() === 'v' || (e.code === 'KeyV' && e.key.charCodeAt(0) > 0x7F);
|
||||
if (isV && (IS_MAC ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey)) {
|
||||
return { c: 47, m: e.shiftKey ? 5 : 4 };
|
||||
}
|
||||
if (!IS_MAC && e.key === 'Insert' && e.shiftKey && !e.ctrlKey && !e.metaKey) return { c: 110, m: 1 };
|
||||
return null;
|
||||
}
|
||||
|
||||
/* A paste key press: let the browser do its paste, into the sink, and pick up the event. */
|
||||
function beginKeyPaste(e) {
|
||||
const chord = pasteChord(e);
|
||||
if (!chord) return false;
|
||||
if (e.repeat || keyPaste) {
|
||||
e.preventDefault();
|
||||
return true;
|
||||
}
|
||||
if (IS_MAC) {
|
||||
/* Command is held on the phone as Super: let go of it, without it counting as a Super tap. */
|
||||
for (const [id, sym] of [...pressedKeys]) {
|
||||
if (sym === 0xFFEB || sym === 0xFFEC) {
|
||||
pressedKeys.delete(id);
|
||||
sendJson({ t: 'ktap', c: 29, m: 0 });
|
||||
sendJson({ t: 'key', k: sym, d: 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
const back = document.activeElement === kbdInput ? kbdInput : null;
|
||||
holdTyping();
|
||||
pasteSink.textContent = '';
|
||||
pasteSink.focus({ preventScroll: true });
|
||||
keyPaste = {
|
||||
chord, back,
|
||||
timer: setTimeout(() => {
|
||||
/* No paste event (nothing the browser can paste): the phone's own clipboard then. */
|
||||
const k = endKeyPaste();
|
||||
keyPasteMissed = performance.now();
|
||||
runPaste('', null, k.chord, false);
|
||||
}, 600)
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
function endKeyPaste() {
|
||||
const k = keyPaste;
|
||||
keyPaste = null;
|
||||
clearTimeout(k.timer);
|
||||
pasteSink.textContent = '';
|
||||
if (k.back) k.back.focus();
|
||||
else pasteSink.blur();
|
||||
return k;
|
||||
}
|
||||
|
||||
function pickFromTransfer(dt) {
|
||||
let image = null;
|
||||
for (const it of dt ? dt.items : []) {
|
||||
if (it.kind === 'file' && it.type.startsWith('image/')) { image = it.getAsFile(); break; }
|
||||
}
|
||||
let text = dt ? dt.getData('text/plain') : '';
|
||||
/* A copied image file also comes with its name or path as text. */
|
||||
if (image && text && image.name && text.trim().endsWith(image.name) && !text.trim().includes('\n')) text = '';
|
||||
return text ? [text, null] : ['', image];
|
||||
}
|
||||
|
||||
document.addEventListener('paste', (e) => {
|
||||
if (loginMask.classList.contains('open') || e.target === passInput) return;
|
||||
e.preventDefault();
|
||||
const [text, image] = pickFromTransfer(e.clipboardData);
|
||||
if (keyPaste) {
|
||||
const k = endKeyPaste();
|
||||
runPaste(text, image, k.chord, false);
|
||||
} else if (performance.now() - keyPasteMissed > 2000 && (text || image)) {
|
||||
holdTyping();
|
||||
runPaste(text, image, null, true); /* the browser's own Paste menu item */
|
||||
}
|
||||
});
|
||||
|
||||
/* For the buttons: [text, image] from the async clipboard API, or text asked for. */
|
||||
async function readLocalClipboard(question) {
|
||||
if (navigator.clipboard && navigator.clipboard.read) {
|
||||
try {
|
||||
const items = await navigator.clipboard.read();
|
||||
for (const it of items) {
|
||||
if (it.types.includes('text/plain')) {
|
||||
const t = await (await it.getType('text/plain')).text();
|
||||
if (t) return [t, null];
|
||||
}
|
||||
}
|
||||
for (const it of items) {
|
||||
const ty = it.types.find(x => x.startsWith('image/'));
|
||||
if (ty) return ['', await it.getType(ty)];
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
try {
|
||||
const t = await navigator.clipboard.readText();
|
||||
if (t) return [t, null];
|
||||
} catch (_) {}
|
||||
return [prompt(question) || '', null];
|
||||
}
|
||||
|
||||
/* ---- Android Gboard sentinel-space keyboard bridge ---- */
|
||||
function setKbOpen(open) {
|
||||
kbOpen = open;
|
||||
@@ -660,6 +927,7 @@
|
||||
|
||||
kbdInput.addEventListener('keydown', (e) => {
|
||||
keyHandled = false;
|
||||
if (beginKeyPaste(e)) return;
|
||||
const map = {
|
||||
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
|
||||
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
|
||||
@@ -751,17 +1019,33 @@
|
||||
});
|
||||
|
||||
document.getElementById('clipBtn').addEventListener('click', async () => {
|
||||
let txt = '';
|
||||
try { txt = await navigator.clipboard.readText(); } catch (_) {}
|
||||
if (!txt) txt = prompt('Text to copy to phone clipboard:') || '';
|
||||
if (txt) sendJson({ t: 'clip', s: txt });
|
||||
const [text, image] = await readLocalClipboard('Text to copy to phone clipboard:');
|
||||
if (!text && !image) return;
|
||||
try {
|
||||
const p = await makePayload(text, image);
|
||||
await syncClipboard(p, true);
|
||||
if (!image) toast('Clipboard sent');
|
||||
} catch (err) {
|
||||
toast('Send failed: ' + err.message, true);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('imgBtn').addEventListener('click', () => imgInput.click());
|
||||
imgInput.addEventListener('change', () => {
|
||||
const f = imgInput.files[0];
|
||||
imgInput.value = '';
|
||||
if (!f) return;
|
||||
drawer.classList.remove('open');
|
||||
holdTyping();
|
||||
runPaste('', f, null, true);
|
||||
});
|
||||
|
||||
document.getElementById('pasteBtn').addEventListener('click', async () => {
|
||||
let txt = '';
|
||||
try { txt = await navigator.clipboard.readText(); } catch (_) {}
|
||||
if (!txt) txt = prompt('Text to type on phone:') || '';
|
||||
if (txt) sendJson({ t: 'text', s: txt });
|
||||
const [text, image] = await readLocalClipboard('Text to paste on phone:');
|
||||
if (text || image) {
|
||||
holdTyping();
|
||||
runPaste(text, image, null, true);
|
||||
}
|
||||
kbdInput.focus();
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user