From bfc60ee0e506b996c19298af4b85642fac1702fe Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sat, 28 Nov 2026 17:57:55 -0800 Subject: [PATCH] Add chandra-remote: VNC and web control over Tailscale - remote/: shared-memory framebuffer mirror served as RFB 3.8 (VNC, port 5900) and an HTTP/WebSocket PWA (port 6080), bound to the Tailscale interface and loopback by default - Compositor: remote pointer, button, scroll, modifier, key, key-tap, text and clipboard input, routed past OLED blanking - chandra-ctl: add status, refresh and osk commands; add input-* and clipboard-set for remote control - Camera: debayer 10-bit CSI-2 Quad-Bayer frames for imx371 and high-quality still capture - Camera: rotate frames by the libcamera mounting angle (CCW for 90), fix the expected test values, and restyle the UI for a dark theme --- camera/chandra-camera | 194 ++++++-- camera/chandra-camera-ui.c | 65 ++- camera/test_camera.py | 45 +- compositor/host/compositor.mbt | 112 ++++- compositor/host/control.mbt | 277 +++++++++++ compositor/host/control_test.mbt | 41 ++ docs/handset.md | 7 + face/chandra-face | 154 ++++++- remote/auth.c | 329 +++++++++++++ remote/chandra-remote.c | 767 ++++++++++++++++++++++++++++++ remote/chandra_fb_shm.h | 34 ++ remote/keysym.c | 216 +++++++++ remote/remote_internal.h | 112 +++++ remote/rfb.c | 768 +++++++++++++++++++++++++++++++ remote/test_remote.py | 643 ++++++++++++++++++++++++++ remote/web.c | 763 ++++++++++++++++++++++++++++++ remote/web/icon.svg | 16 + remote/web/index.html | 669 +++++++++++++++++++++++++++ remote/web/manifest.json | 17 + session/chandra-ctl | 5 +- session/chandra-session | 8 + session/install.py | 26 ++ wasmhost/bin/raster.mbt | 5 + wasmhost/bin/raster_stub.c | 116 +++++ 24 files changed, 5310 insertions(+), 79 deletions(-) create mode 100644 remote/auth.c create mode 100644 remote/chandra-remote.c create mode 100644 remote/chandra_fb_shm.h create mode 100644 remote/keysym.c create mode 100644 remote/remote_internal.h create mode 100644 remote/rfb.c create mode 100644 remote/test_remote.py create mode 100644 remote/web.c create mode 100644 remote/web/icon.svg create mode 100644 remote/web/index.html create mode 100644 remote/web/manifest.json diff --git a/camera/chandra-camera b/camera/chandra-camera index b654ea8..cb58317 100755 --- a/camera/chandra-camera +++ b/camera/chandra-camera @@ -24,6 +24,8 @@ FLASH_LED_PATH = "/sys/class/leds/white:flash/brightness" IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp") VIDEO_EXTS = (".mp4", ".mkv", ".webm") +QUAD_BAYER_MODELS = {"imx371"} + # Fallback resolutions when a camera reports no enumerated StillCapture sizes. DEFAULT_VIEWFINDER_SIZE = (1280, 960) PREFERRED_STILL_SIZES = [ @@ -212,6 +214,18 @@ def select_initial_camera(cameras, spec): return 0 +def rotate_bgr(bgr, rot, cv2_mod): + """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle).""" + rot_i = int(rot) % 360 + if rot_i == 90: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE) + if rot_i == 180: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180) + if rot_i == 270: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE) + return bgr + + def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None): """Convert raw camera buffer bytes into a contiguous upright uint8 BGR image.""" if np_mod is None: @@ -238,14 +252,64 @@ def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=N else: raise RuntimeError("unsupported pixel format %s" % fmt) - rot_i = int(rot) % 360 - if rot_i == 90: - return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE)) - if rot_i == 180: - return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_180)) - if rot_i == 270: - return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE)) - return bgr + return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod)) + + +def debayer_quad_csi2p( + raw_buf, + width, + height, + stride, + rot=0, + offset=0, + target_size=(960, 720), + high_quality=False, + gamma_lut=None, + cv2_mod=None, + np_mod=None, +): + """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8.""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) + row_bytes = (width // 4) * 5 + even_h = (height // 2) * 2 + even_w = (width // 4) * 4 + if high_quality: + p8 = arr[:even_h, :row_bytes].reshape((even_h, even_w // 4, 5))[:, :, :4].reshape((even_h, even_w)) + bayer = ( + ( + p8[0::2, 0::2].astype(np_mod.uint16) + + p8[0::2, 1::2] + + p8[1::2, 0::2] + + p8[1::2, 1::2] + ) + >> 2 + ).astype(np_mod.uint8) + else: + b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, even_w // 4, 5)) + bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, even_w // 2))) + + bgr = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) + if target_size is not None: + bgr = cv2_mod.resize(bgr, target_size, interpolation=cv2_mod.INTER_AREA) + + f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0) + means = f.mean(axis=(0, 1)) + avg = float(means.mean()) + if avg > 1.0: + gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2) + boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8)) + u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8) + else: + u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8) + if gamma_lut is None: + gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) + out = cv2_mod.LUT(u8, gamma_lut) + return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) def bgr_to_cairo_argb32(bgr, np_mod=None): @@ -355,11 +419,13 @@ class CameraEngine: self._cam = None self._sc = None + self._raw_sc = None self._alloc = None self._requests = [] self._v4l2 = None self._started = False self._reuse_arg = None + self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8) self._latest_bgr = None self._latest_seq = 0 @@ -463,34 +529,61 @@ class CameraEngine: cam.acquire() self._cam = cam try: - role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder - sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES) - chosen_exc = None + self._raw_sc = None configured = False - for w, h in sizes: + if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS: try: - cfg = cam.generate_configuration([role]) - sc = cfg.at(0) - sc.size = libcamera.Size(w, h) - cfg.validate() - cam.configure(cfg) - self._sc = sc - configured = True - break - except Exception as exc: - chosen_exc = exc + cfg = cam.generate_configuration([ + libcamera.StreamRole.Viewfinder, + libcamera.StreamRole.Raw, + ]) + if cfg is not None and len(cfg) >= 2: + cfg.at(0).size = libcamera.Size(640, 480) + cfg.validate() + cam.configure(cfg) + self._sc = cfg.at(0) + self._raw_sc = cfg.at(1) + configured = True + except Exception: + self._raw_sc = None + if not configured: - raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc)) + role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder + sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES) + chosen_exc = None + for w, h in sizes: + try: + cfg = cam.generate_configuration([role]) + sc = cfg.at(0) + sc.size = libcamera.Size(w, h) + cfg.validate() + cam.configure(cfg) + self._sc = sc + configured = True + break + except Exception as exc: + chosen_exc = exc + if not configured: + raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc)) alloc = libcamera.FrameBufferAllocator(cam) if alloc.allocate(self._sc.stream) <= 0: raise RuntimeError("failed to allocate camera buffers for %s" % info.label) self._alloc = alloc reqs = [] - for buf in alloc.buffers(self._sc.stream): - r = cam.create_request() - r.add_buffer(self._sc.stream, buf) - reqs.append(r) + if self._raw_sc is not None: + if alloc.allocate(self._raw_sc.stream) <= 0: + raise RuntimeError("failed to allocate raw buffers for %s" % info.label) + for b0, b1 in zip(alloc.buffers(self._sc.stream), alloc.buffers(self._raw_sc.stream)): + r = cam.create_request() + r.add_buffer(self._sc.stream, b0) + r.add_buffer(self._raw_sc.stream, b1) + reqs.append(r) + else: + for buf in alloc.buffers(self._sc.stream): + r = cam.create_request() + r.add_buffer(self._sc.stream, buf) + reqs.append(r) self._requests = reqs # Drain any stale completed requests before starting the newly acquired sensor. self.cm.get_ready_requests() @@ -525,20 +618,43 @@ class CameraEngine: self._requests = [] self._alloc = None self._sc = None + self._raw_sc = None try: self._cam.release() except Exception: pass self._cam = None - def _read_libcamera_frame(self, cam_info): + def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(960, 720)): ready = self.cm.get_ready_requests() if not ready: return None frame = None for req in ready: - if self._sc is not None and self._sc.stream in req.buffers: - if req.status == self.libcamera.Request.Status.Complete: + if req.status == self.libcamera.Request.Status.Complete: + if self._raw_sc is not None and self._raw_sc.stream in req.buffers: + buf = req.buffers[self._raw_sc.stream] + plane = buf.planes[0] + w = self._raw_sc.size.width + h = self._raw_sc.size.height + stride = self._raw_sc.stride + fmt = str(self._raw_sc.pixel_format) + if "CSI2P" in fmt.upper(): + with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm: + frame = debayer_quad_csi2p( + mm, + w, + h, + stride, + rot=cam_info.rotation, + offset=plane.offset, + target_size=target_size, + high_quality=high_quality, + gamma_lut=self._gamma_lut, + cv2_mod=self.cv2, + np_mod=self.np, + ) + elif self._sc is not None and self._sc.stream in req.buffers: buf = req.buffers[self._sc.stream] plane = buf.planes[0] w = self._sc.size.width @@ -557,7 +673,7 @@ class CameraEngine: cv2_mod=self.cv2, np_mod=self.np, ) - self._requeue(req) + self._requeue(req) return frame def _run_loop(self): @@ -630,7 +746,21 @@ class CameraEngine: def _perform_still_capture(self, dst_path): info = self.active_camera try: - if info.backend == "libcamera": + if info.backend == "libcamera" and self._raw_sc is not None: + captured = None + deadline = time.monotonic() + 4.0 + while time.monotonic() < deadline and not self._stop_event.is_set(): + captured = self._read_libcamera_frame(info, high_quality=True, target_size=None) + if captured is not None: + break + time.sleep(0.01) + if captured is None: + raise RuntimeError("still capture timed out") + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + if not self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]): + raise RuntimeError("failed to write %s" % dst_path) + self._still_result = (dst_path, None) + elif info.backend == "libcamera": self._close_camera() self._open_camera(info, role_name="still", target_sizes=PREFERRED_STILL_SIZES) captured = None diff --git a/camera/chandra-camera-ui.c b/camera/chandra-camera-ui.c index 8588cb3..bb4ef42 100644 --- a/camera/chandra-camera-ui.c +++ b/camera/chandra-camera-ui.c @@ -1105,43 +1105,53 @@ static gboolean start_worker_process(CameraApp *app) { } static void build_ui(CameraApp *app) { + GtkSettings *settings = gtk_settings_get_default(); + if (settings) { + g_object_set(settings, "gtk-application-prefer-dark-theme", TRUE, NULL); + } + const char *css = - "window, .cam-root { background-color: #0b0d14; color: #f4f6fc; }\n" - ".cam-pill { background-color: rgba(14, 18, 30, 0.74); color: #f4f6fc;\n" - " border: 1px solid rgba(255, 255, 255, 0.16); border-radius: 18px;\n" - " padding: 5px 12px; font-size: 13px; font-weight: 600; min-height: 24px; }\n" - ".cam-pill:hover { background-color: rgba(30, 38, 60, 0.88); }\n" - ".cam-pill-active { background-color: rgba(110, 140, 255, 0.88);\n" - " color: #090d16; border-color: rgba(180, 200, 255, 0.90); }\n" - ".cam-pill-danger { background-color: rgba(239, 68, 68, 0.88);\n" - " color: #ffffff; border-color: rgba(255, 180, 180, 0.80); }\n" - ".cam-dock { background-color: rgba(10, 12, 20, 0.86);\n" - " border-top: 1px solid rgba(255, 255, 255, 0.10); padding: 10px 16px 14px 16px; }\n" - ".cam-mode-bar { background-color: rgba(255, 255, 255, 0.08);\n" + "window, .cam-root { background-color: #0b0d14; background-image: none; color: #f4f6fc; }\n" + "button.cam-pill { background-color: rgba(14, 18, 30, 0.82); background-image: none; color: #f4f6fc;\n" + " border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 18px;\n" + " box-shadow: none; text-shadow: none; -gtk-icon-shadow: none;\n" + " padding: 4px 10px; font-size: 12px; font-weight: 600; min-height: 24px; }\n" + "button.cam-pill label { color: inherit; }\n" + "button.cam-pill:hover { background-color: rgba(34, 43, 68, 0.92); background-image: none; }\n" + "button.cam-pill.cam-pill-active { background-color: #6e8cff; background-image: none;\n" + " color: #090d16; border-color: rgba(180, 200, 255, 0.95); }\n" + "button.cam-pill.cam-pill-danger { background-color: #ef4444; background-image: none;\n" + " color: #ffffff; border-color: rgba(255, 180, 180, 0.85); }\n" + ".cam-dock { background-color: rgba(10, 12, 20, 0.88); background-image: none;\n" + " border-top: 1px solid rgba(255, 255, 255, 0.12); padding: 10px 14px 14px 14px; }\n" + ".cam-mode-bar { background-color: rgba(255, 255, 255, 0.10); background-image: none;\n" " border-radius: 18px; padding: 3px; }\n" - ".cam-mode-btn { background-color: transparent; color: #c2cadc; border: none;\n" + "button.cam-mode-btn { background-color: transparent; background-image: none; color: #c2cadc;\n" + " border: none; box-shadow: none; text-shadow: none; -gtk-icon-shadow: none;\n" " border-radius: 15px; padding: 4px 18px; font-size: 13px; font-weight: 600; min-height: 22px; }\n" - ".cam-mode-selected { background-color: #6e8cff; color: #0b0d14; }\n" - ".cam-mode-selected-video { background-color: #ef4444; color: #ffffff; }\n" - ".cam-rec-badge { background-color: rgba(239, 68, 68, 0.90); color: #ffffff;\n" + "button.cam-mode-btn label { color: inherit; }\n" + "button.cam-mode-btn.cam-mode-selected { background-color: #6e8cff; background-image: none; color: #0b0d14; }\n" + "button.cam-mode-btn.cam-mode-selected-video { background-color: #ef4444; background-image: none; color: #ffffff; }\n" + ".cam-rec-badge { background-color: rgba(239, 68, 68, 0.92); color: #ffffff;\n" " border-radius: 12px; padding: 2px 10px; font-size: 12px; font-weight: 700; }\n" - ".cam-icon-btn { background-color: transparent; border: none; padding: 0; box-shadow: none; }\n" - ".cam-gallery-bar { background-color: #111523;\n" - " border-bottom: 1px solid rgba(255, 255, 255, 0.10); padding: 8px 12px; }\n" - ".cam-gallery-foot { background-color: #111523;\n" - " border-top: 1px solid rgba(255, 255, 255, 0.10); padding: 8px 14px; }\n" + "button.cam-icon-btn, button.cam-icon-btn:hover { background-color: transparent; background-image: none;\n" + " border: none; padding: 0; box-shadow: none; outline: none; }\n" + ".cam-gallery-bar { background-color: #111523; background-image: none;\n" + " border-bottom: 1px solid rgba(255, 255, 255, 0.12); padding: 8px 10px; }\n" + ".cam-gallery-foot { background-color: #111523; background-image: none;\n" + " border-top: 1px solid rgba(255, 255, 255, 0.12); padding: 8px 12px; }\n" ".cam-title { font-size: 14px; font-weight: 700; color: #f4f6fc; }\n" ".cam-sub { font-size: 12px; color: #9ba6c2; }\n"; GtkCssProvider *prov = gtk_css_provider_new(); gtk_css_provider_load_from_data(prov, css, -1, NULL); gtk_style_context_add_provider_for_screen( - gdk_screen_get_default(), GTK_STYLE_PROVIDER(prov), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + gdk_screen_get_default(), GTK_STYLE_PROVIDER(prov), GTK_STYLE_PROVIDER_PRIORITY_USER); g_object_unref(prov); app->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(app->window), "Camera"); - gtk_window_set_default_size(GTK_WINDOW(app->window), 520, 960); + gtk_window_set_default_size(GTK_WINDOW(app->window), 480, 860); gtk_widget_set_size_request(app->window, 340, 480); gtk_style_context_add_class(gtk_widget_get_style_context(app->window), "cam-root"); @@ -1372,6 +1382,15 @@ int main(int argc, char **argv) { sync_ui_labels(&app); gtk_widget_show_all(app.window); + GdkDisplay *dpy = gdk_display_get_default(); + GdkMonitor *mon = dpy ? gdk_display_get_monitor(dpy, 0) : NULL; + if (mon) { + GdkRectangle geo; + gdk_monitor_get_geometry(mon, &geo); + if (geo.width <= 900 || geo.height > geo.width) { + gtk_window_maximize(GTK_WINDOW(app.window)); + } + } if (app.open_gallery_start) { open_gallery_view(&app); } else { diff --git a/camera/test_camera.py b/camera/test_camera.py index 6a24dc5..cf41b62 100644 --- a/camera/test_camera.py +++ b/camera/test_camera.py @@ -56,13 +56,13 @@ class TestCameraHelpers(unittest.TestCase): bgr90 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=90, cv2_mod=cv2, np_mod=np) self.assertEqual(bgr90.shape, (2, 3, 3)) - # Clockwise 90 deg puts original (row=0, col=0) at (row=0, col=h-1=2) - self.assertEqual(tuple(bgr90[0, 2]), (200, 20, 10)) + # Libcamera Rotation=90 (CCW mounting) rotates CCW: (row=0, col=0) -> (row=w-1=1, col=0) + self.assertEqual(tuple(bgr90[1, 0]), (200, 20, 10)) bgr270 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=270, cv2_mod=cv2, np_mod=np) self.assertEqual(bgr270.shape, (2, 3, 3)) - # Counter-clockwise 90 deg puts original (row=0, col=0) at (row=w-1=1, col=0) - self.assertEqual(tuple(bgr270[1, 0]), (200, 20, 10)) + # Libcamera Rotation=270 rotates CW: (row=0, col=0) -> (row=0, col=h-1=2) + self.assertEqual(tuple(bgr270[0, 2]), (200, 20, 10)) @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") def test_convert_argb_rgb_and_cairo_bgra(self): @@ -87,6 +87,43 @@ class TestCameraHelpers(unittest.TestCase): even = cam_mod.ensure_even_frame(odd) self.assertEqual(even.shape, (100, 202, 3)) + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_debayer_quad_csi2p(self): + # Construct an 8x8 CSI-2 10-bit packed 4x4 Quad-Bayer SRGGB image: + # Top half (rows 0..3): strong red (R=200, G=24, B=24) + # Bottom half (rows 4..7): strong blue (R=24, G=24, B=200) + w, h, stride = 8, 8, 10 + arr = np.zeros((h, stride), dtype=np.uint8) + for y in range(h): + top = y < 4 + for x_blk in range(2): # 4 pixels per block, 5 bytes per block + # Row phase inside 4x4 Quad-Bayer: y%4 in {0,1} -> R,R,G,G; {2,3} -> G,G,B,B + if (y % 4) < 2: + c0 = 200 if top else 24 # R + c1 = 24 # G + else: + c0 = 24 # G + c1 = 24 if top else 200 # B + base = x_blk * 5 + arr[y, base + 0] = c0 + arr[y, base + 1] = c0 + arr[y, base + 2] = c1 + arr[y, base + 3] = c1 + arr[y, base + 4] = 0 + raw = arr.tobytes() + + out_live = cam_mod.debayer_quad_csi2p( + raw, w, h, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np + ) + out_hq = cam_mod.debayer_quad_csi2p( + raw, w, h, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np + ) + self.assertEqual(out_live.shape, (4, 4, 3)) # 8x8 -> 4x4, rot=90 keeps 4x4 + self.assertEqual(out_hq.shape, (4, 6, 3)) # resized to WxH = 6x4 + # Top row in rot=0 should have R > B; bottom row should have B > R. + self.assertGreater(float(out_hq[0, :, 2].mean()), float(out_hq[0, :, 0].mean()) + 30.0) + self.assertGreater(float(out_hq[3, :, 0].mean()), float(out_hq[3, :, 2].mean()) + 30.0) + if __name__ == "__main__": unittest.main() diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 69f7fd0..09259f7 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -2067,6 +2067,107 @@ pub fn ChandraCompositor::handle_input( self.osk_sync() } +///| Route remote input (from chandra-remote): bypasses physical-display blanking so remote +/// sessions can control an OLED-blanked device without unblanking its panel. +pub fn ChandraCompositor::handle_remote_input( + self : ChandraCompositor, + ev : @nested.InputEvent, + time_ms : UInt, +) -> Unit { + self.note_activity(@sys.monotonic_ms()) + self.dispatch_input_inner(ev, time_ms) + self.osk_sync() +} + +///| Inject a key tap with temporary modifier bitmask, restoring prior modifiers afterwards. +pub fn ChandraCompositor::remote_key_tap( + self : ChandraCompositor, + code : UInt, + mods : UInt, + time_ms : UInt, +) -> Unit { + let saved_mods = self.mods + let saved_lat = self.mods_latched + let saved_lock = self.mods_locked + let saved_group = self.mods_group + let need_mod = mods != saved_mods || saved_lat != 0U + if need_mod { + self.handle_remote_input(Modifiers(mods, 0U, saved_lock, saved_group), time_ms) + } + self.handle_remote_input(Key(code, true), time_ms) + self.handle_remote_input(Key(code, false), time_ms + 1U) + if need_mod { + self.handle_remote_input( + Modifiers(saved_mods, saved_lat, saved_lock, saved_group), + time_ms + 1U, + ) + } +} + +///| Put UTF-8 text on the compositor's own Wayland clipboard. +pub fn ChandraCompositor::remote_set_clipboard( + self : ChandraCompositor, + text : String, +) -> Unit { + self.server.set_own_selection( + ["text/plain;charset=utf-8", "text/plain", "UTF8_STRING"], + @utf8.encode(text), + ) +} + +///| Commit UTF-8 text directly to the active popup, Wayland text-input-v3 surface, or desktop; +/// falls back to putting the text on the clipboard when no text sink accepts it. +pub fn ChandraCompositor::remote_commit_text( + self : ChandraCompositor, + text : String, +) -> Bool { + self.note_activity(@sys.monotonic_ms()) + if self.shell.popup_open() { + for ch in text { + let name = match ch { + '\n' => "Enter" + '\t' => "Tab" + _ => ch.to_string() + } + self.shell.key_down(name) + } + self.run_shell_actions() + self.damage.mark_full() + self.frame_changed = true + return true + } + match self.kbd_win { + Some(wid) => + if self.server.text_input_commit(wid, text) { + self.damage.mark_full() + self.frame_changed = true + return true + } + None => + if self.shell.desktop_has_focus() { + let mut took = false + for ch in text { + let name = match ch { + '\n' => "Enter" + '\t' => "Tab" + _ => ch.to_string() + } + if self.shell.desktop_key(name) { + took = true + } + } + if took { + self.run_shell_actions() + self.damage.mark_full() + self.frame_changed = true + return true + } + } + } + self.remote_set_clipboard(text) + false +} + ///| fn ChandraCompositor::handle_input_inner( self : ChandraCompositor, @@ -2095,6 +2196,15 @@ fn ChandraCompositor::handle_input_inner( return } self.note_activity(@sys.monotonic_ms()) + self.dispatch_input_inner(ev, time_ms) +} + +///| +fn ChandraCompositor::dispatch_input_inner( + self : ChandraCompositor, + ev : @nested.InputEvent, + time_ms : UInt, +) -> Unit { match ev { Modifiers(dep, lat, lock, group) => { self.mods_latched = lat @@ -2319,7 +2429,7 @@ fn ChandraCompositor::handle_input_inner( self.ptr_grab = false self.grab_buttons = 0 self.press_fwd = false - self.handle_input(PointerMove(self.ptr_x, self.ptr_y), time_ms) + self.dispatch_input_inner(PointerMove(self.ptr_x, self.ptr_y), time_ms) } } return diff --git a/compositor/host/control.mbt b/compositor/host/control.mbt index 9254e01..ef78d21 100644 --- a/compositor/host/control.mbt +++ b/compositor/host/control.mbt @@ -188,6 +188,92 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit { } } +///| Parse a signed base-10 integer string. +fn parse_int_opt(s : String) -> Int? { + if s.length() == 0 { + return None + } + let mut neg = false + let mut start = 0 + if s[0] == '-' { + neg = true + start = 1 + } else if s[0] == '+' { + start = 1 + } + if start >= s.length() { + return None + } + let mut acc : Int64 = 0L + for i = start; i < s.length(); i = i + 1 { + let c = s[i].to_int() + if c < 48 || c > 57 { + return None + } + acc = acc * 10L + (c - 48).to_int64() + if acc > 2147483648L { + return None + } + } + let v = if neg { -acc } else { acc } + if v < -2147483648L || v > 2147483647L { + None + } else { + Some(v.to_int()) + } +} + +///| Parse an unsigned base-10 integer string. +fn parse_uint_opt(s : String) -> UInt? { + if s.length() == 0 { + return None + } + let mut acc : UInt64 = 0UL + for i = 0; i < s.length(); i = i + 1 { + let c = s[i].to_int() + if c < 48 || c > 57 { + return None + } + acc = acc * 10UL + (c - 48).to_uint64() + if acc > 4294967295UL { + return None + } + } + Some(acc.to_uint()) +} + +///| Convert one ASCII hex digit into 0..15, or -1 if invalid. +fn hex_nibble(c : Int) -> Int { + if c >= 48 && c <= 57 { + c - 48 + } else if c >= 65 && c <= 70 { + c - 55 + } else if c >= 97 && c <= 102 { + c - 87 + } else { + -1 + } +} + +///| Decode a lowercase/uppercase hex string into UTF-8 `String`. +fn decode_hex_utf8(s : String) -> String? { + if s.length() % 2 != 0 { + return None + } + let out : Array[Byte] = [] + let mut i = 0 + while i < s.length() { + let hi = hex_nibble(s[i].to_int()) + let lo = hex_nibble(s[i + 1].to_int()) + if hi < 0 || lo < 0 { + return None + } + out.push(((hi << 4) | lo).to_byte()) + i = i + 2 + } + Some(@utf8.decode_lossy(Bytes::from_array(out))) +} + ///| Run one control command; the reply lines (the last starts with "ok" or "error") and whether /// it succeeded. pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : String) -> (Array[String], Bool) { @@ -216,6 +302,9 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin "rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display", "screen [on|off|toggle|status] blank or wake the display", "brightness [PCT|status] read or set display backlight percent (5..100)", + "osk [on|off|toggle|status] enable, disable, or query the on-screen keyboard", + "refresh schedule a full frame redraw", + "status report geometry, rotation, screen power, brightness, pointer, OSK", "settings [TAB] open Settings popup (session, desktop, panel, power, shortcuts, apps)", "auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " + @polkit.demo_modes.join(", "), @@ -485,6 +574,194 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin } } } + "status" => { + let deg = (self.rotation * 90).to_string() + let scr = if self.screen_off || self.manual_screen_off { "off" } else { "on" } + let bri = @shell.read_backlight_percent().to_string() + let ptr = self.ptr_x.to_int().to_string() + "," + self.ptr_y.to_int().to_string() + let osk = if self.osk_enabled { "1" } else { "0" } + ( + [ + "ok " + + self.output_w.to_string() + + "x" + + self.output_h.to_string() + + " rot=" + + deg + + " screen=" + + scr + + " brightness=" + + bri + + " ptr=" + + ptr + + " osk=" + + osk, + ], + true, + ) + } + "refresh" => { + self.damage.mark_full() + self.frame_changed = true + (["ok"], true) + } + "osk" => { + let arg = if words.length() >= 2 { words[1] } else { "status" } + if words.length() > 2 { + return (["error usage: osk [on|off|toggle|status]"], false) + } + match arg { + "status" => (["ok " + (if self.osk_enabled { "on" } else { "off" })], true) + "on" => { + self.set_osk_enabled(true) + (["ok on"], true) + } + "off" => { + self.set_osk_enabled(false) + (["ok off"], true) + } + "toggle" => { + let next = !self.osk_enabled + self.set_osk_enabled(next) + (["ok " + (if next { "on" } else { "off" })], true) + } + _ => (["error usage: osk [on|off|toggle|status]"], false) + } + } + "input-ptr" => { + if words.length() != 3 { + return (["error usage: input-ptr X Y"], false) + } + match (parse_int_opt(words[1]), parse_int_opt(words[2])) { + (Some(x), Some(y)) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.handle_remote_input( + @nested.InputEvent::PointerMove(x.to_double(), y.to_double()), + now_ms, + ) + (["ok"], true) + } + _ => (["error invalid coordinates"], false) + } + } + "input-btn" => { + if words.length() != 3 { + return (["error usage: input-btn CODE STATE"], false) + } + match (parse_uint_opt(words[1]), parse_int_opt(words[2])) { + (Some(code), Some(state)) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.handle_remote_input( + @nested.InputEvent::PointerButton(code, state != 0), + now_ms, + ) + (["ok"], true) + } + _ => (["error invalid button args"], false) + } + } + "input-scroll" => { + if words.length() != 4 { + return (["error usage: input-scroll AXIS VAL DISCRETE"], false) + } + match + (parse_uint_opt(words[1]), parse_int_opt(words[2]), parse_int_opt(words[3])) { + (Some(axis), Some(val), Some(disc)) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.handle_remote_input( + @nested.InputEvent::Scroll(axis, val.to_double(), disc), + now_ms, + ) + (["ok"], true) + } + _ => (["error invalid scroll args"], false) + } + } + "input-mods" => { + if words.length() != 5 { + return (["error usage: input-mods DEP LAT LOCK GROUP"], false) + } + match + ( + parse_uint_opt(words[1]), + parse_uint_opt(words[2]), + parse_uint_opt(words[3]), + parse_uint_opt(words[4]), + ) { + (Some(dep), Some(lat), Some(lock), Some(grp)) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.handle_remote_input( + @nested.InputEvent::Modifiers(dep, lat, lock, grp), + now_ms, + ) + (["ok"], true) + } + _ => (["error invalid modifier args"], false) + } + } + "input-key" => { + if words.length() != 3 { + return (["error usage: input-key CODE STATE"], false) + } + match (parse_uint_opt(words[1]), parse_int_opt(words[2])) { + (Some(code), Some(state)) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.handle_remote_input( + @nested.InputEvent::Key(code, state != 0), + now_ms, + ) + (["ok"], true) + } + _ => (["error invalid key args"], false) + } + } + "input-key-tap" => { + if words.length() < 2 || words.length() > 3 { + return (["error usage: input-key-tap CODE [MODS]"], false) + } + let mods = if words.length() == 3 { + match parse_uint_opt(words[2]) { + Some(m) => m + None => return (["error invalid mods"], false) + } + } else { + 0U + } + match parse_uint_opt(words[1]) { + Some(code) => { + let now_ms = @sys.monotonic_ms().to_uint() + self.remote_key_tap(code, mods, now_ms) + (["ok"], true) + } + None => (["error invalid key code"], false) + } + } + "input-text" => { + if words.length() != 2 { + return (["error usage: input-text HEX"], false) + } + match decode_hex_utf8(words[1]) { + Some(text) => + if self.remote_commit_text(text) { + (["ok typed"], true) + } else { + (["ok clipboard"], true) + } + None => (["error invalid hex"], false) + } + } + "clipboard-set" => { + if words.length() != 2 { + return (["error usage: clipboard-set HEX"], false) + } + match decode_hex_utf8(words[1]) { + Some(text) => { + self.remote_set_clipboard(text) + (["ok"], true) + } + None => (["error invalid hex"], false) + } + } other => (["error unknown command '" + other + "' (try: help)"], false) } } diff --git a/compositor/host/control_test.mbt b/compositor/host/control_test.mbt index 0e7384a..0c42769 100644 --- a/compositor/host/control_test.mbt +++ b/compositor/host/control_test.mbt @@ -166,3 +166,44 @@ test "a second compositor leaves a live control socket alone" { assert_true(third.start_control(path)) third.close() } + +///| +test "remote status, refresh, osk, pointer/key/text/clipboard injection and OLED-off routing" { + let (comp, path) = control_comp("remote") + let st = ask(comp, path, "status") + assert_eq(st.length(), 1) + assert_true(st[0].has_prefix("ok 1280x720 rot=0 screen=on")) + assert_true(st[0].contains(" ptr=")) + assert_true(st[0].contains(" osk=")) + assert_eq(ask(comp, path, "refresh"), ["ok"]) + assert_eq(ask(comp, path, "osk off"), ["ok off"]) + assert_eq(ask(comp, path, "osk on"), ["ok on"]) + assert_eq(ask(comp, path, "osk toggle"), ["ok off"]) + // Turn screen off manually: remote pointer/key injection still moves the pointer and + // executes shortcuts WITHOUT unblanking the physical display. + assert_eq(ask(comp, path, "screen off"), ["ok off"]) + assert_true(comp.manual_screen_off) + assert_eq(ask(comp, path, "input-ptr 240 180"), ["ok"]) + assert_eq(comp.ptr_x.to_int(), 240) + assert_eq(comp.ptr_y.to_int(), 180) + assert_true(comp.manual_screen_off) + assert_eq(ask(comp, path, "input-btn 272 1"), ["ok"]) + assert_eq(ask(comp, path, "input-btn 272 0"), ["ok"]) + // Toggle launcher via Super tap (evdev 125 down/up) while screen is still blanked. + assert_eq(ask(comp, path, "input-key 125 1"), ["ok"]) + assert_eq(ask(comp, path, "input-key 125 0"), ["ok"]) + assert_true(comp.shell.launcher_open()) + assert_true(comp.manual_screen_off) + // input-text types into the open launcher popup ("6869" = "hi"). + assert_eq(ask(comp, path, "input-text 6869"), ["ok typed"]) + // Close launcher with Esc tap ("1"), then check clipboard-set + input-text fallback. + assert_eq(ask(comp, path, "input-key-tap 1 0"), ["ok"]) + assert_false(comp.shell.launcher_open()) + assert_eq(ask(comp, path, "clipboard-set 616263"), ["ok"]) + assert_true(comp.server.owns_selection()) + assert_eq(ask(comp, path, "input-text 7879"), ["ok clipboard"]) + assert_true(comp.server.owns_selection()) + assert_eq(ask(comp, path, "screen on"), ["ok on"]) + assert_false(comp.manual_screen_off) + comp.close() +} diff --git a/docs/handset.md b/docs/handset.md index 91df1a7..a04b047 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -50,3 +50,10 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux - [`camera/chandra-camera`](../camera/chandra-camera) and [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c) provide a native GTK3/Cairo Wayland camera app (no extra Python GI packages required) installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`). - Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, Photo mode (`HD` instant / `Full` high-resolution `StillCapture`, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording H.264 MP4s via `ffmpeg` to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control. + +## Remote Control Over Tailscale (`chandra-remote`) + +- [`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**). + - **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. +- 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://:6080/` or `: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. diff --git a/face/chandra-face b/face/chandra-face index 2443edd..ab18f95 100755 --- a/face/chandra-face +++ b/face/chandra-face @@ -509,6 +509,63 @@ def camera_problem(device): return "" +QUAD_BAYER_MODELS = {"imx371"} + + +def rotate_bgr(bgr, rot, cv2_mod): + """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle).""" + rot_i = int(rot) % 360 + if rot_i == 90: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE) + if rot_i == 180: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180) + if rot_i == 270: + return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE) + return bgr + + +def debayer_quad_csi2p( + raw_buf, + width, + height, + stride, + rot=0, + offset=0, + target_size=(640, 480), + gamma_lut=None, + cv2_mod=None, + np_mod=None, +): + """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8.""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) + row_bytes = (width // 4) * 5 + even_h = (height // 2) * 2 + b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, width // 4, 5)) + bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, width // 2))) + bgr = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) + if target_size is not None: + bgr = cv2_mod.resize(bgr, target_size, interpolation=cv2_mod.INTER_AREA) + + f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0) + means = f.mean(axis=(0, 1)) + avg = float(means.mean()) + if avg > 1.0: + gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2) + boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8)) + u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8) + else: + u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8) + if gamma_lut is None: + gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) + out = cv2_mod.LUT(u8, gamma_lut) + return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) + + class LibcameraCamera: """Capture BGR frames via python-libcamera (MIPI/SoftISP phone cameras).""" @@ -524,31 +581,67 @@ class LibcameraCamera: self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None) self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None + self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8) + self.sc = None + self.raw_sc = None + self.alloc = None + self.requests = [] + self._started = False + cid = device[len("libcamera:"):] self.cm = libcamera.CameraManager.singleton() self.cam = self.cm.get(cid) if self.cam is None: raise Fail("camera %s disappeared" % device, 2) self.rot = int(self.cam.properties.get(libcamera.properties.Rotation) or 0) + self.model = str(self.cam.properties.get(libcamera.properties.Model) or "").lower() try: self.cam.acquire() except Exception as e: raise Fail("couldn't acquire camera %s: %s" % (device, e), 2) try: - cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder]) - self.sc = cfg.at(0) - self.sc.size = libcamera.Size(640, 480) - cfg.validate() - self.cam.configure(cfg) + if self.model in QUAD_BAYER_MODELS: + try: + cfg = self.cam.generate_configuration([ + libcamera.StreamRole.Viewfinder, + libcamera.StreamRole.Raw, + ]) + if cfg is not None and len(cfg) >= 2: + cfg.at(0).size = libcamera.Size(640, 480) + cfg.validate() + self.cam.configure(cfg) + self.sc = cfg.at(0) + self.raw_sc = cfg.at(1) + except Exception: + self.raw_sc = None + + if self.raw_sc is None: + cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder]) + self.sc = cfg.at(0) + self.sc.size = libcamera.Size(640, 480) + cfg.validate() + self.cam.configure(cfg) + self.alloc = libcamera.FrameBufferAllocator(self.cam) if self.alloc.allocate(self.sc.stream) <= 0: raise Fail("couldn't allocate camera buffers for %s" % device, 2) self.requests = [] - for buf in self.alloc.buffers(self.sc.stream): - r = self.cam.create_request() - r.add_buffer(self.sc.stream, buf) - self.requests.append(r) + if self.raw_sc is not None: + if self.alloc.allocate(self.raw_sc.stream) <= 0: + raise Fail("couldn't allocate raw buffers for %s" % device, 2) + for b0, b1 in zip(self.alloc.buffers(self.sc.stream), self.alloc.buffers(self.raw_sc.stream)): + r = self.cam.create_request() + r.add_buffer(self.sc.stream, b0) + r.add_buffer(self.raw_sc.stream, b1) + self.requests.append(r) + else: + for buf in self.alloc.buffers(self.sc.stream): + r = self.cam.create_request() + r.add_buffer(self.sc.stream, buf) + self.requests.append(r) + self.cm.get_ready_requests() self.cam.start() + self._started = True for r in self.requests: self.cam.queue_request(r) except Exception as e: @@ -573,13 +666,27 @@ class LibcameraCamera: bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if fmt == "RGB888" else self.np.ascontiguousarray(img) else: raise Fail("unsupported libcamera pixel format %s" % fmt, 2) - if self.rot == 90: - return self.cv2.rotate(bgr, self.cv2.ROTATE_90_CLOCKWISE) - if self.rot == 180: - return self.cv2.rotate(bgr, self.cv2.ROTATE_180) - if self.rot == 270: - return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE) - return bgr + return self.np.ascontiguousarray(rotate_bgr(bgr, self.rot, self.cv2)) + + def _raw_to_bgr(self, buf): + p = buf.planes[0] + w, h, stride = self.raw_sc.size.width, self.raw_sc.size.height, self.raw_sc.stride + fmt = str(self.raw_sc.pixel_format) + if "CSI2P" not in fmt.upper(): + raise Fail("unsupported quad raw format %s" % fmt, 2) + with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm: + return debayer_quad_csi2p( + mm, + w, + h, + stride, + rot=self.rot, + offset=p.offset, + target_size=(640, 480), + gamma_lut=self._gamma_lut, + cv2_mod=self.cv2, + np_mod=self.np, + ) def _requeue(self, req): if self._reuse_arg is not None: @@ -605,7 +712,10 @@ class LibcameraCamera: frame = None try: if req.status == self.libcamera.Request.Status.Complete: - frame = self._to_bgr(req.buffers[self.sc.stream]) + if self.raw_sc is not None and self.raw_sc.stream in req.buffers: + frame = self._raw_to_bgr(req.buffers[self.raw_sc.stream]) + elif self.sc is not None and self.sc.stream in req.buffers: + frame = self._to_bgr(req.buffers[self.sc.stream]) finally: self._requeue(req) if frame is not None: @@ -615,11 +725,19 @@ class LibcameraCamera: def close(self): try: - self.cam.stop() + if getattr(self, "_started", False): + self.cam.stop() + except Exception: + pass + self._started = False + try: + self.cm.get_ready_requests() except Exception: pass self.requests = [] self.alloc = None + self.sc = None + self.raw_sc = None try: self.cam.release() except Exception: diff --git a/remote/auth.c b/remote/auth.c new file mode 100644 index 0000000..3c31a2d --- /dev/null +++ b/remote/auth.c @@ -0,0 +1,329 @@ +#include "remote_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void remote_default_config(RemoteConfig *cfg) { + memset(cfg, 0, sizeof *cfg); + cfg->enabled = 1; + snprintf(cfg->bind, sizeof cfg->bind, "tailscale"); + cfg->bind_loopback = 1; + cfg->auth_mode = REMOTE_AUTH_NONE; + cfg->vnc_port = 5900; + cfg->web_port = 6080; + cfg->jpeg_quality = 82; + cfg->max_fps = 30; +} + +int remote_bind_is_loopback(const char *b) { + return strcmp(b, "127.0.0.1") == 0 || strcmp(b, "::1") == 0 || strcmp(b, "localhost") == 0; +} + +int remote_bind_is_tailscale(const char *b) { + return strcmp(b, "tailscale") == 0; +} + +void remote_generate_password(char *out, size_t len) { + static const char alpha[] = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz"; + size_t n = sizeof(alpha) - 1; + uint8_t rnd[64]; + if (len == 0) return; + if (len > sizeof rnd) len = sizeof rnd; + if (RAND_bytes(rnd, (int)len) != 1) { + for (size_t i = 0; i < len - 1; i++) out[i] = alpha[i % n]; + out[len - 1] = 0; + return; + } + for (size_t i = 0; i < len - 1; i++) { + out[i] = alpha[rnd[i] % n]; + } + out[len - 1] = 0; +} + +static char *trim_ws(char *s) { + while (*s && isspace((unsigned char)*s)) s++; + size_t l = strlen(s); + while (l > 0 && isspace((unsigned char)s[l - 1])) s[--l] = 0; + return s; +} + +static int clamp_int(int v, int lo, int hi) { + return v < lo ? lo : (v > hi ? hi : v); +} + +static void mkdir_parents(const char *file_path) { + char tmp[512]; + snprintf(tmp, sizeof tmp, "%s", file_path); + for (char *p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = 0; + mkdir(tmp, 0700); + *p = '/'; + } + } +} + +int remote_save_config(const char *path, const RemoteConfig *cfg) { + mkdir_parents(path); + char tmp[528]; + snprintf(tmp, sizeof tmp, "%s.tmp", path); + FILE *f = fopen(tmp, "w"); + if (!f) return -1; + chmod(tmp, 0600); + fprintf(f, + "# Chandra Remote Desktop configuration\n" + "enabled=%d\n" + "bind=%s\n" + "bind_loopback=%d\n" + "auth=%s\n" + "vnc_port=%d\n" + "web_port=%d\n" + "jpeg_quality=%d\n" + "max_fps=%d\n", + cfg->enabled ? 1 : 0, + cfg->bind, + cfg->bind_loopback ? 1 : 0, + cfg->auth_mode == REMOTE_AUTH_NONE ? "none" : "password", + cfg->vnc_port, + cfg->web_port, + cfg->jpeg_quality, + cfg->max_fps); + if (cfg->password[0]) { + fprintf(f, "password=%s\n", cfg->password); + } + fclose(f); + if (rename(tmp, path) < 0) { + unlink(tmp); + return -1; + } + chmod(path, 0600); + return 0; +} + +int remote_load_or_init_config(const char *path, RemoteConfig *cfg) { + remote_default_config(cfg); + FILE *f = fopen(path, "r"); + if (!f) { + if (errno == ENOENT) { + return remote_save_config(path, cfg); + } + return -1; + } + char line[256]; + while (fgets(line, sizeof line, f)) { + char *s = trim_ws(line); + if (!*s || *s == '#') continue; + char *eq = strchr(s, '='); + if (!eq) continue; + *eq = 0; + char *k = trim_ws(s); + char *v = trim_ws(eq + 1); + if (strcmp(k, "enabled") == 0) cfg->enabled = atoi(v) != 0; + else if (strcmp(k, "bind") == 0) snprintf(cfg->bind, sizeof cfg->bind, "%s", v); + else if (strcmp(k, "bind_loopback") == 0) cfg->bind_loopback = atoi(v) != 0; + else if (strcmp(k, "auth") == 0) { + cfg->auth_mode = strcmp(v, "none") == 0 ? REMOTE_AUTH_NONE : REMOTE_AUTH_PASSWORD; + } else if (strcmp(k, "vnc_port") == 0) cfg->vnc_port = clamp_int(atoi(v), 1, 65535); + else if (strcmp(k, "web_port") == 0) cfg->web_port = clamp_int(atoi(v), 1, 65535); + else if (strcmp(k, "jpeg_quality") == 0) cfg->jpeg_quality = clamp_int(atoi(v), 20, 95); + else if (strcmp(k, "max_fps") == 0) cfg->max_fps = clamp_int(atoi(v), 5, 60); + else if (strcmp(k, "password") == 0) snprintf(cfg->password, sizeof cfg->password, "%s", v); + } + fclose(f); + if (cfg->auth_mode == REMOTE_AUTH_PASSWORD && !cfg->password[0]) { + remote_generate_password(cfg->password, 11); + remote_save_config(path, cfg); + } + return 0; +} + +int remote_ct_equal(const uint8_t hmac_key[32], const char *a, const char *b) { + uint8_t da[32], db[32]; + unsigned int la = 0, lb = 0; + HMAC(EVP_sha256(), hmac_key, 32, (const uint8_t *)a, strlen(a), da, &la); + HMAC(EVP_sha256(), hmac_key, 32, (const uint8_t *)b, strlen(b), db, &lb); + return la == 32 && lb == 32 && CRYPTO_memcmp(da, db, 32) == 0 && strlen(a) == strlen(b); +} + +/* ---- Self-contained FIPS-46 DES (no OpenSSL 3 legacy provider needed) ---- */ + +static const uint8_t des_pc1[56] = { + 57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36, + 63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4 +}; +static const uint8_t des_pc2[48] = { + 14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2, + 41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32 +}; +static const uint8_t des_rot[16] = { 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1 }; +static const uint8_t des_ip[64] = { + 58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8, + 57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7 +}; +static const uint8_t des_fp[64] = { + 40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29, + 36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25 +}; +static const uint8_t des_e[48] = { + 32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17, + 16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1 +}; +static const uint8_t des_p[32] = { + 16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25 +}; +static const uint8_t des_s[8][64] = { + {14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7, 0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8, + 4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0, 15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13}, + {15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10, 3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5, + 0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15, 13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9}, + {10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8, 13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1, + 13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7, 1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12}, + {7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15, 13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9, + 10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4, 3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14}, + {2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9, 14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6, + 4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14, 11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3}, + {12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11, 10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8, + 9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6, 4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13}, + {4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1, 13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6, + 1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2, 6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12}, + {13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7, 1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2, + 7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8, 2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11} +}; + +static uint64_t permute_be(uint64_t val, int in_bits, const uint8_t *tbl, int out_bits) { + uint64_t res = 0; + for (int i = 0; i < out_bits; i++) { + int shift = in_bits - tbl[i]; + res = (res << 1) | ((val >> shift) & 1ULL); + } + return res; +} + +static uint32_t rol28(uint32_t v, int k) { + return ((v << k) | (v >> (28 - k))) & 0x0FFFFFFFu; +} + +static uint32_t des_feistel(uint32_t r, uint64_t subkey) { + uint64_t exp = permute_be(r, 32, des_e, 48) ^ subkey; + uint32_t s_out = 0; + for (int i = 0; i < 8; i++) { + uint8_t six = (uint8_t)((exp >> ((7 - i) * 6)) & 0x3Fu); + int row = ((six & 0x20u) >> 4) | (six & 0x01u); + int col = (six >> 1) & 0x0Fu; + s_out = (s_out << 4) | des_s[i][row * 16 + col]; + } + return (uint32_t)permute_be(s_out, 32, des_p, 32); +} + +static void des_ecb_encrypt(const uint8_t key[8], const uint8_t in[8], uint8_t out[8]) { + uint64_t k64 = 0, d64 = 0; + for (int i = 0; i < 8; i++) { + k64 = (k64 << 8) | key[i]; + d64 = (d64 << 8) | in[i]; + } + uint64_t cd = permute_be(k64, 64, des_pc1, 56); + uint32_t c = (uint32_t)(cd >> 28) & 0x0FFFFFFFu; + uint32_t d = (uint32_t)cd & 0x0FFFFFFFu; + uint64_t sk[16]; + for (int r = 0; r < 16; r++) { + c = rol28(c, des_rot[r]); + d = rol28(d, des_rot[r]); + sk[r] = permute_be(((uint64_t)c << 28) | d, 56, des_pc2, 48); + } + uint64_t ip = permute_be(d64, 64, des_ip, 64); + uint32_t L = (uint32_t)(ip >> 32); + uint32_t R = (uint32_t)ip; + for (int r = 0; r < 16; r++) { + uint32_t nR = L ^ des_feistel(R, sk[r]); + L = R; + R = nR; + } + uint64_t pre = ((uint64_t)R << 32) | L; + uint64_t ciph = permute_be(pre, 64, des_fp, 64); + for (int i = 0; i < 8; i++) out[i] = (uint8_t)((ciph >> ((7 - i) * 8)) & 0xFFu); +} + +static uint8_t rev8(uint8_t b) { + b = (uint8_t)(((b & 0xF0u) >> 4) | ((b & 0x0Fu) << 4)); + b = (uint8_t)(((b & 0xCCu) >> 2) | ((b & 0x33u) << 2)); + b = (uint8_t)(((b & 0xAAu) >> 1) | ((b & 0x55u) << 1)); + return b; +} + +void vnc_des_encrypt_challenge(const char *password, const uint8_t challenge[16], uint8_t out[16]) { + uint8_t key[8]; + size_t plen = strlen(password); + for (int i = 0; i < 8; i++) { + uint8_t ch = (i < (int)plen) ? (uint8_t)password[i] : 0u; + key[i] = rev8(ch); + } + des_ecb_encrypt(key, challenge, out); + des_ecb_encrypt(key, challenge + 8, out + 8); +} + +/* ---- Web session token & RFC 6455 accept ---- */ + +static const uint64_t WEB_TOKEN_TTL_SEC = 30ULL * 24ULL * 3600ULL; + +void web_token_sign(const uint8_t key[32], uint64_t now_sec, char *out, size_t cap) { + char ts[32]; + snprintf(ts, sizeof ts, "%llu", (unsigned long long)now_sec); + uint8_t mac[32]; + unsigned int mlen = 0; + HMAC(EVP_sha256(), key, 32, (const uint8_t *)ts, strlen(ts), mac, &mlen); + char hex[65]; + hex_encode(mac, mlen, hex); + snprintf(out, cap, "%s.%s", ts, hex); +} + +int web_token_verify(const uint8_t key[32], const char *tok, uint64_t now_sec) { + if (!tok || !*tok) return 0; + const char *dot = strchr(tok, '.'); + if (!dot || dot == tok || strlen(dot + 1) != 64) return 0; + char ts[32]; + size_t tlen = (size_t)(dot - tok); + if (tlen >= sizeof ts) return 0; + memcpy(ts, tok, tlen); + ts[tlen] = 0; + char *endp = NULL; + uint64_t issued = strtoull(ts, &endp, 10); + if (!endp || *endp != 0) return 0; + if (now_sec > issued && now_sec - issued > WEB_TOKEN_TTL_SEC) return 0; + if (issued > now_sec + 300ULL) return 0; + + uint8_t expected[32], got[32]; + unsigned int elen = 0; + HMAC(EVP_sha256(), key, 32, (const uint8_t *)ts, tlen, expected, &elen); + for (int i = 0; i < 32; i++) { + unsigned int v = 0; + if (sscanf(dot + 1 + i * 2, "%2x", &v) != 1) return 0; + got[i] = (uint8_t)v; + } + return elen == 32 && CRYPTO_memcmp(expected, got, 32) == 0; +} + +int ws_compute_accept(const char *client_key, char *out, size_t cap) { + static const char guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + char buf[256]; + if (!client_key || strlen(client_key) > 128) return -1; + snprintf(buf, sizeof buf, "%s%s", client_key, guid); + uint8_t sha[EVP_MAX_MD_SIZE]; + unsigned int slen = 0; + if (!EVP_Digest(buf, strlen(buf), sha, &slen, EVP_sha1(), NULL)) return -1; + if (cap < 32) return -1; + int n = EVP_EncodeBlock((unsigned char *)out, sha, (int)slen); + if (n <= 0 || (size_t)n >= cap) return -1; + out[n] = 0; + return 0; +} diff --git a/remote/chandra-remote.c b/remote/chandra-remote.c new file mode 100644 index 0000000..8ee9f7e --- /dev/null +++ b/remote/chandra-remote.c @@ -0,0 +1,767 @@ +#include "remote_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t g_running = 1; +static volatile sig_atomic_t g_reload = 0; + +static void on_term(int sig) { + (void)sig; + g_running = 0; +} + +static void on_hup(int sig) { + (void)sig; + g_reload = 1; +} + +uint64_t remote_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)ts.tv_nsec / 1000000ULL; +} + +void remote_sleep_ms(int ms) { + if (ms <= 0) return; + struct timespec req = { .tv_sec = ms / 1000, .tv_nsec = (long)(ms % 1000) * 1000000L }; + while (nanosleep(&req, &req) < 0 && errno == EINTR && g_running) {} +} + +/* ---- Control socket client ---- */ + +static int unix_connect_path(const char *path) { + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) return -1; + struct timeval tv = { .tv_sec = 2, .tv_usec = 0 }; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); + struct sockaddr_un sa; + memset(&sa, 0, sizeof sa); + sa.sun_family = AF_UNIX; + if (strlen(path) >= sizeof sa.sun_path) { close(fd); return -1; } + snprintf(sa.sun_path, sizeof sa.sun_path, "%s", path); + if (connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) { + close(fd); + return -1; + } + return fd; +} + +static int resolve_control_socket(char *out, size_t cap) { + const char *env = getenv("CHANDRA_CONTROL"); + if (env && env[0]) { snprintf(out, cap, "%s", env); return 0; } + char rt[256]; + const char *xrt = getenv("XDG_RUNTIME_DIR"); + if (xrt && xrt[0]) snprintf(rt, sizeof rt, "%s", xrt); + else snprintf(rt, sizeof rt, "/run/user/%u", (unsigned)getuid()); + const char *wd = getenv("WAYLAND_DISPLAY"); + if (wd && wd[0]) { + const char *base = strrchr(wd, '/'); + base = base ? base + 1 : wd; + snprintf(out, cap, "%s/chandra/%s.sock", rt, base); + if (access(out, F_OK) == 0) return 0; + } + snprintf(out, cap, "%s/chandra/wayland-moon-0.sock", rt); + return 0; +} + +static int resolve_shm_path(char *out, size_t cap) { + const char *env = getenv("CHANDRA_FB_SHM"); + if (env && env[0]) { snprintf(out, cap, "%s", env); return 0; } + char rt[256]; + const char *xrt = getenv("XDG_RUNTIME_DIR"); + if (xrt && xrt[0]) snprintf(rt, sizeof rt, "%s", xrt); + else snprintf(rt, sizeof rt, "/run/user/%u", (unsigned)getuid()); + snprintf(out, cap, "%s/chandra/fb.shm", rt); + return 0; +} + +static void default_config_path(char *out, size_t cap) { + const char *xc = getenv("XDG_CONFIG_HOME"); + if (xc && xc[0]) { + snprintf(out, cap, "%s/chandra/remote.conf", xc); + return; + } + const char *home = getenv("HOME"); + snprintf(out, cap, "%s/.config/chandra/remote.conf", home && home[0] ? home : "/tmp"); +} + +static void default_pid_path(char *out, size_t cap) { + const char *xrt = getenv("XDG_RUNTIME_DIR"); + if (xrt && xrt[0]) snprintf(out, cap, "%s/chandra/remote.pid", xrt); + else snprintf(out, cap, "/run/user/%u/chandra/remote.pid", (unsigned)getuid()); +} + +void ctl_init(CtlConn *c, const char *sock_path) { + pthread_mutex_init(&c->mu, NULL); + c->fd = -1; + c->last_try_ms = 0; + snprintf(c->sock_path, sizeof c->sock_path, "%s", sock_path); +} + +void ctl_close(CtlConn *c) { + pthread_mutex_lock(&c->mu); + if (c->fd >= 0) { close(c->fd); c->fd = -1; } + pthread_mutex_unlock(&c->mu); +} + +static int ctl_once_locked(CtlConn *c, const char *line, 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; + c->last_try_ms = now; + c->fd = unix_connect_path(c->sock_path); + if (c->fd < 0) return -1; + } + size_t l = strlen(line); + char *msg = malloc(l + 2); + if (!msg) return -1; + memcpy(msg, line, l); + msg[l] = '\n'; + size_t sent = 0; + while (sent < l + 1) { + ssize_t w = send(c->fd, msg + sent, l + 1 - sent, MSG_NOSIGNAL); + if (w <= 0) { + free(msg); + close(c->fd); + c->fd = -1; + c->last_try_ms = 0; + return -1; + } + sent += (size_t)w; + } + free(msg); + + char rbuf[4096]; + size_t rlen = 0; + int ok = -1; + for (;;) { + ssize_t r = recv(c->fd, rbuf + rlen, sizeof rbuf - 1 - rlen, 0); + if (r <= 0) { + close(c->fd); + c->fd = -1; + c->last_try_ms = 0; + return -1; + } + rlen += (size_t)r; + rbuf[rlen] = 0; + if (rbuf[rlen - 1] == '\n') { + /* Check the last non-empty line for ok / error terminator. */ + char *last = rbuf; + for (size_t i = 0; i + 1 < rlen; i++) { + if (rbuf[i] == '\n') last = rbuf + i + 1; + } + if (strncmp(last, "ok", 2) == 0 && (last[2] == 0 || last[2] == ' ' || last[2] == '\n')) { + ok = 0; + break; + } + if (strncmp(last, "error", 5) == 0 && (last[5] == 0 || last[5] == ' ' || last[5] == '\n')) { + ok = 1; + break; + } + } + if (rlen + 1 >= sizeof rbuf) break; + } + if (reply && reply_cap > 0) { + /* Strip trailing newline into reply buffer. */ + while (rlen > 0 && (rbuf[rlen - 1] == '\n' || rbuf[rlen - 1] == '\r')) rlen--; + size_t cp = rlen < reply_cap - 1 ? rlen : reply_cap - 1; + memcpy(reply, rbuf, cp); + reply[cp] = 0; + } + return ok; +} + +int ctl_cmd(CtlConn *c, const char *line, char *reply, size_t reply_cap) { + pthread_mutex_lock(&c->mu); + int r = ctl_once_locked(c, line, reply, reply_cap); + if (r < 0) { + c->last_try_ms = 0; + r = ctl_once_locked(c, line, reply, reply_cap); + } + pthread_mutex_unlock(&c->mu); + return r; +} + +int ctl_fire(CtlConn *c, const char *line) { + return ctl_cmd(c, line, NULL, 0); +} + +/* ---- Shared-memory framebuffer reader ---- */ + +void fb_reader_init(FbReader *r, const char *shm_path) { + r->fd = -1; + r->hdr = NULL; + r->last_open_try_ms = 0; + snprintf(r->shm_path, sizeof r->shm_path, "%s", shm_path); +} + +void fb_reader_close(FbReader *r) { + if (r->hdr) { munmap(r->hdr, CHANDRA_FB_TOTAL_BYTES); r->hdr = NULL; } + if (r->fd >= 0) { close(r->fd); r->fd = -1; } +} + +static int fb_ensure_open(FbReader *r) { + if (r->hdr) return 0; + uint64_t now = remote_now_ms(); + if (now - r->last_open_try_ms < 250) return -1; + r->last_open_try_ms = now; + int fd = open(r->shm_path, O_RDWR | O_CLOEXEC); + if (fd < 0) return -1; + struct stat st; + if (fstat(fd, &st) < 0 || (size_t)st.st_size < CHANDRA_FB_TOTAL_BYTES) { + close(fd); + return -1; + } + void *m = mmap(NULL, CHANDRA_FB_TOTAL_BYTES, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (m == MAP_FAILED) { + close(fd); + return -1; + } + ChandraFbHeader *hdr = (ChandraFbHeader *)m; + if (hdr->magic != CHANDRA_FB_MAGIC || hdr->version != CHANDRA_FB_VERSION || + hdr->slot_bytes != CHANDRA_FB_SLOT_BYTES) { + munmap(m, CHANDRA_FB_TOTAL_BYTES); + close(fd); + return -1; + } + r->fd = fd; + r->hdr = hdr; + return 0; +} + +void fb_reader_ping(FbReader *r) { + if (fb_ensure_open(r) < 0) return; + __atomic_store_n(&r->hdr->consumer_ping_ms, remote_now_ms(), __ATOMIC_RELEASE); +} + +int fb_reader_grab( + FbReader *r, + uint64_t last_seq, + uint32_t last_w, + uint32_t last_h, + int *out_full, + uint32_t *out_w, + uint32_t *out_h, + int *out_x0, + int *out_y0, + int *out_x1, + int *out_y1, + uint64_t *out_seq, + uint8_t **scratch, + size_t *scratch_cap) { + if (fb_ensure_open(r) < 0) return -1; + ChandraFbHeader *hdr = r->hdr; + + for (int attempt = 0; attempt < 3; attempt++) { + uint64_t seq1 = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE); + if (seq1 == 0) return 0; + uint32_t w = hdr->width; + uint32_t h = hdr->height; + if (w == 0 || h == 0 || w > 4096 || h > 4096 || + (size_t)w * (size_t)h * 4 > hdr->slot_bytes) { + return 0; + } + if (seq1 == last_seq && w == last_w && h == last_h) return 0; + + int full = (attempt > 0 || last_seq == 0 || seq1 < last_seq || + seq1 > last_seq + 1 || w != last_w || h != last_h); + int x0 = full ? 0 : hdr->dmg_x0; + int y0 = full ? 0 : hdr->dmg_y0; + int x1 = full ? (int)w : hdr->dmg_x1; + int y1 = full ? (int)h : hdr->dmg_y1; + if (x0 < 0) x0 = 0; + if (y0 < 0) y0 = 0; + if (x1 > (int)w) x1 = (int)w; + if (y1 > (int)h) y1 = (int)h; + if (x0 >= x1 || y0 >= y1) { + x0 = 0; y0 = 0; x1 = (int)w; y1 = (int)h; + full = 1; + } + + size_t need = (size_t)w * (size_t)h * 4; + if (*scratch_cap < need) { + uint8_t *ns = realloc(*scratch, need); + if (!ns) return -1; + *scratch = ns; + *scratch_cap = need; + } + + uint32_t slot = __atomic_load_n(&hdr->active_slot, __ATOMIC_ACQUIRE) & 1u; + const uint8_t *src = chandra_fb_slot_ptr(hdr, slot, hdr->slot_bytes); + if (x0 == 0 && x1 == (int)w) { + size_t off = (size_t)y0 * (size_t)w * 4; + size_t bytes = (size_t)(y1 - y0) * (size_t)w * 4; + memcpy(*scratch + off, src + off, bytes); + } else { + size_t span = (size_t)(x1 - x0) * 4; + for (int y = y0; y < y1; y++) { + size_t off = ((size_t)y * (size_t)w + (size_t)x0) * 4; + memcpy(*scratch + off, src + off, span); + } + } + + uint64_t seq2 = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE); + if (seq2 == seq1 && hdr->width == w && hdr->height == h) { + *out_full = full; + *out_w = w; + *out_h = h; + *out_x0 = x0; + *out_y0 = y0; + *out_x1 = x1; + *out_y1 = y1; + *out_seq = seq1; + return 1; + } + } + return 0; +} + +/* ---- Network & Tailscale interface lookup ---- */ + +static int is_tailscale_ipv4(uint32_t host_order_ip) { + return (host_order_ip & 0xFFC00000u) == 0x64400000u; /* 100.64.0.0/10 */ +} + +static int is_loopback_ipv4(uint32_t host_order_ip) { + return (host_order_ip & 0xFF000000u) == 0x7F000000u; /* 127.0.0.0/8 */ +} + +int remote_find_tailscale_ipv4(char *out, size_t cap) { + struct ifaddrs *ifap = NULL; + if (getifaddrs(&ifap) < 0) return -1; + int found = -1; + for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) continue; + if (!ifa->ifa_name) continue; + if (strcmp(ifa->ifa_name, "tailscale0") != 0 && + strncmp(ifa->ifa_name, "tailscale", 9) != 0 && + strncmp(ifa->ifa_name, "ts", 2) != 0) { + continue; + } + const struct sockaddr_in *sin = (const struct sockaddr_in *)ifa->ifa_addr; + uint32_t ip = ntohl(sin->sin_addr.s_addr); + if (!is_tailscale_ipv4(ip)) continue; + if (inet_ntop(AF_INET, &sin->sin_addr, out, (socklen_t)cap)) { + found = 0; + if (strcmp(ifa->ifa_name, "tailscale0") == 0) break; + } + } + freeifaddrs(ifap); + return found; +} + +int remote_peer_allowed(const RemoteConfig *cfg, const struct sockaddr_storage *ss, socklen_t slen) { + if (!remote_bind_is_tailscale(cfg->bind) || cfg->allow_insecure_open) return 1; + if (ss->ss_family == AF_INET && slen >= (socklen_t)sizeof(struct sockaddr_in)) { + const struct sockaddr_in *s = (const struct sockaddr_in *)ss; + uint32_t ip = ntohl(s->sin_addr.s_addr); + return is_tailscale_ipv4(ip) || (cfg->bind_loopback && is_loopback_ipv4(ip)); + } + if (ss->ss_family == AF_INET6 && slen >= (socklen_t)sizeof(struct sockaddr_in6)) { + const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)ss; + if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr)) { + uint32_t ip = ((uint32_t)s6->sin6_addr.s6_addr[12] << 24) | + ((uint32_t)s6->sin6_addr.s6_addr[13] << 16) | + ((uint32_t)s6->sin6_addr.s6_addr[14] << 8) | + (uint32_t)s6->sin6_addr.s6_addr[15]; + return is_tailscale_ipv4(ip) || (cfg->bind_loopback && is_loopback_ipv4(ip)); + } + if (s6->sin6_addr.s6_addr[0] == 0xFD && s6->sin6_addr.s6_addr[1] == 0x7A) return 1; + if (cfg->bind_loopback && IN6_IS_ADDR_LOOPBACK(&s6->sin6_addr)) return 1; + } + return 0; +} + +static int listen_tcp(const char *ip, int port) { + int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) return -1; + int one = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); + struct sockaddr_in sin; + memset(&sin, 0, sizeof sin); + sin.sin_family = AF_INET; + sin.sin_port = htons((uint16_t)port); + if (strcmp(ip, "0.0.0.0") == 0) { + sin.sin_addr.s_addr = INADDR_ANY; + } else if (inet_pton(AF_INET, ip, &sin.sin_addr) != 1) { + close(fd); + return -1; + } + if (bind(fd, (struct sockaddr *)&sin, sizeof sin) < 0 || listen(fd, 16) < 0) { + close(fd); + return -1; + } + return fd; +} + +typedef struct { + RemoteApp *app; + int fd; + int is_web; +} ClientArg; + +static void *client_thread(void *arg) { + ClientArg *ca = (ClientArg *)arg; + RemoteApp *app = ca->app; + int fd = ca->fd; + int is_web = ca->is_web; + free(ca); + if (is_web) web_handle_client(app, fd); + else rfb_handle_client(app, fd); + return NULL; +} + +static void spawn_client(RemoteApp *app, int cfd, int is_web) { + struct sockaddr_storage ss; + socklen_t slen = sizeof ss; + if (getpeername(cfd, (struct sockaddr *)&ss, &slen) == 0) { + RemoteConfig cfg; + pthread_mutex_lock(&app->cfg_mu); + cfg = app->cfg; + pthread_mutex_unlock(&app->cfg_mu); + if (!remote_peer_allowed(&cfg, &ss, slen)) { + close(cfd); + return; + } + } + ClientArg *ca = malloc(sizeof *ca); + if (!ca) { close(cfd); return; } + ca->app = app; + ca->fd = cfd; + ca->is_web = is_web; + pthread_t th; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + if (pthread_create(&th, &attr, client_thread, ca) != 0) { + free(ca); + close(cfd); + } + pthread_attr_destroy(&attr); +} + +static int read_magic_dns_fqdn(char *out, size_t cap) { + FILE *p = popen("tailscale status --json 2>/dev/null", "r"); + if (!p) return -1; + char buf[8192]; + size_t n = fread(buf, 1, sizeof buf - 1, p); + pclose(p); + buf[n] = 0; + char *self = strstr(buf, "\"Self\""); + if (!self) return -1; + char *dns = strstr(self, "\"DNSName\""); + if (!dns) return -1; + dns = strchr(dns + 9, '"'); + if (!dns) return -1; + dns++; + char *end = strchr(dns, '"'); + if (!end || end == dns) return -1; + size_t l = (size_t)(end - dns); + while (l > 0 && dns[l - 1] == '.') l--; + if (l >= cap) l = cap - 1; + memcpy(out, dns, l); + out[l] = 0; + return l > 0 ? 0 : -1; +} + +static int cmd_status(const char *config_path, const char *pid_path) { + RemoteConfig cfg; + if (remote_load_or_init_config(config_path, &cfg) < 0) { + fprintf(stderr, "chandra-remote: cannot read config %s\n", config_path); + return 1; + } + long pid = 0; + FILE *pf = fopen(pid_path, "r"); + if (pf) { + if (fscanf(pf, "%ld", &pid) != 1) pid = 0; + fclose(pf); + } + int running = (pid > 1 && kill((pid_t)pid, 0) == 0); + char ts_ip[64] = {0}, fqdn[128] = {0}; + int has_ts = remote_find_tailscale_ipv4(ts_ip, sizeof ts_ip) == 0; + int has_fqdn = read_magic_dns_fqdn(fqdn, sizeof fqdn) == 0; + + printf("daemon: %s", running ? "running" : "stopped"); + if (running) printf(" (pid %ld)", pid); + printf("\nconfig: %s\nenabled: %s\nbind: %s (loopback=%s)\nauth: %s\n", + config_path, cfg.enabled ? "yes" : "no", cfg.bind, + cfg.bind_loopback ? "on" : "off", + cfg.auth_mode == REMOTE_AUTH_NONE ? "none (Tailscale/loopback trust)" : "password"); + if (has_ts) printf("tailscale_ip: %s\n", ts_ip); + else printf("tailscale_ip: (waiting for tailscale0)\n"); + if (has_fqdn) printf("tailscale_dns: %s\n", fqdn); + const char *host = has_fqdn ? fqdn : (has_ts ? ts_ip : ""); + printf("web_url: http://%s:%d/\nvnc: %s:%d\n", host, cfg.web_port, host, cfg.vnc_port); + + char sock[512]; + resolve_control_socket(sock, sizeof sock); + CtlConn ctl; + ctl_init(&ctl, sock); + char rep[256]; + if (ctl_cmd(&ctl, "status", rep, sizeof rep) == 0) { + printf("compositor: %s\n", rep); + } else { + printf("compositor: offline (%s)\n", sock); + } + ctl_close(&ctl); + return 0; +} + +static int cmd_passwd(const char *config_path, const char *pid_path, const char *arg) { + RemoteConfig cfg; + if (remote_load_or_init_config(config_path, &cfg) < 0) return 1; + if (strcmp(arg, "--none") == 0) { + if (!remote_bind_is_tailscale(cfg.bind) && !remote_bind_is_loopback(cfg.bind)) { + fprintf(stderr, "error: auth=none is only allowed with bind=tailscale or loopback\n"); + return 1; + } + cfg.auth_mode = REMOTE_AUTH_NONE; + cfg.password[0] = 0; + printf("auth set to none (Tailscale/loopback trust)\n"); + } else { + cfg.auth_mode = REMOTE_AUTH_PASSWORD; + snprintf(cfg.password, sizeof cfg.password, "%s", arg); + printf("password updated (auth=password)\n"); + } + if (remote_save_config(config_path, &cfg) < 0) return 1; + FILE *pf = fopen(pid_path, "r"); + if (pf) { + long pid = 0; + if (fscanf(pf, "%ld", &pid) == 1 && pid > 1) kill((pid_t)pid, SIGHUP); + fclose(pf); + } + return 0; +} + +int main(int argc, char **argv) { + char config_path[512], sock_path[512], shm_path[512], web_dir[512], pid_path[512]; + default_config_path(config_path, sizeof config_path); + resolve_control_socket(sock_path, sizeof sock_path); + resolve_shm_path(shm_path, sizeof shm_path); + default_pid_path(pid_path, sizeof pid_path); + const char *wd_env = getenv("CHANDRA_REMOTE_WEB_DIR"); + snprintf(web_dir, sizeof web_dir, "%s", + (wd_env && wd_env[0]) ? wd_env : "/usr/local/share/chandra/remote"); + + const char *override_bind = NULL; + int override_no_loopback = 0; + int override_no_auth = 0; + int override_insecure = 0; + int override_vnc_port = 0; + int override_web_port = 0; + pid_t parent_pid = 0; + + if (argc >= 2 && strcmp(argv[1], "status") == 0) { + for (int i = 2; i < argc - 1; i++) { + if (strcmp(argv[i], "--config") == 0) snprintf(config_path, sizeof config_path, "%s", argv[++i]); + } + return cmd_status(config_path, pid_path); + } + if (argc >= 2 && strcmp(argv[1], "passwd") == 0) { + const char *val = (argc >= 3) ? argv[2] : NULL; + char gen[16]; + if (!val) { remote_generate_password(gen, 11); val = gen; printf("generated password: %s\n", val); } + return cmd_passwd(config_path, pid_path, val); + } + + for (int i = 1; i < argc; i++) { + const char *a = argv[i]; + if (strcmp(a, "--config") == 0 && i + 1 < argc) snprintf(config_path, sizeof config_path, "%s", argv[++i]); + else if (strcmp(a, "--socket") == 0 && i + 1 < argc) snprintf(sock_path, sizeof sock_path, "%s", argv[++i]); + else if (strcmp(a, "--shm") == 0 && i + 1 < argc) snprintf(shm_path, sizeof shm_path, "%s", argv[++i]); + else if (strcmp(a, "--web-dir") == 0 && i + 1 < argc) snprintf(web_dir, sizeof web_dir, "%s", argv[++i]); + else if (strcmp(a, "--bind") == 0 && i + 1 < argc) override_bind = argv[++i]; + else if (strcmp(a, "--no-loopback") == 0) override_no_loopback = 1; + else if (strcmp(a, "--no-auth") == 0) override_no_auth = 1; + else if (strcmp(a, "--allow-insecure-open") == 0) override_insecure = 1; + else if (strcmp(a, "--vnc-port") == 0 && i + 1 < argc) override_vnc_port = atoi(argv[++i]); + else if (strcmp(a, "--web-port") == 0 && i + 1 < argc) override_web_port = atoi(argv[++i]); + else if (strcmp(a, "--parent-pid") == 0 && i + 1 < argc) parent_pid = (pid_t)atol(argv[++i]); + else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) { + printf("usage: chandra-remote [status | passwd [PASS|--none] | --config PATH --socket PATH --shm PATH --web-dir DIR --bind IP --no-loopback --no-auth --vnc-port N --web-port N --parent-pid PID]\n"); + return 0; + } + } + + RemoteApp app; + memset(&app, 0, sizeof app); + app.running = &g_running; + pthread_mutex_init(&app.cfg_mu, NULL); + pthread_mutex_init(&app.ping_mu, NULL); + snprintf(app.config_path, sizeof app.config_path, "%s", config_path); + snprintf(app.web_dir, sizeof app.web_dir, "%s", web_dir); + snprintf(app.shm_path, sizeof app.shm_path, "%s", shm_path); + ctl_init(&app.ctl, sock_path); + if (RAND_bytes(app.hmac_key, sizeof app.hmac_key) != 1) { + fprintf(stderr, "chandra-remote: RAND_bytes failed\n"); + return 1; + } + + if (remote_load_or_init_config(config_path, &app.cfg) < 0) { + fprintf(stderr, "chandra-remote: failed to load/init config %s\n", config_path); + return 1; + } + if (override_bind) snprintf(app.cfg.bind, sizeof app.cfg.bind, "%s", override_bind); + if (override_no_loopback) app.cfg.bind_loopback = 0; + if (override_no_auth) app.cfg.auth_mode = REMOTE_AUTH_NONE; + if (override_insecure) app.cfg.allow_insecure_open = 1; + if (override_vnc_port > 0) app.cfg.vnc_port = override_vnc_port; + if (override_web_port > 0) app.cfg.web_port = override_web_port; + + if (app.cfg.auth_mode == REMOTE_AUTH_NONE && + !remote_bind_is_tailscale(app.cfg.bind) && + !remote_bind_is_loopback(app.cfg.bind) && + !app.cfg.allow_insecure_open) { + fprintf(stderr, "chandra-remote: refusing unauthenticated bind='%s' (use bind=tailscale or 127.0.0.1)\n", + app.cfg.bind); + return 1; + } + + signal(SIGPIPE, SIG_IGN); + signal(SIGINT, on_term); + signal(SIGTERM, on_term); + signal(SIGHUP, on_hup); + + /* Record PID for `chandra-remote status` / `passwd`. */ + { + char pdir[512]; + snprintf(pdir, sizeof pdir, "%s", pid_path); + char *slash = strrchr(pdir, '/'); + if (slash) { *slash = 0; mkdir(pdir, 0700); } + FILE *pf = fopen(pid_path, "w"); + if (pf) { fprintf(pf, "%ld\n", (long)getpid()); fclose(pf); } + } + + int vnc_ts_fd = -1, web_ts_fd = -1; + int vnc_lo_fd = -1, web_lo_fd = -1; + char active_ts_ip[64] = {0}; + + if (remote_bind_is_tailscale(app.cfg.bind)) { + if (app.cfg.bind_loopback) { + vnc_lo_fd = listen_tcp("127.0.0.1", app.cfg.vnc_port); + web_lo_fd = listen_tcp("127.0.0.1", app.cfg.web_port); + fprintf(stderr, "chandra-remote: loopback VNC 127.0.0.1:%d, Web 127.0.0.1:%d\n", + vnc_lo_fd >= 0 ? app.cfg.vnc_port : -1, + web_lo_fd >= 0 ? app.cfg.web_port : -1); + } + } else { + vnc_ts_fd = listen_tcp(app.cfg.bind, app.cfg.vnc_port); + web_ts_fd = listen_tcp(app.cfg.bind, app.cfg.web_port); + if (vnc_ts_fd < 0 || web_ts_fd < 0) { + fprintf(stderr, "chandra-remote: failed to bind %s:%d/%d: %s\n", + app.cfg.bind, app.cfg.vnc_port, app.cfg.web_port, strerror(errno)); + if (vnc_ts_fd >= 0) close(vnc_ts_fd); + if (web_ts_fd >= 0) close(web_ts_fd); + return 1; + } + fprintf(stderr, "chandra-remote: listening on %s VNC:%d Web:%d (auth=%s)\n", + app.cfg.bind, app.cfg.vnc_port, app.cfg.web_port, + app.cfg.auth_mode == REMOTE_AUTH_NONE ? "none" : "password"); + } + + uint64_t last_iface_check = 0; + uint64_t last_parent_check = 0; + + while (g_running) { + if (g_reload) { + g_reload = 0; + RemoteConfig ncfg; + if (remote_load_or_init_config(config_path, &ncfg) == 0) { + pthread_mutex_lock(&app.cfg_mu); + ncfg.allow_insecure_open = app.cfg.allow_insecure_open; + if (override_bind) snprintf(ncfg.bind, sizeof ncfg.bind, "%s", override_bind); + if (override_no_loopback) ncfg.bind_loopback = 0; + if (override_no_auth) ncfg.auth_mode = REMOTE_AUTH_NONE; + if (override_vnc_port > 0) ncfg.vnc_port = override_vnc_port; + if (override_web_port > 0) ncfg.web_port = override_web_port; + app.cfg = ncfg; + pthread_mutex_unlock(&app.cfg_mu); + fprintf(stderr, "chandra-remote: reloaded config (auth=%s)\n", + ncfg.auth_mode == REMOTE_AUTH_NONE ? "none" : "password"); + } + } + + uint64_t now = remote_now_ms(); + if (parent_pid > 1 && now - last_parent_check >= 1000) { + last_parent_check = now; + if (kill(parent_pid, 0) < 0 && errno == ESRCH) break; + } + + if (remote_bind_is_tailscale(app.cfg.bind) && + (last_iface_check == 0 || now - last_iface_check >= 2000)) { + last_iface_check = now; + char ts_ip[64] = {0}; + int has = remote_find_tailscale_ipv4(ts_ip, sizeof ts_ip) == 0; + if (has && strcmp(ts_ip, active_ts_ip) != 0) { + if (vnc_ts_fd >= 0) { close(vnc_ts_fd); vnc_ts_fd = -1; } + if (web_ts_fd >= 0) { close(web_ts_fd); web_ts_fd = -1; } + vnc_ts_fd = listen_tcp(ts_ip, app.cfg.vnc_port); + web_ts_fd = listen_tcp(ts_ip, app.cfg.web_port); + snprintf(active_ts_ip, sizeof active_ts_ip, "%s", ts_ip); + fprintf(stderr, "chandra-remote: bound tailscale0 VNC %s:%d (%s), Web %s:%d (%s)\n", + ts_ip, app.cfg.vnc_port, vnc_ts_fd >= 0 ? "ok" : "fail", + ts_ip, app.cfg.web_port, web_ts_fd >= 0 ? "ok" : "fail"); + } else if (!has && active_ts_ip[0]) { + if (vnc_ts_fd >= 0) { close(vnc_ts_fd); vnc_ts_fd = -1; } + if (web_ts_fd >= 0) { close(web_ts_fd); web_ts_fd = -1; } + active_ts_ip[0] = 0; + fprintf(stderr, "chandra-remote: tailscale0 went down; waiting for Tailscale IP\n"); + } + } + + struct pollfd pfds[4]; + int types[4]; /* 0=vnc, 1=web */ + nfds_t nfds = 0; + int fds[4] = { vnc_ts_fd, vnc_lo_fd, web_ts_fd, web_lo_fd }; + int ftypes[4] = { 0, 0, 1, 1 }; + for (int i = 0; i < 4; i++) { + if (fds[i] >= 0) { + pfds[nfds].fd = fds[i]; + pfds[nfds].events = POLLIN; + pfds[nfds].revents = 0; + types[nfds] = ftypes[i]; + nfds++; + } + } + if (nfds == 0) { + remote_sleep_ms(500); + continue; + } + int pr = poll(pfds, nfds, 500); + if (pr < 0) { + if (errno == EINTR) continue; + break; + } + for (nfds_t i = 0; i < nfds; i++) { + if (pfds[i].revents & POLLIN) { + int cfd = accept(pfds[i].fd, NULL, NULL); + if (cfd >= 0) spawn_client(&app, cfd, types[i]); + } + } + } + + if (vnc_ts_fd >= 0) close(vnc_ts_fd); + if (web_ts_fd >= 0) close(web_ts_fd); + if (vnc_lo_fd >= 0) close(vnc_lo_fd); + if (web_lo_fd >= 0) close(web_lo_fd); + ctl_close(&app.ctl); + unlink(pid_path); + return 0; +} diff --git a/remote/chandra_fb_shm.h b/remote/chandra_fb_shm.h new file mode 100644 index 0000000..9efc26a --- /dev/null +++ b/remote/chandra_fb_shm.h @@ -0,0 +1,34 @@ +#ifndef CHANDRA_FB_SHM_H +#define CHANDRA_FB_SHM_H + +#include +#include + +#define CHANDRA_FB_MAGIC 0x43484642u /* "CHFB" */ +#define CHANDRA_FB_VERSION 1u +#define CHANDRA_FB_HDR_BYTES 4096u +/* Fits up to 3840x2160x4 (~33.2 MiB); sparse tmpfs only backs written pages. */ +#define CHANDRA_FB_SLOT_BYTES (34u * 1024u * 1024u) +#define CHANDRA_FB_TOTAL_BYTES (CHANDRA_FB_HDR_BYTES + 2u * CHANDRA_FB_SLOT_BYTES) + +typedef struct { + uint32_t magic; + uint32_t version; + uint32_t slot_bytes; + uint32_t active_slot; /* 0 or 1, atomic release/acquire */ + uint32_t width; /* logical width of active_slot */ + uint32_t height; /* logical height of active_slot */ + int32_t dmg_x0; /* bounding box damaged on last publish */ + int32_t dmg_y0; + int32_t dmg_x1; + int32_t dmg_y1; + uint64_t seq; /* monotonic frame counter, atomic release/acquire */ + uint64_t frame_ms; /* CLOCK_MONOTONIC ms when published */ + uint64_t consumer_ping_ms; /* CLOCK_MONOTONIC ms kept fresh by chandra-remote */ +} ChandraFbHeader; + +static inline uint8_t *chandra_fb_slot_ptr(void *base, uint32_t slot, uint32_t slot_bytes) { + return (uint8_t *)base + CHANDRA_FB_HDR_BYTES + (size_t)(slot & 1u) * (size_t)slot_bytes; +} + +#endif /* CHANDRA_FB_SHM_H */ diff --git a/remote/keysym.c b/remote/keysym.c new file mode 100644 index 0000000..64340c1 --- /dev/null +++ b/remote/keysym.c @@ -0,0 +1,216 @@ +#include "remote_internal.h" + +#include +#include + +void hex_encode(const uint8_t *in, size_t len, char *out) { + static const char hx[] = "0123456789abcdef"; + for (size_t i = 0; i < len; i++) { + out[i * 2] = hx[(in[i] >> 4) & 0x0Fu]; + out[i * 2 + 1] = hx[in[i] & 0x0Fu]; + } + out[len * 2] = 0; +} + +typedef struct { + uint32_t sym; + uint32_t evdev; + int shift; + int mod_bit; +} KeyMapEntry; + +static const KeyMapEntry special_keys[] = { + { 0xFF08u, 14u, 0, 0 }, /* BackSpace */ + { 0xFF09u, 15u, 0, 0 }, /* Tab */ + { 0xFE20u, 15u, 1, 0 }, /* ISO_Left_Tab */ + { 0xFF0Du, 28u, 0, 0 }, /* Return */ + { 0xFF1Bu, 1u, 0, 0 }, /* Escape */ + { 0xFF63u, 110u, 0, 0 }, /* Insert */ + { 0xFFFFu, 111u, 0, 0 }, /* Delete */ + { 0xFF50u, 102u, 0, 0 }, /* Home */ + { 0xFF57u, 107u, 0, 0 }, /* End */ + { 0xFF55u, 104u, 0, 0 }, /* Page_Up */ + { 0xFF56u, 109u, 0, 0 }, /* Page_Down */ + { 0xFF51u, 105u, 0, 0 }, /* Left */ + { 0xFF52u, 103u, 0, 0 }, /* Up */ + { 0xFF53u, 106u, 0, 0 }, /* Right */ + { 0xFF54u, 108u, 0, 0 }, /* Down */ + { 0xFFBEu, 59u, 0, 0 }, /* F1 */ + { 0xFFBFu, 60u, 0, 0 }, /* F2 */ + { 0xFFC0u, 61u, 0, 0 }, /* F3 */ + { 0xFFC1u, 62u, 0, 0 }, /* F4 */ + { 0xFFC2u, 63u, 0, 0 }, /* F5 */ + { 0xFFC3u, 64u, 0, 0 }, /* F6 */ + { 0xFFC4u, 65u, 0, 0 }, /* F7 */ + { 0xFFC5u, 66u, 0, 0 }, /* F8 */ + { 0xFFC6u, 67u, 0, 0 }, /* F9 */ + { 0xFFC7u, 68u, 0, 0 }, /* F10 */ + { 0xFFC8u, 87u, 0, 0 }, /* F11 */ + { 0xFFC9u, 88u, 0, 0 }, /* F12 */ + /* Keypad */ + { 0xFF8Du, 96u, 0, 0 }, /* KP_Enter */ + { 0xFFAAu, 55u, 0, 0 }, /* KP_Multiply */ + { 0xFFABu, 78u, 0, 0 }, /* KP_Add */ + { 0xFFADu, 74u, 0, 0 }, /* KP_Subtract */ + { 0xFFAEu, 83u, 0, 0 }, /* KP_Decimal */ + { 0xFFAFu, 98u, 0, 0 }, /* KP_Divide */ + { 0xFFB0u, 82u, 0, 0 }, /* KP_0 */ + { 0xFFB1u, 79u, 0, 0 }, /* KP_1 */ + { 0xFFB2u, 80u, 0, 0 }, /* KP_2 */ + { 0xFFB3u, 81u, 0, 0 }, /* KP_3 */ + { 0xFFB4u, 75u, 0, 0 }, /* KP_4 */ + { 0xFFB5u, 76u, 0, 0 }, /* KP_5 */ + { 0xFFB6u, 77u, 0, 0 }, /* KP_6 */ + { 0xFFB7u, 71u, 0, 0 }, /* KP_7 */ + { 0xFFB8u, 72u, 0, 0 }, /* KP_8 */ + { 0xFFB9u, 73u, 0, 0 }, /* KP_9 */ + { 0xFF95u, 102u, 0, 0 }, /* KP_Home */ + { 0xFF96u, 105u, 0, 0 }, /* KP_Left */ + { 0xFF97u, 103u, 0, 0 }, /* KP_Up */ + { 0xFF98u, 106u, 0, 0 }, /* KP_Right */ + { 0xFF99u, 108u, 0, 0 }, /* KP_Down */ + { 0xFF9Au, 104u, 0, 0 }, /* KP_Prior */ + { 0xFF9Bu, 109u, 0, 0 }, /* KP_Next */ + { 0xFF9Cu, 107u, 0, 0 }, /* KP_End */ + { 0xFF9Eu, 110u, 0, 0 }, /* KP_Insert */ + { 0xFF9Fu, 111u, 0, 0 }, /* KP_Delete */ + /* Modifiers */ + { 0xFFE1u, 42u, 0, 1 }, /* Shift_L */ + { 0xFFE2u, 54u, 0, 1 }, /* Shift_R */ + { 0xFFE3u, 29u, 0, 4 }, /* Control_L */ + { 0xFFE4u, 97u, 0, 4 }, /* Control_R */ + { 0xFFE9u, 56u, 0, 8 }, /* Alt_L */ + { 0xFFEAu, 100u, 0, 8 }, /* Alt_R */ + { 0xFE03u, 100u, 0, 8 }, /* ISO_Level3_Shift */ + { 0xFFEBu, 125u, 0, 64 },/* Super_L */ + { 0xFFECu, 126u, 0, 64 },/* Super_R */ + { 0xFFE7u, 125u, 0, 64 },/* Meta_L */ + { 0xFFE8u, 126u, 0, 64 },/* Meta_R */ + { 0xFFE5u, 58u, 0, 2 }, /* Caps_Lock */ + { 0xFF7Fu, 69u, 0, 0 }, /* Num_Lock */ + { 0xFF67u, 127u, 0, 0 }, /* Menu */ + /* Media / Android hardware keys */ + { 0x1008FF11u, 114u, 0, 0 }, /* XF86AudioLowerVolume */ + { 0x1008FF12u, 113u, 0, 0 }, /* XF86AudioMute */ + { 0x1008FF13u, 115u, 0, 0 }, /* XF86AudioRaiseVolume */ +}; + +static int ascii_to_evdev(uint32_t ch, uint32_t *ev, int *sh) { + static const uint8_t letter_code[26] = { + 30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,19,31,20,22,47,17,45,21,44 + }; + static const uint8_t digit_code[10] = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + if (ch >= 'a' && ch <= 'z') { *ev = letter_code[ch - 'a']; *sh = 0; return 1; } + if (ch >= 'A' && ch <= 'Z') { *ev = letter_code[ch - 'A']; *sh = 1; return 1; } + if (ch >= '0' && ch <= '9') { *ev = digit_code[ch - '0']; *sh = 0; return 1; } + switch (ch) { + case ' ': *ev = 57; *sh = 0; return 1; + case '!': *ev = 2; *sh = 1; return 1; + case '@': *ev = 3; *sh = 1; return 1; + case '#': *ev = 4; *sh = 1; return 1; + case '$': *ev = 5; *sh = 1; return 1; + case '%': *ev = 6; *sh = 1; return 1; + case '^': *ev = 7; *sh = 1; return 1; + case '&': *ev = 8; *sh = 1; return 1; + case '*': *ev = 9; *sh = 1; return 1; + case '(': *ev = 10; *sh = 1; return 1; + case ')': *ev = 11; *sh = 1; return 1; + case '-': *ev = 12; *sh = 0; return 1; + case '_': *ev = 12; *sh = 1; return 1; + case '=': *ev = 13; *sh = 0; return 1; + case '+': *ev = 13; *sh = 1; return 1; + case '[': *ev = 26; *sh = 0; return 1; + case '{': *ev = 26; *sh = 1; return 1; + case ']': *ev = 27; *sh = 0; return 1; + case '}': *ev = 27; *sh = 1; return 1; + case '\\': *ev = 43; *sh = 0; return 1; + case '|': *ev = 43; *sh = 1; return 1; + case ';': *ev = 39; *sh = 0; return 1; + case ':': *ev = 39; *sh = 1; return 1; + case '\'': *ev = 40; *sh = 0; return 1; + case '"': *ev = 40; *sh = 1; return 1; + case '`': *ev = 41; *sh = 0; return 1; + case '~': *ev = 41; *sh = 1; return 1; + case ',': *ev = 51; *sh = 0; return 1; + case '<': *ev = 51; *sh = 1; return 1; + case '.': *ev = 52; *sh = 0; return 1; + case '>': *ev = 52; *sh = 1; return 1; + case '/': *ev = 53; *sh = 0; return 1; + case '?': *ev = 53; *sh = 1; return 1; + default: return 0; + } +} + +int keysym_to_evdev(uint32_t sym, uint32_t *out_evdev, int *out_shift, int *out_mod_bit, uint32_t *out_unicode) { + *out_evdev = 0; + *out_shift = 0; + *out_mod_bit = 0; + *out_unicode = 0; + if (sym >= 0x20u && sym <= 0x7Eu) { + return ascii_to_evdev(sym, out_evdev, out_shift); + } + for (size_t i = 0; i < sizeof special_keys / sizeof special_keys[0]; i++) { + if (special_keys[i].sym == sym) { + *out_evdev = special_keys[i].evdev; + *out_shift = special_keys[i].shift; + *out_mod_bit = special_keys[i].mod_bit; + return 1; + } + } + if (sym >= 0x01000020u && sym <= 0x0110FFFFu) { + uint32_t cp = sym - 0x01000000u; + if (cp >= 0x20u && cp <= 0x7Eu && ascii_to_evdev(cp, out_evdev, out_shift)) return 1; + *out_unicode = cp; + return 1; + } + if (sym >= 0xA0u && sym <= 0xFFu) { + *out_unicode = sym; + return 1; + } + return 0; +} + +static void flush_unicode_run(CtlConn *ctl, const uint8_t *buf, size_t len) { + if (len == 0) return; + char cmd[2048]; + if (len > 900) len = 900; + memcpy(cmd, "input-text ", 11); + hex_encode(buf, len, cmd + 11); + ctl_fire(ctl, cmd); +} + +void remote_send_utf8_text(CtlConn *ctl, const char *utf8) { + const uint8_t *p = (const uint8_t *)utf8; + uint8_t run[900]; + size_t rlen = 0; + while (*p) { + uint8_t c = *p; + if (c == '\r') { p++; continue; } + if (c == '\n' || c == '\t' || (c >= 0x20u && c <= 0x7Eu)) { + if (rlen > 0) { flush_unicode_run(ctl, run, rlen); rlen = 0; } + uint32_t ev = 0; + int sh = 0; + if (c == '\n') ev = 28u; + else if (c == '\t') ev = 15u; + else ascii_to_evdev(c, &ev, &sh); + if (ev) { + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-key-tap %u %d", ev, sh ? 1 : 0); + ctl_fire(ctl, cmd); + } + p++; + continue; + } + size_t clen = 1; + if ((c & 0xE0u) == 0xC0u) clen = 2; + else if ((c & 0xF0u) == 0xE0u) clen = 3; + else if ((c & 0xF8u) == 0xF0u) clen = 4; + size_t avail = strlen((const char *)p); + if (clen > avail) clen = avail; + if (rlen + clen > sizeof run) { flush_unicode_run(ctl, run, rlen); rlen = 0; } + memcpy(run + rlen, p, clen); + rlen += clen; + p += clen; + } + if (rlen > 0) flush_unicode_run(ctl, run, rlen); +} diff --git a/remote/remote_internal.h b/remote/remote_internal.h new file mode 100644 index 0000000..fde1534 --- /dev/null +++ b/remote/remote_internal.h @@ -0,0 +1,112 @@ +#ifndef CHANDRA_REMOTE_INTERNAL_H +#define CHANDRA_REMOTE_INTERNAL_H + +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include + +#include "chandra_fb_shm.h" + +#define REMOTE_AUTH_NONE 0 +#define REMOTE_AUTH_PASSWORD 1 + +typedef struct { + int enabled; + char bind[64]; /* "tailscale", "127.0.0.1", "0.0.0.0", or IP */ + int bind_loopback; /* 1 to also bind 127.0.0.1 when bind == "tailscale" */ + int auth_mode; /* REMOTE_AUTH_NONE or REMOTE_AUTH_PASSWORD */ + int vnc_port; + int web_port; + int jpeg_quality; + int max_fps; + char password[64]; + int allow_insecure_open; +} RemoteConfig; + +typedef struct { + pthread_mutex_t mu; + int fd; + char sock_path[512]; + uint64_t last_try_ms; +} CtlConn; + +typedef struct { + int fd; + ChandraFbHeader *hdr; + char shm_path[512]; + uint64_t last_open_try_ms; +} FbReader; + +typedef struct { + RemoteConfig cfg; + pthread_mutex_t cfg_mu; + char config_path[512]; + char web_dir[512]; + CtlConn ctl; + uint8_t hmac_key[32]; + volatile sig_atomic_t *running; + pthread_mutex_t ping_mu; + char shm_path[512]; +} RemoteApp; + +/* Time helper */ +uint64_t remote_now_ms(void); +void remote_sleep_ms(int ms); + +/* Config & auth (auth.c) */ +void remote_default_config(RemoteConfig *cfg); +int remote_bind_is_loopback(const char *bind_str); +int remote_bind_is_tailscale(const char *bind_str); +int remote_load_or_init_config(const char *path, RemoteConfig *cfg); +int remote_save_config(const char *path, const RemoteConfig *cfg); +void remote_generate_password(char *out, size_t len); +int remote_ct_equal(const uint8_t hmac_key[32], const char *a, const char *b); +void vnc_des_encrypt_challenge(const char *password, const uint8_t challenge[16], uint8_t out[16]); +void web_token_sign(const uint8_t key[32], uint64_t now_sec, char *out, size_t cap); +int web_token_verify(const uint8_t key[32], const char *tok, uint64_t now_sec); +int ws_compute_accept(const char *client_key, char *out, size_t cap); + +/* Control socket & compositor I/O (chandra-remote.c) */ +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); + +/* Shared framebuffer reader (chandra-remote.c) */ +void fb_reader_init(FbReader *r, const char *shm_path); +void fb_reader_close(FbReader *r); +void fb_reader_ping(FbReader *r); +int fb_reader_grab( + FbReader *r, + uint64_t last_seq, + uint32_t last_w, + uint32_t last_h, + int *out_full, + uint32_t *out_w, + uint32_t *out_h, + int *out_x0, + int *out_y0, + int *out_x1, + int *out_y1, + uint64_t *out_seq, + uint8_t **scratch, + size_t *scratch_cap); + +/* Peer & socket helpers (chandra-remote.c) */ +int remote_peer_allowed(const RemoteConfig *cfg, const struct sockaddr_storage *ss, socklen_t slen); +int remote_find_tailscale_ipv4(char *out, size_t cap); + +/* Keysym & UTF-8 translation (keysym.c) */ +int keysym_to_evdev(uint32_t keysym, uint32_t *out_evdev, int *out_shift, int *out_mod_bit, uint32_t *out_unicode); +void remote_send_utf8_text(CtlConn *ctl, const char *utf8); +void hex_encode(const uint8_t *in, size_t len, char *out); + +/* RFB & Web servers (rfb.c, web.c) */ +void rfb_handle_client(RemoteApp *app, int fd); +void web_handle_client(RemoteApp *app, int fd); + +#endif /* CHANDRA_REMOTE_INTERNAL_H */ diff --git a/remote/rfb.c b/remote/rfb.c new file mode 100644 index 0000000..c1aea68 --- /dev/null +++ b/remote/rfb.c @@ -0,0 +1,768 @@ +#include "remote_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + uint8_t bpp; + uint8_t depth; + uint8_t big_endian; + uint8_t true_colour; + uint16_t red_max; + uint16_t green_max; + uint16_t blue_max; + uint8_t red_shift; + uint8_t green_shift; + uint8_t blue_shift; +} RfbPixelFormat; + +typedef struct { + int fd; + RemoteApp *app; + RfbPixelFormat pf; + int supports_raw; + int supports_zlib; + int supports_tight; + int jpeg_quality_idx; /* -1 if client did not advertise -32..-23 */ + int supports_desktop_size; + int supports_ext_desktop_size; + int supports_continuous; + int continuous; + int update_requested; + int force_full; + uint16_t req_x, req_y, req_w, req_h; + uint32_t client_w, client_h; + uint64_t last_seq; + uint64_t last_send_ms; + uint8_t prev_btn_mask; + uint32_t held_mods; + int z_init; + z_stream z; + tjhandle tj; + FbReader fb; + uint8_t *scratch; + size_t scratch_cap; + uint8_t *pixbuf; + size_t pixbuf_cap; + uint8_t *zbuf; + size_t zbuf_cap; +} RfbClient; + +static int write_all(int fd, const void *buf, size_t len) { + const uint8_t *p = (const uint8_t *)buf; + size_t done = 0; + while (done < len) { + ssize_t w = send(fd, p + done, len - done, MSG_NOSIGNAL); + if (w < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + struct pollfd pfd = { .fd = fd, .events = POLLOUT }; + if (poll(&pfd, 1, 5000) <= 0) return -1; + continue; + } + return -1; + } + if (w == 0) return -1; + done += (size_t)w; + } + return 0; +} + +static int read_exact(int fd, void *buf, size_t len) { + uint8_t *p = (uint8_t *)buf; + size_t got = 0; + while (got < len) { + ssize_t r = recv(fd, p + got, len - got, 0); + if (r < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + if (poll(&pfd, 1, 10000) <= 0) return -1; + continue; + } + return -1; + } + if (r == 0) return -1; + got += (size_t)r; + } + return 0; +} + +static void put_be16(uint8_t *p, uint16_t v) { + p[0] = (uint8_t)(v >> 8); + p[1] = (uint8_t)v; +} + +static void put_be32(uint8_t *p, uint32_t v) { + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +static uint16_t get_be16(const uint8_t *p) { + return (uint16_t)(((uint16_t)p[0] << 8) | p[1]); +} + +static uint32_t get_be32(const uint8_t *p) { + return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3]; +} + +static void encode_pixel_format(uint8_t out[16], const RfbPixelFormat *pf) { + out[0] = pf->bpp; + out[1] = pf->depth; + out[2] = pf->big_endian; + out[3] = pf->true_colour; + put_be16(out + 4, pf->red_max); + put_be16(out + 6, pf->green_max); + put_be16(out + 8, pf->blue_max); + out[10] = pf->red_shift; + out[11] = pf->green_shift; + out[12] = pf->blue_shift; + out[13] = out[14] = out[15] = 0; +} + +static void decode_pixel_format(const uint8_t in[16], RfbPixelFormat *pf) { + pf->bpp = in[0]; + pf->depth = in[1]; + pf->big_endian = in[2] ? 1 : 0; + pf->true_colour = in[3] ? 1 : 0; + pf->red_max = get_be16(in + 4); + pf->green_max = get_be16(in + 6); + pf->blue_max = get_be16(in + 8); + pf->red_shift = in[10]; + pf->green_shift = in[11]; + pf->blue_shift = in[12]; +} + +static int ensure_buf(uint8_t **buf, size_t *cap, size_t need) { + if (need <= *cap) return 0; + uint8_t *nb = realloc(*buf, need); + if (!nb) return -1; + *buf = nb; + *cap = need; + return 0; +} + +static int rfb_send_reason(int fd, const char *msg) { + size_t len = strlen(msg); + uint8_t hdr[8]; + put_be32(hdr, 1u); + put_be32(hdr + 4, (uint32_t)len); + if (write_all(fd, hdr, 8) < 0) return -1; + return write_all(fd, msg, len); +} + +static int rfb_handshake(RfbClient *c) { + const char ver[] = "RFB 003.008\n"; + if (write_all(c->fd, ver, 12) < 0) return -1; + char cver[13]; + if (read_exact(c->fd, cver, 12) < 0) return -1; + cver[12] = 0; + if (strncmp(cver, "RFB ", 4) != 0) return -1; + int minor = atoi(cver + 8); + + RemoteConfig cfg; + pthread_mutex_lock(&c->app->cfg_mu); + cfg = c->app->cfg; + pthread_mutex_unlock(&c->app->cfg_mu); + + if (minor <= 3) { + if (cfg.auth_mode == REMOTE_AUTH_NONE) { + uint8_t ok4[4] = { 0, 0, 0, 1 }; + if (write_all(c->fd, ok4, 4) < 0) return -1; + } else { + uint8_t sec4[4] = { 0, 0, 0, 2 }; + uint8_t chal[16], resp[16], exp[16]; + if (write_all(c->fd, sec4, 4) < 0) return -1; + if (RAND_bytes(chal, 16) != 1) return -1; + if (write_all(c->fd, chal, 16) < 0) return -1; + if (read_exact(c->fd, resp, 16) < 0) return -1; + vnc_des_encrypt_challenge(cfg.password, chal, exp); + if (memcmp(resp, exp, 16) != 0) { + uint8_t fail[4] = { 0, 0, 0, 1 }; + write_all(c->fd, fail, 4); + return -1; + } + uint8_t ok[4] = { 0, 0, 0, 0 }; + if (write_all(c->fd, ok, 4) < 0) return -1; + } + } else { + uint8_t sec_type = cfg.auth_mode == REMOTE_AUTH_NONE ? 1 : 2; + uint8_t list[2] = { 1, sec_type }; + if (write_all(c->fd, list, 2) < 0) return -1; + uint8_t chosen = 0; + if (read_exact(c->fd, &chosen, 1) < 0) return -1; + if (chosen != sec_type) { + rfb_send_reason(c->fd, "Unsupported security type"); + return -1; + } + if (sec_type == 2) { + uint8_t chal[16], resp[16], exp[16]; + if (RAND_bytes(chal, 16) != 1) return -1; + if (write_all(c->fd, chal, 16) < 0) return -1; + if (read_exact(c->fd, resp, 16) < 0) return -1; + vnc_des_encrypt_challenge(cfg.password, chal, exp); + int match = 0; + volatile uint8_t diff = 0; + for (int i = 0; i < 16; i++) diff |= (uint8_t)(resp[i] ^ exp[i]); + match = (diff == 0); + if (!match) { + rfb_send_reason(c->fd, "Authentication failed"); + return -1; + } + } + uint8_t ok[4] = { 0, 0, 0, 0 }; + if (write_all(c->fd, ok, 4) < 0) return -1; + } + + uint8_t shared_flag = 0; + if (read_exact(c->fd, &shared_flag, 1) < 0) return -1; + (void)shared_flag; + + /* Query compositor size if shm isn't populated yet */ + uint32_t init_w = 540, init_h = 1170; + char reply[256]; + if (ctl_cmd(&c->app->ctl, "status", reply, sizeof reply) == 0) { + unsigned int rw = 0, rh = 0; + if (sscanf(reply, "ok %ux%u", &rw, &rh) == 2 && rw > 0 && rh > 0) { + init_w = rw; + init_h = rh; + } + } + c->client_w = init_w; + c->client_h = init_h; + + uint8_t sinit[24 + 7]; + put_be16(sinit, (uint16_t)init_w); + put_be16(sinit + 2, (uint16_t)init_h); + encode_pixel_format(sinit + 4, &c->pf); + put_be32(sinit + 20, 7u); + memcpy(sinit + 24, "Chandra", 7); + return write_all(c->fd, sinit, sizeof sinit); +} + +static size_t pack_rect_pixels(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, int rx, int ry, int rw, int rh) { + int bpp_bytes = (c->pf.bpp == 8) ? 1 : (c->pf.bpp == 16) ? 2 : 4; + size_t need = (size_t)rw * (size_t)rh * (size_t)bpp_bytes; + if (ensure_buf(&c->pixbuf, &c->pixbuf_cap, need) < 0) return 0; + + if (bpp_bytes == 4 && !c->pf.big_endian && c->pf.true_colour && + c->pf.red_shift == 0 && c->pf.green_shift == 8 && c->pf.blue_shift == 16 && + c->pf.red_max == 255 && c->pf.green_max == 255 && c->pf.blue_max == 255) { + for (int y = 0; y < rh; y++) { + const uint8_t *src = rgba + ((size_t)(ry + y) * (size_t)fb_w + (size_t)rx) * 4; + memcpy(c->pixbuf + (size_t)y * (size_t)rw * 4, src, (size_t)rw * 4); + } + return need; + } + + uint8_t *dst = c->pixbuf; + uint32_t rmax = c->pf.red_max ? c->pf.red_max : 255u; + uint32_t gmax = c->pf.green_max ? c->pf.green_max : 255u; + uint32_t bmax = c->pf.blue_max ? c->pf.blue_max : 255u; + for (int y = 0; y < rh; y++) { + const uint8_t *src = rgba + ((size_t)(ry + y) * (size_t)fb_w + (size_t)rx) * 4; + for (int x = 0; x < rw; x++) { + uint32_t r = ((uint32_t)src[x * 4 + 0] * rmax + 127u) / 255u; + uint32_t g = ((uint32_t)src[x * 4 + 1] * gmax + 127u) / 255u; + uint32_t b = ((uint32_t)src[x * 4 + 2] * bmax + 127u) / 255u; + uint32_t v = (r << c->pf.red_shift) | (g << c->pf.green_shift) | (b << c->pf.blue_shift); + if (bpp_bytes == 1) { + *dst++ = (uint8_t)v; + } else if (bpp_bytes == 2) { + if (c->pf.big_endian) { + dst[0] = (uint8_t)(v >> 8); + dst[1] = (uint8_t)v; + } else { + dst[0] = (uint8_t)v; + dst[1] = (uint8_t)(v >> 8); + } + dst += 2; + } else { + if (c->pf.big_endian) { + dst[0] = (uint8_t)(v >> 24); + dst[1] = (uint8_t)(v >> 16); + dst[2] = (uint8_t)(v >> 8); + dst[3] = (uint8_t)v; + } else { + dst[0] = (uint8_t)v; + dst[1] = (uint8_t)(v >> 8); + dst[2] = (uint8_t)(v >> 16); + dst[3] = (uint8_t)(v >> 24); + } + dst += 4; + } + } + } + return need; +} + +static size_t encode_tight_compact_len(uint32_t len, uint8_t out[3]) { + out[0] = (uint8_t)(len & 0x7Fu); + if (len < 128u) return 1; + out[0] |= 0x80u; + out[1] = (uint8_t)((len >> 7) & 0x7Fu); + if (len < 16384u) return 2; + out[1] |= 0x80u; + out[2] = (uint8_t)((len >> 14) & 0xFFu); + return 3; +} + +static int send_rect_raw(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, int rx, int ry, int rw, int rh) { + size_t raw_bytes = pack_rect_pixels(c, rgba, fb_w, rx, ry, rw, rh); + if (raw_bytes == 0) return -1; + uint8_t hdr[12]; + put_be16(hdr + 0, (uint16_t)rx); + put_be16(hdr + 2, (uint16_t)ry); + put_be16(hdr + 4, (uint16_t)rw); + put_be16(hdr + 6, (uint16_t)rh); + put_be32(hdr + 8, 0u); /* Raw */ + if (write_all(c->fd, hdr, 12) < 0) return -1; + return write_all(c->fd, c->pixbuf, raw_bytes); +} + +static int send_rect_zlib(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, int rx, int ry, int rw, int rh) { + if (!c->z_init) { + memset(&c->z, 0, sizeof c->z); + if (deflateInit(&c->z, Z_BEST_SPEED) != Z_OK) { + return send_rect_raw(c, rgba, fb_w, rx, ry, rw, rh); + } + c->z_init = 1; + } + size_t raw_bytes = pack_rect_pixels(c, rgba, fb_w, rx, ry, rw, rh); + if (raw_bytes == 0) return -1; + uLong bound = deflateBound(&c->z, (uLong)raw_bytes); + if (ensure_buf(&c->zbuf, &c->zbuf_cap, (size_t)bound + 64) < 0) return -1; + c->z.next_in = c->pixbuf; + c->z.avail_in = (uInt)raw_bytes; + c->z.next_out = c->zbuf; + c->z.avail_out = (uInt)c->zbuf_cap; + int zr = deflate(&c->z, Z_SYNC_FLUSH); + if (zr != Z_OK || c->z.avail_in != 0) return -1; + size_t zlen = c->zbuf_cap - (size_t)c->z.avail_out; + uint8_t hdr[16]; + put_be16(hdr + 0, (uint16_t)rx); + put_be16(hdr + 2, (uint16_t)ry); + put_be16(hdr + 4, (uint16_t)rw); + put_be16(hdr + 6, (uint16_t)rh); + put_be32(hdr + 8, 6u); /* Zlib */ + put_be32(hdr + 12, (uint32_t)zlen); + if (write_all(c->fd, hdr, 16) < 0) return -1; + return write_all(c->fd, c->zbuf, zlen); +} + +static int send_rect_tight_jpeg(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, int rx, int ry, int rw, int rh) { + static const int qtbl[10] = { 25, 35, 45, 55, 65, 72, 78, 84, 89, 94 }; + if (!c->tj) { + c->tj = tjInitCompress(); + if (!c->tj) return send_rect_raw(c, rgba, fb_w, rx, ry, rw, rh); + } + int q = qtbl[c->jpeg_quality_idx >= 0 && c->jpeg_quality_idx <= 9 ? c->jpeg_quality_idx : 7]; + const uint8_t *ptr = rgba + ((size_t)ry * (size_t)fb_w + (size_t)rx) * 4; + unsigned char *jbuf = NULL; + unsigned long jsz = 0; + if (tjCompress2(c->tj, ptr, rw, (int)fb_w * 4, rh, TJPF_RGBX, &jbuf, &jsz, TJSAMP_420, q, TJFLAG_FASTDCT) != 0 || + !jbuf || jsz == 0) { + if (jbuf) tjFree(jbuf); + return send_rect_raw(c, rgba, fb_w, rx, ry, rw, rh); + } + uint8_t hdr[16]; + put_be16(hdr + 0, (uint16_t)rx); + put_be16(hdr + 2, (uint16_t)ry); + put_be16(hdr + 4, (uint16_t)rw); + put_be16(hdr + 6, (uint16_t)rh); + put_be32(hdr + 8, 7u); /* Tight */ + hdr[12] = 0x90u; /* Tight JPEG subencoding */ + size_t clen = encode_tight_compact_len((uint32_t)jsz, hdr + 13); + int rc = write_all(c->fd, hdr, 13 + clen); + if (rc == 0) rc = write_all(c->fd, jbuf, (size_t)jsz); + tjFree(jbuf); + return rc; +} + +static int can_use_tight_jpeg(const RfbClient *c) { + return c->supports_tight && c->jpeg_quality_idx >= 0 && c->pf.true_colour && + (c->pf.bpp == 32 || c->pf.bpp == 16); +} + +static int send_pixel_rect(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, int rx, int ry, int rw, int rh) { + if (can_use_tight_jpeg(c)) return send_rect_tight_jpeg(c, rgba, fb_w, rx, ry, rw, rh); + if (c->supports_zlib && c->pf.true_colour) return send_rect_zlib(c, rgba, fb_w, rx, ry, rw, rh); + return send_rect_raw(c, rgba, fb_w, rx, ry, rw, rh); +} + +static int send_frame_update(RfbClient *c, const uint8_t *rgba, uint32_t fb_w, uint32_t fb_h, int rx, int ry, int rw, int rh, int need_resize) { + int use_ext = need_resize && c->supports_ext_desktop_size; + int use_ds = need_resize && !use_ext && c->supports_desktop_size; + + /* Count pixel tiles (Tight JPEG caps tile width/height at 2048). */ + int max_tile = can_use_tight_jpeg(c) ? 2048 : 4096; + int n_tiles_x = (rw + max_tile - 1) / max_tile; + int n_tiles_y = (rh + max_tile - 1) / max_tile; + int n_pixel_rects = (rw > 0 && rh > 0) ? (n_tiles_x * n_tiles_y) : 0; + int nrects = n_pixel_rects + ((use_ext || use_ds) ? 1 : 0); + if (nrects <= 0) return 0; + + uint8_t u_hdr[4] = { 0, 0, (uint8_t)(nrects >> 8), (uint8_t)nrects }; + if (write_all(c->fd, u_hdr, 4) < 0) return -1; + + if (use_ext) { + uint8_t r[32]; + memset(r, 0, sizeof r); + put_be16(r + 0, 0); + put_be16(r + 2, 0); + put_be16(r + 4, (uint16_t)fb_w); + put_be16(r + 6, (uint16_t)fb_h); + put_be32(r + 8, (uint32_t)(-308)); /* ExtendedDesktopSize */ + r[12] = 1; /* number-of-screens */ + put_be32(r + 16, 1u); /* screen id */ + put_be16(r + 24, (uint16_t)fb_w); + put_be16(r + 26, (uint16_t)fb_h); + if (write_all(c->fd, r, 32) < 0) return -1; + } else if (use_ds) { + uint8_t r[12]; + put_be16(r + 0, 0); + put_be16(r + 2, 0); + put_be16(r + 4, (uint16_t)fb_w); + put_be16(r + 6, (uint16_t)fb_h); + put_be32(r + 8, (uint32_t)(-223)); /* DesktopSize */ + if (write_all(c->fd, r, 12) < 0) return -1; + } + + for (int ty = 0; ty < rh; ty += max_tile) { + int th = (ty + max_tile <= rh) ? max_tile : (rh - ty); + for (int tx = 0; tx < rw; tx += max_tile) { + int tw = (tx + max_tile <= rw) ? max_tile : (rw - tx); + if (send_pixel_rect(c, rgba, fb_w, rx + tx, ry + ty, tw, th) < 0) return -1; + } + } + return 0; +} + +static void rfb_send_mods(RfbClient *c, uint32_t mods) { + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", mods); + ctl_fire(&c->app->ctl, cmd); +} + +static int rfb_handle_message(RfbClient *c) { + uint8_t msg_type = 0; + if (read_exact(c->fd, &msg_type, 1) < 0) return -1; + + switch (msg_type) { + case 0: { /* SetPixelFormat */ + uint8_t buf[19]; + if (read_exact(c->fd, buf, 19) < 0) return -1; + decode_pixel_format(buf + 3, &c->pf); + c->force_full = 1; + break; + } + case 2: { /* SetEncodings */ + uint8_t buf[3]; + if (read_exact(c->fd, buf, 3) < 0) return -1; + uint16_t n = get_be16(buf + 1); + c->supports_raw = 0; + c->supports_zlib = 0; + c->supports_tight = 0; + c->jpeg_quality_idx = -1; + c->supports_desktop_size = 0; + c->supports_ext_desktop_size = 0; + c->supports_continuous = 0; + for (uint16_t i = 0; i < n; i++) { + uint8_t eb[4]; + if (read_exact(c->fd, eb, 4) < 0) return -1; + int32_t enc = (int32_t)get_be32(eb); + if (enc == 0) c->supports_raw = 1; + else if (enc == 6) c->supports_zlib = 1; + else if (enc == 7) c->supports_tight = 1; + else if (enc == -223) c->supports_desktop_size = 1; + else if (enc == -308) c->supports_ext_desktop_size = 1; + else if (enc == -313) c->supports_continuous = 1; + else if (enc >= -32 && enc <= -23) { + int qi = enc - (-32); + if (qi > c->jpeg_quality_idx) c->jpeg_quality_idx = qi; + } + } + break; + } + case 3: { /* FramebufferUpdateRequest */ + uint8_t buf[9]; + if (read_exact(c->fd, buf, 9) < 0) return -1; + uint8_t inc = buf[0]; + c->req_x = get_be16(buf + 1); + c->req_y = get_be16(buf + 3); + c->req_w = get_be16(buf + 5); + c->req_h = get_be16(buf + 7); + if (!inc) c->force_full = 1; + c->update_requested = 1; + break; + } + case 4: { /* KeyEvent */ + uint8_t buf[7]; + if (read_exact(c->fd, buf, 7) < 0) return -1; + int down = buf[0] != 0; + uint32_t sym = get_be32(buf + 3); + uint32_t ev = 0, uc = 0; + int sh = 0, mod_bit = 0; + if (!keysym_to_evdev(sym, &ev, &sh, &mod_bit, &uc)) break; + if (uc != 0) { + if (down) { + uint8_t u8[8]; + size_t n = 0; + if (uc < 0x80u) { u8[n++] = (uint8_t)uc; } + else if (uc < 0x800u) { + u8[n++] = (uint8_t)(0xC0u | (uc >> 6)); + u8[n++] = (uint8_t)(0x80u | (uc & 0x3Fu)); + } else if (uc < 0x10000u) { + u8[n++] = (uint8_t)(0xE0u | (uc >> 12)); + u8[n++] = (uint8_t)(0x80u | ((uc >> 6) & 0x3Fu)); + u8[n++] = (uint8_t)(0x80u | (uc & 0x3Fu)); + } else { + u8[n++] = (uint8_t)(0xF0u | (uc >> 18)); + u8[n++] = (uint8_t)(0x80u | ((uc >> 12) & 0x3Fu)); + u8[n++] = (uint8_t)(0x80u | ((uc >> 6) & 0x3Fu)); + u8[n++] = (uint8_t)(0x80u | (uc & 0x3Fu)); + } + char cmd[48]; + memcpy(cmd, "input-text ", 11); + hex_encode(u8, n, cmd + 11); + ctl_fire(&c->app->ctl, cmd); + } + break; + } + if (mod_bit) { + if (down) c->held_mods |= (uint32_t)mod_bit; + else c->held_mods &= ~(uint32_t)mod_bit; + rfb_send_mods(c, c->held_mods); + char cmd[48]; + snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down); + ctl_fire(&c->app->ctl, cmd); + break; + } + uint32_t eff_mods = c->held_mods | (sh ? 1u : 0u); + if (eff_mods != c->held_mods) rfb_send_mods(c, eff_mods); + char cmd[48]; + snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down); + ctl_fire(&c->app->ctl, cmd); + if (eff_mods != c->held_mods) rfb_send_mods(c, c->held_mods); + break; + } + case 5: { /* PointerEvent */ + uint8_t buf[5]; + if (read_exact(c->fd, buf, 5) < 0) return -1; + uint8_t mask = buf[0]; + uint16_t x = get_be16(buf + 1); + uint16_t y = get_be16(buf + 3); + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-ptr %u %u", x, y); + ctl_fire(&c->app->ctl, cmd); + uint8_t diff = (uint8_t)(mask ^ c->prev_btn_mask); + if (diff & 0x01u) { + snprintf(cmd, sizeof cmd, "input-btn 272 %d", (mask & 0x01u) ? 1 : 0); + ctl_fire(&c->app->ctl, cmd); + } + if (diff & 0x02u) { + snprintf(cmd, sizeof cmd, "input-btn 274 %d", (mask & 0x02u) ? 1 : 0); + ctl_fire(&c->app->ctl, cmd); + } + if (diff & 0x04u) { + snprintf(cmd, sizeof cmd, "input-btn 273 %d", (mask & 0x04u) ? 1 : 0); + ctl_fire(&c->app->ctl, cmd); + } + if ((diff & 0x08u) && (mask & 0x08u)) ctl_fire(&c->app->ctl, "input-scroll 0 -30 -1"); + if ((diff & 0x10u) && (mask & 0x10u)) ctl_fire(&c->app->ctl, "input-scroll 0 30 1"); + if ((diff & 0x20u) && (mask & 0x20u)) ctl_fire(&c->app->ctl, "input-scroll 1 -30 -1"); + if ((diff & 0x40u) && (mask & 0x40u)) ctl_fire(&c->app->ctl, "input-scroll 1 30 1"); + c->prev_btn_mask = mask; + break; + } + case 6: { /* ClientCutText */ + 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; + 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; } + uint32_t rem = len - take; + uint8_t drain[512]; + while (rem > 0) { + size_t chunk = rem > sizeof drain ? sizeof drain : rem; + 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); + } + } + free(txt); + break; + } + case 150: { /* EnableContinuousUpdates */ + uint8_t buf[9]; + if (read_exact(c->fd, buf, 9) < 0) return -1; + c->continuous = buf[0] != 0; + if (!c->continuous && c->supports_continuous) { + uint8_t eoc = 150; + write_all(c->fd, &eoc, 1); + } + break; + } + case 251: { /* SetDesktopSize (consume gracefully) */ + uint8_t hdr[7]; + if (read_exact(c->fd, hdr, 7) < 0) return -1; + uint8_t nscreens = hdr[5]; + for (int i = 0; i < (int)nscreens; i++) { + uint8_t sc[16]; + if (read_exact(c->fd, sc, 16) < 0) return -1; + } + break; + } + default: + return -1; + } + return 0; +} + +void rfb_handle_client(RemoteApp *app, int fd) { + RfbClient *c = calloc(1, sizeof *c); + if (!c) { close(fd); return; } + c->fd = fd; + c->app = app; + c->pf.bpp = 32; + c->pf.depth = 24; + c->pf.big_endian = 0; + c->pf.true_colour = 1; + c->pf.red_max = 255; + c->pf.green_max = 255; + c->pf.blue_max = 255; + c->pf.red_shift = 0; + c->pf.green_shift = 8; + c->pf.blue_shift = 16; + c->jpeg_quality_idx = -1; + c->supports_raw = 1; + + fb_reader_init(&c->fb, app->shm_path); + fb_reader_ping(&c->fb); + ctl_fire(&app->ctl, "refresh"); + + if (rfb_handshake(c) < 0) goto done; + + uint64_t last_ping = 0; + while (*app->running) { + uint64_t now = remote_now_ms(); + if (now - last_ping >= 250) { + fb_reader_ping(&c->fb); + last_ping = now; + } + + struct pollfd pfd = { .fd = c->fd, .events = POLLIN }; + int pr = poll(&pfd, 1, 16); + if (pr < 0) { + if (errno == EINTR) continue; + break; + } + if (pr > 0) { + if (pfd.revents & (POLLHUP | POLLERR)) break; + if (pfd.revents & POLLIN) { + if (rfb_handle_message(c) < 0) break; + /* Drain any immediately queued client requests before sending next frame. */ + while (*app->running) { + struct pollfd p2 = { .fd = c->fd, .events = POLLIN }; + if (poll(&p2, 1, 0) <= 0 || !(p2.revents & POLLIN)) break; + if (rfb_handle_message(c) < 0) goto done; + } + } + } + + if (!c->update_requested && !c->continuous) continue; + + RemoteConfig cfg; + pthread_mutex_lock(&app->cfg_mu); + cfg = app->cfg; + pthread_mutex_unlock(&app->cfg_mu); + uint64_t min_gap = (uint64_t)(1000 / (cfg.max_fps > 0 ? cfg.max_fps : 30)); + now = remote_now_ms(); + if (!c->force_full && now - c->last_send_ms < min_gap) continue; + + uint64_t seq_before = c->force_full ? 0 : c->last_seq; + int full = 0, x0 = 0, y0 = 0, x1 = 0, y1 = 0; + uint32_t fb_w = 0, fb_h = 0; + uint64_t new_seq = 0; + int got = fb_reader_grab(&c->fb, seq_before, c->client_w, c->client_h, + &full, &fb_w, &fb_h, &x0, &y0, &x1, &y1, &new_seq, + &c->scratch, &c->scratch_cap); + if (got <= 0) { + if (c->force_full && c->scratch && c->client_w > 0 && c->client_h > 0 && + fb_reader_grab(&c->fb, 0, c->client_w, c->client_h, + &full, &fb_w, &fb_h, &x0, &y0, &x1, &y1, &new_seq, + &c->scratch, &c->scratch_cap) > 0) { + got = 1; + } else { + continue; + } + } + + int need_resize = (fb_w != c->client_w || fb_h != c->client_h); + if (need_resize || c->force_full || full) { + x0 = 0; y0 = 0; x1 = (int)fb_w; y1 = (int)fb_h; + } + if (need_resize && !c->supports_ext_desktop_size && !c->supports_desktop_size) { + /* Client didn't advertise resize support; clip to its buffer size. */ + if (x1 > (int)c->client_w) x1 = (int)c->client_w; + if (y1 > (int)c->client_h) y1 = (int)c->client_h; + } + if (!c->force_full && !need_resize && c->req_w > 0 && c->req_h > 0 && !c->continuous) { + int rx0 = c->req_x, ry0 = c->req_y; + int rx1 = rx0 + c->req_w, ry1 = ry0 + c->req_h; + if (x0 < rx0) x0 = rx0; + if (y0 < ry0) y0 = ry0; + if (x1 > rx1) x1 = rx1; + if (y1 > ry1) y1 = ry1; + } + int rw = x1 - x0; + int rh = y1 - y0; + if (rw <= 0 || rh <= 0) { + c->last_seq = new_seq; + c->force_full = 0; + continue; + } + if (send_frame_update(c, c->scratch, fb_w, fb_h, x0, y0, rw, rh, need_resize) < 0) break; + c->client_w = fb_w; + c->client_h = fb_h; + c->last_seq = new_seq; + c->last_send_ms = now; + c->force_full = 0; + c->update_requested = 0; + } + +done: + if (c->held_mods) rfb_send_mods(c, 0u); + if (c->prev_btn_mask & 0x01u) ctl_fire(&app->ctl, "input-btn 272 0"); + if (c->prev_btn_mask & 0x02u) ctl_fire(&app->ctl, "input-btn 274 0"); + if (c->prev_btn_mask & 0x04u) ctl_fire(&app->ctl, "input-btn 273 0"); + if (c->z_init) deflateEnd(&c->z); + if (c->tj) tjDestroy(c->tj); + fb_reader_close(&c->fb); + free(c->scratch); + free(c->pixbuf); + free(c->zbuf); + close(c->fd); + free(c); +} diff --git a/remote/test_remote.py b/remote/test_remote.py new file mode 100644 index 0000000..651731e --- /dev/null +++ b/remote/test_remote.py @@ -0,0 +1,643 @@ +#!/usr/bin/env python3 +"""End-to-end tests for chandra-remote (RFB 3.8 VNC + HTTP/WebSocket + Tailscale/Auth guardrails).""" +import base64 +import hashlib +import http.client +import json +import mmap +import os +import shutil +import socket +import struct +import subprocess +import tempfile +import threading +import time +import unittest +import zlib + +CHANDRA_FB_MAGIC = 0x43484642 +CHANDRA_FB_VERSION = 1 +CHANDRA_FB_HDR_BYTES = 4096 +CHANDRA_FB_SLOT_BYTES = 34 * 1024 * 1024 +CHANDRA_FB_TOTAL_BYTES = CHANDRA_FB_HDR_BYTES + 2 * CHANDRA_FB_SLOT_BYTES + + +def free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def decode_jpeg_rgb(jpg: bytes): + """Return (w, h, bytes_rgb24) from JPEG bytes using cv2, PIL, djpeg, or ffmpeg.""" + try: + import cv2 + import numpy as np + + arr = np.frombuffer(jpg, dtype=np.uint8) + bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR) + if bgr is not None: + rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + h, w, _ = rgb.shape + return w, h, rgb.tobytes() + except ImportError: + pass + try: + import io + from PIL import Image + + im = Image.open(io.BytesIO(jpg)).convert("RGB") + return im.width, im.height, im.tobytes() + except ImportError: + pass + if shutil.which("djpeg"): + p = subprocess.run(["djpeg", "-rgb"], input=jpg, capture_output=True) + if p.returncode == 0 and p.stdout.startswith(b"P6"): + nl1 = p.stdout.find(b"\n") + nl2 = p.stdout.find(b"\n", nl1 + 1) + nl3 = p.stdout.find(b"\n", nl2 + 1) + dims = p.stdout[nl1 + 1 : nl2].decode().split() + return int(dims[0]), int(dims[1]), p.stdout[nl3 + 1 :] + if shutil.which("ffmpeg"): + # Probe size + decode rgb24 + p = subprocess.run( + ["ffmpeg", "-v", "error", "-f", "mjpeg", "-i", "pipe:0", "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"], + input=jpg, + capture_output=True, + ) + if p.returncode == 0: + # Find SOF0/SOF2 dimensions in JPEG header + i = 2 + w = h = 0 + while i + 9 < len(jpg): + if jpg[i] != 0xFF: + break + m = jpg[i + 1] + if m in (0xC0, 0xC1, 0xC2): + h, w = struct.unpack(">HH", jpg[i + 5 : i + 9]) + break + ln = struct.unpack(">H", jpg[i + 2 : i + 4])[0] + i += 2 + ln + return w, h, p.stdout + raise RuntimeError("No JPEG decoder available (cv2, PIL, djpeg, or ffmpeg)") + + +def vnc_des_encrypt_py(password: str, challenge: bytes) -> bytes: + """Reference FIPS-46 DES for VNCAuth test client (pure Python).""" + IP = [58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8, + 57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7] + FP = [40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29, + 36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25] + PC1 = [57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36, + 63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4] + PC2 = [14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2, + 41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32] + ROT = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1] + E = [32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17, + 16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1] + P = [16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25] + S = [ + [14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8, + 4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13], + [15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5, + 0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9], + [10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1, + 13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12], + [7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9, + 10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14], + [2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6, + 4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3], + [12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8, + 9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13], + [4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6, + 1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12], + [13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2, + 7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11], + ] + + def perm(val, inb, tbl): + out = 0 + for b in tbl: + out = (out << 1) | ((val >> (inb - b)) & 1) + return out + + raw = password.encode("latin-1", "replace")[:8].ljust(8, b"\x00") + k64 = 0 + for byte in raw: + rev = int(f"{byte:08b}"[::-1], 2) + k64 = (k64 << 8) | rev + cd = perm(k64, 64, PC1) + C, D = cd >> 28, cd & 0x0FFFFFFF + sk = [] + for r in ROT: + C = ((C << r) | (C >> (28 - r))) & 0x0FFFFFFF + D = ((D << r) | (D >> (28 - r))) & 0x0FFFFFFF + sk.append(perm((C << 28) | D, 56, PC2)) + + def enc_block(blk): + ip = perm(int.from_bytes(blk, "big"), 64, IP) + L, R = ip >> 32, ip & 0xFFFFFFFF + for k in sk: + exp = perm(R, 32, E) ^ k + sout = 0 + for i in range(8): + six = (exp >> ((7 - i) * 6)) & 0x3F + row = ((six & 0x20) >> 4) | (six & 1) + col = (six >> 1) & 0x0F + sout = (sout << 4) | S[i][row * 16 + col] + L, R = R, L ^ perm(sout, 32, P) + return perm((R << 32) | L, 64, FP).to_bytes(8, "big") + + return enc_block(challenge[:8]) + enc_block(challenge[8:16]) + + +class MockShm: + def __init__(self, path: str): + self.path = path + self.fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600) + os.ftruncate(self.fd, CHANDRA_FB_TOTAL_BYTES) + self.mm = mmap.mmap(self.fd, CHANDRA_FB_TOTAL_BYTES) + self.seq = 0 + self.slot = 0 + struct.pack_into(" bytes: + buf = bytearray() + while len(buf) < n: + c = s.recv(n - len(buf)) + if not c: + raise EOFError("short read") + buf += c + return bytes(buf) + + +def ws_connect(host: str, port: int, path: str = "/ws", cookie: str = ""): + s = socket.create_connection((host, port), timeout=5) + key = base64.b64encode(os.urandom(16)).decode() + hdrs = [ + f"GET {path} HTTP/1.1", + f"Host: {host}:{port}", + "Upgrade: websocket", + "Connection: Upgrade", + f"Sec-WebSocket-Key: {key}", + "Sec-WebSocket-Version: 13", + ] + if cookie: + hdrs.append(f"Cookie: {cookie}") + s.sendall(("\r\n".join(hdrs) + "\r\n\r\n").encode()) + raw = b"" + while b"\r\n\r\n" not in raw: + chunk = s.recv(4096) + if not chunk: + raise EOFError("ws handshake closed") + raw += chunk + head, extra = raw.split(b"\r\n\r\n", 1) + status_line = head.split(b"\r\n", 1)[0].decode() + return s, status_line, head.decode("latin-1"), extra + + +def ws_send_text(s: socket.socket, text: str): + payload = text.encode("utf-8") + mask = os.urandom(4) + hdr = bytearray([0x81]) + n = len(payload) + if n <= 125: + hdr.append(0x80 | n) + elif n <= 65535: + hdr.append(0x80 | 126) + hdr += struct.pack(">H", n) + else: + hdr.append(0x80 | 127) + hdr += struct.pack(">Q", n) + hdr += mask + masked = bytes(payload[i] ^ mask[i & 3] for i in range(n)) + s.sendall(bytes(hdr) + masked) + + +def ws_read_frame(s: socket.socket, buf: bytearray): + while len(buf) < 2: + buf += s.recv(4096) + b0, b1 = buf[0], buf[1] + op = b0 & 0x0F + plen = b1 & 0x7F + pos = 2 + if plen == 126: + while len(buf) < 4: + buf += s.recv(4096) + plen = struct.unpack(">H", buf[2:4])[0] + pos = 4 + elif plen == 127: + while len(buf) < 10: + buf += s.recv(4096) + plen = struct.unpack(">Q", buf[2:10])[0] + pos = 10 + while len(buf) < pos + plen: + buf += s.recv(65536) + payload = bytes(buf[pos : pos + plen]) + del buf[: pos + plen] + return op, payload + + +def find_remote_bin() -> str: + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + cand = os.path.join(root, "build/chandra-remote") + if os.path.exists(cand): + return cand + if shutil.which("chandra-remote"): + return shutil.which("chandra-remote") + raise FileNotFoundError("build/chandra-remote not built") + + +class RemoteTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="chandra-remote-test-") + self.shm_path = os.path.join(self.tmp, "fb.shm") + self.sock_path = os.path.join(self.tmp, "wayland.sock") + self.cfg_path = os.path.join(self.tmp, "remote.conf") + self.web_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "web") + self.bin = find_remote_bin() + self.shm = MockShm(self.shm_path) + self.ctl = MockCtlServer(self.sock_path) + self.proc = None + + def tearDown(self): + if self.proc: + if self.proc.poll() is None: + self.proc.terminate() + self.proc.wait(timeout=5) + if self.proc.stdout: + self.proc.stdout.close() + if self.proc.stderr: + self.proc.stderr.close() + self.ctl.close() + self.shm.close() + shutil.rmtree(self.tmp, ignore_errors=True) + + def start_daemon(self, auth="none", password="", bind="127.0.0.1"): + with open(self.cfg_path, "w") as f: + f.write( + f"enabled=1\nbind={bind}\nbind_loopback=1\nauth={auth}\n" + f"jpeg_quality=88\nmax_fps=60\n" + ) + if password: + f.write(f"password={password}\n") + self.vnc_port = free_port() + self.web_port = free_port() + self.proc = subprocess.Popen( + [ + self.bin, + "--config", self.cfg_path, + "--socket", self.sock_path, + "--shm", self.shm_path, + "--web-dir", self.web_dir, + "--bind", bind, + "--vnc-port", str(self.vnc_port), + "--web-port", str(self.web_port), + ], + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + ) + # Wait until web port accepts TCP + deadline = time.time() + 5.0 + while time.time() < deadline: + if self.proc.poll() is not None: + raise RuntimeError(f"daemon exited early: {self.proc.stderr.read().decode()}") + try: + with socket.create_connection(("127.0.0.1", self.web_port), timeout=0.2): + return + except OSError: + time.sleep(0.05) + raise TimeoutError("daemon failed to listen") + + def test_01_refuse_unauth_open_bind(self): + with open(self.cfg_path, "w") as f: + f.write("enabled=1\nbind=0.0.0.0\nauth=none\n") + r = subprocess.run( + [self.bin, "--config", self.cfg_path, "--vnc-port", str(free_port()), "--web-port", str(free_port())], + capture_output=True, + text=True, + ) + self.assertNotEqual(r.returncode, 0) + self.assertIn("refusing", r.stderr) + + def test_02_vnc_none_tight_zlib_raw_resize_and_input(self): + self.shm.write_frame(120, 80, lambda x, y: (220, 40, 30) if x < 60 else (20, 180, 60)) + self.start_daemon(auth="none") + + with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s: + self.assertEqual(recv_exact(s, 12), b"RFB 003.008\n") + s.sendall(b"RFB 003.008\n") + nt = recv_exact(s, 1)[0] + types = recv_exact(s, nt) + self.assertIn(1, types) + s.sendall(b"\x01") + self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 0) + s.sendall(b"\x01") # ClientInit shared=1 + sinit = recv_exact(s, 24) + w0, h0 = struct.unpack(">HH", sinit[:4]) + self.assertGreater(w0, 0) + name_len = struct.unpack(">I", sinit[20:24])[0] + self.assertEqual(recv_exact(s, name_len), b"Chandra") + + # Advertise Tight(7), JPEG quality -24, Zlib(6), Raw(0), ExtendedDesktopSize(-308) + encs = [7, -24, 6, 0, -308] + s.sendall(struct.pack(">BxH" + "i" * len(encs), 2, len(encs), *encs)) + + # Request full Tight JPEG frame + s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, 120, 80)) + msg = recv_exact(s, 4) + self.assertEqual(msg[0], 0) + nrects = struct.unpack(">H", msg[2:4])[0] + saw_pixel = False + for _ in range(nrects): + rx, ry, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12)) + if enc == -308: + nscr = recv_exact(s, 4)[0] + recv_exact(s, nscr * 16) + elif enc == 7: + ctrl = recv_exact(s, 1)[0] + self.assertEqual(ctrl, 0x90) + jlen = 0 + for sh in (0, 7, 14): + b = recv_exact(s, 1)[0] + if sh < 14: + jlen |= (b & 0x7F) << sh + if not (b & 0x80): + break + else: + jlen |= b << sh + jpg = recv_exact(s, jlen) + jw, jh, rgb = decode_jpeg_rgb(jpg) + self.assertEqual((jw, jh), (120, 80)) + # Left half red, right half green (verify no R/B swap!) + lr, lg, lb = rgb[(40 * jw + 20) * 3 : (40 * jw + 20) * 3 + 3] + rr, rg, rb = rgb[(40 * jw + 100) * 3 : (40 * jw + 100) * 3 + 3] + self.assertGreater(lr, 180) + self.assertLess(lb, 60) + self.assertGreater(rg, 140) + self.assertLess(rr, 60) + saw_pixel = True + self.assertTrue(saw_pixel) + + # Rotate SHM dimensions 120x80 -> 80x120 and verify ExtendedDesktopSize(-308) + self.shm.write_frame(80, 120, lambda x, y: (30, 50, 230)) + s.sendall(struct.pack(">BBHHHH", 3, 1, 0, 0, 120, 80)) + msg = recv_exact(s, 4) + nrects = struct.unpack(">H", msg[2:4])[0] + got_ext = False + for _ in range(nrects): + rx, ry, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12)) + if enc == -308: + self.assertEqual((rw, rh), (80, 120)) + nscr = recv_exact(s, 4)[0] + recv_exact(s, nscr * 16) + got_ext = True + elif enc == 7: + recv_exact(s, 1) + jlen = 0 + for sh in (0, 7, 14): + b = recv_exact(s, 1)[0] + if sh < 14: + jlen |= (b & 0x7F) << sh + if not (b & 0x80): + break + else: + jlen |= b << sh + jw, jh, rgb = decode_jpeg_rgb(recv_exact(s, jlen)) + self.assertEqual((jw, jh), (80, 120)) + br, bg, bb = rgb[(60 * jw + 40) * 3 : (60 * jw + 40) * 3 + 3] + self.assertGreater(bb, 190) + self.assertLess(br, 60) + self.assertTrue(got_ext) + + # Pointer, scroll, Shift+'A', Unicode é, CutText + s.sendall(struct.pack(">BBHH", 5, 1, 25, 35)) + s.sendall(struct.pack(">BBHH", 5, 8, 25, 35)) # scroll up bit + s.sendall(struct.pack(">BBxxI", 4, 1, 0x0041)) # 'A' down + s.sendall(struct.pack(">BBxxI", 4, 0, 0x0041)) # 'A' up + s.sendall(struct.pack(">BBxxI", 4, 1, 0x00E9)) # Latin-1 e-acute + cut = b"hello-vnc" + s.sendall(struct.pack(">BxxxI", 6, len(cut)) + cut) + time.sleep(0.15) + cmds = "\n".join(self.ctl.commands) + self.assertIn("input-ptr 25 35", cmds) + self.assertIn("input-btn 272 1", cmds) + 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) + + def test_03_vnc_password_and_zlib(self): + self.shm.write_frame(64, 48, lambda x, y: (10, 200, 220)) + self.start_daemon(auth="password", password="TestPass99") + + # Bad password fails + with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s: + recv_exact(s, 12) + s.sendall(b"RFB 003.008\n") + nt = recv_exact(s, 1)[0] + types = recv_exact(s, nt) + self.assertEqual(types, b"\x02") + s.sendall(b"\x02") + chal = recv_exact(s, 16) + s.sendall(vnc_des_encrypt_py("WrongPass", chal)) + self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 1) + + # Good password + Zlib frame + with socket.create_connection(("127.0.0.1", self.vnc_port), timeout=5) as s: + recv_exact(s, 12) + s.sendall(b"RFB 003.008\n") + recv_exact(s, 2) + s.sendall(b"\x02") + chal = recv_exact(s, 16) + s.sendall(vnc_des_encrypt_py("TestPass99", chal)) + self.assertEqual(struct.unpack(">I", recv_exact(s, 4))[0], 0) + s.sendall(b"\x01") + sinit = recv_exact(s, 24) + recv_exact(s, struct.unpack(">I", sinit[20:24])[0]) + s.sendall(struct.pack(">BxHii", 2, 2, 6, 0)) # Zlib, Raw + s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, 64, 48)) + msg = recv_exact(s, 4) + nrects = struct.unpack(">H", msg[2:4])[0] + self.assertEqual(nrects, 1) + _, _, rw, rh, enc = struct.unpack(">HHHHi", recv_exact(s, 12)) + self.assertEqual((rw, rh, enc), (64, 48, 6)) + zlen = struct.unpack(">I", recv_exact(s, 4))[0] + px = zlib.decompressobj().decompress(recv_exact(s, zlen)) + self.assertEqual(len(px), 64 * 48 * 4) + self.assertEqual(tuple(px[:3]), (10, 200, 220)) + + def test_04_web_no_auth_stream_ack_and_ctl(self): + self.shm.write_frame(160, 120, lambda x, y: (240, 120, 15)) + self.start_daemon(auth="none") + + c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5) + c.request("GET", "/api/info") + r = c.getresponse() + self.assertEqual(r.status, 200) + info = json.loads(r.read()) + self.assertFalse(info["auth_required"]) + + c.request("GET", "/") + r = c.getresponse() + self.assertEqual(r.status, 200) + self.assertIn(b"Chandra Remote", r.read()) + c.close() + + ws, status_line, _, extra = ws_connect("127.0.0.1", self.web_port) + self.assertIn("101", status_line) + buf = bytearray(extra) + frames = [] + statuses = [] + deadline = time.time() + 4.0 + while time.time() < deadline and (len(frames) < 1 or len(statuses) < 1): + op, payload = ws_read_frame(ws, buf) + if op == 1: + statuses.append(json.loads(payload)) + elif op == 2: + frames.append(payload) + self.assertGreaterEqual(len(statuses), 1) + self.assertEqual(statuses[0]["t"], "status") + hdr = struct.unpack(">BBHHHHHHI", frames[0][:18]) + ftype, flags, x, y, w, h, fbw, fbh, fid = hdr + self.assertEqual((ftype, fbw, fbh), (1, 160, 120)) + jw, jh, rgb = decode_jpeg_rgb(frames[0][18:]) + self.assertEqual((jw, jh), (160, 120)) + pr, pg, pb = rgb[:3] + self.assertGreater(pr, 200) + self.assertGreater(pg, 90) + self.assertLess(pb, 50) + + ws_send_text(ws, json.dumps({"t": "ack", "id": fid})) + ws_send_text(ws, json.dumps({"t": "tap", "x": 50, "y": 60, "b": 1})) + ws_send_text(ws, json.dumps({"t": "text", "s": "hi!"})) + ws_send_text(ws, json.dumps({"t": "ctl", "cmd": "rotate cw"})) + + deadline = time.time() + 3.0 + saw_rot = False + while time.time() < deadline and not saw_rot: + op, payload = ws_read_frame(ws, buf) + if op == 1: + st = json.loads(payload) + if st.get("rot") == 90: + saw_rot = True + self.assertTrue(saw_rot) + cmds = "\n".join(self.ctl.commands) + self.assertIn("input-ptr 50 60", cmds) + self.assertIn("input-btn 272 1", cmds) + self.assertIn("input-key-tap 2 1", cmds) # '!' shifted (KEY_1) + self.assertIn("rotate cw", cmds) + ws.close() + + def test_05_web_password_auth_gate(self): + self.shm.write_frame(96, 96, lambda x, y: (40, 90, 210)) + self.start_daemon(auth="password", password="Secret42") + + ws0, status_line0, _, _ = ws_connect("127.0.0.1", self.web_port) + self.assertIn("401", status_line0) + ws0.close() + + c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=5) + c.request("POST", "/api/login", body=json.dumps({"password": "bad"})) + self.assertEqual(c.getresponse().status, 401) + c.request("POST", "/api/login", body=json.dumps({"password": "Secret42"})) + r = c.getresponse() + self.assertEqual(r.status, 200) + tok = json.loads(r.read())["token"] + self.assertTrue(len(tok) > 10) + c.close() + + ws, status_line, _, _ = ws_connect("127.0.0.1", self.web_port, path=f"/ws?token={tok}") + self.assertIn("101", status_line) + ws.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/remote/web.c b/remote/web.c new file mode 100644 index 0000000..42c4470 --- /dev/null +++ b/remote/web.c @@ -0,0 +1,763 @@ +#include "remote_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int write_all_fd(int fd, const void *buf, size_t len) { + const uint8_t *p = (const uint8_t *)buf; + size_t done = 0; + while (done < len) { + ssize_t w = send(fd, p + done, len - done, MSG_NOSIGNAL); + if (w < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + struct pollfd pfd = { .fd = fd, .events = POLLOUT }; + if (poll(&pfd, 1, 5000) <= 0) return -1; + continue; + } + return -1; + } + if (w == 0) return -1; + done += (size_t)w; + } + return 0; +} + +static void http_send(int fd, const char *status, const char *ctype, const char *extra_hdr, + const void *body, size_t blen) { + char hdr[1024]; + int n = snprintf(hdr, sizeof hdr, + "HTTP/1.1 %s\r\n" + "Content-Type: %s\r\n" + "Content-Length: %zu\r\n" + "Cache-Control: no-store\r\n" + "Connection: close\r\n" + "%s\r\n", + status, ctype, blen, extra_hdr ? extra_hdr : ""); + if (n > 0) write_all_fd(fd, hdr, (size_t)n); + if (blen > 0) write_all_fd(fd, body, blen); +} + +static int serve_static(int fd, const char *web_dir, const char *name, const char *ctype) { + char path[600]; + snprintf(path, sizeof path, "%s/%s", web_dir, name); + int f = open(path, O_RDONLY | O_CLOEXEC); + if (f < 0) { + const char *msg = "Not found"; + http_send(fd, "404 Not Found", "text/plain", NULL, msg, strlen(msg)); + return -1; + } + struct stat st; + if (fstat(f, &st) < 0 || st.st_size < 0 || st.st_size > 2 * 1024 * 1024) { + close(f); + const char *msg = "Error reading file"; + http_send(fd, "500 Internal Server Error", "text/plain", NULL, msg, strlen(msg)); + return -1; + } + size_t len = (size_t)st.st_size; + uint8_t *buf = len ? malloc(len) : NULL; + if (len && !buf) { close(f); return -1; } + size_t got = 0; + while (got < len) { + ssize_t r = read(f, buf + got, len - got); + if (r <= 0) break; + got += (size_t)r; + } + close(f); + http_send(fd, "200 OK", ctype, NULL, buf, got); + free(buf); + return 0; +} + +/* Extract a JSON string value for key `"key":"..."` safely (handles escapes). */ +static int json_get_str(const char *json, const char *key, char *out, size_t cap) { + char pat[64]; + snprintf(pat, sizeof pat, "\"%s\"", key); + const char *p = json; + while ((p = strstr(p, pat)) != NULL) { + const char *q = p + strlen(pat); + while (*q && isspace((unsigned char)*q)) q++; + if (*q != ':') { p++; continue; } + q++; + while (*q && isspace((unsigned char)*q)) q++; + if (*q != '"') return 0; + q++; + size_t o = 0; + while (*q && *q != '"') { + char ch = *q++; + if (ch == '\\' && *q) { + char esc = *q++; + if (esc == 'n') ch = '\n'; + else if (esc == 'r') ch = '\r'; + else if (esc == 't') ch = '\t'; + else ch = esc; + } + if (o + 1 < cap) out[o++] = ch; + } + out[o] = 0; + return *q == '"'; + } + return 0; +} + +static int json_get_int(const char *json, const char *key, long *out) { + char pat[64]; + snprintf(pat, sizeof pat, "\"%s\"", key); + const char *p = json; + while ((p = strstr(p, pat)) != NULL) { + const char *q = p + strlen(pat); + while (*q && isspace((unsigned char)*q)) q++; + if (*q != ':') { p++; continue; } + q++; + while (*q && isspace((unsigned char)*q)) q++; + if (*q != '-' && !isdigit((unsigned char)*q)) return 0; + char *endp = NULL; + long v = strtol(q, &endp, 10); + if (endp == q) return 0; + *out = v; + return 1; + } + return 0; +} + +static const char *find_header(const char *hdrs, const char *name, char *val, size_t cap) { + size_t nlen = strlen(name); + const char *line = strstr(hdrs, "\r\n"); + if (!line) return NULL; + line += 2; + while (*line && !(line[0] == '\r' && line[1] == '\n')) { + const char *eol = strstr(line, "\r\n"); + const char *next = eol ? eol + 2 : NULL; + if (!eol) eol = line + strlen(line); + if (strncasecmp(line, name, nlen) == 0 && line[nlen] == ':') { + const char *v = line + nlen + 1; + while (v < eol && (*v == ' ' || *v == '\t')) v++; + const char *ve = eol; + while (ve > v && (ve[-1] == ' ' || ve[-1] == '\t')) ve--; + size_t l = (size_t)(ve - v); + if (l >= cap) l = cap - 1; + memcpy(val, v, l); + val[l] = 0; + return val; + } + if (!next) break; + line = next; + } + return NULL; +} + +static int extract_cookie_token(const char *cookie, char *out, size_t cap) { + if (!cookie) return 0; + const char *p = cookie; + while ((p = strstr(p, "chandra_remote=")) != NULL) { + p += 15; + const char *e = p; + while (*e && *e != ';' && !isspace((unsigned char)*e)) e++; + size_t l = (size_t)(e - p); + if (l > 0 && l < cap) { + memcpy(out, p, l); + out[l] = 0; + return 1; + } + } + return 0; +} + +static int extract_query_token(const char *target, char *out, size_t cap) { + const char *q = strchr(target, '?'); + if (!q) return 0; + q++; + const char *p = strstr(q, "token="); + if (!p) return 0; + p += 6; + const char *e = p; + while (*e && *e != '&' && *e != ' ') e++; + size_t l = (size_t)(e - p); + if (l == 0 || l >= cap) return 0; + memcpy(out, p, l); + out[l] = 0; + return 1; +} + +static int ws_send_frame(int fd, uint8_t opcode, const void *data, size_t len) { + uint8_t hdr[10]; + size_t hlen = 2; + hdr[0] = (uint8_t)(0x80u | (opcode & 0x0Fu)); + if (len <= 125) { + hdr[1] = (uint8_t)len; + } else if (len <= 65535) { + hdr[1] = 126; + hdr[2] = (uint8_t)(len >> 8); + hdr[3] = (uint8_t)len; + hlen = 4; + } else { + hdr[1] = 127; + uint64_t l64 = (uint64_t)len; + for (int i = 0; i < 8; i++) hdr[2 + i] = (uint8_t)(l64 >> ((7 - i) * 8)); + hlen = 10; + } + if (write_all_fd(fd, hdr, hlen) < 0) return -1; + if (len > 0 && write_all_fd(fd, data, len) < 0) return -1; + return 0; +} + +static int ws_send_text(int fd, const char *s) { + return ws_send_frame(fd, 0x01u, s, strlen(s)); +} + +/* Validate allowlisted `ctl` commands exposed to the mobile Web UI. */ +static int ctl_command_allowed(const char *cmd) { + if (strcmp(cmd, "refresh") == 0 || strcmp(cmd, "status") == 0) return 1; + if (strncmp(cmd, "rotate ", 7) == 0) { + const char *a = cmd + 7; + return !strcmp(a, "cw") || !strcmp(a, "ccw") || !strcmp(a, "flip") || + !strcmp(a, "0") || !strcmp(a, "90") || !strcmp(a, "180") || !strcmp(a, "270"); + } + if (strncmp(cmd, "screen ", 7) == 0) { + const char *a = cmd + 7; + return !strcmp(a, "on") || !strcmp(a, "off") || !strcmp(a, "toggle"); + } + if (strncmp(cmd, "osk ", 4) == 0) { + const char *a = cmd + 4; + return !strcmp(a, "on") || !strcmp(a, "off") || !strcmp(a, "toggle"); + } + if (strncmp(cmd, "shortcut ", 9) == 0) { + const char *a = cmd + 9; + return !strcmp(a, "launcher") || !strcmp(a, "overview") || !strcmp(a, "show-desktop"); + } + if (strncmp(cmd, "brightness ", 11) == 0) { + char *endp = NULL; + long v = strtol(cmd + 11, &endp, 10); + return endp && *endp == 0 && v >= 5 && v <= 100; + } + return 0; +} + +static int parse_status_json(const char *reply, char *out, size_t cap) { + unsigned int w = 0, h = 0; + int rot = 0, bri = -1, px = 0, py = 0, osk = 0; + char scr[16] = "on"; + const char *p = strstr(reply, "ok "); + if (!p) return -1; + if (sscanf(p, "ok %ux%u rot=%d screen=%15s brightness=%d ptr=%d,%d osk=%d", + &w, &h, &rot, scr, &bri, &px, &py, &osk) < 4) { + return -1; + } + snprintf(out, cap, + "{\"t\":\"status\",\"w\":%u,\"h\":%u,\"rot\":%d,\"screen\":\"%s\",\"brightness\":%d,\"osk\":%d}", + w, h, rot, scr, bri, osk); + return 0; +} + +typedef struct { + int fd; + RemoteApp *app; + uint32_t held_mods; + uint32_t acked_id; + uint32_t next_frame_id; + int quality; + int max_fps; + char last_status_json[256]; +} WsState; + +static void ws_send_status(WsState *ws) { + char reply[256], js[256]; + if (ctl_cmd(&ws->app->ctl, "status", reply, sizeof reply) == 0 && + parse_status_json(reply, js, sizeof js) == 0) { + if (strcmp(js, ws->last_status_json) != 0) { + snprintf(ws->last_status_json, sizeof ws->last_status_json, "%s", js); + ws_send_text(ws->fd, js); + } + } +} + +static void ws_handle_text(WsState *ws, const char *msg) { + char type[32] = {0}; + if (!json_get_str(msg, "t", type, sizeof type)) return; + + if (strcmp(type, "ack") == 0) { + long id = 0; + if (json_get_int(msg, "id", &id) && id >= 0 && (uint32_t)id > ws->acked_id) { + ws->acked_id = (uint32_t)id; + } + return; + } + if (strcmp(type, "ptr") == 0) { + long x = 0, y = 0; + if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) { + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y); + ctl_fire(&ws->app->ctl, cmd); + } + return; + } + if (strcmp(type, "btn") == 0) { + long b = 1, d = 0; + if (json_get_int(msg, "b", &b) && json_get_int(msg, "d", &d)) { + unsigned int code = (b == 3) ? 273u : (b == 2) ? 274u : 272u; + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-btn %u %d", code, d ? 1 : 0); + ctl_fire(&ws->app->ctl, cmd); + } + return; + } + if (strcmp(type, "tap") == 0) { + long x = 0, y = 0, b = 1; + if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) { + json_get_int(msg, "b", &b); + unsigned int code = (b == 3) ? 273u : (b == 2) ? 274u : 272u; + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y); + ctl_fire(&ws->app->ctl, cmd); + snprintf(cmd, sizeof cmd, "input-btn %u 1", code); + ctl_fire(&ws->app->ctl, cmd); + snprintf(cmd, sizeof cmd, "input-btn %u 0", code); + ctl_fire(&ws->app->ctl, cmd); + } + return; + } + if (strcmp(type, "scroll") == 0) { + long x = 0, y = 0, dx = 0, dy = 0; + if (json_get_int(msg, "x", &x) && json_get_int(msg, "y", &y)) { + json_get_int(msg, "dx", &dx); + json_get_int(msg, "dy", &dy); + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-ptr %ld %ld", x, y); + ctl_fire(&ws->app->ctl, cmd); + if (dy != 0) { + snprintf(cmd, sizeof cmd, "input-scroll 0 %ld 0", dy); + ctl_fire(&ws->app->ctl, cmd); + } + if (dx != 0) { + snprintf(cmd, sizeof cmd, "input-scroll 1 %ld 0", dx); + ctl_fire(&ws->app->ctl, cmd); + } + } + return; + } + if (strcmp(type, "ktap") == 0) { + long code = 0, mods = 0; + if (json_get_int(msg, "c", &code) && code > 0) { + json_get_int(msg, "m", &mods); + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-key-tap %ld %ld", code, mods); + ctl_fire(&ws->app->ctl, cmd); + } + return; + } + if (strcmp(type, "key") == 0) { + long sym = 0, down = 1; + if (!json_get_int(msg, "k", &sym)) return; + json_get_int(msg, "d", &down); + uint32_t ev = 0, uc = 0; + int sh = 0, mod_bit = 0; + if (!keysym_to_evdev((uint32_t)sym, &ev, &sh, &mod_bit, &uc)) return; + if (mod_bit) { + if (down) ws->held_mods |= (uint32_t)mod_bit; + else ws->held_mods &= ~(uint32_t)mod_bit; + char cmd[64]; + snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", ws->held_mods); + ctl_fire(&ws->app->ctl, cmd); + snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down ? 1 : 0); + ctl_fire(&ws->app->ctl, cmd); + } else if (ev) { + uint32_t em = ws->held_mods | (sh ? 1u : 0u); + char cmd[64]; + if (em != ws->held_mods) { + snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", em); + ctl_fire(&ws->app->ctl, cmd); + } + snprintf(cmd, sizeof cmd, "input-key %u %d", ev, down ? 1 : 0); + ctl_fire(&ws->app->ctl, cmd); + if (em != ws->held_mods) { + snprintf(cmd, sizeof cmd, "input-mods %u 0 0 0", ws->held_mods); + ctl_fire(&ws->app->ctl, cmd); + } + } + return; + } + if (strcmp(type, "text") == 0) { + char txt[1024] = {0}; + if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) { + remote_send_utf8_text(&ws->app->ctl, txt); + } + return; + } + if (strcmp(type, "clip") == 0) { + char txt[2048] = {0}; + if (json_get_str(msg, "s", txt, sizeof txt) && txt[0]) { + size_t n = strlen(txt); + char *cmd = malloc(16 + n * 2 + 1); + if (cmd) { + memcpy(cmd, "clipboard-set ", 14); + hex_encode((const uint8_t *)txt, n, cmd + 14); + ctl_fire(&ws->app->ctl, cmd); + free(cmd); + } + } + return; + } + if (strcmp(type, "ctl") == 0) { + char cstr[128] = {0}; + if (json_get_str(msg, "cmd", cstr, sizeof cstr) && ctl_command_allowed(cstr)) { + ctl_fire(&ws->app->ctl, cstr); + ws->last_status_json[0] = 0; + ws_send_status(ws); + } + return; + } + if (strcmp(type, "cfg") == 0) { + long q = 0, fps = 0; + if (json_get_int(msg, "q", &q)) { + ws->quality = q < 20 ? 20 : (q > 95 ? 95 : (int)q); + } + if (json_get_int(msg, "fps", &fps)) { + ws->max_fps = fps < 5 ? 5 : (fps > 60 ? 60 : (int)fps); + } + } +} + +static void ws_loop(RemoteApp *app, int fd) { + WsState ws; + memset(&ws, 0, sizeof ws); + ws.fd = fd; + ws.app = app; + ws.next_frame_id = 1; + pthread_mutex_lock(&app->cfg_mu); + ws.quality = app->cfg.jpeg_quality; + ws.max_fps = app->cfg.max_fps; + pthread_mutex_unlock(&app->cfg_mu); + + FbReader fb; + fb_reader_init(&fb, app->shm_path); + fb_reader_ping(&fb); + ctl_fire(&app->ctl, "refresh"); + + tjhandle tj = tjInitCompress(); + uint8_t *scratch = NULL, *frame_pkt = NULL; + size_t scratch_cap = 0, pkt_cap = 0; + uint8_t *rx = malloc(65536); + size_t rx_len = 0, rx_cap = 65536; + if (!rx) goto out; + + uint64_t last_seq = 0, last_send_ms = 0, last_ping = 0, last_status_ms = 0; + uint32_t last_w = 0, last_h = 0; + + ws_send_status(&ws); + + while (*app->running) { + uint64_t now = remote_now_ms(); + if (now - last_ping >= 250) { + fb_reader_ping(&fb); + last_ping = now; + } + if (now - last_status_ms >= 2000) { + ws_send_status(&ws); + last_status_ms = now; + } + + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + int pr = poll(&pfd, 1, 16); + if (pr < 0) { + if (errno == EINTR) continue; + break; + } + if (pr > 0) { + if (pfd.revents & (POLLHUP | POLLERR)) break; + if (pfd.revents & POLLIN) { + if (rx_len == rx_cap) { + if (rx_cap >= 1024 * 1024) break; + uint8_t *nrx = realloc(rx, rx_cap * 2); + if (!nrx) break; + rx = nrx; + rx_cap *= 2; + } + ssize_t r = recv(fd, rx + rx_len, rx_cap - rx_len, 0); + if (r <= 0) break; + rx_len += (size_t)r; + + while (rx_len >= 2) { + uint8_t b0 = rx[0], b1 = rx[1]; + uint8_t op = (uint8_t)(b0 & 0x0Fu); + int masked = (b1 & 0x80u) != 0; + uint64_t plen = (uint64_t)(b1 & 0x7Fu); + size_t pos = 2; + if (plen == 126) { + if (rx_len < 4) break; + plen = ((uint64_t)rx[2] << 8) | rx[3]; + pos = 4; + } else if (plen == 127) { + if (rx_len < 10) break; + plen = 0; + for (int i = 0; i < 8; i++) plen = (plen << 8) | rx[2 + i]; + pos = 10; + } + if (plen > 512u * 1024u) { rx_len = 0; goto out; } + size_t mlen = masked ? 4 : 0; + if (rx_len < pos + mlen + (size_t)plen) break; + + uint8_t mask[4] = {0}; + if (masked) memcpy(mask, rx + pos, 4); + uint8_t *payload = rx + pos + mlen; + if (masked) { + for (size_t i = 0; i < (size_t)plen; i++) payload[i] ^= mask[i & 3u]; + } + if (op == 0x08u) { /* Close */ + ws_send_frame(fd, 0x08u, NULL, 0); + goto out; + } else if (op == 0x09u) { /* Ping */ + ws_send_frame(fd, 0x0Au, payload, (size_t)plen); + } else if (op == 0x01u) { /* Text */ + char *tmsg = malloc((size_t)plen + 1); + if (tmsg) { + memcpy(tmsg, payload, (size_t)plen); + tmsg[plen] = 0; + ws_handle_text(&ws, tmsg); + free(tmsg); + } + } + size_t total = pos + mlen + (size_t)plen; + memmove(rx, rx + total, rx_len - total); + rx_len -= total; + } + } + } + + uint32_t sent_so_far = ws.next_frame_id - 1; + uint32_t in_flight = sent_so_far > ws.acked_id ? sent_so_far - ws.acked_id : 0; + if (in_flight >= 2) continue; + + now = remote_now_ms(); + uint64_t min_gap = (uint64_t)(1000 / (ws.max_fps > 0 ? ws.max_fps : 30)); + if (last_seq != 0 && now - last_send_ms < min_gap) continue; + + int full = 0, x0 = 0, y0 = 0, x1 = 0, y1 = 0; + uint32_t fb_w = 0, fb_h = 0; + uint64_t new_seq = 0; + int got = fb_reader_grab(&fb, last_seq, last_w, last_h, + &full, &fb_w, &fb_h, &x0, &y0, &x1, &y1, &new_seq, + &scratch, &scratch_cap); + if (got <= 0) continue; + + if (full || fb_w != last_w || fb_h != last_h) { + x0 = 0; y0 = 0; x1 = (int)fb_w; y1 = (int)fb_h; + full = 1; + } + int rw = x1 - x0; + int rh = y1 - y0; + if (rw <= 0 || rh <= 0) { + last_seq = new_seq; + last_w = fb_w; + last_h = fb_h; + continue; + } + if (!tj) break; + const uint8_t *ptr = scratch + ((size_t)y0 * (size_t)fb_w + (size_t)x0) * 4; + unsigned char *jbuf = NULL; + unsigned long jsz = 0; + if (tjCompress2(tj, ptr, rw, (int)fb_w * 4, rh, TJPF_RGBX, &jbuf, &jsz, TJSAMP_420, + ws.quality, TJFLAG_FASTDCT) != 0 || !jbuf || jsz == 0) { + if (jbuf) tjFree(jbuf); + continue; + } + size_t need = 18 + (size_t)jsz; + if (need > pkt_cap) { + uint8_t *np = realloc(frame_pkt, need); + if (!np) { tjFree(jbuf); break; } + frame_pkt = np; + pkt_cap = need; + } + uint32_t fid = ws.next_frame_id++; + frame_pkt[0] = 1; + frame_pkt[1] = full ? 1 : 0; + frame_pkt[2] = (uint8_t)(x0 >> 8); frame_pkt[3] = (uint8_t)x0; + frame_pkt[4] = (uint8_t)(y0 >> 8); frame_pkt[5] = (uint8_t)y0; + frame_pkt[6] = (uint8_t)(rw >> 8); frame_pkt[7] = (uint8_t)rw; + frame_pkt[8] = (uint8_t)(rh >> 8); frame_pkt[9] = (uint8_t)rh; + frame_pkt[10] = (uint8_t)(fb_w >> 8); frame_pkt[11] = (uint8_t)fb_w; + frame_pkt[12] = (uint8_t)(fb_h >> 8); frame_pkt[13] = (uint8_t)fb_h; + frame_pkt[14] = (uint8_t)(fid >> 24); + frame_pkt[15] = (uint8_t)(fid >> 16); + frame_pkt[16] = (uint8_t)(fid >> 8); + frame_pkt[17] = (uint8_t)fid; + memcpy(frame_pkt + 18, jbuf, (size_t)jsz); + tjFree(jbuf); + + if (ws_send_frame(fd, 0x02u, frame_pkt, need) < 0) break; + last_seq = new_seq; + last_w = fb_w; + last_h = fb_h; + last_send_ms = now; + } + +out: + if (ws.held_mods) ctl_fire(&app->ctl, "input-mods 0 0 0 0"); + if (tj) tjDestroy(tj); + fb_reader_close(&fb); + free(scratch); + free(frame_pkt); + free(rx); +} + +void web_handle_client(RemoteApp *app, int fd) { + char buf[16384]; + size_t len = 0; + char *hdr_end = NULL; + while (len + 1 < sizeof buf) { + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + if (poll(&pfd, 1, 5000) <= 0) { close(fd); return; } + ssize_t r = recv(fd, buf + len, sizeof buf - 1 - len, 0); + if (r <= 0) { close(fd); return; } + len += (size_t)r; + buf[len] = 0; + hdr_end = strstr(buf, "\r\n\r\n"); + if (hdr_end) break; + } + if (!hdr_end) { + const char *m = "Header too large"; + http_send(fd, "431 Request Header Fields Too Large", "text/plain", NULL, m, strlen(m)); + close(fd); + return; + } + *hdr_end = 0; + char *body = hdr_end + 4; + size_t body_have = len - (size_t)(body - buf); + + char method[16] = {0}, target[512] = {0}; + if (sscanf(buf, "%15s %511s", method, target) != 2) { + const char *m = "Bad Request"; + http_send(fd, "400 Bad Request", "text/plain", NULL, m, strlen(m)); + close(fd); + return; + } + char path[512]; + snprintf(path, sizeof path, "%s", target); + char *q = strchr(path, '?'); + if (q) *q = 0; + + RemoteConfig cfg; + pthread_mutex_lock(&app->cfg_mu); + cfg = app->cfg; + pthread_mutex_unlock(&app->cfg_mu); + + if (strcmp(method, "GET") == 0 && (strcmp(path, "/") == 0 || strcmp(path, "/index.html") == 0)) { + serve_static(fd, app->web_dir, "index.html", "text/html; charset=utf-8"); + close(fd); + return; + } + if (strcmp(method, "GET") == 0 && strcmp(path, "/manifest.json") == 0) { + serve_static(fd, app->web_dir, "manifest.json", "application/manifest+json; charset=utf-8"); + close(fd); + return; + } + if (strcmp(method, "GET") == 0 && strcmp(path, "/icon.svg") == 0) { + serve_static(fd, app->web_dir, "icon.svg", "image/svg+xml"); + close(fd); + return; + } + if (strcmp(method, "GET") == 0 && strcmp(path, "/api/info") == 0) { + char js[128]; + snprintf(js, sizeof js, "{\"name\":\"Chandra\",\"auth_required\":%s,\"version\":1}", + cfg.auth_mode == REMOTE_AUTH_NONE ? "false" : "true"); + http_send(fd, "200 OK", "application/json", NULL, js, strlen(js)); + close(fd); + return; + } + if (strcmp(method, "POST") == 0 && strcmp(path, "/api/login") == 0) { + char cl_str[32] = {0}; + long cl = 0; + if (find_header(buf, "Content-Length", cl_str, sizeof cl_str)) { + cl = strtol(cl_str, NULL, 10); + } + if (cl < 0 || cl > 4096) { + const char *m = "{\"ok\":false}"; + http_send(fd, "400 Bad Request", "application/json", NULL, m, strlen(m)); + close(fd); + return; + } + char post[4097]; + size_t copy = body_have > (size_t)cl ? (size_t)cl : body_have; + memcpy(post, body, copy); + while (copy < (size_t)cl) { + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + if (poll(&pfd, 1, 3000) <= 0) break; + ssize_t r = recv(fd, post + copy, (size_t)cl - copy, 0); + if (r <= 0) break; + copy += (size_t)r; + } + post[copy] = 0; + + if (cfg.auth_mode == REMOTE_AUTH_NONE) { + const char *ok = "{\"ok\":true,\"token\":\"\"}"; + http_send(fd, "200 OK", "application/json", NULL, ok, strlen(ok)); + close(fd); + return; + } + char pass[128] = {0}; + if (!json_get_str(post, "password", pass, sizeof pass) || + !remote_ct_equal(app->hmac_key, pass, cfg.password)) { + const char *err = "{\"ok\":false,\"error\":\"Invalid password\"}"; + http_send(fd, "401 Unauthorized", "application/json", NULL, err, strlen(err)); + close(fd); + return; + } + char tok[160], ckhdr[256], ok[256]; + web_token_sign(app->hmac_key, (uint64_t)time(NULL), tok, sizeof tok); + snprintf(ckhdr, sizeof ckhdr, "Set-Cookie: chandra_remote=%s; HttpOnly; SameSite=Lax; Path=/\r\n", tok); + snprintf(ok, sizeof ok, "{\"ok\":true,\"token\":\"%s\"}", tok); + http_send(fd, "200 OK", "application/json", ckhdr, ok, strlen(ok)); + close(fd); + return; + } + if (strcmp(method, "GET") == 0 && strcmp(path, "/ws") == 0) { + if (cfg.auth_mode != REMOTE_AUTH_NONE) { + char tok[160] = {0}, cookie[1024] = {0}; + int ok = extract_query_token(target, tok, sizeof tok); + if (!ok && find_header(buf, "Cookie", cookie, sizeof cookie)) { + ok = extract_cookie_token(cookie, tok, sizeof tok); + } + if (!ok || !web_token_verify(app->hmac_key, tok, (uint64_t)time(NULL))) { + const char *m = "Unauthorized"; + http_send(fd, "401 Unauthorized", "text/plain", NULL, m, strlen(m)); + close(fd); + return; + } + } + char upg[64] = {0}, wskey[128] = {0}, accept[64] = {0}; + if (!find_header(buf, "Upgrade", upg, sizeof upg) || strcasecmp(upg, "websocket") != 0 || + !find_header(buf, "Sec-WebSocket-Key", wskey, sizeof wskey) || + ws_compute_accept(wskey, accept, sizeof accept) < 0) { + const char *m = "Bad WebSocket Request"; + http_send(fd, "400 Bad Request", "text/plain", NULL, m, strlen(m)); + close(fd); + return; + } + char resp[256]; + int n = snprintf(resp, sizeof resp, + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: %s\r\n\r\n", + accept); + if (n > 0 && write_all_fd(fd, resp, (size_t)n) == 0) { + ws_loop(app, fd); + } + close(fd); + return; + } + + const char *m = "Not Found"; + http_send(fd, "404 Not Found", "text/plain", NULL, m, strlen(m)); + close(fd); +} diff --git a/remote/web/icon.svg b/remote/web/icon.svg new file mode 100644 index 0000000..293466e --- /dev/null +++ b/remote/web/icon.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/remote/web/index.html b/remote/web/index.html new file mode 100644 index 0000000..1e1619a --- /dev/null +++ b/remote/web/index.html @@ -0,0 +1,669 @@ + + + + + + + + + + +Chandra Remote + + + +
+ +
+
+ +
+
+ + + + +
+
+
+ + + +
+
+ Bright --% + +
+
+ + + +
+
+ + + +
+
+ Quality + + + +
+
540x1170 · Connecting…
+
+
+ +
+ + + + + + + + + + + +
+ + +
+
+

Chandra Remote

+

Enter your remote desktop password

+ + +
+
+
+ + + + diff --git a/remote/web/manifest.json b/remote/web/manifest.json new file mode 100644 index 0000000..4d76c0a --- /dev/null +++ b/remote/web/manifest.json @@ -0,0 +1,17 @@ +{ + "name": "Chandra Remote", + "short_name": "Chandra", + "start_url": "/", + "display": "standalone", + "orientation": "any", + "background_color": "#0b1020", + "theme_color": "#0b1020", + "icons": [ + { + "src": "/icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] +} diff --git a/session/chandra-ctl b/session/chandra-ctl index bee1315..2206ede 100755 --- a/session/chandra-ctl +++ b/session/chandra-ctl @@ -13,6 +13,9 @@ chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status) chandra-ctl screen [ARG] turn display off/on (on, off, toggle, status) chandra-ctl brightness [ARG] get/set backlight brightness percent (5..100, status) + chandra-ctl osk [ARG] enable/disable/query on-screen keyboard (on, off, toggle, status) + chandra-ctl status report display size, rotation, screen power, brightness, pointer, OSK + chandra-ctl refresh schedule a full frame redraw chandra-ctl settings [TAB] open Settings popup tab (session, desktop, panel, power, shortcuts, apps) chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo"); MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md) @@ -29,7 +32,7 @@ import os import socket import sys -USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | settings [TAB] | auth-demo [MODE] | auth-status | help}" +USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | osk [ARG] | status | refresh | settings [TAB] | auth-demo [MODE] | auth-status | help}" def runtime_dir(): diff --git a/session/chandra-session b/session/chandra-session index d2bee79..6be4c67 100755 --- a/session/chandra-session +++ b/session/chandra-session @@ -247,5 +247,13 @@ if [ "$backend" = --drm ] && [ "${CHANDRA_AUTO_ROTATE:-1}" != "0" ] && /usr/local/bin/chandra-auto-rotate --parent-pid "$$" >>"$log" 2>&1 & fi +remote_cfg="${XDG_CONFIG_HOME:-$HOME/.config}/chandra/remote.conf" +if [ "${CHANDRA_REMOTE:-auto}" != "0" ] && [ -x /usr/local/bin/chandra-remote ]; then + if [ "${CHANDRA_REMOTE:-auto}" = "1" ] || grep -Eq '^[[:space:]]*enabled[[:space:]]*=[[:space:]]*1' "$remote_cfg" 2>/dev/null; then + WAYLAND_DISPLAY="$(basename "$sock")" \ + /usr/local/bin/chandra-remote --parent-pid "$$" >>"$log" 2>&1 & + fi +fi + exec "$@" $backend --socket "$sock" \ --theme "$share/config/themes/moon-night.json" >>"$log" 2>&1 diff --git a/session/install.py b/session/install.py index 3b14c65..4bab7a9 100755 --- a/session/install.py +++ b/session/install.py @@ -35,6 +35,8 @@ Installs: /usr/local/lib/chandra/chandra-camera-ui Native GTK3/Cairo Camera UI binary /usr/share/applications/chandra-camera.desktop Camera app desktop entry /usr/share/icons/hicolor/scalable/apps/chandra-camera.svg Camera app icon + /usr/local/bin/chandra-remote Tailscale-first VNC & Mobile Web UI remote daemon + /usr/local/share/chandra/remote/ Remote Web UI / PWA assets /usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's aren't installed /usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime @@ -75,6 +77,7 @@ targets = [ "/usr/local/lib/chandra/chandra-camera-ui", "/usr/share/applications/chandra-camera.desktop", "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", + "/usr/local/bin/chandra-remote", "/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraLight.colors", "/usr/share/wayland-sessions/chandra.desktop", @@ -199,6 +202,29 @@ os.replace(cam_ui_dst + ".new", cam_ui_dst) print("installed", cam_ui_dst) put(os.path.join(root, "camera/chandra-camera.desktop"), "/usr/share/applications/chandra-camera.desktop", 0o644) put(os.path.join(root, "camera/chandra-camera.svg"), "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", 0o644) +remote_srcs = [ + os.path.join(root, "remote", f) + for f in ("chandra-remote.c", "rfb.c", "web.c", "keysym.c", "auth.c") +] +remote_dst = "/usr/local/bin/chandra-remote" +remote_flags = subprocess.check_output( + ["pkg-config", "--cflags", "--libs", "libturbojpeg", "zlib", "libcrypto"], + text=True, +).split() +subprocess.check_call( + [cc, "-O2", "-Wall", "-Wextra", "-o", remote_dst + ".new"] + + remote_srcs + + remote_flags + + ["-lpthread"] +) +os.chmod(remote_dst + ".new", 0o755) +os.replace(remote_dst + ".new", remote_dst) +print("installed", remote_dst) +remote_web_dst = os.path.join(share, "remote") +os.makedirs(remote_web_dst, exist_ok=True) +os.chmod(remote_web_dst, 0o755) +for wf in ("index.html", "manifest.json", "icon.svg"): + put(os.path.join(root, "remote/web", wf), os.path.join(remote_web_dst, wf), 0o644) if shutil.which("gtk-update-icon-cache"): subprocess.run(["gtk-update-icon-cache", "-q", "-f", "/usr/share/icons/hicolor"], check=False) for f in ("ChandraDark.colors", "ChandraLight.colors"): diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index 13d733b..94bd1f4 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -177,6 +177,9 @@ fn changed_images(panel : @wt.Val) -> R { ///| extern "C" fn rs_frame_begin() = "rs_frame_begin" +///| +extern "C" fn rs_publish_frame() = "rs_publish_frame" + ///| extern "C" fn rs_damage(x : Int, y : Int, w : Int, h : Int) = "rs_damage" @@ -706,6 +709,7 @@ fn submit(v : @wt.Val) -> Unit { // Nothing on screen changed (a window off screen, say). last_drawn.val = 0 keep_prev(f) + rs_publish_frame() return } } @@ -816,6 +820,7 @@ fn submit(v : @wt.Val) -> Unit { rs_blit_surface(p.field("surface").to_uint(), a.x, a.y, a.w, a.h) |> ignore } keep_prev(f) + rs_publish_frame() } // ---------------------------------------------------------------- images diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index 43883bd..752e9e9 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -22,6 +22,7 @@ #include #include #include "moonbit.h" +#include "../../remote/chandra_fb_shm.h" #define NANOSVG_IMPLEMENTATION #define NANOSVGRAST_IMPLEMENTATION @@ -961,11 +962,16 @@ static Box box_fb(Box b) { #define EXPORT_SLOTS 3 static Box kms_damage; static Box slot_damage[EXPORT_SLOTS]; +static Box shm_slot_dmg[2]; +static Box shm_pub_dmg; /* The frame just drawn changed (x, y, w, h) of the framebuffer. */ void rs_damage(int32_t x, int32_t y, int32_t w, int32_t h) { box_add(&kms_damage, x, y, x + w, y + h); for (int i = 0; i < EXPORT_SLOTS; i++) box_add(&slot_damage[i], x, y, x + w, y + h); + box_add(&shm_slot_dmg[0], x, y, x + w, y + h); + box_add(&shm_slot_dmg[1], x, y, x + w, y + h); + box_add(&shm_pub_dmg, x, y, x + w, y + h); } /* RGBA8888 -> little-endian XRGB8888 (B, G, R, 255) for the rows and columns of `b`. */ @@ -1244,3 +1250,113 @@ void rs_snapshot_pixels(int32_t x, int32_t y, int32_t w, int32_t h, int32_t ow, } } } + +/* ---- live shared-memory framebuffer mirror (for chandra-remote) ---- */ + +static int shm_fd = -1; +static ChandraFbHeader *shm_hdr; +static int32_t shm_w, shm_h; +static int shm_init_tried; + +static void shm_ensure_open(void) { + if (shm_init_tried) return; + shm_init_tried = 1; + char path[512]; + const char *env = getenv("CHANDRA_FB_SHM"); + if (env && env[0]) { + snprintf(path, sizeof path, "%s", env); + } else { + const char *tc = getenv("CHANDRA_TEST_CONFIG"); + if (tc && tc[0]) return; + const char *rt = getenv("XDG_RUNTIME_DIR"); + if (!rt || !rt[0]) return; + char dir[512]; + snprintf(dir, sizeof dir, "%s/chandra", rt); + mkdir(dir, 0700); + snprintf(path, sizeof path, "%s/fb.shm", dir); + } + int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (fd < 0) return; + struct stat st; + size_t need = (size_t)CHANDRA_FB_TOTAL_BYTES; + if (fstat(fd, &st) < 0 || (size_t)st.st_size < need) { + if (ftruncate(fd, (off_t)need) < 0) { + close(fd); + return; + } + } + void *m = mmap(NULL, need, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (m == MAP_FAILED) { + close(fd); + return; + } + shm_fd = fd; + shm_hdr = (ChandraFbHeader *)m; + uint64_t saved_ping = 0; + if (shm_hdr->magic == CHANDRA_FB_MAGIC && shm_hdr->version == CHANDRA_FB_VERSION && + shm_hdr->slot_bytes == CHANDRA_FB_SLOT_BYTES) { + saved_ping = __atomic_load_n(&shm_hdr->consumer_ping_ms, __ATOMIC_ACQUIRE); + } else { + memset(shm_hdr, 0, sizeof *shm_hdr); + } + shm_hdr->magic = CHANDRA_FB_MAGIC; + shm_hdr->version = CHANDRA_FB_VERSION; + shm_hdr->slot_bytes = CHANDRA_FB_SLOT_BYTES; + shm_hdr->active_slot = 0; + shm_hdr->width = 0; + shm_hdr->height = 0; + shm_hdr->dmg_x0 = shm_hdr->dmg_y0 = shm_hdr->dmg_x1 = shm_hdr->dmg_y1 = 0; + shm_hdr->frame_ms = 0; + __atomic_store_n(&shm_hdr->consumer_ping_ms, saved_ping, __ATOMIC_RELEASE); + __atomic_store_n(&shm_hdr->seq, 0, __ATOMIC_RELEASE); +} + +void rs_publish_frame(void) { + if (!fb || fb_w <= 0 || fb_h <= 0) return; + if ((size_t)fb_w * (size_t)fb_h * 4 > CHANDRA_FB_SLOT_BYTES) return; + shm_ensure_open(); + if (!shm_hdr) return; + uint64_t now = rec_now_ms(); + uint64_t ping = __atomic_load_n(&shm_hdr->consumer_ping_ms, __ATOMIC_ACQUIRE); + uint64_t cur_seq = __atomic_load_n(&shm_hdr->seq, __ATOMIC_RELAXED); + if (cur_seq > 0 && (ping == 0 || now > ping + 5000)) return; + if (fb_w != shm_w || fb_h != shm_h || cur_seq == 0) { + shm_slot_dmg[0] = (Box){ 0, 0, fb_w, fb_h }; + shm_slot_dmg[1] = (Box){ 0, 0, fb_w, fb_h }; + shm_pub_dmg = (Box){ 0, 0, fb_w, fb_h }; + shm_w = fb_w; + shm_h = fb_h; + } + Box pb = box_fb(shm_pub_dmg); + if (pb.x0 >= pb.x1 || pb.y0 >= pb.y1) { + if (cur_seq == 0) pb = (Box){ 0, 0, fb_w, fb_h }; + else return; + } + uint32_t next = 1u - (__atomic_load_n(&shm_hdr->active_slot, __ATOMIC_RELAXED) & 1u); + uint8_t *dst = chandra_fb_slot_ptr(shm_hdr, next, shm_hdr->slot_bytes); + Box sb = box_fb(shm_slot_dmg[next]); + if (sb.x0 < sb.x1 && sb.y0 < sb.y1) { + if (sb.x0 == 0 && sb.x1 == fb_w) { + size_t off = (size_t)sb.y0 * (size_t)fb_w * 4; + size_t bytes = (size_t)(sb.y1 - sb.y0) * (size_t)fb_w * 4; + memcpy(dst + off, fb + off, bytes); + } else { + size_t span = (size_t)(sb.x1 - sb.x0) * 4; + for (int y = sb.y0; y < sb.y1; y++) { + size_t off = ((size_t)y * (size_t)fb_w + (size_t)sb.x0) * 4; + memcpy(dst + off, fb + off, span); + } + } + } + shm_slot_dmg[next] = (Box){ 0, 0, 0, 0 }; + shm_pub_dmg = (Box){ 0, 0, 0, 0 }; + shm_hdr->width = (uint32_t)fb_w; + shm_hdr->height = (uint32_t)fb_h; + shm_hdr->dmg_x0 = pb.x0; + shm_hdr->dmg_y0 = pb.y0; + shm_hdr->dmg_x1 = pb.x1; + shm_hdr->dmg_y1 = pb.y1; + shm_hdr->frame_ms = now; + __atomic_store_n(&shm_hdr->active_slot, next, __ATOMIC_RELEASE); + __atomic_store_n(&shm_hdr->seq, cur_seq + 1, __ATOMIC_RELEASE); +}