Remote: paste the phone clipboard, including images, on the desktop
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:
nandi committed 2026-11-29 15:42:46 -08:00
1 parent 8a6d19d16f
commit d2e00b4658
11 files changed
+849 -64

No files matched your search

+63 -4
View File
@@ -2172,10 +2172,69 @@ pub fn ChandraCompositor::remote_set_clipboard(
self : ChandraCompositor, self : ChandraCompositor,
text : String, text : String,
) -> Unit { ) -> Unit {
self.server.set_own_selection( self.remote_set_clipboard_data("text/plain", @utf8.encode(text))
["text/plain;charset=utf-8", "text/plain", "UTF8_STRING"], }
@utf8.encode(text),
) ///| Put `data` on the compositor's own Wayland clipboard as `mime`: UTF-8 text, or an image.
fn ChandraCompositor::remote_set_clipboard_data(
self : ChandraCompositor,
mime : String,
data : Bytes,
) -> Unit {
let mimes = if mime == "text/plain" {
["text/plain;charset=utf-8", "text/plain", "UTF8_STRING"]
} else {
[mime]
}
self.server.set_own_selection(mimes, data)
}
///| Paste the clipboard. The password dialog and the shell's popups have no paste key of their
/// own, so clipboard text is typed into them as one line. Anything else gets the paste chord:
/// `chord` as (evdev code, modifiers), or the focused app's usual one. True when typed.
pub fn ChandraCompositor::remote_paste(
self : ChandraCompositor,
chord : (UInt, UInt)?,
) -> Bool {
let text = self.server.own_selection_text()
match text {
Some(t) =>
if self.auth is Some(_) || self.shell.popup_open() {
let line = StringBuilder::new()
for ch in @utf8.decode_lossy(t).trim() {
line.write_char(if ch.to_int() < 0x20 { ' ' } else { ch })
}
return self.remote_commit_text(line.to_string())
}
None => ()
}
let (code, mods) = match chord {
Some(c) => c
// Ctrl+V; terminals keep that for themselves and paste text with Ctrl+Shift+V.
None => (47U, if text is Some(_) && self.terminal_focused() { 5U } else { 4U })
}
self.remote_key_tap(code, mods, @sys.monotonic_ms().to_uint())
false
}
///| Whether the window with keyboard focus looks like a terminal, by its app id.
fn ChandraCompositor::terminal_focused(self : ChandraCompositor) -> Bool {
match self.kbd_win {
Some(wid) =>
match self.windows.get(wid) {
Some(w) => {
let id = w.app_id.to_lower()
for s in ["term", "konsole", "console", "foot", "kitty", "alacritty", "ghostty", "ptyxis", "org.kde.kwi"] {
if id.contains(s) {
return true
}
}
false
}
None => false
}
None => false
}
} }
///| Commit UTF-8 text directly to the active popup, Wayland text-input-v3 surface, or desktop; ///| Commit UTF-8 text directly to the active popup, Wayland text-input-v3 surface, or desktop;
+86 -6
View File
@@ -20,10 +20,12 @@
/// The main loop keeps sleeping while idle: the listening socket and the connected clients are /// The main loop keeps sleeping while idle: the listening socket and the connected clients are
/// in `control_fds`, which the loop adds to the fds it waits on. /// in `control_fds`, which the loop adds to the fds it waits on.
///| One connected client: its fd and the bytes of a line not finished yet. ///| One connected client: its fd, the bytes of a line not finished yet, and a file sent along
/// (SCM_RIGHTS) for the command it is writing (-1 when none).
struct ControlClient { struct ControlClient {
fd : Int fd : Int
pending : Array[Byte] pending : Array[Byte]
mut file : Int
} }
///| The listening socket, its path (unlinked on close) and the connected clients. ///| The listening socket, its path (unlinked on close) and the connected clients.
@@ -89,6 +91,7 @@ pub fn ChandraCompositor::stop_control(self : ChandraCompositor) -> Unit {
None => () None => ()
Some(c) => { Some(c) => {
for cl in c.clients { for cl in c.clients {
cl.drop_file()
@sys.close_fd(cl.fd) @sys.close_fd(cl.fd)
} }
@sys.close_fd(c.fd) @sys.close_fd(c.fd)
@@ -112,6 +115,35 @@ pub fn ChandraCompositor::control_fds(self : ChandraCompositor) -> Array[Int] {
} }
} }
///| Close the file the client sent along, if any.
fn ControlClient::drop_file(self : ControlClient) -> Unit {
if self.file >= 0 {
@sys.close_fd(self.file)
self.file = -1
}
}
///| Largest clipboard taken from a file (`clipboard-set-fd`).
let control_max_clipboard : Int = 16 * 1024 * 1024
///| The first `size` bytes of the file `fd`, or None when it is shorter. Read in pieces: on the
/// wasm build every byte of one call is copied as a value of its own.
fn read_fd_bytes(fd : Int, size : Int) -> Bytes? {
let chunk = 512 * 1024
let out : FixedArray[Byte] = FixedArray::make(size, b'\x00')
let mut at = 0
while at < size {
let len = if size - at > chunk { chunk } else { size - at }
let part = @sys.mmap_read_at(fd, at, len)
if part.length() != len {
return None
}
out.blit_from_bytes(at, part, 0, len)
at = at + len
}
Some(Bytes::from_fixedarray(out))
}
///| Longest command line taken; a client sending more without a newline is dropped. ///| Longest command line taken; a client sending more without a newline is dropped.
let control_max_line : Int = 4096 let control_max_line : Int = 4096
@@ -134,7 +166,7 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
if fd < 0 { if fd < 0 {
break break
} }
c.clients.push({ fd, pending: [] }) c.clients.push({ fd, pending: [], file: -1 })
} }
let gone : Array[Int] = [] let gone : Array[Int] = []
let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00') let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00')
@@ -143,7 +175,8 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
while open { while open {
let (n, extra) = @sys.recvmsg_fd(cl.fd, buf, 1024) let (n, extra) = @sys.recvmsg_fd(cl.fd, buf, 1024)
if extra >= 0 { if extra >= 0 {
@sys.close_fd(extra) cl.drop_file()
cl.file = extra
} }
if n == -1 { if n == -1 {
break // nothing more for now break // nothing more for now
@@ -157,7 +190,8 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
if b == b'\n' { if b == b'\n' {
let line = @utf8.decode_lossy(Bytes::from_array(cl.pending)) let line = @utf8.decode_lossy(Bytes::from_array(cl.pending))
cl.pending.clear() cl.pending.clear()
let (out, _) = self.control_command(line) let (out, _) = self.control_command(line, file=cl.file)
cl.drop_file()
let reply = StringBuilder::new() let reply = StringBuilder::new()
for l in out { for l in out {
reply.write_string(l) reply.write_string(l)
@@ -177,6 +211,7 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
} }
} }
if !open { if !open {
cl.drop_file()
gone.push(cl.fd) gone.push(cl.fd)
} }
} }
@@ -275,8 +310,13 @@ fn decode_hex_utf8(s : String) -> String? {
} }
///| Run one control command; the reply lines (the last starts with "ok" or "error") and whether ///| Run one control command; the reply lines (the last starts with "ok" or "error") and whether
/// it succeeded. /// it succeeded. `file` is the file sent along with the command (-1 when none); the caller
pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : String) -> (Array[String], Bool) { /// closes it.
pub fn ChandraCompositor::control_command(
self : ChandraCompositor,
line : String,
file? : Int = -1,
) -> (Array[String], Bool) {
let words : Array[String] = [] let words : Array[String] = []
for w in line.trim(chars=" \t\r").split(" ") { for w in line.trim(chars=" \t\r").split(" ") {
let s = w.to_string() let s = w.to_string()
@@ -831,6 +871,46 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
None => (["error invalid hex"], false) None => (["error invalid hex"], false)
} }
} }
// chandra-remote: `file` holds SIZE bytes to put on the clipboard as MIME.
"clipboard-set-fd" => {
if words.length() != 3 || file < 0 {
return (["error usage: clipboard-set-fd MIME SIZE, with the file sent along"], false)
}
let mime = words[1]
if mime != "text/plain" && mime != "image/png" {
return (["error unsupported type '" + mime + "'"], false)
}
match parse_int_opt(words[2]) {
Some(size) if size > 0 && size <= control_max_clipboard =>
match read_fd_bytes(file, size) {
Some(data) => {
self.remote_set_clipboard_data(mime, data)
(["ok serial=" + self.server.selection_serial.to_string()], true)
}
None => (["error file is shorter than " + words[2] + " bytes"], false)
}
_ => (["error invalid size"], false)
}
}
"clipboard-status" =>
(["ok serial=" + self.server.selection_serial.to_string()], true)
"input-paste" => {
let chord = if words.length() == 3 {
match (parse_uint_opt(words[1]), parse_uint_opt(words[2])) {
(Some(code), Some(mods)) => Some((code, mods))
_ => return (["error invalid paste args"], false)
}
} else if words.length() == 1 {
None
} else {
return (["error usage: input-paste [CODE MODS]"], false)
}
if self.remote_paste(chord) {
(["ok typed"], true)
} else {
(["ok keys"], true)
}
}
other => (["error unknown command '" + other + "' (try: help)"], false) other => (["error unknown command '" + other + "' (try: help)"], false)
} }
} }
+115
View File
@@ -207,3 +207,118 @@ test "remote status, refresh, osk, pointer/key/text/clipboard injection and OLED
assert_false(comp.manual_screen_off) assert_false(comp.manual_screen_off)
comp.close() comp.close()
} }
///| Like `ask` for one command, with `file` sent along.
fn ask_with_file(
comp : @host.ChandraCompositor,
path : String,
line : String,
file : Int,
) -> String raise {
let fd = @sys.unix_connect(path)
assert_true(fd >= 0)
assert_true(@sys.sendmsg_fd(fd, @utf8.encode(line + "\n"), file) > 0)
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let raw : Array[Byte] = []
for _i = 0; _i < 50 && raw.length() == 0; _i = _i + 1 {
comp.step()
if @sys.poll_read(fd, 5) > 0 {
let (n, _) = @sys.recvmsg_fd(fd, buf, 4096)
for i = 0; i < n; i = i + 1 {
raw.push(buf[i])
}
}
}
@sys.close_fd(fd)
@utf8.decode_lossy(Bytes::from_array(raw)).trim().to_string()
}
///|
test "clipboard from a file sent along: images, long text, limits, and paste" {
let (comp, path) = control_comp("clipfd")
assert_eq(ask(comp, path, "clipboard-status"), ["ok serial=0"])
// An image larger than one read of the file.
let size = 700000
let png = Bytes::makei(size, i => (i * 7 % 251).to_byte())
let fd = @sys.memfd_create("clip", size)
assert_eq(@sys.pwrite_bytes(fd, png, 0), size)
assert_eq(
ask_with_file(comp, path, "clipboard-set-fd image/png " + size.to_string(), fd),
"ok serial=1",
)
assert_true(comp.server.owns_selection())
assert_eq(comp.server.own_mimes, ["image/png"])
assert_true(comp.server.own_data == png)
assert_true(comp.server.own_selection_text() is None)
// Refused: no file, a type or size that isn't taken, a file that is too short.
assert_true(ask(comp, path, "clipboard-set-fd image/png 4")[0].has_prefix("error usage"))
assert_eq(
ask_with_file(comp, path, "clipboard-set-fd text/html 4", fd),
"error unsupported type 'text/html'",
)
assert_eq(ask_with_file(comp, path, "clipboard-set-fd image/png 0", fd), "error invalid size")
assert_eq(
ask_with_file(comp, path, "clipboard-set-fd image/png 99999999", fd),
"error invalid size",
)
assert_eq(
ask_with_file(comp, path, "clipboard-set-fd image/png 700001", fd),
"error file is shorter than 700001 bytes",
)
assert_eq(ask(comp, path, "clipboard-status"), ["ok serial=1"])
@sys.close_fd(fd)
// Text: offered as text, and typed into an open popup as one line.
let text = @utf8.encode("fire\nfox\n")
let tfd = @sys.memfd_create("clip", text.length())
ignore(@sys.pwrite_bytes(tfd, text, 0))
assert_eq(
ask_with_file(comp, path, "clipboard-set-fd text/plain " + text.length().to_string(), tfd),
"ok serial=2",
)
@sys.close_fd(tfd)
assert_eq(comp.server.own_selection_text(), Some(text))
assert_eq(ask(comp, path, "input-paste"), ["ok keys"])
assert_eq(ask(comp, path, "input-paste 47 4"), ["ok keys"])
assert_true(ask(comp, path, "input-paste 47")[0].has_prefix("error usage"))
assert_eq(ask(comp, path, "shortcut launcher"), ["ok launcher"])
assert_eq(ask(comp, path, "input-paste 47 4"), ["ok typed"])
assert_true(comp.shell.launcher_open())
comp.close()
}
///|
test "a paste still being written keeps its data when the clipboard changes" {
let (comp, path) = control_comp("clipswap")
// A slow reader: a socket nobody reads from yet, so only part of the data fits.
let sink_path = path + ".sink"
let listener = @sys.unix_listen(sink_path)
let reader = @sys.unix_connect(sink_path)
let writer = @sys.unix_accept(listener)
assert_true(writer >= 0)
let first = Bytes::make(3000000, b'a')
comp.server.set_own_selection(["image/png"], first)
comp.server.transfers.push((writer, comp.server.own_data, 0, @sys.monotonic_ms() + 10000UL))
comp.server.pump_transfers()
assert_eq(comp.server.pending_transfers(), 1)
comp.server.set_own_selection(["image/png"], Bytes::make(10, b'b'))
let buf : FixedArray[Byte] = FixedArray::make(65536, b'\x00')
let mut got = 0
let mut all_first = true
for _i = 0; _i < 2000 && got < first.length(); _i = _i + 1 {
comp.server.pump_transfers()
if @sys.poll_read(reader, 5) > 0 {
let (n, _) = @sys.recvmsg_fd(reader, buf, 65536)
for j = 0; j < n; j = j + 1 {
all_first = all_first && buf[j] == b'a'
}
got = got + n
}
}
assert_eq(got, first.length())
assert_true(all_first)
assert_eq(comp.server.pending_transfers(), 0)
@sys.close_fd(reader)
@sys.close_fd(listener)
@sys.unlink(sink_path)
comp.close()
}
+23 -8
View File
@@ -364,8 +364,11 @@ pub(all) struct WaylandServer {
/// `Some((0, 0))`: its mime types and bytes. /// `Some((0, 0))`: its mime types and bytes.
mut own_mimes : Array[String] mut own_mimes : Array[String]
mut own_data : Bytes mut own_data : Bytes
/// Clipboard pastes of `own_data` still being written: (pipe fd, bytes written, give up at ms). /// Counts every time something was put on the clipboard (by a client or the compositor).
transfers : Array[(Int, Int, UInt64)] mut selection_serial : UInt
/// Clipboard pastes of `own_data` still being written: (pipe fd, the data as it was when the
/// paste began, bytes written, give up at ms).
transfers : Array[(Int, Bytes, Int, UInt64)]
/// CHANDRA_DEBUG_CONFIGURE=1: log each configure, ack and committed buffer size to stderr. /// CHANDRA_DEBUG_CONFIGURE=1: log each configure, ack and committed buffer size to stderr.
mut debug_configure : Bool mut debug_configure : Bool
/// Drag and drop in progress (dnd.mbt), and a drop its target is still taking. /// Drag and drop in progress (dnd.mbt), and a drop its target is still taking.
@@ -405,6 +408,7 @@ pub fn WaylandServer::listen(
popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) }, popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) },
own_mimes: [], own_mimes: [],
own_data: Bytes::from_array([]), own_data: Bytes::from_array([]),
selection_serial: 0U,
transfers: [], transfers: [],
debug_configure: @sys.getenv("CHANDRA_DEBUG_CONFIGURE").length() > 0, debug_configure: @sys.getenv("CHANDRA_DEBUG_CONFIGURE").length() > 0,
drag: None, drag: None,
@@ -937,6 +941,7 @@ fn WaylandServer::dispatch_msg(
self.selection = None self.selection = None
} else { } else {
self.selection = Some((c.client_id, src)) self.selection = Some((c.client_id, src))
self.selection_serial = self.selection_serial + 1U
} }
match old { match old {
Some((ocid, osid)) => Some((ocid, osid)) =>
@@ -976,7 +981,7 @@ fn WaylandServer::dispatch_msg(
// The compositor's own clipboard: write it out a piece at a time (pump_transfers), // The compositor's own clipboard: write it out a piece at a time (pump_transfers),
// so a client that is slow to read can't stall the desktop. // so a client that is slow to read can't stall the desktop.
if self.selection == Some((0U, 0U)) && self.own_mimes.contains(mime) { if self.selection == Some((0U, 0U)) && self.own_mimes.contains(mime) {
self.transfers.push((fd, 0, @sys.monotonic_ms() + 10000UL)) self.transfers.push((fd, self.own_data, 0, @sys.monotonic_ms() + 10000UL))
self.pump_transfers() self.pump_transfers()
} else { } else {
@sys.close_fd(fd) @sys.close_fd(fd)
@@ -2450,6 +2455,7 @@ pub fn WaylandServer::set_own_selection(
self.own_mimes = mime_types self.own_mimes = mime_types
self.own_data = data self.own_data = data
self.selection = Some((0U, 0U)) self.selection = Some((0U, 0U))
self.selection_serial = self.selection_serial + 1U
self.notify_selection() self.notify_selection()
} }
@@ -2458,22 +2464,31 @@ pub fn WaylandServer::owns_selection(self : WaylandServer) -> Bool {
self.selection == Some((0U, 0U)) self.selection == Some((0U, 0U))
} }
///| The text the compositor itself has on the clipboard, if that is what is there.
pub fn WaylandServer::own_selection_text(self : WaylandServer) -> Bytes? {
if self.owns_selection() && self.own_mimes.contains("text/plain;charset=utf-8") {
Some(self.own_data)
} else {
None
}
}
///| Write what the pipes of pending pastes can take without blocking; close the finished ones ///| Write what the pipes of pending pastes can take without blocking; close the finished ones
/// and any a reader stopped taking for ten seconds. /// and any a reader stopped taking for ten seconds.
pub fn WaylandServer::pump_transfers(self : WaylandServer) -> Unit { pub fn WaylandServer::pump_transfers(self : WaylandServer) -> Unit {
if self.transfers.length() == 0 { if self.transfers.length() == 0 {
return return
} }
let total = self.own_data.length()
let now = @sys.monotonic_ms() let now = @sys.monotonic_ms()
let keep : Array[(Int, Int, UInt64)] = [] let keep : Array[(Int, Bytes, Int, UInt64)] = []
for t in self.transfers { for t in self.transfers {
let (fd, sent0, deadline) = t let (fd, data, sent0, deadline) = t
let total = data.length()
let mut sent = sent0 let mut sent = sent0
let mut ok = true let mut ok = true
while sent < total { while sent < total {
let len = if total - sent > 65536 { 65536 } else { total - sent } let len = if total - sent > 65536 { 65536 } else { total - sent }
let n = @sys.write_nonblock(fd, self.own_data[sent:sent + len].to_bytes()) let n = @sys.write_nonblock(fd, data[sent:sent + len].to_bytes())
if n < 0 { if n < 0 {
ok = false ok = false
break break
@@ -2484,7 +2499,7 @@ pub fn WaylandServer::pump_transfers(self : WaylandServer) -> Unit {
sent = sent + n sent = sent + n
} }
if ok && sent < total && now < deadline { if ok && sent < total && now < deadline {
keep.push((fd, sent, deadline)) keep.push((fd, data, sent, deadline))
} else { } else {
@sys.close_fd(fd) @sys.close_fd(fd)
} }
+1
View File
@@ -67,5 +67,6 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux
- [`remote/chandra-remote.c`](../remote/chandra-remote.c) provides a zero-overhead shared-memory framebuffer mirror (`fb.shm` in [`wasmhost/bin/raster_stub.c`](../wasmhost/bin/raster_stub.c)) feeding both: - [`remote/chandra-remote.c`](../remote/chandra-remote.c) provides a zero-overhead shared-memory framebuffer mirror (`fb.shm` in [`wasmhost/bin/raster_stub.c`](../wasmhost/bin/raster_stub.c)) feeding both:
- **VNC (RFB 3.8, port `5900`)** with Tight-JPEG (`libturbojpeg`), Zlib, Raw, dynamic rotation resize (`ExtendedDesktopSize`), clipboard sync, and 1:1 pointer/touch/keyboard input (tested for Android **AVNC**). - **VNC (RFB 3.8, port `5900`)** with Tight-JPEG (`libturbojpeg`), Zlib, Raw, dynamic rotation resize (`ExtendedDesktopSize`), clipboard sync, and 1:1 pointer/touch/keyboard input (tested for Android **AVNC**).
- **Mobile Web UI / PWA (HTTP + WebSocket, port `6080`)** with 1:1 touch gestures (tap, drag, long-press right-click, two-finger scroll/right-click), optional trackpad mode, Android keyboard bridge, live rotation/brightness/OLED-off toggles, and adaptive JPEG streaming. - **Mobile Web UI / PWA (HTTP + WebSocket, port `6080`)** with 1:1 touch gestures (tap, drag, long-press right-click, two-finger scroll/right-click), optional trackpad mode, Android keyboard bridge, live rotation/brightness/OLED-off toggles, and adaptive JPEG streaming.
- **Paste (web UI):** `Ctrl+V`, `Ctrl+Shift+V`, `Shift+Insert` (`Cmd+V` on a Mac) put this device's clipboard, text or an image (up to 16 MB, sent as PNG), on the phone's and then press the same keys there. This works over plain HTTP. If something was copied on the phone since the page was last focused, that is pasted instead. The **Paste** button (`KB` bar) and **Paste Image…** (menu) do the same, with `Ctrl+Shift+V` for text in terminals. In the launcher and the password dialog the text is typed in. The browser uploads to `POST /api/clipboard`; the compositor gets the data as a memfd over the control socket (`clipboard-set-fd`, `input-paste`). VNC clients can send text only.
- `https://chandra-6t.tail.site.latha.org/` serves the web UI over HTTPS, tailnet only, from the `chandra-remote` chart in `nandi/cluster` (Caddy on the phone node, proxying to loopback `6080`). - `https://chandra-6t.tail.site.latha.org/` serves the web UI over HTTPS, tailnet only, from the `chandra-remote` chart in `nandi/cluster` (Caddy on the phone node, proxying to loopback `6080`).
- By default (`~/.config/chandra/remote.conf`), `bind=tailscale`, `bind_loopback=1`, and `auth=none`, binding strictly to the Tailscale `100.64.0.0/10` interface + `127.0.0.1` so any device on the same Tailscale tailnet can connect directly with zero password prompt (`http://<tailscale-dns>:6080/` or `<tailscale-dns>:5900`), even while the handset's physical OLED screen is turned off (`chandra-ctl screen off`). Run `chandra-remote status` to inspect endpoints or `chandra-remote passwd [PASS|--none]` to configure optional password auth. - By default (`~/.config/chandra/remote.conf`), `bind=tailscale`, `bind_loopback=1`, and `auth=none`, binding strictly to the Tailscale `100.64.0.0/10` interface + `127.0.0.1` so any device on the same Tailscale tailnet can connect directly with zero password prompt (`http://<tailscale-dns>:6080/` or `<tailscale-dns>:5900`), even while the handset's physical OLED screen is turned off (`chandra-ctl screen off`). Run `chandra-remote status` to inspect endpoints or `chandra-remote passwd [PASS|--none]` to configure optional password auth.
+66 -5
View File
@@ -1,3 +1,4 @@
#define _GNU_SOURCE /* memfd_create, file seals */
#include "remote_internal.h" #include "remote_internal.h"
#include <arpa/inet.h> #include <arpa/inet.h>
@@ -121,7 +122,8 @@ void ctl_close(CtlConn *c) {
pthread_mutex_unlock(&c->mu); 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) { if (c->fd < 0) {
uint64_t now = remote_now_ms(); uint64_t now = remote_now_ms();
if (now - c->last_try_ms < 250) return -1; 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'; msg[l] = '\n';
size_t sent = 0; size_t sent = 0;
while (sent < l + 1) { 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) { if (w <= 0) {
free(msg); free(msg);
close(c->fd); close(c->fd);
@@ -188,21 +209,61 @@ static int ctl_once_locked(CtlConn *c, const char *line, char *reply, size_t rep
return ok; 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); 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) { if (r < 0) {
c->last_try_ms = 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); pthread_mutex_unlock(&c->mu);
return r; 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) { int ctl_fire(CtlConn *c, const char *line) {
return ctl_cmd(c, line, NULL, 0); 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) { void remote_osk_suppress_acquire(RemoteApp *app, int *client_flag) {
if (*client_flag) return; if (*client_flag) return;
pthread_mutex_lock(&app->osk_mu); pthread_mutex_lock(&app->osk_mu);
+8
View File
@@ -11,6 +11,8 @@
#include "chandra_fb_shm.h" #include "chandra_fb_shm.h"
#define REMOTE_CLIPBOARD_MAX (16u * 1024u * 1024u)
#define REMOTE_AUTH_NONE 0 #define REMOTE_AUTH_NONE 0
#define REMOTE_AUTH_PASSWORD 1 #define REMOTE_AUTH_PASSWORD 1
@@ -78,6 +80,12 @@ void ctl_init(CtlConn *c, const char *sock_path);
void ctl_close(CtlConn *c); void ctl_close(CtlConn *c);
int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap); int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap);
int ctl_fire(CtlConn *c, const char *line); 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_acquire(RemoteApp *app, int *client_flag);
void remote_osk_suppress_release(RemoteApp *app, int *client_flag); void remote_osk_suppress_release(RemoteApp *app, int *client_flag);
void remote_osk_manual_override(RemoteApp *app); void remote_osk_manual_override(RemoteApp *app);
+2 -11
View File
@@ -571,7 +571,7 @@ static int rfb_handle_message(RfbClient *c) {
uint8_t hdr[7]; uint8_t hdr[7];
if (read_exact(c->fd, hdr, 7) < 0) return -1; if (read_exact(c->fd, hdr, 7) < 0) return -1;
uint32_t len = get_be32(hdr + 3); 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; uint8_t *txt = take ? malloc(take) : NULL;
if (take && !txt) return -1; if (take && !txt) return -1;
if (take && read_exact(c->fd, txt, take) < 0) { free(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; } if (read_exact(c->fd, drain, chunk) < 0) { free(txt); return -1; }
rem -= (uint32_t)chunk; rem -= (uint32_t)chunk;
} }
if (take > 0) { if (take > 0) remote_clipboard_set(&c->app->ctl, "text/plain", txt, take, NULL);
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);
}
}
free(txt); free(txt);
break; break;
} }
+72 -2
View File
@@ -199,6 +199,8 @@ class MockCtlServer:
self.screen = "on" self.screen = "on"
self.brightness = 75 self.brightness = 75
self.osk = 1 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 = threading.Thread(target=self._serve, daemon=True)
self.th.start() self.th.start()
@@ -215,11 +217,13 @@ class MockCtlServer:
def _client(self, conn: socket.socket): def _client(self, conn: socket.socket):
buf = b"" buf = b""
files = []
while self.running: while self.running:
try: try:
data = conn.recv(4096) data, fds, _, _ = socket.recv_fds(conn, 4096, 4)
except OSError: except OSError:
break break
files += fds
if not data: if not data:
break break
buf += data buf += data
@@ -244,6 +248,15 @@ class MockCtlServer:
elif cmd == "osk on": elif cmd == "osk on":
self.osk = 1 self.osk = 1
rep = "ok on\n" 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": elif cmd == "osk toggle":
self.osk = 0 if self.osk else 1 self.osk = 0 if self.osk else 1
rep = f"ok {'on' if self.osk else 'off'}\n" 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-scroll 0 -30 -1", cmds)
self.assertIn("input-key 30 1", cmds) self.assertIn("input-key 30 1", cmds)
self.assertIn("input-text c3a9", 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): def test_03_vnc_password_and_zlib(self):
self.shm.write_frame(64, 48, lambda x, y: (10, 200, 220)) self.shm.write_frame(64, 48, lambda x, y: (10, 200, 220))
@@ -761,6 +774,63 @@ class RemoteTests(unittest.TestCase):
time.sleep(0.15) time.sleep(0.15)
self.assertEqual(self.ctl.osk, 1) 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+121 -20
View File
@@ -190,6 +190,22 @@ static int extract_query_token(const char *target, char *out, size_t cap) {
return 1; 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) { static int ws_send_frame(int fd, uint8_t opcode, const void *data, size_t len) {
uint8_t hdr[10]; uint8_t hdr[10];
size_t hlen = 2; size_t hlen = 2;
@@ -478,25 +494,32 @@ static void ws_handle_text(WsState *ws, const char *msg) {
return; return;
} }
if (strcmp(type, "text") == 0) { if (strcmp(type, "text") == 0) {
char txt[1024] = {0}; size_t cap = strlen(msg) + 1;
if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) { char *txt = malloc(cap);
if (txt && json_get_str(msg, "s", txt, cap) && txt[0]) {
ws_note_key_activity(ws); ws_note_key_activity(ws);
remote_send_utf8_text(&ws->app->ctl, txt); remote_send_utf8_text(&ws->app->ctl, txt);
} }
free(txt);
return; return;
} }
if (strcmp(type, "clip") == 0) { if (strcmp(type, "clip") == 0) {
char txt[2048] = {0}; size_t cap = strlen(msg) + 1;
if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) { char *txt = malloc(cap);
size_t n = strlen(txt); if (txt && json_get_str(msg, "s", txt, cap) && txt[0]) {
char *cmd = malloc(16 + n * 2 + 1); remote_clipboard_set(&ws->app->ctl, "text/plain", txt, strlen(txt), NULL);
if (cmd) { }
memcpy(cmd, "clipboard-set ", 14); free(txt);
hex_encode((const uint8_t *)txt, n, cmd + 14); 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); ctl_fire(&ws->app->ctl, cmd);
free(cmd);
}
}
return; return;
} }
if (strcmp(type, "ctl") == 0) { 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) { static void ws_loop(RemoteApp *app, int fd) {
WsState ws; WsState ws;
memset(&ws, 0, sizeof ws); memset(&ws, 0, sizeof ws);
@@ -816,20 +914,23 @@ void web_handle_client(RemoteApp *app, int fd) {
close(fd); close(fd);
return; return;
} }
if (strcmp(method, "GET") == 0 && strcmp(path, "/ws") == 0) { if (strcmp(path, "/api/clipboard") == 0 && (!strcmp(method, "GET") || !strcmp(method, "POST"))) {
if (cfg.auth_mode != REMOTE_AUTH_NONE) { if (!web_authorized(app, &cfg, target, buf)) {
char tok[160] = {0}, cookie[1024] = {0}; const char *m = "{\"ok\":false,\"error\":\"Unauthorized\"}";
int ok = extract_query_token(target, tok, sizeof tok); http_send(fd, "401 Unauthorized", "application/json", NULL, m, strlen(m));
if (!ok && find_header(buf, "Cookie", cookie, sizeof cookie)) { } else {
ok = extract_cookie_token(cookie, tok, sizeof tok); web_clipboard(app, fd, method, buf, body, body_have);
} }
if (!ok || !web_token_verify(app->hmac_key, tok, (uint64_t)time(NULL))) { close(fd);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(path, "/ws") == 0) {
if (!web_authorized(app, &cfg, target, buf)) {
const char *m = "Unauthorized"; const char *m = "Unauthorized";
http_send(fd, "401 Unauthorized", "text/plain", NULL, m, strlen(m)); http_send(fd, "401 Unauthorized", "text/plain", NULL, m, strlen(m));
close(fd); close(fd);
return; return;
} }
}
char upg[64] = {0}, wskey[128] = {0}, accept[64] = {0}; char upg[64] = {0}, wskey[128] = {0}, accept[64] = {0};
if (!find_header(buf, "Upgrade", upg, sizeof upg) || strcasecmp(upg, "websocket") != 0 || if (!find_header(buf, "Upgrade", upg, sizeof upg) || strcasecmp(upg, "websocket") != 0 ||
!find_header(buf, "Sec-WebSocket-Key", wskey, sizeof wskey) || !find_header(buf, "Sec-WebSocket-Key", wskey, sizeof wskey) ||
+292 -8
View File
@@ -87,6 +87,20 @@
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px; position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
opacity: 0; border: 0; padding: 0; font-size: 16px; 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 { #loginMask {
position: fixed; inset: 0; z-index: 50; display: none; position: fixed; inset: 0; z-index: 50; display: none;
align-items: center; justify-content: center; padding: 20px; align-items: center; justify-content: center; padding: 20px;
@@ -142,6 +156,7 @@
</div> </div>
<div class="row"> <div class="row">
<button id="clipBtn" class="btn">Send Clipboard</button> <button id="clipBtn" class="btn">Send Clipboard</button>
<button id="imgBtn" class="btn">Paste Image…</button>
<button id="fsBtn" class="btn">Fullscreen</button> <button id="fsBtn" class="btn">Fullscreen</button>
<button class="btn" data-ctl="refresh">Redraw</button> <button class="btn" data-ctl="refresh">Redraw</button>
</div> </div>
@@ -169,6 +184,9 @@
<button id="kbHideBtn" class="btn">Done</button> <button id="kbHideBtn" class="btn">Done</button>
</div> </div>
<input id="kbdInput" type="text" value=" " autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"> <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"> <div id="loginMask">
<form id="loginForm" class="card"> <form id="loginForm" class="card">
@@ -202,6 +220,9 @@
const loginForm = document.getElementById('loginForm'); const loginForm = document.getElementById('loginForm');
const passInput = document.getElementById('passInput'); const passInput = document.getElementById('passInput');
const loginErr = document.getElementById('loginErr'); const loginErr = document.getElementById('loginErr');
const pasteSink = document.getElementById('pasteSink');
const imgInput = document.getElementById('imgInput');
const toastEl = document.getElementById('toast');
let ws = null; let ws = null;
let token = localStorage.getItem('chandra_remote_token') || ''; let token = localStorage.getItem('chandra_remote_token') || '';
@@ -214,7 +235,20 @@
let keyHandled = false; let keyHandled = false;
let lastPtrSent = 0; 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) { 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) { if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(obj)); ws.send(JSON.stringify(obj));
} }
@@ -308,6 +342,7 @@
sock.onopen = () => { sock.onopen = () => {
setStatusDot('ok', 'Connected'); setStatusDot('ok', 'Connected');
noteClipboardBase();
loginMask.classList.remove('open'); loginMask.classList.remove('open');
}; };
sock.onmessage = (ev) => { sock.onmessage = (ev) => {
@@ -572,6 +607,7 @@
if (loginMask.classList.contains('open')) return; if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) 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 (e.isComposing || e.key === 'Unidentified' || e.key === 'Process' || e.key === 'Dead') return;
if (beginKeyPaste(e)) return;
const sym = eventToKeysym(e); const sym = eventToKeysym(e);
if (sym !== null) { if (sym !== null) {
e.preventDefault(); e.preventDefault();
@@ -599,10 +635,241 @@
}); });
window.addEventListener('blur', releaseAllKeys); window.addEventListener('blur', releaseAllKeys);
window.addEventListener('focus', noteClipboardBase);
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (document.hidden) releaseAllKeys(); 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 ---- */ /* ---- Android Gboard sentinel-space keyboard bridge ---- */
function setKbOpen(open) { function setKbOpen(open) {
kbOpen = open; kbOpen = open;
@@ -660,6 +927,7 @@
kbdInput.addEventListener('keydown', (e) => { kbdInput.addEventListener('keydown', (e) => {
keyHandled = false; keyHandled = false;
if (beginKeyPaste(e)) return;
const map = { const map = {
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111, Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108, ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
@@ -751,17 +1019,33 @@
}); });
document.getElementById('clipBtn').addEventListener('click', async () => { document.getElementById('clipBtn').addEventListener('click', async () => {
let txt = ''; const [text, image] = await readLocalClipboard('Text to copy to phone clipboard:');
try { txt = await navigator.clipboard.readText(); } catch (_) {} if (!text && !image) return;
if (!txt) txt = prompt('Text to copy to phone clipboard:') || ''; try {
if (txt) sendJson({ t: 'clip', s: txt }); 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 () => { document.getElementById('pasteBtn').addEventListener('click', async () => {
let txt = ''; const [text, image] = await readLocalClipboard('Text to paste on phone:');
try { txt = await navigator.clipboard.readText(); } catch (_) {} if (text || image) {
if (!txt) txt = prompt('Text to type on phone:') || ''; holdTyping();
if (txt) sendJson({ t: 'text', s: txt }); runPaste(text, image, null, true);
}
kbdInput.focus(); kbdInput.focus();
}); });