diff --git a/CLAUDE.md b/CLAUDE.md index e067a62..1dca289 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,13 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11) - **Ajustes del sistema**: el sistema es la fuente de verdad. `packaging/zeropower-helper` (bash, se instala en `/usr/lib/zeropower/`): `status` sin root; `set ` y `restore` con root, por `sudo -n` con el sudo sin contraseña que trae el usuario del aparato - (`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). **La tienda no deja + (`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). Si sudo pide + contraseña (`classify_sudo` en `src/model/sudo_password.h`), `SettingsScreen` la pide encima + de la lista y `PowerControl::apply` repite con `sudo -S -p ""`, pasándola por la entrada + estándar de `run_process` y borrándola al acabar (`SecretInput`, `wipe`). En el simulador se + prueba con `ZEROPOWER_SIMULATE_SUDO=`. Para teclearla, `linux_input` entiende Shift + y la capa Sym del Cardputer (lee `/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map`), y + la T no cambia el tema mientras se escribe (`set_text_entry`). **La tienda no deja instalar sudoers** (ni en `/etc/sudoers.d` ni desde los scripts: busca `/etc/sudoers`), ni polkit. Guarda el original de cada ajuste en `/var/lib/zeropower/original/` y `restore` (en el `prerm`) lo devuelve. **No hay servicio de root al arrancar** (la tienda rechaza diff --git a/README.md b/README.md index 68124c9..303aa5c 100644 --- a/README.md +++ b/README.md @@ -62,8 +62,11 @@ volver a aplicarlo. **Al desinstalar ZeroPower, todo lo que cambió vuelve a com `/usr/lib/zeropower/zeropower-helper status` (sin root). - **Para cambiar algo** llama a `sudo -n /usr/lib/zeropower/zeropower-helper set `, con el `sudo` sin contraseña que el usuario del aparato ya trae de fábrica (lo pone el - Raspberry Pi Imager). ZeroPower **no instala ningún fichero de sudoers** ni da permisos - nuevos; sin sudo sin contraseña, la app avisa y no cambia nada. El ayudante es un script de + Raspberry Pi Imager). Si tu usuario necesita contraseña para sudo, la app la pide en + pantalla y repite el cambio con `sudo -S`: la contraseña va por la entrada estándar (nunca + en la línea de órdenes), no se guarda y se borra de la memoria al acabar; sudo la recuerda + unos minutos, como en un terminal. ZeroPower **no instala ningún fichero de sudoers** ni da + permisos nuevos; un usuario sin sudo no puede cambiar nada. El ayudante es un script de bash corto que acepta una lista cerrada de ajustes y valores; la primera vez que cambia algo guarda su valor original en `/var/lib/zeropower/original/` para poder devolverlo (`zeropower-helper restore`, que se ejecuta al desinstalar). diff --git a/app-builder.json b/app-builder.json index 4c060a3..7bcd4ec 100644 --- a/app-builder.json +++ b/app-builder.json @@ -6,7 +6,7 @@ "description": "Battery saver and power settings for the Cardputer Zero", "store": { "summary": "Battery saver: live power draw, turn off Ethernet, HDMI, BT, services", - "description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm) and the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM).\n- Services: Tailscale, background extras (NFS, rpcbind, avahi, apt timers) and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off pauses the launcher and parks its audio (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's passwordless sudo (as set up by Raspberry Pi Imager); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).", + "description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm) and the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM).\n- Services: Tailscale, background extras (NFS, rpcbind, avahi, apt timers) and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off pauses the launcher and parks its audio (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's sudo: passwordless as set up by Raspberry Pi Imager, or ZeroPower asks for the password on screen (never stored); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).", "categories": [ "System Tools" ], diff --git a/src/app/app.cpp b/src/app/app.cpp index 68ec314..cd5675a 100644 --- a/src/app/app.cpp +++ b/src/app/app.cpp @@ -154,7 +154,7 @@ class ShortcutController { const auto result = platform::screenshot::capture_active_screen(); if (result.success) { LOG_INFO("screenshot saved: {}", result.path); - toast_->show_highlighted("Guardada en ", + toast_->show_highlighted("Saved to ", result.path, "", view::widgets::ToastTone::Success, @@ -163,7 +163,7 @@ class ShortcutController { } else { LOG_WARN("screenshot failed: {}", result.error); - toast_->show("No se pudo capturar: " + result.error, + toast_->show("Screenshot failed: " + result.error, view::widgets::ToastTone::Error, 3200); } @@ -230,7 +230,7 @@ class ShortcutController { if (!view_model_.back()) { // Ya no hay adónde volver: se recuerda cómo se sale en vez de salir con // una pulsación que pudo ser de más. - toast_->show_highlighted("Mantén ", "ESC", " para salir", view::widgets::ToastTone::Warning, 2200); + toast_->show_highlighted("Hold ", "ESC", " to exit", view::widgets::ToastTone::Warning, 2200); } } diff --git a/src/model/sudo_password.cpp b/src/model/sudo_password.cpp new file mode 100644 index 0000000..5311f6c --- /dev/null +++ b/src/model/sudo_password.cpp @@ -0,0 +1,95 @@ +/* + * SPDX-License-Identifier: MIT + */ + +#include "sudo_password.h" + +namespace power { +namespace { + +bool contains(const std::string& text, const char* what) { + return text.find(what) != std::string::npos; +} + +} // namespace + +SudoOutcome classify_sudo(int exit_code, const std::string& output) { + if (exit_code == 0) { + return SudoOutcome::Ok; + } + // "Sorry, try again." sale en cuanto una contraseña falla, aunque luego diga otra cosa. + if (contains(output, "incorrect password") || contains(output, "Sorry, try again")) { + return SudoOutcome::WrongPassword; + } + if (contains(output, "a password is required") || contains(output, "no password was provided")) { + return SudoOutcome::NeedsPassword; + } + if (contains(output, "is not in the sudoers") || contains(output, "is not allowed to") || + contains(output, "may not run sudo")) { + return SudoOutcome::NotAllowed; + } + return SudoOutcome::Failed; +} + +void wipe(std::string& text) { + volatile char* p = text.empty() ? nullptr : &text[0]; + for (std::size_t i = 0; i < text.size(); ++i) { + p[i] = '\0'; + } + text.clear(); +} + +SecretInput::SecretInput() { + text_.reserve(kMaxLength + 1); // +1: el salto de línea de take_line() +} + +SecretInput::~SecretInput() { + clear(); +} + +bool SecretInput::add(std::uint32_t ch) { + if (ch < 0x20 || ch > 0x7E || text_.size() >= kMaxLength) { + return false; + } + text_.push_back(static_cast(ch)); + return true; +} + +bool SecretInput::backspace() { + if (text_.empty()) { + return false; + } + text_.back() = '\0'; + text_.pop_back(); + return true; +} + +void SecretInput::clear() { + wipe(text_); +} + +std::string SecretInput::masked(std::size_t max_dots) const { + std::string out; + std::size_t dots = text_.size(); + if (dots > max_dots) { + out = "\u2026"; + dots = max_dots; + } + for (std::size_t i = 0; i < dots; ++i) { + out += "\u2022"; + } + return out; +} + +std::string SecretInput::take_line() { + // Siempre en el montón (más de lo que cabe dentro del propio std::string): al moverla de + // un sitio a otro se pasa el puntero y no quedan copias sueltas. + std::string line; + line.reserve(kMaxLength + 1); + line = text_; + line.push_back('\n'); + clear(); + return line; +} + +} // namespace power diff --git a/src/model/sudo_password.h b/src/model/sudo_password.h new file mode 100644 index 0000000..2aca8fa --- /dev/null +++ b/src/model/sudo_password.h @@ -0,0 +1,61 @@ +/* + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include +#include +#include + +namespace power { + +// Qué ha pasado con una orden lanzada con sudo, según su código de salida y lo que dice +// (sudo se lanza con LC_ALL=C: los mensajes llegan en inglés). +enum class SudoOutcome { + Ok, // la orden se ejecutó y acabó bien + NeedsPassword, // `sudo -n` sin contraseña guardada: hay que pedirla + WrongPassword, // la contraseña no vale + NotAllowed, // el usuario no puede usar sudo para esto + Failed, // la orden se ejecutó y falló, o sudo falló por otra cosa +}; + +SudoOutcome classify_sudo(int exit_code, const std::string& output); + +// Borra el contenido de verdad (el compilador no puede quitarse la escritura de encima) y +// deja la cadena vacía. +void wipe(std::string& text); + +// Lo que se teclea en la pantalla de la contraseña. Reserva la memoria de una vez, para +// que al crecer no queden copias de la contraseña por el montón, y la borra al limpiar. +class SecretInput { +public: + static constexpr std::size_t kMaxLength = 128; + + SecretInput(); + ~SecretInput(); + SecretInput(const SecretInput&) = delete; + SecretInput& operator=(const SecretInput&) = delete; + + bool add(std::uint32_t ch); // sólo ASCII imprimible; false si no cabe o no vale + bool backspace(); + void clear(); + + std::size_t size() const { + return text_.size(); + } + bool empty() const { + return text_.empty(); + } + // Un punto por carácter, para enseñarla sin enseñarla. Si son más de `max_dots`, sólo + // los últimos, detrás de «…». + std::string masked(std::size_t max_dots = kMaxLength) const; + // Lo tecleado seguido de un salto de línea (lo que espera `sudo -S`), y se borra de aquí. + // Quien lo recibe tiene que borrarlo con wipe() al acabar. + std::string take_line(); + +private: + std::string text_; +}; + +} // namespace power diff --git a/src/platform/linux_input.cpp b/src/platform/linux_input.cpp index ee9ab8d..89867f5 100644 --- a/src/platform/linux_input.cpp +++ b/src/platform/linux_input.cpp @@ -51,6 +51,11 @@ struct EvdevKeypad { bool router_event_pending{false}; uint32_t router_key{0}; bool router_pressed{false}; + bool cardputer{false}; // el teclado del Cardputer (tca8418), con su capa Sym + bool shift{false}; + // Lo que dio cada tecla al pulsarla: al soltarla tiene que salir lo mismo aunque + // entretanto se haya soltado Shift, o se quedaría pulsada. + std::array pressed_as{}; }; #endif @@ -242,10 +247,118 @@ uint32_t map_evdev_char(uint16_t code) { return 0; } -uint32_t map_evdev_key(uint16_t code) { +// Teclado de PC (distribución de EE. UU.): lo que dan los números y signos con Shift, y los +// signos que map_evdev_char no trae (sólo hacen falta para escribir la contraseña). +uint32_t map_us_symbol(uint16_t code, bool shift) { + static constexpr struct { + uint16_t code; + char plain; + char shifted; + } kSymbols[] = { + {KEY_1, '1', '!'}, {KEY_2, '2', '@'}, {KEY_3, '3', '#'}, + {KEY_4, '4', '$'}, {KEY_5, '5', '%'}, {KEY_6, '6', '^'}, + {KEY_7, '7', '&'}, {KEY_8, '8', '*'}, {KEY_9, '9', '('}, + {KEY_0, '0', ')'}, {KEY_MINUS, '-', '_'}, {KEY_EQUAL, '=', '+'}, + {KEY_LEFTBRACE, '[', '{'}, {KEY_RIGHTBRACE, ']', '}'}, {KEY_SEMICOLON, ';', ':'}, + {KEY_APOSTROPHE, '\'', '"'}, {KEY_GRAVE, '`', '~'}, {KEY_BACKSLASH, '\\', '|'}, + {KEY_COMMA, ',', '<'}, {KEY_DOT, '.', '>'}, {KEY_SLASH, '/', '?'}, + {KEY_KPASTERISK, '*', '*'}, {KEY_KPSLASH, '/', '/'}, {KEY_KPDOT, '.', '.'}, + }; + for (const auto& entry : kSymbols) { + if (entry.code == code) { + return static_cast(shift ? entry.shifted : entry.plain); + } + } + return 0; +} + +// La capa Sym del Cardputer: el teclado manda códigos propios para cada signo, que no son +// los de un teclado de PC (el 51, la coma de un PC, aquí es «&»). Se leen de su mapa de +// teclas, que trae el sistema, y si no está, los de la versión que hay ahora. +constexpr const char* kCardputerKeymap = "/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map"; + +uint32_t keysym_char(const std::string& name) { + static constexpr struct { + const char* name; + char ch; + } kNames[] = { + {"exclam", '!'}, {"at", '@'}, {"numbersign", '#'}, {"dollar", '$'}, + {"percent", '%'}, {"asciicircum", '^'}, {"ampersand", '&'}, {"asterisk", '*'}, + {"parenleft", '('}, {"parenright", ')'}, {"asciitilde", '~'}, {"grave", '`'}, + {"underscore", '_'}, {"minus", '-'}, {"plus", '+'}, {"equal", '='}, + {"bracketleft", '['}, {"bracketright", ']'}, {"braceleft", '{'}, {"braceright", '}'}, + {"semicolon", ';'}, {"colon", ':'}, {"apostrophe", '\''}, {"quotedbl", '"'}, + {"less", '<'}, {"greater", '>'}, {"backslash", '\\'}, {"bar", '|'}, + {"comma", ','}, {"period", '.'}, {"slash", '/'}, {"question", '?'}, + }; + for (const auto& entry : kNames) { + if (name == entry.name) { + return static_cast(entry.ch); + } + } + return 0; +} + +const std::array& cardputer_symbols() { + static const std::array table = [] { + std::array t{}; + bool loaded = false; + if (FILE* f = std::fopen(kCardputerKeymap, "r")) { + char line[160]; + while (std::fgets(line, sizeof(line), f)) { + unsigned code = 0; + char name[48] = {}; + if (std::sscanf(line, " keycode %u = %47s", &code, name) == 2 && code < KEY_CNT) { + if (const uint32_t ch = keysym_char(name)) { + t[code] = ch; + loaded = true; + } + } + } + std::fclose(f); + } + if (!loaded) { + static constexpr struct { + uint16_t code; + char ch; + } kDefault[] = { + {26, '!'}, {27, '@'}, {39, '#'}, {40, '$'}, {41, '%'}, {43, '^'}, {51, '&'}, + {52, '*'}, {53, '('}, {94, ')'}, {55, '~'}, {69, '`'}, {70, '_'}, {71, '-'}, + {72, '+'}, {73, '='}, {74, '['}, {75, ']'}, {76, '{'}, {77, '}'}, {79, ';'}, + {80, ':'}, {81, '\''}, {82, '"'}, {83, '<'}, {85, '>'}, {86, '\\'}, {89, '|'}, + {90, ','}, {91, '.'}, {92, '/'}, {93, '?'}, + }; + for (const auto& entry : kDefault) { + t[entry.code] = static_cast(entry.ch); + } + } + return t; + }(); + return table; +} + +uint32_t map_evdev_key(uint16_t code, const EvdevKeypad& keypad) { + if (keypad.cardputer && code < KEY_CNT) { + if (const uint32_t ch = cardputer_symbols()[code]) { + return ch; + } + } if (const uint32_t ch = map_evdev_char(code)) { + if (keypad.shift && ch >= 'a' && ch <= 'z') { + return ch - 'a' + 'A'; + } + if (!keypad.cardputer && keypad.shift) { + if (const uint32_t sym = map_us_symbol(code, true)) { + return sym; + } + } return ch; } + if (!keypad.cardputer) { + if (const uint32_t sym = map_us_symbol(code, keypad.shift)) { + return sym; + } + } switch (code) { case KEY_ESC: return LV_KEY_ESC; @@ -309,12 +422,24 @@ void evdev_read_cb(lv_indev_t* indev, lv_indev_data_t* data) { input_event input{}; while (read(keypad->fd, &input, sizeof(input)) == sizeof(input)) { - if (input.type != EV_KEY) { + if (input.type != EV_KEY || input.value == 2 || input.code >= KEY_CNT) { + continue; + } + if (input.code == KEY_LEFTSHIFT || input.code == KEY_RIGHTSHIFT) { + keypad->shift = input.value != 0; continue; } - const auto key = map_evdev_key(input.code); - if (!key || input.value == 2) { + uint32_t key = 0; + if (input.value) { + key = map_evdev_key(input.code, *keypad); + keypad->pressed_as[input.code] = key; + } + else { + key = keypad->pressed_as[input.code]; + keypad->pressed_as[input.code] = 0; + } + if (!key) { continue; } @@ -347,6 +472,10 @@ void evdev_delete_cb(lv_event_t* event) { lv_indev_t* create_keypad_from_fd(int fd) { auto* keypad = new EvdevKeypad; keypad->fd = fd; + char name[64] = {}; + if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0) { + keypad->cardputer = std::strncmp(name, "tca8418", 7) == 0; + } auto* indev = lv_indev_create(); if (!indev) { diff --git a/src/platform/power_control.cpp b/src/platform/power_control.cpp index c9b9612..8deb4d1 100644 --- a/src/platform/power_control.cpp +++ b/src/platform/power_control.cpp @@ -6,6 +6,7 @@ #include "power_settings.h" #include "process.h" +#include "sudo_password.h" #include #include @@ -48,6 +49,11 @@ PowerControl::PowerControl() { } } fake_system_["gpu_mem_active"] = "64"; + const char* fake = std::getenv("ZEROPOWER_SIMULATE_SUDO"); + if (fake && *fake) { + fake_sudo_password_ = std::string(fake) + "\n"; + fake_sudo_ok_ = false; + } } } @@ -75,7 +81,15 @@ std::map PowerControl::read_all() { return values; } -PowerControl::Result PowerControl::apply(const std::string& key, const std::string& value) { +PowerControl::Result PowerControl::apply(const std::string& key, const std::string& value, + std::string password_line) { + struct Wiper { + std::string& s; + ~Wiper() { + power::wipe(s); + } + } wiper{password_line}; + Result result; const power::SettingInfo* info = power::find_setting(key); if (!info || power::option_index(*info, value) < 0) { @@ -112,15 +126,33 @@ PowerControl::Result PowerControl::apply(const std::string& key, const std::stri if (simulated_) { std::this_thread::sleep_for(std::chrono::milliseconds(400)); // como si tardara + if (!fake_sudo_ok_) { + if (password_line.empty()) { + result.needs_password = true; + return result; + } + if (password_line != fake_sudo_password_) { + result.wrong_password = true; + result.message = "Wrong password"; + return result; + } + fake_sudo_ok_ = true; + } fake_system_[key] = value; result.ok = true; result.value = value; return result; } - const auto r = run_process({"sudo", "-n", kHelper, "set", key, value}); + // LC_ALL=C: los mensajes de sudo, en inglés, para poder entenderlos. + // -p "": sin el texto "[sudo] password for…" mezclado con la respuesta del ayudante. + const auto r = password_line.empty() + ? run_process({"env", "LC_ALL=C", "sudo", "-n", kHelper, "set", key, value}) + : run_process({"env", "LC_ALL=C", "sudo", "-S", "-p", "", kHelper, "set", key, value}, + password_line); const std::string line = last_line(r.output); - if (r.exit_code == 0) { + switch (power::classify_sudo(r.exit_code, r.output)) { + case power::SudoOutcome::Ok: { const auto kv = power::parse_key_values(line); const auto it = kv.find(key); result.value = it != kv.end() ? it->second : value; @@ -128,10 +160,22 @@ PowerControl::Result PowerControl::apply(const std::string& key, const std::stri if (!result.ok) { result.message = "Now: " + power::option_label(*info, result.value); } - } else if (line.find("password") != std::string::npos || line.find("sudo") != std::string::npos) { - result.message = "Needs passwordless sudo"; - } else { + break; + } + case power::SudoOutcome::NeedsPassword: + result.needs_password = true; + result.message = "Password required"; + break; + case power::SudoOutcome::WrongPassword: + result.wrong_password = true; + result.message = "Wrong password"; + break; + case power::SudoOutcome::NotAllowed: + result.message = "This user can't use sudo"; + break; + case power::SudoOutcome::Failed: result.message = line.empty() ? "Failed" : line; + break; } return result; } diff --git a/src/platform/power_control.h b/src/platform/power_control.h index 578eca5..fdacef5 100644 --- a/src/platform/power_control.h +++ b/src/platform/power_control.h @@ -31,16 +31,25 @@ class PowerControl { struct Result { bool ok = false; - std::string value; // el valor que queda puesto - std::string message; // por qué falló + std::string value; // el valor que queda puesto + std::string message; // por qué falló + bool needs_password = false; // sudo pide la contraseña: hay que preguntarla y repetir + bool wrong_password = false; // la que se le dio no vale }; - Result apply(const std::string& key, const std::string& value); + // Sin `password_line`, prueba `sudo -n` (sin contraseña, o con la que sudo recuerda de + // hace poco). Con ella (la contraseña y un salto de línea) se la pasa a `sudo -S` por la + // entrada estándar, y la borra al acabar. Nunca se guarda ni va en la línea de órdenes. + Result apply(const std::string& key, const std::string& value, std::string password_line = ""); private: std::map read_daemon_values() const; bool simulated_ = false; std::map fake_system_; + // Para probar la pantalla de la contraseña en el simulador: ZEROPOWER_SIMULATE_SUDO= + // hace que el sistema simulado la pida (una vez, como sudo, que luego la recuerda). + std::string fake_sudo_password_; + bool fake_sudo_ok_ = true; }; } // namespace platform diff --git a/src/platform/process.cpp b/src/platform/process.cpp index 05f78d3..a5ad78b 100644 --- a/src/platform/process.cpp +++ b/src/platform/process.cpp @@ -4,6 +4,7 @@ #include "process.h" +#include #include #include @@ -13,7 +14,7 @@ namespace platform { -ProcessResult run_process(const std::vector& argv) { +ProcessResult run_process(const std::vector& argv, const std::string& input) { ProcessResult result; if (argv.empty()) { return result; @@ -22,6 +23,16 @@ ProcessResult run_process(const std::vector& argv) { if (::pipe2(pipefd, O_CLOEXEC) != 0) { return result; } + int infd[2] = {-1, -1}; + if (!input.empty()) { + // Si el hijo sale sin leer la entrada, escribir daría SIGPIPE y mataría la app. + ::signal(SIGPIPE, SIG_IGN); + if (::pipe2(infd, O_CLOEXEC) != 0) { + ::close(pipefd[0]); + ::close(pipefd[1]); + return result; + } + } // Todo lo que reserva memoria, antes del fork (la app tiene hilos). std::vector args; args.reserve(argv.size() + 1); @@ -34,19 +45,41 @@ ProcessResult run_process(const std::vector& argv) { if (pid < 0) { ::close(pipefd[0]); ::close(pipefd[1]); + if (infd[0] >= 0) { + ::close(infd[0]); + ::close(infd[1]); + } return result; } if (pid == 0) { + ::signal(SIGPIPE, SIG_DFL); // un SIG_IGN se heredaría a través de exec ::dup2(pipefd[1], STDOUT_FILENO); ::dup2(pipefd[1], STDERR_FILENO); - const int devnull = ::open("/dev/null", O_RDONLY); - if (devnull >= 0) { - ::dup2(devnull, STDIN_FILENO); + if (infd[0] >= 0) { + ::dup2(infd[0], STDIN_FILENO); + } else { + const int devnull = ::open("/dev/null", O_RDONLY); + if (devnull >= 0) { + ::dup2(devnull, STDIN_FILENO); + } } ::execvp(args[0], args.data()); ::_exit(127); } ::close(pipefd[1]); + if (infd[0] >= 0) { + // Cabe de sobra en el búfer de la tubería: se escribe entero antes de leer la salida. + ::close(infd[0]); + std::size_t done = 0; + while (done < input.size()) { + const ssize_t w = ::write(infd[1], input.data() + done, input.size() - done); + if (w <= 0) { + break; + } + done += static_cast(w); + } + ::close(infd[1]); + } char buf[512]; ssize_t n; while ((n = ::read(pipefd[0], buf, sizeof(buf))) > 0) { diff --git a/src/platform/process.h b/src/platform/process.h index 398a1fa..3145ef1 100644 --- a/src/platform/process.h +++ b/src/platform/process.h @@ -16,7 +16,9 @@ struct ProcessResult { // Lanza `argv[0]` (buscándolo en el PATH) con esos argumentos, sin shell: nada de lo que va // en los argumentos se interpreta. Espera a que acabe y devuelve su salida. -ProcessResult run_process(const std::vector& argv); +// `input` va a su entrada estándar (vacío: /dev/null). Así llega la contraseña a `sudo -S` +// sin aparecer en la línea de órdenes, que cualquiera ve en /proc. +ProcessResult run_process(const std::vector& argv, const std::string& input = ""); // Lee un fichero de texto entero ("" si no se puede). std::string read_text_file(const std::string& path); diff --git a/src/view/screens/settings_screen.cpp b/src/view/screens/settings_screen.cpp index 30fdfa6..a152f80 100644 --- a/src/view/screens/settings_screen.cpp +++ b/src/view/screens/settings_screen.cpp @@ -8,8 +8,12 @@ #include "theme.h" #include +#include #include +#include +#include + namespace screen { namespace { @@ -37,6 +41,18 @@ void set_text(lv_obj_t* label, const std::string& text) { } } +// La contraseña que pide sudo es la del usuario con el que corre la app. +std::string user_name() { + if (const passwd* pw = ::getpwuid(::geteuid())) { + return pw->pw_name; + } + const char* user = std::getenv("USER"); + return user ? user : "this user"; +} + +// Los puntos que caben en la casilla de la contraseña. +constexpr std::size_t kMaxDots = 34; + } // namespace SettingsScreen::SettingsScreen(viewmodel::BaseViewModel& view_model, app::AssetManager& assets, @@ -45,6 +61,18 @@ SettingsScreen::SettingsScreen(viewmodel::BaseViewModel& view_model, app::AssetM init(); this->view_model().set_page_handlers(this, [this](uint32_t key) { return handle_key(key); }, [this]() { + // ESC en la contraseña: no se cambia nada (mientras + // sudo la comprueba no se puede deshacer: espera). + if (prompt_open_) { + if (!prompt_checking_) { + close_password_prompt(); + std::lock_guard lock(mutex_); + message_ = "Not changed"; + message_error_ = false; + } + refresh(); + return true; + } // ESC con un valor elegido sin aplicar: se descarta // y se queda; otro ESC vuelve al menú. if (!pending_.empty() || !confirm_key_.empty()) { @@ -124,6 +152,49 @@ void SettingsScreen::build_content(lv_obj_t* content) { lv_obj_set_width(status_, kW - 2 * kMargin - 6); lv_obj_align(status_, LV_ALIGN_BOTTOM_LEFT, kMargin + 3, -2); + // La contraseña: tapa la lista entera mientras se pide. + prompt_ = lv_obj_create(content); + lv_obj_remove_style_all(prompt_); + lv_obj_set_size(prompt_, LV_PCT(100), LV_PCT(100)); + lv_obj_set_style_bg_opa(prompt_, LV_OPA_COVER, 0); + lv_obj_remove_flag(prompt_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + + prompt_title_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_title_, title_font ? title_font : &lv_font_montserrat_12, 0); + lv_obj_set_pos(prompt_title_, kMargin + 3, kTop + 2); + lv_label_set_text(prompt_title_, "Password required"); + + prompt_text_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_text_, small ? small : &lv_font_montserrat_12, 0); + lv_label_set_long_mode(prompt_text_, LV_LABEL_LONG_WRAP); + lv_obj_set_width(prompt_text_, kW - 2 * kMargin - 6); + lv_obj_set_pos(prompt_text_, kMargin + 3, kTop + 22); + + prompt_field_ = lv_obj_create(prompt_); + lv_obj_remove_style_all(prompt_field_); + lv_obj_set_size(prompt_field_, kW - 2 * kMargin, 22); + lv_obj_set_pos(prompt_field_, kMargin, kTop + 56); + lv_obj_set_style_radius(prompt_field_, 3, 0); + lv_obj_set_style_border_width(prompt_field_, 1, 0); + lv_obj_set_style_bg_opa(prompt_field_, LV_OPA_COVER, 0); + lv_obj_remove_flag(prompt_field_, LV_OBJ_FLAG_SCROLLABLE); + + prompt_dots_ = lv_label_create(prompt_field_); + lv_obj_set_style_text_font(prompt_dots_, value_font ? value_font : &lv_font_montserrat_12, 0); + lv_label_set_long_mode(prompt_dots_, LV_LABEL_LONG_CLIP); + lv_obj_set_width(prompt_dots_, kW - 2 * kMargin - 12); + lv_obj_align(prompt_dots_, LV_ALIGN_LEFT_MID, 6, 0); + + prompt_error_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_error_, small ? small : &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(prompt_error_, kErrorColor, 0); + lv_obj_set_pos(prompt_error_, kMargin + 3, kTop + 82); + + prompt_footer_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_footer_, small ? small : &lv_font_montserrat_12, 0); + lv_obj_align(prompt_footer_, LV_ALIGN_BOTTOM_LEFT, kMargin + 3, -2); + lv_subject_add_observer_obj(view_model().dark_mode_subject(), theme_observer_cb, content, this); timer_ = lv_timer_create(timer_cb, 150, this); refresh(); @@ -144,6 +215,9 @@ void SettingsScreen::start_job(std::function job) { } bool SettingsScreen::handle_key(uint32_t key) { + if (prompt_open_) { + return handle_password_key(key); + } if (settings_.empty()) { return false; } @@ -226,16 +300,36 @@ void SettingsScreen::apply_value(const power::SettingInfo& info, const std::stri } confirm_key_.clear(); pending_.erase(info.key); - applying_key_ = info.key; + run_apply(info.key, target, ""); +} + +void SettingsScreen::run_apply(const std::string& key, const std::string& target, std::string password_line) { + const power::SettingInfo* info = power::find_setting(key); + if (!info || busy_) { + power::wipe(password_line); + return; + } + applying_key_ = key; applying_value_ = target; - const std::string key_name = info.key; { std::lock_guard lock(mutex_); - message_ = "Applying " + std::string(info.title) + "…"; + message_ = "Applying " + std::string(info->title) + "…"; message_error_ = false; } - start_job([this, key_name, target]() { - const auto result = control_.apply(key_name, target); + // La contraseña se mueve al hilo y PowerControl::apply la borra al acabar. + start_job([this, key_name = key, target, line = std::move(password_line)]() mutable { + const auto result = control_.apply(key_name, target, std::move(line)); + power::wipe(line); + if (result.needs_password || result.wrong_password) { + std::lock_guard lock(mutex_); + password_wanted_ = true; + password_wrong_ = result.wrong_password; + password_key_ = key_name; + password_value_ = target; + message_.clear(); + message_error_ = false; + return; + } auto values = control_.read_all(); std::lock_guard lock(mutex_); values_ = std::move(values); @@ -253,6 +347,74 @@ void SettingsScreen::apply_value(const power::SettingInfo& info, const std::stri }); } +bool SettingsScreen::handle_password_key(uint32_t key) { + if (prompt_checking_) { + return true; // sudo la está comprobando: se espera + } + switch (key) { + case LV_KEY_ENTER: + case '\r': + // El espacio no: puede ir en la contraseña. + if (!password_.empty() && !busy_) { + prompt_checking_ = true; + run_apply(prompt_key_, prompt_value_, password_.take_line()); + } + break; + case LV_KEY_BACKSPACE: + password_.backspace(); + prompt_wrong_ = false; + break; + default: + if (password_.add(key)) { + prompt_wrong_ = false; + } + break; + } + refresh(); + return true; // con la contraseña abierta ninguna tecla hace otra cosa +} + +void SettingsScreen::open_password_prompt(bool wrong) { + password_.clear(); + prompt_open_ = true; + prompt_checking_ = false; + prompt_wrong_ = wrong; + view_model().set_text_entry(true); +} + +void SettingsScreen::close_password_prompt() { + password_.clear(); + prompt_open_ = false; + prompt_checking_ = false; + prompt_wrong_ = false; + prompt_key_.clear(); + prompt_value_.clear(); + view_model().set_text_entry(false); +} + +void SettingsScreen::refresh_password_prompt(const view::ThemePalette& colors) { + if (!prompt_open_) { + lv_obj_add_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + return; + } + lv_obj_remove_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + lv_obj_set_style_bg_color(prompt_, colors.background, 0); + lv_obj_set_style_text_color(prompt_title_, colors.text, 0); + lv_obj_set_style_text_color(prompt_text_, colors.text_disabled, 0); + lv_obj_set_style_text_color(prompt_footer_, prompt_checking_ ? colors.text_disabled : colors.text, 0); + lv_obj_set_style_text_color(prompt_dots_, colors.text, 0); + lv_obj_set_style_bg_color(prompt_field_, colors.surface, 0); + lv_obj_set_style_border_color(prompt_field_, prompt_wrong_ ? kErrorColor : colors.primary, 0); + + const power::SettingInfo* info = power::find_setting(prompt_key_); + const std::string what = info ? std::string(info->title) + " → " + power::option_label(*info, prompt_value_) + : std::string("this setting"); + set_text(prompt_text_, "Changing " + what + " needs root. Enter the sudo password for " + user_name() + "."); + set_text(prompt_dots_, password_.masked(kMaxDots) + (prompt_checking_ ? "" : "_")); + set_text(prompt_error_, prompt_wrong_ ? "Wrong password, try again" : ""); + set_text(prompt_footer_, prompt_checking_ ? "Checking password…" : "ENTER confirm ESC cancel"); +} + void SettingsScreen::refresh() { if (!status_) { return; @@ -262,13 +424,34 @@ void SettingsScreen::refresh() { bool loaded; std::string message; bool message_error; + bool password_wanted; + bool password_wrong; + std::string password_key; + std::string password_value; + // Antes que lo demás: el hilo deja su resultado y luego baja `busy_`, así que si aquí ya + // no trabaja, lo que se lea a continuación es lo último. + const bool busy = busy_; { std::lock_guard lock(mutex_); values = values_; loaded = loaded_; message = message_; message_error = message_error_; + password_wanted = password_wanted_; + password_wrong = password_wrong_; + password_key = password_key_; + password_value = password_value_; + password_wanted_ = false; + } + + if (password_wanted) { + open_password_prompt(password_wrong); + prompt_key_ = password_key; + prompt_value_ = password_value; + } else if (prompt_open_ && prompt_checking_ && !busy) { + close_password_prompt(); // la aceptó: el resultado sale abajo, como siempre } + refresh_password_prompt(colors); for (int i = 0; i < kMaxRows; ++i) { if (i >= static_cast(settings_.size())) { diff --git a/src/view/screens/settings_screen.h b/src/view/screens/settings_screen.h index 4ef19fb..8c36ba9 100644 --- a/src/view/screens/settings_screen.h +++ b/src/view/screens/settings_screen.h @@ -7,6 +7,8 @@ #include "base_screen.h" #include "power_control.h" #include "power_settings.h" +#include "sudo_password.h" +#include "theme.h" #include #include @@ -24,6 +26,9 @@ namespace screen { * interruptor (como en iOS) que ENTER, Z o C cambian y aplican al momento; los de varias * opciones se eligen con Z/C (queda pendiente, marcado) y ENTER los aplica. Leer el estado y aplicar se hace en otro hilo: el * ayudante tarda unas décimas y la pantalla no se queda congelada. + * + * Si sudo pide contraseña, se pide encima de la lista y el cambio se repite con ella. Sudo + * la recuerda unos minutos: los cambios siguientes ya no la piden. */ class SettingsScreen : public BaseScreen { public: @@ -37,9 +42,14 @@ class SettingsScreen : public BaseScreen { static constexpr int kMaxRows = 6; bool handle_key(uint32_t key); + bool handle_password_key(uint32_t key); void start_job(std::function job); void apply_value(const power::SettingInfo& info, const std::string& target); + void run_apply(const std::string& key, const std::string& target, std::string password_line); + void open_password_prompt(bool wrong); + void close_password_prompt(); void refresh(); + void refresh_password_prompt(const view::ThemePalette& colors); static void timer_cb(lv_timer_t* timer); static void theme_observer_cb(lv_observer_t* observer, lv_subject_t* subject); @@ -60,9 +70,28 @@ class SettingsScreen : public BaseScreen { bool loaded_ = false; std::string message_; bool message_error_ = false; + bool password_wanted_ = false; // el último cambio necesita contraseña + bool password_wrong_ = false; // ... porque la que se dio no valía + std::string password_key_; // el cambio que hay que repetir con ella + std::string password_value_; std::atomic busy_{false}; std::thread worker_; + // La pantalla de la contraseña (sólo en el hilo de LVGL). + power::SecretInput password_; + bool prompt_open_ = false; + bool prompt_checking_ = false; // sudo la está comprobando + bool prompt_wrong_ = false; + std::string prompt_key_; + std::string prompt_value_; + lv_obj_t* prompt_ = nullptr; + lv_obj_t* prompt_title_ = nullptr; + lv_obj_t* prompt_text_ = nullptr; + lv_obj_t* prompt_field_ = nullptr; + lv_obj_t* prompt_dots_ = nullptr; + lv_obj_t* prompt_error_ = nullptr; + lv_obj_t* prompt_footer_ = nullptr; + std::array row_boxes_{}; std::array row_titles_{}; std::array row_values_{}; diff --git a/src/viewmodel/base_viewmodel.cpp b/src/viewmodel/base_viewmodel.cpp index 4553dcb..b3f50a6 100644 --- a/src/viewmodel/base_viewmodel.cpp +++ b/src/viewmodel/base_viewmodel.cpp @@ -123,11 +123,12 @@ void BaseViewModel::clear_page_handlers(const void* owner) { page_handlers_owner_ = nullptr; page_key_handler_ = nullptr; page_back_handler_ = nullptr; + text_entry_ = false; } bool BaseViewModel::handle_key(uint32_t key) { - // El tema se cambia desde cualquier pantalla. - if (key == 't' || key == 'T') { + // El tema se cambia desde cualquier pantalla (menos mientras se escribe). + if ((key == 't' || key == 'T') && !text_entry_) { toggle_dark_mode(); return true; } diff --git a/src/viewmodel/base_viewmodel.h b/src/viewmodel/base_viewmodel.h index eb1f821..9f1dd3c 100644 --- a/src/viewmodel/base_viewmodel.h +++ b/src/viewmodel/base_viewmodel.h @@ -67,6 +67,12 @@ class BaseViewModel { void set_page_handlers(const void* owner, KeyHandler key_handler, BackHandler back_handler); void clear_page_handlers(const void* owner); + // Mientras una pantalla pide texto (la contraseña) todas las letras son suyas: la T no + // cambia el tema. + void set_text_entry(bool active) { + text_entry_ = active; + } + private: void move_selection(int delta); // Página que corresponde a la entrada `index` del menú Home. @@ -81,6 +87,7 @@ class BaseViewModel { const void* page_handlers_owner_ = nullptr; KeyHandler page_key_handler_; BackHandler page_back_handler_; + bool text_entry_ = false; }; } // namespace viewmodel diff --git a/tests/power_model_test.cpp b/tests/power_model_test.cpp index a40bd80..0919fe3 100644 --- a/tests/power_model_test.cpp +++ b/tests/power_model_test.cpp @@ -4,6 +4,7 @@ #include "power_logic.h" #include "power_settings.h" +#include "sudo_password.h" #include #include @@ -164,6 +165,40 @@ void test_screen_timeout() { CHECK(v.update(1000, -1, false, 60) == A::None); } +void test_sudo_password() { + using power::SudoOutcome; + CHECK(power::classify_sudo(0, "ethernet=off\n") == SudoOutcome::Ok); + CHECK(power::classify_sudo(1, "sudo: a password is required\n") == SudoOutcome::NeedsPassword); + CHECK(power::classify_sudo(1, "Sorry, try again.\nsudo: no password was provided\n" + "sudo: 1 incorrect password attempt\n") == SudoOutcome::WrongPassword); + CHECK(power::classify_sudo(1, "sudo: no password was provided\n") == SudoOutcome::NeedsPassword); + CHECK(power::classify_sudo(1, "pi is not in the sudoers file.\n") == SudoOutcome::NotAllowed); + CHECK(power::classify_sudo(1, "Sorry, user pi is not allowed to execute '/usr/lib/zeropower/zeropower-helper " + "set ethernet off' as root on cpz.\n") == SudoOutcome::NotAllowed); + CHECK(power::classify_sudo(2, "invalid value\n") == SudoOutcome::Failed); + + power::SecretInput in; + CHECK(in.empty() && in.masked().empty()); + CHECK(in.add('p') && in.add('W') && in.add('!') && in.add(' ')); + CHECK(!in.add('\n') && !in.add(0x7F) && !in.add(0xE9)); // control y no ASCII: fuera + CHECK(in.size() == 4); + CHECK(in.masked() == "\u2022\u2022\u2022\u2022"); + CHECK(in.masked(2) == "\u2026\u2022\u2022"); + CHECK(in.backspace() && in.size() == 3); + std::string line = in.take_line(); + CHECK(line == "pW!\n"); + CHECK(in.empty() && !in.backspace()); + power::wipe(line); + CHECK(line.empty()); + + for (std::size_t i = 0; i < power::SecretInput::kMaxLength; ++i) { + CHECK(in.add('a')); + } + CHECK(!in.add('a')); + in.clear(); + CHECK(in.empty()); +} + } // namespace int main() { @@ -173,6 +208,7 @@ int main() { test_low_battery_guard(); test_idle_tracker(); test_screen_timeout(); + test_sudo_password(); if (failures == 0) { std::printf("power_model_test: todo bien\n"); }