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

+1
View File
@@ -745,6 +745,7 @@ int calllog_run_main(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") {
theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall,
layoutIcon, nullptr, win);
reloadLogsIfNeeded(true);
render();
}
}
+7 -6
View File
@@ -61,13 +61,14 @@ void setTorchState(bool on) {
}
std::string getPicturesDir() {
const char* xdg = std::getenv("XDG_PICTURES_DIR");
if (xdg && xdg[0]) {
::mkdir(xdg, 0755);
return xdg;
if (!isDuressMode()) {
const char* xdg = std::getenv("XDG_PICTURES_DIR");
if (xdg && xdg[0]) {
::mkdir(xdg, 0755);
return xdg;
}
}
const char* home = std::getenv("HOME");
std::string dir = std::string(home && home[0] ? home : "/home/user") + "/Pictures";
std::string dir = getHomeDirPath() + "/Pictures";
::mkdir(dir.c_str(), 0755);
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 lChanged = logStamp.checkAndUpdate(getModemLogFilePath());
if (cChanged || lChanged || !contactsLoadedOnce) {
if (force || cChanged || lChanged || !contactsLoadedOnce) {
contactsLoadedOnce = true;
book.load();
updateFilter();
@@ -984,6 +984,11 @@ int runContactsApp(int argc, char** argv) {
};
auto beginSimOperation = [&](SimOp op) {
if (isDuressMode()) {
setStatus("SIM contacts unavailable", true);
render();
return;
}
pendingSimOp = op;
prevModeBeforeSim =
(op == SimOp::ExportSingle) ? ViewMode::Detail : ViewMode::List;
@@ -1142,6 +1147,7 @@ int runContactsApp(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") {
theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall,
layoutIcon, nullptr, win);
reloadContactsIfNeeded(true);
render();
} else if (cmd == "OPEN") {
showWindow("");
+80 -50
View File
@@ -99,11 +99,15 @@ int dialer_run_main(int argc, char** argv) {
FileStamp contactsStamp;
FileStamp logStamp;
bool contactsLoadedOnce = false;
bool lastDuressState = isDuressMode();
auto reloadContactsIfNeeded = [&]() -> bool {
bool curDuress = isDuressMode();
bool dChanged = (curDuress != lastDuressState);
lastDuressState = curDuress;
bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath());
bool lChanged = logStamp.checkAndUpdate(getModemLogFilePath());
if (cChanged || lChanged || !contactsLoadedOnce) {
if (dChanged || cChanged || lChanged || !contactsLoadedOnce) {
contactsLoadedOnce = true;
book.load();
allContacts = book.buildDialerList();
@@ -524,55 +528,6 @@ int dialer_run_main(int argc, char** argv) {
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) {
if (!visible) {
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) {
showWindow(initArg);
}
@@ -843,6 +859,14 @@ int dialer_run_main(int argc, char** argv) {
openImeiModal();
continue;
}
if (number == "*#2684904#" && !isDuressMode()) {
number.clear();
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
continue;
}
updateFilter();
render();
continue;
@@ -911,6 +935,12 @@ int dialer_run_main(int argc, char** argv) {
if (!target.empty()) {
if (target == "*#06#") {
openImeiModal();
} else if (target == "*#2684904#" && !isDuressMode()) {
number.clear();
hideWindow(false);
if (!sendPluginCommand("engmenu", "OPEN")) {
runAsyncArgv("dwm-plugin", "engmenu");
}
} else if (isUssdCode(target)) {
number.clear();
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) {
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;
}
@@ -412,6 +418,18 @@ int main(int argc, char **argv) {
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 &&
strcmp(plugin_name, "locker") != 0 &&
strcmp(plugin_name, "callscreen") != 0) {
+4
View File
@@ -783,6 +783,8 @@ int email_run_main(int argc, char** argv) {
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
accounts = loadEmailAccounts();
messages = loadCachedMessages();
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("email");
visible = true;
@@ -811,6 +813,8 @@ int email_run_main(int argc, char** argv) {
if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
accounts = loadEmailAccounts();
messages = loadCachedMessages();
if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
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,
TextEdit = 7,
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 {
Name = 0,
Date = 1,
@@ -226,8 +282,7 @@ bool isLikelyTextFile(const std::string& path, off_t size) {
}
std::string shortenPath(const std::string& path) {
const char* home = std::getenv("HOME");
std::string h = (home && home[0]) ? home : "/home/user";
std::string h = getHomeDirPath();
std::string out = path;
if (out == h) {
out = "~";
@@ -356,10 +411,15 @@ int runFilesApp(int argc, char** argv) {
auto& colOrange = pt.colOrange;
auto& colRed = pt.colRed;
const char* homeEnv = std::getenv("HOME");
std::string homeDir = (homeEnv && homeEnv[0]) ? homeEnv : "/home/user";
std::string homeDir = getHomeDirPath();
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;
SortMode sortMode = SortMode::Name;
bool showHidden = false;
@@ -476,11 +536,19 @@ int runFilesApp(int argc, char** argv) {
auto loadDirectory = [&](const std::string& targetDir,
const std::string& selectName = "") {
homeDir = getHomeDirPath();
char resolved[4096];
std::string dir = targetDir;
if (::realpath(targetDir.c_str(), resolved) != nullptr) {
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());
if (!d) {
statusBanner = "Cannot open directory";
@@ -490,7 +558,8 @@ int runFilesApp(int argc, char** argv) {
currentDir = dir;
allItems.clear();
if (currentDir != "/") {
std::string topLimit = isDuressMode() ? std::string(kDuressHomeDirPath) : "/";
if (currentDir != "/" && currentDir != topLimit) {
FileItem parent;
parent.name = "..";
size_t slash = currentDir.rfind('/');
@@ -964,14 +1033,17 @@ int runFilesApp(int argc, char** argv) {
actionsList.clear();
bool hasSel = !filteredItems.empty();
bool isParent = hasSel && filteredItems[selected].isParent;
bool sdMounted = isSdCardMounted();
bool duress = isDuressMode();
bool sdMounted = !duress && isSdCardMounted();
if (hasSel) {
if (!filteredItems[selected].isDir) {
std::string ext = getExtLower(filteredItems[selected].name);
if (isImageExt(ext)) {
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)) {
actionsList.push_back({1, kIconBell, "Preview Ringtone"});
actionsList.push_back({15, kIconCheck, "Set as Ringtone"});
@@ -992,12 +1064,13 @@ int runFilesApp(int argc, char** argv) {
if (ext == "jad") {
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({17, kIconEye, "View Text"});
} else {
actionsList.push_back({1, kIconEye, "Open / View"});
}
actionsList.push_back({25, kIconBluetooth, "Send via Bluetooth"});
actionsList.push_back({16, kIconEdit, "Edit in Text Editor"});
} else {
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({4, kIconFileText, "New Empty File"});
if (hasSel && !isParent) {
if (!filteredItems[selected].isDir) {
if (!filteredItems[selected].isDir && !duress) {
actionsList.push_back({2, kIconEdit, "Edit in nano"});
}
actionsList.push_back({5, kIconEdit, "Rename"});
@@ -1028,15 +1101,17 @@ int runFilesApp(int argc, char** argv) {
else if (sortMode == SortMode::Date) sortLbl += "Size (#)";
else sortLbl += "Name (#)";
actionsList.push_back({11, kIconSort, sortLbl});
if (sdMounted) {
if (currentDir != "/media/sdcard") {
actionsList.push_back({18, kIconFolderOpen, "Open SD Card (/media/sdcard)"});
if (!duress) {
if (sdMounted) {
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"});
} else {
actionsList.push_back({20, kIconFolder, "Mount SD Card (/media/sdcard)"});
actionsList.push_back({12, kIconTerm, "Open Terminal Here"});
}
actionsList.push_back({12, kIconTerm, "Open Terminal Here"});
actionSelected = 0;
};
@@ -1734,6 +1809,64 @@ int runFilesApp(int argc, char** argv) {
drawPango(layoutSmall, &colMuted, 6, 240, 20,
"*:Play #:Set Notif L/R:Step 1:Edit", kWinWidth - 12);
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();
@@ -2118,6 +2251,12 @@ int runFilesApp(int argc, char** argv) {
statusBanner = "No SD card detected";
}
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 {
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();
};
@@ -2277,6 +2442,9 @@ int runFilesApp(int argc, char** argv) {
continue;
} else if (cmd == "RELOAD_THEME") {
pt.reload();
if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) {
loadDirectory(kDuressHomeDirPath);
}
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
@@ -2345,7 +2513,8 @@ int runFilesApp(int argc, char** argv) {
if (sym == XK_BackSpace || sym == XK_Delete) {
if (mode == ViewMode::Browser && searchQuery.empty() &&
currentDir != "/") {
currentDir != "/" &&
(!isDuressMode() || currentDir != kDuressHomeDirPath)) {
std::string prevBase = currentDir;
size_t sl = prevBase.rfind('/');
std::string prevName =
@@ -2375,7 +2544,8 @@ int runFilesApp(int argc, char** argv) {
drawUI();
}
} else if (sym == XK_Left || sym == XK_KP_Left) {
if (currentDir != "/") {
if (currentDir != "/" &&
(!isDuressMode() || currentDir != kDuressHomeDirPath)) {
std::string prevBase = currentDir;
size_t sl = prevBase.rfind('/');
std::string prevName =
@@ -2602,6 +2772,33 @@ int runFilesApp(int argc, char** argv) {
} else if (sym == XK_Return || sym == XK_KP_Enter) {
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)) {
if (cmd == "RELOAD_THEME") {
pt.reload();
if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) {
loadDirectory(kDuressHomeDirPath);
}
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
+8 -1
View File
@@ -708,7 +708,7 @@ int irc_run_main(int argc, char** argv) {
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("irc");
visible = true;
@@ -740,6 +740,13 @@ int irc_run_main(int argc, char** argv) {
if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow();
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();
if (visible) render();
} 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/backlight/backlight/brightness", "0");
writeSysfsStr("/sys/class/backlight/backlight/bl_power", "4");
}
void wakeScreenBacklight() {
@@ -140,17 +141,37 @@ bool constantTimeEq(const std::string& a, const std::string& b) {
return diff == 0;
}
enum class VerifyResult {
Invalid = 0,
NormalUser = 1,
DuressUser = 2,
};
class PasscodeVerifier {
public:
void forceRefresh() {
shadowMtime_ = 0;
shadowSize_ = 0;
duressMtime_ = -1;
cachedHash_.clear();
cachedDuressHash_.clear();
refreshIfNeeded();
}
void refreshIfNeeded() {
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 (!cachedHash_.empty() && st.st_mtim.tv_sec == shadowMtime_ &&
st.st_size == shadowSize_) {
st.st_size == shadowSize_ && curDuressMtime == duressMtime_) {
return;
}
shadowMtime_ = st.st_mtim.tv_sec;
shadowSize_ = st.st_size;
duressMtime_ = curDuressMtime;
}
int pipefd[2];
if (::pipe(pipefd) != 0) {
@@ -172,12 +193,12 @@ class PasscodeVerifier {
::close(pipefd[1]);
}
::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));
::_exit(1);
}
::close(pipefd[1]);
char buf[256];
char buf[512];
ssize_t n = ::read(pipefd[0], buf, sizeof(buf) - 1);
::close(pipefd[0]);
int status = 0;
@@ -185,32 +206,51 @@ class PasscodeVerifier {
::waitpid(pid, &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';
if (buf[0] == '$') {
cachedHash_ = buf;
cachedDuressHash_.clear();
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()) {
return false;
return VerifyResult::Invalid;
}
refreshIfNeeded();
if (!cachedHash_.empty()) {
char* res = ::crypt(candidate.c_str(), cachedHash_.c_str());
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
int pipefd[2];
if (::pipe(pipefd) != 0) {
return false;
return VerifyResult::Invalid;
}
pid_t pid = ::fork();
if (pid == 0) {
@@ -237,16 +277,24 @@ class PasscodeVerifier {
(void)::write(pipefd[1], line.data(), line.size());
::close(pipefd[1]);
int status = 0;
if (pid > 0 && ::waitpid(pid, &status, 0) > 0) {
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
if (pid > 0 && ::waitpid(pid, &status, 0) > 0 && WIFEXITED(status)) {
int code = WEXITSTATUS(status);
if (code == 0) {
return VerifyResult::NormalUser;
}
if (code == 10) {
return VerifyResult::DuressUser;
}
}
return false;
return VerifyResult::Invalid;
}
private:
std::string cachedHash_;
std::string cachedDuressHash_;
time_t shadowMtime_ = 0;
off_t shadowSize_ = 0;
time_t duressMtime_ = -1;
};
int countNotifFiles() {
@@ -545,7 +593,17 @@ int locker_run_main(int argc, char** argv) {
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();
statusMsg.clear();
statusIsError = false;
@@ -606,11 +664,16 @@ int locker_run_main(int argc, char** argv) {
}
return;
}
if (verifier.verify(passcode)) {
unlockPhone();
VerifyResult vres = verifier.verify(passcode);
if (vres == VerifyResult::NormalUser) {
unlockPhone(false);
return;
}
if (explicitSubmit || passcode.size() >= 12) {
if (vres == VerifyResult::DuressUser) {
unlockPhone(true);
return;
}
if (explicitSubmit || passcode.size() >= 32) {
passcode.clear();
++failedAttempts;
statusIsError = true;
@@ -642,6 +705,10 @@ int locker_run_main(int argc, char** argv) {
if (cmd == "NOP") {
continue;
}
if (cmd == "RELOAD_HASH") {
verifier.forceRefresh();
continue;
}
if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
updateClockFont();
@@ -677,8 +744,12 @@ int locker_run_main(int argc, char** argv) {
}
if (cmd.rfind("VERIFY ", 0) == 0) {
std::string code = trimStr(cmd.substr(7));
if (cooldownUntilMs <= nowMs() && verifier.verify(code)) {
unlockPhone();
VerifyResult vres =
(cooldownUntilMs <= nowMs()) ? verifier.verify(code)
: VerifyResult::Invalid;
if (vres == VerifyResult::NormalUser ||
vres == VerifyResult::DuressUser) {
unlockPhone(vres == VerifyResult::DuressUser);
} else {
passcode.clear();
++failedAttempts;
@@ -829,13 +900,18 @@ int locker_run_main(int argc, char** argv) {
}
int timeoutMs = -1;
if (visible) {
if (isScreenBlanked()) {
timeoutMs = 2000;
} else if (cooldownUntilMs > nowMs()) {
if (visible && !isScreenBlanked()) {
int64_t now = nowMs();
if (cooldownUntilMs > now) {
timeoutMs = 250;
} else if (statusClearAtMs > now) {
timeoutMs = static_cast<int>(
std::clamp<int64_t>(statusClearAtMs - now, 100, 5000));
} 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() {
const char* h = std::getenv("HOME");
return (h && *h) ? std::string(h) : "/home/user";
return getHomeDirPath();
}
std::string getConfigDirPath() {
const char* c = std::getenv("XDG_CONFIG_HOME");
if (c && *c) return std::string(c) + "/sxmo";
if (!isDuressMode()) {
const char* c = std::getenv("XDG_CONFIG_HOME");
if (c && *c) return std::string(c) + "/sxmo";
}
return getHomePath() + "/.config/sxmo";
}
@@ -617,6 +618,12 @@ int runMusicApp(int argc, char** argv) {
if (::realpath(targetDir.c_str(), resolved) != nullptr) {
dir = resolved;
}
if (isDuressMode()) {
std::string root = getHomeDirPath();
if (dir != root && dir.rfind(root + "/", 0) != 0) {
dir = root;
}
}
DIR* d = ::opendir(dir.c_str());
if (!d) {
setBanner("Cannot open folder");
@@ -625,7 +632,8 @@ int runMusicApp(int argc, char** argv) {
browserDir = dir;
browserItems.clear();
if (browserDir != "/") {
std::string topLimit = isDuressMode() ? getHomeDirPath() : "/";
if (browserDir != "/" && browserDir != topLimit) {
BrowserItem up;
up.name = ".. (Up)";
size_t sl = browserDir.rfind('/');
+137 -43
View File
@@ -111,6 +111,45 @@ struct BtDeviceEntry {
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() {
std::string out = runCaptureCmd("/usr/sbin/rfkill list wifi 2>/dev/null");
if (out.find("Soft blocked: yes") != std::string::npos ||
@@ -409,7 +448,8 @@ int runNetworksApp(int argc, char** argv) {
bool btOn = false;
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;
@@ -463,6 +503,8 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Bluetooth) {
btOn = isBtEnabledFast();
if (btOn) {
runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1");
btRx = readBtRxStatus();
if (forceScan) {
runCaptureCmd("bluetoothctl --timeout 5 scan on >/dev/null 2>&1");
}
@@ -470,7 +512,7 @@ int runNetworksApp(int argc, char** argv) {
} else {
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;
}
};
@@ -687,58 +729,97 @@ int runNetworksApp(int argc, char** argv) {
}
drawSoftkeyBar("Refresh", "Select", "Close");
} else if (activeTab == NetTab::Bluetooth) {
// Row 0: BT Power Toggle (height 28)
// Row 0: BT Power Toggle (height 26)
bool sel0 = (btRowSel == 0);
XSetForeground(dpy, gc, sel0 ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 28);
drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 28, kIconBluetooth);
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 26);
drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 26, kIconBluetooth);
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,
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);
XSetForeground(dpy, gc, sel1 ? pt.spec.selBg : pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 4, contentY + 30, kWinWidth - 8, 26);
drawPango(layoutIcon, &colYellow, 10, contentY + 30, 26, kIconSearch);
XFillRectangle(dpy, pix, gc, 4, contentY + 28, kWinWidth - 8, 24);
drawPango(layoutIcon, &colYellow, 10, contentY + 28, 24, kIconSearch);
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) {
drawPango(layoutMain, &colMuted, 18, listY + 40, 24,
drawPango(layoutMain, &colMuted, 18, contentY + 96, 24,
"Bluetooth is turned off.");
} else if (btList.empty()) {
drawPango(layoutMain, &colMuted, 18, listY + 40, 24,
"No devices. Select Scan.");
} else {
const int rowH = 38;
const int maxVis = listH / rowH; // 4 rows
int devSel = std::max(0, btRowSel - 2);
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 + 2));
// Row 2: Bluetooth File Reception Widget (height 36)
bool sel2 = (btRowSel == 2);
int rxY = contentY + 54;
XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 36);
XSetForeground(dpy, gc, btRx.state == "RECEIVING" ? pt.spec.warning
: (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.accent));
XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 35);
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,
btRx.state == "RECEIVED" ? &colGreen
: (btRx.state == "RECEIVING" ? &colYellow : &colBlue),
10, rxY + 1, 18,
btRx.state == "RECEIVED" ? kIconCheck : kIconFolderOpen);
drawPango(layoutIcon, d.connected ? &colGreen : (d.paired ? &colBlue : &colMuted),
10, ry + 1, 20, kIconBluetooth);
drawPango(layoutMain, isSel ? &colWhite : &colLight,
30, ry + 1, 20, d.name, kWinWidth - 42);
if (btRx.state == "RECEIVING") {
drawPango(layoutSmall, &colYellow, 30, rxY + 1, 18,
"Receiving: " + btRx.fileName + " (" + btRx.detail + ")",
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] "
: (d.paired ? "[Paired] " : "[Available] ");
st += d.mac;
drawPango(layoutSmall, d.connected ? &colGreen : (isSel ? &colLight : &colMuted),
30, ry + 19, 17, st, kWinWidth - 42);
int listY = contentY + 92;
int listH = contentH - 92;
if (btList.empty()) {
drawPango(layoutMain, &colMuted, 18, listY + 34, 24,
"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");
@@ -1179,8 +1260,18 @@ int runNetworksApp(int argc, char** argv) {
render();
refreshCurrentTab(true);
setBanner("Found " + std::to_string(btList.size()) + " device(s)");
} else if (btRowSel - 2 < static_cast<int>(btList.size())) {
targetBt = btList[btRowSel - 2];
} else if (btRowSel == 2 && btOn) {
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;
modal = NetModal::BtActions;
}
@@ -1373,7 +1464,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 3) % 4;
} 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;
}
render();
@@ -1384,7 +1475,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 1) % 4;
} 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;
}
render();
@@ -1453,6 +1544,9 @@ int runNetworksApp(int argc, char** argv) {
} else if (cmd == "RELOAD_THEME") {
pt.reload();
if (visible) render();
} else if (cmd == "REFRESH_BT") {
btRx = readBtRxStatus();
if (visible) render();
} else if (cmd == "TOGGLE") {
if (visible) hideWindow();
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;
long nsec = -1;
off_t size = -1;
std::string lastPath;
bool checkAndUpdate(const std::string& path) {
bool pathChanged = (path != lastPath);
lastPath = path;
struct stat st {};
if (::stat(path.c_str(), &st) != 0) {
if (sec != 0 || size != 0) {
if (pathChanged || sec != 0 || size != 0) {
sec = 0;
nsec = 0;
size = 0;
@@ -307,8 +310,8 @@ struct FileStamp {
}
return false;
}
if (st.st_mtim.tv_sec != sec || st.st_mtim.tv_nsec != nsec ||
st.st_size != size) {
if (pathChanged || st.st_mtim.tv_sec != sec ||
st.st_mtim.tv_nsec != nsec || st.st_size != size) {
sec = st.st_mtim.tv_sec;
nsec = st.st_mtim.tv_nsec;
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;
}
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() {
if (isDuressMode()) {
return kDuressHomeDirPath;
}
return getHomeDirPath();
}
@@ -587,6 +600,9 @@ inline std::string toT9Digits(const std::string& name) {
}
inline std::string getContactsFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.config/sxmo/contacts.tsv";
}
const char* env = std::getenv("SXMO_CONTACTFILE");
if (env && env[0]) {
return env;
@@ -601,6 +617,10 @@ inline std::string getContactsFilePath() {
}
inline std::string getModemLogFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) +
"/.local/share/sxmo/modem/modemlog.tsv";
}
const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) {
return std::string(env) + "/modemlog.tsv";
@@ -993,6 +1013,9 @@ class ContactBook {
};
inline std::string getBlockFilePath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.config/sxmo/block.tsv";
}
const char* env = std::getenv("SXMO_BLOCKFILE");
if (env && env[0]) {
return env;
@@ -1007,6 +1030,9 @@ inline std::string getBlockFilePath() {
}
inline std::string getBlockDirPath() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.local/share/sxmo/block";
}
const char* env = std::getenv("SXMO_BLOCKDIR");
if (env && env[0]) {
return env;
@@ -1767,6 +1793,10 @@ inline DualSimInfo queryDualSimInfo(bool forceRefresh = false) {
int sub2 = (info.primaryGwSlot == 2) ? 0 : ((info.secondaryGwSlot == 2) ? 1 : -1);
querySubMeta(1, sub1, info.slot1Operator, info.slot1Rat, info.slot1Number);
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,
const std::string& num, std::string& outLabel,
@@ -1842,6 +1872,8 @@ inline void closeOtherPlugins(const char* selfPluginName) {
{"xtox.pid", "tox"},
{"xsmallweb.pid", "smallweb"},
{"xgps.pid", "gps"},
{"xpasscode.pid", "passcode"},
{"xengmenu.pid", "engmenu"},
};
for (const auto& p : kAllPlugins) {
if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) {
@@ -1884,6 +1916,8 @@ inline bool isAnotherPluginActive(const char* selfPluginName) {
{"xtox.pid", "tox"},
{"xsmallweb.pid", "smallweb"},
{"xgps.pid", "gps"},
{"xpasscode.pid", "passcode"},
{"xengmenu.pid", "engmenu"},
};
for (const auto& p : kAllPlugins) {
if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) {
@@ -1935,6 +1969,8 @@ inline void broadcastThemeReload(const char* selfPluginName = nullptr) {
"tox",
"smallweb",
"gps",
"passcode",
"engmenu",
};
for (const char* name : kPlugins) {
if (selfPluginName && std::strcmp(name, selfPluginName) == 0) {
@@ -1947,10 +1983,13 @@ inline void broadcastThemeReload(const char* selfPluginName = nullptr) {
::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() {
if (isDuressMode()) {
return std::string(kDuressHomeDirPath) + "/.local/share/sxmo/modem";
}
const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) {
return env;
@@ -2411,8 +2450,111 @@ inline bool queryQrtrDmsImeis(DeviceImeis& out) {
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() {
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()) {
return cached;
}
@@ -2441,6 +2583,16 @@ inline DeviceImeis queryDeviceImeis() {
}
if (!res.imei1.empty()) {
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;
}
@@ -3007,6 +3159,10 @@ inline bool qrtrReadSimContacts(
std::string& outErr) {
outContacts.clear();
outErr.clear();
if (isDuressMode()) {
outErr = "SIM phonebook empty";
return false;
}
int sfd = -1;
uint32_t uimNode = 0, uimPort = 0;
@@ -3045,6 +3201,10 @@ inline bool qrtrWriteSimContacts(
int& outExported, std::string& outErr) {
outExported = 0;
outErr.clear();
if (isDuressMode()) {
outErr = "SIM phonebook unavailable";
return false;
}
if (contactsToWrite.empty()) {
outErr = "No contacts to export";
return false;
+24 -12
View File
@@ -1268,7 +1268,7 @@ int sip_run_main(int argc, char** argv) {
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("sip");
visible = true;
@@ -1287,9 +1287,11 @@ int sip_run_main(int argc, char** argv) {
};
// Trigger initial background registration for enabled accounts
for (auto& acct : accounts) {
if (acct.enabled) {
sendSipRegister(acct);
if (!isDuressMode()) {
for (auto& acct : accounts) {
if (acct.enabled) {
sendSipRegister(acct);
}
}
}
@@ -1304,6 +1306,13 @@ int sip_run_main(int argc, char** argv) {
if (cmd == "CLOSE") {
closeWindow();
} else if (cmd == "RELOAD_THEME") {
if (isDuressMode()) {
hangupActiveSipCall(false);
accounts.clear();
history.clear();
closeWindow();
continue;
}
neo.reloadTheme();
if (visible) render();
} 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,
reinterpret_cast<struct sockaddr*>(&fromSin), &sl);
if (n <= 0) break;
if (isDuressMode()) continue;
rxBuf[n] = '\0';
handleIncomingSipPacket(std::string(rxBuf, static_cast<size_t>(n)), fromSin);
if (visible) render();
@@ -1348,14 +1358,16 @@ int sip_run_main(int argc, char** argv) {
// 3. Periodic REGISTER keepalive for enabled accounts
int64_t now = nowMs();
bool anyEnabled = false;
for (auto& acct : accounts) {
if (!acct.enabled) continue;
anyEnabled = true;
if (acct.lastRegAttemptMs == 0 ||
(acct.regStatus == "ONLINE" && now >= acct.regExpiresAtMs) ||
(acct.regStatus != "ONLINE" && now - acct.lastRegAttemptMs >= 45000)) {
sendSipRegister(acct);
if (visible) render();
if (!isDuressMode()) {
for (auto& acct : accounts) {
if (!acct.enabled) continue;
anyEnabled = true;
if (acct.lastRegAttemptMs == 0 ||
(acct.regStatus == "ONLINE" && now >= acct.regExpiresAtMs) ||
(acct.regStatus != "ONLINE" && now - acct.lastRegAttemptMs >= 45000)) {
sendSipRegister(acct);
if (visible) render();
}
}
}
+2
View File
@@ -1343,6 +1343,7 @@ int runSmsApp(int argc, char** argv) {
continue;
} else if (cmd == "RELOAD_THEME") {
pt.reload();
reloadAllData(true);
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
@@ -1753,6 +1754,7 @@ int runSmsApp(int argc, char** argv) {
for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "RELOAD_THEME") {
pt.reload();
reloadAllData(true);
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
+39 -14
View File
@@ -106,9 +106,7 @@ void popUtf8(std::string& s) {
}
std::string getXthemesDir() {
const char* home = std::getenv("HOME");
std::string dir =
std::string((home && home[0]) ? home : "/home/user") + "/.xthemes";
std::string dir = getHomeDirPath() + "/.xthemes";
::mkdir(dir.c_str(), 0755);
return dir;
}
@@ -147,6 +145,26 @@ void updateRootResourceManager(const std::string& xresContent,
void ensureDefaultThemesSeeded() {
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";
if (::access(defPath.c_str(), 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") {
continue;
}
if (isDuressMode() && fname != "NordFrost.xth") {
continue;
}
ThemeFileEntry item;
item.name = fname.substr(0, fname.size() - 4);
item.fullPath = dir + "/" + fname;
@@ -469,16 +490,20 @@ int runThemesApp(int argc, char** argv) {
actionsList.clear();
if (!themes.empty()) {
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 (!themes.empty()) {
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({7, kIconTrash, "Delete Theme"});
if (!isDuressMode()) {
actionsList.push_back({3, kIconPlus, "Save Current as New Theme"});
if (!themes.empty()) {
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({7, kIconTrash, "Delete Theme"});
}
}
actionSelected = 0;
};
@@ -1145,13 +1170,13 @@ int runThemesApp(int argc, char** argv) {
drawUI();
} else {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (d == '*' && !themes.empty()) {
if (d == '*' && !themes.empty() && !isDuressMode()) {
editSpec = themes[selected].spec;
editThemeName = themes[selected].name;
editField = 0;
mode = ViewMode::Customize;
drawUI();
} else if (d == '#') {
} else if (d == '#' && !isDuressMode()) {
nameAction = NameModalAction::SaveCurrentAs;
nameTitle = "Save Theme As";
nameInput = "Custom";
+7 -2
View File
@@ -637,7 +637,7 @@ int tox_run_main(int argc, char** argv) {
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
if (isDuressMode() || isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("tox");
visible = true;
@@ -665,6 +665,11 @@ int tox_run_main(int argc, char** argv) {
if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") {
if (isDuressMode()) {
closeWindow();
networkActive = false;
continue;
}
neo.reloadTheme();
if (visible) render();
} 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
bool shouldIterateTox =
networkActive && tox &&
!isDuressMode() && networkActive && tox &&
(visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0);
if (shouldIterateTox) {
tox_iterate(tox, &ctx);
+358 -10
View File
@@ -1,5 +1,5 @@
// 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
#define _DEFAULT_SOURCE
@@ -8,13 +8,19 @@
#define _XOPEN_SOURCE 700
#endif
#include <crypt.h>
#include <ctype.h>
#include <fcntl.h>
#include <pwd.h>
#include <shadow.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.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) {
if (!a || !b) {
return 0;
@@ -31,13 +37,204 @@ static int constant_time_eq(const char *a, const char *b) {
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 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";
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--print-hash") == 0) {
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] != '-') {
username = argv[i];
}
@@ -47,6 +244,13 @@ int main(int argc, char **argv) {
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);
const char *hash = (sp && sp->sp_pwdp) ? sp->sp_pwdp : NULL;
if (!hash || !hash[0]) {
@@ -62,22 +266,166 @@ int main(int argc, char **argv) {
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];
if (!fgets(pass, sizeof(pass), stdin)) {
return 1;
}
size_t len = strlen(pass);
while (len > 0 && (pass[len - 1] == '\n' || pass[len - 1] == '\r')) {
pass[--len] = '\0';
}
if (len == 0) {
trim_crlf(pass);
if (pass[0] == '\0') {
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));
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]));
std::string getConfigDir() {
if (isDuressMode()) {
return getHomeDirPath() + "/.config/sxmo";
}
const char* xdg = std::getenv("XDG_CONFIG_HOME");
if (xdg && *xdg) {
return std::string(xdg) + "/sxmo";
@@ -132,6 +135,19 @@ void scanWallpaperDir(const std::string& dirPath,
std::vector<WallpaperEntry> discoverWallpapers() {
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);
std::string home = getHomeDirPath();
@@ -141,6 +157,9 @@ std::vector<WallpaperEntry> discoverWallpapers() {
}
std::string loadActiveWallpaperPath() {
if (isDuressMode()) {
return "/usr/share/wallpapers/nordic-peaks.png";
}
std::ifstream ifs(getConfigDir() + "/wallpaper");
if (ifs) {
std::string line;
@@ -664,7 +683,7 @@ int runWallpapersApp(int argc, char** argv) {
hideWindow();
} else if (cmd == "RELOAD_THEME") {
pt.reload();
cachedImgPath.clear();
refreshData();
if (visible) render();
} else if (cmd == "TOGGLE") {
if (visible) hideWindow();