diff --git a/README.ko.md b/README.ko.md index c7fdc51..6edd0f9 100644 --- a/README.ko.md +++ b/README.ko.md @@ -152,6 +152,7 @@ export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865" - [Debian rootfs 설치 과정](docs/rootfs-installation.ko.md) - [Debian systemd와 SSH](docs/debian-systemd.ko.md) - [하드웨어 코덱 worker 프로토콜](docs/hardware-codec-protocol.ko.md) +- [네이티브 출력 스키마](docs/native-output-schema.ko.md) - [하드웨어 코덱 구현 결정 기록](docs/media-codec-bridge-plan.ko.md) - [빌드와 배포](docs/building.ko.md) - [내장 부트스트랩 런타임](bfu-runtime/README.ko.md) diff --git a/README.md b/README.md index b496bb8..8dbde47 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ key is not a production signing identity. - [Debian rootfs installation](docs/rootfs-installation.md) - [Debian systemd and SSH](docs/debian-systemd.md) - [Hardware codec worker protocol](docs/hardware-codec-protocol.md) +- [Native output schema](docs/native-output-schema.md) - [Hardware codec implementation decision record](docs/media-codec-bridge-plan.md) - [Build and release](docs/building.md) - [Embedded bootstrap runtime](bfu-runtime/README.md) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 648b3ef..a8568c7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -140,6 +140,7 @@ dependencies { implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.navigation3.ui) implementation(libs.kotlinx.serialization.core) + implementation(libs.kotlinx.serialization.json) debugImplementation(libs.androidx.compose.ui.tooling) testImplementation("junit:junit:4.13.2") diff --git a/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe b/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe index 9a8e96f..d7d56d8 100755 Binary files a/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe and b/app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe differ diff --git a/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe b/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe index 85394e0..6933d0e 100755 Binary files a/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe and b/app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe differ diff --git a/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe b/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe index b0be41e..04496ca 100755 Binary files a/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe and b/app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe differ diff --git a/app/src/main/cpp/bfu_namespace_probe.c b/app/src/main/cpp/bfu_namespace_probe.c index 880c62f..b0153f0 100644 --- a/app/src/main/cpp/bfu_namespace_probe.c +++ b/app/src/main/cpp/bfu_namespace_probe.c @@ -1,5 +1,7 @@ #define _GNU_SOURCE +#include "dawnshell_json.h" + #include #include #include @@ -371,31 +373,59 @@ static void log_matching_snapshot(const char *label, const char *path, (long long) realtime_seconds(), label, emitted); } -static void report_failure_text(const char *message) { +static void report_failure_text(const char *message, size_t length) { if (failure_report_fd >= 0 && message != NULL) { - (void) write(failure_report_fd, message, strlen(message)); + (void) write(failure_report_fd, message, length); } } +static int fail_with(const char *stage, int saved_errno, const char *error, int code) { + char buffer[512]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "failed"); + ds_json_str(&json, "stage", stage); + if (saved_errno != 0) ds_json_int(&json, "errno", saved_errno); + ds_json_str(&json, "error", error); + ds_json_emit(&json, STDERR_FILENO); + report_failure_text(buffer, json.len); + return code; +} + static int fail_errno(const char *stage, int code) { const int saved_errno = errno; - char message[512]; - snprintf(message, sizeof(message), - "BFU_DEBIAN_LAUNCHER_FAILED stage=%s errno=%d error=%s\n", - stage, saved_errno, strerror(saved_errno)); - fputs(message, stderr); - report_failure_text(message); - return code; + return fail_with(stage, saved_errno, strerror(saved_errno), code); } static int fail_message(const char *stage, const char *message_text, int code) { - char message[512]; - snprintf(message, sizeof(message), - "BFU_DEBIAN_LAUNCHER_FAILED stage=%s error=%s\n", - stage, message_text); - fputs(message, stderr); - report_failure_text(message); - return code; + return fail_with(stage, 0, message_text, code); +} + +static void emit_mode_event(const char *event, const char *mode) { + char buffer[160]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), event); + ds_json_str(&json, "mode", mode); + ds_json_emit(&json, STDOUT_FILENO); +} + +/* key == NULL emits the bare event. */ +static void emit_pid_event(const char *event, const char *key, int pid) { + char buffer[160]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), event); + if (key != NULL) ds_json_int(&json, key, pid); + ds_json_emit(&json, STDOUT_FILENO); +} + +/* Reports a failed start to the parent through the readiness pipe. */ +static void emit_start_failed(int fd, const char *stage, int saved_errno, const char *key, int value) { + char buffer[256]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "start_failed"); + ds_json_str(&json, "stage", stage); + if (saved_errno != 0) ds_json_int(&json, "errno", saved_errno); + if (key != NULL) ds_json_int(&json, key, value); + ds_json_emit(&json, fd); } static int run_argv(char *const argv[], bool quiet) { @@ -2910,7 +2940,8 @@ static int set_systemd_parent_namespaces(const char *control_dir, static int enter_debian_probe(const char *root) { static const char probe_command[] = "set -u; " - "fail() { printf 'BFU_DEBIAN_NAMESPACE_FAILED stage=%s\\n' \"$1\"; exit 60; }; " + "ts=$(/usr/bin/date +%s); " + "fail() { printf '{\"v\":1,\"ts\":%s,\"event\":\"namespace_failed\",\"stage\":\"%s\"}\\n' \"$ts\" \"$1\"; exit 60; }; " "[ \"$$\" -eq 1 ] || fail debian_shell_not_pid1; " "IFS= read -r proc1 < /proc/1/comm || fail proc1_read; " "[ \"$proc1\" = sh ] || fail proc1_not_debian_shell; " @@ -2921,9 +2952,9 @@ static int enter_debian_probe(const char *root) { "[ \"$version\" = 13 ] || fail debian_version_not_13; " "if [ -x /sbin/init ]; then init=present; else init=absent; fi; " "if [ -x /usr/bin/systemctl ]; then systemctl=present; else systemctl=absent; fi; " - "cgroup=$(while IFS= read -r line; do printf '%s,' \"$line\"; done < /proc/self/cgroup); " - "printf 'BFU_DEBIAN_NAMESPACE_OK pid=%s proc1=%s arch=%s debian=%s init=%s systemctl=%s cgroup=%s\\n' " - "\"$$\" \"$proc1\" \"$arch\" \"$version\" \"$init\" \"$systemctl\" \"$cgroup\""; + "cgroup=$(while IFS= read -r line; do printf '%s,' \"$line\"; done < /proc/self/cgroup | /usr/bin/tr -cd 'A-Za-z0-9_./:@+=,-'); " + "printf '{\"v\":1,\"ts\":%s,\"event\":\"namespace_ok\",\"pid\":%s,\"proc1\":\"%s\",\"arch\":\"%s\",\"debian\":%s,\"init\":\"%s\",\"systemctl\":\"%s\",\"cgroup\":\"%s\"}\\n' " + "\"$ts\" \"$$\" \"$proc1\" \"$arch\" \"$version\" \"$init\" \"$systemctl\" \"$cgroup\""; int result = prepare_child_mounts(root, NULL, false, CGROUP_MODE_UNKNOWN, HOST_USB_OFF); @@ -2950,14 +2981,14 @@ static int enter_debian_probe(const char *root) { static int enter_debian_compat_probe(const char *root) { static const char probe_command[] = "set -u; " - "fail() { printf 'BFU_DEBIAN_COMPATIBILITY_FAILED stage=%s\\n' \"$1\"; exit 60; }; " + "ts=$(/usr/bin/date +%s); " + "fail() { printf '{\"v\":1,\"ts\":%s,\"event\":\"compat_failed\",\"stage\":\"%s\"}\\n' \"$ts\" \"$1\"; exit 60; }; " "arch=$(/usr/bin/dpkg --print-architecture) || fail dpkg_arch; " "[ -r /etc/debian_version ] || fail debian_version_read; " "version=$(/usr/bin/cut -d. -f1 /etc/debian_version) || fail debian_version_read; " "[ \"$version\" = 13 ] || fail debian_version_not_13; " - "printf 'BFU_DEBIAN_COMPATIBILITY_OK mode=compat arch=%s debian=%s ' " - "\"$arch\" \"$version\"; " - "printf 'pid_namespace=shared mount_namespace=private uts_namespace=private\\n'"; + "printf '{\"v\":1,\"ts\":%s,\"event\":\"compat_ok\",\"mode\":\"compat\",\"arch\":\"%s\",\"debian\":%s,\"pid_namespace\":\"shared\",\"mount_namespace\":\"private\",\"uts_namespace\":\"private\"}\\n' " + "\"$ts\" \"$arch\" \"$version\""; int result = prepare_child_mounts(root, NULL, false, CGROUP_MODE_UNKNOWN, HOST_USB_OFF); @@ -3232,9 +3263,7 @@ static void report_start_grace_failure(int ready_fd, const char *stage, dprintf(STDERR_FILENO, "[%lld] BFU_DEBIAN_START_FAILED stage=%s child_exit=%d\n", (long long) realtime_seconds(), stage, child_exit); - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=%s child_exit=%d\n", - stage, child_exit); + emit_start_failed(ready_fd, stage, 0, "child_exit", child_exit); return; } if (wait_status >= 0 && WIFSIGNALED(wait_status)) { @@ -3242,17 +3271,13 @@ static void report_start_grace_failure(int ready_fd, const char *stage, dprintf(STDERR_FILENO, "[%lld] BFU_DEBIAN_START_FAILED stage=%s child_signal=%d\n", (long long) realtime_seconds(), stage, child_signal); - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=%s child_signal=%d\n", - stage, child_signal); + emit_start_failed(ready_fd, stage, 0, "child_signal", child_signal); return; } dprintf(STDERR_FILENO, "[%lld] BFU_DEBIAN_START_FAILED stage=%s child_status=unknown errno=%d\n", (long long) realtime_seconds(), stage, probe_errno); - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=%s child_status=unknown errno=%d\n", - stage, probe_errno); + emit_start_failed(ready_fd, stage, probe_errno, NULL, 0); } /* systemd's halt signal eventually reaches the kernel reboot path. On some @@ -3322,8 +3347,7 @@ static int supervisor_compat_loop(const char *root, const char *control_dir, int saved_errno = errno; if (network_manager_pid > 0) (void) kill(network_manager_pid, SIGTERM); errno = saved_errno; - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=compat_exec_pipe errno=%d\n", - errno); + emit_start_failed(ready_fd, "compat_exec_pipe", errno, NULL, 0); return 78; } (void) fcntl(exec_pipe[0], F_SETFD, FD_CLOEXEC); @@ -3335,8 +3359,7 @@ static int supervisor_compat_loop(const char *root, const char *control_dir, close(exec_pipe[0]); close(exec_pipe[1]); errno = saved_errno; - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=compat_fork_sshd errno=%d\n", - errno); + emit_start_failed(ready_fd, "compat_fork_sshd", errno, NULL, 0); return 79; } if (service_pid == 0) { @@ -3377,7 +3400,7 @@ static int supervisor_compat_loop(const char *root, const char *control_dir, (void) kill(network_manager_pid, SIGTERM); while (waitpid(network_manager_pid, NULL, 0) < 0 && errno == EINTR) {} } - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=compat_exec_sshd\n"); + emit_start_failed(ready_fd, "compat_exec_sshd", 0, NULL, 0); return 80; } int early_wait_status = -1; @@ -3418,10 +3441,7 @@ static int supervisor_compat_loop(const char *root, const char *control_dir, (void) kill(network_manager_pid, SIGTERM); while (waitpid(network_manager_pid, NULL, 0) < 0 && errno == EINTR) {} } - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED " - "stage=compat_sshd_identity_or_namespace errno=%d\n", - saved_errno); + emit_start_failed(ready_fd, "compat_sshd_identity_or_namespace", saved_errno, NULL, 0); return 82; } @@ -3440,10 +3460,18 @@ static int supervisor_compat_loop(const char *root, const char *control_dir, "net:android-shared cgroup_mode=none host_usb_mode=%s\n", (long long) realtime_seconds(), getpid(), service_pid, host_usb_policy_name(host_usb_policy)); - dprintf(ready_fd, - "BFU_DEBIAN_FALLBACK_STARTED supervisor_pid=%d sshd_pid=%d " - "mode=compat systemd_pid1=false cgroup_mode=none host_usb_mode=%s\n", - getpid(), service_pid, host_usb_policy_name(host_usb_policy)); + { + char buffer[384]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "fallback_started"); + ds_json_int(&json, "supervisor_pid", getpid()); + ds_json_int(&json, "sshd_pid", service_pid); + ds_json_str(&json, "mode", "compat"); + ds_json_bool(&json, "systemd_pid1", false); + ds_json_str(&json, "cgroup_mode", "none"); + ds_json_str(&json, "host_usb_mode", host_usb_policy_name(host_usb_policy)); + ds_json_emit(&json, ready_fd); + } close(ready_fd); bool shutdown_sent = false; @@ -3507,13 +3535,12 @@ static int supervisor_loop(const char *root, const char *control_dir, HostUsbPolicy host_usb_policy, const UsbDeviceFilter *usb_device_filter) { if (setsid() < 0) { - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=setsid errno=%d\n", errno); + emit_start_failed(ready_fd, "setsid", errno, NULL, 0); return 73; } signal(SIGHUP, SIG_IGN); if (redirect_supervisor_stdio(log_path) != 0) { - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=open_lifecycle_log errno=%d\n", - errno); + emit_start_failed(ready_fd, "open_lifecycle_log", errno, NULL, 0); return 74; } dprintf(STDERR_FILENO, @@ -3533,7 +3560,7 @@ static int supervisor_loop(const char *root, const char *control_dir, sigemptyset(&action.sa_mask); if (sigaction(SIGTERM, &action, NULL) != 0 || sigaction(SIGINT, &action, NULL) != 0) { - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=signal_setup errno=%d\n", errno); + emit_start_failed(ready_fd, "signal_setup", errno, NULL, 0); return 75; } @@ -3549,13 +3576,11 @@ static int supervisor_loop(const char *root, const char *control_dir, || read_proc_exe_identity(state.supervisor_pid, &state.supervisor_exe_dev, &state.supervisor_exe_ino) != 0) { - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=supervisor_identity errno=%d\n", errno); + emit_start_failed(ready_fd, "supervisor_identity", errno, NULL, 0); return 76; } if (write_state(control_dir, &state) != 0) { - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=write_starting_state errno=%d\n", - errno); + emit_start_failed(ready_fd, "write_starting_state", errno, NULL, 0); return 77; } @@ -3564,18 +3589,14 @@ static int supervisor_loop(const char *root, const char *control_dir, char host_reboot_fifo[PATH_MAX]; if (prepare_host_reboot_fifo(control_dir, host_reboot_fifo, sizeof(host_reboot_fifo)) != 0) { - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=host_reboot_fifo errno=%d\n", - errno); + emit_start_failed(ready_fd, "host_reboot_fifo", errno, NULL, 0); return 78; } if (start_network_manager(getpid(), lock_fd, ready_fd, host_reboot_fifo, &network_manager_pid, &network_ready_fd) != 0) { unlink(host_reboot_fifo); - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=network_manager_start errno=%d\n", - errno); + emit_start_failed(ready_fd, "network_manager_start", errno, NULL, 0); return 78; } @@ -3587,8 +3608,7 @@ static int supervisor_loop(const char *root, const char *control_dir, &cgroup_mode); if (result != 0) { cleanup_delegated_cgroups(root, control_dir); - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=namespace_setup exit=%d\n", - result); + emit_start_failed(ready_fd, "namespace_setup", 0, "exit", result); return result; } snprintf(state.cgroup_mode, sizeof(state.cgroup_mode), "%s", @@ -3614,7 +3634,7 @@ static int supervisor_loop(const char *root, const char *control_dir, int saved_errno = errno; cleanup_delegated_cgroups(root, control_dir); errno = saved_errno; - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=exec_pipe errno=%d\n", errno); + emit_start_failed(ready_fd, "exec_pipe", errno, NULL, 0); return 78; } (void) fcntl(exec_pipe[0], F_SETFD, FD_CLOEXEC); @@ -3622,7 +3642,7 @@ static int supervisor_loop(const char *root, const char *control_dir, pid_t init_pid = fork(); if (init_pid < 0) { - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=fork_systemd errno=%d\n", errno); + emit_start_failed(ready_fd, "fork_systemd", errno, NULL, 0); close(exec_pipe[0]); close(exec_pipe[1]); cleanup_delegated_cgroups(root, control_dir); @@ -3663,7 +3683,7 @@ static int supervisor_loop(const char *root, const char *control_dir, state.wait_status = 80; (void) write_state(control_dir, &state); cleanup_delegated_cgroups(root, control_dir); - dprintf(ready_fd, "BFU_DEBIAN_START_FAILED stage=exec_systemd\n"); + emit_start_failed(ready_fd, "exec_systemd", 0, NULL, 0); return 80; } @@ -3701,8 +3721,7 @@ static int supervisor_loop(const char *root, const char *control_dir, state.wait_status = 82; (void) write_state(control_dir, &state); cleanup_delegated_cgroups(root, control_dir); - dprintf(ready_fd, - "BFU_DEBIAN_START_FAILED stage=init_identity_or_pid_namespace\n"); + emit_start_failed(ready_fd, "init_identity_or_pid_namespace", 0, NULL, 0); return 82; } @@ -3731,12 +3750,18 @@ static int supervisor_loop(const char *root, const char *control_dir, (unsigned long long) state.init_net_ns_ino, cgroup_mode_name(cgroup_mode), host_usb_policy_name(host_usb_policy), usb_device_filter->count); - dprintf(ready_fd, - "BFU_DEBIAN_STARTED supervisor_pid=%d init_host_pid=%d " - "namespace_pid=1 cgroup_mode=%s host_usb_mode=%s " - "host_usb_filter_count=%zu\n", - getpid(), init_pid, cgroup_mode_name(cgroup_mode), - host_usb_policy_name(host_usb_policy), usb_device_filter->count); + { + char buffer[384]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "started"); + ds_json_int(&json, "supervisor_pid", getpid()); + ds_json_int(&json, "init_host_pid", init_pid); + ds_json_int(&json, "namespace_pid", 1); + ds_json_str(&json, "cgroup_mode", cgroup_mode_name(cgroup_mode)); + ds_json_str(&json, "host_usb_mode", host_usb_policy_name(host_usb_policy)); + ds_json_int(&json, "host_usb_filter_count", (long long) usb_device_filter->count); + ds_json_emit(&json, ready_fd); + } close(ready_fd); bool shutdown_sent = false; @@ -3849,20 +3874,26 @@ static int run_status(const char *root, const char *control_dir) { flock(lock_fd, LOCK_UN); close(lock_fd); if (orphaned_init) { - printf("BFU_DEBIAN_ORPHANED_INIT mode=%s init_host_pid=%d " - "identity_valid=true updated_epoch=%lld\n", - stale.launch_mode, stale.init_host_pid, - (long long) stale.updated_epoch); + char buffer[320]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "orphaned_init"); + ds_json_str(&json, "mode", stale.launch_mode); + ds_json_int(&json, "init_host_pid", stale.init_host_pid); + ds_json_bool(&json, "identity_valid", true); + ds_json_int(&json, "updated_epoch", stale.updated_epoch); + ds_json_emit(&json, STDOUT_FILENO); return 1; } - printf("BFU_DEBIAN_STOPPED last_state=%s mode=%s cgroup_mode=%s host_usb_mode=%s " - "wait_status=%d updated_epoch=%lld\n", - has_state ? stale.state : "none", - has_state ? stale.launch_mode : "systemd", - has_state ? stale.cgroup_mode : "unknown", - has_state ? stale.host_usb_mode : "unknown", - has_state ? stale.wait_status : -1, - (long long) (has_state ? stale.updated_epoch : 0)); + char buffer[320]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "stopped"); + ds_json_str(&json, "last_state", has_state ? stale.state : "none"); + ds_json_str(&json, "mode", has_state ? stale.launch_mode : "systemd"); + ds_json_str(&json, "cgroup_mode", has_state ? stale.cgroup_mode : "unknown"); + ds_json_str(&json, "host_usb_mode", has_state ? stale.host_usb_mode : "unknown"); + ds_json_int(&json, "wait_status", has_state ? stale.wait_status : -1); + ds_json_int(&json, "updated_epoch", has_state ? stale.updated_epoch : 0); + ds_json_emit(&json, STDOUT_FILENO); return 0; } if (errno != EWOULDBLOCK && errno != EAGAIN) { @@ -3881,32 +3912,41 @@ static int run_status(const char *root, const char *control_dir) { ? validate_compat_namespace_topology(&state) == 0 : validate_init_namespace_topology(&state) == 0); close(lock_fd); - printf("BFU_DEBIAN_%s state=%s mode=%s supervisor_pid=%d init_host_pid=%d " - "supervisor_identity_valid=%s init_identity_valid=%s " - "namespace_topology_valid=%s ipc_namespace=android-shared " - "network_namespace=android-shared network_mode=shared-nic cgroup_mode=%s " - "host_usb_mode=%s " - "pid_ns=%llu mnt_ns=%llu uts_ns=%llu ipc_ns=%llu cgroup_ns=%llu " - "net_ns=%llu updated_epoch=%lld\n", - supervisor_valid && (topology_valid || strcmp(state.state, "starting") == 0) - ? "RUNNING" : "STARTING_OR_UNKNOWN", - state.state, state.launch_mode, state.supervisor_pid, state.init_host_pid, - supervisor_valid ? "true" : "false", init_valid ? "true" : "false", - topology_valid ? "true" : "false", state.cgroup_mode, - state.host_usb_mode, - (unsigned long long) state.init_pid_ns_ino, - (unsigned long long) state.init_mnt_ns_ino, - (unsigned long long) state.init_uts_ns_ino, - (unsigned long long) state.init_ipc_ns_ino, - (unsigned long long) state.init_cgroup_ns_ino, - (unsigned long long) state.init_net_ns_ino, - (long long) state.updated_epoch); + char buffer[768]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), + supervisor_valid && (topology_valid || strcmp(state.state, "starting") == 0) + ? "running" : "starting_or_unknown"); + ds_json_str(&json, "state", state.state); + ds_json_str(&json, "mode", state.launch_mode); + ds_json_int(&json, "supervisor_pid", state.supervisor_pid); + ds_json_int(&json, "init_host_pid", state.init_host_pid); + ds_json_bool(&json, "supervisor_identity_valid", supervisor_valid); + ds_json_bool(&json, "init_identity_valid", init_valid); + ds_json_bool(&json, "namespace_topology_valid", topology_valid); + ds_json_str(&json, "ipc_namespace", "android-shared"); + ds_json_str(&json, "network_namespace", "android-shared"); + ds_json_str(&json, "network_mode", "shared-nic"); + ds_json_str(&json, "cgroup_mode", state.cgroup_mode); + ds_json_str(&json, "host_usb_mode", state.host_usb_mode); + ds_json_obj_begin(&json, "ns"); + ds_json_int(&json, "pid", (long long) state.init_pid_ns_ino); + ds_json_int(&json, "mnt", (long long) state.init_mnt_ns_ino); + ds_json_int(&json, "uts", (long long) state.init_uts_ns_ino); + ds_json_int(&json, "ipc", (long long) state.init_ipc_ns_ino); + ds_json_int(&json, "cgroup", (long long) state.init_cgroup_ns_ino); + ds_json_int(&json, "net", (long long) state.init_net_ns_ino); + ds_json_obj_end(&json); + ds_json_int(&json, "updated_epoch", state.updated_epoch); + ds_json_emit(&json, STDOUT_FILENO); return 0; } static int enter_debian_health(const char *root) { static const char health_command[] = "set -u; " + "ts=$(/usr/bin/date +%s); " + "clean() { printf %s \"$1\" | /usr/bin/tr -cd 'A-Za-z0-9_./:@+=,; -'; }; " "pid1=$(/usr/bin/cat /proc/1/comm 2>/dev/null || true); " "pid1_start_ticks=$(/usr/bin/mawk '{print $22}' /proc/1/stat " "2>/dev/null || true); " @@ -3953,33 +3993,11 @@ static int enter_debian_health(const char *root) { "cgroup_mode=v1-nodev; cgroup_delegation=delegated; " "devices_cgroup=unavailable; else cgroup_mode=unknown; " "cgroup_delegation=missing; devices_cgroup=missing; fi; " - "printf 'BFU_DEBIAN_HEALTH pid1=%s pid1_start_ticks=%s " - "system_state=%s dbus_service=%s dbus_bus=%s ssh_service=%s " - "boot_proof_service=%s boot_proof_marker=%s " - "default_target=%s target_state=%s listen_22=%s " - "cgroup_mode=%s cgroup_delegation=%s devices_cgroup=%s " - "devices_hierarchy=%s devices_path=%s systemd_path=%s " - "unified_path=%s\\n' " - "\"$pid1\" \"$pid1_start_ticks\" " - "\"$system_state\" \"$dbus_service\" \"$dbus_bus\" " - "\"$ssh_service\" \"$boot_proof_service\" \"$boot_proof_marker\" " - "\"$default_target\" \"$target_state\" \"$listen_22\" " - "\"$cgroup_mode\" \"$cgroup_delegation\" \"$devices_cgroup\" " - "\"${devices_hierarchy:-0}\" \"${devices_path:-missing}\" " - "\"${systemd_path:-missing}\" \"${unified_path:-missing}\"; " - "if [ \"$pid1\" = systemd ] && [ \"$system_state\" = running ] " - "&& [ \"$dbus_service\" = active ] " - "&& [ \"$dbus_bus\" = ok ] && [ \"$ssh_service\" = active ] " - "&& [ \"$boot_proof_service\" = active ] " - "&& [ \"$boot_proof_marker\" = present ] " - "&& [ \"$default_target\" = multi-user.target ] " - "&& [ \"$target_state\" = active ] " - "&& [ \"$listen_22\" = true ] " - "&& [ \"$cgroup_delegation\" = delegated ]; then exit 0; fi; " - "printf '%s\\n' BFU_DEBIAN_DIAGNOSTICS_BEGIN; " - "/usr/bin/timeout -k 1 3 /usr/bin/systemctl --no-pager --failed " - "2>&1 || true; " - "printf '%s\\n' BFU_DEBIAN_DIAGNOSTICS_END; exit 1"; + "if [ \"$pid1\" = systemd ] && [ \"$system_state\" = running ] && [ \"$dbus_service\" = active ] && [ \"$dbus_bus\" = ok ] && [ \"$ssh_service\" = active ] && [ \"$boot_proof_service\" = active ] && [ \"$boot_proof_marker\" = present ] && [ \"$default_target\" = multi-user.target ] && [ \"$target_state\" = active ] && [ \"$listen_22\" = true ] && [ \"$cgroup_delegation\" = delegated ]; then healthy=true; else healthy=false; fi; " + "printf '{\"v\":1,\"ts\":%s,\"event\":\"health\",\"mode\":\"systemd\",\"pid1\":\"%s\",\"system_state\":\"%s\",\"dbus_service\":\"%s\",\"dbus_bus\":\"%s\",\"ssh_service\":\"%s\",\"boot_proof_service\":\"%s\",\"boot_proof_marker\":\"%s\",\"default_target\":\"%s\",\"target_state\":\"%s\",\"cgroup_mode\":\"%s\",\"cgroup_delegation\":\"%s\",\"devices_cgroup\":\"%s\",\"devices_path\":\"%s\",\"systemd_path\":\"%s\",\"unified_path\":\"%s\",\"pid1_start_ticks\":%s,\"devices_hierarchy\":%s,\"listen_22\":%s,\"healthy\":%s}\\n' \"$ts\" \"$(clean \"$pid1\")\" \"$(clean \"$system_state\")\" \"$(clean \"$dbus_service\")\" \"$(clean \"$dbus_bus\")\" \"$(clean \"$ssh_service\")\" \"$(clean \"$boot_proof_service\")\" \"$(clean \"$boot_proof_marker\")\" \"$(clean \"$default_target\")\" \"$(clean \"$target_state\")\" \"$(clean \"$cgroup_mode\")\" \"$(clean \"$cgroup_delegation\")\" \"$(clean \"$devices_cgroup\")\" \"$(clean \"$devices_path\")\" \"$(clean \"$systemd_path\")\" \"$(clean \"$unified_path\")\" \"${pid1_start_ticks:-0}\" \"${devices_hierarchy:-0}\" \"$listen_22\" \"$healthy\"; " + "[ \"$healthy\" = true ] && exit 0; " + "diagnostic=$(/usr/bin/timeout -k 1 3 /usr/bin/systemctl --no-pager --failed 2>&1 | /usr/bin/head -c 1024 | /usr/bin/tr '\\n' ';'); " + "printf '{\"v\":1,\"ts\":%s,\"event\":\"diagnostic\",\"label\":\"systemctl_failed\",\"content\":\"%s\"}\\n' \"$ts\" \"$(clean \"$diagnostic\")\"; exit 1"; if (chdir(root) != 0) return fail_errno("health_chdir_rootfs", 103); if (chroot(".") != 0) return fail_errno("health_chroot", 104); @@ -4002,14 +4020,7 @@ static int enter_debian_compat_health(const char *root) { "else print \"false\" }'); " "if [ \"$listen_22\" = true ] && [ -x /usr/sbin/sshd ]; then " "compat_ready=true; else compat_ready=false; fi; " - "printf 'BFU_DEBIAN_HEALTH mode=compat pid1=android-host " - "system_state=unavailable dbus_service=unavailable " - "dbus_bus=unavailable ssh_service=direct " - "boot_proof_service=unavailable boot_proof_marker=unavailable " - "default_target=unavailable target_state=unavailable " - "listen_22=%s compat_ready=%s cgroup_mode=none " - "cgroup_delegation=shared devices_cgroup=shared\\n' " - "\"$listen_22\" \"$compat_ready\"; " + "printf '{\"v\":1,\"ts\":%s,\"event\":\"health\",\"mode\":\"compat\",\"pid1\":\"android-host\",\"system_state\":\"unavailable\",\"dbus_service\":\"unavailable\",\"dbus_bus\":\"unavailable\",\"ssh_service\":\"direct\",\"boot_proof_service\":\"unavailable\",\"boot_proof_marker\":\"unavailable\",\"default_target\":\"unavailable\",\"target_state\":\"unavailable\",\"cgroup_mode\":\"none\",\"cgroup_delegation\":\"shared\",\"devices_cgroup\":\"shared\",\"listen_22\":%s,\"compat_ready\":%s,\"healthy\":%s}\\n' \"$(/usr/bin/date +%s)\" \"$listen_22\" \"$compat_ready\" \"$compat_ready\"; " "[ \"$compat_ready\" = true ]"; if (chdir(root) != 0) return fail_errno("compat_health_chdir_rootfs", 103); @@ -4435,14 +4446,21 @@ static int run_shutdown_test(const char *root, const char *control_dir, return fail_message("shutdown_test_mode", "only_poweroff_reboot_or_shutdown_allowed", 108); } - printf("BFU_DEBIAN_SHUTDOWN_TEST_REQUESTED mode=%s\n", mode); + emit_mode_event("shutdown_test_requested", mode); int command_result = run_in_debian_namespaces(root, control_dir, enter_debian_systemctl_shutdown, mode, 15); int stop_result = wait_for_supervisor_exit(control_dir); if (stop_result != 0) return command_result != 0 ? command_result : stop_result; - printf("BFU_DEBIAN_SHUTDOWN_TEST_COMPLETED mode=%s command_result=%d " - "android_reboot_not_assessed\n", mode, command_result); + { + char buffer[256]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "shutdown_test_completed"); + ds_json_str(&json, "mode", mode); + ds_json_int(&json, "command_result", command_result); + ds_json_bool(&json, "android_reboot_assessed", false); + ds_json_emit(&json, STDOUT_FILENO); + } return 0; } @@ -4558,11 +4576,15 @@ static int run_start(const char *root, const char *control_dir, bool valid = read_state(control_dir, &state) == 0 && validate_supervisor_identity(&state); close(lock_fd); - printf("BFU_DEBIAN_ALREADY_RUNNING supervisor_pid=%d init_host_pid=%d " - "identity_valid=%s cgroup_mode=%s host_usb_mode=%s\n", - state.supervisor_pid, state.init_host_pid, - valid ? "true" : "false", state.cgroup_mode, - state.host_usb_mode); + char buffer[320]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "already_running"); + ds_json_int(&json, "supervisor_pid", state.supervisor_pid); + ds_json_int(&json, "init_host_pid", state.init_host_pid); + ds_json_bool(&json, "identity_valid", valid); + ds_json_str(&json, "cgroup_mode", state.cgroup_mode); + ds_json_str(&json, "host_usb_mode", state.host_usb_mode); + ds_json_emit(&json, STDOUT_FILENO); return valid ? 0 : fail_message("locked_state_invalid", "active_lock_has_no_valid_supervisor_identity", 87); } @@ -4589,7 +4611,7 @@ static int run_start(const char *root, const char *control_dir, if (leftover_count > 0) { flock(lock_fd, LOCK_UN); close(lock_fd); - printf("BFU_DEBIAN_ORPHANED_INSTANCE first_pid=%d\n", leftovers[0]); + emit_pid_event("orphaned_instance", "first_pid", leftovers[0]); return fail_message("orphaned_instance", "previous_processes_remain_in_the_delegated_cgroup_run_force_stop", 89); @@ -4628,10 +4650,8 @@ static int run_start(const char *root, const char *control_dir, close(ready_pipe[0]); if (result != 0) return fail_errno("start_readiness_timeout", 91); fputs(message, stdout); - return strncmp(message, "BFU_DEBIAN_STARTED ", - strlen("BFU_DEBIAN_STARTED ")) == 0 - || strncmp(message, "BFU_DEBIAN_FALLBACK_STARTED ", - strlen("BFU_DEBIAN_FALLBACK_STARTED ")) == 0 + return strstr(message, "\"event\":\"started\"") != NULL + || strstr(message, "\"event\":\"fallback_started\"") != NULL ? 0 : 92; } @@ -4665,9 +4685,12 @@ static int run_stop(const char *root, const char *control_dir) { ? validate_compat_service_identity(&orphan) : validate_init_identity(&orphan); if (!alive) { - printf("BFU_DEBIAN_ORPHANED_INIT_STOPPED mode=%s init_host_pid=%d\n", - compatibility ? "compat" : "systemd", - orphan.init_host_pid); + char buffer[192]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "orphaned_init_stopped"); + ds_json_str(&json, "mode", compatibility ? "compat" : "systemd"); + ds_json_int(&json, "init_host_pid", orphan.init_host_pid); + ds_json_emit(&json, STDOUT_FILENO); return 0; } usleep(200000); @@ -4682,7 +4705,7 @@ static int run_stop(const char *root, const char *control_dir) { return fail_message("orphaned_init_stop_timeout", "forced_SIGKILL_after_grace_period", 95); } - printf("BFU_DEBIAN_ALREADY_STOPPED\n"); + emit_pid_event("already_stopped", NULL, 0); return 0; } if (errno != EWOULDBLOCK && errno != EAGAIN) { @@ -4707,7 +4730,7 @@ static int run_stop(const char *root, const char *control_dir) { if (flock(lock_fd, LOCK_EX | LOCK_NB) == 0) { flock(lock_fd, LOCK_UN); close(lock_fd); - printf("BFU_DEBIAN_STOPPED supervisor_pid=%d\n", state.supervisor_pid); + emit_pid_event("stopped", "supervisor_pid", state.supervisor_pid); return 0; } if (errno != EWOULDBLOCK && errno != EAGAIN) { @@ -4761,8 +4784,15 @@ static int run_force_stop(const char *root, const char *control_dir) { cleanup_delegated_cgroups(root, control_dir); initialize_state(&state, "force-stopped"); (void) write_state(control_dir, &state); - printf("BFU_DEBIAN_FORCE_STOPPED supervisor_pid=0 init_host_pid=%d " - "orphan=%s\n", orphan_init_pid, init_valid ? "killed" : "none"); + { + char buffer[256]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "force_stopped"); + ds_json_int(&json, "supervisor_pid", 0); + ds_json_int(&json, "init_host_pid", orphan_init_pid); + ds_json_str(&json, "orphan", init_valid ? "killed" : "none"); + ds_json_emit(&json, STDOUT_FILENO); + } return 0; } if (errno != EWOULDBLOCK && errno != EAGAIN) { @@ -4816,9 +4846,14 @@ static int run_force_stop(const char *root, const char *control_dir) { state.init_host_pid = init_pid; state.wait_status = SIGKILL; (void) write_state(control_dir, &state); - printf("BFU_DEBIAN_FORCE_STOPPED supervisor_pid=%d init_host_pid=%d " - "signal=SIGKILL lock_released=true\n", - supervisor_pid, init_pid); + char buffer[256]; + DsJson json; + ds_json_begin(&json, buffer, sizeof(buffer), "force_stopped"); + ds_json_int(&json, "supervisor_pid", supervisor_pid); + ds_json_int(&json, "init_host_pid", init_pid); + ds_json_str(&json, "signal", "SIGKILL"); + ds_json_bool(&json, "lock_released", true); + ds_json_emit(&json, STDOUT_FILENO); return 0; } if (errno != EWOULDBLOCK && errno != EAGAIN) { diff --git a/app/src/main/cpp/dawnshell_json.h b/app/src/main/cpp/dawnshell_json.h new file mode 100644 index 0000000..06e758e --- /dev/null +++ b/app/src/main/cpp/dawnshell_json.h @@ -0,0 +1,183 @@ +#ifndef DAWNSHELL_JSON_H +#define DAWNSHELL_JSON_H + +/* + * Single-line JSON event writer for DawnShell's native helpers (JSON Lines, + * schema docs/native-output-schema.md). Write-only: no parser, no allocation. + * Every line starts with {"v":1,"ts":,"event":""} and is always + * valid JSON. A field that does not fit is dropped and "truncated":true is set. + */ + +#include +#include +#include +#include +#include + +#define DS_JSON_SCHEMA_VERSION 1 +#define DS_JSON_RESERVE 40 + +/* Kept out of line: inlining the writer at every call site costs ~16 KiB per ABI. */ +#define DS_JSON_OUTLINE static __attribute__((noinline, unused)) + +#ifndef DS_JSON_NOW +#define DS_JSON_NOW() ((long long) time(NULL)) +#endif + +typedef struct { + char *buf; + size_t cap; + size_t len; + int depth; + bool first; + bool overflow; +} DsJson; + +DS_JSON_OUTLINE void ds_json_put(DsJson *j, const char *text, size_t length) { + if (j->overflow || j->len + length + DS_JSON_RESERVE > j->cap) { + j->overflow = true; + return; + } + memcpy(j->buf + j->len, text, length); + j->len += length; +} + +static inline void ds_json_putc(DsJson *j, char c) { + ds_json_put(j, &c, 1); +} + +static inline size_t ds_json_utf8_length(const unsigned char *s, size_t remaining) { + size_t need = s[0] >= 0xf0 ? 4 : s[0] >= 0xe0 ? 3 : s[0] >= 0xc2 ? 2 : 0; + if (need == 0 || need > remaining || s[0] > 0xf4) return 0; + unsigned code = s[0] & (0xffu >> (need + 1)); + for (size_t i = 1; i < need; i++) { + if ((s[i] & 0xc0) != 0x80) return 0; + code = (code << 6) | (s[i] & 0x3fu); + } + static const unsigned minimum[5] = {0, 0, 0x80, 0x800, 0x10000}; + if (code < minimum[need] || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return 0; + return need; +} + +DS_JSON_OUTLINE void ds_json_quoted(DsJson *j, const char *value) { + static const char hex[] = "0123456789abcdef"; + ds_json_putc(j, '"'); + const unsigned char *s = (const unsigned char *) (value != NULL ? value : ""); + for (size_t i = 0; s[i] != '\0' && !j->overflow;) { + unsigned char c = s[i]; + if (c == '"' || c == '\\') { + const char pair[2] = {'\\', (char) c}; + ds_json_put(j, pair, 2); + } else if (c == '\n' || c == '\r' || c == '\t') { + const char pair[2] = {'\\', c == '\n' ? 'n' : c == '\r' ? 'r' : 't'}; + ds_json_put(j, pair, 2); + } else if (c < 0x20) { + const char escape[6] = {'\\', 'u', '0', '0', hex[c >> 4], hex[c & 15]}; + ds_json_put(j, escape, 6); + } else if (c < 0x80) { + ds_json_putc(j, (char) c); + } else { + size_t available = 1; + while (available < 4 && s[i + available] != '\0') available++; + size_t length = ds_json_utf8_length(s + i, available); + if (length == 0) { + ds_json_putc(j, '?'); + } else { + ds_json_put(j, (const char *) s + i, length); + i += length; + continue; + } + } + i++; + } + ds_json_putc(j, '"'); +} + +/* Starts a field; ds_json_commit drops it again when it overflowed. */ +static inline size_t ds_json_key(DsJson *j, const char *key) { + size_t start = j->len; + if (!j->first) ds_json_putc(j, ','); + j->first = false; + ds_json_quoted(j, key); + ds_json_putc(j, ':'); + return start; +} + +static inline void ds_json_commit(DsJson *j, size_t start) { + if (j->overflow) j->len = start; +} + +DS_JSON_OUTLINE void ds_json_int(DsJson *j, const char *key, long long value) { + size_t start = ds_json_key(j, key); + char text[24]; + size_t pos = sizeof(text); + unsigned long long magnitude = value < 0 ? 0ull - (unsigned long long) value : (unsigned long long) value; + do { + text[--pos] = (char) ('0' + magnitude % 10); + magnitude /= 10; + } while (magnitude != 0); + if (value < 0) text[--pos] = '-'; + ds_json_put(j, text + pos, sizeof(text) - pos); + ds_json_commit(j, start); +} + +DS_JSON_OUTLINE void ds_json_bool(DsJson *j, const char *key, bool value) { + size_t start = ds_json_key(j, key); + ds_json_put(j, value ? "true" : "false", value ? 4 : 5); + ds_json_commit(j, start); +} + +DS_JSON_OUTLINE void ds_json_str(DsJson *j, const char *key, const char *value) { + size_t start = ds_json_key(j, key); + ds_json_quoted(j, value); + ds_json_commit(j, start); +} + +DS_JSON_OUTLINE void ds_json_obj_begin(DsJson *j, const char *key) { + size_t start = ds_json_key(j, key); + ds_json_putc(j, '{'); + ds_json_commit(j, start); + if (!j->overflow) j->depth = 1; + j->first = true; +} + +DS_JSON_OUTLINE void ds_json_obj_end(DsJson *j) { + if (j->depth > 0) ds_json_putc(j, '}'); + if (!j->overflow) j->depth = 0; + j->first = false; +} + +DS_JSON_OUTLINE void ds_json_begin(DsJson *j, char *buf, size_t cap, const char *event) { + *j = (DsJson) {.buf = buf, .cap = cap, .first = true}; + ds_json_putc(j, '{'); + ds_json_int(j, "v", DS_JSON_SCHEMA_VERSION); + ds_json_int(j, "ts", DS_JSON_NOW()); + ds_json_str(j, "event", event); +} + +/* Closes the object, appends the newline and returns the line length. */ +static inline size_t ds_json_finish(DsJson *j) { + if (j->depth > 0) { + j->buf[j->len++] = '}'; + j->depth = 0; + } + if (j->overflow) { + memcpy(j->buf + j->len, ",\"truncated\":true", 17); + j->len += 17; + } + j->buf[j->len++] = '}'; + j->buf[j->len++] = '\n'; + return j->len; +} + +/* One write(2) per line keeps lines intact on pipes up to PIPE_BUF. */ +DS_JSON_OUTLINE void ds_json_emit(DsJson *j, int fd) { + size_t total = ds_json_finish(j); + for (size_t done = 0; done < total;) { + ssize_t count = write(fd, j->buf + done, total - done); + if (count <= 0) return; + done += (size_t) count; + } +} + +#endif diff --git a/app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java b/app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java index 2c77700..44c54ab 100644 --- a/app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java +++ b/app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java @@ -16,9 +16,6 @@ final class BfuDebianRuntimeProbe { private static final long PROBE_TIMEOUT_MS = 35_000L; - private static final String SUCCESS_MARKER = "BFU_DEBIAN_NAMESPACE_OK"; - private static final String COMPAT_SUCCESS_MARKER = - "BFU_DEBIAN_COMPATIBILITY_OK"; private static final String LOG_FILE = "bfu-debian-runtime.log"; static final class Result { @@ -72,15 +69,14 @@ static Result run(Context context, BfuRuntime.Layout layout) ? "probe-compat" : "probe"; String shellCommand = BfuSu.shellQuote(layout.namespaceProbeBinary.getAbsolutePath()) + " " + operation + " " + BfuSu.shellQuote(BfuRootfsProbe.ROOTFS_PATH); - BfuSu.Result commandResult = BfuSu.run(shellCommand, PROBE_TIMEOUT_MS); + BfuSu.Result commandResult = BfuSu.runRaw(shellCommand, PROBE_TIMEOUT_MS); boolean userUnlockedAfter = isUserUnlocked(context); - String marker = fallbackAllowed ? COMPAT_SUCCESS_MARKER : SUCCESS_MARKER; boolean successful = commandResult.exitedSuccessfully() - && commandResult.output.contains(marker); + && NativeOutput.has(commandResult.output, fallbackAllowed ? "compat_ok" : "namespace_ok"); Result result = new Result(successful, commandResult.command, commandResult.exitCode, commandResult.timedOut, userUnlockedBefore, userUnlockedAfter, fallbackAllowed ? "compat" : "systemd", - commandResult.output); + BfuSu.sanitize(commandResult.output)); appendPersistentResult(deContext, result); return result; } diff --git a/app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java b/app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java index 320f3ca..29adafd 100644 --- a/app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java +++ b/app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java @@ -6,9 +6,7 @@ import android.os.UserManager; import android.util.Log; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; @@ -47,7 +45,7 @@ String summary() { return "health_attempts=" + attempts + " health_exit=" + result.exitCode + " health_timeout=" + result.timedOut - + " health_output=" + result.output; + + " health_output=" + BfuSu.sanitize(result.output); } } @@ -58,9 +56,8 @@ static boolean isRunning(BfuRuntime.Layout layout) String command = BfuSu.shellQuote(layout.namespaceProbeBinary.getAbsolutePath()) + " status " + BfuSu.shellQuote(BfuRootfsProbe.ROOTFS_PATH) + " " + BfuSu.shellQuote(layout.run.getAbsolutePath()); - BfuSu.Result result = BfuSu.run(command, 12_000L); - return result.exitedSuccessfully() - && result.output.contains("BFU_DEBIAN_RUNNING"); + BfuSu.Result result = BfuSu.runRaw(command, 12_000L); + return result.exitedSuccessfully() && NativeOutput.has(result.output, "running"); } static boolean run(Context context, BfuRuntime.Layout layout, Operation operation, @@ -85,11 +82,11 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio timeoutMs = 12_000L; } - BfuSu.Result result = BfuSu.run(command, timeoutMs); + BfuSu.Result result = BfuSu.runRaw(command, timeoutMs); String summary = "command=" + result.command + " exit=" + result.exitCode + " timeout=" + result.timedOut - + " output=" + result.output; + + " output=" + BfuSu.sanitize(result.output); appendLog(layout.lifecycleLog, "ANDROID_RESULT operation=" + operation.name() + " " + summary); boolean successful = result.exitedSuccessfully(); @@ -99,10 +96,10 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio health = checkHealth(layout, true); successful = health.successful; } else if (successful && operation == Operation.STATUS) { - if (result.output.contains("BFU_DEBIAN_RUNNING")) { + if (NativeOutput.has(result.output, "running")) { health = checkHealth(layout, false); successful = health.successful; - } else if (!result.output.contains("BFU_DEBIAN_STOPPED")) { + } else if (!NativeOutput.has(result.output, "stopped")) { successful = false; appendLog(layout.lifecycleLog, "ANDROID_HEALTH skipped=state_not_running_or_stopped"); @@ -115,7 +112,9 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio + " user_unlocked_before=" + userUnlockedBefore + " user_unlocked_after=" + userUnlockedAfter + " " + summary; - writeStatus(context, (successful ? "SUCCEEDED " : "FAILED ") + summary); + String events = health == null ? result.output : result.output + "\n" + health.result.output; + StatusStore.write(statusFile(context), (successful ? "SUCCEEDED " : "FAILED ") + summary, + NativeOutput.detail(events)); if (successful) { Log.i(TAG, "Debian lifecycle " + summary); } else { @@ -161,21 +160,9 @@ private static HealthOutcome checkHealth(BfuRuntime.Layout layout, BfuSu.Result result; do { attempts++; - result = BfuSu.run(command, HEALTH_COMMAND_TIMEOUT_MS); - boolean compatibility = result.output.contains("mode=compat"); - boolean successful = result.exitedSuccessfully() - && result.output.contains("BFU_DEBIAN_HEALTH") - && result.output.contains("listen_22=true") - && (compatibility - ? result.output.contains("compat_ready=true") - : result.output.contains("system_state=running") - && result.output.contains("dbus_service=active") - && result.output.contains("dbus_bus=ok") - && result.output.contains("ssh_service=active") - && result.output.contains("boot_proof_service=active") - && result.output.contains("boot_proof_marker=present") - && result.output.contains("target_state=active") - && result.output.contains("cgroup_delegation=delegated")); + result = BfuSu.runRaw(command, HEALTH_COMMAND_TIMEOUT_MS); + Health health = NativeOutput.health(result.output); + boolean successful = result.exitedSuccessfully() && health != null && health.getHealthy(); appendLog(layout.lifecycleLog, "ANDROID_HEALTH attempt=" + attempts + " exit=" + result.exitCode @@ -189,21 +176,17 @@ private static HealthOutcome checkHealth(BfuRuntime.Layout layout, return new HealthOutcome(false, attempts, result); } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(statusFile(context)); + } + static String readStatus(Context context) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File file = new File(deContext.getFilesDir(), STATUS_FILE); - if (!file.isFile()) return ""; - try (FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[512]; - int count; - while (output.size() < 4096 - && (count = input.read(buffer, 0, - Math.min(buffer.length, 4096 - output.size()))) >= 0) { - output.write(buffer, 0, count); - } - return new String(output.toByteArray(), StandardCharsets.UTF_8).trim(); - } + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); + } + + private static File statusFile(Context context) { + return new File(BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE); } static String readLogTail(Context context) throws IOException { @@ -254,24 +237,7 @@ private static void appendLog(File file, String value) throws IOException { } private static void writeStatus(Context context, String value) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File destination = new File(deContext.getFilesDir(), STATUS_FILE); - File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new"); - String contents = System.currentTimeMillis() + " " + value + "\n"; - synchronized (FILE_LOCK) { - try (FileOutputStream output = new FileOutputStream(temporary, false)) { - output.write(contents.getBytes(StandardCharsets.UTF_8)); - output.getFD().sync(); - } - setOwnerOnly(temporary); - if (destination.exists() && !destination.delete()) { - throw new IOException("cannot replace lifecycle status"); - } - if (!temporary.renameTo(destination)) { - throw new IOException("cannot publish lifecycle status"); - } - setOwnerOnly(destination); - } + StatusStore.write(statusFile(context), value); } private static String utcTimestamp() { diff --git a/app/src/main/java/me/aroxu/dawnshell/DebianRootfsInstaller.java b/app/src/main/java/me/aroxu/dawnshell/DebianRootfsInstaller.java index ab855d4..7cf7cd0 100644 --- a/app/src/main/java/me/aroxu/dawnshell/DebianRootfsInstaller.java +++ b/app/src/main/java/me/aroxu/dawnshell/DebianRootfsInstaller.java @@ -131,12 +131,14 @@ static void recordMessage(Context context, String message) { } } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(new File( + BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE)); + } + static String readStatus(Context context) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File file = new File(deContext.getFilesDir(), STATUS_FILE); - if (!file.isFile()) return ""; - byte[] bytes = readAtMost(file, 4 * 1024); - return new String(bytes, StandardCharsets.UTF_8).trim(); + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); } static String readLogTail(Context context) throws IOException { @@ -187,43 +189,13 @@ private static void recordFailure(Context deContext, LogSink log, String reason) } private static void writeStatus(Context deContext, String status) throws IOException { - File destination = new File(deContext.getFilesDir(), STATUS_FILE); - File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new"); - String contents = System.currentTimeMillis() + " " + status + "\n"; - synchronized (FILE_LOCK) { - try (FileOutputStream output = new FileOutputStream(temporary, false)) { - output.write(contents.getBytes(StandardCharsets.UTF_8)); - output.getFD().sync(); - } - setOwnerOnly(temporary); - if (destination.exists() && !destination.delete()) { - throw new IOException("cannot replace installer status"); - } - if (!temporary.renameTo(destination)) { - throw new IOException("cannot publish installer status"); - } - setOwnerOnly(destination); - } + StatusStore.write(new File(deContext.getFilesDir(), STATUS_FILE), status); } private static File logFile(Context deContext) { return new File(deContext.getFilesDir(), LOG_FILE); } - private static byte[] readAtMost(File file, int maximum) throws IOException { - try (FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[512]; - int count; - while (output.size() < maximum - && (count = input.read(buffer, 0, - Math.min(buffer.length, maximum - output.size()))) >= 0) { - output.write(buffer, 0, count); - } - return output.toByteArray(); - } - } - private static String sanitizeChildLine(String value) { String clean = value.replace('\0', ' ').replace('\r', ' '); if (clean.length() > MAX_CHILD_LINE_CHARS) { diff --git a/app/src/main/java/me/aroxu/dawnshell/DebianSystemProvisioner.java b/app/src/main/java/me/aroxu/dawnshell/DebianSystemProvisioner.java index 2fc92d3..1acfe04 100644 --- a/app/src/main/java/me/aroxu/dawnshell/DebianSystemProvisioner.java +++ b/app/src/main/java/me/aroxu/dawnshell/DebianSystemProvisioner.java @@ -137,12 +137,14 @@ static void recordMessage(Context context, String message) { } } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(new File( + BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE)); + } + static String readStatus(Context context) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File file = new File(deContext.getFilesDir(), STATUS_FILE); - if (!file.isFile()) return ""; - byte[] bytes = readAtMost(file, 4 * 1024); - return new String(bytes, StandardCharsets.UTF_8).trim(); + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); } static String readLogTail(Context context) throws IOException { @@ -191,43 +193,13 @@ private static void recordFailure(Context deContext, LogSink log, String reason) } private static void writeStatus(Context deContext, String status) throws IOException { - File destination = new File(deContext.getFilesDir(), STATUS_FILE); - File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new"); - String contents = System.currentTimeMillis() + " " + status + "\n"; - synchronized (FILE_LOCK) { - try (FileOutputStream output = new FileOutputStream(temporary, false)) { - output.write(contents.getBytes(StandardCharsets.UTF_8)); - output.getFD().sync(); - } - setOwnerOnly(temporary); - if (destination.exists() && !destination.delete()) { - throw new IOException("cannot replace configuration status"); - } - if (!temporary.renameTo(destination)) { - throw new IOException("cannot publish configuration status"); - } - setOwnerOnly(destination); - } + StatusStore.write(new File(deContext.getFilesDir(), STATUS_FILE), status); } private static File logFile(Context context) { return new File(context.getFilesDir(), LOG_FILE); } - private static byte[] readAtMost(File file, int maximum) throws IOException { - try (FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[512]; - int count; - while (output.size() < maximum - && (count = input.read(buffer, 0, - Math.min(buffer.length, maximum - output.size()))) >= 0) { - output.write(buffer, 0, count); - } - return output.toByteArray(); - } - } - private static String sanitizeChildLine(String value) { String clean = value.replace('\0', ' ').replace('\r', ' '); if (clean.length() > MAX_CHILD_LINE_CHARS) { diff --git a/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java b/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java index b3f8c2a..676d57c 100644 --- a/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java +++ b/app/src/main/java/me/aroxu/dawnshell/DockerNetworkProvisioner.java @@ -142,21 +142,17 @@ static void recordRejected(Context context, String reason) { } } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(statusFile(context)); + } + static String readStatus(Context context) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File file = new File(deContext.getFilesDir(), STATUS_FILE); - if (!file.isFile()) return ""; - try (FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[512]; - int count; - while (output.size() < 4096 - && (count = input.read(buffer, 0, - Math.min(buffer.length, 4096 - output.size()))) >= 0) { - output.write(buffer, 0, count); - } - return new String(output.toByteArray(), StandardCharsets.UTF_8).trim(); - } + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); + } + + private static File statusFile(Context context) { + return new File(BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE); } /** @@ -171,8 +167,8 @@ static boolean needsAutomaticMigration(Context context) { if (revision > 0) { return revision < MANAGED_CONFIGURATION_REVISION; } - String status = readStatus(context); - if (!status.contains(" SUCCEEDED ")) return false; + OperationStatus status = StatusStore.read(statusFile(context)); + if (status == null || status.getState() != OperationState.SUCCEEDED) return false; // Successful policy state from builds predating revision files. // Persist the baseline before attempting the migration so a // failed/interrupted attempt is retried on the next safe start. @@ -234,23 +230,7 @@ private static void recordFailure(Context deContext, LogSink log, String reason) } private static void writeStatus(Context deContext, String status) throws IOException { - File destination = new File(deContext.getFilesDir(), STATUS_FILE); - File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new"); - String contents = System.currentTimeMillis() + " " + status + "\n"; - synchronized (FILE_LOCK) { - try (FileOutputStream output = new FileOutputStream(temporary, false)) { - output.write(contents.getBytes(StandardCharsets.UTF_8)); - output.getFD().sync(); - } - setOwnerOnly(temporary); - if (destination.exists() && !destination.delete()) { - throw new IOException("cannot replace Docker policy status"); - } - if (!temporary.renameTo(destination)) { - throw new IOException("cannot publish Docker policy status"); - } - setOwnerOnly(destination); - } + StatusStore.write(new File(deContext.getFilesDir(), STATUS_FILE), status); } private static int readManagedRevision(Context deContext) throws IOException { diff --git a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecFileSelfTest.java b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecFileSelfTest.java index 15ec8e4..67618e6 100644 --- a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecFileSelfTest.java +++ b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecFileSelfTest.java @@ -109,19 +109,8 @@ static Result run(Context context, long token) { } static String readStatus(Context context) throws IOException { - File file = new File(directory(BfuPreferences.deviceProtectedContext(context)), - STATUS_FILE); - if (!file.isFile()) return ""; - byte[] data = new byte[(int) Math.min(file.length(), 16 * 1024L)]; - try (FileInputStream input = new FileInputStream(file)) { - int offset = 0; - while (offset < data.length) { - int count = input.read(data, offset, data.length - offset); - if (count < 0) break; - offset += count; - } - return new String(data, 0, offset, StandardCharsets.UTF_8).trim(); - } + return StatusStore.readText(new File( + directory(BfuPreferences.deviceProtectedContext(context)), STATUS_FILE)); } static File inputFile(Context context) throws IOException { @@ -267,7 +256,7 @@ private static File directory(Context context) throws IOException { private static void writeStatus(Context context, String value) { try { - writeAtomic(new File(directory(context), STATUS_FILE), value + "\n"); + StatusStore.write(new File(directory(context), STATUS_FILE), value); } catch (IOException e) { HardwareCodecProbe.recordRuntimeEvent(context, "FILE_SELF_TEST_STATUS_WRITE_FAILED error=" + clean(e.getMessage())); diff --git a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecLongRun.java b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecLongRun.java index 1fabb79..0d56953 100644 --- a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecLongRun.java +++ b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecLongRun.java @@ -2,12 +2,8 @@ import android.content.Context; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.Locale; /** Controls the fixed, allow-listed codec soak-test unit inside Debian PID 1. */ @@ -36,21 +32,14 @@ static BfuSu.Result run(Context context, BfuRuntime.Layout layout, return result; } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(new File( + BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE)); + } + static String readStatus(Context context) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File file = new File(deContext.getFilesDir(), STATUS_FILE); - if (!file.isFile()) return ""; - try (FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] buffer = new byte[512]; - int count; - while (output.size() < MAX_STATUS_BYTES - && (count = input.read(buffer, 0, - Math.min(buffer.length, MAX_STATUS_BYTES - output.size()))) >= 0) { - output.write(buffer, 0, count); - } - return new String(output.toByteArray(), StandardCharsets.UTF_8).trim(); - } + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); } static String readLiveReport(Context context) throws IOException { @@ -95,30 +84,8 @@ private static String namespaceCommand(BfuRuntime.Layout layout, String operatio } private static void writeStatus(Context context, String value) throws IOException { - Context deContext = BfuPreferences.deviceProtectedContext(context); - File destination = new File(deContext.getFilesDir(), STATUS_FILE); - File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new"); - String contents = System.currentTimeMillis() + " " + value + "\n"; - try (FileOutputStream output = new FileOutputStream(temporary, false)) { - output.write(contents.getBytes(StandardCharsets.UTF_8)); - output.getFD().sync(); - } - setOwnerOnly(temporary); - if (destination.exists() && !destination.delete()) { - throw new IOException("cannot replace hardware codec long-run status"); - } - if (!temporary.renameTo(destination)) { - throw new IOException("cannot publish hardware codec long-run status"); - } - setOwnerOnly(destination); + StatusStore.write(new File(BfuPreferences.deviceProtectedContext(context).getFilesDir(), + STATUS_FILE), value); } - @SuppressWarnings("ResultOfMethodCallIgnored") - private static void setOwnerOnly(File file) { - file.setReadable(false, false); - file.setWritable(false, false); - file.setExecutable(false, false); - file.setReadable(true, true); - file.setWritable(true, true); - } } diff --git a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecProbe.java b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecProbe.java index cfeddb0..0ebb877 100644 --- a/app/src/main/java/me/aroxu/dawnshell/HardwareCodecProbe.java +++ b/app/src/main/java/me/aroxu/dawnshell/HardwareCodecProbe.java @@ -158,9 +158,13 @@ static Result run(Context context, String trigger) { } } + static OperationStatus readOperationStatus(Context context) throws IOException { + return StatusStore.read(file(BfuPreferences.deviceProtectedContext(context), STATUS_FILE)); + } + static String readStatus(Context context) throws IOException { - return readSmallFile(file(BfuPreferences.deviceProtectedContext(context), - STATUS_FILE), 16 * 1024); + OperationStatus status = readOperationStatus(context); + return status == null ? "" : status.text(); } static String readCapabilities(Context context) throws IOException { @@ -378,7 +382,7 @@ private static File file(Context context, String name) { private static void writeStatus(Context context, String value) { try { - writeAtomic(file(context, STATUS_FILE), clean(value) + "\n"); + StatusStore.write(file(context, STATUS_FILE), clean(value)); } catch (IOException | RuntimeException e) { Log.e(TAG, "Could not persist MediaCodec status", e); } diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.BootScreen.HomePage.kt b/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.BootScreen.HomePage.kt index 2158b87..b55588c 100644 --- a/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.BootScreen.HomePage.kt +++ b/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.BootScreen.HomePage.kt @@ -17,6 +17,7 @@ import androidx.compose.material3.DropdownMenuPopup import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.Text @@ -43,43 +44,75 @@ internal fun HomePage(s: BootUiState, a: BootActions) { SectionTitle(stringResource(R.string.dawnshell_section_runtime)) Small(stringResource(R.string.dawnshell_section_runtime_description), Modifier.padding(top = 4.dp)) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - IconButton(onClick = { - a.openLog(DawnShellLogRepository.LIFECYCLE) - }) { + Box { + var expanded by remember { mutableStateOf(false) } + + IconButton(onClick = { expanded = !expanded }) { Icon( - painterResource(R.drawable.ic_logs_24), - stringResource(R.string.dawnshell_view_runtime_log) + painterResource(R.drawable.ic_more_vert_24), + stringResource(androidx.appcompat.R.string.abc_action_menu_overflow_description), ) } - IconButton(onClick = { - a.requestLifecycle(DebianLauncher.Operation.STATUS) - }) { - Icon( - painterResource(R.drawable.ic_refresh_24), - stringResource(R.string.bfu_status_debian_short) // TODO: Add proper string resource - ) + DropdownMenuPopup(expanded = expanded, onDismissRequest = { expanded = false }) { + DropdownMenuGroup( + shapes = MenuDefaults.groupShapes() + ) { + DropdownMenuItem( + text = { Text(stringResource(R.string.bfu_status_debian_short)) }, + onClick = { + expanded = false + a.requestLifecycle(DebianLauncher.Operation.STATUS) + }, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.dawnshell_view_runtime_log)) }, + onClick = { + expanded = false + a.openLog(DawnShellLogRepository.LIFECYCLE) + }, + ) + HorizontalDivider(Modifier.padding(MenuDefaults.HorizontalDividerPadding)) + DropdownMenuItem( + text = { Text(stringResource(R.string.bfu_force_stop_debian_short)) }, + onClick = { + expanded = false + a.confirmForceStop() + }, + ) + } } } } - // TODO: Rewrite this + val status = s.lifecycleStatus as? StatusLoad.Loaded TerminalPanel(Modifier.fillMaxWidth().padding(top = 14.dp)) { - Text(s.lifecycleStatus, Modifier.padding(14.dp), style = consoleTextStyle(), maxLines = 5) + Text( + s.lifecycleStatus.text( + R.string.bfu_lifecycle_status_none, + R.string.bfu_lifecycle_status, + R.string.bfu_lifecycle_status_failed, + 420, + ), + Modifier.padding(14.dp), style = consoleTextStyle(), maxLines = 5) } Row(Modifier.padding(top = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - DawnShellButton( - stringResource(R.string.bfu_start_debian_short), - { a.requestLifecycle(DebianLauncher.Operation.START) }, Modifier.weight(1f), filled = true, - ) - DawnShellButton(stringResource(R.string.bfu_restart_debian_short), a::confirmRestart, Modifier.weight(1f)) - } - Row(Modifier.padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - DawnShellButton( - stringResource(R.string.bfu_force_stop_debian_short), a::confirmForceStop, - Modifier.weight(1f), contentColor = MaterialTheme.colorScheme.error, - ) - DawnShellButton(stringResource(R.string.bfu_stop_debian_short), a::confirmStop, Modifier.weight(1f)) + if (status != null) + DawnShellButton( + stringResource(R.string.bfu_stop_debian_short), + a::confirmStop, Modifier.weight(1f), filled = true, + ) + else + DawnShellButton( + stringResource(R.string.bfu_start_debian_short), + { a.requestLifecycle(DebianLauncher.Operation.START) }, Modifier.weight(1f), filled = true, + ) + IconButton(a::confirmRestart, shape = IconButtonDefaults.outlinedShape) { + Icon( + painterResource(R.drawable.ic_refresh_24), + contentDescription = stringResource(R.string.bfu_restart_debian_short), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } @@ -137,7 +170,7 @@ private fun SshAccessCard(s: BootUiState, a: BootActions) { Row(Modifier.fillMaxWidth().padding(10.dp), Arrangement.spacedBy(8.dp), Alignment.Bottom) { SelectionContainer(Modifier.weight(1f)) { // TODO: Change to ssh connection command - Text(s.generatedPublicKey, Modifier.padding(14.dp), style = consoleTextStyle()) + Text(a.buildSshConnectCommand(), Modifier.padding(14.dp), style = consoleTextStyle()) } IconButton( onClick = { a.copySshConnectCommand() }, diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.kt b/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.kt index 4dfb14a..e59ac13 100644 --- a/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.kt +++ b/app/src/main/kotlin/me/aroxu/dawnshell/BootActivity.kt @@ -31,8 +31,10 @@ import androidx.navigationevent.compose.LocalNavigationEventDispatcherOwner import java.io.IOException import java.util.Locale import java.util.concurrent.Executors +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import me.aroxu.dawnshell.ui.DawnShellTheme internal class BootActivity : AppCompatActivity(), BootActions { @@ -108,14 +110,32 @@ internal class BootActivity : AppCompatActivity(), BootActions { } } - private fun refreshLiveStatus() { - refreshRootAuthorizationStatus() - refreshInstallerStatus() - refreshSystemConfigurationStatus() - refreshLifecycleStatus() - refreshDockerPolicyStatus() - refreshHardwareCodecStatus() - refreshHardwareCodecLongRunStatus() + private class LiveStatus( + val rootAuthorization: String, + val installer: StatusLoad, + val systemConfig: StatusLoad, + val lifecycle: StatusLoad, + val dockerPolicy: StatusLoad, + val hardwareCodec: StatusLoad, + val hardwareCodecLongRun: StatusLoad, + ) + + /** Reads the status files off the main thread; only the state assignment runs on it. */ + private suspend fun refreshLiveStatus() { + val live = withContext(Dispatchers.IO) { + LiveStatus( + readRootAuthorizationStatus(), readInstallerStatus(), readSystemConfigurationStatus(), + readLifecycleStatus(), readDockerPolicyStatus(), readHardwareCodecStatus(), + readHardwareCodecLongRunStatus(), + ) + } + if (!state.rootAuthorizationInProgress) state.rootAuthorizationStatus = live.rootAuthorization + state.installStatus = live.installer + state.systemConfigStatus = live.systemConfig + state.lifecycleStatus = live.lifecycle + state.dockerPolicyStatus = live.dockerPolicy + state.hardwareCodecStatus = live.hardwareCodec + state.hardwareCodecLongRunStatus = live.hardwareCodecLongRun } // Dialogs @@ -166,6 +186,7 @@ internal class BootActivity : AppCompatActivity(), BootActions { // SSH access + /* private fun refreshGeneratedSshIdentity(provisionPublicKey: Boolean) { state.generatedPublicKey = try { val identity = BfuSshClientKeyStore.ensure(this) @@ -178,6 +199,7 @@ internal class BootActivity : AppCompatActivity(), BootActions { getString(R.string.bfu_generated_key_failed, e.message) } } + */ override fun confirmRotateSshKey() { if (!isUserUnlocked()) { @@ -197,7 +219,7 @@ internal class BootActivity : AppCompatActivity(), BootActions { val identity = BfuSshClientKeyStore.generateAndReplace(this) val layout = BfuRuntime.provision(this) BfuAuthorizedKeys.validateAndSave(layout, identity.publicKey) - state.generatedPublicKey = identity.publicKey + //state.generatedPublicKey = identity.publicKey recordOperation("SSH_CLIENT_KEY_ROTATED algorithm=ed25519 de_public_key_updated=true") state.dialogs += BootDialog.Notice( getString(R.string.bfu_rotate_ssh_key_done_message), @@ -263,7 +285,7 @@ internal class BootActivity : AppCompatActivity(), BootActions { "printf 'Imported DawnShell client key: %s\\n' \"\$KEY\"" } - private fun buildSshConnectCommand() = + override fun buildSshConnectCommand() = "ssh -i \"\$HOME/.ssh/dawnshell-ed25519\" -p 22 " + "-o IdentitiesOnly=yes -o PasswordAuthentication=no " + "-o StrictHostKeyChecking=accept-new " + @@ -304,7 +326,7 @@ internal class BootActivity : AppCompatActivity(), BootActions { state.hardwareCodec = BfuPreferences.hardwareCodecBridge(this) state.selectUsbMode(BfuPreferences.usbPassthroughMode(this)) state.usbDeviceIds.setTextAndPlaceCursorAtEnd(BfuPreferences.usbExclusiveDeviceIds(this)) - refreshGeneratedSshIdentity(true) + //refreshGeneratedSshIdentity(true) refreshRootAuthorizationStatus() refreshProbeStatus(false) refreshInstallerStatus() @@ -549,13 +571,15 @@ internal class BootActivity : AppCompatActivity(), BootActions { private fun refreshRootAuthorizationStatus() { if (state.rootAuthorizationInProgress) return - state.rootAuthorizationStatus = try { - val result = BfuRootAuthorization.readLastPersistentResult(this) - .ifEmpty { getString(R.string.bfu_root_authorization_none) } - getString(R.string.bfu_root_authorization_status, result) - } catch (e: IOException) { - getString(R.string.bfu_root_authorization_read_failed, e.message) - } + state.rootAuthorizationStatus = readRootAuthorizationStatus() + } + + private fun readRootAuthorizationStatus(): String = try { + val result = BfuRootAuthorization.readLastPersistentResult(this) + .ifEmpty { getString(R.string.bfu_root_authorization_none) } + getString(R.string.bfu_root_authorization_status, result) + } catch (e: IOException) { + getString(R.string.bfu_root_authorization_read_failed, e.message) } private fun packagesForUid(uid: Int): String { @@ -1059,73 +1083,50 @@ internal class BootActivity : AppCompatActivity(), BootActions { // Status lines - private inline fun statusLine( - @StringRes none: Int, - @StringRes format: Int, - maximumLength: Int, - @StringRes failed: Int, - read: () -> String, - ): String = try { - getString(format, compact(read().ifEmpty { getString(none) }, maximumLength)) - } catch (e: IOException) { - getString(failed, e.message) - } - - private inline fun codecStatusLine( - @StringRes none: Int, - @StringRes format: Int, - @StringRes failed: Int, - read: () -> String, - ): String = try { - getString(format, compact(read().ifEmpty { getString(none) }, 520)) + private inline fun loadStatus(read: () -> OperationStatus?): StatusLoad = try { + read()?.let(StatusLoad::Loaded) ?: StatusLoad.Missing } catch (e: IOException) { - getString(failed, BfuSu.sanitize(e.message)) + StatusLoad.Failed(BfuSu.sanitize(e.message)) } catch (e: RuntimeException) { - getString(failed, BfuSu.sanitize(e.message)) + StatusLoad.Failed(BfuSu.sanitize(e.message)) } private fun refreshSystemConfigurationStatus() { - state.systemConfigStatus = statusLine( - R.string.bfu_system_config_status_none, R.string.bfu_system_config_status, 360, - R.string.bfu_system_config_status_failed, - ) { DebianSystemProvisioner.readStatus(this) } + state.systemConfigStatus = readSystemConfigurationStatus() } + private fun readSystemConfigurationStatus() = loadStatus { DebianSystemProvisioner.readOperationStatus(this) } + private fun refreshLifecycleStatus() { - state.lifecycleStatus = statusLine( - R.string.bfu_lifecycle_status_none, R.string.bfu_lifecycle_status, 420, - R.string.bfu_lifecycle_status_failed, - ) { DebianLauncher.readStatus(this) } + state.lifecycleStatus = readLifecycleStatus() } + private fun readLifecycleStatus() = loadStatus { DebianLauncher.readOperationStatus(this) } + private fun refreshDockerPolicyStatus() { - state.dockerPolicyStatus = statusLine( - R.string.dawnshell_docker_policy_status_none, R.string.dawnshell_docker_policy_status, 420, - R.string.dawnshell_docker_policy_status_failed, - ) { DockerNetworkProvisioner.readStatus(this) } + state.dockerPolicyStatus = readDockerPolicyStatus() } + private fun readDockerPolicyStatus() = loadStatus { DockerNetworkProvisioner.readOperationStatus(this) } + private fun refreshHardwareCodecStatus() { - state.hardwareCodecStatus = codecStatusLine( - R.string.dawnshell_codec_status_none, R.string.dawnshell_codec_status, - R.string.dawnshell_codec_status_failed, - ) { HardwareCodecProbe.readStatus(this) } + state.hardwareCodecStatus = readHardwareCodecStatus() } + private fun readHardwareCodecStatus() = loadStatus { HardwareCodecProbe.readOperationStatus(this) } + private fun refreshHardwareCodecLongRunStatus() { - state.hardwareCodecLongRunStatus = codecStatusLine( - R.string.dawnshell_codec_long_run_status_none, R.string.dawnshell_codec_long_run_status, - R.string.dawnshell_codec_long_run_status_failed, - ) { HardwareCodecLongRun.readStatus(this) } + state.hardwareCodecLongRunStatus = readHardwareCodecLongRunStatus() } + private fun readHardwareCodecLongRunStatus() = loadStatus { HardwareCodecLongRun.readOperationStatus(this) } + private fun refreshInstallerStatus() { - state.installStatus = statusLine( - R.string.bfu_debian_install_status_none, R.string.bfu_debian_install_status, 360, - R.string.bfu_debian_install_status_failed, - ) { DebianRootfsInstaller.readStatus(this) } + state.installStatus = readInstallerStatus() } + private fun readInstallerStatus() = loadStatus { DebianRootfsInstaller.readOperationStatus(this) } + private fun recordOperation(message: String) { try { BfuOperationLog.append(this, message) diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/BootScreen.kt b/app/src/main/kotlin/me/aroxu/dawnshell/BootScreen.kt index 8b1858f..fdf5696 100644 --- a/app/src/main/kotlin/me/aroxu/dawnshell/BootScreen.kt +++ b/app/src/main/kotlin/me/aroxu/dawnshell/BootScreen.kt @@ -36,6 +36,7 @@ internal interface BootActions { fun confirmForceStop() fun confirmExportPrivateKey() fun confirmCopyKeyImportCommand() + fun buildSshConnectCommand(): String fun copySshConnectCommand() fun confirmRotateSshKey() fun updatePassword(account: String) @@ -88,12 +89,20 @@ internal fun SetupPage(s: BootUiState, a: BootActions) { SectionCard { SectionTitle(stringResource(R.string.dawnshell_section_debian_setup)) Body(stringResource(R.string.dawnshell_section_debian_setup_description), Modifier.padding(top = 4.dp)) - Small(s.installStatus, Modifier.padding(top = 16.dp, start = 4.dp), maxLines = 4) + Small( + s.installStatus.text( + R.string.bfu_debian_install_status_none, R.string.bfu_debian_install_status, R.string.bfu_debian_install_status_failed, 360, + ), + Modifier.padding(top = 16.dp, start = 4.dp), maxLines = 4) DawnShellButton( stringResource(R.string.bfu_install_debian), a::confirmDebianInstall, Modifier.fillMaxWidth().padding(top = 10.dp), filled = true, ) - Small(s.systemConfigStatus, Modifier.padding(top = 16.dp, start = 4.dp), maxLines = 4) + Small( + s.systemConfigStatus.text( + R.string.bfu_system_config_status_none, R.string.bfu_system_config_status, R.string.bfu_system_config_status_failed, 360, + ), + Modifier.padding(top = 16.dp, start = 4.dp), maxLines = 4) DawnShellButton( stringResource(R.string.bfu_configure_system), a::confirmSystemConfiguration, Modifier.fillMaxWidth().padding(top = 10.dp), @@ -243,7 +252,11 @@ internal fun CodecPage(s: BootUiState, a: BootActions) { SubTitle(stringResource(R.string.dawnshell_codec_apply_probe)) // TODO: Rich - SelectableSmall(s.hardwareCodecStatus, Modifier.padding(top = 12.dp)) + SelectableSmall( + s.hardwareCodecStatus.text( + R.string.dawnshell_codec_status_none, R.string.dawnshell_codec_status, R.string.dawnshell_codec_status_failed, 520, + ), + Modifier.padding(top = 12.dp)) DawnShellButton( stringResource(R.string.dawnshell_codec_apply_probe), a::probeHardwareCodecs, Modifier.fillMaxWidth().padding(top = 12.dp), filled = true, @@ -298,7 +311,12 @@ internal fun CodecPage(s: BootUiState, a: BootActions) { Callout(colorResource(R.color.ds_warning_container), colorResource(R.color.ds_on_warning_container), Modifier.padding(top = 8.dp)) { Small(stringResource(R.string.dawnshell_codec_long_run_warning), color = colorResource(R.color.ds_on_warning_container)) } - SelectableSmall(s.hardwareCodecLongRunStatus, Modifier.padding(top = 12.dp)) + SelectableSmall( + s.hardwareCodecLongRunStatus.text( + R.string.dawnshell_codec_long_run_status_none, R.string.dawnshell_codec_long_run_status, + R.string.dawnshell_codec_long_run_status_failed, 520, + ), + Modifier.padding(top = 12.dp)) Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { DawnShellButton( stringResource(R.string.dawnshell_codec_long_run_start), a::confirmLongRunStart, diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/BootUiState.kt b/app/src/main/kotlin/me/aroxu/dawnshell/BootUiState.kt index 531e2b2..0a2af2c 100644 --- a/app/src/main/kotlin/me/aroxu/dawnshell/BootUiState.kt +++ b/app/src/main/kotlin/me/aroxu/dawnshell/BootUiState.kt @@ -71,6 +71,15 @@ internal sealed interface BootDialog { ) : BootDialog } +/** Latest persisted status of one background operation, as read from its *.status file. */ +internal sealed interface StatusLoad { + data object Missing : StatusLoad + + data class Loaded(val status: OperationStatus) : StatusLoad + + data class Failed(val reason: String?) : StatusLoad +} + internal class BootUiState { var enableBfu by mutableStateOf(false) var allowCeReadableBfu by mutableStateOf(false) @@ -87,14 +96,13 @@ internal class BootUiState { var appliedSettings by mutableStateOf(null) var rootAuthorizationStatus by mutableStateOf("") - var installStatus by mutableStateOf("") - var systemConfigStatus by mutableStateOf("") - var lifecycleStatus by mutableStateOf("") - var dockerPolicyStatus by mutableStateOf("") - var hardwareCodecStatus by mutableStateOf("") - var hardwareCodecLongRunStatus by mutableStateOf("") + var installStatus by mutableStateOf(StatusLoad.Missing) + var systemConfigStatus by mutableStateOf(StatusLoad.Missing) + var lifecycleStatus by mutableStateOf(StatusLoad.Missing) + var dockerPolicyStatus by mutableStateOf(StatusLoad.Missing) + var hardwareCodecStatus by mutableStateOf(StatusLoad.Missing) + var hardwareCodecLongRunStatus by mutableStateOf(StatusLoad.Missing) var probeSummary by mutableStateOf("") - var generatedPublicKey by mutableStateOf("") var rootAuthorizationInProgress by mutableStateOf(false) var passwordUpdateInProgress by mutableStateOf(false) diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/NativeEvent.kt b/app/src/main/kotlin/me/aroxu/dawnshell/NativeEvent.kt new file mode 100644 index 0000000..2680489 --- /dev/null +++ b/app/src/main/kotlin/me/aroxu/dawnshell/NativeEvent.kt @@ -0,0 +1,210 @@ +package me.aroxu.dawnshell + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** One JSON Lines event emitted by the native helpers; schema v1 is described in docs/native-output-schema.md. */ +sealed interface NativeEvent { + val event: String +} + +@Serializable +data class Namespaces( + val pid: Long = 0, + val mnt: Long = 0, + val uts: Long = 0, + val ipc: Long = 0, + val cgroup: Long = 0, + val net: Long = 0, +) + +/** The supervisor's lock is held: `running` once its identity is proven, otherwise `starting_or_unknown`. */ +@Serializable +data class LauncherRunning( + override val event: String = "running", + val state: String = "", + val mode: String = "", + @SerialName("supervisor_pid") val supervisorPid: Int = 0, + @SerialName("init_host_pid") val initHostPid: Int = 0, + @SerialName("supervisor_identity_valid") val supervisorIdentityValid: Boolean = false, + @SerialName("init_identity_valid") val initIdentityValid: Boolean = false, + @SerialName("namespace_topology_valid") val namespaceTopologyValid: Boolean = false, + @SerialName("cgroup_mode") val cgroupMode: String = "", + @SerialName("host_usb_mode") val hostUsbMode: String = "", + val ns: Namespaces = Namespaces(), + @SerialName("updated_epoch") val updatedEpoch: Long = 0, +) : NativeEvent { + val isRunning get() = event == "running" +} + +@Serializable +data class LauncherStopped( + override val event: String = "stopped", + @SerialName("last_state") val lastState: String = "", + val mode: String = "", + @SerialName("cgroup_mode") val cgroupMode: String = "", + @SerialName("host_usb_mode") val hostUsbMode: String = "", + @SerialName("wait_status") val waitStatus: Int = -1, + @SerialName("updated_epoch") val updatedEpoch: Long = 0, +) : NativeEvent + +/** `started` (systemd) or `fallback_started` (direct sshd). */ +@Serializable +data class LauncherStarted( + override val event: String = "started", + @SerialName("supervisor_pid") val supervisorPid: Int = 0, + @SerialName("init_host_pid") val initHostPid: Int = 0, + @SerialName("sshd_pid") val sshdPid: Int = 0, + val mode: String = "systemd", + @SerialName("cgroup_mode") val cgroupMode: String = "", + @SerialName("host_usb_mode") val hostUsbMode: String = "", + @SerialName("host_usb_filter_count") val hostUsbFilterCount: Int = 0, +) : NativeEvent + +@Serializable +data class StartFailed( + override val event: String = "start_failed", + val stage: String = "", + val errno: Int? = null, + val exit: Int? = null, + @SerialName("child_exit") val childExit: Int? = null, + @SerialName("child_signal") val childSignal: Int? = null, +) : NativeEvent + +@Serializable +data class Failed( + override val event: String = "failed", + val stage: String = "", + val errno: Int? = null, + val error: String = "", +) : NativeEvent + +/** Health of the systemd instance (`mode=systemd`) or of the direct sshd fallback (`mode=compat`). */ +@Serializable +data class Health( + override val event: String = "health", + val mode: String = "systemd", + val healthy: Boolean = false, + val pid1: String = "", + @SerialName("system_state") val systemState: String = "", + @SerialName("dbus_service") val dbusService: String = "", + @SerialName("dbus_bus") val dbusBus: String = "", + @SerialName("ssh_service") val sshService: String = "", + @SerialName("boot_proof_service") val bootProofService: String = "", + @SerialName("boot_proof_marker") val bootProofMarker: String = "", + @SerialName("default_target") val defaultTarget: String = "", + @SerialName("target_state") val targetState: String = "", + @SerialName("listen_22") val listen22: Boolean = false, + @SerialName("compat_ready") val compatReady: Boolean = false, + @SerialName("cgroup_mode") val cgroupMode: String = "", + @SerialName("cgroup_delegation") val cgroupDelegation: String = "", + @SerialName("devices_cgroup") val devicesCgroup: String = "", +) : NativeEvent + +@Serializable +data class Diagnostic( + override val event: String = "diagnostic", + val label: String = "", + val content: String = "", +) : NativeEvent + +/** Result of the in-chroot runtime probe: `namespace_ok`/`compat_ok` succeed, `*_failed` carry the failed stage. */ +@Serializable +data class RuntimeProbe( + override val event: String = "", + val stage: String = "", + val arch: String = "", + val debian: Int = 0, + val init: String = "", + val systemctl: String = "", +) : NativeEvent { + val succeeded get() = event == "namespace_ok" || event == "compat_ok" +} + +/** Events without a dedicated type (and events newer than this app) keep their raw fields. */ +data class OtherEvent(override val event: String, val fields: JsonObject) : NativeEvent + +object NativeOutput { + private const val MAX_DETAIL_EVENTS = 8 + private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true } + + private val serializers: Map> = mapOf( + "running" to LauncherRunning.serializer(), + "starting_or_unknown" to LauncherRunning.serializer(), + "stopped" to LauncherStopped.serializer(), + "started" to LauncherStarted.serializer(), + "fallback_started" to LauncherStarted.serializer(), + "start_failed" to StartFailed.serializer(), + "failed" to Failed.serializer(), + "health" to Health.serializer(), + "diagnostic" to Diagnostic.serializer(), + "namespace_ok" to RuntimeProbe.serializer(), + "namespace_failed" to RuntimeProbe.serializer(), + "compat_ok" to RuntimeProbe.serializer(), + "compat_failed" to RuntimeProbe.serializer(), + ) + + /** Decodes every JSON line; non-JSON lines such as free-form stderr logs and malformed lines are skipped. */ + @JvmStatic + fun parse(text: String?): List = + text.orEmpty().lineSequence().map(String::trim).filter { it.startsWith("{") }.mapNotNull(::decode).toList() + + /** Raw events (newest $MAX_DETAIL_EVENTS) for the persisted status detail; null when there are none. */ + @JvmStatic + fun detail(text: String?): JsonObject? { + val events = text.orEmpty().lineSequence().map(String::trim).filter { it.startsWith("{") } + .mapNotNull { runCatching { json.parseToJsonElement(it).jsonObject }.getOrNull() } + .toList().takeLast(MAX_DETAIL_EVENTS) + return if (events.isEmpty()) null else JsonObject(mapOf("events" to JsonArray(events))) + } + + @JvmStatic + fun health(text: String?): Health? = parse(text).filterIsInstance().lastOrNull() + + @JvmStatic + fun has(text: String?, event: String): Boolean = parse(text).any { it.event == event } + + @JvmStatic + fun runtimeProbeSucceeded(text: String?): Boolean = + parse(text).filterIsInstance().any { it.succeeded } + + /** Typed view of the events persisted by [detail]. */ + @JvmStatic + fun fromDetail(detail: JsonObject?): List = + (detail?.get("events") as? JsonArray).orEmpty().mapNotNull { (it as? JsonObject)?.let(::decodeFields) } + + private fun decode(line: String): NativeEvent? = try { + decodeFields(json.parseToJsonElement(line).jsonObject) + } catch (e: SerializationException) { + null + } catch (e: IllegalArgumentException) { + null + } + + private fun decodeFields(fields: JsonObject): NativeEvent? = try { + val name = fields["event"]?.jsonPrimitive?.content + when (val serializer = name?.let(serializers::get)) { + null -> name?.let { OtherEvent(it, fields) } + else -> json.decodeFromJsonElement(serializer, fields).withEvent(name) + } + } catch (e: SerializationException) { + null + } catch (e: IllegalArgumentException) { + null + } + + /** One serializer serves several event names, so the decoded event name is the wire name. */ + private fun NativeEvent.withEvent(name: String): NativeEvent = when (this) { + is LauncherRunning -> copy(event = name) + is LauncherStarted -> copy(event = name) + is RuntimeProbe -> copy(event = name) + else -> this + } +} diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/OperationStatus.kt b/app/src/main/kotlin/me/aroxu/dawnshell/OperationStatus.kt new file mode 100644 index 0000000..dc669b6 --- /dev/null +++ b/app/src/main/kotlin/me/aroxu/dawnshell/OperationStatus.kt @@ -0,0 +1,88 @@ +package me.aroxu.dawnshell + +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import java.io.File +import java.io.IOException + +enum class OperationState { QUEUED, RUNNING, SUCCEEDED, FAILED, REJECTED, UNAVAILABLE, UNKNOWN } + +/** Persisted result of one background operation; `detail` carries typed native events when there are any. */ +@Serializable +data class OperationStatus( + val v: Int = 1, + val ts: Long = 0, + val state: OperationState = OperationState.UNKNOWN, + val summary: String = "", + val detail: JsonObject? = null, +) { + /** Legacy one-line form, shown in logs. */ + fun text() = "${state.name} $summary" +} + +/** Reads and atomically writes the *.status files as one JSON object each. */ +object StatusStore { + private const val MAX_BYTES = 64 * 1024 + private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true } + private val lock = Any() + + /** `text` is "STATE summary"; an unknown leading word is kept as UNKNOWN with the whole text as summary. */ + @JvmStatic + @JvmOverloads + @Throws(IOException::class) + fun write(destination: File, text: String, detail: JsonObject? = null) { + val separator = text.indexOf(' ') + val word = if (separator < 0) text else text.substring(0, separator) + val state = OperationState.entries.firstOrNull { it.name == word } + val status = OperationStatus( + ts = System.currentTimeMillis(), + state = state ?: OperationState.UNKNOWN, + summary = if (state == null) text else if (separator < 0) "" else text.substring(separator + 1), + detail = detail, + ) + val temporary = File(destination.parentFile, destination.name + ".new") + synchronized(lock) { + temporary.outputStream().use { output -> + output.write((json.encodeToString(OperationStatus.serializer(), status) + "\n").toByteArray()) + output.fd.sync() + } + ownerOnly(temporary) + if (destination.exists() && !destination.delete()) throw IOException("cannot replace " + destination.name) + if (!temporary.renameTo(destination)) throw IOException("cannot publish " + destination.name) + ownerOnly(destination) + } + } + + /** Null when the file does not exist yet. A pre-JSON " STATE summary" file is still understood. */ + @JvmStatic + @Throws(IOException::class) + fun read(source: File): OperationStatus? { + if (!source.isFile) return null + val bytes = source.inputStream().use { it.readBytes() } + val text = bytes.decodeToString(endIndex = minOf(bytes.size, MAX_BYTES)).trim() + if (text.isEmpty()) return null + try { + return json.decodeFromString(OperationStatus.serializer(), text) + } catch (e: SerializationException) { + val legacy = text.substringAfter(' ', text) + val word = legacy.substringBefore(' ') + val state = OperationState.entries.firstOrNull { it.name == word } ?: OperationState.UNKNOWN + return OperationStatus(state = state, summary = if (state == OperationState.UNKNOWN) text else legacy.substringAfter(' ', "")) + } + } + + /** Empty string when there is no status yet; used by the log screens. */ + @JvmStatic + @Throws(IOException::class) + fun readText(source: File): String = read(source)?.text().orEmpty() + + private fun ownerOnly(file: File) { + file.setReadable(false, false) + file.setWritable(false, false) + file.setExecutable(false, false) + file.setReadable(true, true) + file.setWritable(true, true) + } +} diff --git a/app/src/main/kotlin/me/aroxu/dawnshell/StatusText.kt b/app/src/main/kotlin/me/aroxu/dawnshell/StatusText.kt new file mode 100644 index 0000000..d3c0e23 --- /dev/null +++ b/app/src/main/kotlin/me/aroxu/dawnshell/StatusText.kt @@ -0,0 +1,43 @@ +package me.aroxu.dawnshell + +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource + +@Composable +internal fun StatusLoad.text( + @StringRes none: Int, + @StringRes format: Int, + @StringRes failed: Int, + maximumLength: Int, +): String = when (this) { + StatusLoad.Missing -> stringResource(none) + is StatusLoad.Failed -> stringResource(failed, reason.orEmpty()) + is StatusLoad.Loaded -> stringResource(format, status.display().compactTo(maximumLength)) +} + +/** Typed launcher events, when the status carries them, replace the raw command line. */ +@Composable +private fun OperationStatus.display(): String { + val events = NativeOutput.fromDetail(detail) + val running = events.filterIsInstance().lastOrNull() + val stopped = events.filterIsInstance().lastOrNull() + val health = events.filterIsInstance().lastOrNull() + val launcher = when { + running != null -> stringResource( + R.string.bfu_lifecycle_running_detail, + state.name, running.mode, running.initHostPid, running.cgroupMode, running.hostUsbMode, + ) + stopped != null -> stringResource(R.string.bfu_lifecycle_stopped_detail, state.name, stopped.lastState) + else -> return text() + } + if (health == null) return launcher + return launcher + " · " + stringResource( + if (health.healthy) R.string.bfu_lifecycle_health_ok else R.string.bfu_lifecycle_health_bad, + ) +} + +private fun String.compactTo(maximumLength: Int): String { + val clean = trim() + return if (clean.length <= maximumLength) clean else clean.substring(0, maxOf(0, maximumLength - 1)) + "…" +} diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 459b56c..5fcdfba 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -122,6 +122,10 @@ Debian 제어 요청을 바로 전송했습니다: %1$s Debian 수명 주기 작업을 요청하지 못했습니다: %1$s Debian systemd 수명 주기 상태:\n%1$s + %1$s · %2$s · init PID %3$d · cgroup %4$s · USB %5$s + %1$s · 중지됨 (마지막 상태: %2$s) + 정상 + 비정상 기록된 Debian 수명 주기 작업이 없습니다. Debian 수명 주기 상태를 읽지 못했습니다: %1$s Debian systemd 수명 주기 로그(실시간, 최신 64 KiB): diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1cc33c8..2393409 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -122,6 +122,10 @@ Debian control request sent: %1$s Could not request Debian lifecycle operation: %1$s Debian systemd lifecycle status:\n%1$s + %1$s · %2$s · init PID %3$d · cgroup %4$s · USB %5$s + %1$s · stopped (last state: %2$s) + healthy + unhealthy No Debian lifecycle operation has been recorded yet. Failed to read Debian lifecycle status: %1$s Debian systemd lifecycle log (live, newest 64 KiB): diff --git a/app/src/test/cpp/dawnshell_json_test.c b/app/src/test/cpp/dawnshell_json_test.c new file mode 100644 index 0000000..e70830b --- /dev/null +++ b/app/src/test/cpp/dawnshell_json_test.c @@ -0,0 +1,59 @@ +#define DS_JSON_NOW() 1700000000LL +#include "dawnshell_json.h" + +#include + +static int failures; + +static void expect(const char *name, DsJson *j, const char *expected) { + ds_json_finish(j); + j->buf[j->len] = '\0'; + if (strcmp(j->buf, expected) != 0) { + fprintf(stderr, "FAIL %s\n got: %s expected: %s", name, j->buf, expected); + failures++; + } +} + +int main(void) { + char buf[256]; + DsJson j; + + ds_json_begin(&j, buf, sizeof(buf), "running"); + ds_json_int(&j, "pid", -42); + ds_json_bool(&j, "ok", true); + ds_json_obj_begin(&j, "ns"); + ds_json_int(&j, "pid", 4026531836LL); + ds_json_int(&j, "net", 0); + ds_json_obj_end(&j); + ds_json_str(&j, "mode", "systemd"); + expect("fields", &j, + "{\"v\":1,\"ts\":1700000000,\"event\":\"running\",\"pid\":-42,\"ok\":true," + "\"ns\":{\"pid\":4026531836,\"net\":0},\"mode\":\"systemd\"}\n"); + + ds_json_begin(&j, buf, sizeof(buf), "failed"); + ds_json_str(&j, "error", "quote\" back\\ nl\n tab\t ctl\x01 \xec\x95\x88 bad\xff end"); + expect("escape", &j, + "{\"v\":1,\"ts\":1700000000,\"event\":\"failed\",\"error\":" + "\"quote\\\" back\\\\ nl\\n tab\\t ctl\\u0001 \xec\x95\x88 bad? end\"}\n"); + + ds_json_begin(&j, buf, sizeof(buf), "x"); + ds_json_int(&j, "min", (-9223372036854775807LL - 1)); + expect("int_min", &j, + "{\"v\":1,\"ts\":1700000000,\"event\":\"x\",\"min\":-9223372036854775808}\n"); + + char small[96]; + ds_json_begin(&j, small, sizeof(small), "diagnostic"); + ds_json_str(&j, "content", "this value is far too long to fit in the tiny buffer used here"); + ds_json_int(&j, "after", 1); + expect("truncated", &j, + "{\"v\":1,\"ts\":1700000000,\"event\":\"diagnostic\",\"truncated\":true}\n"); + + ds_json_begin(&j, small, sizeof(small), "health"); + ds_json_obj_begin(&j, "ns"); + ds_json_str(&j, "a", "0123456789012345678901234567890123456789012345678901234567890123456789"); + expect("truncated_nested", &j, + "{\"v\":1,\"ts\":1700000000,\"event\":\"health\",\"ns\":{},\"truncated\":true}\n"); + + if (failures == 0) puts("dawnshell_json: all tests passed"); + return failures == 0 ? 0 : 1; +} diff --git a/app/src/test/kotlin/me/aroxu/dawnshell/NativeOutputTest.kt b/app/src/test/kotlin/me/aroxu/dawnshell/NativeOutputTest.kt new file mode 100644 index 0000000..1ca8525 --- /dev/null +++ b/app/src/test/kotlin/me/aroxu/dawnshell/NativeOutputTest.kt @@ -0,0 +1,77 @@ +package me.aroxu.dawnshell + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NativeOutputTest { + private val running = """{"v":1,"ts":1700000000,"event":"running","state":"running","mode":"systemd","supervisor_pid":812,"init_host_pid":840,"supervisor_identity_valid":true,"init_identity_valid":true,"namespace_topology_valid":true,"ipc_namespace":"android-shared","network_namespace":"android-shared","network_mode":"shared-nic","cgroup_mode":"v2","host_usb_mode":"off","ns":{"pid":4026532600,"mnt":4026532598,"uts":4026532599,"ipc":4026531839,"cgroup":4026532601,"net":4026532001},"updated_epoch":1699999990}""" + private val health = """{"v":1,"ts":1700000000,"event":"health","mode":"systemd","pid1":"systemd","system_state":"running","dbus_service":"active","dbus_bus":"ok","ssh_service":"active","boot_proof_service":"active","boot_proof_marker":"present","default_target":"multi-user.target","target_state":"active","cgroup_mode":"v2","cgroup_delegation":"delegated","devices_cgroup":"bpf","devices_path":"","systemd_path":"","unified_path":"/","pid1_start_ticks":0,"devices_hierarchy":0,"listen_22":true,"healthy":true}""" + + @Test + fun decodesRunningWithNamespaces() { + val event = NativeOutput.parse(running).single() as LauncherRunning + assertTrue(event.isRunning) + assertEquals(812, event.supervisorPid) + assertEquals("v2", event.cgroupMode) + assertEquals(4026532600L, event.ns.pid) + } + + @Test + fun startingKeepsItsWireName() { + val event = NativeOutput.parse(running.replace("\"event\":\"running\"", "\"event\":\"starting_or_unknown\"")).single() + assertFalse((event as LauncherRunning).isRunning) + assertEquals("starting_or_unknown", event.event) + } + + @Test + fun decodesHealthAndIgnoresUnknownFields() { + val event = NativeOutput.health("noise\n$health\n") + assertNotNull(event) + assertTrue(event!!.healthy) + assertTrue(event.listen22) + assertEquals("multi-user.target", event.defaultTarget) + } + + @Test + fun skipsPlainLogLinesAndMalformedJson() { + val text = "[1700000000] BFU_DEBIAN_STAGE private_proc_mounted\n{\"v\":1,\"event\":\n$running\n" + assertEquals(1, NativeOutput.parse(text).size) + assertNull(NativeOutput.health(text)) + } + + @Test + fun keepsUnknownEventsAsOther() { + val event = NativeOutput.parse("""{"v":2,"ts":1,"event":"future_event","x":1}""").single() + assertTrue(event is OtherEvent) + assertEquals("future_event", event.event) + } + + @Test + fun decodesFailureAndStartFailure() { + val text = """{"v":1,"ts":1,"event":"failed","stage":"root_lstat","errno":2,"error":"No such file or directory"} +{"v":1,"ts":1,"event":"start_failed","stage":"namespace_setup","exit":60}""" + val events = NativeOutput.parse(text) + assertEquals(2, events.size) + assertEquals(2, (events[0] as Failed).errno) + assertEquals(60, (events[1] as StartFailed).exit) + assertNull((events[1] as StartFailed).errno) + } + + @Test + fun runtimeProbeResult() { + assertTrue(NativeOutput.runtimeProbeSucceeded("""{"v":1,"ts":1,"event":"namespace_ok","pid":1,"proc1":"sh","arch":"arm64","debian":13,"init":"present","systemctl":"present","cgroup":"0::/,"}""")) + assertFalse(NativeOutput.runtimeProbeSucceeded("""{"v":1,"ts":1,"event":"namespace_failed","stage":"dpkg_arch"}""")) + } + + @Test + fun detailKeepsNewestEvents() { + val text = (1..10).joinToString("\n") { """{"v":1,"ts":$it,"event":"stage$it"}""" } + val events = NativeOutput.detail(text)!!["events"] as kotlinx.serialization.json.JsonArray + assertEquals(8, events.size) + assertNull(NativeOutput.detail("no json here")) + } +} diff --git a/app/src/test/kotlin/me/aroxu/dawnshell/StatusStoreTest.kt b/app/src/test/kotlin/me/aroxu/dawnshell/StatusStoreTest.kt new file mode 100644 index 0000000..653f8b9 --- /dev/null +++ b/app/src/test/kotlin/me/aroxu/dawnshell/StatusStoreTest.kt @@ -0,0 +1,50 @@ +package me.aroxu.dawnshell + +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class StatusStoreTest { + @get:Rule + val folder = TemporaryFolder() + + @Test + fun roundTripsStateSummaryAndDetail() { + val file = folder.newFile("a.status") + StatusStore.write(file, "SUCCEEDED command=x exit=0", NativeOutput.detail("""{"v":1,"event":"running"}""")) + val status = StatusStore.read(file)!! + assertEquals(OperationState.SUCCEEDED, status.state) + assertEquals("command=x exit=0", status.summary) + assertEquals(1, (status.detail as JsonObject).size) + assertEquals("SUCCEEDED command=x exit=0", StatusStore.readText(file)) + } + + @Test + fun missingFileIsNull() { + assertNull(StatusStore.read(folder.root.resolve("none.status"))) + assertEquals("", StatusStore.readText(folder.root.resolve("none.status"))) + } + + @Test + fun unknownLeadingWordIsKeptAsSummary() { + val file = folder.newFile("b.status") + StatusStore.write(file, "UNAVAILABLE user_unlocked=false") + assertEquals(OperationState.UNAVAILABLE, StatusStore.read(file)!!.state) + StatusStore.write(file, "weird text") + val status = StatusStore.read(file)!! + assertEquals(OperationState.UNKNOWN, status.state) + assertEquals("weird text", status.summary) + } + + @Test + fun readsLegacyPlainStatusFiles() { + val file = folder.newFile("c.status") + file.writeText("1700000000000 FAILED stage=boom\n") + val status = StatusStore.read(file)!! + assertEquals(OperationState.FAILED, status.state) + assertEquals("stage=boom", status.summary) + } +} diff --git a/docs/README.ko.md b/docs/README.ko.md index 40ea116..4fb59cc 100644 --- a/docs/README.ko.md +++ b/docs/README.ko.md @@ -71,6 +71,7 @@ DawnShell을 처음 설치하는 사용자부터 내부 구조를 검토하는 | [Debian rootfs 설치 과정](rootfs-installation.ko.md) | 내장 부트스트랩 도구, 서명·해시 검증, 원자적 게시, 실패 보존 | | [Debian systemd와 SSH](debian-systemd.ko.md) | 런타임 mount, PID 1, 네트워크, SSH 정책, 종료와 재시작 | | [하드웨어 코덱 worker 프로토콜](hardware-codec-protocol.ko.md) | `memfd`/`eventfd`, 메시지 형식, 하드웨어 선택, 제한값 | +| [네이티브 출력 스키마](native-output-schema.ko.md) | 네이티브 헬퍼의 JSON Lines 이벤트와 `*.status` 파일 형식 | | [하드웨어 코덱 구현 결정 기록](media-codec-bridge-plan.ko.md) | 최종 구조를 선택한 이유와 비목표를 기록한 설계 결정 문서 | | [빌드와 배포](building.ko.md) | 로컬 빌드, 병렬 작업 수, CI, 서명, Release 구성 | diff --git a/docs/README.md b/docs/README.md index ecf3a7a..43d3676 100644 --- a/docs/README.md +++ b/docs/README.md @@ -72,6 +72,7 @@ Use the [user manual](user-guide.md) for routine operation and the | [Rootfs installation](rootfs-installation.md) | Embedded tools, signature/hash verification, atomic publication, failure preservation | | [Debian systemd and SSH](debian-systemd.md) | Runtime mounts, PID 1, networking, SSH policy, stop and restart | | [Hardware codec worker protocol](hardware-codec-protocol.md) | `memfd`/`eventfd`, wire format, hardware selection, limits | +| [Native output schema](native-output-schema.md) | JSON Lines events from native helpers and the `*.status` file format | | [Hardware codec decision record](media-codec-bridge-plan.md) | Why the final private-worker design was selected and what remains out of scope | | [Build and release](building.md) | Local build, parallel jobs, CI, signing, release contents | diff --git a/docs/architecture.ko.md b/docs/architecture.ko.md index 109679c..023a50e 100644 --- a/docs/architecture.ko.md +++ b/docs/architecture.ko.md @@ -179,6 +179,12 @@ session 통계는 keyframe, timestamp, EOS, 상속 shared-memory 전송과 Surfa `cpu_yuv_frames=0`을 검증합니다. `USER_UNLOCKED`는 Debian을 중지하지 않으며 BFU와 AFU 모두 codec 명령 실행 시에만 worker가 생성됩니다. +## 네이티브 결과와 상태 + +네이티브 헬퍼는 한 줄에 JSON 객체 하나를 출력하고, 앱은 이를 타입이 있는 Kotlin 이벤트로 디코드합니다. +[네이티브 출력 스키마](native-output-schema.ko.md)를 참고하세요. 백그라운드 작업의 결과는 JSON `*.status` 파일로 저장되며, +UI는 텍스트를 파싱하는 대신 타입이 있는 `OperationStatus`로 읽습니다. + ## SSH 키 흐름 1. 사용자가 잠금을 해제한 뒤 앱이 임의 Ed25519 키 쌍을 생성합니다. diff --git a/docs/architecture.md b/docs/architecture.md index 788d885..f3c5252 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -124,6 +124,12 @@ keyframes, timestamps, EOS, inherited shared-memory transport, and zero CPU YUV frames on the Surface path. `USER_UNLOCKED` does not stop Debian; a worker is created only when a codec command runs in either BFU or AFU. +## Native results and status + +The native helpers print one JSON object per line and the app decodes it into typed Kotlin events; see the +[native output schema](native-output-schema.md). Background operations persist their result as a JSON +`*.status` file, which the UI reads as a typed `OperationStatus` instead of parsing text. + ## SSH keys The app generates an Ed25519 key pair after unlock. The private half stays in app diff --git a/docs/building.ko.md b/docs/building.ko.md index c8ed2a8..14c04f2 100644 --- a/docs/building.ko.md +++ b/docs/building.ko.md @@ -84,6 +84,7 @@ dist/dawnshell-app_v+debug.apk ./scripts/test-ffmpeg-bridge-plan.sh ./scripts/test-live-codec-pipeline.sh ./scripts/test-gpu-status-tool.sh +./scripts/test-native-output.sh ./scripts/test-host-reboot-isolation.sh ./scripts/test-rootfs-path-resolution.sh ./scripts/test-lifecycle-control-policy.sh diff --git a/docs/building.md b/docs/building.md index c34092a..4f34dd8 100644 --- a/docs/building.md +++ b/docs/building.md @@ -70,6 +70,7 @@ dist/dawnshell-app_v+debug.apk ./scripts/test-ffmpeg-bridge-plan.sh ./scripts/test-live-codec-pipeline.sh ./scripts/test-gpu-status-tool.sh +./scripts/test-native-output.sh ./scripts/test-host-reboot-isolation.sh ./scripts/test-rootfs-path-resolution.sh ./scripts/test-lifecycle-control-policy.sh diff --git a/docs/native-output-schema.ko.md b/docs/native-output-schema.ko.md new file mode 100644 index 0000000..631b073 --- /dev/null +++ b/docs/native-output-schema.ko.md @@ -0,0 +1,55 @@ +# 네이티브 출력 스키마 + +[English](native-output-schema.md) · [문서](README.ko.md) · [아키텍처](architecture.ko.md) + +DawnShell의 네이티브 헬퍼는 결과를 앱에 **JSON Lines**(한 줄에 JSON 객체 하나, UTF-8)로 전달합니다. 출력은 의존성이 없는 +`app/src/main/cpp/dawnshell_json.h`가 만들고, 앱은 kotlinx.serialization으로 타입이 있는 Kotlin 클래스(`NativeEvent.kt`)에 +디코드합니다. stderr의 자유 형식 로그(예: `[epoch] BFU_DEBIAN_STAGE …`)는 스키마에 포함되지 않으며, 앱은 JSON 객체가 아닌 줄을 +모두 건너뜁니다. + +## 공통 필드 + +```json +{"v":1,"ts":1700000000,"event":"running", "...":"..."} +``` + +| 필드 | 타입 | 의미 | +| --- | --- | --- | +| `v` | int | 스키마 버전. 같은 버전 안에서는 필드 추가만 허용하고, 삭제·변경 시 올립니다. | +| `ts` | int | Unix 시간(초). | +| `event` | string | 이벤트 이름(소문자 snake case). | +| `truncated` | bool, 선택 | 일부 필드가 줄 버퍼에 맞지 않아 생략되었습니다. | + +숫자와 불리언은 JSON 네이티브 타입입니다. 한 줄은 항상 유효한 JSON이며 `write(2)` 한 번으로 출력됩니다. 읽는 쪽은 알 수 없는 +필드를 무시하고 알 수 없는 이벤트를 보존해야 합니다. + +## `bfu-namespace-probe` 이벤트 + +| 이벤트 | 채널 | 필드 | +| --- | --- | --- | +| `running`, `starting_or_unknown` | stdout | `state`, `mode`, `supervisor_pid`, `init_host_pid`, `supervisor_identity_valid`, `init_identity_valid`, `namespace_topology_valid`, `cgroup_mode`, `host_usb_mode`, `ns`{`pid`,`mnt`,`uts`,`ipc`,`cgroup`,`net`}, `updated_epoch` | +| `stopped` | stdout | `last_state`, `mode`, `cgroup_mode`, `host_usb_mode`, `wait_status`, `updated_epoch` | +| `started`, `fallback_started` | stdout | `supervisor_pid`, `init_host_pid` 또는 `sshd_pid`, `mode`, `cgroup_mode`, `host_usb_mode`, `host_usb_filter_count` | +| `start_failed` | stdout | `stage`, 선택 `errno`, `exit`, `child_exit`, `child_signal` | +| `failed` | stderr | `stage`, 선택 `errno`, `error`. 프로세스 종료 코드는 바뀌지 않습니다. | +| `health` | stdout | `mode`(`systemd`/`compat`), `healthy`, `pid1`, `system_state`, `dbus_service`, `dbus_bus`, `ssh_service`, `boot_proof_service`, `boot_proof_marker`, `default_target`, `target_state`, `listen_22`, `compat_ready`, `cgroup_mode`, `cgroup_delegation`, `devices_cgroup` | +| `diagnostic` | stdout | `label`, `content`(실패한 유닛, 정제됨) | +| `namespace_ok`, `compat_ok` | stdout | `arch`, `debian`, 그리고 `pid`, `proc1`, `init`, `systemctl`, `cgroup` 또는 `mode` | +| `namespace_failed`, `compat_failed` | stdout | `stage` | +| `already_running`, `already_stopped`, `orphaned_init`, `orphaned_init_stopped`, `orphaned_instance`, `force_stopped`, `shutdown_test_requested`, `shutdown_test_completed` | stdout | 이벤트별 PID와 모드. `OtherEvent`로 디코드됩니다. | + +Debian chroot 안의 health·probe 스니펫은 셸 스크립트이며 같은 객체를 출력합니다. 문자열 값은 `[A-Za-z0-9_./:@+=,; -]`만 남겨 +따옴표나 제어 문자가 JSON을 깨뜨리지 못하게 합니다. + +## 상태 파일 + +각 `*.status` 파일은 JSON 객체 하나입니다: `{"v":1,"ts":…,"state":"SUCCEEDED","summary":"…","detail":{…}}`. +`state`는 `QUEUED`, `RUNNING`, `SUCCEEDED`, `FAILED`, `REJECTED`, `UNAVAILABLE`, `UNKNOWN` 중 하나입니다. 수명 주기 작업의 +`detail.events`에는 최신 네이티브 이벤트 8개가 들어 있습니다. JSON 이전의 ` STATE text` 파일도 한 번은 읽히며 다음 +쓰기에서 교체됩니다. + +## 호환 규칙 + +- 필드 추가는 자유롭지만, 이름 변경·삭제·타입 변경은 `v`를 올립니다. +- 앱과 헬퍼는 한 APK로 배포되므로 버전 협상은 없습니다. +- 헬퍼의 종료 코드는 바뀌지 않습니다. diff --git a/docs/native-output-schema.md b/docs/native-output-schema.md new file mode 100644 index 0000000..7de0f6b --- /dev/null +++ b/docs/native-output-schema.md @@ -0,0 +1,55 @@ +# Native output schema + +[한국어](native-output-schema.ko.md) · [Documentation](README.md) · [Architecture](architecture.md) + +DawnShell's native helpers report results to the app as **JSON Lines**: one JSON object per line, UTF-8. The +writer is the dependency-free `app/src/main/cpp/dawnshell_json.h`; the app decodes lines into typed Kotlin +classes (`NativeEvent.kt`) with kotlinx.serialization. Free-form log lines on stderr (for example +`[epoch] BFU_DEBIAN_STAGE …`) are not part of the schema; the app skips every line that is not a JSON object. + +## Envelope + +```json +{"v":1,"ts":1700000000,"event":"running", "...":"..."} +``` + +| Field | Type | Meaning | +| --- | --- | --- | +| `v` | int | Schema version. Fields may be added within a version; removing or changing one raises it. | +| `ts` | int | Unix time in seconds. | +| `event` | string | Event name, lower snake case. | +| `truncated` | bool, optional | A field did not fit the line buffer and was dropped. | + +Numbers and booleans are native JSON types. A line is always valid JSON and is written with one `write(2)`. +Readers must ignore unknown fields and keep unknown events. + +## `bfu-namespace-probe` events + +| Event | Channel | Fields | +| --- | --- | --- | +| `running`, `starting_or_unknown` | stdout | `state`, `mode`, `supervisor_pid`, `init_host_pid`, `supervisor_identity_valid`, `init_identity_valid`, `namespace_topology_valid`, `cgroup_mode`, `host_usb_mode`, `ns`{`pid`,`mnt`,`uts`,`ipc`,`cgroup`,`net`}, `updated_epoch` | +| `stopped` | stdout | `last_state`, `mode`, `cgroup_mode`, `host_usb_mode`, `wait_status`, `updated_epoch` | +| `started`, `fallback_started` | stdout | `supervisor_pid`, `init_host_pid` or `sshd_pid`, `mode`, `cgroup_mode`, `host_usb_mode`, `host_usb_filter_count` | +| `start_failed` | stdout | `stage`, optional `errno`, `exit`, `child_exit`, `child_signal` | +| `failed` | stderr | `stage`, optional `errno`, `error`; the process exit code is unchanged | +| `health` | stdout | `mode` (`systemd`/`compat`), `healthy`, `pid1`, `system_state`, `dbus_service`, `dbus_bus`, `ssh_service`, `boot_proof_service`, `boot_proof_marker`, `default_target`, `target_state`, `listen_22`, `compat_ready`, `cgroup_mode`, `cgroup_delegation`, `devices_cgroup` | +| `diagnostic` | stdout | `label`, `content` (failed units, sanitized) | +| `namespace_ok`, `compat_ok` | stdout | `arch`, `debian`, plus `pid`, `proc1`, `init`, `systemctl`, `cgroup` or `mode` | +| `namespace_failed`, `compat_failed` | stdout | `stage` | +| `already_running`, `already_stopped`, `orphaned_init`, `orphaned_init_stopped`, `orphaned_instance`, `force_stopped`, `shutdown_test_requested`, `shutdown_test_completed` | stdout | event-specific PIDs and modes; decoded as `OtherEvent` | + +Inside the Debian chroot the health and probe snippets are shell scripts. They print the same objects; string +values are filtered to `[A-Za-z0-9_./:@+=,; -]` so quotes and control characters cannot break the JSON. + +## Status files + +Each `*.status` file is one JSON object, `{"v":1,"ts":…,"state":"SUCCEEDED","summary":"…","detail":{…}}`. +`state` is one of `QUEUED`, `RUNNING`, `SUCCEEDED`, `FAILED`, `REJECTED`, `UNAVAILABLE`, `UNKNOWN`. For lifecycle +operations `detail.events` holds the newest eight native events. A pre-JSON ` STATE text` file is +still read once and replaced on the next write. + +## Compatibility rules + +- Add fields freely; renaming, removing, or retyping a field raises `v`. +- The app and the helpers ship in one APK, so no cross-version negotiation exists. +- Exit codes of the helpers do not change. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b3d44d8..60d8e4e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -19,6 +19,7 @@ kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", versi [libraries] kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinx-serialization" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity" } androidx-navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "androidx-navigation3" } diff --git a/scripts/build-all.sh b/scripts/build-all.sh index 2304096..9ab00f1 100755 --- a/scripts/build-all.sh +++ b/scripts/build-all.sh @@ -34,6 +34,7 @@ fi "$root_dir/scripts/test-host-reboot-isolation.sh" "$root_dir/scripts/test-rootfs-path-resolution.sh" "$root_dir/scripts/test-lifecycle-control-policy.sh" +"$root_dir/scripts/test-native-output.sh" "$root_dir/scripts/test-documentation.sh" "$root_dir/gradlew" -p "$root_dir" \ clean :app:assembleDebug :app:lintDebug :app:testDebugUnitTest diff --git a/scripts/test-compatibility-policy.sh b/scripts/test-compatibility-policy.sh index 71d1ba5..6ba7aeb 100755 --- a/scripts/test-compatibility-policy.sh +++ b/scripts/test-compatibility-policy.sh @@ -192,11 +192,11 @@ grep -Fq 'action=unbind' "$native_launcher" grep -Fq 'action=restore' "$native_launcher" grep -Fq 'kExclusiveUsbScanIntervalMs' "$native_launcher" grep -Fq 'LAUNCH_MODE_COMPAT' "$native_launcher" -grep -Fq 'BFU_DEBIAN_FALLBACK_STARTED' "$native_launcher" -grep -Fq 'BFU_DEBIAN_COMPATIBILITY_OK' "$native_launcher" +grep -Fq '"fallback_started"' "$native_launcher" +grep -Fq 'compat_ok' "$native_launcher" grep -Fq 'fallback=direct_sshd' "$native_launcher" grep -Fq 'validate_compat_namespace_topology' "$native_launcher" -grep -Fq 'compat_ready=%s' "$native_launcher" +grep -Fq 'compat_ready' "$native_launcher" grep -Fq 'read_optional_proc_namespace_inode(pid, "ipc"' "$native_launcher" grep -Fq 'read_optional_proc_namespace_inode(pid, "net"' "$native_launcher" grep -Fq 'state->init_ipc_ns_ino == 0' "$native_launcher" diff --git a/scripts/test-debian-runtime-bfu.sh b/scripts/test-debian-runtime-bfu.sh index 47f6857..91ebb77 100644 --- a/scripts/test-debian-runtime-bfu.sh +++ b/scripts/test-debian-runtime-bfu.sh @@ -57,6 +57,6 @@ printf '%s\n' "$latest_runtime" | grep -Fq ' namespace_chroot=true ' printf '%s\n' "$latest_runtime" | grep -Fq ' user_unlocked_before=false ' printf '%s\n' "$latest_runtime" | grep -Fq ' user_unlocked_after=false ' printf '%s\n' "$latest_runtime" | grep -Fq \ - "BFU_DEBIAN_NAMESPACE_OK pid=1 proc1=sh arch=$debian_arch debian=13" + "\"event\":\"namespace_ok\",\"pid\":1,\"proc1\":\"sh\",\"arch\":\"$debian_arch\",\"debian\":13" echo "PASS: private namespaces, PID-namespace /proc, and Debian chroot worked during BFU." diff --git a/scripts/test-final-bfu.sh b/scripts/test-final-bfu.sh index 4419b1a..728f7cd 100755 --- a/scripts/test-final-bfu.sh +++ b/scripts/test-final-bfu.sh @@ -163,11 +163,11 @@ for ((cycle = 1; cycle <= cycles; cycle++)); do control="/data/user_de/0/me.aroxu.dawnshell/files/bfu/run" launcher_status="$(adb shell su -c \ "$helper status $rootfs $control" | tr -d '\r')" - grep -Fq 'BFU_DEBIAN_RUNNING' <<<"$launcher_status" - grep -Fq 'namespace_topology_valid=true' <<<"$launcher_status" - grep -Fq 'ipc_namespace=android-shared' <<<"$launcher_status" - grep -Fq 'network_namespace=android-shared network_mode=shared-nic' <<<"$launcher_status" - grep -Eq 'cgroup_mode=(v1|v2)' <<<"$launcher_status" + grep -Fq '"event":"running"' <<<"$launcher_status" + grep -Fq '"namespace_topology_valid":true' <<<"$launcher_status" + grep -Fq '"ipc_namespace":"android-shared"' <<<"$launcher_status" + grep -Fq '"network_namespace":"android-shared","network_mode":"shared-nic"' <<<"$launcher_status" + grep -Eq '"cgroup_mode":"(v1|v2)"' <<<"$launcher_status" device_helper_hash="$(adb exec-out run-as me.aroxu.dawnshell cat "$helper" \ | sha256sum | awk '{print toupper($1)}')" [[ "$device_helper_hash" = "$embedded_helper_hash" ]] || { diff --git a/scripts/test-native-output.sh b/scripts/test-native-output.sh new file mode 100755 index 0000000..5c84a27 --- /dev/null +++ b/scripts/test-native-output.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +work_dir="$(mktemp -d)" +trap 'rm -rf -- "$work_dir"' EXIT + +"${CC:-cc}" -std=c17 -Os -Wall -Wextra -Werror -Wformat=2 \ + -I "$repo_dir/app/src/main/cpp" \ + "$repo_dir/app/src/test/cpp/dawnshell_json_test.c" \ + -o "$work_dir/dawnshell_json_test" +"$work_dir/dawnshell_json_test" diff --git a/scripts/test-systemd-shutdown-isolation.sh b/scripts/test-systemd-shutdown-isolation.sh index 6176d85..17d4013 100644 --- a/scripts/test-systemd-shutdown-isolation.sh +++ b/scripts/test-systemd-shutdown-isolation.sh @@ -129,12 +129,12 @@ initial_boot_id="$(android_boot_id)" status_output="$(timeout 20 adb shell su -c \ "$helper status $rootfs $control" | tr -d '\r')" printf '%s\n' "$status_output" -grep -Fq 'BFU_DEBIAN_RUNNING' <<<"$status_output" -grep -Fq 'supervisor_identity_valid=true' <<<"$status_output" -grep -Fq 'init_identity_valid=true' <<<"$status_output" -grep -Fq 'namespace_topology_valid=true' <<<"$status_output" -grep -Fq 'ipc_namespace=android-shared' <<<"$status_output" -grep -Fq 'network_namespace=android-shared network_mode=shared-nic' <<<"$status_output" +grep -Fq '"event":"running"' <<<"$status_output" +grep -Fq '"supervisor_identity_valid":true' <<<"$status_output" +grep -Fq '"init_identity_valid":true' <<<"$status_output" +grep -Fq '"namespace_topology_valid":true' <<<"$status_output" +grep -Fq '"ipc_namespace":"android-shared"' <<<"$status_output" +grep -Fq '"network_namespace":"android-shared","network_mode":"shared-nic"' <<<"$status_output" echo "Testing explicit restart-debian helper..." restart_output="$(timeout 80 adb shell su -c \ @@ -160,12 +160,12 @@ lifecycle_before_stop="$(adb exec-out run-as me.aroxu.dawnshell \ stop_output="$(timeout 45 adb shell su -c \ "$helper stop $rootfs $control" | tr -d '\r')" printf '%s\n' "$stop_output" -grep -Fq 'BFU_DEBIAN_STOPPED' <<<"$stop_output" +grep -Fq '"event":"stopped"' <<<"$stop_output" stopped_status="$(timeout 20 adb shell su -c \ "$helper status $rootfs $control" | tr -d '\r')" printf '%s\n' "$stopped_status" -grep -Fq 'last_state=stopped' <<<"$stopped_status" -grep -Fq 'wait_status=0' <<<"$stopped_status" +grep -Fq '"last_state":"stopped"' <<<"$stopped_status" +grep -Fq '"wait_status":0' <<<"$stopped_status" grep -Fq 'systemd_manager_exit_queued' \ < <(adb exec-out run-as me.aroxu.dawnshell cat "$lifecycle_log" 2>/dev/null \ | tr -d '\r') @@ -224,7 +224,7 @@ for mode in poweroff reboot shutdown; do exit 5 fi - grep -Fq "BFU_DEBIAN_SHUTDOWN_TEST_COMPLETED mode=$mode" <<<"$output" || { + grep -Fq "\"event\":\"shutdown_test_completed\",\"mode\":\"$mode\"" <<<"$output" || { echo "FAIL: helper did not prove the Debian supervisor stopped" >&2 exit 5 } diff --git a/scripts/test-systemd-ssh-bfu.sh b/scripts/test-systemd-ssh-bfu.sh index 63a39e7..0bb994c 100755 --- a/scripts/test-systemd-ssh-bfu.sh +++ b/scripts/test-systemd-ssh-bfu.sh @@ -287,13 +287,13 @@ grep -Fq 'trigger=locked_boot' <<<"$lifecycle_status" grep -Fq 'user_unlocked_before=false' <<<"$lifecycle_status" grep -Fq 'user_unlocked_after=false' <<<"$lifecycle_status" grep -Fq 'health_exit=0' <<<"$lifecycle_status" -grep -Fq 'system_state=running' <<<"$lifecycle_status" -grep -Fq 'dbus_bus=ok' <<<"$lifecycle_status" -grep -Fq 'boot_proof_service=active' <<<"$lifecycle_status" -grep -Fq 'boot_proof_marker=present' <<<"$lifecycle_status" -grep -Fq 'target_state=active' <<<"$lifecycle_status" -grep -Fq 'listen_22=true' <<<"$lifecycle_status" -grep -Fq 'cgroup_delegation=delegated' <<<"$lifecycle_status" +grep -Fq '"system_state":"running"' <<<"$lifecycle_status" +grep -Fq '"dbus_bus":"ok"' <<<"$lifecycle_status" +grep -Fq '"boot_proof_service":"active"' <<<"$lifecycle_status" +grep -Fq '"boot_proof_marker":"present"' <<<"$lifecycle_status" +grep -Fq '"target_state":"active"' <<<"$lifecycle_status" +grep -Fq '"listen_22":true' <<<"$lifecycle_status" +grep -Fq '"cgroup_delegation":"delegated"' <<<"$lifecycle_status" locked_boot_new="$(fresh_log_lines "$locked_boot_log_path" "$locked_boot_before")" printf '%s\n' "$locked_boot_new" @@ -321,9 +321,9 @@ require_one_fresh_record "BFU namespace/chroot probe" \ 'DEBIAN_RUNTIME_PROBE ' "$runtime_new" grep -Fq 'exit=0 timeout=false namespace_chroot=true' <<<"$runtime_new" grep -Fq 'user_unlocked_before=false user_unlocked_after=false' <<<"$runtime_new" -grep -Fq "BFU_DEBIAN_NAMESPACE_OK pid=1 proc1=sh arch=$debian_arch debian=13" \ +grep -Fq "\"event\":\"namespace_ok\",\"pid\":1,\"proc1\":\"sh\",\"arch\":\"$debian_arch\",\"debian\":13" \ <<<"$runtime_new" -grep -Fq 'init=present systemctl=present' <<<"$runtime_new" +grep -Fq '"init":"present","systemctl":"present"' <<<"$runtime_new" operation_all="$(read_boot_de_file "$operation_log_path")" operation_new="$(printf '%s\n' "$operation_all" \