Add NeoUI passcode configurator, duress mode profile, and Bluetooth OBEX UI

This commit is contained in:
Luxferre committed 2026-10-30 19:28:31 +02:00
1 parent 51a1a91d42
commit 62ac46e498
100 files changed
+2736 -240

No files matched your search

+4
View File
@@ -39,6 +39,10 @@ permit nopass :wheel as root cmd /usr/bin/sxmo_sdcard.sh
permit nopass :wheel as root cmd sxmo_sdcard.sh permit nopass :wheel as root cmd sxmo_sdcard.sh
permit nopass :wheel as root cmd /usr/bin/bananarchy-verify-passcode 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 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-bt-obex
permit nopass :wheel as root cmd bananarchy-bt-obex
permit nopass :wheel as root cmd /usr/bin/plymouth args quit permit nopass :wheel as root cmd /usr/bin/plymouth args quit
permit nopass :wheel as root cmd plymouth args quit permit nopass :wheel as root cmd plymouth args quit
permit nopass :wheel as root cmd rc-service args hexagonrpcd-adsp-sensorspd stop permit nopass :wheel as root cmd rc-service args hexagonrpcd-adsp-sensorspd stop
+117
View File
@@ -0,0 +1,117 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-only
# Activates Bananarchy Duress Mode (blank profile in /tmp/duress_home,
# Nordic theme & wallpaper, SD card unmounted, restricted apps disabled).
export DISPLAY="${DISPLAY:-:0}"
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/10000}"
# Cache real TAC before switching if not already cached
if [ ! -f /tmp/bananarchy_real_tac ]; then
doas -n /usr/libexec/msm-modem-uim-selection imei 2>/dev/null | \
awk -F= '/^IMEI[12]=/ && length($2) >= 8 { print substr($2, 1, 8) }' > /tmp/bananarchy_real_tac.tmp 2>/dev/null || true
if [ -s /tmp/bananarchy_real_tac.tmp ]; then
mv -f /tmp/bananarchy_real_tac.tmp /tmp/bananarchy_real_tac
else
rm -f /tmp/bananarchy_real_tac.tmp
fi
fi
printf '1\n' > /tmp/bananarchy_duress_mode
chmod 0644 /tmp/bananarchy_duress_mode 2>/dev/null || true
# Generate session-persistent Luhn-valid random IMEIs from the device TAC
if [ ! -s /tmp/bananarchy_duress_imei ]; then
TAC1="$(sed -n '1p' /tmp/bananarchy_real_tac 2>/dev/null | tr -cd '0-9' | cut -c1-8)"
TAC2="$(sed -n '2p' /tmp/bananarchy_real_tac 2>/dev/null | tr -cd '0-9' | cut -c1-8)"
[ "${#TAC1}" -ne 8 ] && TAC1="35829909"
[ "${#TAC2}" -ne 8 ] && TAC2="$TAC1"
S1="$(od -An -N4 -tu4 /dev/urandom 2>/dev/null | tr -d ' ')"
S2="$(od -An -N4 -tu4 /dev/urandom 2>/dev/null | tr -d ' ')"
awk -v t1="$TAC1" -v t2="$TAC2" -v s1="${S1:-12345}" -v s2="${S2:-67890}" '
function gen_imei(tac, seed, snr, body, sum, i, d, chk) {
srand(seed)
snr = sprintf("%06d", int(rand() * 900000) + 100000)
body = substr(tac, 1, 8) snr
sum = 0
for (i = 1; i <= 14; i++) {
d = substr(body, i, 1) + 0
if (i % 2 == 0) {
d = d * 2
if (d > 9) d -= 9
}
sum += d
}
chk = (10 - (sum % 10)) % 10
return body chk
}
BEGIN {
i1 = gen_imei(t1, s1 + 0)
i2 = gen_imei(t2, s2 + 17)
if (i2 == i1) i2 = gen_imei(t2, s2 + 99991)
printf "IMEI1=%s\nIMEI2=%s\nIMEI_SV=01\n", i1, i2
}
' > /tmp/bananarchy_duress_imei
fi
# Unmount SD card immediately
doas -n /usr/bin/sxmo_sdcard.sh --force-unmount >/dev/null 2>&1 || true
# Initialize clean blank profile directory
DURESS_HOME="/tmp/duress_home"
rm -rf "$DURESS_HOME" 2>/dev/null || true
mkdir -p \
"$DURESS_HOME/Desktop" \
"$DURESS_HOME/Documents" \
"$DURESS_HOME/Downloads" \
"$DURESS_HOME/Music" \
"$DURESS_HOME/Pictures" \
"$DURESS_HOME/Projects" \
"$DURESS_HOME/Videos" \
"$DURESS_HOME/.config/sxmo" \
"$DURESS_HOME/.config/dunst" \
"$DURESS_HOME/.local/share/sxmo/modem" \
"$DURESS_HOME/.local/share/sxmo/block" \
"$DURESS_HOME/.local/share/sxmo/notifications" \
"$DURESS_HOME/.cache/sxmo" \
"$DURESS_HOME/.local/state" \
"$DURESS_HOME/.xthemes"
: > "$DURESS_HOME/.config/sxmo/contacts.tsv"
: > "$DURESS_HOME/.config/sxmo/block.tsv"
: > "$DURESS_HOME/.local/share/sxmo/modem/modemlog.tsv"
: > "$DURESS_HOME/.local/share/sxmo/block/modemlog.tsv"
# Clear active notification files
rm -rf "$XDG_RUNTIME_DIR/sxmo_notifications"/* 2>/dev/null || true
# Set Nordic theme (NordFrost.xth) and nordic-peaks.png wallpaper only
NORD_SRC="/etc/skel/.xthemes/NordFrost.xth"
[ ! -r "$NORD_SRC" ] && NORD_SRC="/home/user/.xthemes/NordFrost.xth"
if [ -r "$NORD_SRC" ]; then
cp -f "$NORD_SRC" "$DURESS_HOME/.xthemes/NordFrost.xth"
cp -f "$NORD_SRC" "$DURESS_HOME/.Xresources"
fi
printf '/usr/share/wallpapers/nordic-peaks.png\n' > "$DURESS_HOME/.config/sxmo/wallpaper"
printf 'fill\n' > "$DURESS_HOME/.config/sxmo/wallpaper_mode"
if [ -r "$DURESS_HOME/.Xresources" ]; then
xrdb -load "$DURESS_HOME/.Xresources" >/dev/null 2>&1 || true
fi
feh --no-fehbg --bg-fill /usr/share/wallpapers/nordic-peaks.png >/dev/null 2>&1 </dev/null &
# Terminate any open terminals and restricted apps
pkill -9 -x st >/dev/null 2>&1 || true
# Notify all plugins to close overlays and reload theme/profile
for p in dmenu xdrawer passcode tox irc sip engmenu dialer calllog contacts sms files camera themes modem networks ringtones wallpapers music email smallweb gps; do
fifo="/tmp/dwm_plugin_${p}.fifo"
if [ -p "$fifo" ]; then
printf 'CLOSE\nRELOAD_THEME\n' > "$fifo" 2>/dev/null || true
fi
done
/usr/bin/bananarchy-sync-dunst-theme >/dev/null 2>&1 &
dunstctl close-all >/dev/null 2>&1 || true
exit 0
Binary file not shown.
Binary file not shown.
@@ -123,6 +123,7 @@ while [ "$(cat "$SESSION_PID_FILE" 2>/dev/null)" = "$$" ]; do
exit 0 exit 0
fi fi
xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true
/usr/bin/bananarchy-sync-dunst-theme --no-restart >/dev/null 2>&1 || true
WP_FILE="/usr/share/wallpapers/bananarchy.png" WP_FILE="/usr/share/wallpapers/bananarchy.png"
if [ -f "$XDG_CONFIG_HOME/sxmo/wallpaper" ]; then if [ -f "$XDG_CONFIG_HOME/sxmo/wallpaper" ]; then
custom_wp="$(head -n 1 "$XDG_CONFIG_HOME/sxmo/wallpaper" 2>/dev/null)" custom_wp="$(head -n 1 "$XDG_CONFIG_HOME/sxmo/wallpaper" 2>/dev/null)"
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -1
View File
@@ -225,7 +225,8 @@ $icon_phl Modem Log^0^sxmo_modemlog.sh"
bt_is_unblocked_fast && _bt_icon="$icon_ton" bt_is_unblocked_fast && _bt_icon="$icon_ton"
_susp_icon="$icon_ton" _susp_icon="$icon_ton"
[ -e "${XDG_CACHE_HOME:-$HOME/.cache}/sxmo/sxmo.nosuspend" ] && _susp_icon="$icon_tof" [ -e "${XDG_CACHE_HOME:-$HOME/.cache}/sxmo/sxmo.nosuspend" ] && _susp_icon="$icon_tof"
CHOICES="$icon_cfg Themes^0^xthemes CHOICES="$icon_plk Passcode^0^xpasscode
$icon_cfg Themes^0^xthemes
$icon_aru Brightness^1^sxmo_brightness.sh up $icon_aru Brightness^1^sxmo_brightness.sh up
$icon_ard Brightness^1^sxmo_brightness.sh down $icon_ard Brightness^1^sxmo_brightness.sh down
$icon_bth Bluetooth $_bt_icon^1^doas sxmo_bluetoothtoggle.sh && sxmo_hook_statusbar.sh bluetooth $icon_bth Bluetooth $_bt_icon^1^doas sxmo_bluetoothtoggle.sh && sxmo_hook_statusbar.sh bluetooth
+13
View File
@@ -5,6 +5,19 @@
# This script is meant to be sourced by various sxmo scripts # This script is meant to be sourced by various sxmo scripts
# and defines some common settings # and defines some common settings
if [ -e /tmp/bananarchy_duress_mode ]; then
export HOME="/tmp/duress_home"
export XDG_CONFIG_HOME="/tmp/duress_home/.config"
export XDG_DATA_HOME="/tmp/duress_home/.local/share"
export XDG_CACHE_HOME="/tmp/duress_home/.cache"
export XDG_STATE_HOME="/tmp/duress_home/.local/state"
export SXMO_CONTACTFILE="/tmp/duress_home/.config/sxmo/contacts.tsv"
export SXMO_BLOCKFILE="/tmp/duress_home/.config/sxmo/block.tsv"
export SXMO_BLOCKDIR="/tmp/duress_home/.local/share/sxmo/block"
export SXMO_LOGDIR="/tmp/duress_home/.local/share/sxmo/modem"
export SXMO_NOTIFDIR="/tmp/duress_home/.local/share/sxmo/notifications"
fi
export HOME="${HOME:-/home/user}" export HOME="${HOME:-/home/user}"
export DISPLAY="${DISPLAY:-:0}" export DISPLAY="${DISPLAY:-:0}"
export SXMO_WM="${SXMO_WM:-dwm}" export SXMO_WM="${SXMO_WM:-dwm}"
+53 -4
View File
@@ -76,6 +76,9 @@ find_sd_part() {
} }
probe_controller() { probe_controller() {
if [ -f /tmp/bananarchy_duress_mode ]; then
return 1
fi
if [ -b /dev/mmcblk1 ]; then if [ -b /dev/mmcblk1 ]; then
return 0 return 0
fi fi
@@ -91,11 +94,18 @@ probe_controller() {
sleep 0.1 sleep 0.1
i="$(( i + 1 ))" i="$(( i + 1 ))"
done done
if [ ! -b /dev/mmcblk1 ]; then
printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true
fi
fi fi
[ -b /dev/mmcblk1 ] [ -b /dev/mmcblk1 ]
} }
do_mount() { do_mount() {
if [ -f /tmp/bananarchy_duress_mode ]; then
rm -f "$STATE_FILE" 2>/dev/null || true
return 1
fi
if [ "$(id -u)" -ne 0 ]; then if [ "$(id -u)" -ne 0 ]; then
exec doas /usr/bin/sxmo_sdcard.sh mount "$@" exec doas /usr/bin/sxmo_sdcard.sh mount "$@"
fi fi
@@ -178,16 +188,30 @@ do_unmount() {
exec doas /usr/bin/sxmo_sdcard.sh unmount "$@" exec doas /usr/bin/sxmo_sdcard.sh unmount "$@"
fi fi
force_mode=0
if [ "${1:-}" = "--force-unmount" ]; then
force_mode=1
fi
sync sync
if ! is_mounted; then if ! is_mounted; then
rm -f "$STATE_FILE" 2>/dev/null || true rm -f "$STATE_FILE" 2>/dev/null || true
if [ "$force_mode" -eq 1 ] && [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then
printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true
fi
printf "SD card is not mounted\n" printf "SD card is not mounted\n"
return 0 return 0
fi fi
if umount "$MOUNT_POINT" 2>/dev/null || umount -l "$MOUNT_POINT" 2>/dev/null; then if umount "$MOUNT_POINT" 2>/dev/null || umount -l "$MOUNT_POINT" 2>/dev/null; then
rm -f "$STATE_FILE" 2>/dev/null || true rm -f "$STATE_FILE" 2>/dev/null || true
notify_user "SD Card" "Safely unmounted $MOUNT_POINT" if [ "$force_mode" -eq 1 ]; then
if [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then
printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true
fi
else
notify_user "SD Card" "Safely unmounted $MOUNT_POINT"
fi
printf "Unmounted %s\n" "$MOUNT_POINT" printf "Unmounted %s\n" "$MOUNT_POINT"
return 0 return 0
fi fi
@@ -197,6 +221,10 @@ do_unmount() {
} }
do_rescan() { do_rescan() {
if [ -f /tmp/bananarchy_duress_mode ]; then
rm -f "$STATE_FILE" 2>/dev/null || true
return 1
fi
if [ "$(id -u)" -ne 0 ]; then if [ "$(id -u)" -ne 0 ]; then
exec doas /usr/bin/sxmo_sdcard.sh rescan exec doas /usr/bin/sxmo_sdcard.sh rescan
fi fi
@@ -212,6 +240,11 @@ do_rescan() {
} }
do_status() { do_status() {
if [ -f /tmp/bananarchy_duress_mode ]; then
rm -f "$STATE_FILE" 2>/dev/null || true
printf "absent\n"
return 0
fi
if is_mounted; then if is_mounted; then
printf "1\n" > "$STATE_FILE" 2>/dev/null || true printf "1\n" > "$STATE_FILE" 2>/dev/null || true
dev="$(findmnt -rn -o SOURCE "$MOUNT_POINT" 2>/dev/null || printf "/dev/mmcblk1p1")" dev="$(findmnt -rn -o SOURCE "$MOUNT_POINT" 2>/dev/null || printf "/dev/mmcblk1p1")"
@@ -233,6 +266,9 @@ do_status() {
} }
do_menu() { do_menu() {
if [ -f /tmp/bananarchy_duress_mode ]; then
exit 0
fi
. sxmo_hook_icons.sh . sxmo_hook_icons.sh
. sxmo_common.sh . sxmo_common.sh
@@ -280,10 +316,10 @@ case "$cmd" in
do_status do_status
;; ;;
is_mounted|ismounted) is_mounted|ismounted)
is_mounted [ ! -f /tmp/bananarchy_duress_mode ] && is_mounted
;; ;;
is_present|ispresent) is_present|ispresent)
find_sd_part >/dev/null 2>&1 [ ! -f /tmp/bananarchy_duress_mode ] && find_sd_part >/dev/null 2>&1
;; ;;
mount) mount)
do_mount "$@" do_mount "$@"
@@ -291,6 +327,9 @@ case "$cmd" in
unmount|umount|eject) unmount|umount|eject)
do_unmount "$@" do_unmount "$@"
;; ;;
--force-unmount)
do_unmount --force-unmount
;;
rescan|detect|probe) rescan|detect|probe)
do_rescan do_rescan
;; ;;
@@ -299,11 +338,16 @@ case "$cmd" in
kname="${2:-}" kname="${2:-}"
case "$act" in case "$act" in
add|boot) add|boot)
if [ -f /tmp/bananarchy_duress_mode ]; then
exit 0
fi
if [ -n "$kname" ]; then if [ -n "$kname" ]; then
do_mount "/dev/$kname" >/dev/null 2>&1 || true do_mount "/dev/$kname" >/dev/null 2>&1 || true
else else
if find_sd_part >/dev/null 2>&1; then if find_sd_part >/dev/null 2>&1; then
do_mount >/dev/null 2>&1 || true do_mount >/dev/null 2>&1 || true
elif [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then
printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true
fi fi
fi fi
;; ;;
@@ -311,7 +355,12 @@ case "$cmd" in
if [ "$(id -u)" -eq 0 ]; then if [ "$(id -u)" -eq 0 ]; then
umount -l "$MOUNT_POINT" 2>/dev/null || true umount -l "$MOUNT_POINT" 2>/dev/null || true
rm -f "$STATE_FILE" 2>/dev/null || true rm -f "$STATE_FILE" 2>/dev/null || true
notify_user "SD Card" "SD card removed" if [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then
printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true
fi
if [ ! -f /tmp/bananarchy_duress_mode ]; then
notify_user "SD Card" "SD card removed"
fi
fi fi
;; ;;
esac esac
+4
View File
@@ -8,6 +8,10 @@ export CHARSET=UTF-8
export LANG=C.UTF-8 export LANG=C.UTF-8
export LC_ALL=C.UTF-8 export LC_ALL=C.UTF-8
if [ -f /tmp/bananarchy_duress_mode ]; then
exit 1
fi
SXMO_TERMINAL="${SXMO_TERMINAL:-st}" SXMO_TERMINAL="${SXMO_TERMINAL:-st}"
if [ -z "$*" ]; then if [ -z "$*" ]; then
+1
View File
@@ -0,0 +1 @@
dwm-plugin
+1
View File
@@ -0,0 +1 @@
dwm-plugin
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
dwm-plugin
+1
View File
@@ -0,0 +1 @@
dwm-plugin
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -1
View File
@@ -159,7 +159,8 @@ EOF
"$ROOTFS/usr/bin/chsh" \ "$ROOTFS/usr/bin/chsh" \
"$ROOTFS/usr/bin/chfn" \ "$ROOTFS/usr/bin/chfn" \
"$ROOTFS/usr/bin/chage" \ "$ROOTFS/usr/bin/chage" \
"$ROOTFS/usr/bin/expiry"; do "$ROOTFS/usr/bin/expiry" \
"$ROOTFS/usr/bin/bananarchy-engmenu-exec"; do
if [ -e "$suid_bin" ] && [ ! -L "$suid_bin" ]; then if [ -e "$suid_bin" ] && [ ! -L "$suid_bin" ]; then
chmod 4755 "$suid_bin" chmod 4755 "$suid_bin"
fi fi
+5
View File
@@ -52,6 +52,9 @@ mkdir -p "$TARGET_ROOTFS/home/user/.local/share/sxmo/modem" \
chown -R 10000:10000 "$TARGET_ROOTFS/home/user" 2>/dev/null || true chown -R 10000:10000 "$TARGET_ROOTFS/home/user" 2>/dev/null || true
chown 0:0 "$TARGET_ROOTFS/etc/doas.d/50-sxmo.conf" 2>/dev/null || true chown 0:0 "$TARGET_ROOTFS/etc/doas.d/50-sxmo.conf" 2>/dev/null || true
chmod 640 "$TARGET_ROOTFS/etc/doas.d/50-sxmo.conf" 2>/dev/null || true chmod 640 "$TARGET_ROOTFS/etc/doas.d/50-sxmo.conf" 2>/dev/null || true
mkdir -p "$TARGET_ROOTFS/etc/bananarchy"
chown 0:0 "$TARGET_ROOTFS/etc/bananarchy" 2>/dev/null || true
chmod 0700 "$TARGET_ROOTFS/etc/bananarchy" 2>/dev/null || true
chown 0:0 "$TARGET_ROOTFS/usr/bin/sudo" "$TARGET_ROOTFS/usr/bin/doas" "$TARGET_ROOTFS/bin/su" 2>/dev/null || true chown 0:0 "$TARGET_ROOTFS/usr/bin/sudo" "$TARGET_ROOTFS/usr/bin/doas" "$TARGET_ROOTFS/bin/su" 2>/dev/null || true
chmod 4755 "$TARGET_ROOTFS/usr/bin/sudo" "$TARGET_ROOTFS/usr/bin/doas" "$TARGET_ROOTFS/bin/su" 2>/dev/null || true chmod 4755 "$TARGET_ROOTFS/usr/bin/sudo" "$TARGET_ROOTFS/usr/bin/doas" "$TARGET_ROOTFS/bin/su" 2>/dev/null || true
@@ -90,6 +93,8 @@ fi
if [ -d "$BASE_DIR/prebuilt/sxmo-x11/usr" ]; then if [ -d "$BASE_DIR/prebuilt/sxmo-x11/usr" ]; then
cp -af "$BASE_DIR/prebuilt/sxmo-x11/usr/." "$TARGET_ROOTFS/usr/" cp -af "$BASE_DIR/prebuilt/sxmo-x11/usr/." "$TARGET_ROOTFS/usr/"
fi 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
if [ -d "$BASE_DIR/prebuilt/games/usr" ]; then if [ -d "$BASE_DIR/prebuilt/games/usr" ]; then
cp -af "$BASE_DIR/prebuilt/games/usr/." "$TARGET_ROOTFS/usr/" cp -af "$BASE_DIR/prebuilt/games/usr/." "$TARGET_ROOTFS/usr/"
fi fi
+21 -1
View File
@@ -226,6 +226,16 @@ EOF
-o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/gps.so & -o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/gps.so &
pids="$pids $!" pids="$pids $!"
$CXX $CXX_PLUG_FLAGS $PLUG_INCS \
/bananarchy/src/dwm-plugins/passcode_plugin.cpp $NEOUI_LIBS $PLUG_LIBS \
-o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/passcode.so &
pids="$pids $!"
$CXX $CXX_PLUG_FLAGS $PLUG_INCS \
/bananarchy/src/dwm-plugins/engmenu_plugin.cpp $NEOUI_LIBS $PLUG_LIBS \
-o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so &
pids="$pids $!"
for pid in $pids; do for pid in $pids; do
wait "$pid" wait "$pid"
done done
@@ -255,7 +265,9 @@ EOF
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so \ /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so \
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so \ /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so \
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/smallweb.so \ /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/smallweb.so \
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/gps.so /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/gps.so \
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/passcode.so \
/bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/engmenu.so
$CC $OPT_CFLAGS -std=c99 -D_DEFAULT_SOURCE -Wall -Wextra \ $CC $OPT_CFLAGS -std=c99 -D_DEFAULT_SOURCE -Wall -Wextra \
/bananarchy/src/dwm-plugins/dwm_plugin_runner.c -ldl \ /bananarchy/src/dwm-plugins/dwm_plugin_runner.c -ldl \
@@ -272,6 +284,12 @@ EOF
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode $STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode
$CC $OPT_CFLAGS -std=c99 -D_DEFAULT_SOURCE -Wall -Wextra \
/bananarchy/src/dwm-plugins/engmenu_exec.c \
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-engmenu-exec
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-engmenu-exec
chmod 4755 /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-engmenu-exec
$CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra \ $CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra \
/bananarchy/src/dwm-plugins/bananarchy_melody.cpp -lm \ /bananarchy/src/dwm-plugins/bananarchy_melody.cpp -lm \
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody
@@ -309,6 +327,8 @@ EOF
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xgps ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xgps
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xmaps ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xmaps
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xnav ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xnav
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xpasscode
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xengmenu
mkdir -p /bananarchy/overlay/rootfs/usr/bin /bananarchy/overlay/rootfs/usr/lib/dwm/plugins /bananarchy/overlay/rootfs/usr/include mkdir -p /bananarchy/overlay/rootfs/usr/bin /bananarchy/overlay/rootfs/usr/lib/dwm/plugins /bananarchy/overlay/rootfs/usr/include
cp -a /bananarchy/prebuilt/sxmo-x11/usr/bin/. /bananarchy/overlay/rootfs/usr/bin/ cp -a /bananarchy/prebuilt/sxmo-x11/usr/bin/. /bananarchy/overlay/rootfs/usr/bin/
+1
View File
@@ -745,6 +745,7 @@ int calllog_run_main(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall, theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall,
layoutIcon, nullptr, win); layoutIcon, nullptr, win);
reloadLogsIfNeeded(true);
render(); render();
} }
} }
+7 -6
View File
@@ -61,13 +61,14 @@ void setTorchState(bool on) {
} }
std::string getPicturesDir() { std::string getPicturesDir() {
const char* xdg = std::getenv("XDG_PICTURES_DIR"); if (!isDuressMode()) {
if (xdg && xdg[0]) { const char* xdg = std::getenv("XDG_PICTURES_DIR");
::mkdir(xdg, 0755); if (xdg && xdg[0]) {
return xdg; ::mkdir(xdg, 0755);
return xdg;
}
} }
const char* home = std::getenv("HOME"); std::string dir = getHomeDirPath() + "/Pictures";
std::string dir = std::string(home && home[0] ? home : "/home/user") + "/Pictures";
::mkdir(dir.c_str(), 0755); ::mkdir(dir.c_str(), 0755);
return dir; return dir;
} }
+8 -2
View File
@@ -198,10 +198,10 @@ int runContactsApp(int argc, char** argv) {
} }
}; };
auto reloadContactsIfNeeded = [&]() -> bool { auto reloadContactsIfNeeded = [&](bool force = false) -> bool {
bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath()); bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath());
bool lChanged = logStamp.checkAndUpdate(getModemLogFilePath()); bool lChanged = logStamp.checkAndUpdate(getModemLogFilePath());
if (cChanged || lChanged || !contactsLoadedOnce) { if (force || cChanged || lChanged || !contactsLoadedOnce) {
contactsLoadedOnce = true; contactsLoadedOnce = true;
book.load(); book.load();
updateFilter(); updateFilter();
@@ -984,6 +984,11 @@ int runContactsApp(int argc, char** argv) {
}; };
auto beginSimOperation = [&](SimOp op) { auto beginSimOperation = [&](SimOp op) {
if (isDuressMode()) {
setStatus("SIM contacts unavailable", true);
render();
return;
}
pendingSimOp = op; pendingSimOp = op;
prevModeBeforeSim = prevModeBeforeSim =
(op == SimOp::ExportSingle) ? ViewMode::Detail : ViewMode::List; (op == SimOp::ExportSingle) ? ViewMode::Detail : ViewMode::List;
@@ -1142,6 +1147,7 @@ int runContactsApp(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall, theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall,
layoutIcon, nullptr, win); layoutIcon, nullptr, win);
reloadContactsIfNeeded(true);
render(); render();
} else if (cmd == "OPEN") { } else if (cmd == "OPEN") {
showWindow(""); showWindow("");
+80 -50
View File
@@ -99,11 +99,15 @@ int dialer_run_main(int argc, char** argv) {
FileStamp contactsStamp; FileStamp contactsStamp;
FileStamp logStamp; FileStamp logStamp;
bool contactsLoadedOnce = false; bool contactsLoadedOnce = false;
bool lastDuressState = isDuressMode();
auto reloadContactsIfNeeded = [&]() -> bool { auto reloadContactsIfNeeded = [&]() -> bool {
bool curDuress = isDuressMode();
bool dChanged = (curDuress != lastDuressState);
lastDuressState = curDuress;
bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath()); bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath());
bool lChanged = logStamp.checkAndUpdate(getModemLogFilePath()); bool lChanged = logStamp.checkAndUpdate(getModemLogFilePath());
if (cChanged || lChanged || !contactsLoadedOnce) { if (dChanged || cChanged || lChanged || !contactsLoadedOnce) {
contactsLoadedOnce = true; contactsLoadedOnce = true;
book.load(); book.load();
allContacts = book.buildDialerList(); allContacts = book.buildDialerList();
@@ -524,55 +528,6 @@ int dialer_run_main(int argc, char** argv) {
render(); render();
}; };
auto showWindow = [&](const std::string& arg) {
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("dialer");
modal = DialerModal::Inactive;
bool themeChanged = theme.checkAndReload(
dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon,
layoutNum, win);
std::string cleanArg = normalizePhone(arg);
if (!visible) {
openStartMs = nowMs();
startupIgnoreUntilMs = openStartMs + 70;
initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0);
softkeyPending = 0;
softkeyDeadlineMs = 0;
zeroHeld = (cleanArg == "0" && isKeycodeDown(dpy, 19));
zeroPressMs = zeroHeld ? openStartMs : 0;
visible = true;
XMapRaised(dpy, win);
if (cleanArg.empty() && !themeChanged) {
XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0);
}
grabPluginKeyboard(dpy, win);
bool reloaded = reloadContactsIfNeeded();
if (cleanArg == "*#06#") {
openImeiModal();
} else if (!cleanArg.empty() || reloaded || themeChanged || number != cleanArg) {
number = cleanArg;
selected = number.empty() ? (allContacts.empty() ? -1 : 0) : -1;
updateFilter();
render();
}
XFlush(dpy);
} else if (!cleanArg.empty()) {
XRaiseWindow(dpy, win);
grabPluginKeyboard(dpy, win);
if (nowMs() - openStartMs < 40 && number == cleanArg) {
return;
}
number += cleanArg;
selected = -1;
if (number == "*#06#") {
openImeiModal();
} else {
updateFilter();
render();
}
}
};
auto hideWindow = [&](bool drainSoftkeys) { auto hideWindow = [&](bool drainSoftkeys) {
if (!visible) { if (!visible) {
return; return;
@@ -615,6 +570,67 @@ int dialer_run_main(int argc, char** argv) {
} }
}; };
auto showWindow = [&](const std::string& arg) {
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("dialer");
modal = DialerModal::Inactive;
bool themeChanged = theme.checkAndReload(
dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon,
layoutNum, win);
std::string cleanArg = normalizePhone(arg);
if (!visible) {
openStartMs = nowMs();
startupIgnoreUntilMs = openStartMs + 70;
initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0);
softkeyPending = 0;
softkeyDeadlineMs = 0;
zeroHeld = (cleanArg == "0" && isKeycodeDown(dpy, 19));
zeroPressMs = zeroHeld ? openStartMs : 0;
visible = true;
XMapRaised(dpy, win);
if (cleanArg.empty() && !themeChanged) {
XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0);
}
grabPluginKeyboard(dpy, win);
bool reloaded = reloadContactsIfNeeded();
if (cleanArg == "*#06#") {
openImeiModal();
} else if (cleanArg == "*#2684904#" && !isDuressMode()) {
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
return;
} else if (!cleanArg.empty() || reloaded || themeChanged || number != cleanArg) {
number = cleanArg;
selected = number.empty() ? (allContacts.empty() ? -1 : 0) : -1;
updateFilter();
render();
}
XFlush(dpy);
} else if (!cleanArg.empty()) {
XRaiseWindow(dpy, win);
grabPluginKeyboard(dpy, win);
if (nowMs() - openStartMs < 40 && number == cleanArg) {
return;
}
number += cleanArg;
selected = -1;
if (number == "*#06#") {
openImeiModal();
} else if (number == "*#2684904#" && !isDuressMode()) {
number.clear();
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
} else {
updateFilter();
render();
}
}
};
if (!isPreload) { if (!isPreload) {
showWindow(initArg); showWindow(initArg);
} }
@@ -843,6 +859,14 @@ int dialer_run_main(int argc, char** argv) {
openImeiModal(); openImeiModal();
continue; continue;
} }
if (number == "*#2684904#" && !isDuressMode()) {
number.clear();
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
continue;
}
updateFilter(); updateFilter();
render(); render();
continue; continue;
@@ -911,6 +935,12 @@ int dialer_run_main(int argc, char** argv) {
if (!target.empty()) { if (!target.empty()) {
if (target == "*#06#") { if (target == "*#06#") {
openImeiModal(); openImeiModal();
} else if (target == "*#2684904#" && !isDuressMode()) {
number.clear();
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
} else if (isUssdCode(target)) { } else if (isUssdCode(target)) {
number.clear(); number.clear();
selected = allContacts.empty() ? -1 : 0; selected = allContacts.empty() ? -1 : 0;
+18
View File
@@ -320,6 +320,12 @@ static const char *resolve_plugin_name_from_argv0(const char *argv0) {
strcasecmp(base, "xnav") == 0 || strcasecmp(base, "gps") == 0) { strcasecmp(base, "xnav") == 0 || strcasecmp(base, "gps") == 0) {
return "gps"; return "gps";
} }
if (strcasecmp(base, "xpasscode") == 0 || strcasecmp(base, "passcode") == 0) {
return "passcode";
}
if (strcasecmp(base, "xengmenu") == 0 || strcasecmp(base, "engmenu") == 0) {
return "engmenu";
}
return NULL; return NULL;
} }
@@ -412,6 +418,18 @@ int main(int argc, char **argv) {
sub_argv = argv + 1; sub_argv = argv + 1;
} }
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0 &&
(strcmp(plugin_name, "passcode") == 0 ||
strcmp(plugin_name, "tox") == 0 ||
strcmp(plugin_name, "irc") == 0 ||
strcmp(plugin_name, "sip") == 0 ||
strcmp(plugin_name, "engmenu") == 0)) {
const char *a1 = (sub_argc >= 2 && sub_argv[1]) ? sub_argv[1] : "";
if (strcmp(a1, "--preload") != 0 && strcmp(a1, "close") != 0) {
return 1;
}
}
if (access("/tmp/bananarchy_screen_locked", F_OK) == 0 && if (access("/tmp/bananarchy_screen_locked", F_OK) == 0 &&
strcmp(plugin_name, "locker") != 0 && strcmp(plugin_name, "locker") != 0 &&
strcmp(plugin_name, "callscreen") != 0) { strcmp(plugin_name, "callscreen") != 0) {
+4
View File
@@ -783,6 +783,8 @@ int email_run_main(int argc, char** argv) {
auto openWindow = [&]() { auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return; if (isPhonePasscodeLocked()) return;
accounts = loadEmailAccounts();
messages = loadCachedMessages();
writeIntFile(activePidPath, static_cast<int>(::getpid())); writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("email"); closeOtherPlugins("email");
visible = true; visible = true;
@@ -811,6 +813,8 @@ int email_run_main(int argc, char** argv) {
if (cmd == "CLOSE") closeWindow(); if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") { else if (cmd == "RELOAD_THEME") {
neo.reloadTheme(); neo.reloadTheme();
accounts = loadEmailAccounts();
messages = loadCachedMessages();
if (visible) render(); if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
openWindow(); openWindow();
+61
View File
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: GPL-2.0-only
// Root privilege launcher for Bananarchy engineering menu items.
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE
#endif
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0 ||
access("/tmp/bananarchy_screen_locked", F_OK) == 0) {
return 1;
}
uid_t caller = getuid();
if (caller != 0) {
struct passwd *pw = getpwnam("user");
if (!pw || pw->pw_uid != caller) {
return 1;
}
}
if (argc < 3) {
return 1;
}
if (setgid(0) != 0 || setuid(0) != 0) {
return 1;
}
if (!getenv("DISPLAY")) {
setenv("DISPLAY", ":0", 1);
}
if (!getenv("XAUTHORITY")) {
setenv("XAUTHORITY", "/home/user/.Xauthority", 1);
}
setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
if (strcmp(argv[1], "--term") == 0) {
if (argc < 4) {
return 1;
}
const char *title = argv[2];
const char *cmd = argv[3];
execl("/usr/bin/st", "st", "-t", title, "-e", "/bin/sh", "-c", cmd,
(char *)NULL);
return 1;
}
if (strcmp(argv[1], "--exec") == 0) {
const char *cmd = argv[2];
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
return 1;
}
return 1;
}
+388
View File
@@ -0,0 +1,388 @@
// SPDX-License-Identifier: GPL-2.0-only
// Bananarchy Engineering Menu DWM Plugin (240x320)
#include <X11/Xatom.h>
#include <X11/Xft/Xft.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <pango/pango.h>
#include <pango/pangoxft.h>
#include <algorithm>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include "../sxmo-dwm/dwm_plugin.h"
#include "phone_data.h"
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
struct EngMenuItem {
std::string title;
std::string subtitle;
std::string command;
bool runInTerminal = true;
};
void launchEngItemAsRoot(const EngMenuItem& item) {
if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0 ||
isPhonePasscodeLocked() || item.command.empty()) {
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<char*>(nullptr));
::execl("/usr/bin/doas", "doas", "-n",
"/usr/bin/bananarchy-engmenu-exec", "--term",
item.title.c_str(), item.command.c_str(),
static_cast<char*>(nullptr));
} else {
::execl("/usr/bin/bananarchy-engmenu-exec", "bananarchy-engmenu-exec",
"--exec", item.command.c_str(), static_cast<char*>(nullptr));
::execl("/usr/bin/doas", "doas", "-n",
"/usr/bin/bananarchy-engmenu-exec", "--exec",
item.command.c_str(), static_cast<char*>(nullptr));
}
::_exit(0);
}
::_exit(0);
} else if (pid > 0) {
int st = 0;
(void)::waitpid(pid, &st, 0);
}
}
int engmenu_run_main(int argc, char** argv) {
gRunning = 1;
bool isPreload = false;
for (int i = 1; i < argc; ++i) {
if (argv[i] && std::strcmp(argv[i], "--preload") == 0) {
isPreload = true;
}
}
if (!isPreload && ::access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
return 0;
}
if (sendPluginCommand("engmenu", isPreload ? "NOP" : "OPEN")) {
return 0;
}
int daemonLockFd = acquirePluginDaemonLock("engmenu");
if (daemonLockFd < 0) {
for (int i = 0; i < 10; ++i) {
::usleep(30000);
if (sendPluginCommand("engmenu", isPreload ? "NOP" : "OPEN")) {
return 0;
}
}
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("engmenu");
std::string activePidPath = getRuntimeFile("xengmenu.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("engmenu");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGHUP, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xengmenu", "XEngMenu", "Engineering Menu",
kWinX, kWinY, kWinWidth, kWinHeight, true,
ExposureMask | KeyPressMask | KeyReleaseMask |
VisibilityChangeMask | StructureNotifyMask)) {
if (fifoFd >= 0) {
::close(fifoFd);
}
::unlink(daemonPidPath.c_str());
return 1;
}
Display* dpy = neo.dpy;
Window win = neo.win;
Pixmap pix = neo.pix;
GC gc = neo.gc;
PangoLayout* layoutMain = neo.layoutMain;
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<EngMenuItem> items;
bool visible = false;
int selIdx = 0;
int scrollIdx = 0;
auto openWindow = [&]() {
if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0 ||
isPhonePasscodeLocked()) {
return;
}
closeOtherPlugins("engmenu");
writeIntFile(activePidPath, static_cast<int>(::getpid()));
selIdx = 0;
scrollIdx = 0;
if (!visible) {
XMapRaised(dpy, win);
XMoveResizeWindow(dpy, win, kWinX, kWinY, kWinWidth, kWinHeight);
visible = true;
}
grabPluginKeyboard(dpy, win);
};
auto closeWindow = [&]() {
if (visible) {
XUngrabKeyboard(dpy, CurrentTime);
XUnmapWindow(dpy, win);
XFlush(dpy);
visible = false;
}
::unlink(activePidPath.c_str());
};
auto render = [&]() {
if (!visible) {
return;
}
neo.clearBg();
XSetForeground(dpy, gc, theme.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 26);
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");
neo.drawPango(layoutSmall, &theme.colRed, kWinWidth - rbw - 8, 0, 26,
"ROOT");
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<int>(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<int>(items.size()), kMaxRows, scrollIdx);
}
neo.drawSoftbar(items.empty() ? "" : "Run",
items.empty() ? "" : "Exec",
"Close", &theme.colYellow);
neo.present();
};
if (!isPreload) {
openWindow();
render();
}
int xfd = ConnectionNumber(dpy);
while (gRunning) {
if (fifoFd >= 0) {
for (const std::string& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") {
continue;
}
if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
if (visible) {
render();
}
continue;
}
if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
openWindow();
render();
continue;
}
if (cmd == "CLOSE") {
closeWindow();
continue;
}
}
}
if (visible && neo.checkReloadTheme()) {
render();
}
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (ev.type == Expose) {
if (visible && ev.xexpose.count == 0) {
render();
}
} else if (ev.type == KeyPress) {
if (!visible) {
continue;
}
unsigned int kc = ev.xkey.keycode;
KeySym sym = XLookupKeysym(&ev.xkey, 0);
if (querySoftkeysDown(dpy) == 3) {
writeSoftkeySuppress(nowMs() + 400);
closeWindow();
sendPluginCommand("xdrawer", "OPEN");
continue;
}
if (isRightSoftkey(sym, kc) || sym == XK_Escape ||
sym == XK_BackSpace || kc == 124 || sym == XF86XK_HangupPhone ||
sym == XK_Cancel) {
writeSoftkeySuppress(nowMs() + 300);
closeWindow();
continue;
}
if (!items.empty()) {
if (sym == XK_Up || sym == XK_KP_Up) {
selIdx = (selIdx > 0) ? (selIdx - 1)
: (static_cast<int>(items.size()) - 1);
render();
continue;
}
if (sym == XK_Down || sym == XK_KP_Down) {
selIdx = (selIdx + 1 < static_cast<int>(items.size()))
? (selIdx + 1)
: 0;
render();
continue;
}
if (isLeftSoftkey(sym, kc) || sym == XK_Return ||
sym == XK_KP_Enter) {
if (selIdx >= 0 && selIdx < static_cast<int>(items.size())) {
EngMenuItem chosen = items[selIdx];
closeWindow();
launchEngItemAsRoot(chosen);
}
continue;
}
}
}
}
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);
}
closeWindow();
if (fifoFd >= 0) {
::close(fifoFd);
}
if (daemonLockFd >= 0) {
::close(daemonLockFd);
}
::unlink(getPluginFifoPath("engmenu").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int engmenu_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("engmenu", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"engmenu",
"Engineering menu plugin",
engmenu_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
engmenu_run_main
};
+218 -18
View File
@@ -32,8 +32,64 @@ enum class ViewMode {
ConfirmDelete = 6, ConfirmDelete = 6,
TextEdit = 7, TextEdit = 7,
RingtoneView = 8, RingtoneView = 8,
BtSendModal = 9,
}; };
struct BtSendTarget {
std::string mac;
std::string name;
bool paired = false;
bool connected = false;
};
std::vector<BtSendTarget> queryBtSendTargets(bool scanFirst = false) {
std::string rfk = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null");
if (rfk.find("Soft blocked: yes") != std::string::npos ||
rfk.find("Hard blocked: yes") != std::string::npos) {
runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1");
}
if (scanFirst) {
runCaptureCmd("bluetoothctl --timeout 4 scan on >/dev/null 2>&1");
}
std::unordered_set<std::string> pairedMacs;
std::unordered_set<std::string> connectedMacs;
auto parseSet = [](const std::string& raw, std::unordered_set<std::string>& dst) {
std::istringstream ss(raw);
std::string line;
while (std::getline(ss, line)) {
if (line.rfind("Device ", 0) == 0 && line.size() >= 24) {
dst.insert(line.substr(7, 17));
}
}
};
parseSet(runCaptureCmd("bluetoothctl devices Paired 2>/dev/null || "
"bluetoothctl paired-devices 2>/dev/null"),
pairedMacs);
parseSet(runCaptureCmd("bluetoothctl devices Connected 2>/dev/null"),
connectedMacs);
std::vector<BtSendTarget> out;
std::string allRaw = runCaptureCmd("bluetoothctl devices 2>/dev/null");
std::istringstream ss(allRaw);
std::string line;
while (std::getline(ss, line)) {
if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue;
BtSendTarget d;
d.mac = line.substr(7, 17);
d.name = (line.size() > 25) ? trimStr(line.substr(25)) : d.mac;
d.paired = (pairedMacs.count(d.mac) > 0);
d.connected = (connectedMacs.count(d.mac) > 0);
out.push_back(d);
}
std::sort(out.begin(), out.end(),
[](const BtSendTarget& a, const BtSendTarget& b) {
if (a.connected != b.connected) return a.connected > b.connected;
if (a.paired != b.paired) return a.paired > b.paired;
return a.name < b.name;
});
return out;
}
enum class SortMode { enum class SortMode {
Name = 0, Name = 0,
Date = 1, Date = 1,
@@ -226,8 +282,7 @@ bool isLikelyTextFile(const std::string& path, off_t size) {
} }
std::string shortenPath(const std::string& path) { std::string shortenPath(const std::string& path) {
const char* home = std::getenv("HOME"); std::string h = getHomeDirPath();
std::string h = (home && home[0]) ? home : "/home/user";
std::string out = path; std::string out = path;
if (out == h) { if (out == h) {
out = "~"; out = "~";
@@ -356,10 +411,15 @@ int runFilesApp(int argc, char** argv) {
auto& colOrange = pt.colOrange; auto& colOrange = pt.colOrange;
auto& colRed = pt.colRed; auto& colRed = pt.colRed;
const char* homeEnv = std::getenv("HOME"); std::string homeDir = getHomeDirPath();
std::string homeDir = (homeEnv && homeEnv[0]) ? homeEnv : "/home/user";
std::string currentDir = homeDir; std::string currentDir = homeDir;
// Bluetooth send modal state
std::vector<BtSendTarget> btTargets;
int btTargetSel = 0;
std::string btSendFilePath;
std::string btSendFileName;
ViewMode mode = ViewMode::Browser; ViewMode mode = ViewMode::Browser;
SortMode sortMode = SortMode::Name; SortMode sortMode = SortMode::Name;
bool showHidden = false; bool showHidden = false;
@@ -476,11 +536,19 @@ int runFilesApp(int argc, char** argv) {
auto loadDirectory = [&](const std::string& targetDir, auto loadDirectory = [&](const std::string& targetDir,
const std::string& selectName = "") { const std::string& selectName = "") {
homeDir = getHomeDirPath();
char resolved[4096]; char resolved[4096];
std::string dir = targetDir; std::string dir = targetDir;
if (::realpath(targetDir.c_str(), resolved) != nullptr) { if (::realpath(targetDir.c_str(), resolved) != nullptr) {
dir = resolved; dir = resolved;
} }
if (isDuressMode()) {
std::string root = kDuressHomeDirPath;
::mkdir(root.c_str(), 0700);
if (dir != root && dir.rfind(root + "/", 0) != 0) {
dir = root;
}
}
DIR* d = ::opendir(dir.c_str()); DIR* d = ::opendir(dir.c_str());
if (!d) { if (!d) {
statusBanner = "Cannot open directory"; statusBanner = "Cannot open directory";
@@ -490,7 +558,8 @@ int runFilesApp(int argc, char** argv) {
currentDir = dir; currentDir = dir;
allItems.clear(); allItems.clear();
if (currentDir != "/") { std::string topLimit = isDuressMode() ? std::string(kDuressHomeDirPath) : "/";
if (currentDir != "/" && currentDir != topLimit) {
FileItem parent; FileItem parent;
parent.name = ".."; parent.name = "..";
size_t slash = currentDir.rfind('/'); size_t slash = currentDir.rfind('/');
@@ -964,14 +1033,17 @@ int runFilesApp(int argc, char** argv) {
actionsList.clear(); actionsList.clear();
bool hasSel = !filteredItems.empty(); bool hasSel = !filteredItems.empty();
bool isParent = hasSel && filteredItems[selected].isParent; bool isParent = hasSel && filteredItems[selected].isParent;
bool sdMounted = isSdCardMounted(); bool duress = isDuressMode();
bool sdMounted = !duress && isSdCardMounted();
if (hasSel) { if (hasSel) {
if (!filteredItems[selected].isDir) { if (!filteredItems[selected].isDir) {
std::string ext = getExtLower(filteredItems[selected].name); std::string ext = getExtLower(filteredItems[selected].name);
if (isImageExt(ext)) { if (isImageExt(ext)) {
actionsList.push_back({1, kIconEye, "Preview Image"}); actionsList.push_back({1, kIconEye, "Preview Image"});
actionsList.push_back({14, kIconImage, "Set as Wallpaper"}); if (!duress) {
actionsList.push_back({14, kIconImage, "Set as Wallpaper"});
}
} else if (isRingtoneExt(ext)) { } else if (isRingtoneExt(ext)) {
actionsList.push_back({1, kIconBell, "Preview Ringtone"}); actionsList.push_back({1, kIconBell, "Preview Ringtone"});
actionsList.push_back({15, kIconCheck, "Set as Ringtone"}); actionsList.push_back({15, kIconCheck, "Set as Ringtone"});
@@ -992,12 +1064,13 @@ int runFilesApp(int argc, char** argv) {
if (ext == "jad") { if (ext == "jad") {
actionsList.push_back({17, kIconEye, "View JAD Descriptor"}); actionsList.push_back({17, kIconEye, "View JAD Descriptor"});
} }
} else if (isYabasicExt(ext)) { } else if (isYabasicExt(ext) && !duress) {
actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"}); actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"});
actionsList.push_back({17, kIconEye, "View Text"}); actionsList.push_back({17, kIconEye, "View Text"});
} else { } else {
actionsList.push_back({1, kIconEye, "Open / View"}); actionsList.push_back({1, kIconEye, "Open / View"});
} }
actionsList.push_back({25, kIconBluetooth, "Send via Bluetooth"});
actionsList.push_back({16, kIconEdit, "Edit in Text Editor"}); actionsList.push_back({16, kIconEdit, "Edit in Text Editor"});
} else { } else {
actionsList.push_back({1, kIconFolderOpen, "Open Folder"}); actionsList.push_back({1, kIconFolderOpen, "Open Folder"});
@@ -1011,7 +1084,7 @@ int runFilesApp(int argc, char** argv) {
actionsList.push_back({3, kIconPlus, "New Folder"}); actionsList.push_back({3, kIconPlus, "New Folder"});
actionsList.push_back({4, kIconFileText, "New Empty File"}); actionsList.push_back({4, kIconFileText, "New Empty File"});
if (hasSel && !isParent) { if (hasSel && !isParent) {
if (!filteredItems[selected].isDir) { if (!filteredItems[selected].isDir && !duress) {
actionsList.push_back({2, kIconEdit, "Edit in nano"}); actionsList.push_back({2, kIconEdit, "Edit in nano"});
} }
actionsList.push_back({5, kIconEdit, "Rename"}); actionsList.push_back({5, kIconEdit, "Rename"});
@@ -1028,15 +1101,17 @@ int runFilesApp(int argc, char** argv) {
else if (sortMode == SortMode::Date) sortLbl += "Size (#)"; else if (sortMode == SortMode::Date) sortLbl += "Size (#)";
else sortLbl += "Name (#)"; else sortLbl += "Name (#)";
actionsList.push_back({11, kIconSort, sortLbl}); actionsList.push_back({11, kIconSort, sortLbl});
if (sdMounted) { if (!duress) {
if (currentDir != "/media/sdcard") { if (sdMounted) {
actionsList.push_back({18, kIconFolderOpen, "Open SD Card (/media/sdcard)"}); if (currentDir != "/media/sdcard") {
actionsList.push_back({18, kIconFolderOpen, "Open SD Card (/media/sdcard)"});
}
actionsList.push_back({19, kIconOutCall, "Unmount / Eject SD Card"});
} else {
actionsList.push_back({20, kIconFolder, "Mount SD Card (/media/sdcard)"});
} }
actionsList.push_back({19, kIconOutCall, "Unmount / Eject SD Card"}); actionsList.push_back({12, kIconTerm, "Open Terminal Here"});
} else {
actionsList.push_back({20, kIconFolder, "Mount SD Card (/media/sdcard)"});
} }
actionsList.push_back({12, kIconTerm, "Open Terminal Here"});
actionSelected = 0; actionSelected = 0;
}; };
@@ -1734,6 +1809,64 @@ int runFilesApp(int argc, char** argv) {
drawPango(layoutSmall, &colMuted, 6, 240, 20, drawPango(layoutSmall, &colMuted, 6, 240, 20,
"*:Play #:Set Notif L/R:Step 1:Edit", kWinWidth - 12); "*:Play #:Set Notif L/R:Step 1:Edit", kWinWidth - 12);
drawSoftkeyBar("Set Ring", isPl ? "Stop" : "Play [*]", "Back"); drawSoftkeyBar("Set Ring", isPl ? "Stop" : "Play [*]", "Back");
} else if (mode == ViewMode::BtSendModal) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 28);
drawPango(layoutMain, &colYellow, 6, 0, 28,
std::string(kIconBluetooth) + " Send via Bluetooth",
kWinWidth - 12);
XSetForeground(dpy, gc, pt.spec.border);
XDrawLine(dpy, pix, gc, 0, 27, kWinWidth, 27);
XSetForeground(dpy, gc, pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 6, 32, kWinWidth - 12, 22);
drawPango(layoutSmall, &colLight, 10, 32, 22,
"File: " + btSendFileName, kWinWidth - 20);
if (btTargets.empty()) {
drawPango(layoutMain, &colMuted, 12, 110, 24,
"No Bluetooth devices found", kWinWidth - 24);
drawPango(layoutSmall, &colMuted, 12, 136, 20,
"Press * to scan for nearby devices", kWinWidth - 24);
} else {
btTargetSel = std::clamp(
btTargetSel, 0, static_cast<int>(btTargets.size()) - 1);
const int listY = 58;
const int rowH = 30;
const int maxVis = 6;
int startIdx = std::max(0, btTargetSel - maxVis / 2);
if (startIdx + maxVis > static_cast<int>(btTargets.size())) {
startIdx = std::max(0, static_cast<int>(btTargets.size()) - maxVis);
}
for (int i = 0; i < maxVis; ++i) {
int idx = startIdx + i;
if (idx >= static_cast<int>(btTargets.size())) break;
int ry = listY + i * rowH;
bool isSel = (idx == btTargetSel);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 6, ry, kWinWidth - 12, rowH - 2);
if (isSel) {
XSetForeground(dpy, gc, pt.spec.accent);
XFillRectangle(dpy, pix, gc, 6, ry, 3, rowH - 2);
}
std::string label =
std::string(kIconBluetooth) + " " + btTargets[idx].name;
drawPango(layoutMain, isSel ? &colWhite : &colLight, 12, ry, 18,
label, kWinWidth - 74);
std::string st = btTargets[idx].connected
? "Connected"
: (btTargets[idx].paired ? "Paired" : "Nearby");
drawPango(layoutSmall,
btTargets[idx].connected ? &colGreen : &colMuted,
12, ry + 14, 14, btTargets[idx].mac + " [" + st + "]",
kWinWidth - 24);
}
}
drawPango(layoutSmall, &colMuted, 8, 242, 18,
"*:Scan Bluetooth OK:Send file", kWinWidth - 16);
drawSoftkeyBar(btTargets.empty() ? "Scan [*]" : "Send",
btTargets.empty() ? "Scan" : "Send", "Cancel");
} }
int64_t tNow = nowMs(); int64_t tNow = nowMs();
@@ -2118,6 +2251,12 @@ int runFilesApp(int argc, char** argv) {
statusBanner = "No SD card detected"; statusBanner = "No SD card detected";
} }
statusBannerUntilMs = nowMs() + 2200; statusBannerUntilMs = nowMs() + 2200;
} else if (actId == 25 && !filteredItems.empty()) {
btSendFilePath = filteredItems[selected].fullPath;
btSendFileName = filteredItems[selected].name;
btTargets = queryBtSendTargets(false);
btTargetSel = 0;
mode = ViewMode::BtSendModal;
} }
}; };
@@ -2262,6 +2401,32 @@ int runFilesApp(int argc, char** argv) {
} else { } else {
mode = ViewMode::Browser; mode = ViewMode::Browser;
} }
} else if (mode == ViewMode::BtSendModal) {
if (isLeft) {
if (btTargets.empty()) {
statusBanner = "Scanning Bluetooth...";
statusBannerUntilMs = nowMs() + 2500;
drawUI();
btTargets = queryBtSendTargets(true);
btTargetSel = 0;
statusBanner.clear();
statusBannerUntilMs = 0;
} else {
btTargetSel = std::clamp(
btTargetSel, 0, static_cast<int>(btTargets.size()) - 1);
std::string mac = btTargets[btTargetSel].mac;
std::string devName = btTargets[btTargetSel].name;
std::string cmd =
"/usr/bin/bananarchy-bt-obex send " + shellQuote(mac) + " " +
shellQuote(btSendFilePath) + " >/dev/null 2>&1 &";
std::system(cmd.c_str());
statusBanner = "Sending to " + devName + "...";
statusBannerUntilMs = nowMs() + 2500;
mode = ViewMode::Browser;
}
} else {
mode = ViewMode::Browser;
}
} }
drawUI(); drawUI();
}; };
@@ -2277,6 +2442,9 @@ int runFilesApp(int argc, char** argv) {
continue; continue;
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) {
loadDirectory(kDuressHomeDirPath);
}
if (visible) drawUI(); if (visible) drawUI();
} else if (cmd == "CLOSE") { } else if (cmd == "CLOSE") {
hideWindow(); hideWindow();
@@ -2345,7 +2513,8 @@ int runFilesApp(int argc, char** argv) {
if (sym == XK_BackSpace || sym == XK_Delete) { if (sym == XK_BackSpace || sym == XK_Delete) {
if (mode == ViewMode::Browser && searchQuery.empty() && if (mode == ViewMode::Browser && searchQuery.empty() &&
currentDir != "/") { currentDir != "/" &&
(!isDuressMode() || currentDir != kDuressHomeDirPath)) {
std::string prevBase = currentDir; std::string prevBase = currentDir;
size_t sl = prevBase.rfind('/'); size_t sl = prevBase.rfind('/');
std::string prevName = std::string prevName =
@@ -2375,7 +2544,8 @@ int runFilesApp(int argc, char** argv) {
drawUI(); drawUI();
} }
} else if (sym == XK_Left || sym == XK_KP_Left) { } else if (sym == XK_Left || sym == XK_KP_Left) {
if (currentDir != "/") { if (currentDir != "/" &&
(!isDuressMode() || currentDir != kDuressHomeDirPath)) {
std::string prevBase = currentDir; std::string prevBase = currentDir;
size_t sl = prevBase.rfind('/'); size_t sl = prevBase.rfind('/');
std::string prevName = std::string prevName =
@@ -2602,6 +2772,33 @@ int runFilesApp(int argc, char** argv) {
} else if (sym == XK_Return || sym == XK_KP_Enter) { } else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true); handleSoftkeyAction(true);
} }
} else if (mode == ViewMode::BtSendModal) {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (sym == XK_Up || sym == XK_KP_Up) {
if (!btTargets.empty()) {
btTargetSel =
(btTargetSel - 1 + static_cast<int>(btTargets.size())) %
static_cast<int>(btTargets.size());
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!btTargets.empty()) {
btTargetSel =
(btTargetSel + 1) % static_cast<int>(btTargets.size());
drawUI();
}
} else if (d == '*') {
statusBanner = "Scanning Bluetooth...";
statusBannerUntilMs = nowMs() + 2500;
drawUI();
btTargets = queryBtSendTargets(true);
btTargetSel = 0;
statusBanner.clear();
statusBannerUntilMs = 0;
drawUI();
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
}
} }
} }
} }
@@ -2671,6 +2868,9 @@ int runFilesApp(int argc, char** argv) {
for (const auto& cmd : readFifoLines(fifoFd)) { for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "RELOAD_THEME") { if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) {
loadDirectory(kDuressHomeDirPath);
}
if (visible) drawUI(); if (visible) drawUI();
} else if (cmd == "CLOSE") { } else if (cmd == "CLOSE") {
hideWindow(); hideWindow();
+8 -1
View File
@@ -708,7 +708,7 @@ int irc_run_main(int argc, char** argv) {
}; };
auto openWindow = [&]() { auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return; if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid())); writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("irc"); closeOtherPlugins("irc");
visible = true; visible = true;
@@ -740,6 +740,13 @@ int irc_run_main(int argc, char** argv) {
if (cmd == "NOP") continue; if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow(); if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") { else if (cmd == "RELOAD_THEME") {
if (isDuressMode()) {
for (size_t i = 0; i < servers.size(); ++i) {
disconnectServer(static_cast<int>(i));
}
closeWindow();
continue;
}
neo.reloadTheme(); neo.reloadTheme();
if (visible) render(); if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
+103 -27
View File
@@ -97,6 +97,7 @@ void blankScreenBacklight() {
} }
writeSysfsStr("/sys/class/leds/white:kbd_backlight/brightness", "0"); writeSysfsStr("/sys/class/leds/white:kbd_backlight/brightness", "0");
writeSysfsStr("/sys/class/backlight/backlight/brightness", "0"); writeSysfsStr("/sys/class/backlight/backlight/brightness", "0");
writeSysfsStr("/sys/class/backlight/backlight/bl_power", "4");
} }
void wakeScreenBacklight() { void wakeScreenBacklight() {
@@ -140,17 +141,37 @@ bool constantTimeEq(const std::string& a, const std::string& b) {
return diff == 0; return diff == 0;
} }
enum class VerifyResult {
Invalid = 0,
NormalUser = 1,
DuressUser = 2,
};
class PasscodeVerifier { class PasscodeVerifier {
public: public:
void forceRefresh() {
shadowMtime_ = 0;
shadowSize_ = 0;
duressMtime_ = -1;
cachedHash_.clear();
cachedDuressHash_.clear();
refreshIfNeeded();
}
void refreshIfNeeded() { void refreshIfNeeded() {
struct stat st {}; struct stat st {};
struct stat dst {};
time_t curDuressMtime =
(::stat("/etc/bananarchy_duress.hash", &dst) == 0) ? dst.st_mtim.tv_sec
: 0;
if (::stat("/etc/shadow", &st) == 0) { if (::stat("/etc/shadow", &st) == 0) {
if (!cachedHash_.empty() && st.st_mtim.tv_sec == shadowMtime_ && if (!cachedHash_.empty() && st.st_mtim.tv_sec == shadowMtime_ &&
st.st_size == shadowSize_) { st.st_size == shadowSize_ && curDuressMtime == duressMtime_) {
return; return;
} }
shadowMtime_ = st.st_mtim.tv_sec; shadowMtime_ = st.st_mtim.tv_sec;
shadowSize_ = st.st_size; shadowSize_ = st.st_size;
duressMtime_ = curDuressMtime;
} }
int pipefd[2]; int pipefd[2];
if (::pipe(pipefd) != 0) { if (::pipe(pipefd) != 0) {
@@ -172,12 +193,12 @@ class PasscodeVerifier {
::close(pipefd[1]); ::close(pipefd[1]);
} }
::execl("/usr/bin/doas", "doas", "-n", ::execl("/usr/bin/doas", "doas", "-n",
"/usr/bin/bananarchy-verify-passcode", "--print-hash", "user", "/usr/bin/bananarchy-verify-passcode", "--print-hashes", "user",
static_cast<char*>(nullptr)); static_cast<char*>(nullptr));
::_exit(1); ::_exit(1);
} }
::close(pipefd[1]); ::close(pipefd[1]);
char buf[256]; char buf[512];
ssize_t n = ::read(pipefd[0], buf, sizeof(buf) - 1); ssize_t n = ::read(pipefd[0], buf, sizeof(buf) - 1);
::close(pipefd[0]); ::close(pipefd[0]);
int status = 0; int status = 0;
@@ -185,32 +206,51 @@ class PasscodeVerifier {
::waitpid(pid, &status, 0); ::waitpid(pid, &status, 0);
} }
if (n > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0) { if (n > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0) {
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) {
--n;
}
buf[n] = '\0'; buf[n] = '\0';
if (buf[0] == '$') { cachedDuressHash_.clear();
cachedHash_ = buf; std::istringstream ss(buf);
std::string line;
while (std::getline(ss, line)) {
while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) {
line.pop_back();
}
if (line.rfind("USER_HASH=", 0) == 0) {
std::string h = line.substr(10);
if (!h.empty() && h[0] == '$') {
cachedHash_ = h;
}
} else if (line.rfind("DURESS_HASH=", 0) == 0) {
std::string h = line.substr(12);
if (!h.empty() && h[0] == '$') {
cachedDuressHash_ = h;
}
}
} }
} }
} }
bool verify(const std::string& candidate) { VerifyResult verify(const std::string& candidate) {
if (candidate.empty()) { if (candidate.empty()) {
return false; return VerifyResult::Invalid;
} }
refreshIfNeeded(); refreshIfNeeded();
if (!cachedHash_.empty()) { if (!cachedHash_.empty()) {
char* res = ::crypt(candidate.c_str(), cachedHash_.c_str()); char* res = ::crypt(candidate.c_str(), cachedHash_.c_str());
if (res && constantTimeEq(res, cachedHash_)) { if (res && constantTimeEq(res, cachedHash_)) {
return true; return VerifyResult::NormalUser;
} }
return false; if (!cachedDuressHash_.empty()) {
char* dres = ::crypt(candidate.c_str(), cachedDuressHash_.c_str());
if (dres && constantTimeEq(dres, cachedDuressHash_)) {
return VerifyResult::DuressUser;
}
}
return VerifyResult::Invalid;
} }
// Fallback to helper binary via stdin // Fallback to helper binary via stdin
int pipefd[2]; int pipefd[2];
if (::pipe(pipefd) != 0) { if (::pipe(pipefd) != 0) {
return false; return VerifyResult::Invalid;
} }
pid_t pid = ::fork(); pid_t pid = ::fork();
if (pid == 0) { if (pid == 0) {
@@ -237,16 +277,24 @@ class PasscodeVerifier {
(void)::write(pipefd[1], line.data(), line.size()); (void)::write(pipefd[1], line.data(), line.size());
::close(pipefd[1]); ::close(pipefd[1]);
int status = 0; int status = 0;
if (pid > 0 && ::waitpid(pid, &status, 0) > 0) { if (pid > 0 && ::waitpid(pid, &status, 0) > 0 && WIFEXITED(status)) {
return WIFEXITED(status) && WEXITSTATUS(status) == 0; int code = WEXITSTATUS(status);
if (code == 0) {
return VerifyResult::NormalUser;
}
if (code == 10) {
return VerifyResult::DuressUser;
}
} }
return false; return VerifyResult::Invalid;
} }
private: private:
std::string cachedHash_; std::string cachedHash_;
std::string cachedDuressHash_;
time_t shadowMtime_ = 0; time_t shadowMtime_ = 0;
off_t shadowSize_ = 0; off_t shadowSize_ = 0;
time_t duressMtime_ = -1;
}; };
int countNotifFiles() { int countNotifFiles() {
@@ -545,7 +593,17 @@ int locker_run_main(int argc, char** argv) {
neo.present(); neo.present();
}; };
auto unlockPhone = [&]() { auto activateDuressMode = [&]() {
writeSmallFileStr(kDuressModeFlagPath, "1\n");
(void)std::system("/usr/bin/bananarchy-duress-activate >/dev/null 2>&1");
neo.reloadTheme();
updateClockFont();
};
auto unlockPhone = [&](bool isDuressUnlock) {
if (isDuressUnlock) {
activateDuressMode();
}
passcode.clear(); passcode.clear();
statusMsg.clear(); statusMsg.clear();
statusIsError = false; statusIsError = false;
@@ -606,11 +664,16 @@ int locker_run_main(int argc, char** argv) {
} }
return; return;
} }
if (verifier.verify(passcode)) { VerifyResult vres = verifier.verify(passcode);
unlockPhone(); if (vres == VerifyResult::NormalUser) {
unlockPhone(false);
return; return;
} }
if (explicitSubmit || passcode.size() >= 12) { if (vres == VerifyResult::DuressUser) {
unlockPhone(true);
return;
}
if (explicitSubmit || passcode.size() >= 32) {
passcode.clear(); passcode.clear();
++failedAttempts; ++failedAttempts;
statusIsError = true; statusIsError = true;
@@ -642,6 +705,10 @@ int locker_run_main(int argc, char** argv) {
if (cmd == "NOP") { if (cmd == "NOP") {
continue; continue;
} }
if (cmd == "RELOAD_HASH") {
verifier.forceRefresh();
continue;
}
if (cmd == "RELOAD_THEME") { if (cmd == "RELOAD_THEME") {
neo.reloadTheme(); neo.reloadTheme();
updateClockFont(); updateClockFont();
@@ -677,8 +744,12 @@ int locker_run_main(int argc, char** argv) {
} }
if (cmd.rfind("VERIFY ", 0) == 0) { if (cmd.rfind("VERIFY ", 0) == 0) {
std::string code = trimStr(cmd.substr(7)); std::string code = trimStr(cmd.substr(7));
if (cooldownUntilMs <= nowMs() && verifier.verify(code)) { VerifyResult vres =
unlockPhone(); (cooldownUntilMs <= nowMs()) ? verifier.verify(code)
: VerifyResult::Invalid;
if (vres == VerifyResult::NormalUser ||
vres == VerifyResult::DuressUser) {
unlockPhone(vres == VerifyResult::DuressUser);
} else { } else {
passcode.clear(); passcode.clear();
++failedAttempts; ++failedAttempts;
@@ -829,13 +900,18 @@ int locker_run_main(int argc, char** argv) {
} }
int timeoutMs = -1; int timeoutMs = -1;
if (visible) { if (visible && !isScreenBlanked()) {
if (isScreenBlanked()) { int64_t now = nowMs();
timeoutMs = 2000; if (cooldownUntilMs > now) {
} else if (cooldownUntilMs > nowMs()) {
timeoutMs = 250; timeoutMs = 250;
} else if (statusClearAtMs > now) {
timeoutMs = static_cast<int>(
std::clamp<int64_t>(statusClearAtMs - now, 100, 5000));
} else { } else {
timeoutMs = 1000; std::time_t t = std::time(nullptr);
struct tm tmNow {};
localtime_r(&t, &tmNow);
timeoutMs = std::max(1, 60 - tmNow.tm_sec) * 1000;
} }
} }
+13 -5
View File
@@ -247,13 +247,14 @@ void scanTracksInDir(const std::string& dirPath,
} }
std::string getHomePath() { std::string getHomePath() {
const char* h = std::getenv("HOME"); return getHomeDirPath();
return (h && *h) ? std::string(h) : "/home/user";
} }
std::string getConfigDirPath() { std::string getConfigDirPath() {
const char* c = std::getenv("XDG_CONFIG_HOME"); if (!isDuressMode()) {
if (c && *c) return std::string(c) + "/sxmo"; const char* c = std::getenv("XDG_CONFIG_HOME");
if (c && *c) return std::string(c) + "/sxmo";
}
return getHomePath() + "/.config/sxmo"; return getHomePath() + "/.config/sxmo";
} }
@@ -617,6 +618,12 @@ int runMusicApp(int argc, char** argv) {
if (::realpath(targetDir.c_str(), resolved) != nullptr) { if (::realpath(targetDir.c_str(), resolved) != nullptr) {
dir = resolved; dir = resolved;
} }
if (isDuressMode()) {
std::string root = getHomeDirPath();
if (dir != root && dir.rfind(root + "/", 0) != 0) {
dir = root;
}
}
DIR* d = ::opendir(dir.c_str()); DIR* d = ::opendir(dir.c_str());
if (!d) { if (!d) {
setBanner("Cannot open folder"); setBanner("Cannot open folder");
@@ -625,7 +632,8 @@ int runMusicApp(int argc, char** argv) {
browserDir = dir; browserDir = dir;
browserItems.clear(); browserItems.clear();
if (browserDir != "/") { std::string topLimit = isDuressMode() ? getHomeDirPath() : "/";
if (browserDir != "/" && browserDir != topLimit) {
BrowserItem up; BrowserItem up;
up.name = ".. (Up)"; up.name = ".. (Up)";
size_t sl = browserDir.rfind('/'); size_t sl = browserDir.rfind('/');
+137 -43
View File
@@ -111,6 +111,45 @@ struct BtDeviceEntry {
bool connected = false; bool connected = false;
}; };
struct BtRxStatus {
std::string state = "IDLE";
std::string fileName;
std::string detail = "Ready (~/Downloads)";
std::string savedPath;
int pct = 0;
};
BtRxStatus readBtRxStatus() {
BtRxStatus st;
std::ifstream in("/tmp/bananarchy_bt_rx.status");
std::string line;
if (!in.is_open() || !std::getline(in, line)) {
return st;
}
line = trimStr(line);
if (line.empty()) return st;
std::vector<std::string> cols;
std::stringstream ss(line);
std::string c;
while (std::getline(ss, c, '\t')) {
cols.push_back(c);
}
if (!cols.empty()) st.state = cols[0];
if (st.state == "RECEIVING" && cols.size() >= 5) {
st.fileName = cols[1];
st.detail = cols[4];
st.pct = std::clamp(std::atoi(cols[4].c_str()), 0, 100);
} else if (st.state == "RECEIVED" && cols.size() >= 4) {
st.fileName = cols[1];
st.detail = cols[2];
st.savedPath = cols[3];
st.pct = 100;
} else if (cols.size() >= 2) {
st.detail = cols[1];
}
return st;
}
bool isWifiEnabledFast() { bool isWifiEnabledFast() {
std::string out = runCaptureCmd("/usr/sbin/rfkill list wifi 2>/dev/null"); std::string out = runCaptureCmd("/usr/sbin/rfkill list wifi 2>/dev/null");
if (out.find("Soft blocked: yes") != std::string::npos || if (out.find("Soft blocked: yes") != std::string::npos ||
@@ -409,7 +448,8 @@ int runNetworksApp(int argc, char** argv) {
bool btOn = false; bool btOn = false;
std::vector<BtDeviceEntry> btList; std::vector<BtDeviceEntry> btList;
int btRowSel = 0; // 0 = BT Power Toggle, 1 = Scan Devices, 2..N = BT devices BtRxStatus btRx;
int btRowSel = 0; // 0 = BT Power Toggle, 1 = Scan Devices, 2 = File Reception Widget, 3..N = BT devices
int actionSel = 0; int actionSel = 0;
@@ -463,6 +503,8 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Bluetooth) { } else if (activeTab == NetTab::Bluetooth) {
btOn = isBtEnabledFast(); btOn = isBtEnabledFast();
if (btOn) { if (btOn) {
runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1");
btRx = readBtRxStatus();
if (forceScan) { if (forceScan) {
runCaptureCmd("bluetoothctl --timeout 5 scan on >/dev/null 2>&1"); runCaptureCmd("bluetoothctl --timeout 5 scan on >/dev/null 2>&1");
} }
@@ -470,7 +512,7 @@ int runNetworksApp(int argc, char** argv) {
} else { } else {
btList.clear(); btList.clear();
} }
int maxRow = 1 + static_cast<int>(btList.size()); int maxRow = btOn ? (2 + static_cast<int>(btList.size())) : 1;
if (btRowSel > maxRow) btRowSel = maxRow; if (btRowSel > maxRow) btRowSel = maxRow;
} }
}; };
@@ -687,58 +729,97 @@ int runNetworksApp(int argc, char** argv) {
} }
drawSoftkeyBar("Refresh", "Select", "Close"); drawSoftkeyBar("Refresh", "Select", "Close");
} else if (activeTab == NetTab::Bluetooth) { } else if (activeTab == NetTab::Bluetooth) {
// Row 0: BT Power Toggle (height 28) // Row 0: BT Power Toggle (height 26)
bool sel0 = (btRowSel == 0); bool sel0 = (btRowSel == 0);
XSetForeground(dpy, gc, sel0 ? pt.spec.selBg : pt.spec.bgAltEven); XSetForeground(dpy, gc, sel0 ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 28); XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 26);
drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 28, kIconBluetooth); drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 26, kIconBluetooth);
drawPango(layoutMain, sel0 ? &colWhite : &colLight, drawPango(layoutMain, sel0 ? &colWhite : &colLight,
30, contentY, 28, std::string("Bluetooth: ") + (btOn ? "ON" : "OFF")); 30, contentY, 26, std::string("Bluetooth: ") + (btOn ? "ON" : "OFF"));
drawPango(layoutIcon, btOn ? &colGreen : &colMuted, drawPango(layoutIcon, btOn ? &colGreen : &colMuted,
kWinWidth - 28, contentY, 28, btOn ? kIconToggleOn : kIconToggleOff); kWinWidth - 28, contentY, 26, btOn ? kIconToggleOn : kIconToggleOff);
// Row 1: Scan for Devices (height 26) // Row 1: Scan for Devices (height 24)
bool sel1 = (btRowSel == 1); bool sel1 = (btRowSel == 1);
XSetForeground(dpy, gc, sel1 ? pt.spec.selBg : pt.spec.bgAltOdd); XSetForeground(dpy, gc, sel1 ? pt.spec.selBg : pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 4, contentY + 30, kWinWidth - 8, 26); XFillRectangle(dpy, pix, gc, 4, contentY + 28, kWinWidth - 8, 24);
drawPango(layoutIcon, &colYellow, 10, contentY + 30, 26, kIconSearch); drawPango(layoutIcon, &colYellow, 10, contentY + 28, 24, kIconSearch);
drawPango(layoutSmall, sel1 ? &colWhite : &colLight, drawPango(layoutSmall, sel1 ? &colWhite : &colLight,
30, contentY + 30, 26, "Scan for Bluetooth Devices"); 30, contentY + 28, 24, "Scan for Bluetooth Devices");
int listY = contentY + 58;
int listH = contentH - 58;
if (!btOn) { if (!btOn) {
drawPango(layoutMain, &colMuted, 18, listY + 40, 24, drawPango(layoutMain, &colMuted, 18, contentY + 96, 24,
"Bluetooth is turned off."); "Bluetooth is turned off.");
} else if (btList.empty()) {
drawPango(layoutMain, &colMuted, 18, listY + 40, 24,
"No devices. Select Scan.");
} else { } else {
const int rowH = 38; // Row 2: Bluetooth File Reception Widget (height 36)
const int maxVis = listH / rowH; // 4 rows bool sel2 = (btRowSel == 2);
int devSel = std::max(0, btRowSel - 2); int rxY = contentY + 54;
int startIdx = std::clamp(devSel - maxVis / 2, 0, XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgHeader);
std::max(0, static_cast<int>(btList.size()) - maxVis)); XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 36);
for (int i = 0; i < maxVis && (startIdx + i) < static_cast<int>(btList.size()); ++i) { XSetForeground(dpy, gc, btRx.state == "RECEIVING" ? pt.spec.warning
int idx = startIdx + i; : (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.accent));
const auto& d = btList[idx]; XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 35);
int ry = listY + i * rowH;
bool isSel = (btRowSel == (idx + 2));
XSetForeground(dpy, gc, isSel ? pt.spec.selBg drawPango(layoutIcon,
: ((i % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd)); btRx.state == "RECEIVED" ? &colGreen
XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, rowH - 2); : (btRx.state == "RECEIVING" ? &colYellow : &colBlue),
10, rxY + 1, 18,
btRx.state == "RECEIVED" ? kIconCheck : kIconFolderOpen);
drawPango(layoutIcon, d.connected ? &colGreen : (d.paired ? &colBlue : &colMuted), if (btRx.state == "RECEIVING") {
10, ry + 1, 20, kIconBluetooth); drawPango(layoutSmall, &colYellow, 30, rxY + 1, 18,
drawPango(layoutMain, isSel ? &colWhite : &colLight, "Receiving: " + btRx.fileName + " (" + btRx.detail + ")",
30, ry + 1, 20, d.name, kWinWidth - 42); kWinWidth - 38);
int barW = kWinWidth - 42;
XSetForeground(dpy, gc, pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 30, rxY + 22, barW, 8);
int fillW = (barW * std::clamp(btRx.pct, 0, 100)) / 100;
XSetForeground(dpy, gc, pt.spec.success);
XFillRectangle(dpy, pix, gc, 30, rxY + 22, fillW, 8);
} else if (btRx.state == "RECEIVED") {
drawPango(layoutSmall, &colGreen, 30, rxY + 1, 18,
"Received: " + btRx.fileName, kWinWidth - 38);
drawPango(layoutSmall, sel2 ? &colWhite : &colLight, 30, rxY + 18, 16,
btRx.detail + " [OK: Open in Files]", kWinWidth - 38);
} else {
drawPango(layoutSmall, sel2 ? &colWhite : &colYellow, 30, rxY + 1, 18,
"File Receive: Ready (OBEX Push)", kWinWidth - 38);
drawPango(layoutSmall, sel2 ? &colLight : &colMuted, 30, rxY + 18, 16,
"Saves to ~/Downloads [OK: Open]", kWinWidth - 38);
}
std::string st = d.connected ? "[Connected] " int listY = contentY + 92;
: (d.paired ? "[Paired] " : "[Available] "); int listH = contentH - 92;
st += d.mac; if (btList.empty()) {
drawPango(layoutSmall, d.connected ? &colGreen : (isSel ? &colLight : &colMuted), drawPango(layoutMain, &colMuted, 18, listY + 34, 24,
30, ry + 19, 17, st, kWinWidth - 42); "No devices. Select Scan.");
} else {
const int rowH = 36;
const int maxVis = std::max(1, listH / rowH);
int devSel = std::max(0, btRowSel - 3);
int startIdx = std::clamp(devSel - maxVis / 2, 0,
std::max(0, static_cast<int>(btList.size()) - maxVis));
for (int i = 0; i < maxVis && (startIdx + i) < static_cast<int>(btList.size()); ++i) {
int idx = startIdx + i;
const auto& d = btList[idx];
int ry = listY + i * rowH;
bool isSel = (btRowSel == (idx + 3));
XSetForeground(dpy, gc, isSel ? pt.spec.selBg
: ((i % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd));
XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, rowH - 2);
drawPango(layoutIcon, d.connected ? &colGreen : (d.paired ? &colBlue : &colMuted),
10, ry + 1, 18, kIconBluetooth);
drawPango(layoutMain, isSel ? &colWhite : &colLight,
30, ry + 1, 18, d.name, kWinWidth - 42);
std::string st = d.connected ? "[Connected] "
: (d.paired ? "[Paired] " : "[Available] ");
st += d.mac;
drawPango(layoutSmall, d.connected ? &colGreen : (isSel ? &colLight : &colMuted),
30, ry + 18, 16, st, kWinWidth - 42);
}
} }
} }
drawSoftkeyBar("Scan", "Select", "Close"); drawSoftkeyBar("Scan", "Select", "Close");
@@ -1179,8 +1260,18 @@ int runNetworksApp(int argc, char** argv) {
render(); render();
refreshCurrentTab(true); refreshCurrentTab(true);
setBanner("Found " + std::to_string(btList.size()) + " device(s)"); setBanner("Found " + std::to_string(btList.size()) + " device(s)");
} else if (btRowSel - 2 < static_cast<int>(btList.size())) { } else if (btRowSel == 2 && btOn) {
targetBt = btList[btRowSel - 2]; std::string target = (!btRx.savedPath.empty())
? btRx.savedPath
: (getHomeDirPath() + "/Downloads");
::mkdir((getHomeDirPath() + "/Downloads").c_str(), 0755);
hideWindow();
if (!sendPluginCommand("files", "OPEN " + target)) {
runAsyncArgv("xfiles", target.c_str());
}
} else if (btRowSel - 3 >= 0 &&
btRowSel - 3 < static_cast<int>(btList.size())) {
targetBt = btList[btRowSel - 3];
actionSel = 0; actionSel = 0;
modal = NetModal::BtActions; modal = NetModal::BtActions;
} }
@@ -1373,7 +1464,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) { } else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 3) % 4; cellRowSel = (cellRowSel + 3) % 4;
} else if (activeTab == NetTab::Bluetooth) { } else if (activeTab == NetTab::Bluetooth) {
int total = 2 + static_cast<int>(btList.size()); int total = btOn ? (3 + static_cast<int>(btList.size())) : 2;
btRowSel = (btRowSel + total - 1) % total; btRowSel = (btRowSel + total - 1) % total;
} }
render(); render();
@@ -1384,7 +1475,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) { } else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 1) % 4; cellRowSel = (cellRowSel + 1) % 4;
} else if (activeTab == NetTab::Bluetooth) { } else if (activeTab == NetTab::Bluetooth) {
int total = 2 + static_cast<int>(btList.size()); int total = btOn ? (3 + static_cast<int>(btList.size())) : 2;
btRowSel = (btRowSel + 1) % total; btRowSel = (btRowSel + 1) % total;
} }
render(); render();
@@ -1453,6 +1544,9 @@ int runNetworksApp(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
if (visible) render(); if (visible) render();
} else if (cmd == "REFRESH_BT") {
btRx = readBtRxStatus();
if (visible) render();
} else if (cmd == "TOGGLE") { } else if (cmd == "TOGGLE") {
if (visible) hideWindow(); if (visible) hideWindow();
else showWindow(); else showWindow();
+718
View File
@@ -0,0 +1,718 @@
// SPDX-License-Identifier: GPL-2.0-only
// Bananarchy Passcode & Duress Passcode Configurator DWM Plugin (240x320)
// Configures the numeric Linux user password (/etc/shadow) and optional
// lockscreen Duress Mode passcode (/etc/bananarchy_duress.hash).
#include <X11/Xatom.h>
#include <X11/Xft/Xft.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <pango/pango.h>
#include <pango/pangoxft.h>
#include <algorithm>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include "../sxmo-dwm/dwm_plugin.h"
#include "phone_data.h"
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
bool queryDuressConfigured() {
pid_t pid = ::fork();
if (pid == 0) {
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);
}
}
::execl("/usr/bin/doas", "doas", "-n",
"/usr/bin/bananarchy-verify-passcode", "--has-duress", "user",
static_cast<char*>(nullptr));
::_exit(1);
}
int status = 0;
if (pid > 0 && ::waitpid(pid, &status, 0) > 0) {
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
return false;
}
int runPasscodeHelper(const char* modeFlag,
const std::string& stdinData,
std::string& outMsg) {
outMsg.clear();
int inPipe[2];
int outPipe[2];
if (::pipe(inPipe) != 0) {
outMsg = "System pipe error";
return -1;
}
if (::pipe(outPipe) != 0) {
::close(inPipe[0]);
::close(inPipe[1]);
outMsg = "System pipe error";
return -1;
}
pid_t pid = ::fork();
if (pid == 0) {
::close(inPipe[1]);
::close(outPipe[0]);
::dup2(inPipe[0], STDIN_FILENO);
::dup2(outPipe[1], STDOUT_FILENO);
::dup2(outPipe[1], STDERR_FILENO);
if (inPipe[0] > 2) {
::close(inPipe[0]);
}
if (outPipe[1] > 2) {
::close(outPipe[1]);
}
::execl("/usr/bin/doas", "doas", "-n",
"/usr/bin/bananarchy-verify-passcode", modeFlag, "user",
static_cast<char*>(nullptr));
::_exit(127);
}
::close(inPipe[0]);
::close(outPipe[1]);
if (!stdinData.empty()) {
(void)::write(inPipe[1], stdinData.data(), stdinData.size());
}
::close(inPipe[1]);
char buf[256];
ssize_t n = ::read(outPipe[0], buf, sizeof(buf) - 1);
::close(outPipe[0]);
if (n > 0) {
buf[n] = '\0';
outMsg = trimStr(std::string(buf));
}
int status = 0;
if (pid > 0 && ::waitpid(pid, &status, 0) > 0 && WIFEXITED(status)) {
return WEXITSTATUS(status);
}
return -1;
}
std::string maskDigits(const std::string& s, bool reveal) {
if (s.empty()) {
return "";
}
if (reveal) {
return s;
}
std::string out;
out.reserve(s.size() * 2);
for (size_t i = 0; i < s.size(); ++i) {
if (i > 0) {
out.push_back(' ');
}
out.push_back('*');
}
return out;
}
int passcode_run_main(int argc, char** argv) {
gRunning = 1;
bool isPreload = false;
for (int i = 1; i < argc; ++i) {
if (argv[i] && std::strcmp(argv[i], "--preload") == 0) {
isPreload = true;
}
}
if (!isPreload && ::access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
return 0;
}
if (sendPluginCommand("passcode", isPreload ? "NOP" : "OPEN")) {
return 0;
}
int daemonLockFd = acquirePluginDaemonLock("passcode");
if (daemonLockFd < 0) {
for (int i = 0; i < 10; ++i) {
::usleep(30000);
if (sendPluginCommand("passcode", isPreload ? "NOP" : "OPEN")) {
return 0;
}
}
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("passcode");
std::string activePidPath = getRuntimeFile("xpasscode.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("passcode");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGHUP, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xpasscode", "XPasscode", "Passcode Settings",
kWinX, kWinY, kWinWidth, kWinHeight, true,
ExposureMask | KeyPressMask | KeyReleaseMask |
VisibilityChangeMask | StructureNotifyMask)) {
if (fifoFd >= 0) {
::close(fifoFd);
}
::unlink(daemonPidPath.c_str());
return 1;
}
Display* dpy = neo.dpy;
Window win = neo.win;
Pixmap pix = neo.pix;
GC gc = neo.gc;
PangoLayout* layoutMain = neo.layoutMain;
PangoLayout* layoutSmall = neo.layoutSmall;
PangoLayout* layoutIcon = neo.layoutIcon;
PluginTheme& theme = neo.theme;
bool visible = false;
int activeTab = 0; // 0 = User Passcode, 1 = Duress Passcode
int focusIdx = 0; // 0=Current, 1=New, 2=Confirm, 3=Save, 4=Clear (tab 1)
bool revealDigits = false;
bool duressSet = false;
std::string userFields[3]; // [0]=cur, [1]=new, [2]=confirm
std::string duressFields[3]; // [0]=curUser, [1]=newDuress, [2]=confirmDuress
std::string statusMsg;
bool statusError = false;
int64_t statusUntilMs = 0;
auto resetFormState = [&]() {
for (int i = 0; i < 3; ++i) {
std::fill(userFields[i].begin(), userFields[i].end(), '\0');
userFields[i].clear();
std::fill(duressFields[i].begin(), duressFields[i].end(), '\0');
duressFields[i].clear();
}
focusIdx = 0;
revealDigits = false;
statusMsg.clear();
statusError = false;
statusUntilMs = 0;
duressSet = queryDuressConfigured();
};
auto setStatus = [&](const std::string& msg, bool isErr) {
statusMsg = msg;
statusError = isErr;
statusUntilMs = nowMs() + 3500;
};
auto maxFocusForTab = [&]() -> int {
if (activeTab == 0) {
return 3; // 0, 1, 2, 3(Save)
}
return duressSet ? 4 : 3; // 0, 1, 2, 3(Save), 4(Clear)
};
auto openWindow = [&]() {
if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0 ||
isPhonePasscodeLocked()) {
return;
}
closeOtherPlugins("passcode");
writeIntFile(activePidPath, static_cast<int>(::getpid()));
resetFormState();
activeTab = 0;
if (!visible) {
XMapRaised(dpy, win);
XMoveResizeWindow(dpy, win, kWinX, kWinY, kWinWidth, kWinHeight);
visible = true;
}
grabPluginKeyboard(dpy, win);
};
auto closeWindow = [&]() {
resetFormState();
if (visible) {
XUngrabKeyboard(dpy, CurrentTime);
XUnmapWindow(dpy, win);
XFlush(dpy);
visible = false;
}
::unlink(activePidPath.c_str());
};
auto submitUserPasscode = [&]() {
const std::string& curP = userFields[0];
const std::string& newP = userFields[1];
const std::string& cnfP = userFields[2];
if (curP.size() < 4) {
setStatus("Enter current passcode (4+ digits)", true);
focusIdx = 0;
return;
}
if (newP.size() < 4) {
setStatus("New passcode must be 4+ digits", true);
focusIdx = 1;
return;
}
if (newP != cnfP) {
setStatus("New passcodes do not match", true);
focusIdx = 2;
return;
}
std::string out;
std::string payload = curP + "\n" + newP + "\n";
int rc = runPasscodeHelper("--set-user-pass", payload, out);
std::fill(payload.begin(), payload.end(), '\0');
if (rc == 0) {
for (int i = 0; i < 3; ++i) {
std::fill(userFields[i].begin(), userFields[i].end(), '\0');
userFields[i].clear();
}
focusIdx = 0;
sendPluginCommand("locker", "RELOAD_HASH");
runAsyncCmd("sxmo_vibrate 40 >/dev/null 2>&1");
setStatus(out.empty() ? "User passcode updated" : out, false);
} else {
setStatus(out.empty() ? "Failed to update passcode" : out, true);
}
};
auto submitDuressPasscode = [&]() {
const std::string& curP = duressFields[0];
const std::string& newP = duressFields[1];
const std::string& cnfP = duressFields[2];
if (curP.size() < 4) {
setStatus("Enter current user passcode", true);
focusIdx = 0;
return;
}
if (newP.size() < 4) {
setStatus("Duress passcode must be 4+ digits", true);
focusIdx = 1;
return;
}
if (newP != cnfP) {
setStatus("Duress passcodes do not match", true);
focusIdx = 2;
return;
}
std::string out;
std::string payload = curP + "\n" + newP + "\n";
int rc = runPasscodeHelper("--set-duress-pass", payload, out);
std::fill(payload.begin(), payload.end(), '\0');
if (rc == 0) {
for (int i = 0; i < 3; ++i) {
std::fill(duressFields[i].begin(), duressFields[i].end(), '\0');
duressFields[i].clear();
}
duressSet = queryDuressConfigured();
focusIdx = 0;
sendPluginCommand("locker", "RELOAD_HASH");
runAsyncCmd("sxmo_vibrate 40 >/dev/null 2>&1");
setStatus(out.empty() ? "Duress passcode saved" : out, false);
} else {
setStatus(out.empty() ? "Failed to set duress passcode" : out, true);
}
};
auto clearDuressPasscode = [&]() {
const std::string& curP = duressFields[0];
if (curP.size() < 4) {
setStatus("Enter current user passcode first", true);
focusIdx = 0;
return;
}
std::string out;
std::string payload = curP + "\n";
int rc = runPasscodeHelper("--clear-duress-pass", payload, out);
std::fill(payload.begin(), payload.end(), '\0');
if (rc == 0) {
for (int i = 0; i < 3; ++i) {
std::fill(duressFields[i].begin(), duressFields[i].end(), '\0');
duressFields[i].clear();
}
duressSet = queryDuressConfigured();
focusIdx = 0;
sendPluginCommand("locker", "RELOAD_HASH");
runAsyncCmd("sxmo_vibrate 40 >/dev/null 2>&1");
setStatus(out.empty() ? "Duress passcode cleared" : out, false);
} else {
setStatus(out.empty() ? "Failed to clear duress passcode" : out, true);
}
};
auto render = [&]() {
if (!visible) {
return;
}
int64_t now = nowMs();
if (statusUntilMs > 0 && now >= statusUntilMs) {
statusMsg.clear();
statusError = false;
statusUntilMs = 0;
}
neo.clearBg();
// Header (Y=0..26)
XSetForeground(dpy, gc, theme.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 26);
neo.drawPango(layoutIcon, &theme.colYellow, 6, 0, 26, kIconKey);
neo.drawPango(layoutMain, &theme.colWhite, 28, 0, 26, "Passcode Setup", 150);
std::string rightBadge =
(activeTab == 1) ? (duressSet ? "SET" : "OFF") : "0-9";
int rbw = neo.pangoWidth(layoutSmall, rightBadge);
neo.drawPango(layoutSmall,
(activeTab == 1 && duressSet) ? &theme.colGreen
: &theme.colMuted,
kWinWidth - rbw - 8, 0, 26, rightBadge);
XSetForeground(dpy, gc, theme.spec.border);
XDrawLine(dpy, pix, gc, 0, 25, kWinWidth, 25);
// Tab bar (Y=26..48)
const char* tabs[2] = {"User PIN", "Duress PIN"};
for (int t = 0; t < 2; ++t) {
int tx = t * (kWinWidth / 2);
int tw = kWinWidth / 2;
bool isAct = (activeTab == t);
XSetForeground(dpy, gc, isAct ? theme.spec.selBg : theme.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, tx, 26, tw, 22);
if (isAct) {
XSetForeground(dpy, gc, theme.spec.accent);
XFillRectangle(dpy, pix, gc, tx, 46, tw, 2);
}
neo.drawPango(layoutSmall, isAct ? &theme.colWhite : &theme.colMuted,
tx, 26, 22, tabs[t], tw, 1);
}
std::string* fields = (activeTab == 0) ? userFields : duressFields;
const char* labels[3] = {
(activeTab == 0) ? "Current User Passcode" : "Current User Passcode",
(activeTab == 0) ? "New User Passcode (4+ digits)"
: "New Duress Passcode (4+ digits)",
(activeTab == 0) ? "Confirm New Passcode" : "Confirm Duress Passcode",
};
int y = 52;
for (int i = 0; i < 3; ++i) {
bool focused = (focusIdx == i);
neo.drawPango(layoutSmall, focused ? &theme.colYellow : &theme.colMuted,
10, y, 15, labels[i], kWinWidth - 20);
y += 15;
int boxX = 8;
int boxW = kWinWidth - 16;
int boxH = 26;
XSetForeground(dpy, gc, theme.spec.bgInput);
XFillRectangle(dpy, pix, gc, boxX, y, boxW, boxH);
XSetForeground(dpy, gc, focused ? theme.spec.selBg : theme.spec.border);
XDrawRectangle(dpy, pix, gc, boxX, y, boxW - 1, boxH - 1);
if (focused) {
XDrawRectangle(dpy, pix, gc, boxX + 1, y + 1, boxW - 3, boxH - 3);
}
std::string valStr = maskDigits(fields[i], revealDigits);
if (valStr.empty()) {
std::string hint = focused ? "Type digits 0-9..." : "----";
neo.drawPango(layoutSmall, &theme.colMuted, boxX + 6, y + 2, boxH - 4,
hint, boxW - 44);
} else {
neo.drawPango(layoutMain, &theme.colWhite, boxX + 6, y + 2, boxH - 4,
valStr, boxW - 44);
}
std::string lenBadge =
fields[i].empty() ? "" : (std::to_string(fields[i].size()) + "d");
if (!lenBadge.empty()) {
int lw = neo.pangoWidth(layoutSmall, lenBadge);
XftColor* lcol =
(fields[i].size() >= 4) ? &theme.colGreen : &theme.colMuted;
neo.drawPango(layoutSmall, lcol, boxX + boxW - lw - 6, y + 2, boxH - 4,
lenBadge);
}
y += boxH + 4;
}
// Action buttons
int btnY = y + 2;
int btnH = 24;
bool saveFocused = (focusIdx == 3);
uint32_t saveBg = saveFocused ? theme.spec.selBg : theme.spec.bgAltOdd;
XSetForeground(dpy, gc, saveBg);
XFillRectangle(dpy, pix, gc, 8, btnY, kWinWidth - 16, btnH);
XSetForeground(dpy, gc, saveFocused ? theme.spec.accent : theme.spec.border);
XDrawRectangle(dpy, pix, gc, 8, btnY, kWinWidth - 17, btnH - 1);
std::string saveLabel =
(activeTab == 0) ? (std::string(kIconCheck) + " Save User Passcode")
: (std::string(kIconShield) + " Save Duress Passcode");
neo.drawPango(layoutMain, saveFocused ? &theme.colWhite : &theme.colLight,
8, btnY, btnH, saveLabel, kWinWidth - 16, 1);
btnY += btnH + 4;
if (activeTab == 1 && duressSet) {
bool clrFocused = (focusIdx == 4);
uint32_t clrBg = clrFocused ? theme.spec.danger : theme.spec.bgAltEven;
XSetForeground(dpy, gc, clrBg);
XFillRectangle(dpy, pix, gc, 8, btnY, kWinWidth - 16, btnH);
XSetForeground(dpy, gc,
clrFocused ? theme.spec.danger : theme.spec.border);
XDrawRectangle(dpy, pix, gc, 8, btnY, kWinWidth - 17, btnH - 1);
std::string clrLabel = std::string(kIconTrash) + " Clear Duress Passcode";
neo.drawPango(layoutSmall, clrFocused ? &theme.colWhite : &theme.colRed,
8, btnY, btnH, clrLabel, kWinWidth - 16, 1);
btnY += btnH + 4;
}
// Status message or help footer above softbar
int statusY = kWinHeight - 46;
if (!statusMsg.empty()) {
XSetForeground(dpy, gc, theme.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 8, statusY, kWinWidth - 16, 20);
XSetForeground(dpy, gc,
statusError ? theme.spec.danger : theme.spec.accent);
XDrawRectangle(dpy, pix, gc, 8, statusY, kWinWidth - 17, 19);
neo.drawPango(layoutSmall,
statusError ? &theme.colRed : &theme.colGreen,
12, statusY, 20, statusMsg, kWinWidth - 24, 1);
} else {
std::string footer =
revealDigits ? "*: Hide digits | Numeric only (4+)"
: "*: Show digits | Numeric only (4+)";
neo.drawPango(layoutSmall, &theme.colMuted, 8, statusY, 20, footer,
kWinWidth - 16, 1);
}
// Softbar
const char* leftLbl = (focusIdx < 2) ? "Next" : "Save";
if (focusIdx == 4) {
leftLbl = "Clear";
}
const char* rightLbl =
(focusIdx <= 2 && !fields[focusIdx].empty()) ? "Del" : "Back";
neo.drawSoftbar(leftLbl, "OK", rightLbl, &theme.colYellow);
neo.present();
};
if (!isPreload) {
openWindow();
render();
}
int xfd = ConnectionNumber(dpy);
while (gRunning) {
if (fifoFd >= 0) {
for (const std::string& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") {
continue;
}
if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
if (visible) {
render();
}
continue;
}
if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
openWindow();
render();
continue;
}
if (cmd == "CLOSE") {
closeWindow();
continue;
}
}
}
if (visible && neo.checkReloadTheme()) {
render();
}
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (ev.type == Expose) {
if (visible && ev.xexpose.count == 0) {
render();
}
} else if (ev.type == KeyPress) {
if (!visible) {
continue;
}
unsigned int kc = ev.xkey.keycode;
KeySym sym = XLookupKeysym(&ev.xkey, 0);
if (querySoftkeysDown(dpy) == 3) {
writeSoftkeySuppress(nowMs() + 400);
closeWindow();
sendPluginCommand("xdrawer", "OPEN");
continue;
}
std::string* fields = (activeTab == 0) ? userFields : duressFields;
int maxFocus = maxFocusForTab();
if (sym == XK_Left || sym == XK_KP_Left) {
activeTab = (activeTab == 0) ? 1 : 0;
if (focusIdx > maxFocusForTab()) {
focusIdx = maxFocusForTab();
}
statusMsg.clear();
render();
continue;
}
if (sym == XK_Right || sym == XK_KP_Right) {
activeTab = (activeTab == 0) ? 1 : 0;
if (focusIdx > maxFocusForTab()) {
focusIdx = maxFocusForTab();
}
statusMsg.clear();
render();
continue;
}
if (sym == XK_Up || sym == XK_KP_Up) {
focusIdx = (focusIdx > 0) ? (focusIdx - 1) : maxFocus;
render();
continue;
}
if (sym == XK_Down || sym == XK_KP_Down) {
focusIdx = (focusIdx < maxFocus) ? (focusIdx + 1) : 0;
render();
continue;
}
if (isStarKey(sym, kc)) {
revealDigits = !revealDigits;
render();
continue;
}
if (isRightSoftkey(sym, kc) || sym == XK_BackSpace ||
sym == XK_Delete) {
if (focusIdx >= 0 && focusIdx <= 2 && !fields[focusIdx].empty()) {
fields[focusIdx].pop_back();
render();
} else if (isRightSoftkey(sym, kc) || sym == XK_Escape) {
writeSoftkeySuppress(nowMs() + 300);
closeWindow();
}
continue;
}
if (sym == XK_Escape || kc == 124 || sym == XF86XK_HangupPhone ||
sym == XK_Cancel) {
writeSoftkeySuppress(nowMs() + 300);
closeWindow();
continue;
}
if (isLeftSoftkey(sym, kc) || sym == XK_Return || sym == XK_KP_Enter ||
isPoundKey(sym, kc)) {
if (focusIdx < 2) {
++focusIdx;
} else if (focusIdx == 2 || focusIdx == 3) {
if (activeTab == 0) {
submitUserPasscode();
} else {
submitDuressPasscode();
}
} else if (focusIdx == 4 && activeTab == 1 && duressSet) {
clearDuressPasscode();
}
render();
continue;
}
char ch = mapDialKey(sym, kc, ev.xkey.state);
if (ch >= '0' && ch <= '9') {
if (focusIdx > 2) {
focusIdx = 0;
}
if (fields[focusIdx].size() < 32) {
fields[focusIdx].push_back(ch);
statusMsg.clear();
render();
}
continue;
}
}
}
int timeoutMs = -1;
if (visible && statusUntilMs > 0) {
int64_t rem = statusUntilMs - nowMs();
timeoutMs = static_cast<int>(std::max<int64_t>(50, rem));
}
struct pollfd pfds[2] {};
pfds[0].fd = xfd;
pfds[0].events = POLLIN;
pfds[1].fd = fifoFd;
pfds[1].events = POLLIN;
int pr = ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs);
if (pr == 0 && visible && statusUntilMs > 0 && nowMs() >= statusUntilMs) {
render();
}
}
closeWindow();
if (fifoFd >= 0) {
::close(fifoFd);
}
if (daemonLockFd >= 0) {
::close(daemonLockFd);
}
::unlink(getPluginFifoPath("passcode").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int passcode_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("passcode", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"passcode",
"Bananarchy numeric user passcode and duress passcode configurator",
passcode_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
passcode_run_main
};
+164 -4
View File
@@ -295,11 +295,14 @@ struct FileStamp {
time_t sec = -1; time_t sec = -1;
long nsec = -1; long nsec = -1;
off_t size = -1; off_t size = -1;
std::string lastPath;
bool checkAndUpdate(const std::string& path) { bool checkAndUpdate(const std::string& path) {
bool pathChanged = (path != lastPath);
lastPath = path;
struct stat st {}; struct stat st {};
if (::stat(path.c_str(), &st) != 0) { if (::stat(path.c_str(), &st) != 0) {
if (sec != 0 || size != 0) { if (pathChanged || sec != 0 || size != 0) {
sec = 0; sec = 0;
nsec = 0; nsec = 0;
size = 0; size = 0;
@@ -307,8 +310,8 @@ struct FileStamp {
} }
return false; return false;
} }
if (st.st_mtim.tv_sec != sec || st.st_mtim.tv_nsec != nsec || if (pathChanged || st.st_mtim.tv_sec != sec ||
st.st_size != size) { st.st_mtim.tv_nsec != nsec || st.st_size != size) {
sec = st.st_mtim.tv_sec; sec = st.st_mtim.tv_sec;
nsec = st.st_mtim.tv_nsec; nsec = st.st_mtim.tv_nsec;
size = st.st_size; size = st.st_size;
@@ -514,7 +517,17 @@ inline bool isPoundKey(KeySym sym, unsigned int keycode) {
sym == XK_KP_Divide || static_cast<uint32_t>(sym) == 0x1008ffab; sym == XK_KP_Divide || static_cast<uint32_t>(sym) == 0x1008ffab;
} }
constexpr const char* kDuressModeFlagPath = "/tmp/bananarchy_duress_mode";
constexpr const char* kDuressHomeDirPath = "/tmp/duress_home";
inline bool isDuressMode() {
return ::access(kDuressModeFlagPath, F_OK) == 0;
}
inline std::string getHomeDir() { inline std::string getHomeDir() {
if (isDuressMode()) {
return kDuressHomeDirPath;
}
return getHomeDirPath(); return getHomeDirPath();
} }
@@ -587,6 +600,9 @@ inline std::string toT9Digits(const std::string& name) {
} }
inline std::string getContactsFilePath() { inline std::string getContactsFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.config/sxmo/contacts.tsv";
}
const char* env = std::getenv("SXMO_CONTACTFILE"); const char* env = std::getenv("SXMO_CONTACTFILE");
if (env && env[0]) { if (env && env[0]) {
return env; return env;
@@ -601,6 +617,10 @@ inline std::string getContactsFilePath() {
} }
inline std::string getModemLogFilePath() { inline std::string getModemLogFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) +
"/.local/share/sxmo/modem/modemlog.tsv";
}
const char* env = std::getenv("SXMO_LOGDIR"); const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) { if (env && env[0]) {
return std::string(env) + "/modemlog.tsv"; return std::string(env) + "/modemlog.tsv";
@@ -993,6 +1013,9 @@ class ContactBook {
}; };
inline std::string getBlockFilePath() { inline std::string getBlockFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.config/sxmo/block.tsv";
}
const char* env = std::getenv("SXMO_BLOCKFILE"); const char* env = std::getenv("SXMO_BLOCKFILE");
if (env && env[0]) { if (env && env[0]) {
return env; return env;
@@ -1007,6 +1030,9 @@ inline std::string getBlockFilePath() {
} }
inline std::string getBlockDirPath() { inline std::string getBlockDirPath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.local/share/sxmo/block";
}
const char* env = std::getenv("SXMO_BLOCKDIR"); const char* env = std::getenv("SXMO_BLOCKDIR");
if (env && env[0]) { if (env && env[0]) {
return env; return env;
@@ -1767,6 +1793,10 @@ inline DualSimInfo queryDualSimInfo(bool forceRefresh = false) {
int sub2 = (info.primaryGwSlot == 2) ? 0 : ((info.secondaryGwSlot == 2) ? 1 : -1); int sub2 = (info.primaryGwSlot == 2) ? 0 : ((info.secondaryGwSlot == 2) ? 1 : -1);
querySubMeta(1, sub1, info.slot1Operator, info.slot1Rat, info.slot1Number); querySubMeta(1, sub1, info.slot1Operator, info.slot1Rat, info.slot1Number);
querySubMeta(2, sub2, info.slot2Operator, info.slot2Rat, info.slot2Number); querySubMeta(2, sub2, info.slot2Operator, info.slot2Rat, info.slot2Number);
if (isDuressMode()) {
info.slot1Number.clear();
info.slot2Number.clear();
}
auto formatSlotStrings = [](int s, const std::string& op, const std::string& rat, auto formatSlotStrings = [](int s, const std::string& op, const std::string& rat,
const std::string& num, std::string& outLabel, const std::string& num, std::string& outLabel,
@@ -1842,6 +1872,8 @@ inline void closeOtherPlugins(const char* selfPluginName) {
{"xtox.pid", "tox"}, {"xtox.pid", "tox"},
{"xsmallweb.pid", "smallweb"}, {"xsmallweb.pid", "smallweb"},
{"xgps.pid", "gps"}, {"xgps.pid", "gps"},
{"xpasscode.pid", "passcode"},
{"xengmenu.pid", "engmenu"},
}; };
for (const auto& p : kAllPlugins) { for (const auto& p : kAllPlugins) {
if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) { if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) {
@@ -1884,6 +1916,8 @@ inline bool isAnotherPluginActive(const char* selfPluginName) {
{"xtox.pid", "tox"}, {"xtox.pid", "tox"},
{"xsmallweb.pid", "smallweb"}, {"xsmallweb.pid", "smallweb"},
{"xgps.pid", "gps"}, {"xgps.pid", "gps"},
{"xpasscode.pid", "passcode"},
{"xengmenu.pid", "engmenu"},
}; };
for (const auto& p : kAllPlugins) { for (const auto& p : kAllPlugins) {
if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) { if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) {
@@ -1935,6 +1969,8 @@ inline void broadcastThemeReload(const char* selfPluginName = nullptr) {
"tox", "tox",
"smallweb", "smallweb",
"gps", "gps",
"passcode",
"engmenu",
}; };
for (const char* name : kPlugins) { for (const char* name : kPlugins) {
if (selfPluginName && std::strcmp(name, selfPluginName) == 0) { if (selfPluginName && std::strcmp(name, selfPluginName) == 0) {
@@ -1947,10 +1983,13 @@ inline void broadcastThemeReload(const char* selfPluginName = nullptr) {
::close(fd); ::close(fd);
} }
} }
runAsyncCmd("pkill -USR1 -x st >/dev/null 2>&1"); runAsyncCmd("pkill -USR1 -x st >/dev/null 2>&1; /usr/bin/bananarchy-sync-dunst-theme >/dev/null 2>&1");
} }
inline std::string getModemLogDirPath() { inline std::string getModemLogDirPath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.local/share/sxmo/modem";
}
const char* env = std::getenv("SXMO_LOGDIR"); const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) { if (env && env[0]) {
return env; return env;
@@ -2411,8 +2450,111 @@ inline bool queryQrtrDmsImeis(DeviceImeis& out) {
return !out.imei1.empty() || !out.imei2.empty(); return !out.imei1.empty() || !out.imei2.empty();
} }
inline std::string generateRandomImeiFromTac(const std::string& rawTac) {
std::string tac;
for (char c : rawTac) {
if (c >= '0' && c <= '9' && tac.size() < 8) {
tac.push_back(c);
}
}
while (tac.size() < 8) {
tac += "35829909"[tac.size()];
}
unsigned char rnd[6] = {0, 0, 0, 0, 0, 0};
int ufd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
if (ufd >= 0) {
(void)::read(ufd, rnd, sizeof(rnd));
::close(ufd);
}
std::string body = tac;
for (int i = 0; i < 6; ++i) {
body.push_back(static_cast<char>('0' + (rnd[i] % 10)));
}
int sum = 0;
for (int i = 0; i < 14; ++i) {
int d = body[i] - '0';
if ((i % 2) == 1) {
d *= 2;
if (d >= 10) {
d = (d / 10) + (d % 10);
}
}
sum += d;
}
int check = (10 - (sum % 10)) % 10;
body.push_back(static_cast<char>('0' + check));
return body;
}
inline DeviceImeis queryDeviceImeis() { inline DeviceImeis queryDeviceImeis() {
static DeviceImeis cached; static DeviceImeis cached;
static DeviceImeis cachedDuress;
if (isDuressMode()) {
if (!cachedDuress.imei1.empty() && !cachedDuress.imei2.empty()) {
return cachedDuress;
}
const char* kDuressImeiFile = "/tmp/bananarchy_duress_imei";
{
std::ifstream in(kDuressImeiFile);
std::string line;
while (std::getline(in, line)) {
if (line.rfind("IMEI1=", 0) == 0) {
cachedDuress.imei1 = trimStr(line.substr(6));
} else if (line.rfind("IMEI2=", 0) == 0) {
cachedDuress.imei2 = trimStr(line.substr(6));
} else if (line.rfind("IMEI_SV=", 0) == 0) {
cachedDuress.imeiSv = trimStr(line.substr(8));
}
}
}
if (!cachedDuress.imei1.empty() && !cachedDuress.imei2.empty()) {
return cachedDuress;
}
std::string tac1 = "35829909";
std::string tac2 = "35829909";
{
std::ifstream tin("/tmp/bananarchy_real_tac");
std::string tline;
if (std::getline(tin, tline) && tline.size() >= 8) {
tac1 = tline.substr(0, 8);
tac2 = tac1;
}
if (std::getline(tin, tline) && tline.size() >= 8) {
tac2 = tline.substr(0, 8);
}
}
if (!cached.imei1.empty() && cached.imei1.size() >= 8) {
tac1 = cached.imei1.substr(0, 8);
tac2 = (!cached.imei2.empty() && cached.imei2.size() >= 8)
? cached.imei2.substr(0, 8)
: tac1;
} else if (::access("/tmp/bananarchy_real_tac", F_OK) != 0) {
DeviceImeis realTmp;
queryQrtrDmsImeis(realTmp);
if (realTmp.imei1.size() >= 8) {
tac1 = realTmp.imei1.substr(0, 8);
tac2 = (realTmp.imei2.size() >= 8) ? realTmp.imei2.substr(0, 8) : tac1;
}
}
cachedDuress.imei1 = generateRandomImeiFromTac(tac1);
cachedDuress.imei2 = generateRandomImeiFromTac(tac2);
while (cachedDuress.imei2 == cachedDuress.imei1) {
cachedDuress.imei2 = generateRandomImeiFromTac(tac2);
}
cachedDuress.imeiSv = "01";
std::ofstream out(kDuressImeiFile, std::ios::trunc);
if (out.is_open()) {
out << "IMEI1=" << cachedDuress.imei1 << "\n"
<< "IMEI2=" << cachedDuress.imei2 << "\n"
<< "IMEI_SV=" << cachedDuress.imeiSv << "\n";
}
return cachedDuress;
}
if (!cached.imei1.empty() && !cached.imei2.empty()) { if (!cached.imei1.empty() && !cached.imei2.empty()) {
return cached; return cached;
} }
@@ -2441,6 +2583,16 @@ inline DeviceImeis queryDeviceImeis() {
} }
if (!res.imei1.empty()) { if (!res.imei1.empty()) {
cached = res; cached = res;
if (res.imei1.size() >= 8 &&
::access("/tmp/bananarchy_real_tac", F_OK) != 0) {
std::ofstream tout("/tmp/bananarchy_real_tac", std::ios::trunc);
if (tout.is_open()) {
tout << res.imei1.substr(0, 8) << "\n"
<< ((res.imei2.size() >= 8) ? res.imei2.substr(0, 8)
: res.imei1.substr(0, 8))
<< "\n";
}
}
} }
return res; return res;
} }
@@ -3007,6 +3159,10 @@ inline bool qrtrReadSimContacts(
std::string& outErr) { std::string& outErr) {
outContacts.clear(); outContacts.clear();
outErr.clear(); outErr.clear();
if (isDuressMode()) {
outErr = "SIM phonebook empty";
return false;
}
int sfd = -1; int sfd = -1;
uint32_t uimNode = 0, uimPort = 0; uint32_t uimNode = 0, uimPort = 0;
@@ -3045,6 +3201,10 @@ inline bool qrtrWriteSimContacts(
int& outExported, std::string& outErr) { int& outExported, std::string& outErr) {
outExported = 0; outExported = 0;
outErr.clear(); outErr.clear();
if (isDuressMode()) {
outErr = "SIM phonebook unavailable";
return false;
}
if (contactsToWrite.empty()) { if (contactsToWrite.empty()) {
outErr = "No contacts to export"; outErr = "No contacts to export";
return false; return false;
+24 -12
View File
@@ -1268,7 +1268,7 @@ int sip_run_main(int argc, char** argv) {
}; };
auto openWindow = [&]() { auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return; if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid())); writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("sip"); closeOtherPlugins("sip");
visible = true; visible = true;
@@ -1287,9 +1287,11 @@ int sip_run_main(int argc, char** argv) {
}; };
// Trigger initial background registration for enabled accounts // Trigger initial background registration for enabled accounts
for (auto& acct : accounts) { if (!isDuressMode()) {
if (acct.enabled) { for (auto& acct : accounts) {
sendSipRegister(acct); if (acct.enabled) {
sendSipRegister(acct);
}
} }
} }
@@ -1304,6 +1306,13 @@ int sip_run_main(int argc, char** argv) {
if (cmd == "CLOSE") { if (cmd == "CLOSE") {
closeWindow(); closeWindow();
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
if (isDuressMode()) {
hangupActiveSipCall(false);
accounts.clear();
history.clear();
closeWindow();
continue;
}
neo.reloadTheme(); neo.reloadTheme();
if (visible) render(); if (visible) render();
} else if (cmd.rfind("CALL_ACCEPT", 0) == 0) { } else if (cmd.rfind("CALL_ACCEPT", 0) == 0) {
@@ -1339,6 +1348,7 @@ int sip_run_main(int argc, char** argv) {
ssize_t n = ::recvfrom(sipUdpFd, rxBuf, sizeof(rxBuf) - 1, 0, ssize_t n = ::recvfrom(sipUdpFd, rxBuf, sizeof(rxBuf) - 1, 0,
reinterpret_cast<struct sockaddr*>(&fromSin), &sl); reinterpret_cast<struct sockaddr*>(&fromSin), &sl);
if (n <= 0) break; if (n <= 0) break;
if (isDuressMode()) continue;
rxBuf[n] = '\0'; rxBuf[n] = '\0';
handleIncomingSipPacket(std::string(rxBuf, static_cast<size_t>(n)), fromSin); handleIncomingSipPacket(std::string(rxBuf, static_cast<size_t>(n)), fromSin);
if (visible) render(); if (visible) render();
@@ -1348,14 +1358,16 @@ int sip_run_main(int argc, char** argv) {
// 3. Periodic REGISTER keepalive for enabled accounts // 3. Periodic REGISTER keepalive for enabled accounts
int64_t now = nowMs(); int64_t now = nowMs();
bool anyEnabled = false; bool anyEnabled = false;
for (auto& acct : accounts) { if (!isDuressMode()) {
if (!acct.enabled) continue; for (auto& acct : accounts) {
anyEnabled = true; if (!acct.enabled) continue;
if (acct.lastRegAttemptMs == 0 || anyEnabled = true;
(acct.regStatus == "ONLINE" && now >= acct.regExpiresAtMs) || if (acct.lastRegAttemptMs == 0 ||
(acct.regStatus != "ONLINE" && now - acct.lastRegAttemptMs >= 45000)) { (acct.regStatus == "ONLINE" && now >= acct.regExpiresAtMs) ||
sendSipRegister(acct); (acct.regStatus != "ONLINE" && now - acct.lastRegAttemptMs >= 45000)) {
if (visible) render(); sendSipRegister(acct);
if (visible) render();
}
} }
} }
+2
View File
@@ -1343,6 +1343,7 @@ int runSmsApp(int argc, char** argv) {
continue; continue;
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
reloadAllData(true);
if (visible) drawUI(); if (visible) drawUI();
} else if (cmd == "CLOSE") { } else if (cmd == "CLOSE") {
hideWindow(); hideWindow();
@@ -1753,6 +1754,7 @@ int runSmsApp(int argc, char** argv) {
for (const auto& cmd : readFifoLines(fifoFd)) { for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "RELOAD_THEME") { if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
reloadAllData(true);
if (visible) drawUI(); if (visible) drawUI();
} else if (cmd == "CLOSE") { } else if (cmd == "CLOSE") {
hideWindow(); hideWindow();
+39 -14
View File
@@ -106,9 +106,7 @@ void popUtf8(std::string& s) {
} }
std::string getXthemesDir() { std::string getXthemesDir() {
const char* home = std::getenv("HOME"); std::string dir = getHomeDirPath() + "/.xthemes";
std::string dir =
std::string((home && home[0]) ? home : "/home/user") + "/.xthemes";
::mkdir(dir.c_str(), 0755); ::mkdir(dir.c_str(), 0755);
return dir; return dir;
} }
@@ -147,6 +145,26 @@ void updateRootResourceManager(const std::string& xresContent,
void ensureDefaultThemesSeeded() { void ensureDefaultThemesSeeded() {
std::string dir = getXthemesDir(); std::string dir = getXthemesDir();
if (isDuressMode()) {
std::string nordPath = dir + "/NordFrost.xth";
if (::access(nordPath.c_str(), R_OK) != 0 &&
::access("/etc/skel/.xthemes/NordFrost.xth", R_OK) == 0) {
ThemeSpec ts;
ts.name = "NordFrost";
if (ts.loadFromFile("/etc/skel/.xthemes/NordFrost.xth")) {
ts.name = "NordFrost";
writeTextFile(nordPath, ts.serializeXresources());
}
}
std::string xresPath = getXresourcesPath();
if (::access(xresPath.c_str(), R_OK) != 0) {
ThemeSpec nordSpec;
nordSpec.loadFromFile(nordPath);
writeTextFile(xresPath, nordSpec.serializeXresources());
}
return;
}
std::string defPath = dir + "/Default.xth"; std::string defPath = dir + "/Default.xth";
if (::access(defPath.c_str(), R_OK) != 0) { if (::access(defPath.c_str(), R_OK) != 0) {
if (::access("/etc/skel/.xthemes/Default.xth", R_OK) == 0) { if (::access("/etc/skel/.xthemes/Default.xth", R_OK) == 0) {
@@ -216,6 +234,9 @@ std::vector<ThemeFileEntry> loadInstalledThemes(const ThemeSpec& activeSpec) {
if (fname.size() <= 4 || fname.substr(fname.size() - 4) != ".xth") { if (fname.size() <= 4 || fname.substr(fname.size() - 4) != ".xth") {
continue; continue;
} }
if (isDuressMode() && fname != "NordFrost.xth") {
continue;
}
ThemeFileEntry item; ThemeFileEntry item;
item.name = fname.substr(0, fname.size() - 4); item.name = fname.substr(0, fname.size() - 4);
item.fullPath = dir + "/" + fname; item.fullPath = dir + "/" + fname;
@@ -469,16 +490,20 @@ int runThemesApp(int argc, char** argv) {
actionsList.clear(); actionsList.clear();
if (!themes.empty()) { if (!themes.empty()) {
actionsList.push_back({1, kIconCheck, "Apply Selected Theme"}); actionsList.push_back({1, kIconCheck, "Apply Selected Theme"});
actionsList.push_back({2, kIconPalette, "Customize Theme Colors/Font"}); if (!isDuressMode()) {
actionsList.push_back({2, kIconPalette, "Customize Theme Colors/Font"});
}
} }
actionsList.push_back({3, kIconPlus, "Save Current as New Theme"}); if (!isDuressMode()) {
if (!themes.empty()) { actionsList.push_back({3, kIconPlus, "Save Current as New Theme"});
actionsList.push_back({4, kIconCopy, "Duplicate Theme"}); if (!themes.empty()) {
actionsList.push_back({5, kIconEdit, "Edit .xth in Nano"}); actionsList.push_back({4, kIconCopy, "Duplicate Theme"});
} actionsList.push_back({5, kIconEdit, "Edit .xth in Nano"});
actionsList.push_back({6, kIconSort, "Reset Default Theme"}); }
if (!themes.empty() && themes[selected].name != "Default") { actionsList.push_back({6, kIconSort, "Reset Default Theme"});
actionsList.push_back({7, kIconTrash, "Delete Theme"}); if (!themes.empty() && themes[selected].name != "Default") {
actionsList.push_back({7, kIconTrash, "Delete Theme"});
}
} }
actionSelected = 0; actionSelected = 0;
}; };
@@ -1145,13 +1170,13 @@ int runThemesApp(int argc, char** argv) {
drawUI(); drawUI();
} else { } else {
char d = mapDialKey(sym, kc, ev.xkey.state); char d = mapDialKey(sym, kc, ev.xkey.state);
if (d == '*' && !themes.empty()) { if (d == '*' && !themes.empty() && !isDuressMode()) {
editSpec = themes[selected].spec; editSpec = themes[selected].spec;
editThemeName = themes[selected].name; editThemeName = themes[selected].name;
editField = 0; editField = 0;
mode = ViewMode::Customize; mode = ViewMode::Customize;
drawUI(); drawUI();
} else if (d == '#') { } else if (d == '#' && !isDuressMode()) {
nameAction = NameModalAction::SaveCurrentAs; nameAction = NameModalAction::SaveCurrentAs;
nameTitle = "Save Theme As"; nameTitle = "Save Theme As";
nameInput = "Custom"; nameInput = "Custom";
+7 -2
View File
@@ -637,7 +637,7 @@ int tox_run_main(int argc, char** argv) {
}; };
auto openWindow = [&]() { auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return; if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid())); writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("tox"); closeOtherPlugins("tox");
visible = true; visible = true;
@@ -665,6 +665,11 @@ int tox_run_main(int argc, char** argv) {
if (cmd == "NOP") continue; if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow(); if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") { else if (cmd == "RELOAD_THEME") {
if (isDuressMode()) {
closeWindow();
networkActive = false;
continue;
}
neo.reloadTheme(); neo.reloadTheme();
if (visible) render(); if (visible) render();
} else if (cmd.rfind("CALL_ACCEPT", 0) == 0) { } else if (cmd.rfind("CALL_ACCEPT", 0) == 0) {
@@ -706,7 +711,7 @@ int tox_run_main(int argc, char** argv) {
// Iterate Tox and ToxAV when visible, in a call, or when friends are configured // Iterate Tox and ToxAV when visible, in a call, or when friends are configured
bool shouldIterateTox = bool shouldIterateTox =
networkActive && tox && !isDuressMode() && networkActive && tox &&
(visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0); (visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0);
if (shouldIterateTox) { if (shouldIterateTox) {
tox_iterate(tox, &ctx); tox_iterate(tox, &ctx);
+358 -10
View File
@@ -1,5 +1,5 @@
// SPDX-License-Identifier: GPL-2.0-only // SPDX-License-Identifier: GPL-2.0-only
// Bananarchy shadow passcode verifier for the fullscreen phone locker. // Bananarchy shadow passcode & duress passcode manager/verifier.
#ifndef _DEFAULT_SOURCE #ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE #define _DEFAULT_SOURCE
@@ -8,13 +8,19 @@
#define _XOPEN_SOURCE 700 #define _XOPEN_SOURCE 700
#endif #endif
#include <crypt.h> #include <crypt.h>
#include <ctype.h>
#include <fcntl.h>
#include <pwd.h> #include <pwd.h>
#include <shadow.h> #include <shadow.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
static const char *kDuressHashPath = "/etc/bananarchy_duress.hash";
static const char *kDuressModeFlag = "/tmp/bananarchy_duress_mode";
static int constant_time_eq(const char *a, const char *b) { static int constant_time_eq(const char *a, const char *b) {
if (!a || !b) { if (!a || !b) {
return 0; return 0;
@@ -31,13 +37,204 @@ static int constant_time_eq(const char *a, const char *b) {
return diff == 0; return diff == 0;
} }
static void trim_crlf(char *s) {
if (!s) {
return;
}
size_t len = strlen(s);
while (len > 0 && (s[len - 1] == '\n' || s[len - 1] == '\r')) {
s[--len] = '\0';
}
}
static int is_valid_numeric_passcode(const char *s) {
if (!s) {
return 0;
}
size_t len = strlen(s);
if (len < 4 || len > 32) {
return 0;
}
for (size_t i = 0; i < len; ++i) {
if (s[i] < '0' || s[i] > '9') {
return 0;
}
}
return 1;
}
static int read_duress_hash(char *out, size_t out_sz) {
if (!out || out_sz == 0) {
return 0;
}
out[0] = '\0';
FILE *fp = fopen(kDuressHashPath, "r");
if (!fp) {
return 0;
}
if (!fgets(out, (int)out_sz, fp)) {
fclose(fp);
out[0] = '\0';
return 0;
}
fclose(fp);
trim_crlf(out);
if (out[0] != '$' || strlen(out) < 12) {
out[0] = '\0';
return 0;
}
return 1;
}
static int verify_against_hash(const char *candidate, const char *hash) {
if (!candidate || !candidate[0] || !hash || hash[0] != '$') {
return 0;
}
char *calc = crypt(candidate, hash);
if (!calc) {
return 0;
}
return constant_time_eq(calc, hash);
}
static int check_duress_conflict(const char *candidate_pass) {
if (!candidate_pass || !candidate_pass[0]) {
return 0;
}
FILE *fp = fopen(kDuressHashPath, "r");
if (!fp) {
return 0;
}
size_t clen = strlen(candidate_pass);
char line[256];
while (fgets(line, sizeof(line), fp)) {
trim_crlf(line);
if (line[0] != '$' || strlen(line) < 12) {
continue;
}
char prefix[64];
for (size_t plen = 4; plen <= clen && plen < sizeof(prefix); ++plen) {
memcpy(prefix, candidate_pass, plen);
prefix[plen] = '\0';
if (verify_against_hash(prefix, line)) {
memset(prefix, 0, sizeof(prefix));
fclose(fp);
return 1;
}
}
memset(prefix, 0, sizeof(prefix));
}
fclose(fp);
return 0;
}
static int generate_sha512_salt(char *salt_out, size_t salt_sz) {
static const char kSaltChars[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (!salt_out || salt_sz < 21) {
return 0;
}
unsigned char rnd[16];
int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return 0;
}
ssize_t n = read(fd, rnd, sizeof(rnd));
close(fd);
if (n != (ssize_t)sizeof(rnd)) {
return 0;
}
salt_out[0] = '$';
salt_out[1] = '6';
salt_out[2] = '$';
for (int i = 0; i < 16; ++i) {
salt_out[3 + i] = kSaltChars[rnd[i] & 0x3F];
}
salt_out[19] = '$';
salt_out[20] = '\0';
return 1;
}
static int update_shadow_hash(const char *username, const char *new_hash) {
struct stat st;
int have_stat = (stat("/etc/shadow", &st) == 0);
FILE *in = fopen("/etc/shadow", "r");
if (!in) {
return 0;
}
const char *tmp_path = "/etc/shadow.bananarchy.tmp";
int tfd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (tfd < 0) {
fclose(in);
return 0;
}
FILE *out = fdopen(tfd, "w");
if (!out) {
close(tfd);
fclose(in);
unlink(tmp_path);
return 0;
}
size_t ulen = strlen(username);
int updated = 0;
char line[2048];
while (fgets(line, sizeof(line), in)) {
if (strncmp(line, username, ulen) == 0 && line[ulen] == ':') {
const char *rest = strchr(line + ulen + 1, ':');
if (rest) {
fprintf(out, "%s:%s%s", username, new_hash, rest);
updated = 1;
continue;
}
}
fputs(line, out);
}
fflush(out);
fsync(tfd);
fclose(out);
fclose(in);
if (!updated) {
unlink(tmp_path);
return 0;
}
if (have_stat) {
(void)chown(tmp_path, st.st_uid, st.st_gid);
(void)chmod(tmp_path, st.st_mode & 07777);
} else {
(void)chmod(tmp_path, 0640);
}
if (rename(tmp_path, "/etc/shadow") != 0) {
unlink(tmp_path);
return 0;
}
return 1;
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
int print_hash = 0; int print_hash = 0;
int print_hashes = 0;
int has_duress = 0;
int set_user_pass = 0;
int set_duress_pass = 0;
int clear_duress_pass = 0;
const char *username = "user"; const char *username = "user";
for (int i = 1; i < argc; ++i) { for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--print-hash") == 0) { if (strcmp(argv[i], "--print-hash") == 0) {
print_hash = 1; print_hash = 1;
} else if (strcmp(argv[i], "--print-hashes") == 0) {
print_hashes = 1;
} else if (strcmp(argv[i], "--has-duress") == 0) {
has_duress = 1;
} else if (strcmp(argv[i], "--set-user-pass") == 0) {
set_user_pass = 1;
} else if (strcmp(argv[i], "--set-duress-pass") == 0) {
set_duress_pass = 1;
} else if (strcmp(argv[i], "--clear-duress-pass") == 0) {
clear_duress_pass = 1;
} else if (argv[i][0] != '-') { } else if (argv[i][0] != '-') {
username = argv[i]; username = argv[i];
} }
@@ -47,6 +244,13 @@ int main(int argc, char **argv) {
return 2; return 2;
} }
char duress_hash[256];
int duress_configured = read_duress_hash(duress_hash, sizeof(duress_hash));
if (has_duress) {
return duress_configured ? 0 : 1;
}
struct spwd *sp = getspnam(username); struct spwd *sp = getspnam(username);
const char *hash = (sp && sp->sp_pwdp) ? sp->sp_pwdp : NULL; const char *hash = (sp && sp->sp_pwdp) ? sp->sp_pwdp : NULL;
if (!hash || !hash[0]) { if (!hash || !hash[0]) {
@@ -62,22 +266,166 @@ int main(int argc, char **argv) {
return 0; return 0;
} }
if (print_hashes) {
printf("USER_HASH=%s\n", hash);
printf("DURESS_HASH=%s\n", duress_configured ? duress_hash : "");
return 0;
}
if (set_user_pass || set_duress_pass || clear_duress_pass) {
if (access(kDuressModeFlag, F_OK) == 0) {
puts("Operation unavailable");
return 5;
}
char cur_pass[128];
if (!fgets(cur_pass, sizeof(cur_pass), stdin)) {
puts("Missing current passcode");
return 2;
}
trim_crlf(cur_pass);
if (!verify_against_hash(cur_pass, hash)) {
memset(cur_pass, 0, sizeof(cur_pass));
puts("Current passcode is incorrect");
return 2;
}
if (clear_duress_pass) {
memset(cur_pass, 0, sizeof(cur_pass));
unlink(kDuressHashPath);
puts("Duress passcode cleared");
return 0;
}
char new_pass[128];
if (!fgets(new_pass, sizeof(new_pass), stdin)) {
memset(cur_pass, 0, sizeof(cur_pass));
puts("Missing new passcode");
return 3;
}
trim_crlf(new_pass);
if (!is_valid_numeric_passcode(new_pass)) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Passcode must be 4-32 numeric digits (0-9)");
return 3;
}
if (set_user_pass) {
if (duress_configured && check_duress_conflict(new_pass)) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("New passcode conflicts with duress passcode");
return 4;
}
char salt[32];
if (!generate_sha512_salt(salt, sizeof(salt))) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Failed to generate cryptographic salt");
return 6;
}
char *new_hash = crypt(new_pass, salt);
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
if (!new_hash || new_hash[0] != '$') {
puts("Failed to hash new passcode");
return 6;
}
if (!update_shadow_hash(username, new_hash)) {
puts("Failed to update /etc/shadow");
return 6;
}
puts("User passcode updated");
return 0;
}
if (set_duress_pass) {
size_t ulen = strlen(cur_pass);
size_t dlen = strlen(new_pass);
size_t min_len = (ulen < dlen) ? ulen : dlen;
if (strncmp(cur_pass, new_pass, min_len) == 0) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Duress passcode cannot match or prefix user passcode");
return 4;
}
char salt[32];
if (!generate_sha512_salt(salt, sizeof(salt))) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Failed to generate cryptographic salt");
return 6;
}
char *new_hash = crypt(new_pass, salt);
if (!new_hash || new_hash[0] != '$') {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Failed to hash duress passcode");
return 6;
}
char main_hash_copy[256];
snprintf(main_hash_copy, sizeof(main_hash_copy), "%s", new_hash);
const char *tmp_duress = "/etc/bananarchy_duress.hash.tmp";
int fd = open(tmp_duress, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) {
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
puts("Failed to write duress hash");
return 6;
}
size_t hlen = strlen(main_hash_copy);
ssize_t w1 = write(fd, main_hash_copy, hlen);
ssize_t w2 = write(fd, "\n", 1);
for (size_t plen = 4; plen < dlen && plen < 64; ++plen) {
char psalt[32];
if (generate_sha512_salt(psalt, sizeof(psalt))) {
char pbuf[64];
memcpy(pbuf, new_pass, plen);
pbuf[plen] = '\0';
char *ph = crypt(pbuf, psalt);
memset(pbuf, 0, sizeof(pbuf));
if (ph && ph[0] == '$') {
(void)write(fd, ph, strlen(ph));
(void)write(fd, "\n", 1);
}
}
}
memset(cur_pass, 0, sizeof(cur_pass));
memset(new_pass, 0, sizeof(new_pass));
fsync(fd);
close(fd);
if (w1 != (ssize_t)hlen || w2 != 1 ||
rename(tmp_duress, kDuressHashPath) != 0) {
unlink(tmp_duress);
puts("Failed to save duress hash");
return 6;
}
puts("Duress passcode updated");
return 0;
}
}
char pass[128]; char pass[128];
if (!fgets(pass, sizeof(pass), stdin)) { if (!fgets(pass, sizeof(pass), stdin)) {
return 1; return 1;
} }
size_t len = strlen(pass); trim_crlf(pass);
while (len > 0 && (pass[len - 1] == '\n' || pass[len - 1] == '\r')) { if (pass[0] == '\0') {
pass[--len] = '\0';
}
if (len == 0) {
return 1; return 1;
} }
char *calc = crypt(pass, hash); int ok_user = verify_against_hash(pass, hash);
int ok_duress = (!ok_user && duress_configured)
? verify_against_hash(pass, duress_hash)
: 0;
memset(pass, 0, sizeof(pass)); memset(pass, 0, sizeof(pass));
if (!calc) {
return 1; if (ok_user) {
return 0;
} }
return constant_time_eq(calc, hash) ? 0 : 1; if (ok_duress) {
return 10;
}
return 1;
} }
+20 -1
View File
@@ -52,6 +52,9 @@ constexpr int kNumScaleModes =
static_cast<int>(sizeof(kScaleModes) / sizeof(kScaleModes[0])); static_cast<int>(sizeof(kScaleModes) / sizeof(kScaleModes[0]));
std::string getConfigDir() { std::string getConfigDir() {
if (isDuressMode()) {
return getHomeDirPath() + "/.config/sxmo";
}
const char* xdg = std::getenv("XDG_CONFIG_HOME"); const char* xdg = std::getenv("XDG_CONFIG_HOME");
if (xdg && *xdg) { if (xdg && *xdg) {
return std::string(xdg) + "/sxmo"; return std::string(xdg) + "/sxmo";
@@ -132,6 +135,19 @@ void scanWallpaperDir(const std::string& dirPath,
std::vector<WallpaperEntry> discoverWallpapers() { std::vector<WallpaperEntry> discoverWallpapers() {
std::vector<WallpaperEntry> list; std::vector<WallpaperEntry> list;
if (isDuressMode()) {
const std::string nordWall = "/usr/share/wallpapers/nordic-peaks.png";
struct stat st {};
if (::stat(nordWall.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
WallpaperEntry e;
e.path = nordWall;
e.displayName = "Nordic peaks";
e.sourceTag = "System";
e.sizeBytes = st.st_size;
list.push_back(e);
}
return list;
}
scanWallpaperDir("/usr/share/wallpapers", "System", list); scanWallpaperDir("/usr/share/wallpapers", "System", list);
std::string home = getHomeDirPath(); std::string home = getHomeDirPath();
@@ -141,6 +157,9 @@ std::vector<WallpaperEntry> discoverWallpapers() {
} }
std::string loadActiveWallpaperPath() { std::string loadActiveWallpaperPath() {
if (isDuressMode()) {
return "/usr/share/wallpapers/nordic-peaks.png";
}
std::ifstream ifs(getConfigDir() + "/wallpaper"); std::ifstream ifs(getConfigDir() + "/wallpaper");
if (ifs) { if (ifs) {
std::string line; std::string line;
@@ -664,7 +683,7 @@ int runWallpapersApp(int argc, char** argv) {
hideWindow(); hideWindow();
} else if (cmd == "RELOAD_THEME") { } else if (cmd == "RELOAD_THEME") {
pt.reload(); pt.reload();
cachedImgPath.clear(); refreshData();
if (visible) render(); if (visible) render();
} else if (cmd == "TOGGLE") { } else if (cmd == "TOGGLE") {
if (visible) hideWindow(); if (visible) hideWindow();
+6 -1
View File
@@ -294,6 +294,9 @@ uint32_t blendRgb(uint32_t c1, uint32_t c2, int weight2Pct) {
} }
std::string getHomeDirPath() { std::string getHomeDirPath() {
if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
return "/tmp/duress_home";
}
const char* h = std::getenv("HOME"); const char* h = std::getenv("HOME");
return (h && h[0]) ? h : "/home/user"; return (h && h[0]) ? h : "/home/user";
} }
@@ -1774,13 +1777,15 @@ int neoui_broadcast_theme_reload(const char* skip_plugin) {
const char* kPlugins[] = { const char* kPlugins[] = {
"dmenu", "locker", "xdrawer", "dialer", "calllog", "callscreen", "contacts", "dmenu", "locker", "xdrawer", "dialer", "calllog", "callscreen", "contacts",
"sms", "files", "camera", "themes", "modem", "networks", "ringtones", "sms", "files", "camera", "themes", "modem", "networks", "ringtones",
"wallpapers", "music", "sip", "email", "irc", "tox", "smallweb", "gps" "wallpapers", "music", "sip", "email", "irc", "tox", "smallweb", "gps",
"passcode", "engmenu"
}; };
std::string skip = (skip_plugin && skip_plugin[0]) ? skip_plugin : ""; std::string skip = (skip_plugin && skip_plugin[0]) ? skip_plugin : "";
for (const char* p : kPlugins) { for (const char* p : kPlugins) {
if (skip == p) continue; if (skip == p) continue;
bananarchy::sendPluginFifoMsg(p, "RELOAD_THEME"); bananarchy::sendPluginFifoMsg(p, "RELOAD_THEME");
} }
(void)std::system("/usr/bin/bananarchy-sync-dunst-theme >/dev/null 2>&1 &");
return 1; return 1;
} }
+107 -32
View File
@@ -814,6 +814,11 @@ spawn_detached_sh(const char *cmd)
{ {
if (!cmd || !cmd[0]) if (!cmd || !cmd[0])
return; return;
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
if (strncmp(cmd, "st ", 3) == 0 || strcmp(cmd, "st") == 0 ||
strstr(cmd, "sxmo_terminal.sh") != NULL)
return;
}
if (fork() == 0) { if (fork() == 0) {
if (dpy) if (dpy)
close(ConnectionNumber(dpy)); close(ConnectionNumber(dpy));
@@ -2105,6 +2110,16 @@ add_parsed_choice_line(const char *line)
trim_inplace(cmd); trim_inplace(cmd);
if (!label[0] || !cmd[0]) if (!label[0] || !cmd[0])
return; return;
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
if (strstr(label, "Bantam") || strstr(label, "SIP") ||
strstr(label, "IRC") || strstr(label, "Tox") ||
strstr(label, "Passcode") || strstr(label, "Terminal") ||
strstr(cmd, "xsip") || strstr(cmd, "xirc") ||
strstr(cmd, "xtox") || strstr(cmd, "xpasscode") ||
strstr(cmd, "sxmo_terminal.sh") || strncmp(cmd, "st ", 3) == 0 ||
strcmp(cmd, "st") == 0)
return;
}
for (size_t i = 0; i < items_count; i++) { for (size_t i = 0; i < items_count; i++) {
if (items[i].text && strcmp(items[i].text, label) == 0) if (items[i].text && strcmp(items[i].text, label) == 0)
return; return;
@@ -2114,6 +2129,10 @@ add_parsed_choice_line(const char *line)
return; return;
if (items[i].text && strstr(label, "ReMEdy") && strstr(items[i].text, "ReMEdy")) if (items[i].text && strstr(label, "ReMEdy") && strstr(items[i].text, "ReMEdy"))
return; return;
if (items[i].text && strstr(label, "Scoundrel") && strstr(items[i].text, "Scoundrel"))
return;
if (items[i].text && strstr(label, "Passcode") && strstr(items[i].text, "Passcode"))
return;
if (items[i].text && strstr(label, "SIP VoIP") && strstr(items[i].text, "SIP VoIP")) if (items[i].text && strstr(label, "SIP VoIP") && strstr(items[i].text, "SIP VoIP"))
return; return;
if (items[i].text && strstr(label, "Email") && strstr(items[i].text, "Email")) if (items[i].text && strstr(label, "Email") && strstr(items[i].text, "Email"))
@@ -2366,6 +2385,7 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(current_builtin_menu, sizeof(current_builtin_menu), "%s", menu_name); snprintf(current_builtin_menu, sizeof(current_builtin_menu), "%s", menu_name);
menu_mode = MODE_BUILTIN; menu_mode = MODE_BUILTIN;
int duress = (access("/tmp/bananarchy_duress_mode", F_OK) == 0);
if (strcmp(menu_name, "sys") == 0) { if (strcmp(menu_name, "sys") == 0) {
reset_session_defaults(1, "Sys"); reset_session_defaults(1, "Sys");
@@ -2379,12 +2399,14 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Clear Notification", ICON_BEL); snprintf(label, sizeof(label), "%s Clear Notification", ICON_BEL);
add_menu_item(label, "@toggle:notif_clear_all", 0); add_menu_item(label, "@toggle:notif_clear_all", 0);
} }
const char *sh = getenv("SHELL"); if (!duress) {
if (!sh || !sh[0]) const char *sh = getenv("SHELL");
sh = "/bin/sh"; if (!sh || !sh[0])
snprintf(label, sizeof(label), "%s Terminal", ICON_TRM); sh = "/bin/sh";
snprintf(cmd, sizeof(cmd), "st -e %s", sh); snprintf(label, sizeof(label), "%s Terminal", ICON_TRM);
add_menu_item(label, cmd, 0); snprintf(cmd, sizeof(cmd), "st -e %s", sh);
add_menu_item(label, cmd, 0);
}
snprintf(label, sizeof(label), "%s Apps", ICON_GRD); snprintf(label, sizeof(label), "%s Apps", ICON_GRD);
add_menu_item(label, "@menu:applications", 1); add_menu_item(label, "@menu:applications", 1);
@@ -2392,14 +2414,18 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Games", ICON_GAM); snprintf(label, sizeof(label), "%s Games", ICON_GAM);
add_menu_item(label, "@menu:games", 1); add_menu_item(label, "@menu:games", 1);
snprintf(label, sizeof(label), "%s Scripts", ICON_GRD); if (!duress) {
add_menu_item(label, "@menu:scripts", 1); snprintf(label, sizeof(label), "%s Scripts", ICON_GRD);
add_menu_item(label, "@menu:scripts", 1);
}
snprintf(label, sizeof(label), "%s Files", ICON_DIR); snprintf(label, sizeof(label), "%s Files", ICON_DIR);
add_menu_item(label, "@plugin:files", 0); add_menu_item(label, "@plugin:files", 0);
snprintf(label, sizeof(label), "%s SD Card %s", ICON_DIR, sdcard_is_mounted_fast() ? ICON_TON : ICON_TOF); if (!duress) {
add_menu_item(label, "@menu:sdcard", 1); snprintf(label, sizeof(label), "%s SD Card %s", ICON_DIR, sdcard_is_mounted_fast() ? ICON_TON : ICON_TOF);
add_menu_item(label, "@menu:sdcard", 1);
}
snprintf(label, sizeof(label), "%s Dialer", ICON_PHN); snprintf(label, sizeof(label), "%s Dialer", ICON_PHN);
add_menu_item(label, "@plugin:dialer", 0); add_menu_item(label, "@plugin:dialer", 0);
@@ -2413,17 +2439,21 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Contacts", ICON_USR); snprintf(label, sizeof(label), "%s Contacts", ICON_USR);
add_menu_item(label, "@plugin:contacts", 0); add_menu_item(label, "@plugin:contacts", 0);
snprintf(label, sizeof(label), "%s SIP VoIP", ICON_PHN); if (!duress) {
add_menu_item(label, "@plugin:sip", 0); snprintf(label, sizeof(label), "%s SIP VoIP", ICON_PHN);
add_menu_item(label, "@plugin:sip", 0);
}
snprintf(label, sizeof(label), "%s Email", ICON_EML); snprintf(label, sizeof(label), "%s Email", ICON_EML);
add_menu_item(label, "@plugin:email", 0); add_menu_item(label, "@plugin:email", 0);
snprintf(label, sizeof(label), "%s IRC Chat", ICON_MSG); if (!duress) {
add_menu_item(label, "@plugin:irc", 0); snprintf(label, sizeof(label), "%s IRC Chat", ICON_MSG);
add_menu_item(label, "@plugin:irc", 0);
snprintf(label, sizeof(label), "%s Tox Messenger", ICON_MSG); snprintf(label, sizeof(label), "%s Tox Messenger", ICON_MSG);
add_menu_item(label, "@plugin:tox", 0); add_menu_item(label, "@plugin:tox", 0);
}
snprintf(label, sizeof(label), "%s Kopher (SmallWeb)", ICON_GLB); snprintf(label, sizeof(label), "%s Kopher (SmallWeb)", ICON_GLB);
add_menu_item(label, "@plugin:smallweb", 0); add_menu_item(label, "@plugin:smallweb", 0);
@@ -2485,7 +2515,7 @@ open_builtin_menu(const char *menu_name, int keep_idx)
const char *home = getenv("HOME"); const char *home = getenv("HOME");
char bpath[256]; char bpath[256];
snprintf(bpath, sizeof(bpath), "%s/.local/bin/bantam", (home && home[0]) ? home : "/home/user"); snprintf(bpath, sizeof(bpath), "%s/.local/bin/bantam", (home && home[0]) ? home : "/home/user");
if (access("/usr/bin/bantam", X_OK) == 0 || access("/usr/local/bin/bantam", X_OK) == 0 || access(bpath, X_OK) == 0) { if (!duress && (access("/usr/bin/bantam", X_OK) == 0 || access("/usr/local/bin/bantam", X_OK) == 0 || access(bpath, X_OK) == 0)) {
snprintf(label, sizeof(label), "%s Bantam", ICON_TRM); snprintf(label, sizeof(label), "%s Bantam", ICON_TRM);
add_menu_item(label, "cd \"$HOME\" && sxmo_terminal.sh bantam", 0); add_menu_item(label, "cd \"$HOME\" && sxmo_terminal.sh bantam", 0);
} }
@@ -2493,14 +2523,18 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s ReMEdy (J2ME)", ICON_GAM); snprintf(label, sizeof(label), "%s ReMEdy (J2ME)", ICON_GAM);
add_menu_item(label, "remedy", 0); add_menu_item(label, "remedy", 0);
} }
snprintf(label, sizeof(label), "%s SIP VoIP", ICON_PHN); if (!duress) {
add_menu_item(label, "@plugin:sip", 0); snprintf(label, sizeof(label), "%s SIP VoIP", ICON_PHN);
add_menu_item(label, "@plugin:sip", 0);
}
snprintf(label, sizeof(label), "%s Email", ICON_EML); snprintf(label, sizeof(label), "%s Email", ICON_EML);
add_menu_item(label, "@plugin:email", 0); add_menu_item(label, "@plugin:email", 0);
snprintf(label, sizeof(label), "%s IRC Chat", ICON_MSG); if (!duress) {
add_menu_item(label, "@plugin:irc", 0); snprintf(label, sizeof(label), "%s IRC Chat", ICON_MSG);
snprintf(label, sizeof(label), "%s Tox Messenger", ICON_MSG); add_menu_item(label, "@plugin:irc", 0);
add_menu_item(label, "@plugin:tox", 0); snprintf(label, sizeof(label), "%s Tox Messenger", ICON_MSG);
add_menu_item(label, "@plugin:tox", 0);
}
snprintf(label, sizeof(label), "%s Kopher (SmallWeb)", ICON_GLB); snprintf(label, sizeof(label), "%s Kopher (SmallWeb)", ICON_GLB);
add_menu_item(label, "@plugin:smallweb", 0); add_menu_item(label, "@plugin:smallweb", 0);
snprintf(label, sizeof(label), "%s GPS & Maps", ICON_MAP); snprintf(label, sizeof(label), "%s GPS & Maps", ICON_MAP);
@@ -2537,6 +2571,10 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Tetris", ICON_GAM); snprintf(label, sizeof(label), "%s Tetris", ICON_GAM);
add_menu_item(label, "tetris", 0); add_menu_item(label, "tetris", 0);
} }
if (access("/usr/bin/scoundrel", X_OK) == 0) {
snprintf(label, sizeof(label), "%s Scoundrel", ICON_GAM);
add_menu_item(label, "scoundrel", 0);
}
if (access("/usr/bin/gambatte", X_OK) == 0) { if (access("/usr/bin/gambatte", X_OK) == 0) {
snprintf(label, sizeof(label), "%s Game Boy (Gambatte)", ICON_GAM); snprintf(label, sizeof(label), "%s Game Boy (Gambatte)", ICON_GAM);
add_menu_item(label, "gambatte", 0); add_menu_item(label, "gambatte", 0);
@@ -2679,6 +2717,11 @@ open_builtin_menu(const char *menu_name, int keep_idx)
add_menu_item(label, "@menu:config", 1); add_menu_item(label, "@menu:config", 1);
populate_timezone_menu(); populate_timezone_menu();
} else if (strcmp(menu_name, "sdcard") == 0) { } else if (strcmp(menu_name, "sdcard") == 0) {
if (duress) {
hide_menu();
menu_mode = MODE_NONE;
return;
}
reset_session_defaults(1, "SD Card"); reset_session_defaults(1, "SD Card");
append_active_call_entries(); append_active_call_entries();
int mounted = sdcard_is_mounted_fast(); int mounted = sdcard_is_mounted_fast();
@@ -2705,6 +2748,11 @@ open_builtin_menu(const char *menu_name, int keep_idx)
if (!home || !home[0]) if (!home || !home[0])
home = "/home/user"; home = "/home/user";
if (!duress) {
snprintf(label, sizeof(label), "%s Passcode", ICON_PLK);
add_menu_item(label, "@plugin:passcode", 0);
}
snprintf(label, sizeof(label), "%s Themes", ICON_THM); snprintf(label, sizeof(label), "%s Themes", ICON_THM);
add_menu_item(label, "@plugin:themes", 0); add_menu_item(label, "@plugin:themes", 0);
snprintf(label, sizeof(label), "%s Wallpapers", ICON_THM); snprintf(label, sizeof(label), "%s Wallpapers", ICON_THM);
@@ -2719,19 +2767,23 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Bluetooth %s", ICON_BTH, bt_is_unblocked_fast() ? ICON_TON : ICON_TOF); snprintf(label, sizeof(label), "%s Bluetooth %s", ICON_BTH, bt_is_unblocked_fast() ? ICON_TON : ICON_TOF);
add_menu_item(label, "@toggle:bluetooth", 1); add_menu_item(label, "@toggle:bluetooth", 1);
snprintf(label, sizeof(label), "%s SD Card %s", ICON_DIR, sdcard_is_mounted_fast() ? ICON_TON : ICON_TOF); if (!duress) {
add_menu_item(label, "@menu:sdcard", 1); snprintf(label, sizeof(label), "%s SD Card %s", ICON_DIR, sdcard_is_mounted_fast() ? ICON_TON : ICON_TOF);
add_menu_item(label, "@menu:sdcard", 1);
}
snprintf(label, sizeof(label), "%s Change Timezone", ICON_CLK); snprintf(label, sizeof(label), "%s Change Timezone", ICON_CLK);
add_menu_item(label, "@menu:timezone", 1); add_menu_item(label, "@menu:timezone", 1);
snprintf(label, sizeof(label), "%s Hooks", ICON_TRM); if (!duress) {
add_menu_item(label, "sxmo_hookmenu.sh", 0); snprintf(label, sizeof(label), "%s Hooks", ICON_TRM);
snprintf(label, sizeof(label), "%s Log", ICON_INF); add_menu_item(label, "sxmo_hookmenu.sh", 0);
snprintf(cmd, sizeof(cmd), "sxmo_terminal.sh tail -n 100 -f %s/sxmo.log", home); snprintf(label, sizeof(label), "%s Log", ICON_INF);
add_menu_item(label, cmd, 0); snprintf(cmd, sizeof(cmd), "sxmo_terminal.sh tail -n 100 -f %s/sxmo.log", home);
snprintf(label, sizeof(label), "%s Version", ICON_INF); add_menu_item(label, cmd, 0);
add_menu_item(label, "sxmo_terminal.sh sxmo_version.sh --block", 0); snprintf(label, sizeof(label), "%s Version", ICON_INF);
add_menu_item(label, "sxmo_terminal.sh sxmo_version.sh --block", 0);
}
snprintf(label, sizeof(label), "%s System Menu", ICON_MNU); snprintf(label, sizeof(label), "%s System Menu", ICON_MNU);
add_menu_item(label, "@menu:sys", 1); add_menu_item(label, "@menu:sys", 1);
@@ -2773,6 +2825,11 @@ open_builtin_menu(const char *menu_name, int keep_idx)
add_menu_item("Yes", "sxmo_power.sh poweroff", 0); add_menu_item("Yes", "sxmo_power.sh poweroff", 0);
add_menu_item("No", "@menu:power", 1); add_menu_item("No", "@menu:power", 1);
} else if (strcmp(menu_name, "st") == 0) { } else if (strcmp(menu_name, "st") == 0) {
if (duress) {
hide_menu();
menu_mode = MODE_NONE;
return;
}
reset_session_defaults(1, "St"); reset_session_defaults(1, "St");
append_active_call_entries(); append_active_call_entries();
snprintf(label, sizeof(label), "%s New Terminal", ICON_TRM); snprintf(label, sizeof(label), "%s New Terminal", ICON_TRM);
@@ -2808,6 +2865,11 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS); snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS);
add_menu_item(label, "@close", 0); add_menu_item(label, "@close", 0);
} else if (strcmp(menu_name, "nano") == 0) { } else if (strcmp(menu_name, "nano") == 0) {
if (duress) {
hide_menu();
menu_mode = MODE_NONE;
return;
}
reset_session_defaults(1, "Nano"); reset_session_defaults(1, "Nano");
append_active_call_entries(); append_active_call_entries();
snprintf(label, sizeof(label), "%s Scroll up", ICON_ARU); snprintf(label, sizeof(label), "%s Scroll up", ICON_ARU);
@@ -2837,6 +2899,11 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS); snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS);
add_menu_item(label, "@close", 0); add_menu_item(label, "@close", 0);
} else if (strcmp(menu_name, "sthotkeys") == 0) { } else if (strcmp(menu_name, "sthotkeys") == 0) {
if (duress) {
hide_menu();
menu_mode = MODE_NONE;
return;
}
reset_session_defaults(1, "St"); reset_session_defaults(1, "St");
append_active_call_entries(); append_active_call_entries();
add_menu_item("Send Ctrl-C", "@key:ctrl:c", 0); add_menu_item("Send Ctrl-C", "@key:ctrl:c", 0);
@@ -2891,6 +2958,8 @@ any_other_plugin_active(void)
"xtox.pid", "xtox.pid",
"xsmallweb.pid", "xsmallweb.pid",
"xgps.pid", "xgps.pid",
"xpasscode.pid",
"xengmenu.pid",
}; };
const char *rdir = getenv("XDG_RUNTIME_DIR"); const char *rdir = getenv("XDG_RUNTIME_DIR");
const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000"; const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000";
@@ -2941,6 +3010,8 @@ close_other_active_plugins(void)
{ "xtox.pid", "/tmp/dwm_plugin_tox.fifo" }, { "xtox.pid", "/tmp/dwm_plugin_tox.fifo" },
{ "xsmallweb.pid", "/tmp/dwm_plugin_smallweb.fifo" }, { "xsmallweb.pid", "/tmp/dwm_plugin_smallweb.fifo" },
{ "xgps.pid", "/tmp/dwm_plugin_gps.fifo" }, { "xgps.pid", "/tmp/dwm_plugin_gps.fifo" },
{ "xpasscode.pid", "/tmp/dwm_plugin_passcode.fifo" },
{ "xengmenu.pid", "/tmp/dwm_plugin_engmenu.fifo" },
}; };
const char *rdir = getenv("XDG_RUNTIME_DIR"); const char *rdir = getenv("XDG_RUNTIME_DIR");
const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000"; const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000";
@@ -2989,6 +3060,8 @@ load_dmenu_xresources(void)
XrmInitialize(); XrmInitialize();
const char *home = getenv("HOME"); const char *home = getenv("HOME");
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0)
home = "/tmp/duress_home";
char path[512]; char path[512];
snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user"); snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user");
struct stat st; struct stat st;
@@ -3122,6 +3195,8 @@ static void
check_dmenu_xres_changed(void) check_dmenu_xres_changed(void)
{ {
const char *home = getenv("HOME"); const char *home = getenv("HOME");
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0)
home = "/tmp/duress_home";
char path[512]; char path[512];
snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user"); snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user");
struct stat st; struct stat st;
+11
View File
@@ -1282,6 +1282,7 @@ set_hw_backlight(int on)
} }
write_sysfs_str("/sys/class/leds/white:kbd_backlight/brightness", "0"); write_sysfs_str("/sys/class/leds/white:kbd_backlight/brightness", "0");
write_sysfs_str("/sys/class/backlight/backlight/brightness", "0"); write_sysfs_str("/sys/class/backlight/backlight/brightness", "0");
write_sysfs_str("/sys/class/backlight/backlight/bl_power", "4");
} }
} }
@@ -3137,6 +3138,14 @@ sigchld(int unused)
void void
spawn(const Arg *arg) spawn(const Arg *arg)
{ {
if (!arg || !arg->v || !((char **)arg->v)[0])
return;
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0) {
const char *p0 = ((const char *const *)arg->v)[0];
const char *p2 = (p0 && ((const char *const *)arg->v)[1]) ? ((const char *const *)arg->v)[2] : NULL;
if (strcmp(p0, "st") == 0 || (p2 && strcmp(p2, "st") == 0))
return;
}
if (arg->v == dmenucmd) if (arg->v == dmenucmd)
dmenumon[0] = '0' + selmon->num; dmenumon[0] = '0' + selmon->num;
if (fork() == 0) { if (fork() == 0) {
@@ -3829,6 +3838,8 @@ readxresources(void)
unsigned char *prop = NULL; unsigned char *prop = NULL;
const char *home = getenv("HOME"); const char *home = getenv("HOME");
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0)
home = "/tmp/duress_home";
char path[512]; char path[512];
snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user"); snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user");
xdb = XrmGetFileDatabase(path); xdb = XrmGetFileDatabase(path);
+2
View File
@@ -2204,6 +2204,8 @@ usage(void)
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
if (access("/tmp/bananarchy_duress_mode", F_OK) == 0)
return 1;
xw.l = xw.t = 0; xw.l = xw.t = 0;
xw.isfixed = False; xw.isfixed = False;
xsetcursor(cursorshape); xsetcursor(cursorshape);
+6 -5
View File
@@ -490,12 +490,13 @@ class PhoneController {
} }
static std::string getSxmoCfgDir() { static std::string getSxmoCfgDir() {
const char* xdg = std::getenv("XDG_CONFIG_HOME"); if (::access("/tmp/bananarchy_duress_mode", F_OK) != 0) {
if (xdg && xdg[0]) { const char* xdg = std::getenv("XDG_CONFIG_HOME");
return std::string(xdg) + "/sxmo"; if (xdg && xdg[0]) {
return std::string(xdg) + "/sxmo";
}
} }
const char* home = std::getenv("HOME"); return bananarchy::getHomeDirPath() + "/.config/sxmo";
return std::string((home && home[0]) ? home : "/home/user") + "/.config/sxmo";
} }
static int readRingerMode() { static int readRingerMode() {