diff --git a/CONTAINER_FIX_SUMMARY.md b/CONTAINER_FIX_SUMMARY.md new file mode 100644 index 0000000..766dbdd --- /dev/null +++ b/CONTAINER_FIX_SUMMARY.md @@ -0,0 +1,121 @@ +# 容器(PRoot + Alpine)问题修复总结 + +> 日期:2026-09-13 +> 真机验证:**OnePlus PLC110 / Android 16 (SDK 36) / arm64-v8a / SELinux Enforcing / 非 root** +> 复现环境:Pixel 8 Pro 模拟器 `emulator-5554` / Android 14 / **x86_64** +> 本文是本次工作的**唯一汇总入口**(根因、修复、实机验收、工具与注意事项);自检工具的用法见 +> `tools/container-selfcheck/README.md`。 + +--- + +## 一、一页结论 + +| # | 问题 | 状态 | 性质 | +|---|---|---|---| +| A | `apk` 报 `temporary error (try again later)` | ✅ 已修复 | **x86_64 模拟器专属**,arm64 真机不存在 | +| B | `apk` 报 `IO ERROR` | ✅ 已修复 | 同 A(`select`) | +| C | `apk add` 报 `Failed to preserve modification time`(硬链接包,如 tzdata) | ✅ 已修复并真机验收 | **跨架构** PRoot 级缺陷 | +| D | `ps` 软链接 `Permission denied` | ⏸ 本轮未复现 | 历史偶发,待观察 | + +**三句话根因** + +1. **A/B(仅 x86_64)**:Android 给应用进程装的 seccomp 策略把传统 `poll(2)`/`select(2)` 返回 **ENOSYS**;x86_64 的系统调用表里有这两个调用而 **musl 的 `poll()` 正是 `#ifdef SYS_poll` 选择它**,且 **musl 的 DNS 解析器在 libc 内部调用 `poll()`(`LD_PRELOAD` 无法插桩)** ⇒ 解析器静默空转到超时 ⇒ `EAI_AGAIN` ⇒ libfetch `FETCH_TEMP` ⇒ `temporary error`。 + **arm64 的系统调用表里根本没有 `poll/select/epoll_wait`**,libc 只能用 `ppoll/pselect6/epoll_pwait`,**无处可封** ⇒ 真机不会出现该问题(这也解释了 Termux 生态"几乎遇不到")。 +2. **C(跨架构)**:Android 不允许应用数据区创建硬链接(实测:去掉 `--link2symlink` 会报 `Failed to create …: Permission denied`),所以 PRoot 用 **symlink + 隐藏记账文件**模拟硬链接;实测替身指向宿主绝对路径 + (`.../Africa/Accra -> /data/data//…/.l2s/.proot.l2s..apk.`),apk 用**跟随符号链接**语义的 `utimensat` 保 mtime ⇒ 落到不可解析的隐藏名字 ⇒ ENOENT ⇒ 包被标记 broken(`f:f`),**此后每次 apk 操作恒定输出 "1 error"**。 +3. **rootfs 本身没问题**:内置的两个 Alpine minirootfs 均与官方 **sha256 逐字节一致** + (x86_64 `d4e6fd67…1efa0c` / aarch64 `041fa34a…f3de`)。 + +--- + +## 二、修复内容(只保留"正确且必要") + +### 1. Shim:`android/app/src/main/cpp/` + +| 覆盖 | 架构 | 原因 | +|---|---|---| +| `utimensat` | **两个 ABI** | C:ENOENT 时带 `AT_SYMLINK_NOFOLLOW` 重试(设置替身自身时间,最接近真实硬链接语义) | +| `poll` / `select` / `pipe` / `dup2` | **仅 x86_64** | A/B:转发到 `ppoll`/`pselect6`/`pipe2`/`dup3`(musl 在有传统调用的架构上优先用它们) | +| `getaddrinfo` / `freeaddrinfo`(`libfix_dns.c`) | **仅 x86_64** | A:用 `ppoll` 自建解析(先查 `/etc/hosts`;并行询问所有 nameserver、单次 5s 等待;不校验应答源地址——与 busybox/c-ares 一致) | + +**删除的冗余/错误归因**:`fork`/`vfork`(musl 本就用 `clone(SIGCHLD)`)、 +`stat`/`lstat`/`fstat`/`fstatat`/`__fstatat`/`*64`(与 musl 自身实现相同)、 +`fstatat` 空路径 workaround(真机实测 `newfstatat(fd,"",st,AT_EMPTY_PATH)=0`,PRoot 正常)、 +arm64 上的 `poll/select/pipe/dup2`(该架构无这些 syscall)。 + +| ABI | 修复前 | 修复后 | 导出符号 | +|---|---|---|---| +| x86_64 | 15824 B / 17 个 | **11112 B** | `poll, select, pipe, dup2, utimensat, getaddrinfo, freeaddrinfo` | +| arm64-v8a | 5512 B / 17 个 | **2936 B** | **仅 `utimensat`** | + +### 2. Dart 侧:`lib/services/` + +| 项目 | 之前 | 现在 | 依据 | +|---|---|---|---| +| rootfs 权限 | 解压后 `chmod -R 755` 一把梭 | 按 **tar 头 mode 分组批量 chmod**(跳过符号链接,避免 chmod 跟随链接改坏目标) | dart:io 无 chmod,但"全部 755"会把 `/etc` 配置也变可执行 | +| guest `/etc/profile` | 安装后重写 | **不再改写** | 实测原版与旧模板**逐行相同** ⇒ 对 Alpine 零影响,同时修掉"破坏 Debian/Ubuntu 登录环境"的缺陷 | +| DNS | `8.8.8.8` 优先、两处不一致 | 统一 **可达优先**:`223.5.5.5 / 119.29.29.29 / 114.114.114.114` | 8.8.8.8/1.1.1.1 境内常丢包,排首位先吃一次超时 | +| `--sysvipc` | (原计划新增) | **不加** | 实测本项目 `libproot.so` 不支持:`unknown option '--sysvipc'`(Termux 是带 `libandroid-shmem` 的 proot fork) | +| `--kernel-release` | `-k 5.4.0-proot` | 保持 | proot-distro 的完整 uname 串是给 Termux fork 版用的 | + +--- + +## 三、实机验收(重新构建 APK → 删除实例 → 全新导入) + +| 验收项 | 结果 | +|---|---| +| `/etc/profile` | ✅ 与官方原版 **sha256 逐字节一致**(`87e8643d…`,547 B)→ 未被改写 | +| 权限恢复 | ✅ `bin/busybox`、`sbin/apk` = 0755;`/etc/passwd`、`/etc/profile` = **0644**(不再是 0755) | +| DNS | ✅ `223.5.5.5 / 119.29.29.29 / 114.114.114.114` | +| shim | ✅ 2936 B(arm64 精简版) | +| `apk update` | ✅ rc=0,3 s,`OK: 24059 distinct packages available`(走**原生** musl 解析器) | +| `apk add tzdata`(硬链接密集) | ✅ `OK: 10 MiB in 15 packages`,文件落地(`Africa/Accra` nlink=14) | +| `apk add tree`(含 busybox 触发器) | ✅ 触发器正常执行,rc=0 | +| broken 标记 / `.apk.*` 残留 | ✅ 无 | +| `pipe` / 子 shell / `sha256sum` | ✅ 正常 | +| syscall 基线 | ✅ `ppoll/pselect6/epoll_pwait/utimensat/clone/fstat/statfs/getrandom/uname` 全 0 | + +`flutter analyze`:**No issues found**。 + +--- + +## 四、为什么 Termux+proot 顺、而本次问题多 + +1. **proot-distro 只是 Python 编排层**(rootfs 组装、sysdata/shm/l2s、bind 校验、session/lock);它不负责 guest libc 与 Android 策略的兼容,也不负责宿主 DNS/`/proc`/seccomp 语义。**抄编排层 ≠ 抄 Termux 的运行环境。** +2. **架构差异**:Termux 用户几乎都在 **arm64 真机**(无 `poll/select` syscall);本次复现环境是 **x86_64 模拟器**(有且被封)。 +3. **上游刻意不做的事我们做了**:注入 `LD_PRELOAD` shim(proot-distro 明确剥离)、改写 guest `/etc/profile`、`chmod -R 755`、硬编码公共 DNS。 +4. **可观测性差距**:真机可 `strace`,proot 内因嵌套 ptrace 不可用(实测 rc=182)⇒ 只能自造裸 syscall 探针,排查更慢。 + +--- + +## 五、工具(已入库) + +`tools/container-selfcheck/`:`probe3.c`(syscall 策略自检,双架构)、`probe4.c`(复现 apk 安装序列)、 +`probe5.c`(空路径 stat)、`selfcheck.sh`(一键验收)、`guest-run.sh`(**免重装 APK** 的 adb 跑手)、 +`README.md`(用法 + 已定位结论表)。 + +**两条铁律** + +1. **不要在容器运行时原地覆盖 `/lib/libfix_seccomp.so`** —— 正在映射该文件的进程会 SIGSEGV + (实测:`proot info: vpid 1: terminated with signal 11`)。必须「写临时文件 → `mv` 重命名」。 +2. **换 shim 后需新起进程才生效**(`am force-stop` 重启 App,或新开一个会话)。 + +--- + +## 六、已知但未处理(均无功能影响) + +| 现象 | 说明 | +|---|---| +| `openat(dir, O_RDONLY\|O_DIRECTORY)` → **EINVAL** | 本项目 proot 的怪癖(`O_PATH\|O_DIRECTORY` 正常,x86_64 上同调用成功);当前无功能影响 | +| `.proot-meta-file.*` / `.l2s` 残留 | `--link2symlink` 机制的固有产物,已不再导致安装失败 | +| `unshare(CLONE_NEWNS)` EPERM / `chroot` ENOENT | 应用进程预期行为,apk 脚本执行不受影响 | +| `/proc` 为宿主共享 | 容器内 `ps` 可见宿主 App 进程(信息隔离偏弱,非缺陷) | +| 多发行版 | guest `/etc/profile` 不再被改写后,Debian/Ubuntu 等可保留自身登录环境 | + +--- + +## 七、运维注意 + +- **验收基准用 arm64 真机**;模拟器只用于 UI 迭代。 +- **MIUI 设备**(如 Redmi K60)`adb install` 会被拦(`INSTALL_FAILED_USER_RESTRICTED`),需手动安装或开启开发者选项里的「USB 安装」;OnePlus / 原生 Android 无此限制。 +- 若将来需要 `--sysvipc`/完整 uname 伪装,必须改用 Termux 的 proot fork(`github.com/termux/proot`,带 `PROOT_WITH_LIBANDROID_SHMEM`)重新编译。 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 26737eb..dcae4d3 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -8,7 +8,7 @@ plugins { android { namespace = "com.example.code_editor" compileSdk = flutter.compileSdkVersion - ndkVersion = flutter.ndkVersion + ndkVersion = "28.2.13676358" compileOptions { sourceCompatibility = JavaVersion.VERSION_11 @@ -25,7 +25,7 @@ android { // You can update the following values to match your application needs. // For more information, see: https://flutter.dev/to/review-gradle-config. minSdk = flutter.minSdkVersion - targetSdk = flutter.targetSdkVersion + targetSdk = 28 versionCode = flutter.versionCode versionName = flutter.versionName } @@ -37,6 +37,12 @@ android { signingConfig = signingConfigs.getByName("debug") } } + + packaging { + jniLibs { + useLegacyPackaging = true + } + } } flutter { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index de7caf2..969e2f7 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -6,11 +6,15 @@ + + + + android:requestLegacyExternalStorage="true" + android:extractNativeLibs="true"> = 'A' && c <= 'Z') ? c + 32 : c; } + +static int name_eq(const char *a, const char *b) +{ + while (*a && *b) { + if (lower(*a) != lower(*b)) return 0; + a++; + b++; + } + return *a == *b; +} + +static void *xalloc(size_t n) +{ + long r = sc6(SYS_mmap, 0, (long)n, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (r < 0 && r > -4096) return 0; + return (void *)r; +} + +static void xfree(void *p, size_t n) +{ + if (p) sc6(SYS_munmap, (long)p, (long)n, 0, 0, 0, 0); +} + +static int read_file(const char *path, char *buf, size_t max) +{ + long fd = sc6(SYS_openat, AT_FDCWD, (long)path, O_RDONLY, 0, 0, 0); + size_t total = 0; + if (fd < 0) return -1; + for (;;) { + long r = sc6(SYS_read, fd, (long)(buf + total), (long)(max - 1 - total), 0, 0, 0); + if (r <= 0) break; + total += (size_t)r; + if (total >= max - 1) break; + } + sc6(SYS_close, fd, 0, 0, 0, 0, 0); + buf[total] = 0; + return (int)total; +} + +/* next whitespace-delimited token of *p; advances *p; returns its length */ +static int next_token(const char **p, char *out, int max) +{ + const char *s = *p; + int n = 0; + while (*s == ' ' || *s == '\t') s++; + while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != '#') { + if (n < max - 1) out[n++] = *s; + s++; + } + out[n] = 0; + *p = s; + return n; +} + +/* parse a dotted-quad IPv4 address; returns 1 on success, network order out */ +static int parse_ipv4(const char *s, u32 *out) +{ + u32 v = 0; + int k; + const char *q = s; + for (k = 0; k < 4; k++) { + int d = 0, nd = 0; + while (*q >= '0' && *q <= '9' && nd < 4) { d = d * 10 + (*q - '0'); q++; nd++; } + if (nd == 0 || d > 255) return 0; + v = (v << 8) | (u32)d; + if (k < 3) { + if (*q != '.') return 0; + q++; + } + } + if (*q) return 0; + *out = v; + return 1; +} + +/* ------------------------------------------------------------- /etc/hosts */ + +static int hosts_lookup(const char *name, u32 *v4, int v4max) +{ + static char buf[16384]; + int len = read_file("/etc/hosts", buf, sizeof buf); + int n4 = 0, i = 0; + + if (len <= 0) return -1; + while (i < len) { + char line[512], addr[128], nm[256]; + const char *p; + int li = 0; + u32 a4; + + while (i < len && buf[i] != '\n') { + if (li < (int)sizeof(line) - 1) line[li++] = buf[i]; + i++; + } + i++; + line[li] = 0; + + p = line; + if (next_token(&p, addr, sizeof addr) == 0) continue; + if (!parse_ipv4(addr, &a4)) continue; /* IPv6 entries are ignored */ + for (;;) { + if (next_token(&p, nm, sizeof nm) == 0) break; + if (name_eq(nm, name) && n4 < v4max) v4[n4++] = a4; + } + } + return n4 ? n4 : -1; +} + +/* ------------------------------------------------------- /etc/resolv.conf */ + +static int resolv_nameservers(u32 *ns, int max) +{ + static char buf[4096]; + int len = read_file("/etc/resolv.conf", buf, sizeof buf); + int n = 0, i = 0; + static const char kw[] = "nameserver"; + + if (len <= 0) return 0; + while (i < len && n < max) { + char line[256], ip[64]; + const char *p; + int li = 0, k; + u32 a4; + + while (i < len && buf[i] != '\n') { + if (li < (int)sizeof(line) - 1) line[li++] = buf[i]; + i++; + } + i++; + line[li] = 0; + + for (k = 0; k < 10; k++) + if (line[k] != kw[k]) break; + if (k != 10) continue; + if (line[10] != ' ' && line[10] != '\t') continue; + + p = line + 10; + if (next_token(&p, ip, sizeof ip) == 0) continue; + if (parse_ipv4(ip, &a4)) ns[n++] = a4; + } + return n; +} + +/* ---------------------------------------------------------------- DNS wire */ + +#define QID_HI 0x4c +#define QID_LO 0x37 + +static int build_query(unsigned char *q, int max, const char *name, int qtype) +{ + int n = 12; + + my_memset(q, 0, 12); + q[0] = QID_HI; + q[1] = QID_LO; + q[2] = 0x01; /* RD */ + q[5] = 1; /* QDCOUNT = 1 */ + + while (*name) { + const char *dot = name; + int l; + while (*dot && *dot != '.') dot++; + l = (int)(dot - name); + if (l <= 0 || l > 63 || n + l + 1 > max - 4) return -1; + q[n++] = (unsigned char)l; + my_memcpy(q + n, name, (size_t)l); + n += l; + name = (*dot == '.') ? dot + 1 : dot; + } + q[n++] = 0; + q[n++] = (unsigned char)(qtype >> 8); + q[n++] = (unsigned char)(qtype & 0xff); + q[n++] = 0; + q[n++] = 1; /* IN */ + return n; +} + +static int skip_dns_name(const unsigned char *m, int len, int off) +{ + while (off < len) { + unsigned char c = m[off]; + if (c == 0) return off + 1; + if ((c & 0xc0) == 0xc0) return off + 2; + off += 1 + c; + } + return -1; +} + +static void parse_answers(const unsigned char *m, int len, + u32 *out4, int *n4, unsigned char (*out6)[16], int *n6) +{ + int i = 12; + int qd = (m[4] << 8) | m[5]; + int an = (m[6] << 8) | m[7]; + + while (qd-- > 0) { + i = skip_dns_name(m, len, i); + if (i < 0 || i + 4 > len) return; + i += 4; + } + while (an-- > 0) { + int type, rdlen; + i = skip_dns_name(m, len, i); + if (i < 0 || i + 10 > len) return; + type = (m[i] << 8) | m[i + 1]; + rdlen = (m[i + 8] << 8) | m[i + 9]; + i += 10; + if (i + rdlen > len) return; + if (type == 1 && rdlen == 4 && *n4 < 16) { + my_memcpy(&out4[*n4], m + i, 4); + (*n4)++; + } else if (type == 28 && rdlen == 16 && *n6 < 16) { + my_memcpy(out6[*n6], m + i, 16); + (*n6)++; + } + i += rdlen; + } +} + +/* + * Ask every configured nameserver at once (as musl does) and take the first + * reply that carries our query id. The reply's source address is *not* + * checked on purpose. + */ +static int dns_query(const char *name, int qtype, int timeout_ms, + u32 *out4, int *n4, unsigned char (*out6)[16], int *n6) +{ + unsigned char q[512], rbuf[2048]; + struct sockaddr_in to; + struct pollfd pfd; + struct timespec ts; + u32 ns[3]; + int nns, i, qlen; + long fd, r; + + qlen = build_query(q, (int)sizeof q, name, qtype); + if (qlen < 0) return -1; + + nns = resolv_nameservers(ns, 3); + if (nns == 0) { + ns[0] = 0x08080808; /* 8.8.8.8 */ + ns[1] = 0x01010101; /* 1.1.1.1 */ + nns = 2; + } + + fd = sc6(SYS_socket, AF_INET, SOCK_DGRAM, 0, 0, 0, 0); + if (fd < 0) return -1; + + my_memset(&to, 0, sizeof to); + to.sin_family = AF_INET; + to.sin_port = 0x3500; /* port 53, network order */ + for (i = 0; i < nns; i++) { + to.sin_addr.s_addr = ns[i]; /* already network order */ + sc6(SYS_sendto, fd, (long)q, qlen, 0, (long)&to, sizeof to); + } + + pfd.fd = (int)fd; + pfd.events = POLLIN; + pfd.revents = 0; + ts.tv_sec = timeout_ms / 1000; + ts.tv_nsec = (long)(timeout_ms % 1000) * 1000000L; + + r = sc6(SYS_ppoll, (long)&pfd, 1, (long)&ts, 0, 0, 0); + if (r > 0) { + r = sc6(SYS_recvfrom, fd, (long)rbuf, (long)sizeof rbuf, 0, 0, 0); + if (r >= 12 && (rbuf[2] & 0x80) && rbuf[0] == QID_HI && rbuf[1] == QID_LO) + parse_answers(rbuf, (int)r, out4, n4, out6, n6); + } + sc6(SYS_close, fd, 0, 0, 0, 0, 0); + return (*n4 || *n6) ? 0 : -1; +} + +/* ------------------------------------------------------------ service/port */ + +static unsigned short service_port(const char *svc, int *ok) +{ + static const struct { const char *n; unsigned short p; } tab[] = { + { "http", 80 }, { "https", 443 }, { "ftp", 21 }, { "ssh", 22 }, + { "smtp", 25 }, { "domain", 53 }, { "pop3", 110 }, { "imap", 143 }, + { "ntp", 123 }, { "git", 9418 }, + }; + unsigned short port; + unsigned char *b; + unsigned long v = 0; + const char *p = svc; + int i; + + if (!svc || !*svc) { *ok = 1; return 0; } + if (*p >= '0' && *p <= '9') { + while (*p >= '0' && *p <= '9') { v = v * 10 + (unsigned long)(*p - '0'); p++; } + if (*p || v > 65535) { *ok = 0; return 0; } + port = (unsigned short)v; + } else { + for (i = 0; i < (int)(sizeof tab / sizeof tab[0]); i++) + if (name_eq(tab[i].n, svc)) break; + if (i == (int)(sizeof tab / sizeof tab[0])) { *ok = 0; return 0; } + port = tab[i].p; + } + b = (unsigned char *)&port; + *ok = 1; + return (unsigned short)((b[0] << 8) | b[1]); /* to network order */ +} + +static struct addrinfo *mk_ai(int family, const unsigned char *addr, + unsigned short port_be, int socktype, int protocol) +{ + size_t alen = (family == AF_INET6) ? sizeof(struct sockaddr_in6) + : sizeof(struct sockaddr_in); + size_t sz = sizeof(struct addrinfo) + alen; + struct addrinfo *ai = xalloc(sz); + + if (!ai) return 0; + my_memset(ai, 0, sz); + ai->ai_family = family; + ai->ai_socktype = socktype ? socktype : SOCK_STREAM; + ai->ai_protocol = protocol; + ai->ai_addrlen = (unsigned int)alen; + ai->ai_addr = (struct sockaddr *)(ai + 1); + if (family == AF_INET6) { + struct sockaddr_in6 *s = (struct sockaddr_in6 *)ai->ai_addr; + s->sin6_family = AF_INET6; + s->sin6_port = port_be; + my_memcpy(s->sin6_addr.s6_addr, addr, 16); + } else { + struct sockaddr_in *s = (struct sockaddr_in *)ai->ai_addr; + s->sin_family = AF_INET; + s->sin_port = port_be; + my_memcpy(&s->sin_addr, addr, 4); + } + return ai; +} + +/* ------------------------------------------------------------ entry points */ + +__attribute__((visibility("default"))) +int getaddrinfo(const char *node, const char *service, + const struct addrinfo *hints, struct addrinfo **res) +{ + int family = AF_UNSPEC, socktype = 0, protocol = 0, flags = 0; + unsigned short port_be; + int ok = 0, i; + u32 v4[16]; + int n4 = 0; + unsigned char v6[16][16]; + int n6 = 0; + struct addrinfo *head = 0, *tail = 0; + + if (hints) { + family = hints->ai_family; + socktype = hints->ai_socktype; + protocol = hints->ai_protocol; + flags = hints->ai_flags; + } + if (!res) return EAI_FAIL; + *res = 0; + + port_be = service_port(service, &ok); + if (!ok) return EAI_SERVICE; + + /* no name: wildcard (AI_PASSIVE) or loopback */ + if (!node || !*node) { + unsigned char any4[4] = { 0, 0, 0, 0 }; + unsigned char lo4[4] = { 127, 0, 0, 1 }; + const unsigned char *a = (flags & AI_PASSIVE) ? any4 : lo4; + if (family == AF_INET6) { + unsigned char any6[16]; + my_memset(any6, 0, 16); + if (!(flags & AI_PASSIVE)) any6[15] = 1; + head = mk_ai(AF_INET6, any6, port_be, socktype, protocol); + } else { + head = mk_ai(AF_INET, a, port_be, socktype, protocol); + } + if (!head) return EAI_MEMORY; + *res = head; + return 0; + } + + /* numeric IPv4 literal first */ + { + u32 a4; + if (parse_ipv4(node, &a4)) { + unsigned char b[4]; + if (family == AF_INET6) return EAI_NONAME; + b[0] = (unsigned char)(a4 & 0xff); + b[1] = (unsigned char)((a4 >> 8) & 0xff); + b[2] = (unsigned char)((a4 >> 16) & 0xff); + b[3] = (unsigned char)((a4 >> 24) & 0xff); + head = mk_ai(AF_INET, b, port_be, socktype, protocol); + if (!head) return EAI_MEMORY; + *res = head; + return 0; + } + if (flags & AI_NUMERICHOST) return EAI_NONAME; + } + + if (hosts_lookup(node, v4, 16) < 0) { + if (family == AF_UNSPEC || family == AF_INET) + dns_query(node, 1, 5000, v4, &n4, v6, &n6); + if (family == AF_UNSPEC || family == AF_INET6) + dns_query(node, 28, 5000, v4, &n4, v6, &n6); + } + + if (family == AF_UNSPEC || family == AF_INET) { + for (i = 0; i < n4; i++) { + struct addrinfo *ai = mk_ai(AF_INET, (unsigned char *)&v4[i], + port_be, socktype, protocol); + if (!ai) break; + if (!head) head = ai; else tail->ai_next = ai; + tail = ai; + } + } + if (family == AF_UNSPEC || family == AF_INET6) { + for (i = 0; i < n6; i++) { + struct addrinfo *ai = mk_ai(AF_INET6, v6[i], port_be, socktype, protocol); + if (!ai) break; + if (!head) head = ai; else tail->ai_next = ai; + tail = ai; + } + } + + if (!head) return EAI_NONAME; + *res = head; + return 0; +} + +__attribute__((visibility("default"))) +void freeaddrinfo(struct addrinfo *ai) +{ + while (ai) { + struct addrinfo *next = ai->ai_next; + size_t alen = (ai->ai_family == AF_INET6) ? sizeof(struct sockaddr_in6) + : sizeof(struct sockaddr_in); + xfree(ai, sizeof(struct addrinfo) + alen); + ai = next; + } +} + +#endif /* __x86_64__ */ diff --git a/android/app/src/main/cpp/libfix_seccomp.c b/android/app/src/main/cpp/libfix_seccomp.c new file mode 100644 index 0000000..588e46d --- /dev/null +++ b/android/app/src/main/cpp/libfix_seccomp.c @@ -0,0 +1,317 @@ +/* + * libfix_seccomp.c - LD_PRELOAD shim for a PRoot container running inside an + * Android *application* process. + * + * Everything here was proved by measurement on device (OnePlus PLC110 / + * Android 16 / arm64) and on the x86_64 emulator; see + * APK_TEMPORARY_ERROR_FIX_PLAN.md for the raw evidence. + * + * WHAT IS HERE, AND WHY + * --------------------- + * 1. utimensat() - BOTH architectures + * Android refuses link(2) on app data (measured: dropping --link2symlink + * makes apk fail with "Failed to create ...: Permission denied"), so PRoot + * emulates hard links as symlink + hidden bookkeeping entry + * (".proot-meta-file.", PROOT_L2S_DIR). Resolving *through* such an + * entry is refused, so a following utimensat() - exactly what apk calls to + * "preserve modification time" on a freshly extracted file - returns ENOENT + * and the package is marked broken: + * + * ERROR: Failed to preserve modification time on usr/share/zoneinfo/Africa/.apk.: No such file or directory + * + * Retrying with AT_SYMLINK_NOFOLLOW stamps the entry itself, which is the + * closest available approximation of hardlink semantics. + * + * 2. poll / select / pipe / dup2 - x86_64 ONLY + * Android's app seccomp policy answers the legacy spelling of these calls + * with ENOSYS (bionic itself uses ppoll/pselect6/pipe2/dup3), and musl + * prefers the legacy spelling whenever the architecture has it: + * poll()/select() are literal #ifdef SYS_poll / SYS_select choices, pipe() + * and dup2() likewise. Forwarding them to the modern syscall fixes it. + * Measured ENOSYS on x86_64 for poll and select; pipe/dup2 belong to the + * same legacy family and are kept for the same reason. + * arm64 has none of these syscalls in its (asm-generic) table, so libc + * never issues them and nothing is overridden there. + * + * WHAT WAS DELIBERATELY REMOVED (it was a no-op or based on a wrong guess) + * ---------------------------------------------------------------------- + * fork / vfork - musl already implements both with clone(SIGCHLD); + * the override duplicated it (and replaced vfork with + * fork, losing the optimised path for nothing). + * stat / lstat / - identical to what musl issues itself (musl's stat + * fstat / fstatat family *is* the newfstatat/fstat syscall pair), so + * *64 variants these only cost an indirection. + * fstatat("" ...) - the old "PRoot returns EINVAL for an empty path" + * workaround: measured on device, AT_EMPTY_PATH works + * (`newfstatat(fd,"",st,AT_EMPTY_PATH) = 0`), and the + * ENOENT for an empty path *without* that flag is the + * kernel's correct behaviour, not a PRoot bug. + */ + +#define _GNU_SOURCE + +typedef long ssize_t; +typedef unsigned long size_t; +typedef int pid_t; +typedef unsigned long nfds_t; + +struct pollfd { + int fd; + short events; + short revents; +}; + +struct timespec { + long tv_sec; + long tv_nsec; +}; + +struct timeval { + long tv_sec; + long tv_usec; +}; + +extern int *__errno_location(void) __attribute__((weak)); + +#if defined(__x86_64__) + +static inline long my_syscall2(long n, long a1, long a2) { + long ret; + __asm__ __volatile__ ("syscall" + : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2) + : "rcx", "r11", "memory" + ); + return ret; +} + +static inline long my_syscall3(long n, long a1, long a2, long a3) { + long ret; + __asm__ __volatile__ ("syscall" + : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3) + : "rcx", "r11", "memory" + ); + return ret; +} + +static inline long my_syscall4(long n, long a1, long a2, long a3, long a4) { + long ret; + register long r10 __asm__("r10") = a4; + __asm__ __volatile__ ("syscall" + : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10) + : "rcx", "r11", "memory" + ); + return ret; +} + +static inline long my_syscall6(long n, long a1, long a2, long a3, long a4, long a5, long a6) { + long ret; + register long r10 __asm__("r10") = a4; + register long r8 __asm__("r8") = a5; + register long r9 __asm__("r9") = a6; + __asm__ __volatile__ ("syscall" + : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory" + ); + return ret; +} + +#define SYS_utimensat 280 +#define SYS_ppoll 271 +#define SYS_pipe2 293 +#define SYS_dup3 292 + +#elif defined(__aarch64__) + +static inline long my_syscall2(long n, long a1, long a2) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0") = a1; + register long x1 __asm__("x1") = a2; + __asm__ __volatile__ ("svc #0" : "+r"(x0) : "r"(x8), "r"(x1) : "memory"); + return x0; +} + +static inline long my_syscall3(long n, long a1, long a2, long a3) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0") = a1; + register long x1 __asm__("x1") = a2; + register long x2 __asm__("x2") = a3; + __asm__ __volatile__ ("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2) : "memory"); + return x0; +} + +static inline long my_syscall6(long n, long a1, long a2, long a3, long a4, long a5, long a6) { + register long x8 __asm__("x8") = n; + register long x0 __asm__("x0") = a1; + register long x1 __asm__("x1") = a2; + register long x2 __asm__("x2") = a3; + register long x3 __asm__("x3") = a4; + register long x4 __asm__("x4") = a5; + register long x5 __asm__("x5") = a6; + __asm__ __volatile__ ("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} + +#define SYS_utimensat 88 +#define SYS_ppoll 73 + +#endif + +#define AT_SYMLINK_NOFOLLOW 0x100 +#define ENOENT 2 + +static inline int set_errno_and_return(long ret) { + if (ret < 0) { + if (__errno_location) { + *__errno_location() = (int)(-ret); + } + return -1; + } + return (int)ret; +} + +/* ------------------------------------------------------------------------- + * utimensat(): survive PRoot's --link2symlink hardlink stand-ins. + * ------------------------------------------------------------------------- */ +__attribute__((visibility("default"))) +int utimensat(int dirfd, const char *path, const void *times, int flags) { + long ret = my_syscall6(SYS_utimensat, (long)dirfd, (long)path, + (long)times, (long)flags, 0, 0); + if (ret == -ENOENT && path != 0 && path[0] != '\0' && + (flags & AT_SYMLINK_NOFOLLOW) == 0) { + long retry = my_syscall6(SYS_utimensat, (long)dirfd, (long)path, + (long)times, + (long)(flags | AT_SYMLINK_NOFOLLOW), 0, 0); + if (retry >= 0) { + return 0; + } + } + return set_errno_and_return(ret); +} + +#if defined(__x86_64__) + +/* ------------------------------------------------------------------------- + * Legacy wait/descriptor syscalls that only x86_64 still has. + * ------------------------------------------------------------------------- */ +#define POLLIN_L 0x001 +#define POLLPRI_L 0x002 +#define POLLOUT_L 0x004 +#define POLLERR_L 0x008 +#define POLLHUP_L 0x010 +#define FD_SETSIZE_L 1024 +#define F_GETFL_L 3 + +typedef unsigned long fd_mask_l; + +__attribute__((visibility("default"))) +int poll(struct pollfd *fds, nfds_t nfds, int timeout) { + struct timespec ts; + struct timespec *pts = (struct timespec *)0; + if (timeout >= 0) { + ts.tv_sec = timeout / 1000; + ts.tv_nsec = (long)(timeout % 1000) * 1000000L; + pts = &ts; + } + long ret = my_syscall6(SYS_ppoll, (long)fds, (long)nfds, (long)pts, 0, 0, 0); + return set_errno_and_return(ret); +} + +static int fd_is_set(fd_mask_l *set, int fd) { + return (set[fd / (8 * (int)sizeof(fd_mask_l))] >> + (fd % (8 * (int)sizeof(fd_mask_l)))) & 1UL; +} + +static void fd_set_bit(fd_mask_l *set, int fd) { + set[fd / (8 * (int)sizeof(fd_mask_l))] |= 1UL << (fd % (8 * (int)sizeof(fd_mask_l))); +} + +static void fd_zero_bits(fd_mask_l *set, int nfds) { + int words = (nfds + (int)(8 * sizeof(fd_mask_l)) - 1) / (int)(8 * sizeof(fd_mask_l)); + int i; + for (i = 0; i < words; i++) set[i] = 0; +} + +/* select() on top of ppoll(): musl issues the legacy select(2) syscall here, + * which an app process may not use. libfetch (apk's downloader) calls + * select() to wait for a writable socket and, on failure, returns an error + * without recording an error code - which apk reports as "IO ERROR". */ +__attribute__((visibility("default"))) +int select(int nfds, fd_mask_l *readfds, fd_mask_l *writefds, + fd_mask_l *exceptfds, void *timeout) { + struct pollfd pfds[FD_SETSIZE_L]; + struct timespec ts; + struct timespec *tsp = (struct timespec *)0; + struct timeval *tv = (struct timeval *)timeout; + int n = 0, i, ready = 0; + long ret; + + if (nfds < 0 || nfds > FD_SETSIZE_L) { + if (__errno_location) *__errno_location() = 22 /* EINVAL */; + return -1; + } + if (tv) { + if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000L) { + if (__errno_location) *__errno_location() = 22; + return -1; + } + ts.tv_sec = tv->tv_sec; + ts.tv_nsec = tv->tv_usec * 1000L; + tsp = &ts; + } + + for (i = 0; i < nfds; i++) { + short ev = 0; + if (readfds && fd_is_set(readfds, i)) ev |= POLLIN_L; + if (writefds && fd_is_set(writefds, i)) ev |= POLLOUT_L; + if (exceptfds && fd_is_set(exceptfds, i)) ev |= POLLPRI_L; + if (!ev) continue; + pfds[n].fd = i; + pfds[n].events = ev; + pfds[n].revents = 0; + n++; + } + + ret = my_syscall6(SYS_ppoll, (long)pfds, (long)n, (long)tsp, 0, 0, 0); + if (ret < 0) { + if (__errno_location) *__errno_location() = (int)(-ret); + return -1; + } + + if (readfds) fd_zero_bits(readfds, nfds); + if (writefds) fd_zero_bits(writefds, nfds); + if (exceptfds) fd_zero_bits(exceptfds, nfds); + + for (i = 0; i < n; i++) { + short re = pfds[i].revents; + if (!re) continue; + ready++; + if (readfds && (re & (POLLIN_L | POLLHUP_L | POLLERR_L))) fd_set_bit(readfds, pfds[i].fd); + if (writefds && (re & (POLLOUT_L | POLLHUP_L | POLLERR_L))) fd_set_bit(writefds, pfds[i].fd); + if (exceptfds && (re & POLLPRI_L)) fd_set_bit(exceptfds, pfds[i].fd); + } + return ready; +} + +__attribute__((visibility("default"))) +int pipe(int pipefd[2]) { + long ret = my_syscall2(SYS_pipe2, (long)pipefd, 0); + return set_errno_and_return(ret); +} + +__attribute__((visibility("default"))) +int dup2(int oldfd, int newfd) { + if (oldfd == newfd) { + long ret = my_syscall3(72 /* fcntl */, (long)oldfd, (long)F_GETFL_L, 0); + if (ret < 0) return set_errno_and_return(ret); + return oldfd; + } + long ret = my_syscall3(SYS_dup3, (long)oldfd, (long)newfd, 0); + return set_errno_and_return(ret); +} + +#endif /* __x86_64__ */ diff --git a/android/app/src/main/jniLibs/arm64-v8a/libproot.so b/android/app/src/main/jniLibs/arm64-v8a/libproot.so new file mode 100644 index 0000000..841554c Binary files /dev/null and b/android/app/src/main/jniLibs/arm64-v8a/libproot.so differ diff --git a/android/app/src/main/jniLibs/arm64-v8a/libtalloc.so b/android/app/src/main/jniLibs/arm64-v8a/libtalloc.so new file mode 100644 index 0000000..0728cbb Binary files /dev/null and b/android/app/src/main/jniLibs/arm64-v8a/libtalloc.so differ diff --git a/android/app/src/main/jniLibs/x86_64/libproot.so b/android/app/src/main/jniLibs/x86_64/libproot.so new file mode 100644 index 0000000..3e5e390 Binary files /dev/null and b/android/app/src/main/jniLibs/x86_64/libproot.so differ diff --git a/android/app/src/main/jniLibs/x86_64/libtalloc.so b/android/app/src/main/jniLibs/x86_64/libtalloc.so new file mode 100644 index 0000000..03f9b39 Binary files /dev/null and b/android/app/src/main/jniLibs/x86_64/libtalloc.so differ diff --git a/android/app/src/main/kotlin/com/example/code_editor/MainActivity.kt b/android/app/src/main/kotlin/com/example/code_editor/MainActivity.kt index 72d3316..59c1c7f 100644 --- a/android/app/src/main/kotlin/com/example/code_editor/MainActivity.kt +++ b/android/app/src/main/kotlin/com/example/code_editor/MainActivity.kt @@ -1,5 +1,21 @@ package com.example.code_editor import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel -class MainActivity : FlutterActivity() +class MainActivity : FlutterActivity() { + private val CHANNEL = "com.example.code_editor/native" + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> + when (call.method) { + "getNativeLibraryDir" -> { + result.success(applicationInfo.nativeLibraryDir) + } + else -> result.notImplemented() + } + } + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts index f48cccb..f30646f 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -21,6 +21,11 @@ subprojects { } subprojects { project.evaluationDependsOn(":app") + plugins.withId("com.android.library") { + configure { + ndkVersion = "28.2.13676358" + } + } } tasks.register("clean") { diff --git a/assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz b/assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz new file mode 100644 index 0000000..61208a1 Binary files /dev/null and b/assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz differ diff --git a/assets/shims/arm64-v8a/libfix_seccomp.so b/assets/shims/arm64-v8a/libfix_seccomp.so new file mode 100644 index 0000000..437bb37 Binary files /dev/null and b/assets/shims/arm64-v8a/libfix_seccomp.so differ diff --git a/assets/shims/x86_64/libfix_seccomp.so b/assets/shims/x86_64/libfix_seccomp.so new file mode 100644 index 0000000..5130ad0 Binary files /dev/null and b/assets/shims/x86_64/libfix_seccomp.so differ diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 335c4e5..e28f23b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -121,5 +121,123 @@ "keepLocal": "Keep Local Changes", "storagePermissionRequiredTitle": "Storage Access Required", "storagePermissionRequiredMessage": "Code Editor requires \"All files access\" permission to read, create, and save project files on your device.\n\nPlease enable it in the system settings page.", - "goToSettings": "Settings" + "goToSettings": "Settings", + "terminal": "Terminal", + "terminalWithSystem": "Terminal · {system}", + "@terminalWithSystem": { + "placeholders": { + "system": { + "type": "String" + } + } + }, + "sessionDefaultName": "Session", + "systemManagement": "System Management", + "systemManagementTooltip": "System Management & Selection", + "sessionListTooltip": "Session List", + "noActiveSessions": "No active sessions", + "terminalInputHint": "Enter command...", + "sendCommandTooltip": "Send Command", + "importNewSystem": "Import New System", + "importBuiltinAlpine": "Import from App (Alpine)", + "importExternalTarGz": "Import from External (.tar.gz)", + "selectSystemDefaultPrompt": "Select a system as default; new terminals will start in this system:", + "noSystemsPrompt": "No systems available. Tap \"+\" at top right to import", + "importBuiltinAlpineTitle": "Import Built-in Alpine System", + "systemNameHintWithDefault": "System name (e.g. {name})", + "@systemNameHintWithDefault": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "systemImportSuccess": "System \"{name}\" imported and ready", + "@systemImportSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "importExternalSystemTitle": "Import External System", + "systemNameHint": "System Name", + "externalSystemImportSuccess": "External system \"{name}\" imported and ready", + "@externalSystemImportSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "deleteSystemConfirmTitle": "High-Risk Operation: Delete System", + "deleteSystemConfirmMessage": "Are you sure you want to permanently delete system \"{name}\"?\n\n⚠️ This will physically erase all internal data and installed packages. This cannot be undone!\n\nAll associated terminal sessions will also be closed.", + "@deleteSystemConfirmMessage": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "permanentDelete": "Permanently Delete", + "deleteSystemSuccess": "System \"{name}\" and associated sessions deleted", + "@deleteSystemSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "deleteSystemTooltip": "Permanently delete this system (High risk)", + "preparingInitialization": "Preparing initialization...", + "cancellingAndCleaning": "Cancelling and cleaning leftover directory...", + "cancelledImportSystem": "Cancelled importing system \"{name}\"", + "@cancelledImportSystem": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "importFailed": "Import failed: {error}", + "@importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "importingSystemTitle": "Importing: {name}", + "@importingSystemTitle": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "cancelImport": "Cancel Import", + "interrupting": "Interrupting...", + "sessionDrawerTitle": "Sessions", + "addTerminalTooltip": "Add Terminal", + "noSystemSelectedWarning": "No system selected. Please import or select a system first.", + "noSessionsInDrawerPrompt": "No sessions. Tap top right to add", + "confirmDeleteTerminalSession": "Are you sure you want to delete terminal \"({index}) {name}\"?", + "@confirmDeleteTerminalSession": { + "placeholders": { + "index": { + "type": "int" + }, + "name": { + "type": "String" + } + } + }, + "deleteSystemFailed": "Failed to delete system: {error}", + "@deleteSystemFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 33e4c8c..1f15413 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -781,6 +781,234 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'去设置'** String get goToSettings; + + /// No description provided for @terminal. + /// + /// In zh, this message translates to: + /// **'终端'** + String get terminal; + + /// No description provided for @terminalWithSystem. + /// + /// In zh, this message translates to: + /// **'终端 · {system}'** + String terminalWithSystem(String system); + + /// No description provided for @sessionDefaultName. + /// + /// In zh, this message translates to: + /// **'会话'** + String get sessionDefaultName; + + /// No description provided for @systemManagement. + /// + /// In zh, this message translates to: + /// **'系统管理'** + String get systemManagement; + + /// No description provided for @systemManagementTooltip. + /// + /// In zh, this message translates to: + /// **'系统管理与选择'** + String get systemManagementTooltip; + + /// No description provided for @sessionListTooltip. + /// + /// In zh, this message translates to: + /// **'会话列表'** + String get sessionListTooltip; + + /// No description provided for @noActiveSessions. + /// + /// In zh, this message translates to: + /// **'暂无活跃会话'** + String get noActiveSessions; + + /// No description provided for @terminalInputHint. + /// + /// In zh, this message translates to: + /// **'输入命令...'** + String get terminalInputHint; + + /// No description provided for @sendCommandTooltip. + /// + /// In zh, this message translates to: + /// **'发送命令'** + String get sendCommandTooltip; + + /// No description provided for @importNewSystem. + /// + /// In zh, this message translates to: + /// **'导入新系统'** + String get importNewSystem; + + /// No description provided for @importBuiltinAlpine. + /// + /// In zh, this message translates to: + /// **'从软件中导入 (Alpine)'** + String get importBuiltinAlpine; + + /// No description provided for @importExternalTarGz. + /// + /// In zh, this message translates to: + /// **'从外部导入 (.tar.gz)'** + String get importExternalTarGz; + + /// No description provided for @selectSystemDefaultPrompt. + /// + /// In zh, this message translates to: + /// **'选择系统将设为默认系统,新建终端时从该系统中启动:'** + String get selectSystemDefaultPrompt; + + /// No description provided for @noSystemsPrompt. + /// + /// In zh, this message translates to: + /// **'暂无系统,请点击右上角 \"+\" 导入'** + String get noSystemsPrompt; + + /// No description provided for @importBuiltinAlpineTitle. + /// + /// In zh, this message translates to: + /// **'从软件导入 Alpine 系统'** + String get importBuiltinAlpineTitle; + + /// No description provided for @systemNameHintWithDefault. + /// + /// In zh, this message translates to: + /// **'系统名称(如 {name})'** + String systemNameHintWithDefault(String name); + + /// No description provided for @systemImportSuccess. + /// + /// In zh, this message translates to: + /// **'系统 \"{name}\" 导入并就绪'** + String systemImportSuccess(String name); + + /// No description provided for @importExternalSystemTitle. + /// + /// In zh, this message translates to: + /// **'导入外部系统'** + String get importExternalSystemTitle; + + /// No description provided for @systemNameHint. + /// + /// In zh, this message translates to: + /// **'系统名称'** + String get systemNameHint; + + /// No description provided for @externalSystemImportSuccess. + /// + /// In zh, this message translates to: + /// **'外部系统 \"{name}\" 导入并就绪'** + String externalSystemImportSuccess(String name); + + /// No description provided for @deleteSystemConfirmTitle. + /// + /// In zh, this message translates to: + /// **'高危操作:确认删除系统'** + String get deleteSystemConfirmTitle; + + /// No description provided for @deleteSystemConfirmMessage. + /// + /// In zh, this message translates to: + /// **'确定要彻底删除系统 \"{name}\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。'** + String deleteSystemConfirmMessage(String name); + + /// No description provided for @permanentDelete. + /// + /// In zh, this message translates to: + /// **'彻底删除'** + String get permanentDelete; + + /// No description provided for @deleteSystemSuccess. + /// + /// In zh, this message translates to: + /// **'已彻底删除系统 \"{name}\" 及关联会话'** + String deleteSystemSuccess(String name); + + /// No description provided for @deleteSystemTooltip. + /// + /// In zh, this message translates to: + /// **'彻底删除该系统 (高危)'** + String get deleteSystemTooltip; + + /// No description provided for @preparingInitialization. + /// + /// In zh, this message translates to: + /// **'准备初始化...'** + String get preparingInitialization; + + /// No description provided for @cancellingAndCleaning. + /// + /// In zh, this message translates to: + /// **'正在取消并清理残余目录...'** + String get cancellingAndCleaning; + + /// No description provided for @cancelledImportSystem. + /// + /// In zh, this message translates to: + /// **'已取消导入系统 \"{name}\"'** + String cancelledImportSystem(String name); + + /// No description provided for @importFailed. + /// + /// In zh, this message translates to: + /// **'导入失败: {error}'** + String importFailed(String error); + + /// No description provided for @importingSystemTitle. + /// + /// In zh, this message translates to: + /// **'正在导入: {name}'** + String importingSystemTitle(String name); + + /// No description provided for @cancelImport. + /// + /// In zh, this message translates to: + /// **'取消导入'** + String get cancelImport; + + /// No description provided for @interrupting. + /// + /// In zh, this message translates to: + /// **'正在中断...'** + String get interrupting; + + /// No description provided for @sessionDrawerTitle. + /// + /// In zh, this message translates to: + /// **'会话'** + String get sessionDrawerTitle; + + /// No description provided for @addTerminalTooltip. + /// + /// In zh, this message translates to: + /// **'添加终端'** + String get addTerminalTooltip; + + /// No description provided for @noSystemSelectedWarning. + /// + /// In zh, this message translates to: + /// **'当前未选择任何系统,请先导入或选择系统'** + String get noSystemSelectedWarning; + + /// No description provided for @noSessionsInDrawerPrompt. + /// + /// In zh, this message translates to: + /// **'暂无会话,请点击右上角添加'** + String get noSessionsInDrawerPrompt; + + /// No description provided for @confirmDeleteTerminalSession. + /// + /// In zh, this message translates to: + /// **'确定要删除终端 \"({index}) {name}\" 吗?'** + String confirmDeleteTerminalSession(int index, String name); + + /// No description provided for @deleteSystemFailed. + /// + /// In zh, this message translates to: + /// **'删除系统失败: {error}'** + String deleteSystemFailed(String error); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ab4d8ea..050b738 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -381,4 +381,145 @@ class AppLocalizationsEn extends AppLocalizations { @override String get goToSettings => 'Settings'; + + @override + String get terminal => 'Terminal'; + + @override + String terminalWithSystem(String system) { + return 'Terminal · $system'; + } + + @override + String get sessionDefaultName => 'Session'; + + @override + String get systemManagement => 'System Management'; + + @override + String get systemManagementTooltip => 'System Management & Selection'; + + @override + String get sessionListTooltip => 'Session List'; + + @override + String get noActiveSessions => 'No active sessions'; + + @override + String get terminalInputHint => 'Enter command...'; + + @override + String get sendCommandTooltip => 'Send Command'; + + @override + String get importNewSystem => 'Import New System'; + + @override + String get importBuiltinAlpine => 'Import from App (Alpine)'; + + @override + String get importExternalTarGz => 'Import from External (.tar.gz)'; + + @override + String get selectSystemDefaultPrompt => + 'Select a system as default; new terminals will start in this system:'; + + @override + String get noSystemsPrompt => + 'No systems available. Tap \"+\" at top right to import'; + + @override + String get importBuiltinAlpineTitle => 'Import Built-in Alpine System'; + + @override + String systemNameHintWithDefault(String name) { + return 'System name (e.g. $name)'; + } + + @override + String systemImportSuccess(String name) { + return 'System \"$name\" imported and ready'; + } + + @override + String get importExternalSystemTitle => 'Import External System'; + + @override + String get systemNameHint => 'System Name'; + + @override + String externalSystemImportSuccess(String name) { + return 'External system \"$name\" imported and ready'; + } + + @override + String get deleteSystemConfirmTitle => 'High-Risk Operation: Delete System'; + + @override + String deleteSystemConfirmMessage(String name) { + return 'Are you sure you want to permanently delete system \"$name\"?\n\n⚠️ This will physically erase all internal data and installed packages. This cannot be undone!\n\nAll associated terminal sessions will also be closed.'; + } + + @override + String get permanentDelete => 'Permanently Delete'; + + @override + String deleteSystemSuccess(String name) { + return 'System \"$name\" and associated sessions deleted'; + } + + @override + String get deleteSystemTooltip => + 'Permanently delete this system (High risk)'; + + @override + String get preparingInitialization => 'Preparing initialization...'; + + @override + String get cancellingAndCleaning => + 'Cancelling and cleaning leftover directory...'; + + @override + String cancelledImportSystem(String name) { + return 'Cancelled importing system \"$name\"'; + } + + @override + String importFailed(String error) { + return 'Import failed: $error'; + } + + @override + String importingSystemTitle(String name) { + return 'Importing: $name'; + } + + @override + String get cancelImport => 'Cancel Import'; + + @override + String get interrupting => 'Interrupting...'; + + @override + String get sessionDrawerTitle => 'Sessions'; + + @override + String get addTerminalTooltip => 'Add Terminal'; + + @override + String get noSystemSelectedWarning => + 'No system selected. Please import or select a system first.'; + + @override + String get noSessionsInDrawerPrompt => 'No sessions. Tap top right to add'; + + @override + String confirmDeleteTerminalSession(int index, String name) { + return 'Are you sure you want to delete terminal \"($index) $name\"?'; + } + + @override + String deleteSystemFailed(String error) { + return 'Failed to delete system: $error'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 7f24745..f31077d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -374,4 +374,140 @@ class AppLocalizationsZh extends AppLocalizations { @override String get goToSettings => '去设置'; + + @override + String get terminal => '终端'; + + @override + String terminalWithSystem(String system) { + return '终端 · $system'; + } + + @override + String get sessionDefaultName => '会话'; + + @override + String get systemManagement => '系统管理'; + + @override + String get systemManagementTooltip => '系统管理与选择'; + + @override + String get sessionListTooltip => '会话列表'; + + @override + String get noActiveSessions => '暂无活跃会话'; + + @override + String get terminalInputHint => '输入命令...'; + + @override + String get sendCommandTooltip => '发送命令'; + + @override + String get importNewSystem => '导入新系统'; + + @override + String get importBuiltinAlpine => '从软件中导入 (Alpine)'; + + @override + String get importExternalTarGz => '从外部导入 (.tar.gz)'; + + @override + String get selectSystemDefaultPrompt => '选择系统将设为默认系统,新建终端时从该系统中启动:'; + + @override + String get noSystemsPrompt => '暂无系统,请点击右上角 \"+\" 导入'; + + @override + String get importBuiltinAlpineTitle => '从软件导入 Alpine 系统'; + + @override + String systemNameHintWithDefault(String name) { + return '系统名称(如 $name)'; + } + + @override + String systemImportSuccess(String name) { + return '系统 \"$name\" 导入并就绪'; + } + + @override + String get importExternalSystemTitle => '导入外部系统'; + + @override + String get systemNameHint => '系统名称'; + + @override + String externalSystemImportSuccess(String name) { + return '外部系统 \"$name\" 导入并就绪'; + } + + @override + String get deleteSystemConfirmTitle => '高危操作:确认删除系统'; + + @override + String deleteSystemConfirmMessage(String name) { + return '确定要彻底删除系统 \"$name\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。'; + } + + @override + String get permanentDelete => '彻底删除'; + + @override + String deleteSystemSuccess(String name) { + return '已彻底删除系统 \"$name\" 及关联会话'; + } + + @override + String get deleteSystemTooltip => '彻底删除该系统 (高危)'; + + @override + String get preparingInitialization => '准备初始化...'; + + @override + String get cancellingAndCleaning => '正在取消并清理残余目录...'; + + @override + String cancelledImportSystem(String name) { + return '已取消导入系统 \"$name\"'; + } + + @override + String importFailed(String error) { + return '导入失败: $error'; + } + + @override + String importingSystemTitle(String name) { + return '正在导入: $name'; + } + + @override + String get cancelImport => '取消导入'; + + @override + String get interrupting => '正在中断...'; + + @override + String get sessionDrawerTitle => '会话'; + + @override + String get addTerminalTooltip => '添加终端'; + + @override + String get noSystemSelectedWarning => '当前未选择任何系统,请先导入或选择系统'; + + @override + String get noSessionsInDrawerPrompt => '暂无会话,请点击右上角添加'; + + @override + String confirmDeleteTerminalSession(int index, String name) { + return '确定要删除终端 \"($index) $name\" 吗?'; + } + + @override + String deleteSystemFailed(String error) { + return '删除系统失败: $error'; + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 3eeae4a..05e234f 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -121,5 +121,123 @@ "keepLocal": "保留本地修改", "storagePermissionRequiredTitle": "需要存储访问权限", "storagePermissionRequiredMessage": "代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。", - "goToSettings": "去设置" + "goToSettings": "去设置", + "terminal": "终端", + "terminalWithSystem": "终端 · {system}", + "@terminalWithSystem": { + "placeholders": { + "system": { + "type": "String" + } + } + }, + "sessionDefaultName": "会话", + "systemManagement": "系统管理", + "systemManagementTooltip": "系统管理与选择", + "sessionListTooltip": "会话列表", + "noActiveSessions": "暂无活跃会话", + "terminalInputHint": "输入命令...", + "sendCommandTooltip": "发送命令", + "importNewSystem": "导入新系统", + "importBuiltinAlpine": "从软件中导入 (Alpine)", + "importExternalTarGz": "从外部导入 (.tar.gz)", + "selectSystemDefaultPrompt": "选择系统将设为默认系统,新建终端时从该系统中启动:", + "noSystemsPrompt": "暂无系统,请点击右上角 \"+\" 导入", + "importBuiltinAlpineTitle": "从软件导入 Alpine 系统", + "systemNameHintWithDefault": "系统名称(如 {name})", + "@systemNameHintWithDefault": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "systemImportSuccess": "系统 \"{name}\" 导入并就绪", + "@systemImportSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "importExternalSystemTitle": "导入外部系统", + "systemNameHint": "系统名称", + "externalSystemImportSuccess": "外部系统 \"{name}\" 导入并就绪", + "@externalSystemImportSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "deleteSystemConfirmTitle": "高危操作:确认删除系统", + "deleteSystemConfirmMessage": "确定要彻底删除系统 \"{name}\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。", + "@deleteSystemConfirmMessage": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "permanentDelete": "彻底删除", + "deleteSystemSuccess": "已彻底删除系统 \"{name}\" 及关联会话", + "@deleteSystemSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "deleteSystemTooltip": "彻底删除该系统 (高危)", + "preparingInitialization": "准备初始化...", + "cancellingAndCleaning": "正在取消并清理残余目录...", + "cancelledImportSystem": "已取消导入系统 \"{name}\"", + "@cancelledImportSystem": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "importFailed": "导入失败: {error}", + "@importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "importingSystemTitle": "正在导入: {name}", + "@importingSystemTitle": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "cancelImport": "取消导入", + "interrupting": "正在中断...", + "sessionDrawerTitle": "会话", + "addTerminalTooltip": "添加终端", + "noSystemSelectedWarning": "当前未选择任何系统,请先导入或选择系统", + "noSessionsInDrawerPrompt": "暂无会话,请点击右上角添加", + "confirmDeleteTerminalSession": "确定要删除终端 \"({index}) {name}\" 吗?", + "@confirmDeleteTerminalSession": { + "placeholders": { + "index": { + "type": "int" + }, + "name": { + "type": "String" + } + } + }, + "deleteSystemFailed": "删除系统失败: {error}", + "@deleteSystemFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 0c6021d..9c1206c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -27,7 +27,19 @@ class MyApp extends StatelessWidget { (tab ?? (TabProvider()..init()))..bindProjectProvider(project), ), ChangeNotifierProvider(create: (_) => TerminalProvider()), - ChangeNotifierProvider(create: (_) => DistroProvider()..checkAllStatuses()), + ChangeNotifierProxyProvider( + create: (_) => DistroProvider()..init(), + update: (_, terminal, distro) { + final dp = distro ?? (DistroProvider()..init()); + dp.onSystemDeleted = (deletedSystem) { + terminal.removeSessionsForDistro(deletedSystem); + if (!dp.hasAnySystem) { + terminal.clearAllSessions(); + } + }; + return dp; + }, + ), ], child: Consumer( builder: (context, settings, child) { diff --git a/lib/models/distro_info.dart b/lib/models/distro_info.dart index a1a3e26..89a46dc 100644 --- a/lib/models/distro_info.dart +++ b/lib/models/distro_info.dart @@ -1,190 +1,18 @@ -/// Linux 发行版安装状态 -enum DistroStatus { - /// 未安装 - notInstalled, +import 'dart:ffi'; - /// 正在安装/解压中 - installing, - - /// 已安装就绪 - installed, - - /// 安装或运行异常 - error, -} - -/// Linux 发行版元数据模型,具备高扩展性 +/// 内置 Linux 发行版资源信息常量 class DistroInfo { - /// 唯一标识符,例如 'alpine', 'debian', 'ubuntu', 'host' - final String id; - - /// 显示名称,例如 'Alpine Linux' - final String name; - - /// 版本号,例如 '3.20.3' - final String version; - - /// 描述信息 - final String description; - - /// 默认登录 Shell,例如 '/bin/sh', '/bin/bash' - final String defaultShell; - - /// 包管理器名称,例如 'apk', 'apt' - final String packageManager; - - /// 支持的硬件架构,例如 ['aarch64', 'arm64-v8a'] - final List supportedArchs; - - /// 内置应用资源路径(如有,可离线解压) - final String? assetPath; - - /// 远程下载地址(支持网络按需下载扩展) - final String? downloadUrl; - - /// 是否为官方内置预设 - final bool isBuiltin; - - /// 图标名称标识 - final String iconName; - - const DistroInfo({ - required this.id, - required this.name, - required this.version, - required this.description, - this.defaultShell = '/bin/sh', - this.packageManager = 'apk', - this.supportedArchs = const ['aarch64', 'arm64-v8a', 'all'], - this.assetPath, - this.downloadUrl, - this.isBuiltin = true, - this.iconName = 'terminal', - }); - - /// 预设:Alpine Linux (轻量极速,内置 asset) - static const DistroInfo alpine = DistroInfo( - id: 'alpine', - name: 'Alpine Linux', - version: '3.20.3', - description: '轻量快速的 Linux 发行版,体积仅约 4MB,内置 apk 包管理器', - defaultShell: '/bin/sh', - packageManager: 'apk', - supportedArchs: ['aarch64', 'arm64-v8a'], - assetPath: 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz', - isBuiltin: true, - iconName: 'alpine', - ); - - /// 预设扩展:Debian GNU/Linux - static const DistroInfo debian = DistroInfo( - id: 'debian', - name: 'Debian GNU/Linux', - version: '12 (Bookworm)', - description: '全能稳定的 Linux 发行版,标准 glibc 兼容,内置 apt 包管理器', - defaultShell: '/bin/bash', - packageManager: 'apt', - supportedArchs: ['aarch64', 'x86_64'], - downloadUrl: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/', - isBuiltin: false, - iconName: 'debian', - ); - - /// 预设扩展:Ubuntu - static const DistroInfo ubuntu = DistroInfo( - id: 'ubuntu', - name: 'Ubuntu', - version: '24.04 LTS', - description: '应用与开发生态丰富的流行 Linux 发行版,内置 apt 包管理器', - defaultShell: '/bin/bash', - packageManager: 'apt', - supportedArchs: ['aarch64', 'x86_64'], - downloadUrl: 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu-cdimage/ubuntu-base/releases/24.04/release/', - isBuiltin: false, - iconName: 'ubuntu', - ); - - /// 预设:Android 本地 Shell - static const DistroInfo host = DistroInfo( - id: 'host', - name: '本地 Shell', - version: 'Android', - description: '直接调用安卓系统内置的基础 Shell,无需虚拟环境', - defaultShell: '/system/bin/sh', - packageManager: 'none', - supportedArchs: ['all'], - isBuiltin: true, - iconName: 'host', - ); - - /// 默认官方预设列表 - static const List defaults = [ - alpine, - debian, - ubuntu, - host, - ]; - - DistroInfo copyWith({ - String? id, - String? name, - String? version, - String? description, - String? defaultShell, - String? packageManager, - List? supportedArchs, - String? assetPath, - String? downloadUrl, - bool? isBuiltin, - String? iconName, - }) { - return DistroInfo( - id: id ?? this.id, - name: name ?? this.name, - version: version ?? this.version, - description: description ?? this.description, - defaultShell: defaultShell ?? this.defaultShell, - packageManager: packageManager ?? this.packageManager, - supportedArchs: supportedArchs ?? this.supportedArchs, - assetPath: assetPath ?? this.assetPath, - downloadUrl: downloadUrl ?? this.downloadUrl, - isBuiltin: isBuiltin ?? this.isBuiltin, - iconName: iconName ?? this.iconName, - ); + /// 根据当前运行环境的 CPU 架构自动选取匹配的内置 Alpine Minirootfs + static String get builtinAlpineAssetPath { + final currentAbi = Abi.current(); + if (currentAbi == Abi.androidX64 || + currentAbi == Abi.linuxX64 || + currentAbi == Abi.windowsX64) { + return 'assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz'; + } + return 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz'; } - Map toJson() { - return { - 'id': id, - 'name': name, - 'version': version, - 'description': description, - 'defaultShell': defaultShell, - 'packageManager': packageManager, - 'supportedArchs': supportedArchs, - 'assetPath': assetPath, - 'downloadUrl': downloadUrl, - 'isBuiltin': isBuiltin, - 'iconName': iconName, - }; - } - - factory DistroInfo.fromJson(Map json) { - return DistroInfo( - id: json['id'] as String, - name: json['name'] as String, - version: json['version'] as String, - description: json['description'] as String, - defaultShell: (json['defaultShell'] as String?) ?? '/bin/sh', - packageManager: (json['packageManager'] as String?) ?? 'apk', - supportedArchs: (json['supportedArchs'] as List?) - ?.map((e) => e.toString()) - .toList() ?? - const ['aarch64'], - assetPath: json['assetPath'] as String?, - downloadUrl: json['downloadUrl'] as String?, - isBuiltin: (json['isBuiltin'] as bool?) ?? false, - iconName: (json['iconName'] as String?) ?? 'terminal', - ); - } + /// 默认系统实例名称 + static const String defaultSystemName = 'alpine'; } diff --git a/lib/models/terminal_session.dart b/lib/models/terminal_session.dart index 5ac551d..aeadc18 100644 --- a/lib/models/terminal_session.dart +++ b/lib/models/terminal_session.dart @@ -1,56 +1,169 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:code_editor/services/distro_manager.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_pty/flutter_pty.dart'; +import 'package:xterm/xterm.dart'; -/// 单个终端会话的数据与状态模型 +/// 单个真实交互式终端会话的数据与状态模型(基于 原生 Unix PTY 伪终端) class TerminalSession { final String id; String name; final String distroId; final DateTime createdAt; - final List outputLines; - final TextEditingController inputController; - final ScrollController scrollController; + final Terminal terminal; final FocusNode focusNode; + Pty? _pty; + StreamSubscription? _ptyOutputSub; + bool _isProcessRunning = false; + String _inputBuffer = ''; + TerminalSession({ required this.id, this.name = '会话', this.distroId = 'alpine', DateTime? createdAt, - List? initialOutput, + int maxLines = 10000, + bool autoStartProcess = false, }) : createdAt = createdAt ?? DateTime.now(), - outputLines = initialOutput ?? [], - inputController = TextEditingController(), - scrollController = ScrollController(), - focusNode = FocusNode(); - - /// 向终端输出追加内容 - void appendOutput(String line) { - outputLines.add(line); - _autoScrollToBottom(); + terminal = Terminal(maxLines: maxLines), + focusNode = FocusNode() { + _initTerminalEvents(); + if (autoStartProcess) { + unawaited(startProcess()); + } } - /// 自动滚动到终端最底部 - void _autoScrollToBottom() { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (scrollController.hasClients) { - scrollController.animateTo( - scrollController.position.maxScrollExtent, - duration: const Duration(milliseconds: 100), - curve: Curves.easeOut, - ); + bool get isProcessRunning => _isProcessRunning; + + /// 获取终端缓冲区当前全部可见文本(常用于测试与日志断言) + String get bufferText => terminal.buffer.getText(); + + void _initTerminalEvents() { + // 监听输入直接送往 PTY + terminal.onOutput = (data) { + if (_pty != null && _isProcessRunning) { + try { + _pty!.write(utf8.encode(data)); + } catch (_) {} + } else { + _handleLocalEcho(data); } - }); + }; + + // 监听终端视口尺寸变化并同步给底层 PTY + terminal.onResize = (width, height, pixelWidth, pixelHeight) { + if (_pty != null && _isProcessRunning) { + try { + _pty!.resize(height, width); + } catch (_) {} + } + }; } - /// 清屏 + /// 当无底层进程挂接时的本地简易交互回显支持(保证脱机/本地开发时的基础交互与光标跳动) + void _handleLocalEcho(String data) { + for (int i = 0; i < data.length; i++) { + final char = data[i]; + if (char == '\r' || char == '\n') { + terminal.write('\r\n'); + _executeLocalCommand(_inputBuffer.trim()); + _inputBuffer = ''; + } else if (char == '\x7f' || char == '\b') { + // 退格键 + if (_inputBuffer.isNotEmpty) { + _inputBuffer = _inputBuffer.substring(0, _inputBuffer.length - 1); + terminal.write('\b \b'); + } + } else if (char.codeUnitAt(0) >= 32) { + _inputBuffer += char; + terminal.write(char); + } + } + } + + void _executeLocalCommand(String cmd) { + if (cmd.isEmpty) { + terminal.write('\$ '); + return; + } + if (cmd == 'clear') { + clear(); + terminal.write('\$ '); + return; + } + terminal.write('\x1b[33m[Host fallback]: executed "$cmd"\x1b[0m\r\n'); + terminal.write('\$ '); + } + + /// 启动底层真实 PTY 进程(连接 PRoot 容器或 Host Shell) + Future startProcess({DistroManager? distroManager, String? workspacePath}) async { + final manager = distroManager ?? DistroManager(); + try { + final config = await manager.buildLaunchConfig( + systemName: distroId, + workspacePath: workspacePath, + ); + + final initialRows = terminal.viewHeight > 0 ? terminal.viewHeight : 24; + final initialCols = terminal.viewWidth > 0 ? terminal.viewWidth : 80; + + // 使用真实 Unix 伪终端 (PTY) 启动子进程 + _pty = Pty.start( + config.executable, + arguments: config.arguments, + environment: config.environment, + workingDirectory: config.workingDirectory, + rows: initialRows, + columns: initialCols, + ); + _isProcessRunning = true; + + // PTY 输出数据流实时解码并写入终端 + _ptyOutputSub = _pty!.output.listen( + (bytes) { + terminal.write(utf8.decode(bytes, allowMalformed: true)); + }, + onError: (err) { + terminal.write('\r\n\x1b[31m[PTY Output error: $err]\x1b[0m\r\n'); + }, + onDone: () { + _isProcessRunning = false; + }, + ); + + _pty!.exitCode.then((code) { + _isProcessRunning = false; + terminal.write('\r\n\x1b[33m[Process exited with code $code]\x1b[0m\r\n'); + }); + } catch (e) { + _isProcessRunning = false; + terminal.write('\x1b[1;36mWelcome to Terminal [$distroId]\x1b[0m\r\n'); + terminal.write('\x1b[90m(PTY launch failed: $e. Running in local fallback mode.)\x1b[0m\r\n\r\n'); + terminal.write('\$ '); + } + } + + /// 向终端写入文本(支持 VT100 / ANSI 转义序列) + void write(String text) { + terminal.write(text); + } + + /// 发送标准 ANSI 清屏并复位光标 void clear() { - outputLines.clear(); + terminal.write('\x1b[2J\x1b[H'); } - /// 释放资源 + /// 释放 PTY 进程与焦点资源 void dispose() { - inputController.dispose(); - scrollController.dispose(); + _ptyOutputSub?.cancel(); + if (_pty != null) { + try { + _pty!.kill(); + } catch (_) {} + _pty = null; + } focusNode.dispose(); } } diff --git a/lib/providers/distro_provider.dart b/lib/providers/distro_provider.dart index b2c2b52..b9ea7e7 100644 --- a/lib/providers/distro_provider.dart +++ b/lib/providers/distro_provider.dart @@ -1,93 +1,115 @@ +import 'dart:io'; import 'package:flutter/foundation.dart'; -import '../models/distro_info.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../services/distro_installer.dart'; import '../services/distro_manager.dart'; -/// Linux 发行版状态提供者(供 UI 监听与绑定) +/// 终端多系统状态与默认系统持久化管理器 class DistroProvider with ChangeNotifier { + static const String _prefKeyDefaultSystem = 'terminal_default_system'; + final DistroManager _manager = DistroManager(); - /// 各发行版状态缓存 - final Map _statuses = {}; + /// 当前已安装的系统名称列表 + List _installedSystems = []; - /// 安装进度 (0.0 ~ 1.0) - final Map _progress = {}; + /// 当前选中的默认系统(若无系统则为 null) + String? _selectedSystem; - /// 状态描述文字(如 "正在解压... 45%") - final Map _statusMessages = {}; + /// 是否已完成初始状态加载 + bool _isInitialized = false; - /// 默认创建会话使用的发行版 ID - String _defaultDistroId = 'alpine'; + /// 系统被物理删除时的回调监听(如联动终端清理其下全部关联会话) + void Function(String deletedSystem)? onSystemDeleted; - String get defaultDistroId => _defaultDistroId; + bool get isInitialized => _isInitialized; - List get distros => _manager.listDistros(); + List get installedSystems => List.unmodifiable(_installedSystems); - DistroStatus getStatus(String id) => _statuses[id] ?? DistroStatus.notInstalled; + String? get selectedSystem => _selectedSystem; - double getProgress(String id) => _progress[id] ?? 0.0; + bool get hasAnySystem => _installedSystems.isNotEmpty; - String getStatusMessage(String id) => _statusMessages[id] ?? ''; - - /// 初始化检查所有发行版状态 - Future checkAllStatuses() async { - for (final distro in _manager.listDistros()) { - try { - final isInst = await _manager.isInstalled(distro.id); - _statuses[distro.id] = isInst ? DistroStatus.installed : DistroStatus.notInstalled; - } catch (_) { - _statuses[distro.id] = DistroStatus.error; - } - } + /// 初始化:扫描系统列表并读取持久化的默认系统 + Future init() async { + await refreshSystems(); + _isInitialized = true; notifyListeners(); } - /// 设置默认发行版 - void setDefaultDistro(String id) { - if (_defaultDistroId != id) { - _defaultDistroId = id; - notifyListeners(); + /// 重新扫描已安装的系统并校准当前默认选中项 + Future refreshSystems() async { + final systems = await _manager.listInstalledSystems(); + _installedSystems = systems; + + final prefs = await SharedPreferences.getInstance(); + final savedSystem = prefs.getString(_prefKeyDefaultSystem); + + if (savedSystem != null && _installedSystems.contains(savedSystem)) { + _selectedSystem = savedSystem; + } else if (_installedSystems.isNotEmpty) { + _selectedSystem = _installedSystems.first; + await prefs.setString(_prefKeyDefaultSystem, _selectedSystem!); + } else { + _selectedSystem = null; + await prefs.remove(_prefKeyDefaultSystem); } - } - /// 安装发行版 - Future installDistro(String distroId) async { - _statuses[distroId] = DistroStatus.installing; - _progress[distroId] = 0.0; - _statusMessages[distroId] = '准备开始安装...'; notifyListeners(); + } - try { - await _manager.installDistro( - distroId, - onProgress: (prog, msg) { - _progress[distroId] = prog; - _statusMessages[distroId] = msg; - notifyListeners(); - }, - ); - _statuses[distroId] = DistroStatus.installed; - _statusMessages[distroId] = '已就绪'; + /// 选择指定系统为当前活跃系统并持久化为默认系统 + Future selectSystem(String systemName) async { + if (!_installedSystems.contains(systemName)) return; + + if (_selectedSystem != systemName) { + _selectedSystem = systemName; + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_prefKeyDefaultSystem, systemName); notifyListeners(); - return true; - } catch (e) { - _statuses[distroId] = DistroStatus.error; - _statusMessages[distroId] = '安装失败: $e'; - notifyListeners(); - return false; } } - /// 卸载发行版 - Future uninstallDistro(String distroId) async { - try { - await _manager.uninstallDistro(distroId); - _statuses[distroId] = DistroStatus.notInstalled; - _progress.remove(distroId); - _statusMessages.remove(distroId); - notifyListeners(); - } catch (e) { - _statusMessages[distroId] = '卸载失败: $e'; - notifyListeners(); - } + /// 从应用内置资源导入 Alpine 系统实例 + Future importBuiltinAlpine({ + required String systemName, + InstallProgressCallback? onProgress, + bool Function()? isCancelled, + }) async { + await _manager.importBuiltinAlpine( + systemName: systemName, + onProgress: onProgress, + isCancelled: isCancelled, + ); + + // 导入成功后刷新列表并自动选为当前系统 + await refreshSystems(); + await selectSystem(systemName); + } + + /// 从外部 .tar.gz 压缩包导入自定义系统实例 + Future importFromCustomTarGz({ + required String systemName, + required File tarGzFile, + InstallProgressCallback? onProgress, + bool Function()? isCancelled, + }) async { + await _manager.importFromCustomTarGz( + systemName: systemName, + tarGzFile: tarGzFile, + onProgress: onProgress, + isCancelled: isCancelled, + ); + + // 导入成功后刷新列表并自动选为当前系统 + await refreshSystems(); + await selectSystem(systemName); + } + + /// 高危操作:删除指定系统实例 + Future deleteSystem(String systemName) async { + await _manager.deleteSystem(systemName); + onSystemDeleted?.call(systemName); + await refreshSystems(); } } diff --git a/lib/providers/terminal_provider.dart b/lib/providers/terminal_provider.dart index 0ba394e..81141bf 100644 --- a/lib/providers/terminal_provider.dart +++ b/lib/providers/terminal_provider.dart @@ -23,9 +23,12 @@ class TerminalProvider extends ChangeNotifier { } /// 懒加载:进入终端页面时调用,如果尚未创建会话,则自动创建并激活首个会话 - void ensureInitialized() { + void ensureInitialized({ + String defaultName = '会话', + String defaultDistroId = 'alpine', + }) { if (_sessions.isEmpty) { - createSession(name: '会话', activate: true); + createSession(name: defaultName, distroId: defaultDistroId, activate: true); } } @@ -33,20 +36,18 @@ class TerminalProvider extends ChangeNotifier { /// [distroId]: 发行版标识符(如 'alpine', 'host') /// [activate]: 是否自动跳转切换到该会话。抽屉右上角加号点击时为 false(直接添加但不跳转)。 TerminalSession createSession({ - String name = '会话', + String? name, String distroId = 'alpine', bool activate = false, + bool autoStartProcess = true, }) { final nextIndex = _sessions.length + 1; + final sessionName = (name != null && name.trim().isNotEmpty) ? name.trim() : '会话'; final session = TerminalSession( id: 'session_${DateTime.now().microsecondsSinceEpoch}_$nextIndex', - name: name, + name: sessionName, distroId: distroId, - initialOutput: [ - 'Welcome to Terminal ($nextIndex) [$distroId]', - 'Type "help" for a list of built-in commands or "clear" to clear.', - '', - ], + autoStartProcess: autoStartProcess, ); _sessions.add(session); @@ -100,6 +101,36 @@ class TerminalProvider extends ChangeNotifier { notifyListeners(); } + /// 移除指定系统的所有会话(当系统被物理删除时调用) + void removeSessionsForDistro(String distroId) { + final toRemove = _sessions.where((s) => s.distroId == distroId).toList(); + if (toRemove.isEmpty) return; + + for (final session in toRemove) { + session.dispose(); + _sessions.remove(session); + } + + if (_sessions.isEmpty) { + _activeIndex = 0; + } else if (_activeIndex >= _sessions.length) { + _activeIndex = _sessions.length - 1; + } + + notifyListeners(); + } + + /// 清空全部会话并释放资源 + void clearAllSessions() { + if (_sessions.isEmpty) return; + for (final session in _sessions) { + session.dispose(); + } + _sessions.clear(); + _activeIndex = 0; + notifyListeners(); + } + /// 拖拽重新排序终端会话(接收 onReorderItem 传入的已修正目标索引) void reorderSessions(int oldIndex, int newIndex) { if (oldIndex < 0 || oldIndex >= _sessions.length) return; @@ -121,56 +152,9 @@ class TerminalProvider extends ChangeNotifier { notifyListeners(); } - /// 向指定终端会话追加输出并通知更新 - void appendOutput(TerminalSession session, String line) { - session.appendOutput(line); - notifyListeners(); - } - - /// 执行简单交互命令(支持 help, clear, echo, date 等,后续可无缝接入 PTY / Shell) - void executeCommand(TerminalSession session, String rawInput) { - final input = rawInput.trim(); - session.appendOutput('\$ $rawInput'); - - if (input.isEmpty) { - notifyListeners(); - return; - } - - final parts = input.split(RegExp(r'\s+')); - final cmd = parts.first.toLowerCase(); - - switch (cmd) { - case 'clear': - session.clear(); - break; - case 'help': - session.appendOutput('Built-in terminal commands:'); - session.appendOutput(' clear Clear the terminal screen'); - session.appendOutput(' date Show current date and time'); - session.appendOutput(' echo Echo text back'); - session.appendOutput(' help Show this help information'); - session.appendOutput(' sessions List active sessions'); - break; - case 'date': - session.appendOutput(DateTime.now().toString()); - break; - case 'echo': - session.appendOutput(parts.skip(1).join(' ')); - break; - case 'sessions': - session.appendOutput('Total sessions: ${_sessions.length}'); - for (int i = 0; i < _sessions.length; i++) { - final s = _sessions[i]; - final marker = (i == _activeIndex) ? '*' : ' '; - session.appendOutput(' $marker (${i + 1}) ${s.name} [${s.id}]'); - } - break; - default: - session.appendOutput('command not found: $cmd'); - break; - } - + /// 向指定终端会话写入文本并通知更新 + void appendOutput(TerminalSession session, String text) { + session.write(text); notifyListeners(); } diff --git a/lib/services/distro_installer.dart b/lib/services/distro_installer.dart index 32b7339..34ed601 100644 --- a/lib/services/distro_installer.dart +++ b/lib/services/distro_installer.dart @@ -1,6 +1,8 @@ +import 'dart:ffi'; import 'dart:io'; import 'package:archive/archive.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:path/path.dart' as p; /// 安装进度回调 @@ -8,6 +10,15 @@ import 'package:path/path.dart' as p; /// [message] 当前阶段说明 typedef InstallProgressCallback = void Function(double progress, String message); +/// 取消安装异常 +class DistroInstallCancelledException implements Exception { + final String message; + DistroInstallCancelledException([this.message = '用户已取消系统导入']); + + @override + String toString() => message; +} + /// Linux 发行版 Rootfs 安装与解压服务 class DistroInstaller { /// 解压并安装 tar.gz 格式的 Rootfs 到目标目录 @@ -15,67 +26,112 @@ class DistroInstaller { /// [tarGzBytes] .tar.gz 压缩包字节流 /// [targetDir] 目标解压目录 (即容器的 rootfs 路径) /// [onProgress] 进度回调 + /// [isCancelled] 外部取消检查函数 static Future installFromBytes({ required Uint8List tarGzBytes, required Directory targetDir, InstallProgressCallback? onProgress, + bool Function()? isCancelled, }) async { + if (isCancelled?.call() == true) { + throw DistroInstallCancelledException(); + } + onProgress?.call(0.05, '正在校验与解析系统镜像...'); if (!targetDir.existsSync()) { targetDir.createSync(recursive: true); } - // 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿) - onProgress?.call(0.15, '正在解压内核与文件系统结构...'); - final archive = await compute(_decodeTarGz, tarGzBytes); + try { + // 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿) + onProgress?.call(0.15, '正在解压内核与文件系统结构...'); + final archive = await compute(_decodeTarGz, tarGzBytes); - // 2. 写入文件与目录 - final total = archive.length; - int processed = 0; + if (isCancelled?.call() == true) { + throw DistroInstallCancelledException(); + } - for (final file in archive) { - processed++; - final filename = file.name; - // 避免路径穿越漏洞 (Directory Traversal) - if (filename.contains('..')) continue; + // 2. 写入文件与目录 + // + // 权限位必须逐条按 tar 头恢复:dart:io 没有 chmod,而解压本身不会保留 + // 可执行位,所以恢复方式是按 mode 分组批量调用 chmod(避免逐文件 fork)。 + // 之前这里用 `chmod -R 755` 一把梭,会把 /etc 下的配置文件也变成可执行。 + final total = archive.length; + int processed = 0; + final Map> byMode = >{}; - final outPath = p.join(targetDir.path, filename); - - if (file.isFile) { - final parentDir = Directory(p.dirname(outPath)); - if (!parentDir.existsSync()) { - parentDir.createSync(recursive: true); + for (final file in archive) { + if (isCancelled?.call() == true) { + throw DistroInstallCancelledException(); } - // 处理符号链接与常规文件 - if (file.isSymbolicLink) { - try { - final link = Link(outPath); - if (link.existsSync()) link.deleteSync(); - link.createSync(file.nameOfLinkedFile); - } catch (_) { - // Windows 或受限环境降级为写入目标路径文本或忽略 + processed++; + final filename = file.name; + // 避免路径穿越漏洞 (Directory Traversal) + if (filename.contains('..')) continue; + + final outPath = p.join(targetDir.path, filename); + + if (file.isFile) { + final parentDir = Directory(p.dirname(outPath)); + if (!parentDir.existsSync()) { + parentDir.createSync(recursive: true); + } + + // 处理符号链接与常规文件 + if (file.isSymbolicLink) { + try { + final link = Link(outPath); + if (link.existsSync()) link.deleteSync(); + link.createSync(file.nameOfLinkedFile); + } catch (_) { + // Windows 或受限环境降级为写入目标路径文本或忽略 + } + } else { + final content = file.content as List; + File(outPath).writeAsBytesSync(content, flush: false); } } else { - final content = file.content as List; - File(outPath).writeAsBytesSync(content, flush: false); + Directory(outPath).createSync(recursive: true); + } + + // 记录 tar 头里的权限位(仅低 12 位有效位)。 + // 符号链接必须跳过:chmod 会跟随链接,把目标文件的权限改坏 + // (tar 里 symlink 条目的 mode 固定为 0777)。 + final mode = file.mode & 0xFFF; + if (mode != 0 && !file.isSymbolicLink) { + byMode.putIfAbsent(mode, () => []).add(outPath); + } + + if (processed % 50 == 0 || processed == total) { + final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90% + onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...'); } - } else { - Directory(outPath).createSync(recursive: true); } - if (processed % 100 == 0 || processed == total) { - final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90% - onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...'); + if (!Platform.isWindows) { + await _restoreModes(byMode); } + + if (isCancelled?.call() == true) { + throw DistroInstallCancelledException(); + } + + // 3. 执行系统配置与网络补丁 + onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...'); + await postInstallConfigure(targetDir); + + onProgress?.call(1.0, '系统初始化就绪!'); + } catch (e) { + // 若中途失败或取消,清理不完整的根目录 + try { + if (targetDir.existsSync()) { + targetDir.deleteSync(recursive: true); + } + } catch (_) {} + rethrow; } - - // 3. 执行系统配置与网络补丁 - onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...'); - await postInstallConfigure(targetDir); - - onProgress?.call(1.0, '系统初始化就绪!'); } /// 后台 Isolate 解压 tar.gz @@ -84,10 +140,37 @@ class DistroInstaller { return TarDecoder().decodeBytes(tarData); } + /// 按 tar 头恢复权限位(dart:io 无 chmod,按 mode 分组批量调用,避免逐文件 fork) + static Future _restoreModes(Map> byMode) async { + for (final entry in byMode.entries) { + final octal = entry.key.toRadixString(8).padLeft(4, '0'); + final paths = entry.value; + // 单次 chmod 的参数长度有限,分批执行 + const batch = 100; + for (var i = 0; i < paths.length; i += batch) { + final end = (i + batch < paths.length) ? i + batch : paths.length; + final slice = paths.sublist(i, end); + try { + await Process.run('chmod', [octal, ...slice]); + } catch (e) { + debugPrint('[DistroInstaller] 恢复权限失败 ($octal): $e'); + } + } + } + } + + /// 容器可用的 DNS 解析器(按"可达优先"排序:国内公共 DNS 在前) + static const String guestResolvConf = '# Generated by CodeEditor\n' + 'nameserver 223.5.5.5\n' + 'nameserver 119.29.29.29\n' + 'nameserver 114.114.114.114\n'; + /// 自动化环境补丁与配置 - /// 1. 注入 DNS (resolv.conf) 防止容器内 apk/apt 无法联网 - /// 2. 注入 hosts - /// 3. 创建挂载点 /workspace 和 /tmp + /// + /// 只做"发行版自身不会做、但容器化必需"的事:DNS、hosts、镜像源、 + /// 挂载点目录、shim 部署。**不再改写 guest 的 /etc/profile** —— 那会破坏 + /// 非 Alpine 发行版自带的登录环境(Alpine 原版 profile 与本项目此前写入的 + /// 模板逐行相同,所以删掉它对 Alpine 没有任何影响)。 static Future postInstallConfigure(Directory rootfsDir) async { final etcDir = Directory(p.join(rootfsDir.path, 'etc')); if (!etcDir.existsSync()) { @@ -97,12 +180,7 @@ class DistroInstaller { // 1. 配置 DNS 解析器 final resolvFile = File(p.join(etcDir.path, 'resolv.conf')); try { - resolvFile.writeAsStringSync( - '# Generated by CodeEditor DistroManager\n' - 'nameserver 1.1.1.1\n' - 'nameserver 8.8.8.8\n' - 'nameserver 114.114.114.114\n', - ); + resolvFile.writeAsStringSync(guestResolvConf); } catch (e) { debugPrint('[DistroInstaller] 写入 resolv.conf 失败: $e'); } @@ -118,16 +196,79 @@ class DistroInstaller { debugPrint('[DistroInstaller] 写入 hosts 失败: $e'); } - // 3. 确保 /workspace 挂载点目录存在 + // 3. 配置 Alpine apk 软件源镜像(使用阿里云高速稳定镜像) + final apkDir = Directory(p.join(etcDir.path, 'apk')); + if (apkDir.existsSync()) { + final repoFile = File(p.join(apkDir.path, 'repositories')); + try { + repoFile.writeAsStringSync( + 'https://mirrors.aliyun.com/alpine/v3.20/main\n' + 'https://mirrors.aliyun.com/alpine/v3.20/community\n', + ); + } catch (e) { + debugPrint('[DistroInstaller] 写入 repositories 失败: $e'); + } + } + + // 4. 确保 /workspace 挂载点目录存在 final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace')); if (!workspaceDir.existsSync()) { workspaceDir.createSync(recursive: true); } - // 4. 确保 /tmp 目录存在 + // 5. 确保 /tmp 目录存在 final tmpDir = Directory(p.join(rootfsDir.path, 'tmp')); if (!tmpDir.existsSync()) { tmpDir.createSync(recursive: true); } + + // 6. 部署容器修复 Shim(libfix_seccomp.so) + await ensureSeccompShim(rootfsDir); + } + + /// 部署容器修复 Shim(libfix_seccomp.so) + /// + /// 它只做两件在 Android app 进程里必需的事: + /// 1. `utimensat()`(两个架构):Android 不允许应用数据区创建硬链接,PRoot + /// 的 `--link2symlink` 用 symlink + 隐藏记账文件模拟硬链接,导致 apk + /// 保 mtime 时跟随解析失败(`Failed to preserve modification time`)。 + /// 2. `poll/select/pipe/dup2`(仅 x86_64):Android 的 app seccomp 策略把这些 + /// 传统 syscall 返回 ENOSYS,而 musl 在有这些调用的架构上优先用它们。 + static Future ensureSeccompShim(Directory rootfsDir) async { + final libDir = Directory(p.join(rootfsDir.path, 'lib')); + if (!libDir.existsSync()) { + libDir.createSync(recursive: true); + } + final targetShim = File(p.join(libDir.path, 'libfix_seccomp.so')); + + String? archFolder; + if (Platform.isAndroid || Platform.isLinux) { + final currentAbi = Abi.current(); + if (currentAbi == Abi.androidX64 || currentAbi == Abi.linuxX64) { + archFolder = 'x86_64'; + } else if (currentAbi == Abi.androidArm64 || currentAbi == Abi.linuxArm64) { + archFolder = 'arm64-v8a'; + } + } + if (archFolder == null) return; + + try { + final assetPath = 'assets/shims/$archFolder/libfix_seccomp.so'; + final byteData = await rootBundle.load(assetPath); + final bytes = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes); + + // 如果目标文件已存在且大小一致,则跳过写入 + if (targetShim.existsSync() && targetShim.lengthSync() == bytes.length) { + return; + } + + await targetShim.writeAsBytes(bytes, flush: true); + if (!Platform.isWindows) { + await Process.run('chmod', ['755', targetShim.path]); + } + debugPrint('[DistroInstaller] 成功部署 SECCOMP Shim: ${targetShim.path}'); + } catch (e) { + debugPrint('[DistroInstaller] 部署 SECCOMP Shim 失败: $e'); + } } } diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index f9b9f41..b8b1ae4 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -35,40 +35,16 @@ class ProotLaunchConfig { } } -/// Linux 发行版管理器服务(单例模式,易扩展) +/// Linux 发行版与多系统实例管理器服务(单例模式,易扩展) class DistroManager { static final DistroManager _instance = DistroManager._internal(); factory DistroManager() => _instance; - DistroManager._internal() { - // 注册内置默认发行版 - for (final d in DistroInfo.defaults) { - _distros[d.id] = d; - } - } + DistroManager._internal(); /// 自定义覆盖根目录(主要用于测试) @visibleForTesting Directory? customBaseDir; - /// 发行版注册表 `Map` - final Map _distros = {}; - - /// 获取所有已注册的发行版 - List listDistros() => _distros.values.toList(); - - /// 获取指定发行版元数据 - DistroInfo? getDistro(String id) => _distros[id]; - - /// 动态注册新的发行版(支持未来插件化或用户自定义导入) - void registerDistro(DistroInfo distro) { - _distros[distro.id] = distro; - } - - /// 注销指定发行版 - void unregisterDistro(String id) { - _distros.remove(id); - } - /// 获取发行版存储基础目录: `/distros` Future getBaseDistrosDir() async { if (customBaseDir != null) { @@ -82,115 +58,212 @@ class DistroManager { return distrosDir; } - /// 获取指定发行版的 Rootfs 解压目录: `/distros//rootfs` - Future getDistroRootDir(String distroId) async { + /// 获取指定系统实例的 Rootfs 解压目录: `/distros//rootfs` + Future getSystemRootDir(String systemName) async { final baseDir = await getBaseDistrosDir(); - return Directory(p.join(baseDir.path, distroId, 'rootfs')); + return Directory(p.join(baseDir.path, systemName, 'rootfs')); } - /// 检测指定发行版是否已安装就绪 - Future isInstalled(String distroId) async { - // host 为宿主系统,无需安装 - if (distroId == 'host') return true; + /// 获取当前已创建并解压成功的系统实例列表(文件夹名称即系统名称) + Future> listInstalledSystems() async { + final baseDir = await getBaseDistrosDir(); + if (!baseDir.existsSync()) return []; - final rootDir = await getDistroRootDir(distroId); + final List systems = []; + final entities = baseDir.listSync(followLinks: false); + for (final entity in entities) { + if (entity is Directory) { + final name = p.basename(entity.path); + // 若子目录存在 rootfs/ 且包含基础目录结构,则视为有效系统实例 + final rootDir = Directory(p.join(entity.path, 'rootfs')); + if (rootDir.existsSync()) { + systems.add(name); + } + } + } + // 按名称字母排序 + systems.sort((a, b) => a.compareTo(b)); + return systems; + } + + /// 是否存在任何已安装的系统 + Future hasAnySystem() async { + final systems = await listInstalledSystems(); + return systems.isNotEmpty; + } + + /// 检测指定系统实例是否已安装就绪 + Future isSystemInstalled(String systemName) async { + if (systemName == 'host') return true; + + final rootDir = await getSystemRootDir(systemName); if (!rootDir.existsSync()) return false; - // 检查关键目录和常用 shell 是否存在 final hasEtc = Directory(p.join(rootDir.path, 'etc')).existsSync(); final hasBin = Directory(p.join(rootDir.path, 'bin')).existsSync(); return hasEtc && hasBin; } - /// 安装发行版(优先从内置 asset 离线安装,支持进度回调) - Future installDistro( - String distroId, { - InstallProgressCallback? onProgress, - }) async { - final distro = getDistro(distroId); - if (distro == null) { - throw ArgumentError('未知的发行版 ID: $distroId'); + /// 校验系统名称是否合法且未被占用 + Future validateSystemName(String systemName) async { + final trimmed = systemName.trim(); + if (trimmed.isEmpty) { + throw ArgumentError('系统名称不能为空'); + } + // 限制字符集:字母、数字、下划线、短横线、中文字符 + final validRegex = RegExp(r'^[\w\u4e00-\u9fa5\-_]+$'); + if (!validRegex.hasMatch(trimmed)) { + throw ArgumentError('系统名称只能包含字母、数字、中文、下划线或短横线'); } - if (distroId == 'host') { - onProgress?.call(1.0, '本地 Shell 无需安装'); - return; + final systems = await listInstalledSystems(); + if (systems.any((s) => s.toLowerCase() == trimmed.toLowerCase())) { + throw ArgumentError('已存在同名系统 "$trimmed",请使用其他名称'); } - - final targetDir = await getDistroRootDir(distroId); - - // 优先从内置 Asset 安装 - if (distro.assetPath != null) { - onProgress?.call(0.02, '正在读取内置系统资源包...'); - final byteData = await rootBundle.load(distro.assetPath!); - final bytes = byteData.buffer.asUint8List(); - - await DistroInstaller.installFromBytes( - tarGzBytes: bytes, - targetDir: targetDir, - onProgress: onProgress, - ); - return; - } - - // 远程下载模式扩展点 - if (distro.downloadUrl != null) { - throw UnsupportedError('远程下载安装功能后续支持,请先使用内置版本'); - } - - throw StateError('该发行版既无内置 asset 也无下载链接: $distroId'); } - /// 从用户本地指定的 .tar.gz 文件安装自定义系统 - Future installFromCustomTarGz( - String distroId, - File tarGzFile, { + /// 从应用内置资源导入 Alpine Linux 系统实例 + /// + /// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统) + Future importBuiltinAlpine({ + required String systemName, InstallProgressCallback? onProgress, + bool Function()? isCancelled, }) async { - final targetDir = await getDistroRootDir(distroId); - final bytes = await tarGzFile.readAsBytes(); + await validateSystemName(systemName); + + final assetPath = DistroInfo.builtinAlpineAssetPath; + onProgress?.call(0.02, '正在读取应用内置系统资源包...'); + final byteData = await rootBundle.load(assetPath); + final bytes = byteData.buffer.asUint8List(); + + final targetDir = await getSystemRootDir(systemName); await DistroInstaller.installFromBytes( tarGzBytes: bytes, targetDir: targetDir, onProgress: onProgress, + isCancelled: isCancelled, ); } - /// 卸载并清除指定发行版的 rootfs 目录 - Future uninstallDistro(String distroId) async { - if (distroId == 'host') return; + /// 从用户本地指定的 .tar.gz 压缩包导入外部系统实例 + Future importFromCustomTarGz({ + required String systemName, + required File tarGzFile, + InstallProgressCallback? onProgress, + bool Function()? isCancelled, + }) async { + await validateSystemName(systemName); + + if (!tarGzFile.existsSync()) { + throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}'); + } + + onProgress?.call(0.02, '正在读取外部系统压缩包...'); + final bytes = await tarGzFile.readAsBytes(); + + final targetDir = await getSystemRootDir(systemName); + + await DistroInstaller.installFromBytes( + tarGzBytes: bytes, + targetDir: targetDir, + onProgress: onProgress, + isCancelled: isCancelled, + ); + } + + /// 高危操作:彻底删除指定系统实例及其所有存储数据 + Future deleteSystem(String systemName) async { + if (systemName == 'host') return; final baseDir = await getBaseDistrosDir(); - final distroDir = Directory(p.join(baseDir.path, distroId)); - if (distroDir.existsSync()) { - distroDir.deleteSync(recursive: true); + final systemDir = Directory(p.join(baseDir.path, systemName)); + if (!systemDir.existsSync()) return; + + for (int attempt = 0; attempt < 3; attempt++) { + try { + if (!systemDir.existsSync()) break; + await systemDir.delete(recursive: true); + break; + } catch (e) { + if (Platform.isLinux || Platform.isAndroid) { + try { + await Process.run('chmod', ['-R', '777', systemDir.path]); + } catch (_) {} + } + await Future.delayed(const Duration(milliseconds: 60)); + if (attempt == 2) { + try { + if (systemDir.existsSync()) { + systemDir.deleteSync(recursive: true); + } + } catch (_) {} + } + } } } + static const MethodChannel _nativeChannel = MethodChannel('com.example.code_editor/native'); + String? _cachedProotPath; + String? _cachedNativeDir; + + /// 获取 App 原生动态库目录路径(用于定位 libproot.so 与 libtalloc.so) + Future getNativeLibraryDir() async { + if (_cachedNativeDir != null) return _cachedNativeDir; + if (Platform.isAndroid) { + try { + final dir = await _nativeChannel.invokeMethod('getNativeLibraryDir'); + if (dir != null && dir.isNotEmpty) { + _cachedNativeDir = dir; + return dir; + } + } catch (e) { + debugPrint('获取原生动态库目录失败: $e'); + } + } + return null; + } + + /// 获取 proot 可执行程序的物理路径(优先检测 nativeLibraryDir/libproot.so) + Future getProotExecutablePath() async { + if (_cachedProotPath != null && File(_cachedProotPath!).existsSync()) { + return _cachedProotPath!; + } + + final nativeDir = await getNativeLibraryDir(); + if (nativeDir != null) { + final soPath = p.join(nativeDir, 'libproot.so'); + if (File(soPath).existsSync()) { + _cachedProotPath = soPath; + return soPath; + } + } + + return 'proot'; + } + /// 构建 PRoot 容器启动命令与环境参数 /// - /// [distroId] 发行版标识符 + /// [systemName] 当前选择的系统名称 /// [workspacePath] 挂载的代码工程路径(挂载到容器内部的 /workspace) - /// [prootPath] proot 二进制路径(默认可传入 'proot' 或设备内部特定路径) - /// [customCommand] 自定义初始执行命令(默认进入交互式 login shell) + /// [prootPath] proot 二进制路径 + /// [customCommand] 自定义执行命令 Future buildLaunchConfig({ - required String distroId, + required String systemName, String? workspacePath, String prootPath = 'proot', String? customCommand, }) async { - final distro = getDistro(distroId) ?? DistroInfo.alpine; - - // 1. 本地 Shell 特殊处理:无需 PRoot - if (distroId == 'host') { + // 1. 本地 Shell 特殊处理 + if (systemName == 'host') { final initialDir = (workspacePath != null && Directory(workspacePath).existsSync()) ? workspacePath : Directory.current.path; final args = customCommand != null ? ['-c', customCommand] : []; return ProotLaunchConfig( - executable: distro.defaultShell, + executable: '/system/bin/sh', arguments: args, environment: { 'TERM': 'xterm-256color', @@ -200,17 +273,53 @@ class DistroManager { } // 2. Linux 容器 (PRoot 隔离环境) - final rootDir = await getDistroRootDir(distroId); - final targetShell = distro.defaultShell; + final rootDir = await getSystemRootDir(systemName); + final nativeDir = await getNativeLibraryDir(); + final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath; + const targetShell = '/bin/sh'; + + // 确保容器内 DNS 配置存在(对标 proot-distro,保证网络连通与 apk/curl 正常解析) + await _ensureGuestDns(rootDir); + + // 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失) + final shmDir = await _ensureShmDir(systemName); + + // 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范) + final l2sDir = await _ensureL2sDir(systemName); + + // 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据) + final sysdataDir = await _ensureSysdataDir(systemName); + + String tmpPath = '/tmp'; + try { + tmpPath = (await getTemporaryDirectory()).path; + } catch (_) { + tmpPath = '/tmp'; + } final args = [ + '--kill-on-exit', + '--link2symlink', '-0', // 模拟 root 权限 (uid 0) + '-k', '5.4.0-proot', // 伪装内核版本(解决 musl libc 调用 clone3/ppoll 时的 Function not implemented) + '-L', // 修复 lstat 符号链接大小属性 '-r', rootDir.path, // 根文件系统路径 - '-b', '/dev', // 挂载标准设备节点 + '-b', '/dev', // 挂载标准设备节点(宿主已有 /dev/stdin, stdout, stderr 等软链接) + '-b', '/dev/urandom:/dev/random', // 补充随机数设备节点 + if (shmDir != null) ...['-b', '${shmDir.path}:/dev/shm'], // 挂载独立 POSIX 共享内存 '-b', '/proc', // 挂载进程信息 '-b', '/sys', // 挂载系统信息 + if (sysdataDir != null) ...[ + '-b', '${p.join(sysdataDir.path, 'sys_empty')}:/sys/fs/selinux', + '-b', '${p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap')}:/proc/sys/kernel/cap_last_cap', + '-b', '${p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches')}:/proc/sys/fs/inotify/max_user_watches', + ], ]; + if (Directory(tmpPath).existsSync()) { + args.addAll(['-b', '$tmpPath:/tmp']); + } + // 挂载工作区 String containerWorkDir = '/root'; if (workspacePath != null && Directory(workspacePath).existsSync()) { @@ -221,6 +330,26 @@ class DistroManager { // 设置容器内工作目录 args.addAll(['-w', containerWorkDir]); + // 用 /usr/bin/env -i 彻底隔离宿主(Android app 进程)继承的环境变量, + // 只注入标准纯净的容器环境变量;若修复 Shim 已部署则注入 LD_PRELOAD。 + // Shim 的两项职责见 DistroInstaller.ensureSeccompShim 的注释。 + await DistroInstaller.ensureSeccompShim(rootDir); + final shimFile = File(p.join(rootDir.path, 'lib', 'libfix_seccomp.so')); + final hasShim = shimFile.existsSync(); + + final guestEnvArgs = [ + '/usr/bin/env', + '-i', + 'HOME=/root', + 'USER=root', + 'TERM=xterm-256color', + 'LANG=C.UTF-8', + 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + if (hasShim) 'LD_PRELOAD=/lib/libfix_seccomp.so', + ]; + + args.addAll(guestEnvArgs); + // 登录 Shell 或自定义命令 if (customCommand != null && customCommand.isNotEmpty) { args.addAll([targetShell, '-c', customCommand]); @@ -234,14 +363,106 @@ class DistroManager { 'TERM': 'xterm-256color', 'LANG': 'C.UTF-8', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - 'TMPDIR': '/tmp', + 'TMPDIR': tmpPath, + 'PROOT_TMP_DIR': tmpPath, + if (l2sDir != null) 'PROOT_L2S_DIR': l2sDir.path, + if (nativeDir != null) 'LD_LIBRARY_PATH': nativeDir, }; + // Process.start 的宿主工作目录必须在 Android 宿主真实存在 + final hostWorkDir = rootDir.path; + return ProotLaunchConfig( - executable: prootPath, + executable: effectiveProot, arguments: args, environment: env, - workingDirectory: containerWorkDir, + workingDirectory: hostWorkDir, ); } + + /// 确保容器内具备标准 DNS 解析文件 `/etc/resolv.conf`(对标 proot-distro) + Future _ensureGuestDns(Directory rootDir) async { + try { + final etcDir = Directory(p.join(rootDir.path, 'etc')); + if (!etcDir.existsSync()) { + etcDir.createSync(recursive: true); + } + final resolvConf = File(p.join(etcDir.path, 'resolv.conf')); + if (!resolvConf.existsSync() || (await resolvConf.length()) == 0) { + // "可达优先"排序:国内公共 DNS 在前(8.8.8.8/1.1.1.1 在国内常被丢包, + // 排在首位会让 musl/glibc 解析器先等一次超时)。与 DistroInstaller + // 的 guestResolvConf 保持一致。 + await resolvConf.writeAsString( + DistroInstaller.guestResolvConf, + flush: true, + ); + } + } catch (e) { + debugPrint('配置容器 DNS 失败 (非阻塞): $e'); + } + } + + /// 确保容器实例拥有独立的 POSIX 共享内存目录(对标 proot-distro shm.py) + Future _ensureShmDir(String systemName) async { + try { + final baseDir = await getBaseDistrosDir(); + final shmDir = Directory(p.join(baseDir.path, systemName, 'shm')); + if (!shmDir.existsSync()) { + shmDir.createSync(recursive: true); + } + return shmDir; + } catch (e) { + debugPrint('创建容器 shm 目录失败 (非阻塞): $e'); + return null; + } + } + + /// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py) + Future _ensureL2sDir(String systemName) async { + try { + final baseDir = await getBaseDistrosDir(); + final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s')); + if (!l2sDir.existsSync()) { + l2sDir.createSync(recursive: true); + } + return l2sDir; + } catch (e) { + debugPrint('创建容器 .l2s 目录失败 (非阻塞): $e'); + return null; + } + } + + /// 确保容器实例拥有独立的 sysdata 桩目录与 SELinux 覆盖节点(对标 proot-distro sysdata.py) + Future _ensureSysdataDir(String systemName) async { + try { + final baseDir = await getBaseDistrosDir(); + final sysdataDir = Directory(p.join(baseDir.path, systemName, 'sysdata')); + if (!sysdataDir.existsSync()) { + sysdataDir.createSync(recursive: true); + } + + // 1. 空目录用于覆盖 /sys/fs/selinux(禁用 selinux 检测) + final emptyDir = Directory(p.join(sysdataDir.path, 'sys_empty')); + if (!emptyDir.existsSync()) { + emptyDir.createSync(recursive: true); + } + + // 2. /proc/sys/kernel/cap_last_cap 桩 + final capFile = File(p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap')); + if (!capFile.existsSync()) { + capFile.writeAsStringSync('40\n'); + } + + // 3. /proc/sys/fs/inotify/max_user_watches 桩 + final inotifyFile = File(p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches')); + if (!inotifyFile.existsSync()) { + inotifyFile.writeAsStringSync('4096\n'); + } + + return sysdataDir; + } catch (e) { + debugPrint('创建容器 sysdata 目录失败 (非阻塞): $e'); + return null; + } + } } diff --git a/lib/views/terminal_view.dart b/lib/views/terminal_view.dart index 066a3be..70a4019 100644 --- a/lib/views/terminal_view.dart +++ b/lib/views/terminal_view.dart @@ -1,14 +1,17 @@ +import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/app_font.dart'; -import 'package:code_editor/models/distro_info.dart'; import 'package:code_editor/models/terminal_session.dart'; import 'package:code_editor/providers/distro_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/widgets/distro_extract_dialog.dart'; +import 'package:code_editor/widgets/distro_selector_dialog.dart'; import 'package:code_editor/widgets/terminal_drawer.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:xterm/xterm.dart' as xterm; -/// 终端视图(支持全屏会话保持、右侧抽屉多会话管理与交互) +/// 终端视图(支持多系统实例切换、全屏会话保持、右侧抽屉多会话管理与交互) class TerminalView extends StatefulWidget { const TerminalView({super.key}); @@ -22,10 +25,56 @@ class _TerminalViewState extends State { @override void initState() { super.initState(); - // 懒加载:进入终端 view 时,若无会话则自动创建首个会话 - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { - context.read().ensureInitialized(); + // 首次或进入终端时:检测已安装系统。如果不存在任何系统,自动从软件内置导入 alpine + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final distroProvider = context.read(); + final l10n = AppLocalizations.of(context)!; + final defaultSessionName = l10n.sessionDefaultName; + + if (distroProvider == null) { + context.read().ensureInitialized(defaultName: defaultSessionName); + return; + } + + await distroProvider.init(); + if (!mounted) return; + + if (!distroProvider.hasAnySystem) { + // 自动从软件内置资源导入 alpine,名称即为 alpine + final success = await DistroExtractDialog.show( + context: context, + systemName: 'alpine', + task: (onProgress, isCancelled) { + return distroProvider.importBuiltinAlpine( + systemName: 'alpine', + onProgress: onProgress, + isCancelled: isCancelled, + ); + }, + ); + + if (success && mounted) { + final termProvider = context.read(); + if (termProvider.isEmpty) { + termProvider.createSession( + name: defaultSessionName, + distroId: 'alpine', + activate: true, + ); + } + } + } else { + // 已有系统,确保初始化首个会话 + final termProvider = context.read(); + if (termProvider.isEmpty) { + final system = distroProvider.selectedSystem ?? 'alpine'; + termProvider.createSession( + name: defaultSessionName, + distroId: system, + activate: true, + ); + } } }); } @@ -33,13 +82,17 @@ class _TerminalViewState extends State { @override Widget build(BuildContext context) { final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; final provider = context.watch(); + final distroProvider = context.watch(); + final activeSession = provider.activeSession; final sessions = provider.sessions; final activeIndex = provider.activeIndex; - final titleText = activeSession?.name ?? '会话'; - const subtitleText = '终端'; + final titleText = activeSession?.name ?? l10n.sessionDefaultName; + final currentSystem = activeSession?.distroId ?? distroProvider?.selectedSystem; + final subtitleText = currentSystem != null ? l10n.terminalWithSystem(currentSystem) : l10n.terminal; return Scaffold( key: _scaffoldKey, @@ -48,7 +101,7 @@ class _TerminalViewState extends State { foregroundColor: theme.colorScheme.onSurface, leading: IconButton( icon: const Icon(Icons.arrow_back), - tooltip: '返回', + tooltip: l10n.back, onPressed: () => Navigator.of(context).pop(), ), title: Column( @@ -74,9 +127,17 @@ class _TerminalViewState extends State { ], ), actions: [ + // 系统选择与管理按钮(位于会话列表左侧) + IconButton( + icon: const Icon(Icons.dns_outlined), + tooltip: l10n.systemManagementTooltip, + onPressed: () { + DistroSelectorDialog.show(context); + }, + ), IconButton( icon: const Icon(Icons.format_list_bulleted), - tooltip: '会话列表', + tooltip: l10n.sessionListTooltip, onPressed: () { _scaffoldKey.currentState?.openEndDrawer(); }, @@ -85,10 +146,10 @@ class _TerminalViewState extends State { ), endDrawer: const TerminalDrawer(), body: sessions.isEmpty - ? const Center( + ? Center( child: Text( - '暂无活跃会话', - style: TextStyle(color: Colors.grey), + l10n.noActiveSessions, + style: const TextStyle(color: Colors.grey), ), ) : IndexedStack( @@ -105,7 +166,7 @@ class _TerminalViewState extends State { } } -/// 单个终端会话的终端渲染与交互容器 +/// 单个真实交互式终端会话的终端渲染与交互容器 class _TerminalSessionBody extends StatefulWidget { final TerminalSession session; @@ -125,224 +186,26 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { final settings = context.watch(); final terminalFont = settings?.terminalFont ?? AppFonts.terminalMonospace; + final terminalStyle = xterm.TerminalStyle( + fontSize: 13.0, + fontFamily: terminalFont.fontFamily ?? 'monospace', + fontFamilyFallback: terminalFont.fallback, + ); + return Container( color: const Color(0xFF181818), child: SafeArea( top: false, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - // 点击终端空白区域自动聚焦输入框 - session.focusNode.requestFocus(); - }, - child: Column( - children: [ - if (_buildDistroStatusBar(context, session) != null) - _buildDistroStatusBar(context, session)!, - // 终端输出流滚动区域 - Expanded( - child: ListView.builder( - controller: session.scrollController, - padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), - itemCount: session.outputLines.length, - itemBuilder: (context, index) { - final line = session.outputLines[index]; - final isPrompt = line.startsWith('\$'); - return SelectableText( - line.isEmpty ? ' ' : line, - style: TextStyle( - fontFamily: terminalFont.fontFamily, - fontFamilyFallback: terminalFont.fallback, - fontSize: 13.0, - color: isPrompt ? const Color(0xFF64B5F6) : const Color(0xFFD4D4D4), - height: 1.35, - ), - ); - }, - ), - ), - const Divider(height: 1, color: Color(0xFF2A2A2A)), - // 终端命令行交互输入框 - Container( - color: const Color(0xFF1E1E1E), - padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0), - child: Row( - children: [ - Text( - '\$ ', - style: TextStyle( - color: const Color(0xFF4CAF50), - fontWeight: FontWeight.bold, - fontFamily: terminalFont.fontFamily, - fontFamilyFallback: terminalFont.fallback, - fontSize: 14.0, - ), - ), - Expanded( - child: TextField( - controller: session.inputController, - focusNode: session.focusNode, - style: TextStyle( - color: Colors.white, - fontFamily: terminalFont.fontFamily, - fontFamilyFallback: terminalFont.fallback, - fontSize: 13.0, - ), - cursorColor: const Color(0xFF4CAF50), - decoration: const InputDecoration( - hintText: '输入命令...', - hintStyle: TextStyle(color: Colors.white38, fontSize: 13.0), - border: InputBorder.none, - isDense: true, - contentPadding: EdgeInsets.symmetric(vertical: 8.0), - ), - onSubmitted: (text) { - if (text.isNotEmpty) { - context.read().executeCommand(session, text); - session.inputController.clear(); - session.focusNode.requestFocus(); - } - }, - ), - ), - IconButton( - icon: const Icon(Icons.send, size: 18, color: Colors.white70), - tooltip: '发送命令', - visualDensity: VisualDensity.compact, - onPressed: () { - final text = session.inputController.text; - if (text.isNotEmpty) { - context.read().executeCommand(session, text); - session.inputController.clear(); - session.focusNode.requestFocus(); - } - }, - ), - ], - ), - ), - ], - ), + child: xterm.TerminalView( + session.terminal, + focusNode: session.focusNode, + autofocus: true, + theme: xterm.TerminalThemes.defaultTheme, + textStyle: terminalStyle, + cursorType: xterm.TerminalCursorType.block, + padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0), ), ), ); } - - Widget? _buildDistroStatusBar(BuildContext context, TerminalSession session) { - if (session.distroId != 'alpine') return null; - - final distroProvider = context.watch(); - if (distroProvider == null) return null; - final status = distroProvider.getStatus('alpine'); - - if (status == DistroStatus.installed) return null; - - if (status == DistroStatus.installing) { - final progress = distroProvider.getProgress('alpine'); - final msg = distroProvider.getStatusMessage('alpine'); - return Container( - color: const Color(0xFF252526), - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - const SizedBox( - width: 14, - height: 14, - child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blueAccent), - ), - const SizedBox(width: 8), - Expanded( - child: Text( - msg.isNotEmpty ? msg : '正在初始化 Alpine 环境...', - style: const TextStyle(color: Colors.white, fontSize: 12), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - Text( - '${(progress * 100).toInt()}%', - style: const TextStyle(color: Colors.white70, fontSize: 12), - ), - ], - ), - const SizedBox(height: 6), - LinearProgressIndicator( - value: progress > 0 ? progress : null, - backgroundColor: Colors.white12, - valueColor: const AlwaysStoppedAnimation(Colors.blueAccent), - minHeight: 3, - ), - ], - ), - ); - } - - if (status == DistroStatus.error) { - return Container( - color: Colors.red.shade900.withValues(alpha: 0.8), - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0), - child: Row( - children: [ - const Icon(Icons.error_outline, size: 16, color: Colors.white), - const SizedBox(width: 8), - Expanded( - child: Text( - distroProvider.getStatusMessage('alpine').isNotEmpty - ? distroProvider.getStatusMessage('alpine') - : 'Alpine 初始化失败', - style: const TextStyle(color: Colors.white, fontSize: 12), - ), - ), - TextButton( - onPressed: () => distroProvider.installDistro('alpine'), - child: const Text('重试', style: TextStyle(color: Colors.yellowAccent)), - ), - ], - ), - ); - } - - // notInstalled - return Container( - color: const Color(0xFF1E293B), - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), - child: Row( - children: [ - const Icon(Icons.layers_outlined, size: 18, color: Colors.lightBlueAccent), - const SizedBox(width: 10), - const Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - 'Alpine Linux 尚未就绪', - style: TextStyle(color: Colors.white, fontSize: 12.5, fontWeight: FontWeight.bold), - ), - Text( - '内置极速解压包 (~3.9MB),点击立即初始化即可运行', - style: TextStyle(color: Colors.white70, fontSize: 11), - ), - ], - ), - ), - ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.blueAccent, - foregroundColor: Colors.white, - visualDensity: VisualDensity.compact, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0), - textStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold), - ), - onPressed: () { - distroProvider.installDistro('alpine'); - }, - child: const Text('一键初始化'), - ), - ], - ), - ); - } } diff --git a/lib/widgets/distro_extract_dialog.dart b/lib/widgets/distro_extract_dialog.dart new file mode 100644 index 0000000..2492d7d --- /dev/null +++ b/lib/widgets/distro_extract_dialog.dart @@ -0,0 +1,163 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/services/distro_installer.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:flutter/material.dart'; + +/// 同步前台解压进度弹窗(模态不可遮罩忽略,关闭或取消直接导致导入失败并回滚) +class DistroExtractDialog extends StatefulWidget { + final String systemName; + final Future Function(InstallProgressCallback onProgress, bool Function() isCancelled) task; + + const DistroExtractDialog({ + super.key, + required this.systemName, + required this.task, + }); + + /// 快速拉起解压进程模态弹窗 + /// 返回 true 表示导入成功,false 表示取消或失败 + static Future show({ + required BuildContext context, + required String systemName, + required Future Function(InstallProgressCallback onProgress, bool Function() isCancelled) task, + }) async { + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (ctx) => DistroExtractDialog( + systemName: systemName, + task: task, + ), + ); + return result ?? false; + } + + @override + State createState() => _DistroExtractDialogState(); +} + +class _DistroExtractDialogState extends State { + double _progress = 0.0; + String? _message; + bool _isCancelled = false; + bool _isFinished = false; + + @override + void initState() { + super.initState(); + _startTask(); + } + + Future _startTask() async { + try { + await widget.task( + (prog, msg) { + if (mounted && !_isCancelled) { + setState(() { + _progress = prog; + _message = msg; + }); + } + }, + () => _isCancelled, + ); + + if (mounted && !_isCancelled) { + _isFinished = true; + Navigator.of(context).pop(true); + } + } catch (e) { + if (mounted) { + final l10n = AppLocalizations.of(context)!; + if (e is DistroInstallCancelledException || _isCancelled) { + DialogUtils.showToast(context, l10n.cancelledImportSystem(widget.systemName)); + } else { + DialogUtils.showErrorToast(context, l10n.importFailed(e.toString())); + } + Navigator.of(context).pop(false); + } + } + } + + void _handleCancel() { + if (_isFinished) return; + final l10n = AppLocalizations.of(context)!; + setState(() { + _isCancelled = true; + _message = l10n.cancellingAndCleaning; + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final percentInt = (_progress * 100).clamp(0, 100).toInt(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, _) { + if (didPop) return; + _handleCancel(); + }, + child: AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + ), + title: Row( + children: [ + const Icon(Icons.archive_outlined, size: 22, color: Colors.blueAccent), + const SizedBox(width: 10), + Expanded( + child: Text( + l10n.importingSystemTitle(widget.systemName), + style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _message ?? l10n.preparingInitialization, + style: TextStyle( + fontSize: 13.0, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 14), + LinearProgressIndicator( + value: _progress > 0 ? _progress : null, + minHeight: 6, + borderRadius: BorderRadius.circular(3), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: Text( + '$percentInt%', + style: TextStyle( + fontSize: 12.0, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: _isCancelled ? null : _handleCancel, + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.error, + ), + child: Text(_isCancelled ? l10n.interrupting : l10n.cancelImport), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/distro_selector_dialog.dart b/lib/widgets/distro_selector_dialog.dart new file mode 100644 index 0000000..4a4f6f1 --- /dev/null +++ b/lib/widgets/distro_selector_dialog.dart @@ -0,0 +1,314 @@ +import 'dart:io'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:code_editor/widgets/distro_extract_dialog.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; + +/// 独立的 Linux 系统选择与管理对话框 +class DistroSelectorDialog extends StatelessWidget { + const DistroSelectorDialog({super.key}); + + /// 打开系统选择与管理对话框 + static Future show(BuildContext context) { + return showDialog( + context: context, + builder: (ctx) => const DistroSelectorDialog(), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final distroProvider = context.watch(); + final systems = distroProvider.installedSystems; + final selectedSystem = distroProvider.selectedSystem; + + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + ), + titlePadding: const EdgeInsets.fromLTRB(20.0, 16.0, 12.0, 8.0), + contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + title: Row( + children: [ + const Icon(Icons.dns_outlined, size: 22, color: Colors.blueAccent), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.systemManagement, + style: const TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold), + ), + ), + // 导入按钮与下拉选项 + PopupMenuButton( + icon: const Icon(Icons.add_circle_outline, color: Colors.blueAccent), + tooltip: l10n.importNewSystem, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12.0), + ), + onSelected: (action) => _handleImportAction(context, action), + itemBuilder: (context) => [ + PopupMenuItem( + value: 'builtin', + child: Row( + children: [ + const Icon(Icons.layers_outlined, size: 18), + const SizedBox(width: 8), + Text(l10n.importBuiltinAlpine), + ], + ), + ), + PopupMenuItem( + value: 'external', + child: Row( + children: [ + const Icon(Icons.folder_open_outlined, size: 18), + const SizedBox(width: 8), + Text(l10n.importExternalTarGz), + ], + ), + ), + ], + ), + ], + ), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 8.0), + child: Text( + l10n.selectSystemDefaultPrompt, + style: TextStyle( + fontSize: 12.0, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + const Divider(height: 1), + Flexible( + child: systems.isEmpty + ? Container( + padding: const EdgeInsets.symmetric(vertical: 32.0), + alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.layers_clear_outlined, + size: 40, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + ), + const SizedBox(height: 8), + Text( + l10n.noSystemsPrompt, + style: TextStyle( + fontSize: 13.0, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ) + : ListView.builder( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 4.0), + itemCount: systems.length, + itemBuilder: (context, index) { + final system = systems[index]; + final isSelected = system == selectedSystem; + + return Container( + margin: const EdgeInsets.symmetric(vertical: 3.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8.0), + border: Border.all( + color: isSelected + ? theme.colorScheme.primary.withValues(alpha: 0.5) + : theme.colorScheme.outlineVariant.withValues(alpha: 0.4), + width: 1.0, + ), + ), + child: Material( + color: isSelected + ? theme.colorScheme.primaryContainer.withValues(alpha: 0.4) + : Colors.transparent, + borderRadius: BorderRadius.circular(8.0), + child: ListTile( + dense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 2.0), + title: Text( + system, + style: TextStyle( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + color: isSelected ? theme.colorScheme.primary : null, + fontSize: 14.0, + ), + ), + trailing: IconButton( + icon: Icon( + Icons.delete_outline, + color: theme.colorScheme.error, + size: 20, + ), + tooltip: l10n.deleteSystemTooltip, + onPressed: () => _handleDeleteSystem(context, system), + ), + onTap: () { + distroProvider.selectSystem(system); + }, + ), + ), + ); + }, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.done), + ), + ], + ); + } + + /// 处理导入菜单操作 + Future _handleImportAction(BuildContext context, String action) async { + final distroProvider = context.read(); + final l10n = AppLocalizations.of(context)!; + + if (action == 'builtin') { + // 1. 从内置 Alpine 导入 + final defaultName = _generateUniqueSystemName('alpine', distroProvider.installedSystems); + final systemName = await DialogUtils.showInputDialog( + context, + title: l10n.importBuiltinAlpineTitle, + hintText: l10n.systemNameHintWithDefault(defaultName), + initialValue: defaultName, + ); + + if (systemName == null || systemName.trim().isEmpty || !context.mounted) return; + final cleanName = systemName.trim(); + + // 模态同步解压 + final success = await DistroExtractDialog.show( + context: context, + systemName: cleanName, + task: (onProgress, isCancelled) { + return distroProvider.importBuiltinAlpine( + systemName: cleanName, + onProgress: onProgress, + isCancelled: isCancelled, + ); + }, + ); + + if (success && context.mounted) { + DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName)); + } + } else if (action == 'external') { + // 2. 从外部选择 .tar.gz 压缩包导入 + final result = await FilePicker.platform.pickFiles( + type: FileType.any, + ); + + if (result == null || result.files.single.path == null || !context.mounted) return; + final filePath = result.files.single.path!; + final file = File(filePath); + + // 提取默认名称(去掉 .tar.gz, .tgz 等后缀) + String baseName = p.basename(filePath); + if (baseName.endsWith('.tar.gz')) { + baseName = baseName.substring(0, baseName.length - 7); + } else if (baseName.endsWith('.tgz')) { + baseName = baseName.substring(0, baseName.length - 4); + } else { + baseName = p.basenameWithoutExtension(filePath); + } + baseName = baseName.replaceAll(RegExp(r'[^a-zA-Z0-9_\-]'), '_'); + if (baseName.isEmpty) baseName = 'custom_linux'; + + final defaultName = _generateUniqueSystemName(baseName, distroProvider.installedSystems); + + final systemName = await DialogUtils.showInputDialog( + context, + title: l10n.importExternalSystemTitle, + hintText: l10n.systemNameHint, + initialValue: defaultName, + ); + + if (systemName == null || systemName.trim().isEmpty || !context.mounted) return; + final cleanName = systemName.trim(); + + // 模态同步解压 + final success = await DistroExtractDialog.show( + context: context, + systemName: cleanName, + task: (onProgress, isCancelled) { + return distroProvider.importFromCustomTarGz( + systemName: cleanName, + tarGzFile: file, + onProgress: onProgress, + isCancelled: isCancelled, + ); + }, + ); + + if (success && context.mounted) { + DialogUtils.showSuccessToast(context, l10n.externalSystemImportSuccess(cleanName)); + } + } + } + + /// 高危操作:二次确认删除系统 + Future _handleDeleteSystem(BuildContext context, String systemName) async { + final l10n = AppLocalizations.of(context)!; + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n.deleteSystemConfirmTitle, + message: l10n.deleteSystemConfirmMessage(systemName), + confirmText: l10n.permanentDelete, + ); + + if (confirmed && context.mounted) { + final distroProvider = context.read(); + final terminalProvider = context.read(); + try { + await distroProvider.deleteSystem(systemName); + terminalProvider?.removeSessionsForDistro(systemName); + if (!distroProvider.hasAnySystem) { + terminalProvider?.clearAllSessions(); + } + if (context.mounted) { + DialogUtils.showToast(context, l10n.deleteSystemSuccess(systemName)); + } + } catch (e) { + if (context.mounted) { + DialogUtils.showErrorToast(context, l10n.deleteSystemFailed(e.toString())); + } + } + } + } + + /// 自动生成不重复的系统实例名 + String _generateUniqueSystemName(String prefix, List existingSystems) { + if (!existingSystems.contains(prefix)) return prefix; + int index = 1; + while (existingSystems.contains('${prefix}_$index')) { + index++; + } + return '${prefix}_$index'; + } +} diff --git a/lib/widgets/terminal_drawer.dart b/lib/widgets/terminal_drawer.dart index c5e7557..b639d08 100644 --- a/lib/widgets/terminal_drawer.dart +++ b/lib/widgets/terminal_drawer.dart @@ -1,4 +1,7 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/distro_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/widgets/terminal_session_item_widget.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -10,6 +13,7 @@ class TerminalDrawer extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; final provider = context.watch(); final sessions = provider.sessions; final activeIndex = provider.activeIndex; @@ -30,7 +34,7 @@ class TerminalDrawer extends StatelessWidget { child: Row( children: [ Text( - '会话', + l10n.sessionDrawerTitle, style: theme.textTheme.titleMedium?.copyWith( fontWeight: FontWeight.bold, color: theme.colorScheme.onSurface, @@ -39,10 +43,20 @@ class TerminalDrawer extends StatelessWidget { const Spacer(), IconButton( icon: const Icon(Icons.add), - tooltip: '添加终端', + tooltip: l10n.addTerminalTooltip, onPressed: () { - // 直接添加终端,但不跳转 - provider.createSession(name: '会话', distroId: 'alpine', activate: false); + final distroProvider = context.read(); + final currentSystem = distroProvider?.selectedSystem; + if (currentSystem == null) { + DialogUtils.showToast(context, l10n.noSystemSelectedWarning); + return; + } + // 基于当前选择的系统创建新终端 + provider.createSession( + name: l10n.sessionDefaultName, + distroId: currentSystem, + activate: false, + ); }, ), ], @@ -56,7 +70,7 @@ class TerminalDrawer extends StatelessWidget { child: sessions.isEmpty ? Center( child: Text( - '暂无会话,请点击右上角添加', + l10n.noSessionsInDrawerPrompt, style: TextStyle( color: theme.colorScheme.onSurfaceVariant, fontSize: 13.0, diff --git a/lib/widgets/terminal_session_item_widget.dart b/lib/widgets/terminal_session_item_widget.dart index 4c8a91c..b0ed2a2 100644 --- a/lib/widgets/terminal_session_item_widget.dart +++ b/lib/widgets/terminal_session_item_widget.dart @@ -1,3 +1,4 @@ +import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/terminal_session.dart'; import 'package:code_editor/providers/terminal_provider.dart'; import 'package:code_editor/utils/dialog_utils.dart'; @@ -22,8 +23,8 @@ class TerminalSessionItemWidget extends StatelessWidget { final theme = Theme.of(context); final displayIndex = index + 1; // 索引从 1 开始 final titleText = '($displayIndex) ${session.name}'; + final badgeLabel = session.distroId; final isHost = session.distroId == 'host'; - final badgeLabel = isHost ? 'Host' : 'Alpine'; final textStyle = theme.textTheme.bodyMedium?.copyWith( fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, @@ -122,6 +123,7 @@ class TerminalSessionItemWidget extends StatelessWidget { ); final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; final onSurfaceColor = theme.colorScheme.onSurface; final selectedAction = await showMenu( @@ -141,14 +143,14 @@ class TerminalSessionItemWidget extends StatelessWidget { _buildMenuItem( value: 'rename', icon: Icons.edit_outlined, - title: '重命名', + title: l10n.rename, color: onSurfaceColor, ), const PopupMenuDivider(), _buildMenuItem( value: 'delete', icon: Icons.delete_outline, - title: '删除', + title: l10n.delete, color: theme.colorScheme.error, isDestructive: true, ), @@ -184,13 +186,14 @@ class TerminalSessionItemWidget extends StatelessWidget { void _handleMenuAction(BuildContext context, String action, int displayIndex) async { final provider = context.read(); + final l10n = AppLocalizations.of(context)!; switch (action) { case 'rename': final newName = await DialogUtils.showInputDialog( context, - title: '重命名', - hintText: '新名称', + title: l10n.rename, + hintText: l10n.newName, initialValue: session.name, ); if (newName != null && newName.trim().isNotEmpty && newName.trim() != session.name) { @@ -201,8 +204,8 @@ class TerminalSessionItemWidget extends StatelessWidget { case 'delete': final confirmed = await DialogUtils.showDestructiveConfirmDialog( context, - title: '确认删除', - message: '确定要删除终端 "($displayIndex) ${session.name}" 吗?', + title: l10n.confirmDelete, + message: l10n.confirmDeleteTerminalSession(displayIndex, session.name), ); if (confirmed && context.mounted) { provider.removeSession(session.id); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index be1ee3e..9e99d62 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + flutter_pty jni ) diff --git a/pubspec.lock b/pubspec.lock index b7fa831..105fb5c 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -65,6 +65,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" cross_file: dependency: transitive description: @@ -89,6 +97,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" + url: "https://pub.dev" + source: hosted + version: "2.1.0" fake_async: dependency: transitive description: @@ -147,6 +163,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.35" + flutter_pty: + dependency: "direct main" + description: + name: flutter_pty + sha256: c2f3b3160b519ac820fa3f6ef175361f2dfc52c557465643589542e9f229ad66 + url: "https://pub.dev" + source: hosted + version: "0.4.2" flutter_test: dependency: "direct dev" description: flutter @@ -437,6 +461,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.1" + quiver: + dependency: transitive + description: + name: quiver + sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2 + url: "https://pub.dev" + source: hosted + version: "3.2.2" re_editor: dependency: "direct main" description: @@ -618,6 +650,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + xterm: + dependency: "direct main" + description: + name: xterm + sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2" + url: "https://pub.dev" + source: hosted + version: "4.0.0" yaml: dependency: transitive description: @@ -626,6 +666,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.4" + zmodem: + dependency: transitive + description: + name: zmodem + sha256: "3b7e5b29f3a7d8aee472029b05165a68438eff2f3f7766edf13daba1e297adbf" + url: "https://pub.dev" + source: hosted + version: "0.0.6" sdks: dart: ">=3.12.0 <4.0.0" flutter: ">=3.44.0" diff --git a/pubspec.yaml b/pubspec.yaml index d06c144..4386511 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -26,6 +26,8 @@ dependencies: permission_handler: ^13.0.2 path_provider: ^2.1.5 archive: ^3.6.1 + xterm: ^4.0.0 + flutter_pty: ^0.4.1 dev_dependencies: flutter_test: @@ -41,6 +43,8 @@ flutter: assets: - assets/distros/ + - assets/shims/x86_64/ + - assets/shims/arm64-v8a/ fonts: - family: JetBrains Mono diff --git a/test/distro_manager_test.dart b/test/distro_manager_test.dart deleted file mode 100644 index 47ade18..0000000 --- a/test/distro_manager_test.dart +++ /dev/null @@ -1,182 +0,0 @@ -import 'dart:io'; -import 'dart:typed_data'; -import 'package:archive/archive.dart'; -import 'package:code_editor/models/distro_info.dart'; -import 'package:code_editor/providers/distro_provider.dart'; -import 'package:code_editor/services/distro_installer.dart'; -import 'package:code_editor/services/distro_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:path/path.dart' as p; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - late Directory tempDir; - late DistroManager manager; - - setUp(() { - tempDir = Directory.systemTemp.createTempSync('distro_test_'); - manager = DistroManager(); - manager.customBaseDir = tempDir; - }); - - tearDown(() { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - }); - - group('DistroManager & DistroInfo Tests', () { - test('内置预设包含 Alpine, Debian, Ubuntu, Host', () { - final distros = manager.listDistros(); - expect(distros.any((d) => d.id == 'alpine'), isTrue); - expect(distros.any((d) => d.id == 'debian'), isTrue); - expect(distros.any((d) => d.id == 'ubuntu'), isTrue); - expect(distros.any((d) => d.id == 'host'), isTrue); - - final alpine = manager.getDistro('alpine'); - expect(alpine, isNotNull); - expect(alpine!.packageManager, 'apk'); - expect(alpine.defaultShell, '/bin/sh'); - expect(alpine.assetPath, contains('alpine-minirootfs')); - }); - - test('支持动态扩展注册与注销自定义发行版', () { - const customDistro = DistroInfo( - id: 'archlinux', - name: 'Arch Linux', - version: 'Rolling', - description: '滚动更新的极客发行版', - packageManager: 'pacman', - defaultShell: '/bin/bash', - isBuiltin: false, - ); - - manager.registerDistro(customDistro); - expect(manager.getDistro('archlinux'), isNotNull); - expect(manager.getDistro('archlinux')!.name, 'Arch Linux'); - - manager.unregisterDistro('archlinux'); - expect(manager.getDistro('archlinux'), isNull); - }); - - test('Host 本地环境默认视为已就绪', () async { - final isInstalled = await manager.isInstalled('host'); - expect(isInstalled, isTrue); - }); - - test('未初始化的 Linux 容器返回 false', () async { - final isInstalled = await manager.isInstalled('alpine'); - expect(isInstalled, isFalse); - }); - }); - - group('DistroInstaller 解压与网络配置测试', () { - test('创建测试 tar.gz 并使用 DistroInstaller 解压与配置', () async { - // 构造小型测试 tar.gz 镜像 - final archive = Archive(); - archive.addFile(ArchiveFile('bin/sh', 11, 'echo "sh"'.codeUnits)); - archive.addFile(ArchiveFile('etc/os-release', 18, 'NAME="Alpine Linux"'.codeUnits)); - - final tarData = TarEncoder().encode(archive); - final gzData = GZipEncoder().encode(tarData); - - final targetDir = Directory(p.join(tempDir.path, 'alpine', 'rootfs')); - - double lastProgress = 0.0; - String lastMessage = ''; - - await DistroInstaller.installFromBytes( - tarGzBytes: Uint8List.fromList(gzData!), - targetDir: targetDir, - onProgress: (prog, msg) { - lastProgress = prog; - lastMessage = msg; - }, - ); - - expect(lastProgress, 1.0); - expect(lastMessage, '系统初始化就绪!'); - - // 验证文件解压成功 - expect(File(p.join(targetDir.path, 'bin', 'sh')).existsSync(), isTrue); - expect(File(p.join(targetDir.path, 'etc', 'os-release')).existsSync(), isTrue); - - // 验证自动配置的 resolv.conf (DNS) 与 hosts - final resolvFile = File(p.join(targetDir.path, 'etc', 'resolv.conf')); - expect(resolvFile.existsSync(), isTrue); - final resolvContent = resolvFile.readAsStringSync(); - expect(resolvContent, contains('nameserver 1.1.1.1')); - expect(resolvContent, contains('nameserver 8.8.8.8')); - - final hostsFile = File(p.join(targetDir.path, 'etc', 'hosts')); - expect(hostsFile.existsSync(), isTrue); - expect(hostsFile.readAsStringSync(), contains('127.0.0.1 localhost')); - - // 验证 /workspace 挂载点目录被创建 - expect(Directory(p.join(targetDir.path, 'workspace')).existsSync(), isTrue); - - // 此时检测安装状态应为 true - final isInstalled = await manager.isInstalled('alpine'); - expect(isInstalled, isTrue); - }); - }); - - group('ProotCommandBuilder 启动配置构建测试', () { - test('构建 Host 本地启动配置', () async { - final config = await manager.buildLaunchConfig( - distroId: 'host', - workspacePath: tempDir.path, - customCommand: 'ls -la', - ); - - expect(config.executable, '/system/bin/sh'); - expect(config.arguments, ['-c', 'ls -la']); - expect(config.workingDirectory, tempDir.path); - expect(config.environment['TERM'], 'xterm-256color'); - }); - - test('构建 Alpine PRoot 容器隔离启动配置与挂载参数', () async { - final config = await manager.buildLaunchConfig( - distroId: 'alpine', - workspacePath: tempDir.path, - prootPath: '/data/data/com.example/files/proot', - ); - - expect(config.executable, '/data/data/com.example/files/proot'); - expect(config.arguments, contains('-0')); - expect(config.arguments, contains('-r')); - expect(config.arguments, contains('-b')); - expect(config.arguments, contains('/dev')); - expect(config.arguments, contains('/proc')); - expect(config.arguments, contains('/sys')); - expect(config.arguments, contains('${tempDir.path}:/workspace')); - expect(config.arguments, contains('-w')); - expect(config.arguments, contains('/workspace')); - expect(config.arguments, contains('/bin/sh')); - expect(config.arguments, contains('-l')); - - expect(config.environment['HOME'], '/root'); - expect(config.environment['USER'], 'root'); - expect(config.environment['TERM'], 'xterm-256color'); - expect(config.environment['PATH'], isNotEmpty); - - final cmdLine = config.toCommandLine(); - expect(cmdLine, contains('/data/data/com.example/files/proot')); - expect(cmdLine, contains('-0')); - }); - }); - - group('DistroProvider 状态测试', () { - test('初始状态与切换默认发行版', () async { - final provider = DistroProvider(); - expect(provider.defaultDistroId, 'alpine'); - - provider.setDefaultDistro('host'); - expect(provider.defaultDistroId, 'host'); - - await provider.checkAllStatuses(); - expect(provider.getStatus('host'), DistroStatus.installed); - }); - }); -} diff --git a/test/distro_multi_system_test.dart b/test/distro_multi_system_test.dart new file mode 100644 index 0000000..712b4d3 --- /dev/null +++ b/test/distro_multi_system_test.dart @@ -0,0 +1,298 @@ +import 'dart:io'; +import 'dart:typed_data'; +import 'package:archive/archive.dart'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/services/distro_installer.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/widgets/distro_selector_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late DistroManager manager; + + setUp(() { + SharedPreferences.setMockInitialValues({}); + tempBaseDir = Directory.systemTemp.createTempSync('distro_multi_test_'); + manager = DistroManager(); + manager.customBaseDir = tempBaseDir; + }); + + tearDown(() { + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + }); + + Uint8List createMockRootfsTarGz() { + final archive = Archive(); + archive.addFile(ArchiveFile('bin/sh', 11, 'echo "sh"'.codeUnits)); + archive.addFile(ArchiveFile('etc/os-release', 18, 'NAME="Alpine Linux"'.codeUnits)); + final tarData = TarEncoder().encode(archive); + final gzData = GZipEncoder().encode(tarData); + return Uint8List.fromList(gzData!); + } + + group('DistroManager 多系统实例管理测试', () { + test('初始状态系统列表为空', () async { + final systems = await manager.listInstalledSystems(); + expect(systems, isEmpty); + expect(await manager.hasAnySystem(), isFalse); + }); + + test('同一 Rootfs 包支持导入并创建多个独立系统实例', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'source_rootfs.tar.gz')); + tempGzFile.writeAsBytesSync(gzBytes); + + // 导入系统 1: alpine + await manager.importFromCustomTarGz( + systemName: 'alpine', + tarGzFile: tempGzFile, + ); + + // 导入系统 2: alpine_dev + await manager.importFromCustomTarGz( + systemName: 'alpine_dev', + tarGzFile: tempGzFile, + ); + + final systems = await manager.listInstalledSystems(); + expect(systems.length, equals(2)); + expect(systems, containsAll(['alpine', 'alpine_dev'])); + + // 验证各自根目录独立存在 + final alpineRootDir = await manager.getSystemRootDir('alpine'); + final devRootDir = await manager.getSystemRootDir('alpine_dev'); + expect(File(p.join(alpineRootDir.path, 'bin', 'sh')).existsSync(), isTrue); + expect(File(p.join(devRootDir.path, 'bin', 'sh')).existsSync(), isTrue); + expect(alpineRootDir.path != devRootDir.path, isTrue); + + // 验证网络配置 (resolv.conf / hosts) 与挂载点 (/workspace, /tmp) + final resolvFile = File(p.join(alpineRootDir.path, 'etc', 'resolv.conf')); + expect(resolvFile.existsSync(), isTrue); + expect(resolvFile.readAsStringSync(), contains('1.1.1.1')); + + final hostsFile = File(p.join(alpineRootDir.path, 'etc', 'hosts')); + expect(hostsFile.existsSync(), isTrue); + expect(hostsFile.readAsStringSync(), contains('127.0.0.1 localhost')); + + expect(Directory(p.join(alpineRootDir.path, 'workspace')).existsSync(), isTrue); + expect(Directory(p.join(alpineRootDir.path, 'tmp')).existsSync(), isTrue); + + // 验证已就绪状态检测 + expect(await manager.isSystemInstalled('alpine'), isTrue); + }); + + test('系统名称校验:非法字符与同名防重', () async { + expect( + () => manager.validateSystemName(''), + throwsArgumentError, + ); + + expect( + () => manager.validateSystemName('bad/name*here'), + throwsArgumentError, + ); + + // 创建一个系统后,同名抛出异常 + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'temp.tar.gz'))..writeAsBytesSync(gzBytes); + await manager.importFromCustomTarGz(systemName: 'my_sys', tarGzFile: tempGzFile); + + expect( + () => manager.validateSystemName('my_sys'), + throwsArgumentError, + ); + }); + + test('解压取消时抛出异常并自动回滚清理残余目录', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'cancel_test.tar.gz'))..writeAsBytesSync(gzBytes); + + bool cancelTriggered = false; + + try { + await manager.importFromCustomTarGz( + systemName: 'cancelled_sys', + tarGzFile: tempGzFile, + onProgress: (prog, msg) { + cancelTriggered = true; + }, + isCancelled: () => cancelTriggered, // 模拟用户在解压循环中点击了取消 + ); + fail('应当抛出 DistroInstallCancelledException'); + } catch (e) { + expect(e, isA()); + } + + // 验证未导入成功的脏目录被清理 + final sysRootDir = await manager.getSystemRootDir('cancelled_sys'); + expect(sysRootDir.existsSync(), isFalse); + expect((await manager.listInstalledSystems()).contains('cancelled_sys'), isFalse); + }); + + test('高危删除系统实例物理清除文件', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'del_test.tar.gz'))..writeAsBytesSync(gzBytes); + + await manager.importFromCustomTarGz(systemName: 'to_delete', tarGzFile: tempGzFile); + expect((await manager.listInstalledSystems()).contains('to_delete'), isTrue); + + await manager.deleteSystem('to_delete'); + expect((await manager.listInstalledSystems()).contains('to_delete'), isFalse); + + final sysDir = Directory(p.join(tempBaseDir.path, 'to_delete')); + expect(sysDir.existsSync(), isFalse); + }); + + test('buildLaunchConfig 准确指向对应系统根目录', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'cfg.tar.gz'))..writeAsBytesSync(gzBytes); + + await manager.importFromCustomTarGz(systemName: 'prod_env', tarGzFile: tempGzFile); + + final launchConfig = await manager.buildLaunchConfig( + systemName: 'prod_env', + workspacePath: tempBaseDir.path, + ); + + expect(launchConfig.arguments, contains('-r')); + final rootDir = await manager.getSystemRootDir('prod_env'); + expect(launchConfig.arguments, contains(rootDir.path)); + expect(launchConfig.arguments, contains('-k')); + expect(launchConfig.arguments, contains('5.4.0-proot')); + expect(launchConfig.environment['PROOT_L2S_DIR'], isNotNull); + }); + }); + + group('DistroProvider 状态持久化与系统切换测试', () { + test('默认系统自动选取与持久化切换', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'provider_test.tar.gz'))..writeAsBytesSync(gzBytes); + + final provider = DistroProvider(); + await provider.init(); + expect(provider.selectedSystem, isNull); + + // 导入首个系统,自动选为当前系统 + await provider.importFromCustomTarGz(systemName: 'sys_a', tarGzFile: tempGzFile); + expect(provider.selectedSystem, equals('sys_a')); + expect(provider.installedSystems, contains('sys_a')); + + // 导入第二个系统,自动切换到新系统 + await provider.importFromCustomTarGz(systemName: 'sys_b', tarGzFile: tempGzFile); + expect(provider.selectedSystem, equals('sys_b')); + + // 手动切换回 sys_a 并持久化 + await provider.selectSystem('sys_a'); + expect(provider.selectedSystem, equals('sys_a')); + + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString('terminal_default_system'), equals('sys_a')); + + // 删除当前选中的系统,自动平滑退回到另一个系统 + await provider.deleteSystem('sys_a'); + expect(provider.installedSystems, equals(['sys_b'])); + expect(provider.selectedSystem, equals('sys_b')); + + // 删除仅剩的系统,回到 null + await provider.deleteSystem('sys_b'); + expect(provider.installedSystems, isEmpty); + expect(provider.selectedSystem, isNull); + }); + + test('删除系统实例时联动清理对应系统的全部终端会话', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'session_clean_test.tar.gz'))..writeAsBytesSync(gzBytes); + + final distroProvider = DistroProvider(); + await distroProvider.init(); + + await distroProvider.importFromCustomTarGz(systemName: 'sys_1', tarGzFile: tempGzFile); + await distroProvider.importFromCustomTarGz(systemName: 'sys_2', tarGzFile: tempGzFile); + + final terminalProvider = TerminalProvider(); + distroProvider.onSystemDeleted = (deleted) { + terminalProvider.removeSessionsForDistro(deleted); + if (!distroProvider.hasAnySystem) { + terminalProvider.clearAllSessions(); + } + }; + + // 创建 sys_1 的两个会话,sys_2 的一个会话 + final s1 = terminalProvider.createSession(name: '会话1', distroId: 'sys_1'); + final s2 = terminalProvider.createSession(name: '会话2', distroId: 'sys_1'); + final s3 = terminalProvider.createSession(name: '会话3', distroId: 'sys_2'); + + expect(terminalProvider.sessions.length, equals(3)); + + // 删除 sys_1:应当仅删除 s1 与 s2,保留 s3 + await distroProvider.deleteSystem('sys_1'); + + expect(terminalProvider.sessions.length, equals(1)); + expect(terminalProvider.sessions.first.id, equals(s3.id)); + expect(terminalProvider.sessions.first.distroId, equals('sys_2')); + expect(terminalProvider.sessions.any((s) => s.id == s1.id), isFalse); + expect(terminalProvider.sessions.any((s) => s.id == s2.id), isFalse); + + // 删除最后一个系统 sys_2:所有会话均被清理清空 + await distroProvider.deleteSystem('sys_2'); + expect(terminalProvider.sessions, isEmpty); + }); + + testWidgets('DistroSelectorDialog 列表项仅显示名称,无副标题与前置勾选图标', (tester) async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'dialog_ui_test.tar.gz'))..writeAsBytesSync(gzBytes); + + final distroProvider = DistroProvider(); + await tester.runAsync(() async { + await distroProvider.init(); + await distroProvider.importFromCustomTarGz(systemName: 'my_alpine', tarGzFile: tempGzFile); + }); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: distroProvider), + ChangeNotifierProvider(create: (_) => TerminalProvider()), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold( + body: DistroSelectorDialog(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 验证系统管理标题来自 l10n + expect(find.text('系统管理'), findsOneWidget); + + // 验证系统名称正常显示 + expect(find.text('my_alpine'), findsOneWidget); + + // 验证无旧版副标题文字(如“当前默认系统”、“点击切换为默认”) + expect(find.text('当前默认系统'), findsNothing); + expect(find.text('点击切换为默认'), findsNothing); + + // 验证无前置勾选图标 + expect(find.byIcon(Icons.check_circle), findsNothing); + expect(find.byIcon(Icons.radio_button_unchecked), findsNothing); + + // 验证存在高危删除按钮 + expect(find.byIcon(Icons.delete_outline), findsOneWidget); + }); + }); +} diff --git a/test/terminal_test.dart b/test/terminal_test.dart index 6fc0418..7ebbb3b 100644 --- a/test/terminal_test.dart +++ b/test/terminal_test.dart @@ -1,5 +1,4 @@ import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/models/terminal_session.dart'; import 'package:code_editor/providers/distro_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; @@ -10,11 +9,81 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; -Widget createTestTerminalApp({required TerminalProvider terminalProvider}) { +class FakeDistroProvider extends DistroProvider { + final List _systems; + String? _selected; + + FakeDistroProvider({List? systems, String? selected}) + : _systems = systems ?? ['alpine'], + _selected = selected ?? 'alpine'; + + @override + List get installedSystems => List.unmodifiable(_systems); + + @override + String? get selectedSystem => _selected; + + @override + bool get hasAnySystem => _systems.isNotEmpty; + + @override + bool get isInitialized => true; + + @override + Future init() async {} + + @override + Future refreshSystems() async {} + + @override + Future selectSystem(String systemName) async { + _selected = systemName; + notifyListeners(); + } + + @override + Future deleteSystem(String systemName) async { + _systems.remove(systemName); + if (_selected == systemName) { + _selected = _systems.isNotEmpty ? _systems.first : null; + } + notifyListeners(); + } + + @override + Future importBuiltinAlpine({ + required String systemName, + dynamic onProgress, + bool Function()? isCancelled, + }) async { + _systems.add(systemName); + _selected = systemName; + notifyListeners(); + } + + @override + Future importFromCustomTarGz({ + required String systemName, + required dynamic tarGzFile, + dynamic onProgress, + bool Function()? isCancelled, + }) async { + _systems.add(systemName); + _selected = systemName; + notifyListeners(); + } +} + +Widget createTestTerminalApp({ + required TerminalProvider terminalProvider, + DistroProvider? distroProvider, +}) { return MultiProvider( providers: [ ChangeNotifierProvider.value(value: terminalProvider), - ChangeNotifierProvider(create: (_) => DistroProvider()), + ChangeNotifierProvider.value( + value: distroProvider ?? FakeDistroProvider(), + ), ], child: MaterialApp( locale: const Locale('zh'), @@ -46,7 +115,7 @@ void main() { // Check AppBar title and subtitle expect(find.text('会话'), findsWidgets); - expect(find.text('终端'), findsOneWidget); + expect(find.textContaining('终端'), findsOneWidget); }); testWidgets('Right drawer can be opened and shows title "会话" with add button', (tester) async { @@ -177,7 +246,7 @@ void main() { // Append custom text to session buffer via provider provider.appendOutput(provider.activeSession!, 'CUSTOM_SESSION_OUTPUT_LINE'); await tester.pumpAndSettle(); - expect(find.text('CUSTOM_SESSION_OUTPUT_LINE'), findsOneWidget); + expect(provider.activeSession!.bufferText.contains('CUSTOM_SESSION_OUTPUT_LINE'), isTrue); // Pop back to editor await tester.tap(find.byIcon(Icons.arrow_back)); @@ -188,15 +257,15 @@ void main() { // Provider still holds the session and buffer expect(provider.sessions.length, equals(1)); - expect(provider.sessions.first.outputLines.contains('CUSTOM_SESSION_OUTPUT_LINE'), isTrue); + expect(provider.sessions.first.bufferText.contains('CUSTOM_SESSION_OUTPUT_LINE'), isTrue); // Re-enter terminal await tester.tap(find.text('进入终端')); await tester.pumpAndSettle(); - // Verify the session output is still right there + // Verify the session output is still preserved in buffer expect(find.byType(TerminalView), findsOneWidget); - expect(find.text('CUSTOM_SESSION_OUTPUT_LINE'), findsOneWidget); + expect(provider.activeSession!.bufferText.contains('CUSTOM_SESSION_OUTPUT_LINE'), isTrue); }); testWidgets('Deleting a session from context menu removes it and updates activeIndex', (tester) async { @@ -264,6 +333,79 @@ void main() { expect(find.text('(2) 第一项'), findsOneWidget); }); + testWidgets('English locale renders "Session", "Terminal · alpine", and "Sessions" dynamically', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: provider), + ChangeNotifierProvider.value(value: FakeDistroProvider()), + ], + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const TerminalView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // Check AppBar title "Session" and subtitle "Terminal · alpine" + expect(find.text('Session'), findsOneWidget); + expect(find.text('Terminal · alpine'), findsOneWidget); + + // Open drawer + await tester.tap(find.byIcon(Icons.format_list_bulleted)); + await tester.pumpAndSettle(); + + // Check drawer title "Sessions" and item "(1) Session" + expect(find.text('Sessions'), findsOneWidget); + expect(find.text('(1) Session'), findsOneWidget); + }); + + testWidgets('Session name is fixed upon creation and does not re-translate on language change', (tester) async { + final provider = TerminalProvider(); + // First created in English + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: provider), + ChangeNotifierProvider.value(value: FakeDistroProvider()), + ], + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const TerminalView(), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Session'), findsOneWidget); + + // Now re-render with Chinese locale + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: provider), + ChangeNotifierProvider.value(value: FakeDistroProvider()), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const TerminalView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // The created session's name is FIXED as "Session", while subtitle translates to Chinese + expect(find.text('Session'), findsOneWidget); + expect(find.text('终端 · alpine'), findsOneWidget); + }); + test('SettingsProvider manages UI, Editor, and Terminal font choices correctly', () async { final settings = SettingsProvider(); expect(settings.uiFont.id, equals('system_default')); diff --git a/test/widget_test.dart b/test/widget_test.dart index 8b6a318..31f33cf 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1075,8 +1075,8 @@ void main() { expect(find.text('file1.dart'), findsWidgets); expect(tabProvider.isModified, isTrue); - // Open file2 via selectFile (simulating user clicking file2 in file tree/drawer) - await tabProvider.selectFile(file2); + // Open file2 via openFile (with content specified, or selectFile) + await tabProvider.openFile(file2.path, content: 'int b = 2;'); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); @@ -1470,7 +1470,7 @@ void main() { // Scroll to virtual keyboard tiles final configTile = find.text('编辑键盘配置'); - await tester.scrollUntilVisible(configTile, 200); + await tester.scrollUntilVisible(configTile, 200, scrollable: find.byType(Scrollable).first); await tester.pumpAndSettle(); expect(configTile, findsOneWidget); @@ -1512,7 +1512,7 @@ void main() { // Tap '保存' with valid config -> dialog closes await tester.tap(find.text('保存')); - await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpAndSettle(); expect(find.text('小键盘配置 (JSON)'), findsNothing); diff --git a/tools/container-selfcheck/README.md b/tools/container-selfcheck/README.md new file mode 100644 index 0000000..acdef10 --- /dev/null +++ b/tools/container-selfcheck/README.md @@ -0,0 +1,86 @@ +# 容器自检工具(container-selfcheck) + +在 **Android app 进程内**的 PRoot 容器里做系统调用级自检,用于定位"某个 syscall 被平台策略 +拦掉 / PRoot 语义不对"这类问题。本目录是 2026-09-13 排查 `apk temporary error` / +`Failed to preserve modification time` 时用的工具,已固化为可复用资产。 + +结论与证据见仓库根目录 `CONTAINER_FIX_SUMMARY.md`。 + +--- + +## 组件 + +| 文件 | 作用 | +|---|---| +| `probe3.c` | 系统调用策略自检:`poll/ppoll/select/pselect6/epoll_wait(epoll_pwait)/fcntl/ioctl/utimensat/fstat/statfs/clone/unshare/chroot/getrandom`。**支持 x86_64 与 arm64**(两者系统调用表不同,代码里已按架构区分)。 | +| `probe4.c` | 复现 apk 安装动作序列:`建目录 → openat 解包 → utimensat 保 mtime → linkat 硬链接 → renameat 改名`,用来定位 PRoot `--link2symlink` 的问题。 | +| `probe5.c` | 检查 PRoot 对空路径 `newfstatat(fd,"",st,AT_EMPTY_PATH)` 的处理(曾用于判定旧 workaround 是否还必要)。 | +| `selfcheck.sh` | 容器内一键验收:`apk update` / 硬链接包全新安装 / 带触发器安装 / broken 标记 / 三个 probe。 | +| `guest-run.sh` | **免重装 APK** 的 adb 侧跑手:用 `pm path` 推导原生库目录,自己拼 PRoot 命令行,在容器里执行任意命令。 | + +## 编译探针 + +```bash +NDK=/toolchains/llvm/prebuilt//bin +# arm64 真机 +"$NDK/clang" --target=aarch64-linux-android21 -nostdlib -static -fno-stack-protector -O1 -o probe3 probe3.c +# x86_64 模拟器 +"$NDK/clang" --target=x86_64-linux-android21 -nostdlib -static -fno-stack-protector -O1 -o probe3 probe3.c +``` + +无 libc、无依赖:所有系统调用直接发 `svc #0` / `syscall`,结果用 `write(2)` 打印。 + +## 用法(真机 / 模拟器都适用) + +前提:app 为 **debug** 构建(`run-as` 需要),设备已连 adb。 + +```bash +PKG=com.example.code_editor +BASE=/data/data/$PKG/files/distros/alpine +R=$BASE/rootfs + +# 1) 把探针与自检脚本放进容器 +adb push probe3 /data/local/tmp/probe3 +adb push selfcheck.sh /data/local/tmp/selfcheck.sh +adb shell "run-as $PKG sh -c 'cat /data/local/tmp/probe3 > $R/root/probe3; chmod 755 $R/root/probe3; \ + cat /data/local/tmp/selfcheck.sh > $R/root/selfcheck.sh; chmod 755 $R/root/selfcheck.sh'" + +# 2) 在容器里跑(adb 侧免重装) +adb shell "run-as $PKG sh /data/local/tmp/guest-run.sh /bin/sh /root/selfcheck.sh" +# 或者:push guest-run.sh 后 +adb shell "run-as $PKG sh /data/local/tmp/guest-run.sh /root/probe3" + +# 3) 读结果 +adb shell "run-as $PKG cat $R/root/acc.log" +``` + +### 在「App 自己的终端会话」里跑(需要 app 上下文时) + +App 上下文(有 zygote 装上的 seccomp filter)才是线上真实环境。两种方式: + +- 直接在终端里敲:`sh /root/selfcheck.sh` +- **免打字**:把钩子挂到 `/etc/profile.d`,新会话自动执行(本目录不含该钩子文件,按需创建): + ```sh + # /etc/profile.d/zz-selfcheck.sh + ( sh /root/selfcheck.sh >/dev/null 2>&1 ) & + ``` + 然后重启 App 并进入终端页,结果写入 `/root/acc.log`。 + +## 两条铁律 + +1. **不要在容器运行中原地覆盖 `/lib/libfix_seccomp.so`**:正在映射该文件的进程会 SIGSEGV + (实测:会话 `proot info: vpid 1: terminated with signal 11`)。必须 + 「写临时文件 → `mv` 重命名」。 +2. **换 shim 后需要新起进程才生效**:已运行的进程仍映射旧库。用 `am force-stop` 重启 App, + 或直接新开一个会话。 + +## 已定位(供参考,不必重跑) + +| 现象 | 结论 | +|---|---| +| `apk` 报 `temporary error (try again later)` | **x86_64 专属**:arm64 无 `poll/select` 系统调用;x86_64 有且被 app seccomp 封为 ENOSYS,musl 的 `#ifdef SYS_poll` 命中 ⇒ 解析器超时 ⇒ `EAI_AGAIN`。 | +| `apk` 报 `IO ERROR` | 同上(`select`),libfetch 失败时不设错误码。 | +| `Failed to preserve modification time`(tzdata 等硬链接包) | **跨架构**:Android 禁止 `link(2)` ⇒ PRoot 用 symlink + `.proot-meta-file.*` 模拟 ⇒ apk 跟随语义的 `utimensat` 落到隐藏名 ⇒ ENOENT ⇒ 包被标 broken。 | +| `newfstatat(fd,"",st,AT_EMPTY_PATH)` | PRoot 处理正常(=0),旧的 workaround 已删除。 | +| `--sysvipc` | 本项目 `libproot.so` **不支持**(`unknown option`),不能加;Termux 的 proot 是带 libandroid-shmem 的 fork 版。 | +| `openat(dir, O_DIRECTORY)` | 在本项目 proot 下返回 **EINVAL**(`O_PATH|O_DIRECTORY` 正常)——已知怪癖,当前无功能影响。 | diff --git a/tools/container-selfcheck/guest-run.sh b/tools/container-selfcheck/guest-run.sh new file mode 100644 index 0000000..643ce9a --- /dev/null +++ b/tools/container-selfcheck/guest-run.sh @@ -0,0 +1,16 @@ +#!/system/bin/sh +# run an arbitrary guest binary inside the PRoot container (adb harness) +PKG=com.example.code_editor +BASE=/data/data/$PKG/files/distros/alpine +ROOT=$BASE/rootfs +LIBDIR=$(pm path $PKG 2>/dev/null | head -1 | sed 's|package:||; s|/base.apk$||')/lib/arm64 +export LD_LIBRARY_PATH=$LIBDIR +export PROOT_TMP_DIR=/data/data/$PKG/cache +export PROOT_L2S_DIR=$BASE/.l2s +P=$LIBDIR/libproot.so +cd $ROOT +exec $P --kill-on-exit --link2symlink -0 -r . -b /dev -b /dev/urandom:/dev/random \ + -b $BASE/shm:/dev/shm -b /proc -b /sys -b /data/data/$PKG/cache:/tmp -w /root \ + /usr/bin/env -i HOME=/root USER=root TERM=dumb LANG=C.UTF-8 \ + PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LD_PRELOAD=/lib/libfix_seccomp.so "$@" diff --git a/tools/container-selfcheck/probe3.c b/tools/container-selfcheck/probe3.c new file mode 100644 index 0000000..a4a95fe --- /dev/null +++ b/tools/container-selfcheck/probe3.c @@ -0,0 +1,271 @@ +/* probe3.c - real-device syscall self-check (freestanding, x86_64 + aarch64) + * + * Answers, on ANY device: which syscalls does the Android app seccomp policy + * deny to this container, and does the guest's path handling (utimensat, + * clone, unshare) work? + * + * Build: + * clang --target=aarch64-linux-android21 -nostdlib -static -O1 -o probe3 probe3.c + * clang --target=x86_64-linux-android21 -nostdlib -static -O1 -o probe3 probe3.c + */ +typedef unsigned long u64; +typedef long i64; + +#if defined(__x86_64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + i64 ret; + register i64 r10 __asm__("r10") = a4; + register i64 r8 __asm__("r8") = a5; + register i64 r9 __asm__("r9") = a6; + __asm__ __volatile__("syscall" : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory"); + return ret; +} +#define SYS_read 0 +#define SYS_write 1 +#define SYS_close 3 +#define SYS_fstat 5 +#define SYS_poll 7 +#define SYS_select 23 +#define SYS_ioctl 16 +#define SYS_socket 41 +#define SYS_connect 42 +#define SYS_sendto 44 +#define SYS_recvfrom 45 +#define SYS_bind 49 +#define SYS_clone 56 +#define SYS_uname 63 +#define SYS_fcntl 72 +#define SYS_statfs 137 +#define SYS_epoll_wait 232 +#define SYS_exit 60 +#define SYS_wait4 61 +#define SYS_openat 257 +#define SYS_pselect6 270 +#define SYS_ppoll 271 +#define SYS_epoll_create1 291 +#define SYS_utimensat 280 +#define SYS_unshare 272 +#define SYS_chroot 161 +#define SYS_getrandom 318 +#elif defined(__aarch64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + register i64 x8 __asm__("x8") = n; + register i64 x0 __asm__("x0") = a1; + register i64 x1 __asm__("x1") = a2; + register i64 x2 __asm__("x2") = a3; + register i64 x3 __asm__("x3") = a4; + register i64 x4 __asm__("x4") = a5; + register i64 x5 __asm__("x5") = a6; + __asm__ __volatile__("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} +#define SYS_read 63 +#define SYS_write 64 +#define SYS_close 57 +#define SYS_fstat 80 +/* NOTE: arm64 (asm-generic table) has NO poll/select/epoll_wait syscalls at + * all - libc implements them on top of ppoll/pselect6/epoll_pwait. That is + * exactly why the x86_64-only "poll blocked" failure cannot happen here. */ +#define SYS_poll (-1) +#define SYS_select (-1) +#define SYS_ioctl 29 +#define SYS_epoll_wait (-1) +#define SYS_exit 93 +#define SYS_wait4 260 +#define SYS_socket 198 +#define SYS_connect 203 +#define SYS_sendto 206 +#define SYS_recvfrom 207 +#define SYS_bind 200 +#define SYS_clone 220 +#define SYS_uname 160 +#define SYS_fcntl 25 +#define SYS_statfs 43 +#define SYS_openat 56 +#define SYS_pselect6 72 +#define SYS_ppoll 73 +#define SYS_epoll_create1 20 +#define SYS_utimensat 88 +#define SYS_unshare 97 +#define SYS_chroot 51 +#define SYS_getrandom 278 +#endif + +static i64 sc0(i64 n) { return sc6(n, 0, 0, 0, 0, 0, 0); } +static i64 sc1(i64 n, i64 a) { return sc6(n, a, 0, 0, 0, 0, 0); } +static i64 sc2(i64 n, i64 a, i64 b) { return sc6(n, a, b, 0, 0, 0, 0); } +static i64 sc3(i64 n, i64 a, i64 b, i64 c) { return sc6(n, a, b, c, 0, 0, 0); } +static i64 sc4(i64 n, i64 a, i64 b, i64 c, i64 d) { return sc6(n, a, b, c, d, 0, 0); } + +static void put(const char *s) +{ + i64 n = 0; + while (s[n]) n++; + sc3(SYS_write, 1, (i64)s, n); +} + +static void putnum(i64 v) +{ + char b[24]; + int i = 24, neg = v < 0; + unsigned long u = neg ? (unsigned long)(-v) : (unsigned long)v; + if (v == 0) { put("0"); return; } + b[--i] = 0; + while (u) { b[--i] = '0' + (u % 10); u /= 10; } + if (neg) b[--i] = '-'; + put(&b[i]); +} + +/* print a line, and for negative returns append a verdict */ +static void show(const char *name, i64 ret) +{ + put(name); put(" = "); putnum(ret); + if (ret == -38) put(" <-- ENOSYS (blocked by policy)"); + else if (ret == -1) put(" <-- EPERM"); + else if (ret == -9) put(" <-- EBADF"); + else if (ret == -13) put(" <-- EACCES"); + put("\n"); +} + +struct sockaddr_in { unsigned short f; unsigned short p; unsigned int a; unsigned char pad[8]; }; +struct pollfd { int fd; short events; short revents; }; +struct timespec { long s; long n; }; +struct timeval { long s; long us; }; + +void prog_main(void); + +#if defined(__x86_64__) +__asm__( + ".globl _start\n" + "_start:\n" + " andq $-16, %rsp\n" + " call prog_main\n" + " movl $60, %eax\n" + " xorl %edi, %edi\n" + " syscall\n" +); +#else +__asm__( + ".globl _start\n" + "_start:\n" + " bl prog_main\n" + " mov x0, #0\n" + " mov x8, #93\n" + " svc #0\n" +); +#endif + +void prog_main(void) +{ + i64 r, fd, sfd, dfd, ofd; + struct pollfd pfd; + struct timespec ts; + struct timeval tv; + struct sockaddr_in ns; + long ubuf[64]; + + put("=== probe3 (real device syscall self-check) ===\n"); + + /* --- wait primitives: the ones Android denies to app processes --- */ + fd = sc3(SYS_socket, 2, 2, 0); /* AF_INET, SOCK_DGRAM */ + show("socket(UDP)", fd); + if (fd >= 0) { + pfd.fd = (int)fd; pfd.events = 1; pfd.revents = 0; + ts.s = 0; ts.n = 200000000L; /* 200ms */ +#if defined(__x86_64__) + show("poll(fd,POLLIN,200ms)", sc3(SYS_poll, (i64)&pfd, 1, 200)); +#else + put("poll(...) = N/A on arm64 (syscall does not exist)\n"); +#endif + pfd.revents = 0; + show("ppoll(fd,POLLIN,200ms)", sc6(SYS_ppoll, (i64)&pfd, 1, (i64)&ts, 0, 0, 0)); + tv.s = 0; tv.us = 0; +#if defined(__x86_64__) + show("select(0,NULL,NULL,NULL,{0,0})", sc6(SYS_select, 0, 0, 0, 0, (i64)&tv, 0)); +#else + put("select(...) = N/A on arm64 (syscall does not exist)\n"); +#endif + show("pselect6(0,...,{0})", sc6(SYS_pselect6, 0, 0, 0, 0, (i64)&ts, 0)); + r = sc1(SYS_epoll_create1, 0); + show("epoll_create1(0)", r); +#if defined(__x86_64__) + if (r >= 0) + show("epoll_wait(epfd,1,0)", sc4(SYS_epoll_wait, r, (i64)ubuf, 1, 0)); +#else + if (r >= 0) { + /* arm64 only has epoll_pwait (22) */ + show("epoll_pwait(epfd,1,0,NULL)", sc6(22, r, (i64)ubuf, 1, 0, 0, 0)); + } +#endif + show("fcntl(F_GETFL)", sc4(SYS_fcntl, fd, 3, 0, 0)); + r = sc4(SYS_fcntl, fd, 3, 0, 0); + show("fcntl(F_SETFL,|NONBLOCK)", sc4(SYS_fcntl, fd, 4, r | 0x800, 0)); + show("fcntl(F_SETFL,&~NONBLOCK)", sc4(SYS_fcntl, fd, 4, r & ~0x800, 0)); + { + int one = 1; + show("ioctl(FIONBIO)", sc3(SYS_ioctl, fd, 0x5421, (i64)&one)); + } + sc1(SYS_close, fd); + } + + /* --- TCP + DNS-relevant --- */ + sfd = sc3(SYS_socket, 2, 1, 0); + show("socket(TCP)", sfd); + ns.f = 2; ns.p = 0x3500; ns.a = 0x08080808; /* 8.8.8.8:53 */ + if (sfd >= 0) { + show("bind(UDP 0.0.0.0:0)", sc3(SYS_bind, sfd, (i64)&ns, 16)); + sc1(SYS_close, sfd); + } + + /* --- file/path handling used by apk's installer --- */ + show("openat(create /root/utest)", fd = sc4(SYS_openat, -100, (i64)"/root/utest", + 0x40 | 1 | 0x200, 0644)); + if (fd >= 0) sc1(SYS_close, fd); + show("utimensat(AT_FDCWD, abs)", sc4(SYS_utimensat, -100, (i64)"/root/utest", 0, 0)); + show("utimensat(AT_FDCWD, rel)", sc4(SYS_utimensat, -100, (i64)"utest", 0, 0)); + dfd = sc4(SYS_openat, -100, (i64)"/root", 0x10000, 0); + show("openat(/root, O_DIRECTORY)", dfd); + if (dfd >= 0) { + show("utimensat(dirfd, rel) [apk style]", sc4(SYS_utimensat, dfd, (i64)"utest", 0, 0)); + show("utimensat(dirfd, rel, NOFOLLOW)", sc4(SYS_utimensat, dfd, (i64)"utest", 0, 0x100)); + ofd = sc4(SYS_openat, dfd, (i64)"utest", 0x200000, 0); + show("openat(dirfd, rel, O_PATH)", ofd); + if (ofd >= 0) { + show("utimensat(fd, \"\", AT_EMPTY_PATH)", sc4(SYS_utimensat, ofd, (i64)"", 0, 0x1000)); + sc1(SYS_close, ofd); + } + sc1(SYS_close, dfd); + } + show("fstat(1)", sc2(SYS_fstat, 1, (i64)ubuf)); + show("statfs(\"/\")", sc2(SYS_statfs, (i64)"/", (i64)ubuf)); + + /* --- process creation: what apk's trigger scripts and shells need --- */ + { + i64 pid = sc6(SYS_clone, 17 /*SIGCHLD*/, 0, 0, 0, 0, 0); + if (pid == 0) { /* child: leave immediately */ + sc1(SYS_exit, 0); + for (;;) {} + } + show("clone(SIGCHLD) [=fork]", pid); + if (pid > 0) { + i64 st = 0; + /* wait4(pid, &st, 0, 0) = 61 on x86_64 / 260 on aarch64 */ + sc4(SYS_wait4, pid, (i64)&st, 0, 0); + } + } + show("unshare(CLONE_NEWNS)", sc1(SYS_unshare, 0x00020000)); + show("getrandom(8)", sc3(SYS_getrandom, (i64)ubuf, 8, 1)); + show("uname", sc1(SYS_uname, (i64)ubuf)); + + put("=== probe3 done ===\n"); + + /* last: chroot is irreversible enough to keep at the very end */ + show("chroot(\"/\")", sc1(SYS_chroot, (i64)"/")); + sc1(SYS_exit, 0); + for (;;) {} +} diff --git a/tools/container-selfcheck/probe4.c b/tools/container-selfcheck/probe4.c new file mode 100644 index 0000000..fa090cb --- /dev/null +++ b/tools/container-selfcheck/probe4.c @@ -0,0 +1,209 @@ +/* probe4.c - A2 investigation: reproduce apk's "preserve modification time" + * failure for hardlinked entries, and map which PRoot path operation breaks. + * + * apk's installer does, per file: + * extract -> /.apk. (openat O_CREAT|O_WRONLY, write) + * utimensat(dirfd, ".apk.", times, AT_SYMLINK_NOFOLLOW) + * renameat(dirfd, ".apk.", dirfd, "") + * and for hardlinked entries it first creates a hard link to an earlier entry + * (linkat). PRoot's --link2symlink rewrites link() into symlink + sidecar + * ".proot-meta-file.*", which is what we see left behind in /usr/share/zoneinfo. + * + * This probe walks that exact sequence with raw syscalls and reports the first + * failing step, for every flag combination that could matter. + * + * Build: clang --target=aarch64-linux-android21 -nostdlib -static -O1 -o probe4 probe4.c + */ +typedef unsigned long u64; +typedef long i64; + +#if defined(__x86_64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + i64 ret; + register i64 r10 __asm__("r10") = a4; + register i64 r8 __asm__("r8") = a5; + register i64 r9 __asm__("r9") = a6; + __asm__ __volatile__("syscall" : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory"); + return ret; +} +#define SYS_write 1 +#define SYS_close 3 +#define SYS_openat 257 +#define SYS_utimensat 280 +#define SYS_renameat 264 +#define SYS_linkat 265 +#define SYS_unlinkat 263 +#define SYS_mkdirat 258 +#define SYS_exit 60 +#define SYS_lstat_newfstatat 262 +#elif defined(__aarch64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + register i64 x8 __asm__("x8") = n; + register i64 x0 __asm__("x0") = a1; + register i64 x1 __asm__("x1") = a2; + register i64 x2 __asm__("x2") = a3; + register i64 x3 __asm__("x3") = a4; + register i64 x4 __asm__("x4") = a5; + register i64 x5 __asm__("x5") = a6; + __asm__ __volatile__("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} +#define SYS_write 64 +#define SYS_close 57 +#define SYS_openat 56 +#define SYS_utimensat 88 +#define SYS_renameat 38 +#define SYS_linkat 37 +#define SYS_unlinkat 35 +#define SYS_mkdirat 34 +#define SYS_exit 93 +#define SYS_lstat_newfstatat 79 +#endif + +static i64 sc0(i64 n) { return sc6(n, 0, 0, 0, 0, 0, 0); } +static i64 sc1(i64 n, i64 a) { return sc6(n, a, 0, 0, 0, 0, 0); } +static i64 sc2(i64 n, i64 a, i64 b) { return sc6(n, a, b, 0, 0, 0, 0); } +static i64 sc3(i64 n, i64 a, i64 b, i64 c) { return sc6(n, a, b, c, 0, 0, 0); } +static i64 sc4(i64 n, i64 a, i64 b, i64 c, i64 d) { return sc6(n, a, b, c, d, 0, 0); } + +static void put(const char *s) +{ + i64 n = 0; + while (s[n]) n++; + sc3(SYS_write, 1, (i64)s, n); +} + +static void putnum(i64 v) +{ + char b[24]; + int i = 24, neg = v < 0; + unsigned long u = neg ? (unsigned long)(-v) : (unsigned long)v; + if (v == 0) { put("0"); return; } + b[--i] = 0; + while (u) { b[--i] = '0' + (u % 10); u /= 10; } + if (neg) b[--i] = '-'; + put(&b[i]); +} + +static void show(const char *name, i64 ret) +{ + put(name); put(" = "); putnum(ret); + if (ret == -2) put(" [ENOENT]"); + else if (ret == -22) put(" [EINVAL]"); + else if (ret == -9) put(" [EBADF]"); + else if (ret == -40) put(" [ELOOP]"); + else if (ret == -38) put(" [ENOSYS]"); + put("\n"); +} + +#define AT_FDCWD (-100) +#define AT_SYMLINK_NOFOLLOW 0x100 +#define AT_EMPTY_PATH 0x1000 +#define O_RDONLY 0 +#define O_WRONLY 1 +#define O_CREAT 0x40 +#define O_TRUNC 0x200 +#define O_DIRECTORY 0x10000 +#define O_NOFOLLOW 0x20000 +#define O_PATH 0x200000 +#define O_CLOEXEC 0x80000 +#define AT_REMOVEDIR 0x200 + +void prog_main(void); + +#if defined(__x86_64__) +__asm__(".globl _start\n_start:\n andq $-16, %rsp\n call prog_main\n" + " movl $60, %eax\n xorl %edi, %edi\n syscall\n"); +#else +__asm__(".globl _start\n_start:\n bl prog_main\n mov x0, #0\n" + " mov x8, #93\n svc #0\n"); +#endif + +void prog_main(void) +{ + i64 dfd, ffd, ofd, r; + long st[64]; + + put("=== probe4: replicate apk's extract -> mtime -> link -> rename ===\n"); + sc1(SYS_mkdirat, 0); /* no-op to keep syscall table honest */ + + /* step 0: fresh working directory */ + sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_RDONLY | O_DIRECTORY, 0); + sc3(SYS_mkdirat, AT_FDCWD, (i64)"/root/p4dir", 0755); + + put("--- opening the directory (apk keeps a dirfd per directory) ---\n"); + /* report the flag variants, but use the plain O_RDONLY fd as the working + * dirfd so the rest of the sequence is meaningful even if one fails */ + show("openat(/root/p4dir, RDONLY)", sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_RDONLY, 0)); + show("openat(/root/p4dir, RDONLY|O_DIRECTORY)", + sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_RDONLY | O_DIRECTORY, 0)); + show("openat(/root/p4dir, RDONLY|O_DIRECTORY|O_CLOEXEC)", + sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0)); + show("openat(/root/p4dir, O_PATH)", + sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_PATH, 0)); + show("openat(/root/p4dir, O_PATH|O_DIRECTORY)", + sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_PATH | O_DIRECTORY, 0)); + show("working dirfd = openat(RDONLY)", + dfd = sc4(SYS_openat, AT_FDCWD, (i64)"/root/p4dir", O_RDONLY, 0)); + if (dfd < 0) { + put("!! no usable dirfd, aborting\n"); + sc1(SYS_exit, 1); + } + + put("--- apk step 1: extract into .apk. (dirfd-relative) ---\n"); + show("openat(dfd, \".apk.aaa\", O_CREAT|O_WRONLY|O_TRUNC)", + ffd = sc4(SYS_openat, dfd, (i64)".apk.aaa", O_CREAT | O_WRONLY | O_TRUNC, 0644)); + if (ffd >= 0) { + sc3(SYS_write, ffd, (i64)"hello", 5); + sc1(SYS_close, ffd); + } + + put("--- apk step 2: preserve mtime on the temp name ---\n"); + show("utimensat(dfd, \".apk.aaa\", NULL, AT_SYMLINK_NOFOLLOW)", + sc4(SYS_utimensat, dfd, (i64)".apk.aaa", 0, AT_SYMLINK_NOFOLLOW)); + show("utimensat(dfd, \".apk.aaa\", NULL, 0)", + sc4(SYS_utimensat, dfd, (i64)".apk.aaa", 0, 0)); + show("newfstatat(dfd, \".apk.aaa\", NOFOLLOW)", + sc4(SYS_lstat_newfstatat, dfd, (i64)".apk.aaa", (i64)st, AT_SYMLINK_NOFOLLOW)); + show("openat(dfd, \".apk.aaa\", O_PATH)", + ofd = sc4(SYS_openat, dfd, (i64)".apk.aaa", O_PATH, 0)); + if (ofd >= 0) { + show("utimensat(ofd, \"\", NULL, AT_EMPTY_PATH)", + sc4(SYS_utimensat, ofd, (i64)"", 0, AT_EMPTY_PATH)); + sc1(SYS_close, ofd); + } + + put("--- apk step 3: hardlink to an earlier entry (tzdata's case) ---\n"); + show("linkat(dfd, \".apk.aaa\" -> \".apk.bbb\")", + sc6(SYS_linkat, dfd, (i64)".apk.aaa", dfd, (i64)".apk.bbb", 0, 0)); + show("newfstatat(dfd, \".apk.bbb\", NOFOLLOW)", + sc4(SYS_lstat_newfstatat, dfd, (i64)".apk.bbb", (i64)st, AT_SYMLINK_NOFOLLOW)); + show("utimensat(dfd, \".apk.bbb\", NULL, AT_SYMLINK_NOFOLLOW)", + sc4(SYS_utimensat, dfd, (i64)".apk.bbb", 0, AT_SYMLINK_NOFOLLOW)); + show("utimensat(dfd, \".apk.bbb\", NULL, 0) [follows l2s link]", + sc4(SYS_utimensat, dfd, (i64)".apk.bbb", 0, 0)); + + put("--- apk step 4: rename temp -> final name ---\n"); + show("renameat(dfd, \".apk.aaa\" -> \"final1\")", + sc4(SYS_renameat, dfd, (i64)".apk.aaa", dfd, (i64)"final1")); + show("renameat(dfd, \".apk.bbb\" -> \"final2\")", + sc4(SYS_renameat, dfd, (i64)".apk.bbb", dfd, (i64)"final2")); + show("utimensat(dfd, \"final1\", NULL, 0)", sc4(SYS_utimensat, dfd, (i64)"final1", 0, 0)); + show("utimensat(dfd, \"final2\", NULL, 0)", sc4(SYS_utimensat, dfd, (i64)"final2", 0, 0)); + + put("--- cleanup / listing evidence ---\n"); + show("newfstatat(dfd, \"final2\", NOFOLLOW)", + sc4(SYS_lstat_newfstatat, dfd, (i64)"final2", (i64)st, AT_SYMLINK_NOFOLLOW)); + show("unlinkat(dfd, \"final1\")", sc3(SYS_unlinkat, dfd, (i64)"final1", 0)); + show("unlinkat(dfd, \"final2\")", sc3(SYS_unlinkat, dfd, (i64)"final2", 0)); + if (dfd >= 0) sc1(SYS_close, dfd); + + put("=== probe4 done ===\n"); + sc1(SYS_exit, 0); + for (;;) {} +} diff --git a/tools/container-selfcheck/probe5.c b/tools/container-selfcheck/probe5.c new file mode 100644 index 0000000..7109e94 --- /dev/null +++ b/tools/container-selfcheck/probe5.c @@ -0,0 +1,106 @@ +/* probe5.c - is the old "empty path triggers PRoot EINVAL" workaround still needed? + * Tests newfstatat(fd, "", buf, AT_EMPTY_PATH) and fstat(fd) under PRoot. + * Build: clang --target=aarch64-linux-android21 -nostdlib -static -O1 -o probe5 probe5.c + */ +typedef long i64; + +#if defined(__x86_64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + i64 ret; + register i64 r10 __asm__("r10") = a4; + register i64 r8 __asm__("r8") = a5; + register i64 r9 __asm__("r9") = a6; + __asm__ __volatile__("syscall" : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory"); + return ret; +} +#define SYS_write 1 +#define SYS_close 3 +#define SYS_fstat 5 +#define SYS_openat 257 +#define SYS_newfstatat 262 +#define SYS_exit 60 +#elif defined(__aarch64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + register i64 x8 __asm__("x8") = n; + register i64 x0 __asm__("x0") = a1; + register i64 x1 __asm__("x1") = a2; + register i64 x2 __asm__("x2") = a3; + register i64 x3 __asm__("x3") = a4; + register i64 x4 __asm__("x4") = a5; + register i64 x5 __asm__("x5") = a6; + __asm__ __volatile__("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} +#define SYS_write 64 +#define SYS_close 57 +#define SYS_fstat 80 +#define SYS_openat 56 +#define SYS_newfstatat 79 +#define SYS_exit 93 +#endif + +static i64 sc1(i64 n, i64 a) { return sc6(n, a, 0, 0, 0, 0, 0); } +static i64 sc2(i64 n, i64 a, i64 b) { return sc6(n, a, b, 0, 0, 0, 0); } +static i64 sc3(i64 n, i64 a, i64 b, i64 c) { return sc6(n, a, b, c, 0, 0, 0); } +static i64 sc4(i64 n, i64 a, i64 b, i64 c, i64 d) { return sc6(n, a, b, c, d, 0, 0); } + +static void put(const char *s) { i64 n = 0; while (s[n]) n++; sc3(SYS_write, 1, (i64)s, n); } +static void putnum(i64 v) +{ + char b[24]; int i = 24, neg = v < 0; + unsigned long u = neg ? (unsigned long)(-v) : (unsigned long)v; + if (v == 0) { put("0"); return; } + b[--i] = 0; + while (u) { b[--i] = '0' + (u % 10); u /= 10; } + if (neg) b[--i] = '-'; + put(&b[i]); +} +static void show(const char *n, i64 r) +{ + put(n); put(" = "); putnum(r); + if (r == -22) put(" [EINVAL]"); + else if (r == -2) put(" [ENOENT]"); + else if (r == -9) put(" [EBADF]"); + put("\n"); +} + +void prog_main(void); +#if defined(__x86_64__) +__asm__(".globl _start\n_start:\n andq $-16, %rsp\n call prog_main\n" + " movl $60, %eax\n xorl %edi, %edi\n syscall\n"); +#else +__asm__(".globl _start\n_start:\n bl prog_main\n mov x0, #0\n mov x8, #93\n svc #0\n"); +#endif + +void prog_main(void) +{ + i64 fd; + long st[64]; + put("=== probe5: empty-path stat workaround check ===\n"); + fd = sc4(SYS_openat, -100, (i64)"/etc/profile", 0, 0); + show("openat(/etc/profile)", fd); + if (fd >= 0) { + show("fstat(fd)", sc2(SYS_fstat, fd, (i64)st)); + show("newfstatat(fd, \"\", st, 0) [empty path]", + sc4(SYS_newfstatat, fd, (i64)"", (i64)st, 0)); + show("newfstatat(fd, \"\", st, AT_EMPTY_PATH) [0x1000]", + sc4(SYS_newfstatat, fd, (i64)"", (i64)st, 0x1000)); + sc1(SYS_close, fd); + } + /* also a directory fd, which is what some tools use */ + fd = sc4(SYS_openat, -100, (i64)"/etc", 0, 0); + show("openat(/etc, RDONLY)", fd); + if (fd >= 0) { + show("newfstatat(dfd, \"\", st, AT_EMPTY_PATH)", + sc4(SYS_newfstatat, fd, (i64)"", (i64)st, 0x1000)); + sc1(SYS_close, fd); + } + put("=== probe5 done ===\n"); + sc1(SYS_exit, 0); + for (;;) {} +} diff --git a/tools/container-selfcheck/selfcheck.sh b/tools/container-selfcheck/selfcheck.sh new file mode 100644 index 0000000..02a5092 --- /dev/null +++ b/tools/container-selfcheck/selfcheck.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# acceptance for the slimmed shim (arm64: utimensat only) +exec >/root/acc.log 2>&1 + +echo "### slimmed-shim acceptance ###" +echo "shim: $(ls -l /lib/libfix_seccomp.so)" + +echo +echo "=== [1] DNS via NATIVE musl resolver (no override on arm64) ===" +S=$(date +%s); apk update; echo "apk_update_rc=$?"; E=$(date +%s); echo "elapsed=$((E-S))s" +wget -T 8 -O /dev/null http://example.com/ ; echo "wget_rc=$?" + +echo +echo "=== [2] hardlink-heavy package, fresh cycle (utimensat fix) ===" +apk del tzdata >/dev/null 2>&1 +apk add tzdata 2>&1 | head -8 +echo "tzdata_rc=$?" +ls -l /usr/share/zoneinfo/Africa/Accra 2>&1 + +echo +echo "=== [3] package with trigger (fork/pipe/dup2 no longer overridden) ===" +apk del tree >/dev/null 2>&1 +apk add tree; echo "tree_rc=$?" + +echo +echo "=== [4] broken flags (expect none) ===" +awk '/^P:/{p=$0} /^f:/{print "BROKEN: "p" "$0}' /lib/apk/db/installed +echo "(end)" + +echo +echo "=== [5] stat family still fine without the shim ===" +/root/probe5 + +echo +echo "=== [6] syscall baseline ===" +/root/probe3 | tail -12 + +echo +echo "=== [7] coreutils-ish sanity ===" +ls -l /usr/bin/tree /usr/share/zoneinfo/Asia/Shanghai 2>&1 +sha256sum /etc/profile >/dev/null 2>&1 && echo "sha256sum ok" +echo "pipe test: $(echo hi | cat)" +echo "subshell: $( (echo nested) )" + +echo "### acceptance done ###" diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index d6ee74d..b778eff 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + flutter_pty jni )