diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d2c988d..29dc6dc 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -16,7 +16,7 @@ Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, - **Patched suckless desktop**: - `st` with HarfBuzz font shaping (`hb.c`) supporting Fira Code programming ligatures, Nerd Font fallback, mouse/two-finger wheel scrollback, and `SIGUSR1` live `.Xresources` reload. - `dwm` with Pango/HarfBuzz multi-font bar (`drw.c`), EWMH/XEmbed system tray, touch-friendly `>= 68px` status bar, `Mod4 = Fn+Alt` + one-shot `Super_L` tap-latch, and `SIGUSR1` `.Xresources` reload. - - `dmenu` with Pango/HarfBuzz, dynamic full-screen-height item rows (`68px` touch rows), and mouse/touch click selection. + - `dmenu` with Pango/HarfBuzz, dynamic full-screen-height item rows (`68px` touch rows), and mouse/touch click selection, paired with `geminux-launcher` pinning the 11 GUI apps alongside `Bantam AI agent` and `Lynx Web Browser` in `st` (and wrapping `Terminal=true` `.desktop` entries in `st -e`). - **Zero-Rust notifications**: `dunst v1.12.2` compiled with `WAYLAND=0 DUNSTIFY=0` and custom pure-C PNG (`libpng` + Cairo) / JPEG (`libjpeg-turbo`) icon loader replacing `gdk-pixbuf` ([src/dunst-notify/](file:///home/lux/proj/geminux/src/dunst-notify/)), paired with a lightweight GDBus `notify-send` / `dunstify`. ## Custom UI toolkit and zero-poll C11 daemons @@ -24,7 +24,7 @@ Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, - **`libgemui.so`** ([src/libgemui/](file:///home/lux/proj/geminux/src/libgemui)): Double-buffered Cairo + Pango/HarfBuzz Xlib toolkit polling X11 events, `SIGUSR1` self-pipe for instant `.Xresources` reloads, dynamic timers, `MSG_NOSIGNAL`/drained Unix socket IPC (`gemui_unix_cmd`), and non-blocking extra FDs (such as V4L2 or `inotify`). - **11 landscape HiDPI applications** ([src/geminux-apps/](file:///home/lux/proj/geminux/src/geminux-apps)): `geminux-control`, `geminux-audio`, `geminux-datetime`, `geminux-net`, `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts`, `geminux-camera` (MT6797 Media Controller pipeline + 10-bit Bayer demosaic/AWB software ISP), `geminux-themes`, and `geminux-lock`. - **Zero-poll C11 daemons** ([src/geminux-daemons/](file:///home/lux/proj/geminux/src/geminux-daemons)): - - `geminux-powerd` — `epoll` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`), `KOBJECT_UEVENT`, `/run/geminux/powerd.sock`, and on-demand `timerfd`; resolves the active desktop user dynamically from UID `10000`. + - `geminux-powerd` — `epoll` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, keyboard/touch/pointer activity), `KOBJECT_UEVENT`, `/run/geminux/powerd.sock`, and `timerfd`; drives two-stage screensaver idle dim/lock/suspend timed from the last active user input and resolves the active desktop user dynamically from UID `10000`. - `geminux-statusd` — `epoll` over `signalfd` (`SIGUSR1`), `RTMGRP_LINK`/`RTMGRP_IPV4_IFADDR`, `KOBJECT_UEVENT`, `inotify`, and minute-aligned `timerfd`; updates root `WM_NAME` with zero child shell forks. - `geminux-touchd` — XInput 2.2 multi-touch gesture daemon (2-finger tap/hold right-click, 3-finger middle-click, 2-finger scroll). - `geminux-leds` — AW9120 back cover RGB controller driving `rgb:indicator-1..5` (default off when idle/full; `rgb:indicator-6` amber while charging; persistent manual override; `SIGPIPE`-safe socket server at `/run/geminux/leds.sock`). @@ -36,15 +36,16 @@ Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, To keep Alpine Edge `aarch64` userspace freely updatable while locking all hardware-tuned components: 1. Build-time host Docker containers use `postmarketos/v26.06` solely for `gcc-aarch64`, `binutils-aarch64`, and `mkbootimg-osm0sis`. All `$SYSROOT` trees and the target `$ROOTFS` use only pure **Alpine Edge** (`main`, `community`, `testing`) plus the RSA-4096 signed local `@geminux` repository (`/var/lib/geminux/apk-repo`). -2. [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) builds seven `.apk` packages via `apk mkpkg` and indexes them into `APKINDEX.tar.gz` via `apk mkndx`: +2. [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) builds eight `.apk` packages via `apk mkpkg` and indexes them into `APKINDEX.tar.gz` via `apk mkndx`: - `geminux-kernel-modules` - `geminux-xlibre` - `geminux-suckless` - `geminux-dunst` - `geminux-ui` - - `geminux-bantam` (`bantam` minimalist C++20 CLI AI agent built via [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh)) - - `geminux-config` -3. `/etc/apk/world` pins all seven with `name@geminux=version` and locks out Rust/Wayland/upstream overrides via `!` constraints from [scripts/rootfs-prune-packages.txt](file:///home/lux/proj/geminux/scripts/rootfs-prune-packages.txt). + - `geminux-bantam` (`bantam` minimalist C++20 CLI AI agent with `kilo-auto/free` default model, built via [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh)) + - `geminux-gsocket` (`gs-netcat` / `gsocket` NAT traversal toolkit built via [scripts/build-gsocket.sh](file:///home/lux/proj/geminux/scripts/build-gsocket.sh)) + - `geminux-config` (includes `/etc/htoprc`, `/etc/skel/.config/htop/htoprc`, `/etc/skel/.lynx.cfg`, `/etc/skel/.apexrc`) +3. `/etc/apk/world` pins all eight with `name@geminux=version` and locks out Rust/Wayland/upstream overrides via `!` constraints from [scripts/rootfs-prune-packages.txt](file:///home/lux/proj/geminux/scripts/rootfs-prune-packages.txt). 4. `/etc/apk/protected_paths.d/geminux.list` shields Geminux configuration directories across upgrades. ## Pure-Linux flasher and eMMC layout diff --git a/MANUAL.md b/MANUAL.md index 336c30f..0d49a91 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -17,7 +17,7 @@ In [src/dwm/config.h](file:///home/lux/proj/geminux/src/dwm/config.h), `MODKEY` | --- | --- | | `Mod4 + Return` | Launch `st` terminal (with Fira Code HarfBuzz ligatures) | | `Mod4 + Shift + Return` | Promote focused window to master (`zoom`) | -| `Mod4 + Space` / `Mod4 + p` | Launch `geminux-launcher` (`dmenu` with Nerd Font icons) | +| `Mod4 + Space` / `Mod4 + p` | Launch `geminux-launcher` (`dmenu` with Nerd Font icons, pinned GUI apps, `Bantam AI agent`, and `Lynx Web Browser` in `st`) | | `Mod4 + c` | Open `geminux-control` (backlight, volume, power profiles, LEDs, suspend) | | `Mod4 + d` | Open `geminux-dialer` | | `Mod4 + s` | Open `geminux-sms` | @@ -61,8 +61,8 @@ geminux-apply-theme TokyoNight - **Audio & date/time**: `geminux-audio` manages PipeWire sink/source routing, mute state, and per-stream volume via `wpctl`/`pactl`. `geminux-datetime` manages the system timezone (`geminux-tzctl`) and shows live Chrony NTP sync status. - **Connectivity**: `geminux-net` manages Wi-Fi (`nmcli`), 4G/CCCI state (`mmcli` + `/run/geminux/ccci.sock`), Bluetooth (`bluetoothctl` / `rfkill`), and SiI9024 external HDMI output (`xrandr`). - **Camera**: `geminux-camera` configures the MT6797 Media Controller pipeline (`ov5670`/`s5k4e6` -> `seninf` -> `camsv`), captures 10-bit Bayer (`SBGGR10`/`SGRBG10`) frames over V4L2 `mmap` with a pure-C demosaic + AWB software ISP, and writes native `libjpeg-turbo` stills to `~/Pictures/` and MJPEG-AVI clips to `~/Videos/`. -- **System control, LEDs & lock**: `geminux-control` adjusts display backlight, PipeWire audio volume, MT6797X power profile (`eco`, `balanced`, `performance`), and AW9120 LEDs (`/run/geminux/leds.sock`). `geminux-leds` drives the 5-LED RGB back strip (`rgb:indicator-1..5`, defaulting to off when idle or 100% charged) plus `rgb:indicator-6` (amber while charging), supports calibrated presets including `rgb 160 16 0` ("Amber Warn"), and preserves manual `off` / `rgb` overrides across battery uevents. `geminux-lock` secures the X session using `doas -n /usr/sbin/geminux-checkpw`, while `geminux-lock` / `geminux-powerd` resolve the desktop account dynamically from UID `10000` (`--username` or default `user`). -- **CLI developer tools**: `bantam` (`geminux-bantam`, minimalist C++20 OpenAI-compatible terminal AI agent; see [src/bantam/README.md](file:///home/lux/proj/geminux/src/bantam/README.md)) and a preconfigured `/etc/skel/.gitconfig` are preinstalled. +- **System control, LEDs & lock**: `geminux-control` adjusts display backlight, PipeWire audio volume, MT6797X power profile (`eco`, `balanced`, `performance`), and AW9120 LEDs (`/run/geminux/leds.sock`). `geminux-leds` drives the 5-LED RGB back strip (`rgb:indicator-1..5`, defaulting to off when idle or 100% charged) plus `rgb:indicator-6` (amber while charging), supports calibrated presets including `rgb 160 16 0` ("Amber Warn"), and preserves manual `off` / `rgb` overrides across battery uevents. `geminux-lock` secures the X session using `doas -n /usr/sbin/geminux-checkpw`, resolving the desktop account dynamically from UID `10000` (`--username` or default `user`). `geminux-powerd` implements an input-driven screensaver: on battery it dims then triggers `geminux-lock` + suspend, while on AC / `performance` it triggers `geminux-lock` + backlight blanking (waking back onto the lock screen on key, touch, pointer, or power-button activity), timed strictly from the last active user input. +- **CLI developer & network tools**: `bantam` (`geminux-bantam`, minimalist C++20 OpenAI-compatible terminal AI agent defaulting to `kilo-auto/free`; see [src/bantam/README.md](file:///home/lux/proj/geminux/src/bantam/README.md)), `lynx` (configured via `~/.lynx.cfg` with `http://frogfind.com` start page, UTF-8, vi keys, mouse support, and persistent sessions/cookies), `gsocket` (`gs-netcat` plus `gs-key`/`gs-enter`/`gs-deploy-cmd`), `dtach` (`dmux`), `ovault`, default `htop` layout (`/etc/htoprc` / `~/.config/htop/htoprc`), `/etc/skel/.apexrc` defaults (`EDITOR='nano -FEDSMAGic/max%_T2'`, `PAGER='less -RXF'`, `nn`, `pg`, `l`, `defalias`/`toalias`/`savealias`, `rw`/`ee`, `sshed`, `dl`, `gcm`/`gp`/`gpm`, `sloc`, and `doas`-aware `pkgadd`/`pkgdel`/`pkgsearch`/`sysup`/`sysclean`), and `/etc/skel/.gitconfig` are preinstalled. ## Maintaining Alpine Edge packages safely @@ -73,4 +73,4 @@ doas apk update doas apk upgrade ``` -Because custom Geminux components (`geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam`, `geminux-config`) are exact-version pinned (`name@geminux=version`) in `/etc/apk/world` and Rust/upstream overrides (`!rust`, `!cargo`, `!librsvg`, `!libglycin`, `!gdk-pixbuf`, `!xorg-server`, `!linux-edge`, etc.) are negated in `/etc/apk/world`, normal Alpine Edge upgrades update upstream libraries, CLI tools, NetworkManager, ModemManager, PipeWire, and Mesa without overwriting custom patched binaries or pulling Rust packages. +Because custom Geminux components (`geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam`, `geminux-gsocket`, `geminux-config`) are exact-version pinned (`name@geminux=version`) in `/etc/apk/world` and Rust/upstream overrides (`!rust`, `!cargo`, `!librsvg`, `!libglycin`, `!gdk-pixbuf`, `!xorg-server`, `!linux-edge`, etc.) are negated in `/etc/apk/world`, normal Alpine Edge upgrades update upstream libraries, CLI tools, NetworkManager, ModemManager, PipeWire, and Mesa without overwriting custom patched binaries or pulling Rust packages. diff --git a/POWER-OPTIMIZATION.md b/POWER-OPTIMIZATION.md index e4e5feb..1db7649 100644 --- a/POWER-OPTIMIZATION.md +++ b/POWER-OPTIMIZATION.md @@ -17,7 +17,7 @@ Configured in [kernel/configs/geminux-mt6797x.config](file:///home/lux/proj/gemi All background system services avoid wake-up timers and polling loops: -- **`geminux-powerd`**: Sleeps indefinitely in `epoll_wait()` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`), `KOBJECT_UEVENT` netlink (AC charger/HDMI hotplug), `/run/geminux/powerd.sock`, and an on-demand `timerfd`. +- **`geminux-powerd`**: Sleeps indefinitely in `epoll_wait()` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, keyboard/touch/pointer activity), `KOBJECT_UEVENT` netlink (AC charger/HDMI hotplug), `/run/geminux/powerd.sock`, and a lazy-rearming `timerfd`; implements two-stage screensaver dimming and auto-lock/blank or suspend strictly timed from the last active user input (`dim_timeout_s` / `suspend_timeout_s`). - **`geminux-statusd`**: Uses `signalfd` (`SIGUSR1`), `RTMGRP_LINK` netlink, `inotify`, and a minute-aligned `timerfd` so the DWM status bar wakes only on actual network/power/modem changes or minute boundaries with zero child shell forks. - **`geminux-touchd`**: Event-driven XInput 2.2 multi-touch gesture recognizer with zero polling loops. - **`geminux-ccci-daemon` & `geminux-modem-ctl`**: Event-driven `epoll_wait()` over `/dev/ccci_*`, AT port, and netlink; enter completely idle sleep when no modem activity is pending. @@ -27,11 +27,13 @@ All background system services avoid wake-up timers and polling loops: `geminux-power-ctl` (and `geminux-control`) switches between three profiles managed in [src/geminux-daemons/geminux-power-policy.c](file:///home/lux/proj/geminux/src/geminux-daemons/geminux-power-policy.c): -| Profile | Governor | A72 big cores (`cpu8..9`) | A53 max freq | Auto-suspend on battery | -| --- | --- | --- | --- | --- | -| `eco` | `schedutil` | Offline (`0`) | `1391 MHz` | `180 s` idle | -| `balanced` | `schedutil` | Online (`1`) | `1547 MHz` | `300 s` idle | -| `performance` | `schedutil` | Online (`1`) | `1846 MHz` | Disabled | +| Profile | Governor | A72 big cores (`cpu8..9`) | A53 max freq | Battery idle (dim -> lock+suspend) | AC idle (lock+blank screensaver) | +| --- | --- | --- | --- | --- | --- | +| `eco` | `schedutil` | Offline (`0`) | `1391 MHz` | `60 s` -> `180 s` | `180 s` | +| `balanced` | `schedutil` | Online (`1`) | `1547 MHz` | `120 s` -> `300 s` | `300 s` | +| `performance` | `schedutil` | Online (`1`) | `1846 MHz` | `180 s` (lock+blank, no suspend) | `600 s` | + +All idle thresholds above are measured from the last active keyboard, touchscreen, pointer, or lid-open event (`CLOCK_MONOTONIC`) and are not reset by periodic battery `power_supply` uevents. Closing the Gemini PDA clamshell (`SW_LID = 1`) suspends immediately to RAM (`mem`), unless inhibited by an active voice call (`inhibit add call`), an explicit inhibitor, or a connected external HDMI monitor (`SiI9024`). diff --git a/README.md b/README.md index 6bae6d7..4d44ec9 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # Geminux -Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built specifically for the Planet Computers Gemini PDA (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It runs a patched Linux `7.3.5-geminux` kernel, XLibre Xorg with Panfrost Glamor 3D acceleration, a custom Pango/HarfBuzz-enabled DWM/st/dmenu desktop with Fira Code ligatures and Noto fonts, zero-poll C11 system daemons, 11 landscape HiDPI applications (`libgemui.so`), the preinstalled `bantam` CLI AI agent (`geminux-bantam`), and a pure-Linux MediaTek flasher with account provisioning and optional LUKS2 full-disk encryption. +Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built specifically for the Planet Computers Gemini PDA (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It runs a patched Linux `7.3.5-geminux` kernel, XLibre Xorg with Panfrost Glamor 3D acceleration, a custom Pango/HarfBuzz-enabled DWM/st/dmenu desktop with Fira Code ligatures and Noto fonts, zero-poll C11 system daemons, 11 landscape HiDPI applications (`libgemui.so`), the preinstalled `bantam` CLI AI agent (`geminux-bantam`, `kilo-auto/free` default), `lynx`, `gsocket`, and a pure-Linux MediaTek flasher with account provisioning and optional LUKS2 full-disk encryption. ## Key design goals - Pure Alpine Edge userspace updatable via `apk update && apk upgrade` -- Pinned kernel, modules, XLibre, suckless desktop, custom UI, `bantam`, and device configs in local signed `@geminux` APK packages (`name@geminux=version`) +- Pinned kernel, modules, XLibre, suckless desktop, custom UI, `bantam`, `gsocket`, and device configs in local signed `@geminux` APK packages (`name@geminux=version`) - Zero Rust-dependent packages preinstalled (verified across installed ELF binaries and blocked via `!` pins in `/etc/apk/world`) - Full eMMC occupancy for Linux (`geminux-root`) without Android dual-boot sharing, while strictly preserving the MediaTek protected region (`LBA 0..0x6FFFF`) - Optional LUKS2 + `dm-crypt` full-disk encryption (`--encrypt`, `aes-xts-plain64` with ARMv8 AES-CE, Argon2id) with early-boot `simpledrm` + Gemini matrix keyboard unlock and automatic first-boot ext4 expansion, alongside offline desktop/`root` credential provisioning during flashing @@ -20,8 +20,8 @@ Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built specific | Display server | XLibre Xorg 25.x (`Glamor`, `modesetting`, `fbdev`, `libinput`) | [scripts/build-xlibre.sh](file:///home/lux/proj/geminux/scripts/build-xlibre.sh) | | Window manager & terminal | Patched `dwm` (Pango, systray, `.Xresources`, `Mod4`), `st` (HarfBuzz ligatures, wheel scrollback), full-height `dmenu` | [scripts/build-suckless.sh](file:///home/lux/proj/geminux/scripts/build-suckless.sh) | | Notifications | Pure-X11 zero-`gdk-pixbuf` `dunst v1.12.2` + custom GDBus `notify-send` / `dunstify` | [scripts/build-dunst.sh](file:///home/lux/proj/geminux/scripts/build-dunst.sh) | -| UI, daemons & CLI agent | `libgemui.so`, 11 landscape HiDPI apps, zero-poll C11 daemons, and `bantam` CLI AI agent | [scripts/build-geminux-ui.sh](file:///home/lux/proj/geminux/scripts/build-geminux-ui.sh), [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh) | -| Local APK repository | 7 signed `@geminux` `.apk` packages + `APKINDEX.tar.gz` | [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) | +| UI, daemons & CLI tools | `libgemui.so`, 11 landscape HiDPI apps, zero-poll C11 daemons, `bantam` CLI AI agent, `lynx`, `gsocket`, `.apexrc`, default `htoprc` | [scripts/build-geminux-ui.sh](file:///home/lux/proj/geminux/scripts/build-geminux-ui.sh), [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh), [scripts/build-gsocket.sh](file:///home/lux/proj/geminux/scripts/build-gsocket.sh) | +| Local APK repository | 8 signed `@geminux` `.apk` packages + `APKINDEX.tar.gz` | [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) | | Full build & checks | Full image assembly + offline verification suite | [rebuild-image.sh](file:///home/lux/proj/geminux/rebuild-image.sh), [scripts/check-rebuild.sh](file:///home/lux/proj/geminux/scripts/check-rebuild.sh) | ## Repository layout @@ -45,7 +45,7 @@ Live hardware bring-up on a physical Planet Computers Gemini PDA (x27 Wi-Fi + 4G ./scripts/check-rebuild.sh ``` -To rebuild all cross-compiled components from scratch (kernel, XLibre, suckless desktop, dunst, UI apps/daemons, signed `@geminux` APKs, and rootfs ext4): +To rebuild all cross-compiled components from scratch (kernel, XLibre, suckless desktop, dunst, UI apps/daemons, Bantam, gsocket, signed `@geminux` APKs, and rootfs ext4): ```sh ./rebuild-image.sh --rebuild-all --force-bootstrap diff --git a/overlay/rootfs/etc/htoprc b/overlay/rootfs/etc/htoprc new file mode 100644 index 0000000..99f55f2 --- /dev/null +++ b/overlay/rootfs/etc/htoprc @@ -0,0 +1,59 @@ +# Beware! This file is rewritten by htop when settings are changed in the interface. +# The parser is also very primitive, and not human-friendly. +htop_version=3.5.3-3.5.3 +config_reader_min_version=3 +fields=0 48 17 18 39 2 46 47 1 +hide_kernel_threads=1 +hide_userland_threads=1 +hide_running_in_container=0 +shadow_other_users=0 +show_thread_names=0 +show_program_path=1 +highlight_base_name=0 +highlight_deleted_exe=1 +shadow_distribution_path_prefix=0 +highlight_megabytes=1 +highlight_threads=1 +highlight_changes=0 +highlight_changes_delay_secs=5 +find_comm_in_cmdline=1 +strip_exe_from_cmdline=1 +show_merged_command=0 +header_margin=0 +screen_tabs=1 +detailed_cpu_time=0 +cpu_count_from_one=0 +show_cpu_smt_labels=0 +show_cpu_usage=1 +sticky_follow=1 +show_cpu_frequency=0 +show_cpu_temperature=0 +degree_fahrenheit=0 +show_cached_memory=1 +update_process_names=0 +account_guest_in_cpu_meter=0 +color_scheme=0 +enable_mouse=1 +delay=15 +hide_function_bar=1 +header_layout=two_50_50 +column_meters_0=AllCPUs4 +column_meter_modes_0=1 +column_meters_1=MemorySwap LoadAverage Uptime +column_meter_modes_1=1 2 2 +tree_view=1 +sort_key=111 +tree_sort_key=0 +sort_direction=-1 +tree_sort_direction=1 +tree_view_always_by_pid=1 +all_branches_collapsed=0 +screen:Main=PID USER PRIORITY NICE M_RESIDENT STATE PERCENT_CPU PERCENT_MEM Command +.sort_key=IO_RATE +.tree_sort_key=PID +.tree_view_always_by_pid=1 +.tree_view=1 +.sort_direction=-1 +.tree_sort_direction=1 +.all_branches_collapsed=0 +.stable_tree_view=0 diff --git a/overlay/rootfs/etc/profile.d/10-geminux-env.sh b/overlay/rootfs/etc/profile.d/10-geminux-env.sh index 85630ee..2c7f9c8 100644 --- a/overlay/rootfs/etc/profile.d/10-geminux-env.sh +++ b/overlay/rootfs/etc/profile.d/10-geminux-env.sh @@ -5,6 +5,13 @@ export LANGUAGE=en_US.UTF-8 export SHELL=/bin/bash export TERMINAL=st export EDITOR=nano +case ":${PATH:-}:" in + *":$HOME/.local/bin:"*) ;; + *) [ -n "${HOME:-}" ] && export PATH="${PATH:+$PATH:}$HOME/.local/bin" ;; +esac +if [ -n "${HOME:-}" ] && [ -r "$HOME/.lynx.cfg" ]; then + export LYNX_CFG="$HOME/.lynx.cfg" +fi export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" diff --git a/overlay/rootfs/etc/skel/.apexrc b/overlay/rootfs/etc/skel/.apexrc new file mode 100644 index 0000000..9ede05b --- /dev/null +++ b/overlay/rootfs/etc/skel/.apexrc @@ -0,0 +1,94 @@ +# Geminux default CLI aliases and helpers (adapted from https://luxferre.top/apex) +shopt -s expand_aliases + +export EDITOR='nano -FEDSMAGic/max%_T2' +export PAGER='less -RXF' + +# Core aliases +alias nn="$EDITOR" +alias pg="$PAGER" +alias reload-rc='. "$BASH_SOURCE"' +alias edit-rc='$EDITOR "$BASH_SOURCE" && . "$BASH_SOURCE"' +alias lastcmd='history | tail -q -n 2 | head -q -n 1 | sed "s/^[[:space:]]*[0-9]*[[:space:]]*//"' +alias defalias='___(){ __="$1";shift;alias $__="_$__(){ $*; };_$__";unset __; };___' +defalias toalias 'defalias "$1" "$(lastcmd)";alias "$1"' +defalias savealias "[ -n \"\$1\" ] && echo \"alias \$(alias \$1 | sed 's/^alias //')\" >> \"$BASH_SOURCE\"" +alias rw='rlwrap -R' +alias ee='rlwrap -R ed -p:' +defalias l 'ls -lahF --time-style=long-iso --color=always $* | less -RXF' +defalias sshed 'f="$(mktemp)";scp $1 $f && $EDITOR $f && scp $f $1 && rm -f $f && unset f' +alias dl='curl -fsSLO' +alias gcm='git commit -a -m' +alias gp='git push origin' +alias gpm='git push origin master' +alias sloc="awk 'BEGIN{s=u=0}{u++}/^\s*#/{s++}/^\s*$/{s++}END{print(u-s)}'" + +if [ "$(id -u)" -eq 0 ]; then + alias pkgadd='apk add' + alias pkgdel='apk del' + alias sysup='apk upgrade' + alias sysclean='rm -rf /var/cache/apk/*' +else + alias pkgadd='doas apk add' + alias pkgdel='doas apk del' + alias sysup='doas apk upgrade' + alias sysclean='doas sh -c "rm -rf /var/cache/apk/*"' +fi +alias pkgsearch='apk search' + +# Load user Lynx configuration explicitly +alias lynx='lynx -cfg="$HOME/.lynx.cfg"' + +# OpenSSL-based vault helper +ovault() { + local pw="$4" + local op='-d' + [ "$1" = 'e' ] && op='-e' + if [ -z "$pw" ]; then + read -rs -p 'Enter vault password: ' pw + echo + fi + openssl aes-256-cbc $op -pbkdf2 -iter 100000 -pass pass:"$pw" -in "$2" -out "$3" +} + +# dmux, a simple dtach based terminal session manager, as a Bash function +dmux() { + local SDIR="$HOME/.dtsess" SPFILE="$SDIR/.list" sname + local -a MENU + mkdir -p "$SDIR" + touch "$SPFILE" + mapfile -t MENU < "$SPFILE" + if [[ -z "$(ls -1 "$SDIR")" ]]; then + for sname in "${MENU[@]}"; do + dtach -n "$SDIR/$sname" $SHELL + done + fi + PS3='Select a session: ' + while true; do + select sname in "${MENU[@]}" New Quit; do break; done + [[ "$sname" = 'Quit' ]] && printf '\033[0m' && break + [[ "$sname" = 'New' ]] && read -r -p 'New session name: ' sname + [[ -n "$sname" ]] && printf '\033[0m' && dtach -A "$SDIR/$sname" $SHELL + ls -1 "$SDIR" > "$SPFILE" + mapfile -t MENU < "$SPFILE" + done +} + +# Generate a pseudorandom key from machine alias +gs-key() { + echo "$*"|sha512sum -b|base64 -w0|tr -d -c a-z0-9|cut -c 1-22 +} + +# Enter the machine by its alias +gs-enter() { + gs-netcat -i -s "$(gs-key "$*")" +} + +# Print out GS deployment/undeployment/access commands +gs-deploy-cmd() { + local machinekey + machinekey="$(gs-key "$*")" + printf 'Deploy on target:\ncurl -fsSL https://gsocket.io/y | X=%s bash\n' "$machinekey" + printf 'Undeploy from target:\ncurl -fsSL https://gsocket.io/y | GS_UNDO=1 bash\n' + printf 'Access:\ngs-enter %s\n' "$*" +} diff --git a/overlay/rootfs/etc/skel/.bashrc b/overlay/rootfs/etc/skel/.bashrc index 2da820e..42f3282 100644 --- a/overlay/rootfs/etc/skel/.bashrc +++ b/overlay/rootfs/etc/skel/.bashrc @@ -1,6 +1,13 @@ # Geminux interactive shell configuration +if [ -r /etc/profile.d/10-geminux-env.sh ]; then + . /etc/profile.d/10-geminux-env.sh +fi export LANG="${LANG:-en_US.UTF-8}" export LC_ALL="${LC_ALL:-en_US.UTF-8}" PS1='[\u@\h \W]\$ ' alias ll='ls -la' alias power-audit='geminux-power-audit' +export ENV="$HOME/.bashrc" +if [ -n "${BASH_VERSION:-}" ] && [ -r "$HOME/.apexrc" ]; then + . "$HOME/.apexrc" +fi diff --git a/overlay/rootfs/etc/skel/.config/htop/htoprc b/overlay/rootfs/etc/skel/.config/htop/htoprc new file mode 100644 index 0000000..99f55f2 --- /dev/null +++ b/overlay/rootfs/etc/skel/.config/htop/htoprc @@ -0,0 +1,59 @@ +# Beware! This file is rewritten by htop when settings are changed in the interface. +# The parser is also very primitive, and not human-friendly. +htop_version=3.5.3-3.5.3 +config_reader_min_version=3 +fields=0 48 17 18 39 2 46 47 1 +hide_kernel_threads=1 +hide_userland_threads=1 +hide_running_in_container=0 +shadow_other_users=0 +show_thread_names=0 +show_program_path=1 +highlight_base_name=0 +highlight_deleted_exe=1 +shadow_distribution_path_prefix=0 +highlight_megabytes=1 +highlight_threads=1 +highlight_changes=0 +highlight_changes_delay_secs=5 +find_comm_in_cmdline=1 +strip_exe_from_cmdline=1 +show_merged_command=0 +header_margin=0 +screen_tabs=1 +detailed_cpu_time=0 +cpu_count_from_one=0 +show_cpu_smt_labels=0 +show_cpu_usage=1 +sticky_follow=1 +show_cpu_frequency=0 +show_cpu_temperature=0 +degree_fahrenheit=0 +show_cached_memory=1 +update_process_names=0 +account_guest_in_cpu_meter=0 +color_scheme=0 +enable_mouse=1 +delay=15 +hide_function_bar=1 +header_layout=two_50_50 +column_meters_0=AllCPUs4 +column_meter_modes_0=1 +column_meters_1=MemorySwap LoadAverage Uptime +column_meter_modes_1=1 2 2 +tree_view=1 +sort_key=111 +tree_sort_key=0 +sort_direction=-1 +tree_sort_direction=1 +tree_view_always_by_pid=1 +all_branches_collapsed=0 +screen:Main=PID USER PRIORITY NICE M_RESIDENT STATE PERCENT_CPU PERCENT_MEM Command +.sort_key=IO_RATE +.tree_sort_key=PID +.tree_view_always_by_pid=1 +.tree_view=1 +.sort_direction=-1 +.tree_sort_direction=1 +.all_branches_collapsed=0 +.stable_tree_view=0 diff --git a/overlay/rootfs/etc/skel/.lynx.cfg b/overlay/rootfs/etc/skel/.lynx.cfg new file mode 100644 index 0000000..75b0bc7 --- /dev/null +++ b/overlay/rootfs/etc/skel/.lynx.cfg @@ -0,0 +1,27 @@ +DEFAULT_USER_MODE:ADVANCED +STARTFILE:http://frogfind.com +VI_KEYS_ALWAYS_ON:TRUE +ASSUME_CHARSET:utf-8 +PREFERRED_CHARSET:utf-8 +ASSUME_LOCAL_CHARSET:utf-8 +CHARACTER_SET:utf-8 +REUSE_TEMPFILES:TRUE +AUTO_SESSION:TRUE +SESSION_FILE:~/.lynx_session +USE_MOUSE:TRUE +ACCEPT_ALL_COOKIES:TRUE +PERSISTENT_COOKIES:TRUE +SYSTEM_EDITOR:nano -FEDSMAGic/max%_T2 +TAGSOUP:TRUE +ENABLE_LYNXRC:USERAGENT:ON +ENABLE_LYNXRC:SEND_USERAGENT:ON +DEFAULT_COLORS:OFF +COLOR_STYLE: +COLOR:0:white:black +COLOR:1:cyan:black +COLOR:2:yellow:black +COLOR:3:green:black +COLOR:4:green:black +COLOR:5:brightgreen:black +COLOR:6:brightcyan:black +COLOR:7:black:cyan diff --git a/overlay/rootfs/usr/bin/geminux-launcher b/overlay/rootfs/usr/bin/geminux-launcher index baabf33..e96fee1 100755 --- a/overlay/rootfs/usr/bin/geminux-launcher +++ b/overlay/rootfs/usr/bin/geminux-launcher @@ -20,6 +20,8 @@ fi LAUNCHER_LIST="  Terminal|st +󰚩 Bantam AI agent|st -t 'Bantam AI agent' -e /bin/bash -lc 'exec bantam' +󰖟 Lynx Web Browser|st -e sh -c 'exec lynx -cfg="$HOME/.lynx.cfg"'  Dialer|geminux-dialer 󰍩 SMS Messages|geminux-sms  Contacts|geminux-contacts @@ -69,7 +71,11 @@ case "$choice" in if [ "$n" = "$app_name" ]; then ex="$(awk -F= '/^Exec=/{print $2; exit}' "$df" | sed 's/ %[fFuUdDnNickvm]//g')" if [ -n "$ex" ]; then - setsid sh -c "$ex" >/dev/null 2>&1 /dev/null; then + setsid st -e /bin/sh -c "$ex" >/dev/null 2>&1 /dev/null 2>&1 /dev/null 2>&1 || { echo >&2 "${GS_NETCAT_BIN} not found. Check PATH=?"; exit 1; } +command -v rsync >/dev/null 2>&1 || { echo >&2 "rsync not found. Try 'apt-get install rsync' or check PATH=?"; exit 1; } + +usage() +{ + echo "blitz [-k file] [-s password] [-l] [FILES ...] + -l Server Mode. + -s Secret (e.g. password). + -k Read Secret from file. + -f Read list of file names from FILE [or - for stdin] + -o RSOPT=val Options passed to rsync. + + Example: + $ blitz -s MySecret -l # Server + $ blitz -s MySecret *.dat # Client + +...limiting transfer rate to 10kB/sec + $ blitz -s MySecret -o 'RSOPT=--bwlimit=10 -v' /etc/*.conf *.dat + +...reading the file list from standard-in + $ cd /etc + $ find . -name '*.mp3' | blitz -s MySecret -f - + +...limit the amount of path information by inserting a dot and slash + $ blitz -s MySecret ~/tools/./upx/mp3 + +See 'man gs-netcat' and 'man rsync' for more options." + exit 0 +} + +read_password() +{ + printf >&2 "Enter Secret (or press Enter to generate): " + read -r password + if [[ -z "${password}" ]]; then + password=$(${GS_NETCAT_BIN} -g) + fi + echo "${password}" | tr -d "[:space:]" +} + +# remove -o from parameter list. +# Remove -s/-k from parameter list +# Copy all other +OPTERR=0 +FL_NEED_PASSWORD=1 +# Check if -s or -k is already supplied in environment and dont ask again. +[[ "$GSOCKET_ARGS" =~ ^'-s' ]] && unset FL_NEED_PASSWORD +[[ "$GSOCKET_ARGS" =~ ' -s' ]] && unset FL_NEED_PASSWORD +[[ "$GSOCKET_ARGS" =~ ^'-k' ]] && unset FL_NEED_PASSWORD +[[ "$GSOCKET_ARGS" =~ ' -k' ]] && unset FL_NEED_PASSWORD +# Current options are options for gs-netcat followed by a list of files. We +# need to split off the gs-netcat options (all but -o/-s/-k) without the +# files. To do so we need to know which gs-netcat options takes an argument +# at add those to getopts's optstring (such as -L ). +# These are caught by '*'. +# All single options (e.g. -w etc) are caught by '\?'. +# shellcheck disable=SC2220 # Invalid flags are not handled. Add a *) case. +while getopts ":hgls:k:o:L:f:" opt; do + case ${opt} in + o ) + RSYNC_ARGS+=${OPTARG//RSOPT=/} + RSYNC_ARGS+=" " + ;; + s ) + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-s" # Add to end of array + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="$OPTARG" # Add to end of array + unset FL_NEED_PASSWORD + ;; + k ) + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-k" # Add to end of array + KFILE=$(cd "$(dirname "$OPTARG")" && pwd)/$(basename "$OPTARG") + [[ -f "${KFILE}" ]] || { echo >&2 "File not found: ${KFILE}"; exit 255; } + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="${KFILE}" # Add to end of array + unset FL_NEED_PASSWORD + ;; + g ) + "${GS_NETCAT_BIN}" -g + exit + ;; + h ) + usage + ;; + f ) + RSYNC_ARGS+="--files-from=${OPTARG} . " + IS_FILES_FROM=1 + ;; + l ) + IS_SERVER=1 + ARGS_NEW[${#ARGS_NEW[@]}]="-l" # Add to end of array + ;; + \? ) + # UNKNOWN option. Handle before '*' (e.g. -l) + ARGS_NEW[${#ARGS_NEW[@]}]="-${OPTARG}" # Add to end of array + ;; + * ) + # Other (known opts from opstring) w parameters (e.g. -L ) + ARGS_NEW[${#ARGS_NEW[@]}]="-${opt}" # Add to end of array + ARGS_NEW[${#ARGS_NEW[@]}]="${OPTARG}" # Add to end of array + ;; + esac +done + +if [[ -z ${IS_SERVER} ]]; then + # CLIENT + shift $((OPTIND -1)) # list of files... + # echo "Remaining (files): $*" + [[ -z $* ]] && [[ -z $IS_FILES_FROM ]] && { echo >&2 "ERROR: No files specified."; usage; } + [[ -n $* ]] && [[ -n $IS_FILES_FROM ]] && { echo >&2 "ERROR: Either -f FILE or FILES, but not both."; usage; } +fi + +# Prepare existing GSOCKET_ARGS to take more arguments if there are any +[[ -n "$GSOCKET_ARGS" ]] && GSOCKET_ARGS+=" " +# Must read here unless -s/-k was used +if [[ -n "$FL_NEED_PASSWORD" ]]; then + password=$(read_password) + echo "=Secret :\"${password}\"" + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-s" # Add to end of array + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="$password" # Add to end of array +fi +echo "=Encryption : SRP-AES-256-CBC-SHA-End2End (Prime: 4096 bits)" +ENV_ARGS="${GSOCKET_ARGS}${GSNC_ENV_ARGS[*]}" + +# echo $OPTIND +# echo args-new : ${ARGS_NEW[@]} +# echo gsnc-env-args : \'${GSNC_ENV_ARGS[@]}\' +# echo rsync-args : ${RSYNC_ARGS} + +if [[ -n ${IS_SERVER} ]]; then + # SERVER + ENV_ARGS="${GSOCKET_ARGS}${GSNC_ENV_ARGS[*]}" + GSOCKET_NO_GREETINGS="1" GSOCKET_ARGS="${ENV_ARGS}" exec "${GS_NETCAT_BIN}" "${ARGS_NEW[@]}" -e "rsync ${RSYNC_SERVER_DEFAULTS} ${RSYNC_ARGS} ." +else + # CLIENT + ARGS=" -q" + # ARGS="" + [[ -n ${ARGS_NEW[*]} ]] && ARGS+=" ${ARGS_NEW[*]}" + # shellcheck disable=SC2086 # Double quote to prevent globbing and word splitting. ${RSYNC_ARGS} -> We want word splitting for multiple arugments. + GSOCKET_NO_GREETINGS="1" GSOCKET_ARGS="${ENV_ARGS}" exec rsync ${RSYNC_CLIENT_DEFAULTS} -e "${GS_NETCAT_BIN}${ARGS} --" ${RSYNC_ARGS} "${@}" 127.1:. +fi + diff --git a/prebuilt/gsocket/usr/local/bin/gs-mount b/prebuilt/gsocket/usr/local/bin/gs-mount new file mode 100755 index 0000000..78d653f --- /dev/null +++ b/prebuilt/gsocket/usr/local/bin/gs-mount @@ -0,0 +1,53 @@ +#! /usr/bin/env bash + +# A wrapper script to do this (essentially): +# $ gs-netcat -s MySecret -l -e /usr/lib/sftp-server # Host +# +# $ export GSOCKET_ARGS="-s MySecret" # Workstation +# $ sshfs -o ServerAliveInterval=30,reconnect,attr_timeout=60,auto_cache,compression=yes,default_permissions -o ssh_command="gs-netcat --" -o idmap=user,uid="${UID}",gid="$(id -g)" x@127.1:. ~/gs-fs + + +# Try to use the gs-netcat that's in the same directory as this executable. +BASEDIR="$(cd "$(dirname "${0}")" || exit; pwd)" +# shellcheck disable=SC1090 # Can't follow non-constant source. Use a directive to specify location. +# shellcheck disable=SC1091 # Not following: /etc/gsocket.conf was not specified as input (see shellcheck -x) +source "${BASEDIR}/gs_funcs" 2>/dev/null || source "${BASEDIR}/../share/gsocket/gs_funcs" 2>/dev/null || { { source /etc/gsocket.conf 2>/dev/null || source "${BASEDIR}/../etc/gsocket.conf" 2>/dev/null || { echo >&2 "gsocket: gsocket.conf not found."; exit 3; } } && { source "${GS_PREFIX}/share/gsocket/gs_funcs" 2>/dev/null; } } || { echo >&2 "gsocket: gs_funcs not found"; exit 3; } + +my_usage() +{ + echo "${BIN_NAME} [-k file] [-s password] [-l] [mount point]" + usage "${BIN_NAME}" + exit 0 +} + +gs_init +do_getopt "$@" +shift $((OPTIND -1)) # Mount Point +env_arg_init + +if [[ -z ${IS_SERVER} ]]; then + # CLIENT + SSHFS_OPT="ServerAliveInterval=30,reconnect,attr_timeout=60,auto_cache,compression=yes,default_permissions,idmap=user,uid=${UID},gid=$(id -g)" + # echo "Remaining (files): $*" + [[ -z "${1}" ]] && { echo >&2 "ERROR: No directory (mount point) specified."; my_usage; } + command -v sshfs >/dev/null 2>&1 || { echo >&2 "sshfs not found. Try 'apt-get install sshfs' or check PATH=?"; exit 1; } + # FUSE_OPT=",cache=yes,kernel_cache" + FUSE_OPT="" + if [[ "$OSTYPE" == "darwin"* ]]; then + # Setting 'noapplexattr' prevents 'finder' from copying. + FUSE_OPT+=",async,local,iosize=65536,noappledouble,volname=THC-"$(basename "${1}") + fi +fi + +if [[ -n ${IS_SERVER} ]]; then + # SERVER + sftp_server_start +else + # CLIENT + ARGS=" -q" + [[ -n ${ARGS_NEW[*]} ]] && ARGS=" ${ARGS_NEW[*]}" + + GSOCKET_NO_GREETINGS="1" GSOCKET_ARGS="${ENV_ARGS}" sshfs -o "${SSHFS_OPT}${FUSE_OPT}" -o ssh_command="${GS_NETCAT_BIN}${ARGS} --" x@127.1:. "${1}" || exit 1 + echo "Successfully mounted on ${1}." + command -v fusermount >/dev/null 2>&1 && echo "To unmount use: fusermount -zu ${1}" +fi diff --git a/prebuilt/gsocket/usr/local/bin/gs-netcat b/prebuilt/gsocket/usr/local/bin/gs-netcat new file mode 100755 index 0000000..0e73321 Binary files /dev/null and b/prebuilt/gsocket/usr/local/bin/gs-netcat differ diff --git a/prebuilt/gsocket/usr/local/bin/gs-sftp b/prebuilt/gsocket/usr/local/bin/gs-sftp new file mode 100755 index 0000000..a1a3d40 --- /dev/null +++ b/prebuilt/gsocket/usr/local/bin/gs-sftp @@ -0,0 +1,38 @@ +#! /usr/bin/env bash + +# A wrapper script to do this (essentially): +# $ gs-netcat -s MySecret -l -e /usr/lib/sftp-server # Host +# +# $ export GSOCKET_ARGS="-s MySecret" # Workstation +# $ sftp -D gs-netcat # Workstation + +# Try to use the gs-netcat that's in the same directory as this executable. +BASEDIR="$(cd "$(dirname "${0}")" || exit; pwd)" +# shellcheck disable=SC1090 # Can't follow non-constant source. Use a directive to specify location. +# shellcheck disable=SC1091 # Not following: /etc/gsocket.conf was not specified as input (see shellcheck -x) +source "${BASEDIR}/gs_funcs" 2>/dev/null || source "${BASEDIR}/../share/gsocket/gs_funcs" 2>/dev/null || { { source /etc/gsocket.conf 2>/dev/null || source "${BASEDIR}/../etc/gsocket.conf" 2>/dev/null || { echo >&2 "gsocket: gsocket.conf not found."; exit 3; } } && { source "${GS_PREFIX}/share/gsocket/gs_funcs" 2>/dev/null; } } || { echo >&2 "gsocket: gs_funcs not found"; exit 3; } + + +my_usage() +{ + echo "${BIN_NAME} [-k file] [-s password] [-l]" + usage "${BIN_NAME}" + exit 0 +} + +command -v sftp >/dev/null 2>&1 || { echo >&2 "sftp not found. Try 'apt-get install openssh' or check PATH=?"; exit 1; } +gs_init +do_getopt "$@" +shift $((OPTIND -1)) # Mount Point +env_arg_init + +if [[ -n ${IS_SERVER} ]]; then + # SERVER + sftp_server_start +else + # CLIENT + ARGS=" -q" + [[ -n ${ARGS_NEW[*]} ]] && ARGS=" ${ARGS_NEW[*]}" + # shellcheck disable=SC2086 # Double quote to prevent globbing and word splitting. ${RSYNC_ARGS} -> We want word splitting for multiple arugments. + GSOCKET_NO_GREETINGS="1" GSOCKET_ARGS="${ENV_ARGS}${ARGS}" exec sftp -D "${GS_NETCAT_BIN}" +fi diff --git a/prebuilt/gsocket/usr/local/bin/gs_funcs b/prebuilt/gsocket/usr/local/bin/gs_funcs new file mode 100755 index 0000000..c9b0e75 --- /dev/null +++ b/prebuilt/gsocket/usr/local/bin/gs_funcs @@ -0,0 +1,389 @@ +#! /usr/bin/env bash + + +[[ $(basename -- "$0") == "gs_funcs" ]] && { echo "Use gsocket, gs-netcat, gs-sftp, gs-mount or blitz instead."; exit 1; } + +# Find a sftp-server binary +find_binary() +{ + bin=$1 + command -v "${bin}" && { echo "${bin}"; return; } + shift 1 + for dir in "$@"; do + file="${dir}/${bin}" + if [[ -f "$file" ]]; then + echo "${file}" + return + fi + done + echo "" + return +} + +read_password() +{ + echo -n >&2 "${GS_PRFX}Enter Secret (or press Enter to generate): " + read -r password + if [[ -z "${password}" ]]; then + password=$(${GS_NETCAT_BIN} -g) + fi + echo "${password}" | tr -d "[:space:]" +} + +# haystack1 haystack2 needle +ucheck_fail() +{ + [[ "$1" =~ $3 ]] || { echo >&2 "Symbol $3 not found in sftp-server."; exit 255; } + [[ "$2" =~ $3 ]] || { echo >&2 "Symbol $3 not found (2)."; exit 255; } +} + +test_sftp() +{ + echo "${1}" | ./gs-sftp -k id_sec.txt -wq 2>&1 | grep -c "Permission denied" +} + +first_symbol() +{ + for func in "$@"; do + if [[ "$sym_sftp" =~ $func ]]; then + echo "$func " + return + fi + done + echo ">>>$*-NOT-FOUND<<< " +} + +uchroot_check_sym() +{ + command -v nm >/dev/null 2>&1 || { echo >&2 "chroot failed (nm not found. apt-get install binutils?). Try -U to disable."; exit 255; } + + # Extract symbols from .so and sftp-server binary + if [[ "$OSTYPE" == "darwin"* ]]; then + # on OSX remove the starting "_" from symboles + sym_sftp="$(nm -pu "${SFTP_SERVER_BIN}" | sed 's/^_//g')" + sym_uchr="$(nm -p "${UCHROOT_BIN}" | grep " T " | sed 's/^_//g')" + elif [[ "$OSTYPE" == "solaris"* ]]; then + sym_sftp="$(nm -Du "${SFTP_SERVER_BIN}")" + sym_uchr="$(nm -p "${UCHROOT_BIN}" | grep " T ")" + else + sym_sftp="$(nm -Du "${SFTP_SERVER_BIN}")" + sym_uchr="$(nm -D "${UCHROOT_BIN}" | grep " T ")" + fi + + [[ -n "$sym_uchr" ]] || { echo >&2 "chroot self-test failed (nm bad1). Try -U to disable."; exit 255; } + [[ -n "$sym_sftp" ]] || { echo >&2 "chroot self-test failed (nm bad2). Try -U to disable."; exit 255; } + funclist+=$(first_symbol lstat\$INODE64 __lxstat64 __lxstat lstat64 lstat) + funclist+=$(first_symbol stat\$INODE64 __xstat64 __xstat stat64 stat) + funclist+=$(first_symbol opendir\$INODE64 opendir64 opendir) + funclist+=$(first_symbol open64 open) + if [[ ! "$OSTYPE" == "solaris2.10"* ]]; then + # On solaris 10 the stock OpenSSH install does not use statvfs64 (older version) + funclist+=$(first_symbol statvfs64 statvfs) + fi + [[ "${funclist}" =~ "NOT-FOUND"* ]] && { echo >&2 "Missing symbol...${funclist}"; exit 255; } + + funclist+="chmod link mkdir rename rmdir symlink unlink" + # echo "funclist = $funclist" # DEBUG + for func in ${funclist}; do + ucheck_fail "${sym_sftp}" "${sym_uchr}" "${func}" + done +} + +failed() +{ + echo >&2 "ERROR: Self test failed: $1. Try -U to disable." + + exit 255 +} +# Verify that all symboles will get hijacked. exit on failure. +# linux osx solaris +# sftp -Du -pu -Du +# .so -D|T -p|T -p|T +uchroot_check() +{ + local VALID_CMD + local FAIL_CMD + + # skip nm-style symbol check on cygwin + # (sftp-server does not like nm on cygwin?!) + if [[ x"$OSTYPE" != "xcygwin"* ]]; then + # NOT cygwin + uchroot_check_sym + fi + + # Run a self test (sftp -D sftp-server) + command -v sftp >/dev/null 2>&1 || { failed "sftp not found"; } + mkdir -p "${ROOTDIR}/ok" + mkdir -p "${ROOTDIR}/denied" + # echo "ROOTDIR=${ROOTDIR}" # DEBUG + echo hello exist-allowed.txt >"${ROOTDIR}/ok/exist-allowed.txt" + echo hello exist-denied.txt >"${ROOTDIR}/denied/exist-denied.txt" + dd if=/dev/urandom bs=1k count=1 2>/dev/null >"${ROOTDIR}/ok/test1k.dat" + echo "\ +#! /bin/bash +cd \"${ROOTDIR}\"/ok +${PRELOAD} ${SFTP_SERVER_BIN} ${SFTP_ARGS[*]}" >"${ROOTDIR}/sftp-server.sh" + chmod 755 "${ROOTDIR}/sftp-server.sh" + + # Run GOOD commands that should work + VALID_CMD=" +mkdir dir1 +cd dir1 +cd .. +cd dir1 +cd ../ +ls ${ROOTDIR}/ok +ls ${ROOTDIR}/ok/exist-allowed.txt +put test1k.dat dir1 +mkdir ./dir2/ +" + [[ $(cd "${ROOTDIR}/ok"; echo "$VALID_CMD" | sftp -D "${ROOTDIR}/sftp-server.sh" 2>&1 | grep -c "Permission denied") -eq 0 ]] || { failed "valid cmd 0"; } + [[ -d "${ROOTDIR}/ok/dir1" ]] || { failed "valid-cmd 1"; } + [[ -d "${ROOTDIR}/ok/dir2" ]] || { failed "valid-cmd 2"; } + [[ -f "${ROOTDIR}/ok/dir1/test1k.dat" ]] || { failed "valid-cmd 3"; } + + + FAIL_CMD=" +rename exist-allowed.txt ../denied/0wned.txt +mkdir ./dir1/../../denied/0wned +cd dir1/../../denied +cd ./../denied +ls ${ROOTDIR} +cd ${ROOTDIR} +cd ${ROOTDIR}/denied +cd ${ROOTDIR}/ok/../denied +rm ./../denied/exist-denied.txt +put test1k.dat ../denied/0wned.dat +put test1k.dat ../denied/exist-denied.txt +rename exist-allowed.txt ../denied/0wned.txt +rename exist-allowed.txt /0wned.txt +" + [[ $(cd "${ROOTDIR}/ok"; echo "$FAIL_CMD" | sftp -D "${ROOTDIR}/sftp-server.sh" 2>&1 | grep -c "Permission denied") -eq 13 ]] || { failed "fail cmd (2)"; } + + FAIL_CMD=" +ls dir1/../../denied +ls ./../denied/exist-denied.txt" + [[ $(cd "${ROOTDIR}/ok"; echo "$FAIL_CMD" | sftp -D "${ROOTDIR}/sftp-server.sh" 2>&1 | grep -c "not found") -eq 2 ]] || { failed "fail cmd (3)"; } + rm -rf "${ROOTDIR}/ok" &>/dev/null + rm -rf "${ROOTDIR}/denied" &>/dev/null + rm -rf "${ROOTDIR}/sftp-server.sh" &>/dev/null +} + + +gs_find_so_single() +{ + [[ -e "${1}/${2}" ]] && { echo "$(cd "${1}" || exit; pwd)""/${2}"; } +} + +arrayContains() +{ + local e match="$1" + shift + for e; do [[ "$e" == "$match" ]] && return 0; done + return 1 +} + +# Search for the dynamic shared object file. +# 1. Try $basedir +# 2. Try ${basedir}/../lib +# 3. Try /usr/lib +# 4. Try /usr/local/lib +# Return absolute path to DSO. +gs_find_so() +{ + local DL=("${BASEDIR}") + # Debian packaging requires libs in /usr/lib/x86_64-linux-gnu :/ + if command -v dpkg-architecture &>/dev/null; then + DL+=("/usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)") + fi + + DL+=("${1}/lib") # This is either GS_PREFIX/lib or BASEDIR/../lib + arrayContains "/usr/lib" "${DL[@]}" || DL+=("/usr/lib") + arrayContains "/usr/local/lib" "${DL[@]}" || DL+=("/usr/local/lib") + + for dir in "${DL[@]}"; do + res=$(gs_find_so_single "${dir}" "${2}") + [[ -z "$res" ]] || { echo "$res"; return; } + done +} + +gs_init() +{ + GS_NETCAT_BIN="gs-netcat" + BIN="${BASEDIR}/${GS_NETCAT_BIN}" + [[ -f "${BIN}" ]] && GS_NETCAT_BIN="${BIN}" + # shellcheck disable=SC2034 # appears unused. Verify use (or export if used externally). + GS_SFTP_BIN="${BASEDIR}/gs-sftp" + EXE="" + if [[ "$OSTYPE" == "cygwin"* ]]; then + EXE=".exe" + fi + + # To find sftp-server and DSO's in PREFIX/lib + PREFIX="$GS_PREFIX" + [[ -z "$PREFIX" ]] && PREFIX="$(cd "$(dirname "${0}")/../" || exit; pwd)" + + # on OSX the dl-files are called .bundle (not .dylib) but it is generally + # accepted to call them .so. OSX keep those is /System/Library/gsocket + # but automake insists on ${PREFIX}/lib + UCHROOT_BIN=$(gs_find_so "$PREFIX" "gsocket_uchroot_dso.so.0${EXE}") + [[ -z "$UCHROOT_BIN" ]] && { echo >&2 "gsocket: gsocket_uchroot_dso.so.0${EXE} not found. Try 'apt install dpkg-dev'."; exit 5; } + # shellcheck disable=SC2034 # appears unused. Verify use (or export if used externally). + GS_SO_BIN=$(gs_find_so "$PREFIX" "gsocket_dso.so.0${EXE}") + [[ -z "$GS_SO_BIN" ]] && { echo >&2 "gsocket: gsocket_dso.so.0${EXE} not found."; exit 5; } + + # shellcheck disable=SC2034 # appears unused. Verify use (or export if used externally). + BIN_NAME="$(basename "${0}")" + + command -v "${GS_NETCAT_BIN}" >/dev/null 2>&1 || { echo >&2 "${GS_NETCAT_BIN} not found. Check PATH=?"; exit 1; } +} + +usage() +{ + echo " + -l Server Mode. + -R Server in read-only mode. + -s Secret (e.g. password). + -k Read Secret from file. + +Example: + $ ${1} -s MySecret -l # Server + $ ${1} -s MySecret # Client + +See 'gs-netcat -h' for more options." + +} + +do_getopt() +{ + OPTERR=0 + FL_NEED_PASSWORD=1 + IS_UCHROOT=1 + # Check if -s or -k is already supplied in environment and dont ask again. + [[ "$GSOCKET_ARGS" =~ ^'-s' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ' -s' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ^'-k' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ' -k' ]] && unset FL_NEED_PASSWORD + # shellcheck disable=SC2220 # Invalid flags are not handled. Add a *) case. + while getopts ":qhURgls:k:L:" opt; do + case ${opt} in + s ) + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-s" # Add to end of array + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="$OPTARG" # Add to end of array + unset FL_NEED_PASSWORD + ;; + k ) + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-k" # Add to end of array + KFILE=$(cd "$(dirname "$OPTARG")" && pwd)/$(basename "$OPTARG") + [[ -f "${KFILE}" ]] || { echo >&2 "File not found: ${KFILE}"; exit 255; } + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="${KFILE}" # Add to end of array + # KFILE=$(eval echo "$OPTARG") # Add to end of array + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]=$(eval echo "$OPTARG") # Add to end of array + unset FL_NEED_PASSWORD + ;; + g ) + "${GS_NETCAT_BIN}" -g + exit + ;; + h ) + my_usage + ;; + q ) + IS_QUIET=1 + ARGS_NEW[${#ARGS_NEW[@]}]="-q" + ;; + l ) + # shellcheck disable=SC2034 # appears unused. Verify use (or export if used externally). + IS_SERVER=1 + ARGS_NEW[${#ARGS_NEW[@]}]="-l" # Add to end of array + ;; + R ) + # shellcheck disable=SC2034 # appears unused. Verify use (or export if used externally). + IS_READONLY=1 + SFTP_ARGS[${#SFTP_ARGS[@]}]="-R" + ;; + U ) + unset IS_UCHROOT + ;; + \? ) + # UNKNOWN option. Handle before '*' (e.g. -l) + ARGS_NEW[${#ARGS_NEW[@]}]="-${OPTARG}" # Add to end of array + ;; + * ) + # Other (known opts from opstring) w parameters (e.g. -L ) + ARGS_NEW[${#ARGS_NEW[@]}]="-${opt}" # Add to end of array + ARGS_NEW[${#ARGS_NEW[@]}]="${OPTARG}" # Add to end of array + ;; + esac + done + # Solaris 10 problems: + # - stock sftp-server does not allow -p -> Acceptable risk + # - LD_PRELOAD does not seem to work. Does anyone still use solaris10? + if [[ "$OSTYPE" == "solaris2.10"* ]]; then + echo -e >&2 "\033[1;31mWARNING\033[0m: uchroot not (yet) supported on solaris 10." + unset IS_UCHROOT + fi +} + +env_arg_init() +{ + # Prepare existing GSOCKET_ARGS to take more arguments if there are any + [[ -n "$GSOCKET_ARGS" ]] && GSOCKET_ARGS+=" " + if [[ -n "$FL_NEED_PASSWORD" ]]; then + password=$(read_password) + # shellcheck disable=SC2034 # GSOCKET_SECRET appears unused => It's used in 'gs' + GSOCKET_SECRET="${password}" + echo "${GS_PRFX}=Secret : ${password}" + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-s" # Add to end of array + GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="$password" # Add to end of array + fi + # Have to output it here because gs-netcat might be started from withing + # sshfs or sftpd where stderr is no longer available to gs-netcat + [[ -n "$IS_QUIET" ]] || echo >&2 "${GS_PRFX}=Encryption : SRP-AES-256-CBC-SHA-End2End (Prime: 4096 bits)" + ENV_ARGS="${GSOCKET_ARGS}${GSNC_ENV_ARGS[*]}" +} + +sftp_server_start() +{ + # SERVER + if [[ "$OSTYPE" == "darwin"* ]]; then + # OSX does not allow LD_PRELOAD of binaries in /usr/. Copy to tmp... + ROOTDIR=$(mktemp -d -t thc-gs-sftp) + # FIXME: temp file only cleaned on reboot. Hmm... + cp /usr/libexec/sftp-server "${ROOTDIR}/sftp-server" &>/dev/null + SFTP_SERVER_BIN="${ROOTDIR}/sftp-server" + PRELOAD="DYLD_INSERT_LIBRARIES=${UCHROOT_BIN} DYLD_FORCE_FLAT_NAMESPACE=1" + else + if [[ -n "${IS_UCHROOT}" ]]; then + ROOTDIR=$(mktemp -d -t thc-gs-sftp-XXXXXXXXXXXXXXX) + fi + SFTP_SERVER_BIN=$(find_binary "sftp-server${EXE}" "${PREFIX}/lib" /opt/csw/libexec /usr/lib /usr/local/lib /usr/libexec /usr/libexec/openssh /usr/lib/ssh /usr/sbin) + PRELOAD="LD_PRELOAD=${UCHROOT_BIN}" + fi + [[ -z "${SFTP_SERVER_BIN}" ]] && { echo >&2 "sftp-server binary not found."; exit 1; } + + # SFTP_ARGS[${#SFTP_ARGS[@]}]="-l" + # SFTP_ARGS[${#SFTP_ARGS[@]}]="DEBUG3" # tail /var/log/auth.log | grep 'Refusing non-whitelisted' + + # Whitelist of commands sftp-server should allow (most are not needed + # by sftp but for sshfs) + # *** WARNING ***: If you add a string here you also must make sure that + # gsocket_uchroot_dso checks the command for uchroot-escape. + SFTP_ARGS[${#SFTP_ARGS[@]}]="-p" + SFTP_ARGS[${#SFTP_ARGS[@]}]="open,opendir,mkdir,remove,rmdir,symlink,hardlink,stat,posix-rename,statvfs,setstat,fsetstat,fstat,lstat,readdir,realpath,write,read,close" + + ENV_ARGS="${GSOCKET_ARGS}${GSNC_ENV_ARGS[*]}" + + if [[ -n "${IS_UCHROOT}" ]]; then + [[ -z "${ROOTDIR}" ]] && { failed "(mktemp)"; } + uchroot_check + # Try to delete temporary directory. OSX still has sftp-server bin in there and must be deleted + rmdir "${ROOTDIR}" &>/dev/null + else + echo -e >&2 "\033[1;31mWARNING\033[0m: uchroot disabled. Allowing access to *ALL* files on this host." + unset PRELOAD + fi + GSOCKET_NO_GREETINGS="1" GSOCKET_ARGS="${ENV_ARGS}" exec "${GS_NETCAT_BIN}" "${ARGS_NEW[@]}" -e "${PRELOAD} ${SFTP_SERVER_BIN} ${SFTP_ARGS[*]} 2>/dev/null" +} + + diff --git a/prebuilt/gsocket/usr/local/bin/gsocket b/prebuilt/gsocket/usr/local/bin/gsocket new file mode 100755 index 0000000..4561293 --- /dev/null +++ b/prebuilt/gsocket/usr/local/bin/gsocket @@ -0,0 +1,135 @@ +#! /usr/bin/env bash + +# Try to use the gs-netcat that's in the same directory as this executable. +BASEDIR="$(cd "$(dirname "${0}")" || exit; pwd)" +# shellcheck disable=SC1090 # Can't follow non-constant source. Use a directive to specify location. +# shellcheck disable=SC1091 # Not following: /etc/gsocket.conf was not specified as input (see shellcheck -x) +source "${BASEDIR}/gs_funcs" 2>/dev/null || source "${BASEDIR}/../share/gsocket/gs_funcs" 2>/dev/null || { { source /etc/gsocket.conf 2>/dev/null || source "${BASEDIR}/../etc/gsocket.conf" 2>/dev/null || { echo >&2 "gsocket: gsocket.conf not found."; exit 3; } } && { source "${GS_PREFIX}/share/gsocket/gs_funcs" 2>/dev/null; } } || { echo >&2 "gsocket: gs_funcs not found"; exit 3; } + +my_usage() +{ + echo "${BIN_NAME} [-k file] [-s password] + -s Secret (e.g. password). + -k Read Secret from file. + -p Range of listening ports to redirect [default=all] + -T Use TOR. + +Example: + $ ${BIN_NAME} -s MySecret /usr/bin/sshd -d # Server + $ ${BIN_NAME} -s MySecret ssh root@gsocket # Client + +See 'gs-netcat -h' for more options." + exit "$1" +} + +my_getopt() +{ + OPTERR=0 + # shellcheck disable=SC2034 # FL_NEED_PASSWORD appears unused. => used i env_arg_init + FL_NEED_PASSWORD=1 + # Check if -s or -k is already supplied in environment and dont ask again. + [[ "$GSOCKET_ARGS" =~ ^'-s' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ' -s' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ^'-k' ]] && unset FL_NEED_PASSWORD + [[ "$GSOCKET_ARGS" =~ ' -k' ]] && unset FL_NEED_PASSWORD + # shellcheck disable=SC2220 # Invalid flags are not handled. Add a *) case. + while getopts ":qhgTp:s:k:L:" opt; do + case ${opt} in + s ) + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-s" # Add to end of array + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="$OPTARG" # Add to end of array + GSOCKET_SECRET="$OPTARG" + unset FL_NEED_PASSWORD + ;; + k ) + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="-k" # Add to end of array + KFILE=$(cd "$(dirname "$OPTARG")" && pwd)/$(basename "$OPTARG") + [[ -f "${KFILE}" ]] || { echo >&2 "File not found: ${KFILE}"; exit 255; } + GSOCKET_SECRET=$(<"${KFILE}") + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]="${KFILE}" # Add to end of array + # KFILE=$(eval echo "$OPTARG") # Add to end of array + # GSNC_ENV_ARGS[${#GSNC_ENV_ARGS[@]}]=$(eval echo "$OPTARG") # Add to end of array + unset FL_NEED_PASSWORD + ;; + g ) + "${GS_NETCAT_BIN}" -g + exit + ;; + h ) + my_usage 0 + ;; + p ) + GS_HIJACK_PORTS="${OPTARG}" + ;; + T ) + [[ -z "${GSOCKET_SOCKS_IP}" ]] && GSOCKET_SOCKS_IP="127.0.0.1" + ;; + + q ) + # shellcheck disable=SC2034 # IS_QUIET appears unused. => Used in env_arg_init + IS_QUIET=1 + ARGS_NEW[${#ARGS_NEW[@]}]="-q" + ;; + \? ) + # UNKNOWN option. Handle before '*' (e.g. -l) + ARGS_NEW[${#ARGS_NEW[@]}]="-${OPTARG}" # Add to end of array + ;; + * ) + # Other (known opts from opstring) w parameters (e.g. -L ) + ARGS_NEW[${#ARGS_NEW[@]}]="-${opt}" # Add to end of array + ARGS_NEW[${#ARGS_NEW[@]}]="${OPTARG}" # Add to end of array + ;; + esac + done + + [[ -n "${GSOCKET_SECRET}" ]] && unset FL_NEED_PASSWORD +} + +# default values +GS_HIJACK_PORTS="1-65535" +# shellcheck disable=SC2034 # GS_RFX appears unused. => Used in gs_funcs +GS_PRFX="gsocket: " +gs_init +my_getopt "$@" +shift $((OPTIND -1)) + +[[ ${#@} -le 0 ]] && { echo >&2 "ERROR: No program specified"; my_usage 255; } + +command -v "$1" >/dev/null 2>&1 || { echo >&2 "gsocket: command not found: ${1}"; exit 1; } + +if [[ "$OSTYPE" == "darwin"* ]]; then + # OSX does not allow LD_PRELOAD of binaries in /usr/. Copy to tmp... + ROOTDIR=$(mktemp -d -t thc-gsXXXXXX) + PROGBIN_FULLPATH=$(which "$1") + + [[ -z "$PROGBIN_FULLPATH" ]] && { echo >&2 "gsocket: command not found: ${1}"; exit 1; } + # FIXME: temp file is only cleaned on reboot. Hmm... + cp "${PROGBIN_FULLPATH}" "${ROOTDIR}/" &>/dev/null + PROGBIN_NAME="$(basename "${1}")" # programm binary + PROGBIN="${ROOTDIR}/${PROGBIN_NAME}" + # System Integrity Protection makes dyld ignore + # DYLD_INSERT_LIBRARIES. + # There are two ways how MacOS determines if a binary is SIP protected: + # 1. The location of the binary (ls -alO /usr/bin/ssh) + # 2. If the binary contains 'entitlements' (regardless of its location on the fs). + # A hack around this is to remove the signature completed (which will also disable + # any entitlements). + IS_REMOVE_SIGN=1 + command -v csrutil >/dev/null && [[ ! "$(csrutil status)" =~ enabled ]] && { unset IS_REMOVE_SIGN; } + [[ -n $IS_REMOVE_SIGN ]] && command -v codesign >/dev/null && [[ -n "$(codesign -d --entitlements - "${PROGBIN}" 2>/dev/null)" ]] && { + codesign --remove-signature "${PROGBIN}"; + } +else + ROOTDIR="" + PROGBIN="${1}" +fi + +env_arg_init +shift 1 + +if [[ "$OSTYPE" == "darwin"* ]]; then + GS_NETCAT_BIN=${GS_NETCAT_BIN} GS_HIJACK_PORTS="${GS_HIJACK_PORTS}" GSOCKET_SOCKS_IP="${GSOCKET_SOCKS_IP}" GSOCKET_ARGS="${ENV_ARGS} ${ARGS_NEW[*]}" GSOCKET_SECRET="${GSOCKET_SECRET}" DYLD_INSERT_LIBRARIES=${GS_SO_BIN} DYLD_FORCE_FLAT_NAMESPACE=1 exec "${PROGBIN}" "$@" +else + GS_NETCAT_BIN=${GS_NETCAT_BIN} GS_HIJACK_PORTS="${GS_HIJACK_PORTS}" GSOCKET_SOCKS_IP="${GSOCKET_SOCKS_IP}" GSOCKET_ARGS="${ENV_ARGS} ${ARGS_NEW[*]}" GSOCKET_SECRET="${GSOCKET_SECRET}" LD_PRELOAD=${GS_SO_BIN} exec "${PROGBIN}" "$@" +fi + diff --git a/prebuilt/gsocket/usr/local/bin/gsocket_dso.so.0 b/prebuilt/gsocket/usr/local/bin/gsocket_dso.so.0 new file mode 100755 index 0000000..0163f08 Binary files /dev/null and b/prebuilt/gsocket/usr/local/bin/gsocket_dso.so.0 differ diff --git a/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0 b/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0 new file mode 100755 index 0000000..b82759a Binary files /dev/null and b/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0 differ diff --git a/rebuild-image.sh b/rebuild-image.sh index f3d7d7a..7502ff8 100755 --- a/rebuild-image.sh +++ b/rebuild-image.sh @@ -63,6 +63,10 @@ if [ "$REBUILD_ALL" -eq 1 ] || [ ! -x "$BASE_DIR/prebuilt/bantam/usr/bin/bantam" "$BASE_DIR/scripts/build-bantam.sh" fi +if [ "$REBUILD_ALL" -eq 1 ] || [ ! -x "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gs-netcat" ]; then + "$BASE_DIR/scripts/build-gsocket.sh" +fi + if [ "$SKIP_APKS" -eq 0 ]; then "$BASE_DIR/scripts/package-local-apks.sh" fi diff --git a/scripts/apply-geminux-overlay.sh b/scripts/apply-geminux-overlay.sh index 538ed31..5e1900a 100755 --- a/scripts/apply-geminux-overlay.sh +++ b/scripts/apply-geminux-overlay.sh @@ -58,12 +58,12 @@ if command -v apk >/dev/null 2>&1 && \ # Clear any older @geminux world pins and installed hashes so rebuilt local # packages with unchanged -r0 version strings always extract updated payloads. if [ -f "$TARGET_ROOTFS/etc/apk/world" ]; then - grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|config)(@|=|$)' \ + grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|config)(@|=|$)' \ "$TARGET_ROOTFS/etc/apk/world" > "$TARGET_ROOTFS/etc/apk/world.tmp" || true mv "$TARGET_ROOTFS/etc/apk/world.tmp" "$TARGET_ROOTFS/etc/apk/world" fi apk --root "$TARGET_ROOTFS" --arch aarch64 del --no-scripts --purge=yes \ - geminux-config geminux-bantam geminux-ui geminux-dunst geminux-suckless \ + geminux-config geminux-gsocket geminux-bantam geminux-ui geminux-dunst geminux-suckless \ geminux-xlibre geminux-kernel-modules 2>/dev/null || true apk --root "$TARGET_ROOTFS" --arch aarch64 add --no-scripts --clean-protected=no \ @@ -73,13 +73,14 @@ if command -v apk >/dev/null 2>&1 && \ "geminux-dunst@geminux=1.12.2-r0" \ "geminux-ui@geminux=${VER}-r0" \ "geminux-bantam@geminux=${VER}-r0" \ + "geminux-gsocket@geminux=1.4.43-r0" \ "geminux-config@geminux=${VER}-r0" else # Fallback direct copy when running on host without apk-tools if [ -d "$BASE_DIR/overlay/rootfs" ]; then cp -af "$BASE_DIR/overlay/rootfs/." "$TARGET_ROOTFS/" fi - for subdir in xlibre suckless dunst geminux bantam; do + for subdir in xlibre suckless dunst geminux bantam gsocket; do if [ -d "$BASE_DIR/prebuilt/$subdir" ]; then cp -af "$BASE_DIR/prebuilt/$subdir/." "$TARGET_ROOTFS/" fi @@ -195,8 +196,8 @@ if [ -f "$TARGET_ROOTFS/etc/passwd" ]; then "$TARGET_ROOTFS/etc/passwd" fi -mkdir -p "$TARGET_ROOTFS/root" -for f in .bashrc .profile .bash_profile .gitconfig; do +mkdir -p "$TARGET_ROOTFS/root" "$TARGET_ROOTFS/root/.config/htop" +for f in .bashrc .profile .bash_profile .gitconfig .apexrc .lynx.cfg .config/htop/htoprc; do if [ -f "$TARGET_ROOTFS/etc/skel/$f" ]; then cp -f "$TARGET_ROOTFS/etc/skel/$f" "$TARGET_ROOTFS/root/$f" fi diff --git a/scripts/bootstrap-rootfs-container.sh b/scripts/bootstrap-rootfs-container.sh index 574a220..f1de51d 100755 --- a/scripts/bootstrap-rootfs-container.sh +++ b/scripts/bootstrap-rootfs-container.sh @@ -43,7 +43,7 @@ apk add --no-cache python3 kmod openssl glib >/dev/null echo "[3/8] Installing the Geminux aarch64 package set..." PKGS="$(grep -v '^[[:space:]]*#' "$PKGS_FILE" | grep -v '^[[:space:]]*$' | tr '\n' ' ')" if [ -f "$ROOTFS/etc/apk/world" ]; then - grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|config)(@|=|$)' \ + grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|config)(@|=|$)' \ "$ROOTFS/etc/apk/world" > "$ROOTFS/etc/apk/world.tmp" || true mv "$ROOTFS/etc/apk/world.tmp" "$ROOTFS/etc/apk/world" fi diff --git a/scripts/build-bantam.sh b/scripts/build-bantam.sh index 7673bbc..beaa251 100755 --- a/scripts/build-bantam.sh +++ b/scripts/build-bantam.sh @@ -15,6 +15,8 @@ if [ -f "$BANTAM_SRC/bantam.hpp" ]; then [ -f "$f" ] && cp -f "$f" "$BASE_DIR/src/bantam/" done fi +sed -i 's|c\.model = "openrouter/free";|c.model = "kilo-auto/free";|' "$BASE_DIR/src/bantam/config.cpp" +sed -i 's|openrouter/free|kilo-auto/free|g' "$BASE_DIR/src/bantam/README.md" exec docker run --rm --network=host \ -e HOST_UID="$(id -u)" \ diff --git a/scripts/build-gsocket.sh b/scripts/build-gsocket.sh new file mode 100755 index 0000000..58098ab --- /dev/null +++ b/scripts/build-gsocket.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Download, verify, strip, and stage prebuilt gsocket aarch64 binaries for Geminux. +set -eu + +BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)" +GS_VER="1.4.43" +GS_URL="https://github.com/hackerschoice/gsocket/releases/download/v${GS_VER}/gsocket_linux-aarch64.tar.gz" +GS_SHA="2b50ce654feb110208745394267539364f3b60d7be6428ab5059e9815115f2d8" +TARBALL="$BASE_DIR/build-cache/gsocket_linux-aarch64-${GS_VER}.tar.gz" +OUT_DIR="$BASE_DIR/prebuilt/gsocket/usr/local/bin" + +mkdir -p "$BASE_DIR/build-cache" "$OUT_DIR" + +if [ ! -f "$TARBALL" ] || ! printf '%s %s\n' "$GS_SHA" "$TARBALL" | sha256sum -c - >/dev/null 2>&1; then + echo "[*] Downloading gsocket ${GS_VER} (linux-aarch64)..." + curl -fsSL -o "${TARBALL}.tmp" "$GS_URL" + printf '%s %s\n' "$GS_SHA" "${TARBALL}.tmp" | sha256sum -c - + mv -f "${TARBALL}.tmp" "$TARBALL" +fi + +rm -rf "$OUT_DIR" +mkdir -p "$OUT_DIR" +tar -xzf "$TARBALL" -C "$OUT_DIR" +chmod 0755 "$OUT_DIR"/* + +# Strip debug symbols from gsocket DSO helpers using Alpine aarch64 binutils +exec docker run --rm --network=host \ + -e HOST_UID="$(id -u)" \ + -e HOST_GID="$(id -g)" \ + -v "$BASE_DIR:/geminux" \ + alpine:3.24 sh -eu -c ' + cat > /etc/apk/repositories </dev/null || true + apk add --no-cache binutils-aarch64 >/dev/null + for so in /geminux/prebuilt/gsocket/usr/local/bin/gsocket_*.so.*; do + [ -f "$so" ] && aarch64-alpine-linux-musl-strip --strip-unneeded "$so" + done + chown -R "$HOST_UID:$HOST_GID" /geminux/prebuilt/gsocket +' diff --git a/scripts/check-rebuild.sh b/scripts/check-rebuild.sh index d2b35cd..f1b6e04 100755 --- a/scripts/check-rebuild.sh +++ b/scripts/check-rebuild.sh @@ -108,7 +108,7 @@ docker run --rm --network=host \ printf "%s\n" "$UPG_OUT" for pkg in geminux-kernel-modules geminux-xlibre geminux-suckless \ - geminux-dunst geminux-ui geminux-bantam geminux-config; do + geminux-dunst geminux-ui geminux-bantam geminux-gsocket geminux-config; do if ! grep -q "^${pkg}@geminux=" /rootfs/etc/apk/world; then echo "FAIL: ${pkg} is not exact-version pinned to @geminux in world" >&2 exit 1 @@ -146,7 +146,10 @@ file \ "$BASE_DIR/prebuilt/geminux/usr/lib/libgemui.so" \ "$BASE_DIR/prebuilt/geminux/usr/bin/"* \ "$BASE_DIR/prebuilt/geminux/usr/sbin/"* \ - "$BASE_DIR/prebuilt/bantam/usr/bin/bantam" | \ + "$BASE_DIR/prebuilt/bantam/usr/bin/bantam" \ + "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gs-netcat" \ + "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gsocket_dso.so.0" \ + "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0" | \ awk '!/ARM aarch64/ { print "FAIL: not aarch64: " $0; bad=1 } END { exit bad }' echo "OK (all aarch64 ELFs verified)" @@ -283,9 +286,24 @@ for req_rel in ("etc/pam.d/autologin", "etc/init.d/geminux-hwinit", "usr/sbin/geminux-wifi-nvram", "usr/sbin/geminux-tzctl", "usr/bin/geminux-datetime", "usr/bin/bantam", + "usr/bin/lynx", + "usr/bin/dtach", + "usr/bin/openssl", + "usr/local/bin/gs-netcat", + "usr/local/bin/gsocket", + "etc/htoprc", "etc/keymap/gemini-us.map", "etc/skel/.gitconfig", + "etc/skel/.config/htop/htoprc", + "etc/skel/.lynx.cfg", + "etc/skel/.apexrc", "home/user/.gitconfig", + "home/user/.config/htop/htoprc", + "home/user/.lynx.cfg", + "home/user/.apexrc", + "root/.config/htop/htoprc", + "root/.lynx.cfg", + "root/.apexrc", "etc/NetworkManager/dispatcher.d/30-geminux-chrony", "etc/polkit-1/rules.d/10-geminux.rules"): if not os.path.lexists(os.path.join(rootfs, req_rel)): @@ -309,6 +327,7 @@ for rel, needle in ( ("etc/NetworkManager/conf.d/20-geminux-wifi.conf", "wifi.scan-rand-mac-address = no"), ("etc/NetworkManager/conf.d/20-geminux-wifi.conf", "wifi-sec.pmf = 1"), ("etc/shells", "/bin/bash"), + ("usr/bin/geminux-launcher", "Bantam AI agent"), ): p = os.path.join(rootfs, rel) with open(p, "r", encoding="utf-8") as f: @@ -317,6 +336,10 @@ for rel, needle in ( xorg_mode = os.stat(os.path.join(rootfs, "usr/bin/Xorg")).st_mode & 0o7777 if xorg_mode != 0o4755: raise SystemExit(f"FAIL: rootfs/usr/bin/Xorg mode is {oct(xorg_mode)}, expected 0o4755") +with open(os.path.join(rootfs, "usr/bin/bantam"), "rb") as f: + bantam_bin = f.read() +if b"kilo-auto/free" not in bantam_bin or b"openrouter/free" in bantam_bin: + raise SystemExit("FAIL: rootfs/usr/bin/bantam does not default to 'kilo-auto/free'") awk_path = os.path.join(rootfs, "usr", "bin", "awk") if not os.path.lexists(awk_path): diff --git a/scripts/package-local-apks.sh b/scripts/package-local-apks.sh index e8649e2..826b8cc 100755 --- a/scripts/package-local-apks.sh +++ b/scripts/package-local-apks.sh @@ -94,7 +94,7 @@ def collect_needed_so(stage_dir): m = re.search(r"\(NEEDED\)\s+Shared library:\s+\[([^\]]+)\]", line) if m: so = m.group(1) - if so.startswith("ld-musl-") or so in internal: + if so.startswith("ld-musl-") or so == "libc.so" or so in internal: continue needed.add(f"so:{so}") return sorted(needed) @@ -239,7 +239,18 @@ make_pkg( depends=collect_needed_so(bstage), ) -# 7. geminux-config +# 7. geminux-gsocket +gstage = os.path.join(work_dir, "geminux-gsocket") +copy_tree_dedup("/geminux/prebuilt/gsocket", gstage) +make_pkg( + "geminux-gsocket", "1.4.43-r0", + "Gsocket end-to-end encrypted NAT traversal toolkit (gs-netcat, gsocket)", + gstage, + provides=["cmd:gs-netcat=1.4.43-r0", "cmd:gsocket=1.4.43-r0", "gsocket=1.4.43-r0"], + depends=["bash", "openssl"] + collect_needed_so(gstage), +) + +# 8. geminux-config cstage = os.path.join(work_dir, "geminux-config") copy_tree_dedup("/geminux/overlay/rootfs", cstage, dedup=True) for rel in ("etc/os-release", "usr/lib/os-release", "etc/issue", "etc/motd"): @@ -261,6 +272,7 @@ make_pkg( f"geminux-dunst=1.12.2-r0", f"geminux-ui={pkg_ver}", f"geminux-bantam={pkg_ver}", + f"geminux-gsocket=1.4.43-r0", ], replaces=[ "alpine-baselayout", diff --git a/scripts/rootfs-packages.txt b/scripts/rootfs-packages.txt index 48db564..2c18286 100644 --- a/scripts/rootfs-packages.txt +++ b/scripts/rootfs-packages.txt @@ -25,6 +25,7 @@ dbus-openrc dnsmasq doas dosfstools +dtach e2fsprogs e2fsprogs-extra ed @@ -79,6 +80,7 @@ libxinerama libxrandr libxscrnsaver libxtst +lynx mandoc mc mesa-dri-gallium @@ -103,6 +105,7 @@ nsxiv openrc openssh openssh-server-pam +openssl pango perl perl-io-socket-ssl diff --git a/scripts/test-power-policy.py b/scripts/test-power-policy.py index 2fb2661..3b4dc91 100755 --- a/scripts/test-power-policy.py +++ b/scripts/test-power-policy.py @@ -173,6 +173,48 @@ int main(void) { assert(perf.a72_online); assert(perf.suspend_timeout_s == 0); + /* Idle screensaver timing from last active input (battery balanced: dim=120s, suspend=300s) */ + pol.lid_closed = false; + pol.hdmi_connected = false; + pol.on_ac_power = false; + uint64_t next_wait = 999999; + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 0, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 120000); + /* User typed at t=100s, so when initial 120s timer fires (elapsed=20s) it re-arms for 100s */ + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 20000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 100000); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 120000, &next_wait) == IDLE_ACT_DIM); + assert(next_wait == 180000); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_DIMMED, 200000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 100000); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_DIMMED, 300000, &next_wait) == IDLE_ACT_SUSPEND); + assert(next_wait == 0); + + /* AC balanced (dim=300s, suspend=0): acts as lock + blank screensaver without auto-suspend */ + pol.lid_closed = false; + pol.on_ac_power = true; + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 299000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 1000); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 300000, &next_wait) == IDLE_ACT_LOCK_BLANK); + assert(next_wait == 0); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_LOCKED_BLANK, 450000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 0); + + /* Inhibitors, HDMI, and closed lid suppress idle screensaver timers */ + assert(geminux_policy_add_inhibit(&pol, "video")); + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 400000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 0); + assert(geminux_policy_del_inhibit(&pol, "video")); + pol.hdmi_connected = true; + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 400000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 0); + pol.hdmi_connected = false; + pol.lid_closed = true; + assert(geminux_policy_eval_idle(&pol, IDLE_STAGE_ACTIVE, 400000, &next_wait) == IDLE_ACT_NONE); + assert(next_wait == 0); + pol.lid_closed = false; + pol.on_ac_power = false; + test_touch_gestures(); /* Wi-Fi NVRAM record validation, scan, and deterministic MAC fallback */ diff --git a/src/bantam/README.md b/src/bantam/README.md index dc0a522..302b5a3 100644 --- a/src/bantam/README.md +++ b/src/bantam/README.md @@ -116,7 +116,7 @@ Bantam reads `.bantam.cfg` from the current working directory. ```ini endpoint=https://api.kilo.ai/api/openrouter - model=openrouter/free + model=kilo-auto/free temperature=0.7 api_key=your_api_key_here stream=true @@ -151,7 +151,7 @@ Bantam reads `.bantam.cfg` from the current working directory. tokens, and context-window utilization): ```text - [openrouter/free: 1420 prompt (1000 cached, 420 uncached) + 85 completion | context: 1420/262144 (0.5%)] + [kilo-auto/free: 1420 prompt (1000 cached, 420 uncached) + 85 completion | context: 1420/262144 (0.5%)] ``` Sessions are saved under `~/.bantam/sessions/` and can be managed with @@ -231,7 +231,7 @@ override the built-in defaults.) - `endpoint` (base OpenAI-compatible API URL, default `https://api.kilo.ai/api/openrouter`; falls back to `BANTAM_ENDPOINT`). -- `model` (model name, default `openrouter/free`; falls back to +- `model` (model name, default `kilo-auto/free`; falls back to `BANTAM_MODEL`). - `temperature` (model temperature, default `0.7`; falls back to `BANTAM_TEMP` or `BANTAM_TEMPERATURE`). diff --git a/src/bantam/config.cpp b/src/bantam/config.cpp index bb35b58..453126e 100644 --- a/src/bantam/config.cpp +++ b/src/bantam/config.cpp @@ -16,7 +16,7 @@ static void cfg_raw_set(Cfg &c, std::string_view k, std::string_view v) { static void cfg_init(Cfg &c) { c = Cfg{}; c.endpoint = "https://api.kilo.ai/api/openrouter"; - c.model = "openrouter/free"; + c.model = "kilo-auto/free"; c.api_key = "-"; c.temperature = 0.7; c.timeout = 300; diff --git a/src/geminux-daemons/geminux-power-policy.c b/src/geminux-daemons/geminux-power-policy.c index e58d30f..fff07c5 100644 --- a/src/geminux-daemons/geminux-power-policy.c +++ b/src/geminux-daemons/geminux-power-policy.c @@ -61,6 +61,50 @@ geminux_profile_params_t geminux_policy_params(geminux_profile_t prof, bool on_a return out; } +geminux_idle_action_t geminux_policy_eval_idle( + const geminux_power_policy_t *p, + geminux_idle_stage_t stage, + uint64_t elapsed_ms, + uint64_t *next_wait_ms) { + if (next_wait_ms) *next_wait_ms = 0; + if (!p || p->lid_closed || p->hdmi_connected || p->inhibit_count > 0) { + return IDLE_ACT_NONE; + } + + geminux_profile_params_t par = geminux_policy_params(p->profile, p->on_ac_power); + uint64_t dim_ms = (par.dim_timeout_s > 0) ? (uint64_t)par.dim_timeout_s * 1000ULL : 0; + uint64_t susp_ms = + (!p->on_ac_power && par.suspend_timeout_s > 0) ? (uint64_t)par.suspend_timeout_s * 1000ULL : 0; + + if (susp_ms > 0) { + if (elapsed_ms >= susp_ms) { + if (next_wait_ms) *next_wait_ms = 0; + return IDLE_ACT_SUSPEND; + } + if (dim_ms > 0 && dim_ms < susp_ms) { + if (elapsed_ms >= dim_ms) { + if (next_wait_ms) *next_wait_ms = susp_ms - elapsed_ms; + return (stage == IDLE_STAGE_ACTIVE) ? IDLE_ACT_DIM : IDLE_ACT_NONE; + } + if (next_wait_ms) *next_wait_ms = dim_ms - elapsed_ms; + return IDLE_ACT_NONE; + } + if (next_wait_ms) *next_wait_ms = susp_ms - elapsed_ms; + return IDLE_ACT_NONE; + } + + if (dim_ms > 0) { + if (elapsed_ms >= dim_ms) { + if (next_wait_ms) *next_wait_ms = 0; + return (stage != IDLE_STAGE_LOCKED_BLANK) ? IDLE_ACT_LOCK_BLANK : IDLE_ACT_NONE; + } + if (next_wait_ms) *next_wait_ms = dim_ms - elapsed_ms; + return IDLE_ACT_NONE; + } + + return IDLE_ACT_NONE; +} + bool geminux_policy_add_inhibit(geminux_power_policy_t *p, const char *tag) { if (!p || !tag || !tag[0]) return false; for (int i = 0; i < p->inhibit_count; i++) { diff --git a/src/geminux-daemons/geminux-power-policy.h b/src/geminux-daemons/geminux-power-policy.h index 5054b01..a21ea1c 100644 --- a/src/geminux-daemons/geminux-power-policy.h +++ b/src/geminux-daemons/geminux-power-policy.h @@ -2,6 +2,7 @@ #define GEMINUX_POWER_POLICY_H #include +#include #define GEMINUX_MAX_INHIBITORS 16 @@ -11,6 +12,19 @@ typedef enum { POWER_PROFILE_PERFORMANCE = 2, } geminux_profile_t; +typedef enum { + IDLE_STAGE_ACTIVE = 0, + IDLE_STAGE_DIMMED = 1, + IDLE_STAGE_LOCKED_BLANK = 2, +} geminux_idle_stage_t; + +typedef enum { + IDLE_ACT_NONE = 0, + IDLE_ACT_DIM = 1, + IDLE_ACT_LOCK_BLANK = 2, + IDLE_ACT_SUSPEND = 3, +} geminux_idle_action_t; + typedef struct { geminux_profile_t profile; bool lid_closed; @@ -35,6 +49,11 @@ void geminux_policy_init(geminux_power_policy_t *p); bool geminux_policy_set_profile_name(geminux_power_policy_t *p, const char *name); const char *geminux_policy_profile_name(geminux_profile_t prof); geminux_profile_params_t geminux_policy_params(geminux_profile_t prof, bool on_ac); +geminux_idle_action_t geminux_policy_eval_idle( + const geminux_power_policy_t *p, + geminux_idle_stage_t stage, + uint64_t elapsed_ms, + uint64_t *next_wait_ms); bool geminux_policy_add_inhibit(geminux_power_policy_t *p, const char *tag); bool geminux_policy_del_inhibit(geminux_power_policy_t *p, const char *tag); bool geminux_should_suspend_on_lid(const geminux_power_policy_t *p); diff --git a/src/geminux-daemons/geminux-powerd.c b/src/geminux-daemons/geminux-powerd.c index a26b83b..c21f46a 100644 --- a/src/geminux-daemons/geminux-powerd.c +++ b/src/geminux-daemons/geminux-powerd.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,7 @@ #include #include #include +#include #include #define SOCK_PATH "/run/geminux/powerd.sock" @@ -36,9 +38,17 @@ typedef struct { int ev_fds[MAX_EVDEVS]; int num_ev; int saved_brightness; + uint64_t last_input_ms; + geminux_idle_stage_t idle_stage; geminux_power_policy_t policy; } powerd_ctx_t; +static uint64_t monotonic_ms(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + static int write_sysfs_str(const char *path, const char *val) { int fd = open(path, O_WRONLY | O_CLOEXEC); if (fd < 0) return -1; @@ -105,6 +115,113 @@ static void refresh_ac_and_hdmi(powerd_ctx_t *ctx) { } } +static void lock_x11_session(void); +static void trigger_suspend(powerd_ctx_t *ctx); + +static void save_active_brightness(powerd_ctx_t *ctx, const char *bri_path) { + if (ctx->idle_stage != IDLE_STAGE_ACTIVE) return; + char cur[32] = {0}; + if (read_sysfs_line(bri_path, cur, sizeof(cur)) == 0 && atoi(cur) > 0) { + ctx->saved_brightness = atoi(cur); + } +} + +static void toggle_backlight(powerd_ctx_t *ctx, bool on) { + DIR *d = opendir("/sys/class/backlight"); + if (!d) return; + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[320]; + snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); + if (!on) { + save_active_brightness(ctx, p); + write_sysfs_str(p, "0"); + } else { + char restore[32]; + int val = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128; + snprintf(restore, sizeof(restore), "%d", val); + write_sysfs_str(p, restore); + } + break; + } + closedir(d); +} + +static void dim_backlight(powerd_ctx_t *ctx) { + DIR *d = opendir("/sys/class/backlight"); + if (!d) return; + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[320], max_buf[32] = {0}; + snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); + save_active_brightness(ctx, p); + int max_bri = 255; + snprintf(p, sizeof(p), "/sys/class/backlight/%s/max_brightness", de->d_name); + if (read_sysfs_line(p, max_buf, sizeof(max_buf)) == 0 && atoi(max_buf) > 0) { + max_bri = atoi(max_buf); + } + int cur_base = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128; + int target = cur_base / 5; + int min_floor = max_bri / 20; + if (target < min_floor) target = min_floor; + if (target >= cur_base) target = cur_base / 2; + if (target < 4) target = 4; + if (target > cur_base) target = cur_base; + char dim_str[32]; + snprintf(dim_str, sizeof(dim_str), "%d", target); + snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); + write_sysfs_str(p, dim_str); + break; + } + closedir(d); +} + +static void arm_timer_ms(int tmr_fd, uint64_t wait_ms) { + struct itimerspec its; + memset(&its, 0, sizeof(its)); + if (wait_ms > 0) { + its.it_value.tv_sec = (time_t)(wait_ms / 1000ULL); + its.it_value.tv_nsec = (long)((wait_ms % 1000ULL) * 1000000ULL); + if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0) { + its.it_value.tv_nsec = 1000000L; + } + } + timerfd_settime(tmr_fd, 0, &its, NULL); +} + +static void evaluate_idle(powerd_ctx_t *ctx) { + uint64_t now = monotonic_ms(); + uint64_t elapsed = (now >= ctx->last_input_ms) ? (now - ctx->last_input_ms) : 0; + uint64_t next_wait_ms = 0; + geminux_idle_action_t act = geminux_policy_eval_idle(&ctx->policy, ctx->idle_stage, elapsed, &next_wait_ms); + if (act == IDLE_ACT_DIM) { + dim_backlight(ctx); + ctx->idle_stage = IDLE_STAGE_DIMMED; + arm_timer_ms(ctx->tmr_fd, next_wait_ms); + } else if (act == IDLE_ACT_LOCK_BLANK) { + lock_x11_session(); + toggle_backlight(ctx, false); + ctx->idle_stage = IDLE_STAGE_LOCKED_BLANK; + arm_timer_ms(ctx->tmr_fd, 0); + } else if (act == IDLE_ACT_SUSPEND) { + arm_timer_ms(ctx->tmr_fd, 0); + trigger_suspend(ctx); + } else { + arm_timer_ms(ctx->tmr_fd, next_wait_ms); + } +} + +static void note_user_activity(powerd_ctx_t *ctx) { + ctx->last_input_ms = monotonic_ms(); + if (ctx->idle_stage != IDLE_STAGE_ACTIVE) { + ctx->idle_stage = IDLE_STAGE_ACTIVE; + toggle_backlight(ctx, true); + evaluate_idle(ctx); + } +} + static void apply_cpu_policy(powerd_ctx_t *ctx) { geminux_profile_params_t par = geminux_policy_params(ctx->policy.profile, ctx->policy.on_ac_power); @@ -139,37 +256,7 @@ static void apply_cpu_policy(powerd_ctx_t *ctx) { ensure_run_dir(); write_sysfs_str(PROFILE_FILE, geminux_policy_profile_name(ctx->policy.profile)); - - struct itimerspec its; - memset(&its, 0, sizeof(its)); - if (par.suspend_timeout_s > 0 && !ctx->policy.hdmi_connected && ctx->policy.inhibit_count == 0) { - its.it_value.tv_sec = par.suspend_timeout_s; - } - timerfd_settime(ctx->tmr_fd, 0, &its, NULL); -} - -static void toggle_backlight(powerd_ctx_t *ctx, bool on) { - DIR *d = opendir("/sys/class/backlight"); - if (!d) return; - struct dirent *de; - while ((de = readdir(d)) != NULL) { - if (de->d_name[0] == '.') continue; - char p[320], cur[32] = {0}; - snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); - if (!on) { - if (read_sysfs_line(p, cur, sizeof(cur)) == 0 && atoi(cur) > 0) { - ctx->saved_brightness = atoi(cur); - } - write_sysfs_str(p, "0"); - } else { - char restore[32]; - int val = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128; - snprintf(restore, sizeof(restore), "%d", val); - write_sysfs_str(p, restore); - } - break; - } - closedir(d); + evaluate_idle(ctx); } static bool is_lock_running(void) { @@ -254,11 +341,16 @@ static void trigger_suspend(powerd_ctx_t *ctx) { if (write_sysfs_str("/sys/power/state", "mem") == 0 || write_sysfs_str("/sys/power/state", "freeze") == 0) { /* Woken back up from suspend */ + ctx->idle_stage = IDLE_STAGE_ACTIVE; + ctx->last_input_ms = monotonic_ms(); toggle_backlight(ctx, true); refresh_ac_and_hdmi(ctx); apply_cpu_policy(ctx); } else if (!ctx->policy.lid_closed) { + ctx->idle_stage = IDLE_STAGE_ACTIVE; + ctx->last_input_ms = monotonic_ms(); toggle_backlight(ctx, true); + evaluate_idle(ctx); } } @@ -277,7 +369,7 @@ static void scan_input_devices(powerd_ctx_t *ctx) { if (fd < 0) continue; unsigned long evbits = 0; if (ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), &evbits) >= 0 && - ((evbits & (1UL << EV_SW)) || (evbits & (1UL << EV_KEY)))) { + (evbits & ((1UL << EV_SW) | (1UL << EV_KEY) | (1UL << EV_REL) | (1UL << EV_ABS)))) { if (evbits & (1UL << EV_SW)) { unsigned long swbits = 0, swstate = 0; if (ioctl(fd, EVIOCGBIT(EV_SW, sizeof(swbits)), &swbits) >= 0 && @@ -401,6 +493,8 @@ int main(void) { } } + ctx.last_input_ms = monotonic_ms(); + ctx.idle_stage = IDLE_STAGE_ACTIVE; refresh_ac_and_hdmi(&ctx); scan_input_devices(&ctx); apply_cpu_policy(&ctx); @@ -435,9 +529,7 @@ int main(void) { uint64_t exp = 0; while (read(ctx.tmr_fd, &exp, sizeof(exp)) > 0) {} refresh_ac_and_hdmi(&ctx); - if (!ctx.policy.on_ac_power && !ctx.policy.hdmi_connected && ctx.policy.inhibit_count == 0) { - trigger_suspend(&ctx); - } + evaluate_idle(&ctx); } else if (fd == ctx.uev_fd) { char ubuf[2048]; ssize_t ur; @@ -448,29 +540,50 @@ int main(void) { } } if (need_ev_rescan) scan_input_devices(&ctx); + bool prev_ac = ctx.policy.on_ac_power; + bool prev_hdmi = ctx.policy.hdmi_connected; refresh_ac_and_hdmi(&ctx); + if (prev_ac != ctx.policy.on_ac_power || prev_hdmi != ctx.policy.hdmi_connected) { + note_user_activity(&ctx); + } apply_cpu_policy(&ctx); } else { struct input_event iev; + bool saw_activity = false; + bool power_pressed = false; while (read(fd, &iev, sizeof(iev)) == (ssize_t)sizeof(iev)) { if (iev.type == EV_SW && iev.code == SW_LID) { ctx.policy.lid_closed = (iev.value != 0); if (ctx.policy.lid_closed) { lock_x11_session(); + evaluate_idle(&ctx); if (geminux_should_suspend_on_lid(&ctx.policy)) { trigger_suspend(&ctx); } else { toggle_backlight(&ctx, false); } } else { + ctx.idle_stage = IDLE_STAGE_ACTIVE; + ctx.last_input_ms = monotonic_ms(); toggle_backlight(&ctx, true); refresh_ac_and_hdmi(&ctx); apply_cpu_policy(&ctx); } } else if (iev.type == EV_KEY && iev.code == KEY_POWER && iev.value == 1) { - trigger_suspend(&ctx); + if (ctx.idle_stage == IDLE_STAGE_LOCKED_BLANK) { + note_user_activity(&ctx); + } else { + power_pressed = true; + } + } else if (iev.type == EV_KEY || iev.type == EV_REL || iev.type == EV_ABS) { + saw_activity = true; } } + if (power_pressed) { + trigger_suspend(&ctx); + } else if (saw_activity && !ctx.policy.lid_closed) { + note_user_activity(&ctx); + } } } }