diff --git a/MANUAL.md b/MANUAL.md index 87c3765..84333f1 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -25,7 +25,7 @@ This manual covers flashing, operating, and customizing **Bananarchy Linux** (`2 - Uses a lightweight cross-compiled **Xlibre** server with `modesetting` KMS, partial-rectangle `ShadowFB` SPI updates, and zero Wayland overhead. - **Patched `dwm`** provides a `240x320` vertical bottom-stack (`bstack`) layout, a 24px top status bar, a transparent `"Menu"` / `"Names"` desktop softkey bar, a Conky desktop clock and status widget (which refreshes automatically when changing time, timezone, or wallpaper, or when logging out), and `< 2 ms` handling of physical slider (`SW_LID`) and wake keys. 2. **Preloaded resident DWM plugins (`< 2 ms` wakeup)**: - - Core phone applications (`dmenu`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `passcode`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`, `sip`, `email`, `irc`, `tox`, `smallweb`, `gps`, `locker`) run as preloaded resident daemons (`dwm-plugin --preload`) that sleep at 0% CPU and open instantaneously over FIFO/socket IPC. + - Core phone applications (`dmenu`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `passcode`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`, `sip`, `email`, `irc`, `tox`, `smallweb`, `webarchy`, `gps`, `privacy`, `locker`) run as preloaded resident daemons (`dwm-plugin --preload`) that sleep at 0% CPU and open instantaneously over FIFO/socket IPC. - All UI elements — including the `dunst` notification daemon (`bananarchy-sync-dunst-theme`) — share the **NeoUI SDK (`libneoui.so` + `/usr/include/neoui.h`)** and a single **XRDB theming engine** (`~/.xthemes/*.xth` -> `~/.Xresources`) with 20 preinstalled color schemes, proportional font sizing (`theme.baseFontSize`), and live reload without restarting X11. NeoUI exposes both C++20 classes and a C-compatible FFI (`neoui_*`) for building custom native or scripted (`yabasic` via `~/Projects/neoui.yab`, `~/Projects/neoui_demo.yab`, and `~/Projects/bulls_cows.yab`, paired with **NeoNet** in `~/Projects/neonet.yab` and `~/Projects/neonet_demo.yab` for `libcurl` HTTP/HTTPS and TCP/TLS/UDP socket networking) `240x320` GUI applications — see [SDK.md](./SDK.md) for the complete API reference and examples. 3. **First-class terminal (`st`) and 6-mode `fcitx5-t9` keypad input**: - `st` is patched with HarfBuzz OpenType ligature shaping (`Fira Code` default) and live `.Xresources` reload. @@ -122,7 +122,7 @@ You can switch layouts, focus, and workspaces using the **Window management menu - `Mod4+Shift+q`: close the focused window. #### 3.1.2 Preloaded native DWM applications -All twenty-four phone applications are compiled as shared-object plugins (`/usr/lib/dwm/plugins/*.so`), preloaded at `dwm` startup, and awakened over `/tmp/dwm_plugin_.fifo` in `< 2 ms`: +All twenty-five phone applications are compiled as shared-object plugins (`/usr/lib/dwm/plugins/*.so`), preloaded at `dwm` startup, and awakened over `/tmp/dwm_plugin_.fifo` in `< 2 ms`: 1. **System and context menus (`dmenu.so` / `dmenu` / `xdmenu`)**: - **Open / close**: press **Left softkey (`Menu`)** for the **System menu** or **Right softkey (`Back`)** inside an application for its **Context menu**; press the same softkey or `Escape` to close. diff --git a/README.md b/README.md index 5ffbbb3..b7deded 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ ### Keypad-first user experience and native DWM plugins Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs a suite of 25 preloaded C/C++ plugins inside DWM that sleep at 0% CPU and open in `< 2 ms`: - **System and context menus (`dmenu`)**: instant full-screen 10-line vertical menus with live T9 filtering, built-in submenus, and hardware toggles. -- **Passcode-based fullscreen phone locker (`xlocker`), GUI passcode configurator (`xpasscode`), and Duress Mode**: zero-bypass `240x320` fullscreen numeric passcode lock screen verified against the current user's system shadow password (`/usr/bin/bananarchy-verify-passcode`), blocking all desktop, menu, drawer, terminal, and power actions while locked and automatically handing off the display only during incoming calls. Includes a NeoUI **Passcode Configurator (`xpasscode` / `passcode.so`)** in `Config -> Passcode` to change the real Linux user password (`user`, any numeric length `>= 4` digits) and configure a separate **Duress Passcode**. Entering the duress passcode on the lock screen switches the session into **Duress Mode** (`/tmp/duress_home` blank profile with no contacts, SMS, call logs, or personal files, microSD unmounted and disabled, `xfiles` clamped to the profile directory, Passcode/Privacy Center/Engineering Menu/Tox/IRC/SIP/`st` terminal hidden and blocked, `*#06#` displaying a session-persistent random Luhn-valid IMEI derived from the device's TAC, and theme/wallpaper locked to `NordFrost.xth` and `nordic-peaks.png` until poweroff or reboot). +- **Passcode-based fullscreen phone locker (`xlocker`), GUI passcode configurator (`xpasscode`), and Duress Mode**: zero-bypass `240x320` fullscreen numeric passcode lock screen verified against the current user's system shadow password (`/usr/bin/bananarchy-verify-passcode`), blocking all desktop, menu, drawer, terminal, and power actions while locked and automatically handing off the display only during incoming calls. Includes a NeoUI **Passcode Configurator (`xpasscode` / `passcode.so`)** in `Config -> Passcode` to change the real Linux user password (`user`, any numeric length `>= 4` digits) and configure a separate **Duress Passcode**. Entering the duress passcode on the lock screen switches the session into **Duress Mode** (`/tmp/duress_home` blank profile with no contacts, SMS, call logs, or personal files, microSD unmounted and disabled, `xfiles` clamped to the profile directory, Passcode/Privacy Center/Tox/IRC/SIP/`st` terminal hidden and blocked, `*#06#` displaying a session-persistent random Luhn-valid IMEI derived from the device's TAC, and theme/wallpaper locked to `NordFrost.xth` and `nordic-peaks.png` until poweroff or reboot). - **Privacy Center (`xprivacy` / `privacy` / `privacy.so`) and `/usr/bin/bananarchy-privacy-ctl`**: 5-tab NeoUI privacy and tunneling control center (`1:Tor`, `2:Warp`, `3:OVPN`, `4:GS`, `5:WG`, hidden and disabled in Duress Mode) with zero background CPU or battery consumption when services are turned off: - **Tor (`1:Tor`)**: start/stop the Tor anonymity daemon (`SocksPort 9050`, `TransPort 9040`, `DNSPort 9053`) and transparently route all native phone traffic and/or Wi-Fi hotspot (`10.42.0.0/24`) and USB-tethered (`usb0`) traffic through Tor. - **GS-Warp (`2:Warp`)**: start/stop the GSocket-tunneled OpenVPN client (`gs-warp` / `gs-warp-simple.sh` over `tun_gswarp`), configure a custom GSocket secret string (defaulting to the MD5 of the selected `.ovpn` profile), and route native and/or Wi-Fi/USB-tethered traffic through it. diff --git a/overlay/rootfs/etc/doas.d/50-sxmo.conf b/overlay/rootfs/etc/doas.d/50-sxmo.conf index 6576d4a..9648228 100644 --- a/overlay/rootfs/etc/doas.d/50-sxmo.conf +++ b/overlay/rootfs/etc/doas.d/50-sxmo.conf @@ -43,6 +43,8 @@ permit nopass :wheel as root cmd /usr/bin/bananarchy-verify-passcode permit nopass :wheel as root cmd bananarchy-verify-passcode permit nopass :wheel as root cmd /usr/bin/bananarchy-engmenu-exec permit nopass :wheel as root cmd bananarchy-engmenu-exec +permit nopass :wheel as root cmd /usr/bin/bananarchy-engmenu-ctl +permit nopass :wheel as root cmd bananarchy-engmenu-ctl permit nopass :wheel as root cmd /usr/bin/bananarchy-bt-obex permit nopass :wheel as root cmd bananarchy-bt-obex permit nopass :wheel as root cmd /usr/bin/bananarchy-privacy-ctl diff --git a/overlay/rootfs/etc/local.d/10-power-save.start b/overlay/rootfs/etc/local.d/10-power-save.start index 14bbdb9..efd5290 100755 --- a/overlay/rootfs/etc/local.d/10-power-save.start +++ b/overlay/rootfs/etc/local.d/10-power-save.start @@ -45,6 +45,11 @@ if command -v iw >/dev/null 2>&1; then iw dev wlan0 set power_save on 2>/dev/null || true fi +# Restore any persistent Engineering Menu Wi-Fi/BT MAC and IMEI override state +if [ -x /usr/bin/bananarchy-engmenu-ctl ]; then + /usr/bin/bananarchy-engmenu-ctl apply-boot >/dev/null 2>&1 || true +fi + # Automount microSD card if present at boot (unbinds 7864900.sdhci when slot is empty) if [ -x /usr/bin/sxmo_sdcard.sh ]; then /usr/bin/sxmo_sdcard.sh automount boot >/dev/null 2>&1 & diff --git a/overlay/rootfs/usr/bin/bananarchy-engmenu-ctl b/overlay/rootfs/usr/bin/bananarchy-engmenu-ctl new file mode 100755 index 0000000..7b26549 --- /dev/null +++ b/overlay/rootfs/usr/bin/bananarchy-engmenu-ctl @@ -0,0 +1,1072 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0-only +# Bananarchy Linux — Engineering Menu Hardware & Radio Controller +# Implements Qualcomm MSM8905/MSM8909 and Nokia NVRAM operations ported from Wallace Toolbox: +# - Outgoing & tethering TTL override (nftables + iptables + sysctl) +# - IMEI 1 & IMEI 2 editor (tunning nvm/num/550 & nvm/context1/550 + modemst1/2 EFS reset) +# - Wi-Fi MAC editor (tunning nvm/num/4678 + live wlan0 & NetworkManager persistence) +# - Bluetooth MAC editor (tunning nvm/num/447 + persist .bt_nv.bin + live BlueZ/QCA Rome HCI) +# - Qualcomm CPU/GPU overclock & performance governor script +# - Qualcomm USB Diagnostics (05c6:9091 DIAG + AT + NCM) port toggle & RPMSG bridge +set -u + +if [ -e "/tmp/bananarchy_duress_mode" ] || [ -e "/tmp/bananarchy_screen_locked" ]; then + echo "Error: Engineering Menu is unavailable." >&2 + exit 1 +fi + +# Escalate to root via doas or bananarchy-engmenu-exec if invoked as normal user +if [ "$(id -u)" -ne 0 ]; then + if command -v doas >/dev/null 2>&1; then + exec doas -n /usr/bin/bananarchy-engmenu-ctl "$@" + elif [ -x /usr/bin/bananarchy-engmenu-exec ]; then + ESCAPED="" + for arg in "$@"; do + ESCAPED="$ESCAPED '$(printf "%s" "$arg" | sed "s/'/'\\\\''/g")'" + done + exec /usr/bin/bananarchy-engmenu-exec --exec "/usr/bin/bananarchy-engmenu-ctl $ESCAPED" + fi + echo "Error: root privileges required." >&2 + exit 1 +fi + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +STATE_DIR="/var/lib/bananarchy" +CONF_DIR="/etc/bananarchy" +mkdir -p "$STATE_DIR" "$CONF_DIR" + +# Locate eMMC partition block device by GPT PARTNAME +find_part() { + pname="$1" + if [ -b "/dev/disk/by-partlabel/$pname" ]; then + printf "/dev/disk/by-partlabel/%s\n" "$pname" + return 0 + fi + if [ -b "/dev/block/bootdevice/by-name/$pname" ]; then + printf "/dev/block/bootdevice/by-name/%s\n" "$pname" + return 0 + fi + for uev in /sys/block/mmcblk*/mmcblk*p*/uevent /sys/class/block/mmcblk*p*/uevent; do + [ -f "$uev" ] || continue + if grep -q "^PARTNAME=${pname}$" "$uev" 2>/dev/null; then + devname="$(sed -n 's/^DEVNAME=//p' "$uev" | head -n 1)" + if [ -n "$devname" ] && [ -b "/dev/$devname" ]; then + printf "/dev/%s\n" "$devname" + return 0 + fi + fi + done + return 1 +} + +# Validate 15-digit IMEI using Luhn algorithm (Wallace calcIMEIChecksum) +validate_imei() { + imei_str="${1:-}" + case "$imei_str" in + [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) ;; + *) return 1 ;; + esac + awk -v val="$imei_str" ' + BEGIN { + sum = 0 + for (i = 1; i <= 14; i++) { + d = substr(val, i, 1) + 0 + if (i % 2 == 0) { + d *= 2 + if (d > 9) d -= 9 + } + sum += d + } + chk = (10 - (sum % 10)) % 10 + if (chk == (substr(val, 15, 1) + 0)) exit 0 + exit 1 + } + ' +} + +# Normalize 6-byte MAC address to lowercase colon-separated xx:xx:xx:xx:xx:xx +normalize_mac() { + raw_hex="$(printf "%s" "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -cd '0-9a-f')" + if [ "${#raw_hex}" -ne 12 ]; then + return 1 + fi + printf "%s\n" "$raw_hex" | sed 's/\(..\)/\1:/g; s/:$//' +} + +# Detect phone model and NVRAM layout: +# - nokia-argon (Nokia 8110 4G), nokia-beatles (Nokia 2720 Flip), nokia-tough / nokia-coconut (Nokia 800 Tough): +# uses "tunning" ustar partition (Wallace Toolbox / lycan-tun.py: nvm/num/550, nvm/context1/550, nvm/num/4678, nvm/num/447) +# - nokia-sparkler (Nokia 8000 4G), nokia-leo (Nokia 6300 4G), and other Qualcomm devices without tunning: +# uses "rf_nv" binary partition (Project Lycan lycan-rfnv.py: IEMI sig at 0x80, shifted sig at 0x100, IMEI1 at 0x88, CRC1 at 0x94, IMEI2 at 0x108, CRC2 at 0x114) +DEVICE_CODENAME="nokia-argon" +DEVICE_NAME="Nokia 8110 4G" +NV_METHOD="tunning" + +detect_device_model() { + if [ -f /etc/deviceinfo ]; then + # shellcheck disable=SC1091 + . /etc/deviceinfo 2>/dev/null || true + [ -n "${deviceinfo_codename:-}" ] && DEVICE_CODENAME="$deviceinfo_codename" + [ -n "${deviceinfo_name:-}" ] && DEVICE_NAME="$deviceinfo_name" + fi + if [ -r /proc/device-tree/compatible ]; then + dt_compat="$(tr '\0' ' ' < /proc/device-tree/compatible 2>/dev/null || true)" + case "$dt_compat" in + *nokia,sparkler*) + DEVICE_CODENAME="nokia-sparkler" + DEVICE_NAME="Nokia 8000 4G" + ;; + *nokia,leo*) + DEVICE_CODENAME="nokia-leo" + DEVICE_NAME="Nokia 6300 4G" + ;; + *nokia,beatles*) + DEVICE_CODENAME="nokia-beatles" + DEVICE_NAME="Nokia 2720 Flip" + ;; + *nokia,coconut*|*nokia,tough*) + DEVICE_CODENAME="nokia-tough" + DEVICE_NAME="Nokia 800 Tough" + ;; + *nokia,argon*) + DEVICE_CODENAME="nokia-argon" + DEVICE_NAME="Nokia 8110 4G" + ;; + esac + fi + case "$DEVICE_CODENAME" in + nokia-sparkler|sparkler|nokia-leo|leo) + NV_METHOD="rfnv" + ;; + nokia-argon|argon|nokia-beatles|beatles|nokia-tough|nokia-coconut|tough|coconut) + if [ -n "$(find_part tunning || true)" ]; then + NV_METHOD="tunning" + elif [ -n "$(find_part rf_nv || find_part rfnv || true)" ]; then + NV_METHOD="rfnv" + else + NV_METHOD="tunning" + fi + ;; + *) + if [ -n "$(find_part tunning || true)" ]; then + NV_METHOD="tunning" + else + NV_METHOD="rfnv" + fi + ;; + esac +} + +detect_device_model + +# Read NV items from either tunning tar partition (lycan-tun.py) or rf_nv partition (lycan-rfnv.py) +read_nv_info() { + if ! command -v python3 >/dev/null 2>&1; then + return 0 + fi + if [ "$NV_METHOD" = "tunning" ]; then + tun_part="$(find_part tunning || true)" + [ -z "$tun_part" ] && return 0 + python3 - "$tun_part" << 'PY' 2>/dev/null || true +import sys, tarfile + +def nibble_invert(bytestr): + return bytes(((b >> 4) | ((b & 15) << 4)) for b in bytestr) + +def decode_imei(bytestr): + if not bytestr or len(bytestr) < 9: + return "" + s = nibble_invert(bytestr[:9]).hex()[3:] + return s if len(s) == 15 and s.isdigit() else "" + +def decode_mac(data): + if not data or len(data) < 6: + return "" + return ":".join(f"{b:02x}" for b in data[:6]) + +try: + with tarfile.open(sys.argv[1], "r:*") as tf: + for member in tf.getmembers(): + norm = member.name.lstrip("./") + if norm == "nvm/num/550": + f = tf.extractfile(member) + if f: + v = decode_imei(f.read()) + if v: print(f"TUN_IMEI1={v}") + elif norm == "nvm/context1/550": + f = tf.extractfile(member) + if f: + v = decode_imei(f.read()) + if v: print(f"TUN_IMEI2={v}") + elif norm == "nvm/num/4678": + f = tf.extractfile(member) + if f: + v = decode_mac(f.read()) + if v: print(f"TUN_WIFI_MAC={v}") + elif norm == "nvm/num/447": + f = tf.extractfile(member) + if f: + v = decode_mac(f.read()) + if v: print(f"TUN_BT_MAC={v}") +except Exception: + pass +PY + else + rfnv_part="$(find_part rf_nv || find_part rfnv || true)" + [ -z "$rfnv_part" ] && return 0 + python3 - "$rfnv_part" << 'PY' 2>/dev/null || true +import sys + +SIGVAL = b"IEMI" +SIGPOS = 0x80 +SIGVAL2 = b"\x92\x8a\x9a\x92" +SIGPOS2 = SIGPOS + 0x80 +IMEI1POS = SIGPOS + 8 +IMEI2POS = SIGPOS2 + 8 + +def nibble_invert(bytestr): + return bytes(((b >> 4) | ((b & 15) << 4)) for b in bytestr) + +def decode_imei(bytestr): + if not bytestr or len(bytestr) < 9: + return "" + s = nibble_invert(bytestr[:9]).hex()[3:] + return s if len(s) == 15 and s.isdigit() else "" + +try: + with open(sys.argv[1], "rb") as fh: + fh.seek(SIGPOS) + val1 = fh.read(4) + fh.seek(SIGPOS2) + val2 = fh.read(4) + if val1 == SIGVAL and val2 == SIGVAL2: + fh.seek(IMEI1POS) + v1 = decode_imei(fh.read(9)) + fh.seek(IMEI2POS) + v2 = decode_imei(fh.read(9)) + if v1: print(f"TUN_IMEI1={v1}") + if v2: print(f"TUN_IMEI2={v2}") +except Exception: + pass +PY + fi +} + +# Ensure factory backup of tunning or rf_nv partition exists before first write +backup_nv_once() { + nv_part="$1" + bak_name="$2" + if [ -n "$nv_part" ] && [ -b "$nv_part" ] && [ ! -s "$STATE_DIR/$bak_name" ]; then + dd if="$nv_part" of="$STATE_DIR/$bak_name" bs=4096 2>/dev/null || true + fi +} + +# Wipe modemst1 & modemst2 EFS partitions so MPSS rebuilds EFS from tunning/fsg +wipe_modem_efs() { + efs1="$(find_part modemst1 || true)" + efs2="$(find_part modemst2 || true)" + if [ -n "$efs1" ] && [ -b "$efs1" ]; then + dd if=/dev/zero of="$efs1" bs=4096 2>/dev/null || true + fi + if [ -n "$efs2" ] && [ -b "$efs2" ]; then + dd if=/dev/zero of="$efs2" bs=4096 2>/dev/null || true + fi + sync +} + +# Apply Bluetooth MAC address live to hci0 via BlueZ MGMT (0x002E) + QCA Rome vendor HCI (0xFC0B) +apply_bt_mac_live() { + target_mac="$1" + if ! command -v python3 >/dev/null 2>&1; then + return 0 + fi + python3 - "$target_mac" << 'PY' 2>/dev/null || true +import socket, struct, sys + +mac_str = sys.argv[1].strip() +mac_bytes = bytes(int(x, 16) for x in mac_str.split(":")) +if len(mac_bytes) != 6: + sys.exit(0) +bdaddr_le = mac_bytes[::-1] + +AF_BLUETOOTH = 31 +BTPROTO_HCI = 1 +HCI_CHANNEL_RAW = 0 +HCI_CHANNEL_CONTROL = 3 + +# 1. Try BlueZ MGMT_OP_SET_PUBLIC_ADDRESS (0x002E) on HCI_CHANNEL_CONTROL +try: + ms = socket.socket(AF_BLUETOOTH, socket.SOCK_RAW, BTPROTO_HCI) + ms.bind((0xFFFF, HCI_CHANNEL_CONTROL)) + ms.settimeout(0.5) + # Power off hci0 (MGMT_OP_SET_POWERED = 0x0005, index = 0, len = 1, val = 0) + ms.send(struct.pack(" 0xFC0B) +try: + hs = socket.socket(AF_BLUETOOTH, socket.SOCK_RAW, BTPROTO_HCI) + hs.bind((0, HCI_CHANNEL_RAW)) + hs.settimeout(0.5) + # HCI Command packet (0x01), opcode 0xFC0B, plen 6, bdaddr_le + hs.send(struct.pack("/dev/null)" 2>/dev/null || true + rm -f /tmp/bananarchy_diag_bridge.pid + fi + pkill -f "bananarchy_diag_bridge_worker" 2>/dev/null || true +} + +start_diag_bridge() { + stop_diag_bridge + if ! command -v python3 >/dev/null 2>&1; then + return 0 + fi + # Bind any RPMSG DIAG channel on SMD to rpmsg_chrdev + for rpdev in /sys/bus/rpmsg/devices/*DIAG*; do + [ -d "$rpdev" ] || continue + bname="$(basename "$rpdev")" + echo "rpmsg_chrdev" > "$rpdev/driver_override" 2>/dev/null || true + echo "$bname" > /sys/bus/rpmsg/drivers_probe 2>/dev/null || true + done + + python3 - "bananarchy_diag_bridge_worker" >/dev/null 2>&1 /tmp/bananarchy_diag_bridge.pid +} + +if [ "${1:-}" = "_diag_worker" ]; then + exec python3 - "bananarchy_diag_bridge_worker" << 'PY' +import fcntl, glob, os, select, struct, termios, time + +RPMSG_CREATE_EPT_IOCTL = 0x4028B501 + +def open_raw_tty(path): + fd = os.open(path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) + try: + attrs = termios.tcgetattr(fd) + attrs[0] = 0 + attrs[1] = 0 + attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL | termios.B115200 + attrs[3] = 0 + termios.tcsetattr(fd, termios.TCSANOW, attrs) + except Exception: + pass + return fd + +def open_diag_rpmsg(): + for ctrl in sorted(glob.glob("/dev/rpmsg_ctrl*")): + try: + cfd = os.open(ctrl, os.O_RDWR) + ept = struct.pack("32sII", b"DIAG", 0xFFFFFFFF, 0xFFFFFFFF) + fcntl.ioctl(cfd, RPMSG_CREATE_EPT_IOCTL, ept) + os.close(cfd) + except Exception: + pass + for rdev in sorted(glob.glob("/dev/rpmsg[0-9]*")): + try: + return os.open(rdev, os.O_RDWR | os.O_NONBLOCK) + except Exception: + pass + return -1 + +while os.path.exists("/tmp/bananarchy_diag_active"): + gs0 = -1 + rp0 = -1 + gs1 = -1 + at0 = -1 + try: + if os.path.exists("/dev/ttyGS0"): + gs0 = open_raw_tty("/dev/ttyGS0") + rp0 = open_diag_rpmsg() + if os.path.exists("/dev/ttyACM0"): + gs1 = open_raw_tty("/dev/ttyACM0") + elif os.path.exists("/dev/ttyGS1"): + gs1 = open_raw_tty("/dev/ttyGS1") + if os.path.exists("/dev/wwan0at0"): + at0 = os.open("/dev/wwan0at0", os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) + + pairs = {} + if gs0 >= 0 and rp0 >= 0: + pairs[gs0] = rp0 + pairs[rp0] = gs0 + if gs1 >= 0 and at0 >= 0: + pairs[gs1] = at0 + pairs[at0] = gs1 + + if not pairs: + time.sleep(2) + continue + + while os.path.exists("/tmp/bananarchy_diag_active"): + rlist, _, _ = select.select(list(pairs.keys()), [], [], 2.0) + for rfd in rlist: + wfd = pairs.get(rfd, -1) + if wfd < 0: + continue + try: + data = os.read(rfd, 4096) + if data: + os.write(wfd, data) + except OSError: + pass + except Exception: + time.sleep(2) + finally: + for fd in (gs0, rp0, gs1, at0): + if fd >= 0: + try: os.close(fd) + except Exception: pass +PY +fi + +CMD="${1:-status}" + +case "$CMD" in + status) + TUN_IMEI1="" + TUN_IMEI2="" + TUN_WIFI_MAC="" + TUN_BT_MAC="" + eval "$(read_nv_info)" + + # 1. TTL status + ttl_override="0" + if [ -f "/tmp/bananarchy_ttl_override" ]; then + ttl_override="$(cat /tmp/bananarchy_ttl_override 2>/dev/null | tr -cd '0-9')" + [ -z "$ttl_override" ] && ttl_override="0" + fi + ttl_cur="$(sysctl -n net.ipv4.ip_default_ttl 2>/dev/null || echo 64)" + + # 2. IMEI 1 & 2 status + IMEI1="" + IMEI2="" + IMEI_SV="" + if [ -f "/tmp/bananarchy_imei_override" ]; then + # shellcheck disable=SC1091 + . "/tmp/bananarchy_imei_override" 2>/dev/null || true + elif [ -f "$STATE_DIR/imei_override" ]; then + # shellcheck disable=SC1090 + . "$STATE_DIR/imei_override" 2>/dev/null || true + fi + if [ -z "$IMEI1" ] && [ -n "$TUN_IMEI1" ]; then + IMEI1="$TUN_IMEI1" + fi + if [ -z "$IMEI2" ] && [ -n "$TUN_IMEI2" ]; then + IMEI2="$TUN_IMEI2" + fi + if [ -z "$IMEI1" ] || [ -z "$IMEI2" ]; then + if [ -x /usr/libexec/msm-modem-uim-selection ]; then + uim_out="$(/usr/libexec/msm-modem-uim-selection imei 2>/dev/null || true)" + m_imei1="$(printf "%s\n" "$uim_out" | sed -n 's/^IMEI1=//p' | head -n 1)" + m_imei2="$(printf "%s\n" "$uim_out" | sed -n 's/^IMEI2=//p' | head -n 1)" + [ -z "$IMEI1" ] && IMEI1="$m_imei1" + [ -z "$IMEI2" ] && IMEI2="$m_imei2" + fi + fi + [ -z "$IMEI2" ] && IMEI2="$IMEI1" + tac1="$(printf "%s" "$IMEI1" | cut -c1-8)" + tac2="$(printf "%s" "$IMEI2" | cut -c1-8)" + [ "${#tac1}" -lt 8 ] && tac1="35829909" + [ "${#tac2}" -lt 8 ] && tac2="$tac1" + + # 3. Wi-Fi MAC status + wifi_mac="$(cat /sys/class/net/wlan0/address 2>/dev/null | tr '[:upper:]' '[:lower:]' || true)" + if [ -z "$wifi_mac" ] || [ "$wifi_mac" = "00:00:00:00:00:00" ]; then + if [ -f "$CONF_DIR/wifi_mac" ]; then + wifi_mac="$(cat "$CONF_DIR/wifi_mac" 2>/dev/null || true)" + elif [ -n "$TUN_WIFI_MAC" ]; then + wifi_mac="$TUN_WIFI_MAC" + fi + fi + + # 4. Bluetooth MAC status + bt_mac="$(cat /sys/class/bluetooth/hci0/address 2>/dev/null | tr '[:upper:]' '[:lower:]' || true)" + if [ -z "$bt_mac" ] || [ "$bt_mac" = "00:00:00:00:00:00" ]; then + if [ -f "$CONF_DIR/bt_mac" ]; then + bt_mac="$(cat "$CONF_DIR/bt_mac" 2>/dev/null || true)" + elif [ -n "$TUN_BT_MAC" ]; then + bt_mac="$TUN_BT_MAC" + fi + fi + + # 5. Overclock / CPU status + oc_active="0" + if [ -f "/tmp/bananarchy_overclock_active" ]; then + oc_active="1" + fi + cpu_gov="$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_governor 2>/dev/null || cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo schedutil)" + if [ "$cpu_gov" = "performance" ]; then + oc_active="1" + fi + cur_khz="$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq 2>/dev/null || cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq 2>/dev/null || echo 800000)" + max_khz="$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_max_freq 2>/dev/null || cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq 2>/dev/null || echo 1094400)" + cpu_cur_mhz="$((cur_khz / 1000))" + cpu_max_mhz="$((max_khz / 1000))" + + # 6. DIAG port status + diag_active="0" + if [ -f "/tmp/bananarchy_diag_active" ] || [ -e "/sys/kernel/config/usb_gadget/g1/configs/c.1/gser.usb0" ]; then + diag_active="1" + fi + vid="$(cat /sys/kernel/config/usb_gadget/g1/idVendor 2>/dev/null | sed 's/^0x//' || echo 18d1)" + pid="$(cat /sys/kernel/config/usb_gadget/g1/idProduct 2>/dev/null | sed 's/^0x//' || echo d001)" + + echo "MODEL_NAME=$DEVICE_NAME" + echo "CODENAME=$DEVICE_CODENAME" + echo "NV_METHOD=$NV_METHOD" + echo "TTL_OVERRIDE=$ttl_override" + echo "TTL_CURRENT=$ttl_cur" + echo "IMEI1=$IMEI1" + echo "IMEI2=$IMEI2" + echo "TAC1=$tac1" + echo "TAC2=$tac2" + echo "DSDS_SUPPORTED=1" + echo "WIFI_MAC=${wifi_mac:---}" + echo "BT_MAC=${bt_mac:---}" + echo "OVERCLOCK_ACTIVE=$oc_active" + echo "CPU_GOV=$cpu_gov" + echo "CPU_CUR_MHZ=$cpu_cur_mhz" + echo "CPU_MAX_MHZ=$cpu_max_mhz" + echo "DIAG_ACTIVE=$diag_active" + echo "USB_PID=${vid}:${pid}" + ;; + + ttl) + val="${2:-64}" + if [ "$val" = "off" ] || [ "$val" = "reset" ] || [ "$val" = "0" ]; then + sysctl -w net.ipv4.ip_default_ttl=64 >/dev/null 2>&1 || true + sysctl -w net.ipv6.conf.all.hop_limit=64 >/dev/null 2>&1 || true + sysctl -w net.ipv6.conf.default.hop_limit=64 >/dev/null 2>&1 || true + nft delete table inet bananarchy_ttl 2>/dev/null || true + for iface in wwan0 rmnet_data0 wlan0; do + while iptables -t filter -D FORWARD -o "$iface" -j sort_out_interface 2>/dev/null; do :; done + while iptables -t filter -D OUTPUT -o "$iface" -j sort_out_interface 2>/dev/null; do :; done + done + iptables -t filter -F sort_out_interface 2>/dev/null || true + iptables -t filter -X sort_out_interface 2>/dev/null || true + while ip rule del table 164 2>/dev/null; do :; done + ip route flush table 164 2>/dev/null || true + rm -f /tmp/bananarchy_ttl_override + echo "OK: TTL override disabled (default 64)" + exit 0 + fi + case "$val" in + ''|*[!0-9]*) + echo "ERROR: Invalid TTL value" + exit 1 + ;; + esac + if [ "$val" -lt 1 ] || [ "$val" -gt 255 ]; then + echo "ERROR: TTL must be between 1 and 255" + exit 1 + fi + + for mod in nf_tables iptable_mangle iptable_filter; do + modprobe "$mod" 2>/dev/null || true + done + + sysctl -w net.ipv4.ip_default_ttl="$val" >/dev/null 2>&1 || true + sysctl -w net.ipv6.conf.all.hop_limit="$val" >/dev/null 2>&1 || true + sysctl -w net.ipv6.conf.default.hop_limit="$val" >/dev/null 2>&1 || true + + if command -v nft >/dev/null 2>&1; then + nft delete table inet bananarchy_ttl 2>/dev/null || true + nft add table inet bananarchy_ttl 2>/dev/null || true + nft 'add chain inet bananarchy_ttl mangle_post { type filter hook postrouting priority -150 ; policy accept ; }' 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"wwan*\" ip ttl set $val" 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"wwan*\" ip6 hoplimit set $val" 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"rmnet*\" ip ttl set $val" 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"rmnet*\" ip6 hoplimit set $val" 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"wlan*\" ip ttl set $val" 2>/dev/null || true + nft "add rule inet bananarchy_ttl mangle_post oifname \"wlan*\" ip6 hoplimit set $val" 2>/dev/null || true + fi + + echo "$val" > /tmp/bananarchy_ttl_override + echo "OK: TTL fixed at $val until reboot" + ;; + + set-imei) + sim="${2:-1}" + new_imei="${3:-}" + if [ "$sim" != "1" ] && [ "$sim" != "2" ]; then + echo "ERROR: Invalid SIM slot (must be 1 or 2)" + exit 1 + fi + if ! validate_imei "$new_imei"; then + echo "ERROR: Invalid 15-digit Luhn IMEI" + exit 1 + fi + + if [ "$NV_METHOD" = "tunning" ]; then + # Model family A (nokia-argon, nokia-beatles, nokia-tough): + # Wallace Toolbox / lycan-tun.py logic on /dev/disk/by-partlabel/tunning + tun_part="$(find_part tunning || true)" + if [ -z "$tun_part" ] || [ ! -b "$tun_part" ]; then + echo "ERROR: tunning partition not found" + exit 1 + fi + + backup_nv_once "$tun_part" "tunning.factory.bak" + + target_rel="nvm/num/550" + if [ "$sim" = "2" ]; then + target_rel="nvm/context1/550" + fi + + # Build nibble-swapped 9-byte Qualcomm NV 550 payload ('80a' + imei) + q_hex="$(printf "80a%s" "$new_imei" | sed 's/\(.\)\(.\)/\\x\2\1/g')" + + tmpdir="$(mktemp -d /tmp/engmenu_imei.XXXXXX)" + ( + cd "$tmpdir" || exit 1 + busybox tar xf "$tun_part" 2>/dev/null || tar xf "$tun_part" 2>/dev/null || true + mkdir -p "nvm/num" "nvm/context1" + # shellcheck disable=SC2059 + printf "$q_hex" > "$target_rel" + busybox tar cf "$tmpdir.tar" . 2>/dev/null || tar cf "$tmpdir.tar" . + ) + if [ ! -s "$tmpdir.tar" ]; then + rm -rf "$tmpdir" "$tmpdir.tar" + echo "ERROR: Failed to pack tunning archive" + exit 1 + fi + + cat "$tmpdir.tar" > "$tun_part" + rm -rf "$tmpdir" "$tmpdir.tar" + wipe_modem_efs + else + # Model family B (nokia-sparkler, nokia-leo, and other Qualcomm devices without tunning): + # Project Lycan lycan-rfnv.py logic on /dev/disk/by-partlabel/rf_nv + rfnv_part="$(find_part rf_nv || find_part rfnv || true)" + if [ -z "$rfnv_part" ] || [ ! -b "$rfnv_part" ]; then + echo "ERROR: rf_nv partition not found" + exit 1 + fi + + backup_nv_once "$rfnv_part" "rf_nv.factory.bak" + + if ! python3 - "$rfnv_part" "$sim" "$new_imei" << 'PY' +import sys +from struct import pack +from binascii import crc32 + +SIGVAL = b"IEMI" +SIGPOS = 0x80 +SIGVAL2 = b"\x92\x8a\x9a\x92" +SIGPOS2 = SIGPOS + 0x80 +IMEI1POS = SIGPOS + 8 +CRC1POS = SIGPOS + 0x14 +IMEI2POS = SIGPOS2 + 8 +CRC2POS = SIGPOS2 + 0x14 + +def nibble_invert(bytestr): + r = b"" + for b in bytestr: + c = (b >> 4) | ((b & 15) << 4) + r += bytes([c]) + return r + +def encode_imei(imeistr): + return nibble_invert(bytes.fromhex("80a" + imeistr.strip())) + +def read_imei(fh): + fh.seek(IMEI1POS) + imei1 = fh.read(9) + fh.seek(IMEI2POS) + imei2 = fh.read(9) + return imei1, imei2 + +def calc_crc(imei1, imei2): + crc1 = pack("/dev/null || true + cur_imei1="${IMEI1:-}" + cur_imei2="${IMEI2:-}" + fi + if [ -z "$cur_imei1" ] || [ -z "$cur_imei2" ]; then + eval "$(read_nv_info)" + [ -z "$cur_imei1" ] && cur_imei1="${TUN_IMEI1:-}" + [ -z "$cur_imei2" ] && cur_imei2="${TUN_IMEI2:-}" + fi + if [ "$sim" = "1" ]; then + cur_imei1="$new_imei" + else + cur_imei2="$new_imei" + fi + { + [ -n "$cur_imei1" ] && echo "IMEI1=$cur_imei1" + [ -n "$cur_imei2" ] && echo "IMEI2=$cur_imei2" + } > "$STATE_DIR/imei_override" + cp -f "$STATE_DIR/imei_override" "/tmp/bananarchy_imei_override" 2>/dev/null || true + chmod 0644 "/tmp/bananarchy_imei_override" 2>/dev/null || true + + echo "OK: IMEI${sim} changed to ${new_imei}" + ;; + + set-wifi-mac) + norm_mac="$(normalize_mac "${2:-}" || true)" + if [ -z "$norm_mac" ]; then + echo "ERROR: Invalid Wi-Fi MAC address" + exit 1 + fi + + q_payload="\\x$(printf "%s" "$norm_mac" | sed 's/:/\\x/g')" + if [ "$NV_METHOD" = "tunning" ]; then + tun_part="$(find_part tunning || true)" + if [ -n "$tun_part" ] && [ -b "$tun_part" ]; then + backup_nv_once "$tun_part" "tunning.factory.bak" + tmpdir="$(mktemp -d /tmp/engmenu_wmac.XXXXXX)" + ( + cd "$tmpdir" || exit 1 + busybox tar xf "$tun_part" 2>/dev/null || tar xf "$tun_part" 2>/dev/null || true + mkdir -p "nvm/num" + # shellcheck disable=SC2059 + printf "$q_payload" > "nvm/num/4678" + busybox tar cf "$tmpdir.tar" . 2>/dev/null || tar cf "$tmpdir.tar" . + ) + if [ -s "$tmpdir.tar" ]; then + cat "$tmpdir.tar" > "$tun_part" + wipe_modem_efs + fi + rm -rf "$tmpdir" "$tmpdir.tar" + fi + else + hex12="$(printf "%s" "$norm_mac" | tr -d ':' | tr '[:lower:]' '[:upper:]')" + if [ -d "/run/msm-firmware-loader/mnt/persist" ]; then + mount -o remount,rw "/run/msm-firmware-loader/mnt/persist" 2>/dev/null || true + printf "Intf0MacAddress=%s\nEND\n" "$hex12" > "/run/msm-firmware-loader/mnt/persist/wlan_mac.bin" 2>/dev/null || true + sync + mount -o remount,ro "/run/msm-firmware-loader/mnt/persist" 2>/dev/null || true + fi + fi + + # Persist for NetworkManager and wcn36xx wlan0 + printf "%s\n" "$norm_mac" > "$CONF_DIR/wifi_mac" + mkdir -p /etc/NetworkManager/conf.d + cat > /etc/NetworkManager/conf.d/30-wifi-mac.conf </dev/null 2>&1; then + was_up=0 + if ip link show dev wlan0 2>/dev/null | grep -q "UP"; then + was_up=1 + fi + ip link set dev wlan0 down 2>/dev/null || true + ip link set dev wlan0 address "$norm_mac" 2>/dev/null || true + if [ "$was_up" = "1" ]; then + ip link set dev wlan0 up 2>/dev/null || true + fi + nmcli general reload >/dev/null 2>&1 || true + fi + + echo "OK: Wi-Fi MAC changed to ${norm_mac}" + ;; + + set-bt-mac) + norm_mac="$(normalize_mac "${2:-}" || true)" + if [ -z "$norm_mac" ]; then + echo "ERROR: Invalid Bluetooth MAC address" + exit 1 + fi + + q_payload="\\x$(printf "%s" "$norm_mac" | sed 's/:/\\x/g')" + p_payload="\\x01\\x01\\x06${q_payload}" + + if [ "$NV_METHOD" = "tunning" ]; then + tun_part="$(find_part tunning || true)" + if [ -n "$tun_part" ] && [ -b "$tun_part" ]; then + backup_nv_once "$tun_part" "tunning.factory.bak" + tmpdir="$(mktemp -d /tmp/engmenu_bmac.XXXXXX)" + ( + cd "$tmpdir" || exit 1 + busybox tar xf "$tun_part" 2>/dev/null || tar xf "$tun_part" 2>/dev/null || true + mkdir -p "nvm/num" + # shellcheck disable=SC2059 + printf "$q_payload" > "nvm/num/447" + busybox tar cf "$tmpdir.tar" . 2>/dev/null || tar cf "$tmpdir.tar" . + ) + if [ -s "$tmpdir.tar" ]; then + cat "$tmpdir.tar" > "$tun_part" + wipe_modem_efs + fi + rm -rf "$tmpdir" "$tmpdir.tar" + fi + fi + + # Write /persist/bluetooth/.bt_nv.bin (Wallace setNokiaBluetoothMAC) + persist_part="$(find_part persist || true)" + if [ -d "/run/msm-firmware-loader/mnt/persist" ]; then + mount -o remount,rw "/run/msm-firmware-loader/mnt/persist" 2>/dev/null || true + mkdir -p "/run/msm-firmware-loader/mnt/persist/bluetooth" 2>/dev/null || true + # shellcheck disable=SC2059 + printf "$p_payload" > "/run/msm-firmware-loader/mnt/persist/bluetooth/.bt_nv.bin" 2>/dev/null || true + sync + mount -o remount,ro "/run/msm-firmware-loader/mnt/persist" 2>/dev/null || true + elif [ -n "$persist_part" ] && [ -b "$persist_part" ]; then + pmnt="$(mktemp -d /tmp/engmenu_persist.XXXXXX)" + if mount -o rw "$persist_part" "$pmnt" 2>/dev/null; then + mkdir -p "$pmnt/bluetooth" + # shellcheck disable=SC2059 + printf "$p_payload" > "$pmnt/bluetooth/.bt_nv.bin" 2>/dev/null || true + sync + umount "$pmnt" 2>/dev/null || true + fi + rmdir "$pmnt" 2>/dev/null || true + fi + if [ -d "/persist" ]; then + mkdir -p "/persist/bluetooth" 2>/dev/null || true + # shellcheck disable=SC2059 + printf "$p_payload" > "/persist/bluetooth/.bt_nv.bin" 2>/dev/null || true + fi + + printf "%s\n" "$norm_mac" > "$CONF_DIR/bt_mac" + apply_bt_mac_live "$norm_mac" + + echo "OK: Bluetooth MAC changed to ${norm_mac}" + ;; + + overclock) + mode="${2:-toggle}" + if [ "$mode" = "toggle" ]; then + if [ -f "/tmp/bananarchy_overclock_active" ]; then + mode="off" + else + mode="on" + fi + fi + + if [ "$mode" = "on" ]; then + # 1. Wallace Toolbox downstream interactive governor + msm_thermal parameters + if [ -d "/sys/devices/system/cpu/cpufreq/interactive" ]; then + echo 96 > /sys/devices/system/cpu/cpufreq/interactive/target_loads 2>/dev/null || true + echo 1094400 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq 2>/dev/null || true + echo 24 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load 2>/dev/null || true + fi + if [ -w "/sys/module/msm_thermal/core_control/enabled" ]; then + echo 0 > /sys/module/msm_thermal/core_control/enabled 2>/dev/null || true + fi + + # 2. Bring all CPU cores online and lock to peak OPP frequency (1094.4 / 1267.2 MHz) + for c in /sys/devices/system/cpu/cpu[0-9]*/online; do + [ -w "$c" ] && echo 1 > "$c" 2>/dev/null || true + done + for pol in /sys/devices/system/cpu/cpufreq/policy* /sys/devices/system/cpu/cpu[0-9]*/cpufreq; do + [ -d "$pol" ] || continue + hw_max="$(cat "$pol/cpuinfo_max_freq" 2>/dev/null || echo 1094400)" + echo "$hw_max" > "$pol/scaling_max_freq" 2>/dev/null || true + echo "performance" > "$pol/scaling_governor" 2>/dev/null || true + done + for gov_dir in /sys/devices/system/cpu/cpufreq/schedutil /sys/devices/system/cpu/cpufreq/policy*/schedutil; do + if [ -d "$gov_dir" ]; then + echo 500 > "$gov_dir/rate_limit_us" 2>/dev/null || true + echo 500 > "$gov_dir/up_rate_limit_us" 2>/dev/null || true + echo 50000 > "$gov_dir/down_rate_limit_us" 2>/dev/null || true + fi + done + + # 3. Boost Adreno 304 GPU devfreq + for gdev in /sys/class/devfreq/*gpu*; do + [ -d "$gdev" ] || continue + gmax="$(cat "$gdev/max_freq" 2>/dev/null || echo 409600000)" + echo "$gmax" > "$gdev/min_freq" 2>/dev/null || true + done + + echo "1" > /tmp/bananarchy_overclock_active + echo "OK: Overclocking until reboot" + else + for pol in /sys/devices/system/cpu/cpufreq/policy* /sys/devices/system/cpu/cpu[0-9]*/cpufreq; do + [ -d "$pol" ] || continue + hw_min="$(cat "$pol/cpuinfo_min_freq" 2>/dev/null || echo 200000)" + echo "schedutil" > "$pol/scaling_governor" 2>/dev/null || true + echo "$hw_min" > "$pol/scaling_min_freq" 2>/dev/null || true + done + for gov_dir in /sys/devices/system/cpu/cpufreq/schedutil /sys/devices/system/cpu/cpufreq/policy*/schedutil; do + if [ -d "$gov_dir" ]; then + echo 2000 > "$gov_dir/rate_limit_us" 2>/dev/null || true + echo 20000 > "$gov_dir/up_rate_limit_us" 2>/dev/null || true + echo 1000 > "$gov_dir/down_rate_limit_us" 2>/dev/null || true + fi + done + for gdev in /sys/class/devfreq/*gpu*; do + [ -d "$gdev" ] || continue + echo 19200000 > "$gdev/min_freq" 2>/dev/null || true + done + rm -f /tmp/bananarchy_overclock_active + echo "OK: Overclock disabled (schedutil restored)" + fi + ;; + + diag) + mode="${2:-toggle}" + if [ "$mode" = "toggle" ]; then + if [ -f "/tmp/bananarchy_diag_active" ] || [ -e "/sys/kernel/config/usb_gadget/g1/configs/c.1/gser.usb0" ]; then + mode="off" + else + mode="on" + fi + fi + + CONFIGFS="/sys/kernel/config/usb_gadget" + if ! [ -d "$CONFIGFS" ]; then + modprobe libcomposite 2>/dev/null || true + mount -t configfs configfs /sys/kernel/config 2>/dev/null || true + fi + udc_dev="$(ls /sys/class/udc 2>/dev/null | head -n 1 || true)" + + if [ "$mode" = "on" ]; then + for mod in usb_f_serial usb_f_acm u_serial rpmsg_wwan_ctrl; do + modprobe "$mod" 2>/dev/null || true + done + if [ -d "$CONFIGFS/g1" ]; then + echo "" > "$CONFIGFS/g1/UDC" 2>/dev/null || true + echo "0x05c6" > "$CONFIGFS/g1/idVendor" 2>/dev/null || true + echo "0x9091" > "$CONFIGFS/g1/idProduct" 2>/dev/null || true + mkdir -p "$CONFIGFS/g1/functions/gser.usb0" 2>/dev/null || true + mkdir -p "$CONFIGFS/g1/functions/acm.usb0" 2>/dev/null || true + echo "diag,serial_smd,rmnet_qti_bam,adb" > "$CONFIGFS/g1/configs/c.1/strings/0x409/configuration" 2>/dev/null || true + ln -sf "$CONFIGFS/g1/functions/gser.usb0" "$CONFIGFS/g1/configs/c.1/gser.usb0" 2>/dev/null || true + ln -sf "$CONFIGFS/g1/functions/acm.usb0" "$CONFIGFS/g1/configs/c.1/acm.usb0" 2>/dev/null || true + if [ -n "$udc_dev" ]; then + echo "$udc_dev" > "$CONFIGFS/g1/UDC" 2>/dev/null || true + fi + fi + if ip link show dev usb0 >/dev/null 2>&1; then + ip link set usb0 up 2>/dev/null || true + ip -4 addr show dev usb0 2>/dev/null | grep -q "172.16.42.1" || \ + ip addr add 172.16.42.1/16 dev usb0 2>/dev/null || true + fi + echo "1" > /tmp/bananarchy_diag_active + /usr/bin/bananarchy-engmenu-ctl _diag_worker >/dev/null 2>&1 /tmp/bananarchy_diag_bridge.pid + echo "OK: Diagnostics port enabled" + else + rm -f /tmp/bananarchy_diag_active + stop_diag_bridge + if [ -d "$CONFIGFS/g1" ]; then + echo "" > "$CONFIGFS/g1/UDC" 2>/dev/null || true + rm -f "$CONFIGFS/g1/configs/c.1/gser.usb0" "$CONFIGFS/g1/configs/c.1/acm.usb0" 2>/dev/null || true + echo "0x18D1" > "$CONFIGFS/g1/idVendor" 2>/dev/null || true + echo "0xD001" > "$CONFIGFS/g1/idProduct" 2>/dev/null || true + echo "USB network" > "$CONFIGFS/g1/configs/c.1/strings/0x409/configuration" 2>/dev/null || true + if [ -n "$udc_dev" ]; then + echo "$udc_dev" > "$CONFIGFS/g1/UDC" 2>/dev/null || true + fi + fi + if ip link show dev usb0 >/dev/null 2>&1; then + ip link set usb0 up 2>/dev/null || true + ip -4 addr show dev usb0 2>/dev/null | grep -q "172.16.42.1" || \ + ip addr add 172.16.42.1/16 dev usb0 2>/dev/null || true + fi + echo "OK: Diagnostics port disabled" + fi + ;; + + apply-boot) + # Restore persistent IMEI override cache, Wi-Fi MAC, and Bluetooth MAC on boot + if [ -s "$STATE_DIR/imei_override" ]; then + cp -f "$STATE_DIR/imei_override" "/tmp/bananarchy_imei_override" 2>/dev/null || true + chmod 0644 "/tmp/bananarchy_imei_override" 2>/dev/null || true + fi + if [ -s "$CONF_DIR/wifi_mac" ]; then + wmac="$(cat "$CONF_DIR/wifi_mac" 2>/dev/null || true)" + if [ -n "$wmac" ] && ip link show dev wlan0 >/dev/null 2>&1; then + ip link set dev wlan0 down 2>/dev/null || true + ip link set dev wlan0 address "$wmac" 2>/dev/null || true + ip link set dev wlan0 up 2>/dev/null || true + fi + fi + if [ -s "$CONF_DIR/bt_mac" ]; then + bmac="$(cat "$CONF_DIR/bt_mac" 2>/dev/null || true)" + [ -n "$bmac" ] && apply_bt_mac_live "$bmac" + fi + ;; + + reboot) + sync + reboot 2>/dev/null || busybox reboot 2>/dev/null || true + ;; + + *) + echo "Usage: $0 {status|ttl|set-imei|set-wifi-mac|set-bt-mac|overclock|diag|apply-boot|reboot}" >&2 + exit 1 + ;; +esac diff --git a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh index 1893116..922bfa5 100755 --- a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh +++ b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh @@ -20,6 +20,9 @@ on() { rc-update add bluetooth fi sleep 0.4 + if [ -s /etc/bananarchy/bt_mac ] && [ -x /usr/bin/bananarchy-engmenu-ctl ]; then + /usr/bin/bananarchy-engmenu-ctl apply-boot >/dev/null 2>&1 || true + fi timeout 2 bluetoothctl power on >/dev/null 2>&1 || true bt_name="" diff --git a/overlay/rootfs/usr/lib/dwm/plugins/dialer.so b/overlay/rootfs/usr/lib/dwm/plugins/dialer.so index 9d158ad..61af39f 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/dialer.so and b/overlay/rootfs/usr/lib/dwm/plugins/dialer.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/engmenu.so b/overlay/rootfs/usr/lib/dwm/plugins/engmenu.so index 2de0178..173e7fe 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/engmenu.so and b/overlay/rootfs/usr/lib/dwm/plugins/engmenu.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/modem.so b/overlay/rootfs/usr/lib/dwm/plugins/modem.so index 21f2c7e..882785f 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/modem.so and b/overlay/rootfs/usr/lib/dwm/plugins/modem.so differ diff --git a/overlay/rootfs/usr/lib/libtoxcore.so.2 b/overlay/rootfs/usr/lib/libtoxcore.so.2 index a12824a..c9c8293 120000 --- a/overlay/rootfs/usr/lib/libtoxcore.so.2 +++ b/overlay/rootfs/usr/lib/libtoxcore.so.2 @@ -1 +1 @@ -libtoxcore.so.2.23.0 \ No newline at end of file +libtoxcore.so.2.24.0 \ No newline at end of file diff --git a/overlay/rootfs/usr/lib/libtoxcore.so.2.24.0 b/overlay/rootfs/usr/lib/libtoxcore.so.2.24.0 new file mode 100755 index 0000000..4e1ce48 Binary files /dev/null and b/overlay/rootfs/usr/lib/libtoxcore.so.2.24.0 differ diff --git a/overlay/rootfs/usr/libexec/msm-modem-uim-selection b/overlay/rootfs/usr/libexec/msm-modem-uim-selection index ea19c63..ecc147c 100755 --- a/overlay/rootfs/usr/libexec/msm-modem-uim-selection +++ b/overlay/rootfs/usr/libexec/msm-modem-uim-selection @@ -1130,14 +1130,85 @@ PY imei1="" imei2="" imei_sv="" + if [ -s /tmp/bananarchy_imei_override ]; then + # shellcheck disable=SC1091 + . /tmp/bananarchy_imei_override 2>/dev/null || true + imei1="${IMEI1:-}" + imei2="${IMEI2:-}" + elif [ -s /var/lib/bananarchy/imei_override ]; then + # shellcheck disable=SC1091 + . /var/lib/bananarchy/imei_override 2>/dev/null || true + imei1="${IMEI1:-}" + imei2="${IMEI2:-}" + fi if detect_qmicli_modem; then dms_ids="$($QMICLI_MODEM --dms-get-ids 2>/dev/null || true)" - imei1="$(printf "%s\n" "$dms_ids" | sed -n "s/.*IMEI: '\([0-9]\{14,16\}\)'/\1/p" | head -n1)" + [ -z "$imei1" ] && imei1="$(printf "%s\n" "$dms_ids" | sed -n "s/.*IMEI: '\([0-9]\{14,16\}\)'/\1/p" | head -n1)" imei_sv="$(printf "%s\n" "$dms_ids" | sed -n "s/.*IMEI SV: '\([^']*\)'/\1/p" | head -n1)" fi if [ -z "$imei1" ]; then imei1="$(mmcli -m any -K 2>/dev/null | awk -F': ' '/modem\.3gpp\.imei/ {print $2; exit}')" fi + # Decode NV 550 (SIM1) and context1/550 (SIM2) from tunning tar partition if present + if { [ -z "$imei1" ] || [ -z "$imei2" ]; } && [ -e /dev/disk/by-partlabel/tunning ] && command -v python3 >/dev/null 2>&1; then + eval "$(python3 - /dev/disk/by-partlabel/tunning << 'PY' 2>/dev/null || true +import sys, tarfile +def dec(d): + if not d or len(d) < 9 or d[0] != 0x08 or (d[1] & 0x0F) != 0x0A: return "" + s = str((d[1] >> 4) & 0x0F) + "".join(f"{b & 0x0F}{(b >> 4) & 0x0F}" for b in d[2:9]) + return s if s.isdigit() and len(s) == 15 else "" +try: + with tarfile.open(sys.argv[1], "r:*") as tf: + for m in tf.getmembers(): + n = m.name.lstrip("./") + if n == "nvm/num/550": + v = dec(tf.extractfile(m).read()) + if v: print(f"TUN1={v}") + elif n == "nvm/context1/550": + v = dec(tf.extractfile(m).read()) + if v: print(f"TUN2={v}") +except Exception: + pass +PY +)" + [ -z "$imei1" ] && [ -n "${TUN1:-}" ] && imei1="$TUN1" + [ -z "$imei2" ] && [ -n "${TUN2:-}" ] && imei2="$TUN2" + fi + # Decode IMEI1 (0x88) and IMEI2 (0x108) from rf_nv partition (nokia-sparkler, nokia-leo, etc.) + if { [ -z "$imei1" ] || [ -z "$imei2" ]; } && { [ -e /dev/disk/by-partlabel/rf_nv ] || [ -e /dev/disk/by-partlabel/rfnv ]; } && command -v python3 >/dev/null 2>&1; then + rfnv_dev="/dev/disk/by-partlabel/rf_nv" + [ -e "$rfnv_dev" ] || rfnv_dev="/dev/disk/by-partlabel/rfnv" + eval "$(python3 - "$rfnv_dev" << 'PY' 2>/dev/null || true +import sys +SIGVAL = b"IEMI" +SIGPOS = 0x80 +SIGVAL2 = b"\x92\x8a\x9a\x92" +SIGPOS2 = SIGPOS + 0x80 +def dec(d): + if not d or len(d) < 9: return "" + inv = bytes(((b >> 4) | ((b & 15) << 4)) for b in d[:9]) + s = inv.hex()[3:] + return s if len(s) == 15 and s.isdigit() else "" +try: + with open(sys.argv[1], "rb") as fh: + fh.seek(SIGPOS) + v1 = fh.read(4) + fh.seek(SIGPOS2) + v2 = fh.read(4) + if v1 == SIGVAL and v2 == SIGVAL2: + fh.seek(SIGPOS + 8) + i1 = dec(fh.read(9)) + fh.seek(SIGPOS2 + 8) + i2 = dec(fh.read(9)) + if i1: print(f"RFNV1={i1}") + if i2: print(f"RFNV2={i2}") +except Exception: + pass +PY +)" + [ -z "$imei1" ] && [ -n "${RFNV1:-}" ] && imei1="$RFNV1" + [ -z "$imei2" ] && [ -n "${RFNV2:-}" ] && imei2="$RFNV2" + fi # Query secondary AT channel (/dev/wwan0at1) if present if [ -c "/dev/wwan0at1" ]; then at_out="$(timeout 1 sh -c ' diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so index 9d158ad..61af39f 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so index 2de0178..173e7fe 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so index 21f2c7e..882785f 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 index a12824a..c9c8293 120000 --- a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 +++ b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 @@ -1 +1 @@ -libtoxcore.so.2.23.0 \ No newline at end of file +libtoxcore.so.2.24.0 \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.24.0 b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.24.0 new file mode 100755 index 0000000..4e1ce48 Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.24.0 differ diff --git a/scripts/apply-bananarchy-overlay.sh b/scripts/apply-bananarchy-overlay.sh index c4ca6d6..ba313b3 100755 --- a/scripts/apply-bananarchy-overlay.sh +++ b/scripts/apply-bananarchy-overlay.sh @@ -55,6 +55,7 @@ if command -v docker >/dev/null 2>&1; then [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/bin/dwm" ] || \ [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/bin/st" ] || \ [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so" ] || \ + [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so" ] || \ [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/privacy.so" ]; then echo " -> Missing prebuilt sxmo-x11/NeoUI artifacts; running scripts/build-sxmo-x11.sh..." "$BASE_DIR/scripts/build-sxmo-x11.sh" @@ -170,6 +171,8 @@ if [ -d "$BASE_DIR/prebuilt/sxmo-x11/usr" ]; then fi chown 0:0 "$TARGET_ROOTFS/usr/bin/bananarchy-engmenu-exec" 2>/dev/null || true chmod 4755 "$TARGET_ROOTFS/usr/bin/bananarchy-engmenu-exec" 2>/dev/null || true +chown 0:0 "$TARGET_ROOTFS/usr/bin/bananarchy-engmenu-ctl" 2>/dev/null || true +chmod 0755 "$TARGET_ROOTFS/usr/bin/bananarchy-engmenu-ctl" 2>/dev/null || true if [ -d "$BASE_DIR/prebuilt/games/usr" ]; then cp -af "$BASE_DIR/prebuilt/games/usr/." "$TARGET_ROOTFS/usr/" fi diff --git a/src/dwm-plugins/engmenu_plugin.cpp b/src/dwm-plugins/engmenu_plugin.cpp index 34071dd..994c7d0 100644 --- a/src/dwm-plugins/engmenu_plugin.cpp +++ b/src/dwm-plugins/engmenu_plugin.cpp @@ -1,5 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only // Bananarchy Engineering Menu DWM Plugin (240x320) +// Ports Qualcomm MSM8905/MSM8909 ("qualcommonly") and Nokia NVRAM ("imeionly") +// features from Wallace Toolbox into a zero-lag NeoUI resident daemon. #include #include @@ -11,12 +13,15 @@ #include #include +#include +#include #include #include #include #include #include #include +#include #include #include #include @@ -25,6 +30,10 @@ #include "../sxmo-dwm/dwm_plugin.h" #include "phone_data.h" +#ifdef None +#undef None +#endif + namespace { using namespace bananarchy; @@ -35,57 +44,232 @@ void handleSignal(int) { gRunning = 0; } -struct EngMenuItem { - std::string title; - std::string subtitle; - std::string command; - bool runInTerminal = true; +enum class EngModal { + None, + ConfirmImei1, + ConfirmImei2, + ConfirmReboot, + EditTtl, + EditImei1, + EditImei2, + EditWifiMac, + EditBtMac }; -void launchEngItemAsRoot(const EngMenuItem& item) { +struct EngStatus { + std::string codename = "nokia-argon"; + std::string modelName = "Nokia 8110 4G"; + std::string nvMethod = "tunning"; + int ttlOverride = 0; + int ttlCurrent = 64; + std::string imei1; + std::string imei2; + std::string tac1 = "35829909"; + std::string tac2 = "35829909"; + bool dsdsSupported = true; + std::string wifiMac = "--"; + std::string btMac = "--"; + bool overclockActive = false; + std::string cpuGov = "schedutil"; + int cpuCurMhz = 800; + int cpuMaxMhz = 1094; + bool diagActive = false; + std::string usbPid = "18d1:d001"; +}; + +// Calculate 15th Luhn check digit from the first 14 digits (Wallace calcIMEIChecksum) +int calcImeiChecksum(const std::string& imei14) { + if (imei14.size() < 14) return -1; + static constexpr int kRevMap[10] = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}; + int oddSum = 0; + int evenSum = 0; + for (int i = 0; i < 14; ++i) { + char c = imei14[static_cast(i)]; + if (c < '0' || c > '9') return -1; + int d = c - '0'; + if ((i % 2) == 0) { + oddSum += d; + } else { + evenSum += kRevMap[d]; + } + } + int luhn = 10 - ((oddSum + evenSum) % 10); + return (luhn > 9) ? 0 : luhn; +} + +bool isValidImei15(const std::string& imei) { + if (imei.size() != 15) return false; + for (char c : imei) { + if (c < '0' || c > '9') return false; + } + int expected = calcImeiChecksum(imei); + return expected >= 0 && (imei[14] - '0') == expected; +} + +// Generate a random 6-byte locally-administered unicast MAC address (Wallace generateRandomMAC) +std::string generateRandomMac(const std::string& prefix = "") { + std::string hexPref; + for (char c : prefix) { + char lc = static_cast(std::tolower(static_cast(c))); + if ((lc >= '0' && lc <= '9') || (lc >= 'a' && lc <= 'f')) { + if (hexPref.size() < 12) hexPref.push_back(lc); + } + } + unsigned char rnd[12] {}; + int ufd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC); + if (ufd >= 0) { + (void)::read(ufd, rnd, sizeof(rnd)); + ::close(ufd); + } + static constexpr char kHex[17] = "0123456789abcdef"; + std::string raw = hexPref; + for (size_t i = hexPref.size(); i < 12; ++i) { + unsigned int nib = rnd[i] & 0x0Fu; + if (i == 1 && hexPref.size() < 2) { + // Ensure locally-administered unicast MAC (bit 0 = 0, bit 1 = 1 -> 2, 6, a, e) + nib = (nib & 0x0Cu) | 0x02u; + } + raw.push_back(kHex[nib]); + } + std::string out; + for (size_t i = 0; i < 12; i += 2) { + if (i > 0) out.push_back(':'); + out.push_back(raw[i]); + out.push_back(raw[i + 1]); + } + return out; +} + +std::string extractHexDigits(const std::string& s) { + std::string hex; + for (char c : s) { + char lc = static_cast(std::tolower(static_cast(c))); + if ((lc >= '0' && lc <= '9') || (lc >= 'a' && lc <= 'f')) { + if (hex.size() < 12) hex.push_back(lc); + } + } + return hex; +} + +std::string formatMacFromHex(const std::string& hex) { + std::string out; + for (size_t i = 0; i < hex.size() && i < 12; ++i) { + if (i > 0 && (i % 2) == 0) { + out.push_back(':'); + } + out.push_back(hex[i]); + } + return out; +} + +std::string runEngCtlCapture(const std::vector& args) { if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0 || - isPhonePasscodeLocked() || item.command.empty()) { - return; + isPhonePasscodeLocked()) { + return ""; + } + int pipefd[2]; + if (::pipe(pipefd) != 0) { + return ""; } pid_t pid = ::fork(); - if (pid == 0) { - if (::fork() == 0) { - ::setsid(); - int nullfd = ::open("/dev/null", O_RDWR); - if (nullfd >= 0) { - ::dup2(nullfd, STDIN_FILENO); - ::dup2(nullfd, STDOUT_FILENO); - ::dup2(nullfd, STDERR_FILENO); - if (nullfd > 2) { - ::close(nullfd); - } - } - if (item.runInTerminal) { - ::execl("/usr/bin/bananarchy-engmenu-exec", "bananarchy-engmenu-exec", - "--term", item.title.c_str(), item.command.c_str(), - static_cast(nullptr)); - ::execl("/usr/bin/doas", "doas", "-n", - "/usr/bin/bananarchy-engmenu-exec", "--term", - item.title.c_str(), item.command.c_str(), - static_cast(nullptr)); - } else { - ::execl("/usr/bin/bananarchy-engmenu-exec", "bananarchy-engmenu-exec", - "--exec", item.command.c_str(), static_cast(nullptr)); - ::execl("/usr/bin/doas", "doas", "-n", - "/usr/bin/bananarchy-engmenu-exec", "--exec", - item.command.c_str(), static_cast(nullptr)); - } - ::_exit(0); - } - ::_exit(0); - } else if (pid > 0) { - int st = 0; - (void)::waitpid(pid, &st, 0); + if (pid < 0) { + ::close(pipefd[0]); + ::close(pipefd[1]); + return ""; } + if (pid == 0) { + ::close(pipefd[0]); + ::dup2(pipefd[1], STDOUT_FILENO); + if (pipefd[1] != STDOUT_FILENO) { + ::close(pipefd[1]); + } + int nullfd = ::open("/dev/null", O_RDWR); + if (nullfd >= 0) { + ::dup2(nullfd, STDIN_FILENO); + ::dup2(nullfd, STDERR_FILENO); + if (nullfd > 2) { + ::close(nullfd); + } + } + std::vector argv; + argv.push_back(const_cast("doas")); + argv.push_back(const_cast("-n")); + argv.push_back(const_cast("/usr/bin/bananarchy-engmenu-ctl")); + for (const auto& a : args) { + argv.push_back(const_cast(a.c_str())); + } + argv.push_back(nullptr); + ::execvp("/usr/bin/doas", argv.data()); + + // Fallback via suid bananarchy-engmenu-exec + std::string cmdLine = "/usr/bin/bananarchy-engmenu-ctl"; + for (const auto& a : args) { + cmdLine += " " + shellQuote(a); + } + ::execl("/usr/bin/bananarchy-engmenu-exec", "bananarchy-engmenu-exec", + "--exec", cmdLine.c_str(), static_cast(nullptr)); + ::_exit(127); + } + ::close(pipefd[1]); + std::string out; + char buf[512]; + ssize_t n; + while ((n = ::read(pipefd[0], buf, sizeof(buf))) > 0) { + out.append(buf, static_cast(n)); + } + ::close(pipefd[0]); + int st = 0; + (void)::waitpid(pid, &st, 0); + return trimStr(out); +} + +EngStatus queryEngStatus() { + EngStatus st; + std::string raw = runEngCtlCapture({"status"}); + std::istringstream ss(raw); + std::string line; + while (std::getline(ss, line)) { + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + size_t eq = line.find('='); + if (eq == std::string::npos) continue; + std::string k = line.substr(0, eq); + std::string v = line.substr(eq + 1); + if (k == "CODENAME") st.codename = v; + else if (k == "MODEL_NAME") st.modelName = v; + else if (k == "NV_METHOD") st.nvMethod = v; + else if (k == "TTL_OVERRIDE") st.ttlOverride = std::atoi(v.c_str()); + else if (k == "TTL_CURRENT") st.ttlCurrent = std::atoi(v.c_str()); + else if (k == "IMEI1") st.imei1 = v; + else if (k == "IMEI2") st.imei2 = v; + else if (k == "TAC1" && v.size() >= 8) st.tac1 = v.substr(0, 8); + else if (k == "TAC2" && v.size() >= 8) st.tac2 = v.substr(0, 8); + else if (k == "DSDS_SUPPORTED") st.dsdsSupported = (v != "0"); + else if (k == "WIFI_MAC") st.wifiMac = v; + else if (k == "BT_MAC") st.btMac = v; + else if (k == "OVERCLOCK_ACTIVE") st.overclockActive = (v == "1"); + else if (k == "CPU_GOV") st.cpuGov = v; + else if (k == "CPU_CUR_MHZ") st.cpuCurMhz = std::atoi(v.c_str()); + else if (k == "CPU_MAX_MHZ") st.cpuMaxMhz = std::atoi(v.c_str()); + else if (k == "DIAG_ACTIVE") st.diagActive = (v == "1"); + else if (k == "USB_PID") st.usbPid = v; + } + if (st.imei1.empty() || st.imei2.empty()) { + DeviceImeis devIm = queryDeviceImeis(); + if (st.imei1.empty()) st.imei1 = devIm.imei1; + if (st.imei2.empty()) st.imei2 = devIm.imei2; + if (st.imei1.size() >= 8) st.tac1 = st.imei1.substr(0, 8); + if (st.imei2.size() >= 8) st.tac2 = st.imei2.substr(0, 8); + } + return st; } int engmenu_run_main(int argc, char** argv) { gRunning = 1; + std::setlocale(LC_ALL, ""); + XSetLocaleModifiers(""); + bool isPreload = false; for (int i = 1; i < argc; ++i) { if (argv[i] && std::strcmp(argv[i], "--preload") == 0) { @@ -144,14 +328,91 @@ int engmenu_run_main(int argc, char** argv) { PangoLayout* layoutSmall = neo.layoutSmall; PluginTheme& theme = neo.theme; - // Intentionally empty for now; each item added here runs as root via - // /usr/bin/bananarchy-engmenu-exec (--term or --exec). - std::vector items; + EngStatus status; + EngModal modal = EngModal::None; + std::string editBuf; + std::string rebootPromptMsg; + int lastHexKey = -1; + int lastHexCycle = 0; + int64_t lastHexMs = 0; + + std::string toastMsg; + int64_t toastUntilMs = 0; bool visible = false; int selIdx = 0; int scrollIdx = 0; + auto showToast = [&](const std::string& msg, int durationMs = 2400) { + toastMsg = msg; + toastUntilMs = nowMs() + durationMs; + }; + + auto refreshStatus = [&]() { + status = queryEngStatus(); + }; + + struct MenuRow { + std::string keyTag; + std::string title; + std::string subtitle; + std::string badge; + int badgeStyle = 0; // 0 = muted, 1 = green, 2 = yellow, 3 = red + }; + + auto buildRows = [&]() -> std::vector { + std::vector rows; + + bool isRfnv = (status.nvMethod == "rfnv"); + + // 1. [4] Override TTL (qualcommonly) + std::string ttlSub = (status.ttlOverride > 0) + ? ("Fixed at TTL " + std::to_string(status.ttlOverride) + " until reboot") + : ("Default TTL " + std::to_string(status.ttlCurrent) + " (tether & wwan0)"); + std::string ttlBadge = (status.ttlOverride > 0) + ? ("TTL " + std::to_string(status.ttlOverride)) + : "Def 64"; + rows.push_back({"4", "4: Override TTL", ttlSub, ttlBadge, + status.ttlOverride > 0 ? 1 : 0}); + + // 2. [5] Edit IMEI1 (imeionly danger) + std::string im1Sub = "SIM 1: " + (status.imei1.empty() ? std::string("--") : status.imei1); + rows.push_back({"5", "5: Edit IMEI 1", im1Sub, + isRfnv ? "rf_nv" : "NV 550", 3}); + + // 3. [6] Edit IMEI2 (imeionly sim2only danger) + std::string im2Sub = "SIM 2: " + (status.imei2.empty() ? std::string("--") : status.imei2); + rows.push_back({"6", "6: Edit IMEI 2", im2Sub, + isRfnv ? "rf_nv" : "Ctx 1", 3}); + + // 4. [*] Run overclock script (qualcommonly) + std::string ocSub = status.cpuGov + " @ " + + std::to_string(status.cpuCurMhz) + "/" + + std::to_string(status.cpuMaxMhz) + " MHz"; + rows.push_back({"*", "*: Run Overclock Script", ocSub, + status.overclockActive ? "ON" : "OFF", + status.overclockActive ? 1 : 0}); + + // 5. [0] Toggle DIAG port (qualcommonly) + std::string diagSub = "USB " + status.usbPid + + (status.diagActive ? " (DIAG+AT+NCM)" : " (USB Net)"); + rows.push_back({"0", "0: Toggle DIAG Port", diagSub, + status.diagActive ? "ON" : "OFF", + status.diagActive ? 1 : 0}); + + // 6. [Call] Edit Wi-Fi MAC (imeionly) + std::string wmacSub = "wlan0: " + status.wifiMac; + rows.push_back({"Call", "Call: Edit Wi-Fi MAC", wmacSub, + isRfnv ? "persist" : "NV 4678", 2}); + + // 7. [7] Edit Bluetooth MAC (imeionly) + std::string bmacSub = "hci0: " + status.btMac; + rows.push_back({"7", "7: Edit Bluetooth MAC", bmacSub, + isRfnv ? "persist" : "NV 447", 2}); + + return rows; + }; + auto openWindow = [&]() { if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0 || isPhonePasscodeLocked()) { @@ -159,8 +420,8 @@ int engmenu_run_main(int argc, char** argv) { } closeOtherPlugins("engmenu"); writeIntFile(activePidPath, static_cast(::getpid())); - selIdx = 0; - scrollIdx = 0; + modal = EngModal::None; + refreshStatus(); if (!visible) { XMapRaised(dpy, win); XMoveResizeWindow(dpy, win, kWinX, kWinY, kWinWidth, kWinHeight); @@ -176,9 +437,50 @@ int engmenu_run_main(int argc, char** argv) { XFlush(dpy); visible = false; } + modal = EngModal::None; ::unlink(activePidPath.c_str()); }; + auto triggerRowAction = [&](int idx) { + if (idx == 0) { + // 4: Override TTL + editBuf = (status.ttlOverride > 0) ? std::to_string(status.ttlOverride) : "64"; + modal = EngModal::EditTtl; + } else if (idx == 1) { + // 5: Edit IMEI 1 + modal = EngModal::ConfirmImei1; + } else if (idx == 2) { + // 6: Edit IMEI 2 + if (!status.dsdsSupported) { + showToast("Error: single-SIM configuration"); + return; + } + modal = EngModal::ConfirmImei2; + } else if (idx == 3) { + // *: Run Overclock Script + std::string res = runEngCtlCapture({"overclock", "toggle"}); + refreshStatus(); + showToast(status.overclockActive ? "Overclocking until reboot" + : "Overclock disabled (schedutil)"); + } else if (idx == 4) { + // 0: Toggle DIAG Port + std::string res = runEngCtlCapture({"diag", "toggle"}); + refreshStatus(); + showToast(status.diagActive ? "Diagnostics port enabled" + : "Diagnostics port disabled"); + } else if (idx == 5) { + // Call: Edit Wi-Fi MAC + editBuf = generateRandomMac(); + lastHexKey = -1; + modal = EngModal::EditWifiMac; + } else if (idx == 6) { + // 7: Edit Bluetooth MAC + editBuf = generateRandomMac(); + lastHexKey = -1; + modal = EngModal::EditBtMac; + } + }; + auto render = [&]() { if (!visible) { return; @@ -189,68 +491,235 @@ int engmenu_run_main(int argc, char** argv) { neo.drawPango(neo.layoutIcon, &theme.colYellow, 6, 0, 26, kIconSliders); neo.drawPango(layoutMain, &theme.colWhite, 28, 0, 26, "Engineering Menu", 160); - int rbw = neo.pangoWidth(layoutSmall, "ROOT"); + std::string hdrBadge = (status.nvMethod == "rfnv") ? "RFNV" : "TUN"; + int rbw = neo.pangoWidth(layoutSmall, hdrBadge); neo.drawPango(layoutSmall, &theme.colRed, kWinWidth - rbw - 8, 0, 26, - "ROOT"); + hdrBadge); XSetForeground(dpy, gc, theme.spec.border); XDrawLine(dpy, pix, gc, 0, 25, kWinWidth, 25); - if (items.empty()) { - int cardX = 14; - int cardY = 86; - int cardW = kWinWidth - 28; - int cardH = 92; - XSetForeground(dpy, gc, theme.spec.bgAltOdd); - XFillRectangle(dpy, pix, gc, cardX, cardY, cardW, cardH); - XSetForeground(dpy, gc, theme.spec.border); - XDrawRectangle(dpy, pix, gc, cardX, cardY, cardW - 1, cardH - 1); - - neo.drawPango(layoutMain, &theme.colYellow, cardX + 8, cardY + 14, 22, - "Engineering Mode", cardW - 16, 1); - neo.drawPango(layoutSmall, &theme.colMuted, cardX + 8, cardY + 40, 18, - "No applets configured", cardW - 16, 1); - neo.drawPango(layoutSmall, &theme.colMuted, cardX + 8, cardY + 60, 18, - "Root runner ready (suid)", cardW - 16, 1); - } else { - constexpr int kRowY = 28; - constexpr int kRowH = 38; - constexpr int kMaxRows = 6; - if (selIdx < scrollIdx) { - scrollIdx = selIdx; - } else if (selIdx >= scrollIdx + kMaxRows) { - scrollIdx = selIdx - kMaxRows + 1; - } - for (int r = 0; r < kMaxRows; ++r) { - int idx = scrollIdx + r; - if (idx >= static_cast(items.size())) { - break; - } - int ry = kRowY + r * kRowH; - bool selected = (idx == selIdx); - uint32_t rowBg = selected - ? theme.spec.selBg - : ((idx % 2 == 0) ? theme.spec.bgAltEven - : theme.spec.bgAltOdd); - XSetForeground(dpy, gc, rowBg); - XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, kRowH); - XSetForeground(dpy, gc, theme.spec.border); - XDrawLine(dpy, pix, gc, 0, ry + kRowH - 1, kWinWidth, ry + kRowH - 1); - - const auto& it = items[idx]; - neo.drawPango(layoutMain, - selected ? &theme.colWhite : &theme.colLight, - 8, ry + 2, 20, it.title, kWinWidth - 16); - neo.drawPango(layoutSmall, - selected ? &theme.colYellow : &theme.colMuted, - 8, ry + 20, 16, it.subtitle, kWinWidth - 16); - } - neo.drawScrollbar(kWinWidth - 4, kRowY, kMaxRows * kRowH, - static_cast(items.size()), kMaxRows, scrollIdx); + std::vector rows = buildRows(); + constexpr int kRowY = 26; + constexpr int kRowH = 40; + constexpr int kMaxRows = 6; + if (selIdx < scrollIdx) { + scrollIdx = selIdx; + } else if (selIdx >= scrollIdx + kMaxRows) { + scrollIdx = selIdx - kMaxRows + 1; } - neo.drawSoftbar(items.empty() ? "" : "Run", - items.empty() ? "" : "Exec", - "Close", &theme.colYellow); + for (int r = 0; r < kMaxRows; ++r) { + int idx = scrollIdx + r; + if (idx >= static_cast(rows.size())) { + break; + } + int ry = kRowY + r * kRowH; + bool selected = (idx == selIdx); + uint32_t rowBg = selected + ? theme.spec.selBg + : ((idx % 2 == 0) ? theme.spec.bgAltEven + : theme.spec.bgAltOdd); + XSetForeground(dpy, gc, rowBg); + XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, kRowH); + XSetForeground(dpy, gc, theme.spec.border); + XDrawLine(dpy, pix, gc, 0, ry + kRowH - 1, kWinWidth, ry + kRowH - 1); + + const auto& it = rows[static_cast(idx)]; + int badgeW = neo.pangoWidth(layoutSmall, it.badge) + 10; + int badgeX = kWinWidth - badgeW - 8; + int badgeY = ry + 4; + int badgeH = 16; + + uint32_t badgeBg = theme.spec.bgButton; + XftColor* badgeCol = &theme.colMuted; + if (it.badgeStyle == 1) { + badgeBg = blendRgb(theme.spec.bgButton, theme.spec.success, 35); + badgeCol = &theme.colGreen; + } else if (it.badgeStyle == 2) { + badgeCol = &theme.colYellow; + } else if (it.badgeStyle == 3) { + badgeBg = theme.spec.dangerBg; + badgeCol = &theme.colRed; + } + XSetForeground(dpy, gc, badgeBg); + XFillRectangle(dpy, pix, gc, badgeX, badgeY, badgeW, badgeH); + XSetForeground(dpy, gc, theme.spec.border); + XDrawRectangle(dpy, pix, gc, badgeX, badgeY, badgeW - 1, badgeH - 1); + neo.drawPango(layoutSmall, badgeCol, badgeX, badgeY, badgeH, + it.badge, badgeW, 1); + + neo.drawPango(layoutMain, + selected ? &theme.colWhite : &theme.colLight, + 8, ry + 2, 20, it.title, badgeX - 12); + neo.drawPango(layoutSmall, + selected ? &theme.colYellow : &theme.colMuted, + 8, ry + 21, 16, it.subtitle, kWinWidth - 16); + } + + neo.drawScrollbar(kWinWidth - 4, kRowY, kMaxRows * kRowH, + static_cast(rows.size()), kMaxRows, scrollIdx); + + // Modal overlays + if (modal == EngModal::ConfirmImei1 || modal == EngModal::ConfirmImei2 || + modal == EngModal::ConfirmReboot) { + int mx = 10; + int my = 58; + int mw = kWinWidth - 20; + int mh = 156; + XSetForeground(dpy, gc, theme.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, mx, my, mw, mh); + XSetForeground(dpy, gc, theme.spec.danger); + XDrawRectangle(dpy, pix, gc, mx, my, mw - 1, mh - 1); + XSetForeground(dpy, gc, theme.spec.dangerBg); + XFillRectangle(dpy, pix, gc, mx + 1, my + 1, mw - 2, 24); + + if (modal == EngModal::ConfirmReboot) { + std::string nvUpdStr = (status.nvMethod == "rfnv") + ? "rf_nv / persist & EFS updated." + : "NVRAM tunning & EFS updated."; + neo.drawPango(layoutMain, &theme.colYellow, mx + 8, my + 2, 22, + "Reboot to Apply?", mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colWhite, mx + 8, my + 36, 18, + rebootPromptMsg, mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colMuted, mx + 8, my + 66, 18, + nvUpdStr, mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colMuted, mx + 8, my + 88, 18, + "Reboot now to reload baseband?", mw - 16, 1); + neo.drawSoftbar("Reboot", "Reboot", "Later", &theme.colYellow); + } else { + std::string slotStr = (modal == EngModal::ConfirmImei1) ? "IMEI 1" : "IMEI 2"; + std::string nvLine1 = (status.nvMethod == "rfnv") + ? "Writes rf_nv (IEMI + CRC32) &" + : "Writes NV 550 in tunning &"; + neo.drawPango(layoutMain, &theme.colRed, mx + 8, my + 2, 22, + "Change " + slotStr + "?", mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colWhite, mx + 8, my + 34, 18, + "Are you sure you really want", mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colWhite, mx + 8, my + 54, 18, + "to change " + slotStr + "?", mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colYellow, mx + 8, my + 82, 16, + nvLine1, mw - 16, 1); + neo.drawPango(layoutSmall, &theme.colYellow, mx + 8, my + 100, 16, + "resets modemst1/modemst2 EFS.", mw - 16, 1); + neo.drawSoftbar("Yes", "Confirm", "Cancel", &theme.colRed); + } + neo.present(); + return; + } + + if (modal == EngModal::EditTtl || modal == EngModal::EditImei1 || + modal == EngModal::EditImei2 || modal == EngModal::EditWifiMac || + modal == EngModal::EditBtMac) { + int mx = 8; + int my = 44; + int mw = kWinWidth - 16; + int mh = 186; + XSetForeground(dpy, gc, theme.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, mx, my, mw, mh); + XSetForeground(dpy, gc, theme.spec.accent); + XDrawRectangle(dpy, pix, gc, mx, my, mw - 1, mh - 1); + XSetForeground(dpy, gc, theme.spec.bgHeader); + XFillRectangle(dpy, pix, gc, mx + 1, my + 1, mw - 2, 24); + + std::string mTitle; + std::string mHint1; + std::string mHint2; + XftColor* statusCol = &theme.colMuted; + + if (modal == EngModal::EditTtl) { + mTitle = "Override Outbound TTL"; + mHint1 = "1..255 = fixed TTL (64 or 65)"; + mHint2 = "0 = disable override | #: cycle"; + statusCol = &theme.colYellow; + } else if (modal == EngModal::EditImei1 || modal == EngModal::EditImei2) { + if (status.nvMethod == "rfnv") { + mTitle = (modal == EngModal::EditImei1) ? "New IMEI 1 (rf_nv)" + : "New IMEI 2 (rf_nv)"; + } else { + mTitle = (modal == EngModal::EditImei1) ? "New IMEI 1 (NV 550)" + : "New IMEI 2 (Ctx1/550)"; + } + if (editBuf.size() == 15) { + int chk = calcImeiChecksum(editBuf); + if (chk >= 0 && (editBuf[14] - '0') == chk) { + mHint1 = "Luhn Checksum: VALID (15 digits)"; + statusCol = &theme.colGreen; + } else { + mHint1 = "Invalid Luhn (expected " + std::to_string(chk) + ")"; + statusCol = &theme.colRed; + } + } else if (editBuf.size() == 14) { + int chk = calcImeiChecksum(editBuf); + mHint1 = "14 digits (press # to add Luhn " + std::to_string(chk) + ")"; + statusCol = &theme.colYellow; + } else { + mHint1 = "Digits: " + std::to_string(editBuf.size()) + "/15"; + statusCol = &theme.colYellow; + } + mHint2 = "*: Backspace | #: Random / Luhn"; + } else { + if (status.nvMethod == "rfnv") { + mTitle = (modal == EngModal::EditWifiMac) ? "New Wi-Fi MAC (persist)" + : "New Bluetooth MAC (persist)"; + } else { + mTitle = (modal == EngModal::EditWifiMac) ? "New Wi-Fi MAC (NV 4678)" + : "New Bluetooth MAC (NV 447)"; + } + std::string hex = extractHexDigits(editBuf); + if (hex.size() == 12) { + mHint1 = "Valid 6-byte MAC (12 hex digits)"; + statusCol = &theme.colGreen; + } else { + mHint1 = "Hex digits: " + std::to_string(hex.size()) + "/12 (2=abc, 3=def)"; + statusCol = &theme.colYellow; + } + mHint2 = "*: Backspace | #: Random MAC"; + } + + neo.drawPango(layoutMain, &theme.colYellow, mx + 8, my + 2, 22, + mTitle, mw - 16); + + // Input box + int ibx = mx + 8; + int iby = my + 38; + int ibw = mw - 16; + int ibh = 34; + XSetForeground(dpy, gc, theme.spec.bgMain); + XFillRectangle(dpy, pix, gc, ibx, iby, ibw, ibh); + XSetForeground(dpy, gc, theme.spec.accent); + XDrawRectangle(dpy, pix, gc, ibx, iby, ibw - 1, ibh - 1); + neo.drawPango(layoutMain, &theme.colWhite, ibx + 6, iby + 5, 24, + editBuf + "_", ibw - 12); + + neo.drawPango(layoutSmall, statusCol, mx + 8, my + 84, 18, + mHint1, mw - 16); + neo.drawPango(layoutSmall, &theme.colMuted, mx + 8, my + 108, 16, + mHint2, mw - 16); + neo.drawPango(layoutSmall, &theme.colMuted, mx + 8, my + 130, 16, + "LSK/OK: Apply | RSK: Cancel", mw - 16); + + neo.drawSoftbar("Apply", "Save", "Cancel", &theme.colGreen); + neo.present(); + return; + } + + if (!toastMsg.empty() && nowMs() < toastUntilMs) { + int ty = kWinHeight - 24 - 24; + XSetForeground(dpy, gc, theme.spec.bgHeader); + XFillRectangle(dpy, pix, gc, 4, ty, kWinWidth - 8, 22); + XSetForeground(dpy, gc, theme.spec.accent); + XDrawRectangle(dpy, pix, gc, 4, ty, kWinWidth - 9, 21); + neo.drawPango(layoutSmall, &theme.colYellow, 8, ty + 2, 18, + toastMsg, kWinWidth - 16, 1); + } + + std::string lskLabel = "Select"; + if (selIdx == 0 || selIdx == 1 || selIdx == 2 || selIdx == 5 || selIdx == 6) { + lskLabel = "Edit"; + } else if (selIdx == 3 || selIdx == 4) { + lskLabel = "Toggle"; + } + neo.drawSoftbar(lskLabel, "Run", "Close", &theme.colYellow); neo.present(); }; @@ -311,7 +780,9 @@ int engmenu_run_main(int argc, char** argv) { continue; } unsigned int kc = ev.xkey.keycode; + unsigned int kstate = ev.xkey.state; KeySym sym = XLookupKeysym(&ev.xkey, 0); + char dch = mapDialKey(sym, kc, kstate); if (querySoftkeysDown(dpy) == 3) { writeSoftkeySuppress(nowMs() + 400); @@ -326,6 +797,201 @@ int engmenu_run_main(int argc, char** argv) { continue; } + // Handle confirmation modals + if (modal == EngModal::ConfirmImei1 || modal == EngModal::ConfirmImei2 || + modal == EngModal::ConfirmReboot) { + if (isRightSoftkey(sym, kc) || sym == XK_Escape || + sym == XK_BackSpace || sym == XF86XK_HangupPhone || + sym == XK_Cancel) { + writeSoftkeySuppress(nowMs() + 250); + modal = EngModal::None; + render(); + continue; + } + if (isLeftSoftkey(sym, kc) || sym == XK_Return || + sym == XK_KP_Enter) { + if (modal == EngModal::ConfirmImei1) { + editBuf = generateRandomImeiFromTac(status.tac1); + modal = EngModal::EditImei1; + } else if (modal == EngModal::ConfirmImei2) { + editBuf = generateRandomImeiFromTac(status.tac2); + modal = EngModal::EditImei2; + } else if (modal == EngModal::ConfirmReboot) { + modal = EngModal::None; + closeWindow(); + runEngCtlCapture({"reboot"}); + continue; + } + render(); + continue; + } + continue; + } + + // Handle input editor modals + if (modal == EngModal::EditTtl || modal == EngModal::EditImei1 || + modal == EngModal::EditImei2 || modal == EngModal::EditWifiMac || + modal == EngModal::EditBtMac) { + if (isRightSoftkey(sym, kc) || sym == XK_Escape || + sym == XF86XK_HangupPhone || sym == XK_Cancel) { + writeSoftkeySuppress(nowMs() + 250); + modal = EngModal::None; + render(); + continue; + } + + if (isLeftSoftkey(sym, kc) || sym == XK_Return || + sym == XK_KP_Enter) { + if (modal == EngModal::EditTtl) { + int val = editBuf.empty() ? -1 : std::atoi(editBuf.c_str()); + if (val == 0) { + runEngCtlCapture({"ttl", "0"}); + modal = EngModal::None; + refreshStatus(); + showToast("TTL override disabled"); + } else if (val >= 1 && val <= 255) { + runEngCtlCapture({"ttl", std::to_string(val)}); + modal = EngModal::None; + refreshStatus(); + showToast("TTL fixed at " + std::to_string(val) + " until reboot"); + } else { + showToast("Invalid TTL value (1..255)"); + } + } else if (modal == EngModal::EditImei1 || modal == EngModal::EditImei2) { + std::string slot = (modal == EngModal::EditImei1) ? "1" : "2"; + if (!isValidImei15(editBuf)) { + showToast("Error: invalid IMEI"); + } else { + std::string out = runEngCtlCapture({"set-imei", slot, editBuf}); + refreshStatus(); + if (out.rfind("OK:", 0) == 0) { + rebootPromptMsg = "IMEI" + slot + ": " + editBuf; + modal = EngModal::ConfirmReboot; + } else { + modal = EngModal::None; + showToast(out.empty() ? "Error setting IMEI" : out); + } + } + } else if (modal == EngModal::EditWifiMac || modal == EngModal::EditBtMac) { + std::string hex = extractHexDigits(editBuf); + if (hex.size() != 12) { + showToast("Error: invalid MAC"); + } else { + std::string formatted = formatMacFromHex(hex); + std::string subcmd = (modal == EngModal::EditWifiMac) + ? "set-wifi-mac" + : "set-bt-mac"; + std::string out = runEngCtlCapture({subcmd, formatted}); + refreshStatus(); + if (out.rfind("OK:", 0) == 0) { + rebootPromptMsg = "MAC: " + formatted; + modal = EngModal::ConfirmReboot; + } else { + modal = EngModal::None; + showToast(out.empty() ? "Error setting MAC" : out); + } + } + } + render(); + continue; + } + + // Backspace / '*' inside editor modals + if (dch == '*' || sym == XK_BackSpace || sym == XK_Delete || + sym == XK_Left || sym == XK_KP_Left) { + if (modal == EngModal::EditWifiMac || modal == EngModal::EditBtMac) { + std::string hex = extractHexDigits(editBuf); + if (!hex.empty()) { + hex.pop_back(); + } + editBuf = formatMacFromHex(hex); + lastHexKey = -1; + } else if (!editBuf.empty()) { + editBuf.pop_back(); + } + render(); + continue; + } + + // '#' action inside editor modals + if (dch == '#') { + if (modal == EngModal::EditTtl) { + if (editBuf == "64") editBuf = "65"; + else if (editBuf == "65") editBuf = "128"; + else if (editBuf == "128") editBuf = "0"; + else editBuf = "64"; + } else if (modal == EngModal::EditImei1 || modal == EngModal::EditImei2) { + if (editBuf.size() == 14) { + int chk = calcImeiChecksum(editBuf); + if (chk >= 0) { + editBuf.push_back(static_cast('0' + chk)); + } + } else { + const std::string& tac = (modal == EngModal::EditImei1) + ? status.tac1 + : status.tac2; + editBuf = generateRandomImeiFromTac(tac); + } + } else if (modal == EngModal::EditWifiMac || modal == EngModal::EditBtMac) { + editBuf = generateRandomMac(); + lastHexKey = -1; + } + render(); + continue; + } + + // Digit / hex entry inside editor modals + if (dch >= '0' && dch <= '9') { + if (modal == EngModal::EditTtl) { + if (editBuf.size() < 3) { + if (editBuf == "0") editBuf.clear(); + editBuf.push_back(dch); + } + } else if (modal == EngModal::EditImei1 || modal == EngModal::EditImei2) { + if (editBuf.size() < 15) { + editBuf.push_back(dch); + } + } else if (modal == EngModal::EditWifiMac || modal == EngModal::EditBtMac) { + static constexpr const char* kHexMap[10] = { + "0", "1", "2abc", "3def", "4", "5", "6", "7", "8", "9" + }; + int digit = dch - '0'; + const char* seq = kHexMap[digit]; + int seqLen = static_cast(std::strlen(seq)); + int64_t now = nowMs(); + std::string hex = extractHexDigits(editBuf); + if (seqLen > 1 && digit == lastHexKey && + (now - lastHexMs) <= 800 && !hex.empty()) { + lastHexCycle = (lastHexCycle + 1) % seqLen; + hex.back() = seq[lastHexCycle]; + } else if (hex.size() < 12) { + lastHexKey = digit; + lastHexCycle = 0; + hex.push_back(seq[0]); + } + lastHexMs = now; + editBuf = formatMacFromHex(hex); + } + render(); + continue; + } + + // Direct hex letter keys a-f if typed via XIM or keyboard + if ((modal == EngModal::EditWifiMac || modal == EngModal::EditBtMac) && + ((sym >= XK_a && sym <= XK_f) || (sym >= XK_A && sym <= XK_F))) { + std::string hex = extractHexDigits(editBuf); + if (hex.size() < 12) { + hex.push_back(static_cast(std::tolower(static_cast(sym)))); + editBuf = formatMacFromHex(hex); + lastHexKey = -1; + render(); + } + continue; + } + continue; + } + + // Main menu view key handling if (isRightSoftkey(sym, kc) || sym == XK_Escape || sym == XK_BackSpace || sym == XF86XK_HangupPhone || sym == XK_Cancel) { @@ -334,39 +1000,87 @@ int engmenu_run_main(int argc, char** argv) { continue; } - if (!items.empty()) { - if (sym == XK_Up || sym == XK_KP_Up) { - selIdx = (selIdx > 0) ? (selIdx - 1) - : (static_cast(items.size()) - 1); - render(); - continue; - } - if (sym == XK_Down || sym == XK_KP_Down) { - selIdx = (selIdx + 1 < static_cast(items.size())) - ? (selIdx + 1) - : 0; - render(); - continue; - } - if (isLeftSoftkey(sym, kc) || sym == XK_Return || - sym == XK_KP_Enter) { - if (selIdx >= 0 && selIdx < static_cast(items.size())) { - EngMenuItem chosen = items[selIdx]; - closeWindow(); - launchEngItemAsRoot(chosen); - } - continue; - } + constexpr int kNumItems = 7; + if (sym == XK_Up || sym == XK_KP_Up) { + selIdx = (selIdx > 0) ? (selIdx - 1) : (kNumItems - 1); + render(); + continue; + } + if (sym == XK_Down || sym == XK_KP_Down) { + selIdx = (selIdx + 1 < kNumItems) ? (selIdx + 1) : 0; + render(); + continue; + } + + if (isLeftSoftkey(sym, kc) || sym == XK_Return || + sym == XK_KP_Enter) { + triggerRowAction(selIdx); + render(); + continue; + } + + // Direct Wallace Toolbox hotkeys (4, 5, 6, *, 0, Call, 7/#) + if (sym == XF86XK_Phone || sym == XF86XK_PickupPhone || + sym == XF86XK_Send) { + selIdx = 5; + triggerRowAction(5); + render(); + continue; + } + if (dch == '4') { + selIdx = 0; + triggerRowAction(0); + render(); + continue; + } + if (dch == '5') { + selIdx = 1; + triggerRowAction(1); + render(); + continue; + } + if (dch == '6') { + selIdx = 2; + triggerRowAction(2); + render(); + continue; + } + if (dch == '*') { + selIdx = 3; + triggerRowAction(3); + render(); + continue; + } + if (dch == '0') { + selIdx = 4; + triggerRowAction(4); + render(); + continue; + } + if (dch == '7' || dch == '#') { + selIdx = 6; + triggerRowAction(6); + render(); + continue; } } } + int timeoutMs = -1; + if (visible && !toastMsg.empty() && nowMs() < toastUntilMs) { + timeoutMs = static_cast(std::max(50, toastUntilMs - nowMs())); + } + struct pollfd pfds[2] {}; pfds[0].fd = xfd; pfds[0].events = POLLIN; pfds[1].fd = fifoFd; pfds[1].events = POLLIN; - ::poll(pfds, (fifoFd >= 0) ? 2 : 1, -1); + int pr = ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); + if (pr == 0 && visible && !toastMsg.empty() && nowMs() >= toastUntilMs) { + toastMsg.clear(); + render(); + } } closeWindow(); diff --git a/src/dwm-plugins/phone_data.h b/src/dwm-plugins/phone_data.h index 418b285..974a9e1 100644 --- a/src/dwm-plugins/phone_data.h +++ b/src/dwm-plugins/phone_data.h @@ -2596,12 +2596,31 @@ inline DeviceImeis queryDeviceImeis() { return cachedDuress; } + const char* kOverrideImeiFile = "/tmp/bananarchy_imei_override"; + std::string ovrImei1; + std::string ovrImei2; + { + std::ifstream oin(kOverrideImeiFile); + std::string oline; + while (std::getline(oin, oline)) { + if (oline.rfind("IMEI1=", 0) == 0) { + ovrImei1 = trimStr(oline.substr(6)); + } else if (oline.rfind("IMEI2=", 0) == 0) { + ovrImei2 = trimStr(oline.substr(6)); + } + } + } + if (!cached.imei1.empty() && !cached.imei2.empty()) { + if (!ovrImei1.empty()) cached.imei1 = ovrImei1; + if (!ovrImei2.empty()) cached.imei2 = ovrImei2; return cached; } DeviceImeis res = cached; queryQrtrDmsImeis(res); + if (!ovrImei1.empty()) res.imei1 = ovrImei1; + if (!ovrImei2.empty()) res.imei2 = ovrImei2; if (res.imei1.empty() || res.imei2.empty()) { std::string helperOut = runCaptureCmd(