commit e4e5faa55e6840a1bef613de2c994566b00a1bbb Author: ssw-tds-test Date: Fri Nov 13 10:19:19 2026 +0800 init: ssw-tds-test 可信数据空间部署测试工程 初始提交,沉淀 k8s-tenant-wuguirong 租户下完整可信数据空间 的部署、真机/真数据/真多方验证成果。 包含: - CLAUDE.md / docs/:工程入口、armv7 glibc 兼容性整改规格、 ssw-platform#1(armv7 stdout=文件即 exit 100)issue 正文 - build/:TDS 服务端 + tdc-connector 交叉构建脚本、cube 沙箱 编排、三方拓扑/真机验收脚本、ELF 符号扫描工具 - card/:软卡(softcard)源码与预编译产物(local/amd64/armv7) - evidence/:验收报告、三方真实结果、armv7 stdout 矩阵复现证据 - .workbuddy/memory/:工作日志 排除:ssw-tds/ 与 ssw-acz7015/ 为上游源码独立仓库(含 .git, 体积大);build/ 下 ctx-*/dist/pglite-* 等可重建中间产物; build/.env.*、tdc-conn-key/、.tdc-identity-secret 等明文密钥。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d3ec09 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# 防御性忽略:本目录当前不是 git 仓库,但若将来 git init / 被工具扫描, +# 下面两类绝不能入库 —— 明文密钥 与 ~750M 可重建的构建中间产物。 + +# 1) 明文密钥 / 烘进 ConfigMap 的清单 / 连接器私钥 +build/.env.* +build/.tdc-identity-secret +build/*-k8s.yaml +build/tdc-conn-key/ + +# 2) 构建中间产物(由 gen-*.sh 与 Dockerfile 重建,体积大) +build/ctx-*/ +build/dist/ +build/dist-device/ +build/pglite-*/ +build/*.tar.gz + +# 3) 本机杂项 +.DS_Store +*.log.tmp + +# 4) 上游源码克隆(各自是独立 git 仓库,含 .git,体积大,不入库) +# ssw-tds/ = TDS 服务端源码 848M;ssw-acz7015/ = 安全卡方案源码 +ssw-tds/ +ssw-acz7015/ diff --git a/.workbuddy/memory/2026-11-12.md b/.workbuddy/memory/2026-11-12.md new file mode 100644 index 0000000..97a2625 --- /dev/null +++ b/.workbuddy/memory/2026-11-12.md @@ -0,0 +1,50 @@ +# 2026-11-12 可信数据空间部署与真机验证 + +## 完成 +- TDS 平台 + MPC 编排收敛为单 Pod 6 容器(`ssw-tds`,wuguirong),TDC 独立 Deployment;NodePort 30200/30201/30202/30203。验收脚本 verify-tds 9/9、verify-mpc 3/3、connector-online 8/8、publish-tds-product 8/8。 +- 连接器 `TDC-WUGUIRONG-01`(id `890556829011018181`)ONLINE;主体 `890556815866069445` CONNECTED;产品 `PRD-WUGUIRONG-PSI-001` ONLINE/PASS/PRIVACY,TDC ServiceCatalog 可见。 +- 三方真机(AMD 192.168.1.7 sev-snp / 海光 192.168.1.102 hygon-csv / ZYNQ 192.168.1.233 armv7 none)实测:PSI 交集 **84**(三方逐项一致、与本地真值吻合);纵向 LR 4/4 权重逐位一致(`0.3898658752441406 / 0.02921295166015625 / 0.01927947998046875 / -0.03290557861328125`)。 +- 结果落库编排:FlowRun 1(runMode=real)/ StepRun 2 / Artifact 2 / RunEvent 5;结构化证据 `evidence/real-3party-result.json`;报告 `evidence/acceptance-report.html`。 + +## 关键技术结论(别再踩) +- **心跳签名**:本机 OpenSSL 4.0.3 的 `dgst -sha256 -sign -outform DER` 不支持、`pkeyutl` 不摘要 ⇒ Java `SHA256withECDSA` 验签必挂。用 `build/sign-ecdsa.py`(Python cryptography,天然 DER),已与 Java 21 权威对拍通过。 +- **心跳 TTL**:`heartbeatInterval(5s) × graceMultiplier(3) = 15s`,停跳即 OFFLINE ⇒ 主体 CONNECTED 退回 JOINED,产品链路读侧失效。验证期间必须跑 `build/heartbeat-keepalive.py`(默认 5s 一次)。长期方案应由 TDC 自己上报心跳。 +- **上线四闸门**:approval=02 / compliance=01(envInfo + 严格 JSON 数组 ipWhitelist)/ 有效设备证书 certType=02 且公钥一致 / deployment READY + status ONLINE。 +- **产品上架门槛**:`deliveryInfo` 是 varchar(64) 文件标识;`declaration` 需 3 个 slot(complianceAndLegalStatement / dataSourceStatement / aiTrainingLicense);空间 `f_portal_host` 非空;主体 CONNECTED(读时派生);成员角色 DATA_PROVIDER(含 Publish) APPROVED。 +- **实体 JSON 名有 @JsonProperty 别名**:productName / productId / description / limitations / deliveryCapability / unit,别按 Java 字段名猜。 +- **编排是单进程**:缺 `mpc` 二进制(available=false、realExec=false),会话型算子(PSI/LR)按设计降级 simulation ⇒ 真多方计算必须跨机点火,再落库编排。本地有可用 x86_64 musl 静态二进制 `ssw-mpc/target/x86_64-unknown-linux-musl/release/mpc`。 +- **三方会话硬约束**:`--listen + --peers` 网状;party 编号按站点名字典序;启动顺序 carol→bob→alice;密态端口自动 +1;seed/PSK 全体一致;只有 label-owner 给 `--data-y`。ZYNQ 是 BusyBox:无 setsid 用 `nohup … &`,无 base64 用 tar.gz 管道传物料。 + +## 未做(诚实边界,别当成已完成) +- 编排层自动驱动多方会话、TEE guest 内闭环/芯片验签、真实链上存证回执(FISCO 块高 45 可达但 `MPC_CHAIN_URL` 指向同 Pod 回环、缺 `MPC_FISCO_CHAIN_CONFIG`)、编排 PGlite 持久化(默认 memory://,重启清空)、声明/交付材料文件本体(当前为 fileId 清单占位)、下单/账单链路。 + +## 项目空间整理(14:40) +- 新增根目录 `CLAUDE.md`(108 行项目级入口):目录地图 / 环境入口 / 部署形态 / 10 条不变量 / 最短复现路径 / 关键 ID / 诚实边界。与全局 `~/.claude/CLAUDE.md`(硬约定)、上游 `ssw-tds/CLAUDE.md`(变更单流程)明确分工,不重复。 +- 新增 `.gitignore`(防明文密钥与 ~750M 构建中间产物误入库);把 `.tdc-identity-secret`、`tds-k8s.yaml`、`tdc-conn-key/ec.key` 收紧为 600;`gen-tdc-manifest.sh` 加 `umask 077`,`gen-tds-manifest.sh` 用法改 `umask 077; … > yaml` 并修正「四容器」注释为六容器,清单已按新生成器重建(内容仅注释变化)。 +- **未删除任何文件**。疑似冗余只在 CLAUDE.md 列出待确认:`ctx-mpc-flow/`(14M)、`pglite-dl/`(空)、`pglite-linux.tar.gz`(12M)、`ctx-tds-admin/`(370M)、`dist/sspf-*.tar.gz`(163M)。 + +## 设备侧「1 设备 1 卡 1 连接器」改造(15:40 起,进行中) +- 用户纠正:连接器是 `tdc-rs`(此前笔误 tds-rs),必须部署在设备里而非 k8s;1 设备 1 张安全卡(硬/软)+ 1 个连接器;**ZYNQ 不在设备内编译**,交叉编译后(含 pglite ~30MB、常驻 ~20MB)完全跑得动。 +- 实测设备:HG `192.168.1.102` x86_64/glibc 2.28/32GB/有 docker;ZYNQ `192.168.1.233` **armv7l**/glibc **2.26**/509MB(可用 411MB)/6.6GB 磁盘/BusyBox 无 ldd、无 docker;AMD `192.168.1.7` SSH 持续超时。⇒ 资源不是瓶颈。 +- 软卡 `card/`:补齐 `bridge.go` 设备侧自主心跳(TDS 登录密文、HTTP Date 时钟校准、5s 心跳、`/v1/bridge` 状态),`main.go` 接入;`bash card/build.sh` 出 amd64 6.6M / armv7 6.4M 静态二进制。**ZYNQ 上直接实跑通过**(SELFTEST OK + SPKI 公钥导出),证明「编译后直接投放」成立。 +- 真正硬约束(与内存无关):① `pglite-rs` 0.2.7 官方引擎只发 x86_64/aarch64 的 `libpglite.a`(内嵌 PostgreSQL 17.5),**armv7 无包**;② 现有 linux/amd64 `tdc-connector` 要求 `GLIBC_2.34`,HG 2.28 / ZYNQ 2.26 都装不下。 +- 解法:统一交叉编译到 `armv7-unknown-linux-musleabihf`(静态 musl,零设备 libc 依赖)。`pglite-rs-sys` 支持 `PGLITE_LIB_DIR` 覆盖预编译库,`pglite-rs` build.rs 把 `pglite-runtime.tar` 内嵌进二进制 ⇒ 最终仍是「一个静态二进制 + webroot」。上游 `native/build-libpglite.sh` 用 zig cc 交叉编译可产出 libpglite.a + 含 arm 原生 initdb/postgres 的 runtime.tar。 +- 新增 `build/cross-tdc-armv7.sh`:prepare/engine/platform/connector/pack 五阶段,复用运行中的 `sspf-build`(/src=ssw-platform)、`tdc-build`(/src=tdc-rs);产物 `build/dist-device/`(已加 .gitignore)。**进度**:脚本与软卡完成,zig 0.13 / PostgreSQL 固定 commit `06c837c6a303` 源码下载中,engine 编译未开始。 +- 坑:`fetch-platform.sh` 只在 `vendor/sspf-v0.5.0/lib` 不存在时解包 ⇒ 交叉编译前必须删旧 x86_64 闭包,否则静默沿用错架构 rlib;`pglite-rs-sys` 无条件 `-lz` ⇒ 需 armv7-musl 的 libz.a(从 qemu armv7 alpine 导出)。 + +## armv7 平台包验收:glibc 版本不匹配(20:20 起) +- 用户决定让 **ssw-platform 出 armv7 基础包**(决策正确:引擎是上游职责,本项目只消费)。上游已产出 `dist/sspf-v0.5.0-armv7-unknown-linux-gnueabihf.tar.gz`(150M) + `dist/pglite-armv7-unknown-linux-gnueabihf.tar.gz`(10M)。 +- **架构完全正确**:127 个 rlib 目标三元组均为 armv7-unknown-linux-gnueabihf(无 x86_64 残留);引擎 `bin/postgres`/`bin/initdb` = ELF 32-bit ARM EABI5 armhf。 +- **但链接出的产物在老 glibc 上跑不起来**(核心发现): + - `objdump -T`:`postgres`/`initdb` 要求 GLIBC_2.28/2.29/2.33/2.34;`libpq.so.5.17` 要求 2.33。 + - 复现(无需真机):`docker run --platform linux/arm/v7 -v rt:/rt:ro arm32v7/debian:buster`(glibc **2.28**)⇒ `initdb: libc.so.6: version 'GLIBC_2.34' not found`;起 `sspf-admin` ⇒ `[启动失败] 打开数据库失败: boot failed: initdb failed`。 + - **根因**:上游 `build-pglite-engine.sh` 用 `gcc-arm-linux-gnueabihf` + `libc6-dev-armhf-cross`,sysroot 是 **Debian 12 = GLIBC 2.36** ⇒ 符号全绑到 2.34 节点。 + - **关键澄清**:被抬版本号的符号(`sem_*` `shm_open` `dlopen` `stat64` `exp` `log` `pow` `fcntl`)**本身在 2.26 就都存在** ⇒ 不是缺功能,是**版本标签不匹配**,降 sysroot 或改 musl 即可。 + - 上游冒烟没发现的原因:冒烟用 `arm32v7/debian:bookworm-slim`(也是 glibc 2.36),与编译 sysroot 同版本 ⇒ 天然通过。**建议冒烟改 buster(2.28)/stretch(2.24)**。 +- **连接器依赖引擎**:`tdc-rs` 源码无 pglite 引用,但 `src/platform/db.rs` 用 `sspf::Db`(= PGlite 引擎)做持久化,`src/main.rs` 注入平台锁 ⇒ **引擎必须在设备可跑,否则连接器起不来** ⇒ 引擎修复是设备部署的前置条件。 +- 已产出并提交上游(`ssw-platform` commit `5420c0f`,已推送 origin/main):`docs/armv7-glibc-compat.md`(证据链 + 两条修法 + 验收命令)。 +- 本项目新增:`build/check-armv7-runtime.sh`(**设备侧自检**:读设备 glibc 版本 + 列引擎需求 + 真跑 initdb,退出码 0/1 可直接当验收门)、`build/build-engine-musl-armv7.sh`(**musl 静态引擎**交叉编译,方案 A 落地脚本)。 +- musl 方案已本地验证可行:`zig cc -target arm-linux-musleabihf -static` 出静态 armv7 二进制,在 `arm32v7/debian:buster`(glibc 2.28) 与 `alpine:3.20`(musl) 上均实跑通过 ⇒ **静态产物与设备 glibc 版本无关**,ZYNQ 的 2.26 无风险。 +- musl 编译坑:`CC=zig` 不行(autoconf 会调 `zig` 而非 `zig cc` ⇒ "C compiler cannot create executables")⇒ 需包装脚本 `zigcc` 转 `zig cc`。 +- 下载加速:直连 GitHub 被代理限速到 ~20KB/s(600s 超时重下);`ghfast.top` 镜像实测 **1.75MB/s**(快约 45 倍),PostgreSQL 源码 28MB 用它 80 秒下完。 +- 设备状态:ZYNQ(233) 与海光(102) 当晚掉线(ping 不通 / ARP incomplete),仅 AMD(7) 在线。 diff --git a/.workbuddy/memory/2026-11-13.md b/.workbuddy/memory/2026-11-13.md new file mode 100644 index 0000000..fe2a201 --- /dev/null +++ b/.workbuddy/memory/2026-11-13.md @@ -0,0 +1,203 @@ +# 2026-11-13 + +## armv7 PGlite 引擎 glibc 兼容 —— 完全打通(GLIBC 2.34 → 2.18) + +### 交付物 +- 引擎:`/Users/xs/Desktop/workspace/ssw-platform/dist/pglite-engine-armv7-glibc26/` + - `libpglite.a`(838 对象,**库内不含 compat shim**) + - `compat/{glibc26_compat.o, getrandom_compat.o}` ← 链接期注入用 + - `pglite-runtime.tar` / `pglite-runtime-glibc26.tar`(initdb GLIBC 2.14) + - `postgres`(2.17)/ `initdb`(2.14) +- 脚本(`ssw-tds-test/build/`): + - `build-engine-glibc26-armv7.sh` — 引擎重链(8 阶段) + - `zig-cc-armv7-glibc26.sh` — cargo 交叉链接器包装器 + - `cross-build-armv7.sh` — 一键交叉编译 + 容器实跑 + - `getrandom-compat.c` / `glibc26-compat.c` — glibc 2.25 符号 shim + - `sysroot-armhf/` — zlib-only sysroot(libz GLIBC 2.4) + +### 根因与结论(本轮实测) +1. 🔴 **rustc 重打包归档不确定**:pglite-rs-sys 用 `-Wl,--whole-archive` 链整个 + libpglite.a,rustc 会把归档**重打包**到临时目录;对 `glibc26_compat.o` 这类 + 「只被 undefined 引用」的成员处理**时有时无** ⇒ 产物 GLIBC 需求在 2.18/2.25 + 之间随机跳变。**唯一确定方案:compat 不入库,链接期注入。** +2. 🔴 **compat 必须在所有 .a 之后注入**(链接器包装器末尾 append), + 否则与 libc.so.6 的版本化符号冲突(duplicate symbol)。 +3. 🔴 **`getrandom` 弱引用也致命**:链接器把 weak undefined 也写进 + `.gnu.version_r` ⇒ 动态链接器启动即报 "version `GLIBC_2.25' not found"。 +4. 🔴 **`pglite-runtime.tar` 文件名固定**:pglite-rs-sys build.rs 找不到它就 panic; + 且它必须是**本次新构建**的,否则 Rust 侧解包旧 initdb(2.25)。 +5. 🔴 **bash heredoc 会吃掉 `done`**:`for ... do ... done` 写成 `fi` ⇒ 包装器 + 语法错误 ⇒ rustc 静默链接失败、cargo 却报 "Finished" 且无产物。 + ⇒ 用 Write 工具写脚本;写完必须 `bash -n` 验证。 + +### 实测证据 +``` +二进制 GLIBC 最高 = GLIBC_2.18 +arm32v7/debian:stretch (glibc 2.24) → PGLITE_ARMv7_OK +arm32v7/debian:buster (glibc 2.28) → PGLITE_ARMv7_OK +``` + +### 现状 +- 海光 192.168.1.102 / ZYNQ 192.168.1.233 **仍物理离线**(ping 无响应), + armv7 产物暂无法在真机实测;AMD 192.168.1.7 正常。 +- 下一步:用新引擎重编 sspf 平台 armv7 rlib 闭包,再交叉编译 tdc-connector。 + +--- + +## 🔴🔴 上轮结论修正 + 新根因:rustc bundle 内嵌旧引擎 + +### ⚠️ 上轮「全库 0 个 fcntl64 引用」是**假结论** +核验用了 `zig nm` —— **zig 0.14.1 没有 `nm` 子命令**,它打印 usage 文本, +被 `grep -q fcntl64` 过滤成空 ⇒ 结论全假。**本机无 llvm-nm**(rustup 只带 +gcc-ld / rust-lld / rust-objcopy)⇒ 核验 ELF 符号只能用 **Python 手写 ELF32 +解析器**(读 `.symtab`/`.strtab`,判 `st_shndx==0` 即 UNDEF)。 + +### 🎯 新根因(完整链条) +``` +release.sh 隔离 rlib 构建目录 target/rlibbuild-armv7-*/ + └─ build script 缓存(pglite-rs-sys 的 output)仍写�� + cargo:rustc-link-search=native=dist/pglite-engine-armv7 ← 旧引擎! + └─ 换 PGLITE_LIB_DIR 后 build script 不重跑(cargo 按 output 缓存) + └─ rustc **bundle 机制**把 native 静态库打进 rlib + (libpglite_sys.rlib 里有个 `libpglite.a` 成员,ELF 包裹的完整归档) + └─ 旧引擎的 pqcomm.o/postmaster.o/noblock_srv.o/miscinit.o + 是 **Debian GCC 12.2.0** 编译 ⇒ 引用真实 fcntl64(非宏重定向的 pgl_fcntl) + └─ 消费方(tdc-connector)链接 ⇒ ld.lld: undefined symbol: fcntl64 +``` +**判别铁证**:`.comment` 段里 `.comment` 内容 —— +- clang(zig) 版:`clang version 19.1.7 (zig-bootstrap ...)` +- Debian GCC 版:`GCC: (Debian 12.2.0-14) 12.2.0` +- 对象大小:pqcomm.o clang=**84700** vs GCC=**21340**;postmaster.o 159212 vs 46716 + +### 🔴🔴🔴 **真正的元凶:sccache 缓存命中**(最终定位) +rustc 会把 `-L native=<引擎目录>` 的 `libpglite.a` **bundle 进 `libpglite_sys.rlib`**。 +而 **rustc 的编译指纹不含 native 静态库的内容哈希** ⇒ 换引擎后 rustc 认为 +「没变化」⇒ **sccache 直接命中旧缓存**,返回**内嵌旧引擎**的 rlib。 + +⇒ 症状极具迷惑性: +- 引擎目录的 `libpglite.a` 是新的(手工 `zig cc --whole-archive` 直接链**完全正常**) +- build script 的 output 也指向新引擎(`cargo:rustc-link-search=native=<新>`) +- 把引擎目录的 `libpglite.a` **移走**,rustc 仍能链接成功 ⇒ 它根本没读那个文件 +- `cargo clean -p pglite-rs-sys` 清了 12.7MiB,重新生成 rlib —— **内嵌的还是旧库** +- `sccache --show-stats` ⇒ **Cache hits rate 100.00%,Cache misses 0,Compilations 0** + ⇒ 一次真实编译都没发生 + +**⇒ 唯一修复:交叉构建一律 `RUSTC_WRAPPER=""`(绕开 sccache)。** +(`SCCACHE_DISABLE=1` 对本机 sccache 版本**不生效**,实测统计仍是 100% 命中。) + +**固化位置**:`ssw-platform/scripts/release.sh`(CROSS 分支)、`scripts/build-armv7.sh`、 +`ssw-tds-test/build/cross-build-tdc-armv7.sh` —— 三处都加了 `export RUSTC_WRAPPER=""`。 + +### 🔴 三个「库被换掉」的坑(都会伪装成链接期随机失败) +1. **sccache 缓存命中**(真正的元凶,见上) +2. **build script 缓存**:隔离 target 目录里的 pglite-rs-sys output + 记着**上一次的**引擎路径 ⇒ 换引擎不重跑。 + ⇒ 修复:`release.sh` 加 `purge_stale_engine_artifacts()`, + 按 `output` 里的 `cargo:lib_dir=` 比对,删掉指向其它引擎的实例 + 其 rlib。 +3. **`pglite-runtime.tar` 被 `include_bytes!` 烤进 rlib** + (`pglite-rs-sys/src/lib.rs:66`)⇒ 换引擎必须重编 rlib,rlib 换不了。 + +### 🎯 定位手法(可复用) +- 用 `ZIG_LOG=` 跑 `zig-cc-armv7.sh` ⇒ 落盘改写后的**裸路径**参数 + + `.bare-libpglite.a`(链接器真正吃进去的那份归档副本)。 +- 对比源库与 bare 归档:md5 / 成员数 / 每成员大小 / `.comment` 编译器标识。 +- rlib 内嵌 native 库:`zig ar x rlib` → 得到 `libpglite.a`(**ELF 包裹的 ar 归档**, + 真实 `!` 在偏移 52;`ar x` 会报 "truncated or malformed", + **要自己从 `!` 偏移切出来**再解)。 +- ar 长名表:成员名 `/NNN` 要按 `//` 表的偏移解析,否则找不到 `noblock_srv.o`。 +- **核验符号必须手写 ELF32 解析器**:本机无 llvm-nm,rustup 只带 + gcc-ld / rust-lld / rust-objcopy。⚠️ `zig nm` **不是有效命令**(zig 0.14.1 + 没有 nm 子命令,只打印 usage)⇒ 用它核验会得到**全假**的"0 引用"结论。 + + +--- + +## 🔴🔴🔴 两个新根因(2026-11-13 02:30-02:45,armv7 闭包 → tdc-connector 打通) + +### ① `acts: command not found` —— 不是脚本 bug,是「运行中改脚本」自伤 +- 现象:出包编译成功(`Finished in 2m 02s`),但末尾报 + `scripts/release.sh: line 225: acts: command not found`,组装/打包段没执行。 +- 真相:`acts` 是 `purge_stale_engine_artifacts` 的**尾部子串**(arti**f-acts**)。 + bash 执行脚本时是**按字节偏移增量读取**的 ⇒ 我在脚本运行期间编辑了它 + ⇒ bash 从错位的字节位置继续执行,把 `acts` 当成命令。 +- ⚠️ **铁律:后台跑 `release.sh` 期间绝不编辑该文件**(以及任何被 bash 正在读的脚本)。 + 症状具有迷惑性(看似语法错误,实为字节错位)。 +- 证据:`stat` 显示脚本 mtime `02:17:24` 晚于出包启动时间。 + +### ② 🔴🔴🔴 **交叉出包漏掉宿主 proc-macro dylib** ⇒ 消费方 E0463 +- 现象:闭包已产出(127 rlib + 127 rmeta)、tdc-connector 交叉编译报: + ``` + error[E0463]: can't find crate for `axum` / `serde` / `tokio` / `pglite` / `aes` ... + error: cannot find attribute `serde` in this scope + ``` +- 真相:**proc-macro crate 编译期在宿主上执行** ⇒ 交叉编译时 cargo 把它们编成 + **宿主架构**(macOS x86_64)的 `.dylib`,产物落在 + `/release/deps/`(**无 triple 层**), + **不在** `//release/deps/`。 + ⇒ 出包脚本只拷 triple 层 ⇒ **4 个 proc-macro 全丢**: + `serde_derive` / `tokio_macros` / `futures_macro` / `thiserror_impl`。 +- 定位手法:`ls /release/deps/ | grep dylib` vs `ls //release/deps/`, + **两个目录对比**是关键(否则只会看到"target 层很完整"的假象)。 +- 修复:`release.sh` 新增 `RLIB_HOST_DEPS`,收集 host deps 里的 `.dylib`/`.so` 一并进 `lib/`。 +- 配套自检:`cross-build-tdc-armv7.sh` 新增 [1.5] 段 —— 闭包里 proc-macro 为 0 ⇒ 直接失败。 +- **注意**:本机编译(非交叉)时 host 与 target 同层 ⇒ 本来就不漏 ⇒ **这个坑只在交叉包出现**。 + +### ③ 验证:tdc-connector armv7 打通 ✅ +- 产物:`tdc-rs/target/armv7-unknown-linux-gnueabihf/release/tdc-connector` + (79,997,720 字节,ELF 32-bit LSB PIE ARM EABI5,`/lib/ld-linux-armhf.so.3`) +- GLIBC 需求最高 **2.18**(与 sspf-admin 同规格) +- `fcntl64` 无未定义引用 ✅;`explicit_bzero`/`getrandom`/`pgl_fcntl` 本地强符号 ✅ +- 编译耗时 19.85s(闭包零重编,方案 C 生效) + +### ④ armv7 平台闭包核验(新版,含新引擎) +- `dist/sspf-v0.5.0-armv7-unknown-linux-gnueabihf/`:lib/ 385 文件(含 4 dylib)、 + `bin/sspf-admin` 79,965,944 字节、tar.gz 167MB / 2291 条目 +- `libpglite_sys-*.rlib` 内嵌归档 = **11740136 字节** = 新 glibc26 引擎 ✅ + (旧引擎 11487132),内嵌成员含 0 个 `fcntl64` 引用 +- 全部 rlib 内 `.o` 均为真 ARM32(`e_machine=40`)✅ + +### ⑤ armv7 `sspf-admin` exit 100 归属定案 → 提 sspf issue #1 +- **结论:不是引擎/我方重编的问题,是 sspf 平台启动路径的问题**。 + A/B:upstream 11-12 发布包二进制 vs 我用 glibc26 引擎重链的二进制, + 同容器同命令 **都 EXIT=100** ⇒ 与我方改动无关。 +- **干净单变量矩阵**(`/tmp/vertest/matrix.sh`,每 case 全新容器、串行、 + 无并发 armv7 容器,`timeout -k 5 150`,判据 = 退出码): + | stdout | 耗时 | rc | 结果 | + |---|---|---|---| + | 继承 docker pipe | 153s | 124 | ✅ `已启动` + 14255 条示例数据 | + | 普通文件 `> /tmp/srv.log 2>&1` | 36s | **100** | ❌ 仅 46B banner | + | `/dev/null` 字符设备 | 51s | **100** | ❌ stderr 0B | +- **根因**:pglite `initDummyPort()` 设 `s.sock=1`,`-Drecv=pgl_recv`/`-Dsend=pgl_send` + 把 fd 1 当名义 socket;协议同步丢失 → `pgl_longjmp` 命中顶层 buf → + `exit(100)`(`pglitec.c` 带 `-Dexit=pgl_native_exit`)→ `pgl_tramp_top==-1` 真退出。 + `src/backend/src/boot.rs:353 ensure_stdout_for_pglite()` **策略反了**: + 只处理 `S_IFCHR`,且把 fd 1 换成**普通文件**(= 失败形态);注释讲的 kqueue/kevent + 是 macOS 语义,Linux 不适用。`S_IFREG`(最主要部署形态)完全没覆盖。 + ⇒ 应改为「保证 fd 1 是 pipe」+ macOS 分支 cfg 限定。 +- **验收链盲区**:`scripts/build-armv7.sh:137` 冒烟用 `> /tmp/srv.log 2>&1`(=失败形态), + 而 `docs/armv7-build.md:211` 成功验证**无重定向**(=成功形态),两处结论不一致。 +- **已投递**:`ssw/ssw-platform#1`(本地 Gitea `127.0.0.1:13300`,open), + 正文副本 `docs/issue-ssw-platform-armv7-stdout-exit100.md`。 + 关联项一并写进 issue:`PGLITE_RUNTIME_DIR` 跨架构抢占、glibc26 `fcntl64` 整改收编。 +- **踩过的坑(别再犯)**: + ① shell 函数调用重定向 `f > /dev/null` 会被函数体内 `> file` 覆盖 ⇒ 之前 + 「字符设备 vs 普通文件」的因果是伪相关; + ② 多个 armv7 qemu 常驻容器并发会抢资源、刷出 GB 级 FATAL 日志并污染结论 + ⇒ 每次实验前 `docker ps` 清残留; + ③ 成功 case 是常驻服务,必须用 `timeout -k`(纯 `timeout` 发 TERM 后 + `shutdown_pg()` 会挂住不退出)。 +- **部署侧规避(非根治)**:`sspf-admin | cat > app.log`;根治等平台侧修。 +- Gitea 写接口禁用 basic auth(`token is required`)⇒ 用 basic auth 建一次性 token + (`POST /api/v1/users/{u}/tokens`)→ 建 issue → **再用 basic auth DELETE 撤销** + (token 自带 scope 不够会 403)。本次 token 已删净,账号只剩原有 `ontology-feedback`。 + +### ⑥ 文档 / 证据整理(会话交接前) +- 复现证据归档进仓:`evidence/armv7-stdout-matrix.sh`(参数化,传 sspf-admin 路径即可)、 + `evidence/armv7-stdout-matrix.log`、`evidence/armv7-ab-control.log`。 +- `CLAUDE.md` §2 补 `docs/` 与 evidence 新条目;新增 §11「armv7 启动约束 / 平台侧待修」, + 只给结论 + 指针(细节不重复 issue 正文)。 +- handoff 按 `@skill:handoff` 写到系统临时目录 `/tmp/HANDOFF-ssw-tds-test-2026-11-13.md` + (不在工作区)。 +- `/tmp/vertest` 约 2.2G 全是可重建实验产物(`data*` / `pgdata*` / `rt-*` 数据目录、 + 二进制副本、探针源码),**未删**,留待确认;`/tmp/pglite-engine-armv7` 是 + postgres-pglite 源码树(issue 根因引用它),别删。 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fbf9046 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,169 @@ +# ssw-tds-test · 可信数据空间部署与三方真机验证 + +> 项目级入口。**全局硬约定不在这里**:`~/.claude/CLAUDE.md`(软链用户级 MEMORY.md)管 xop、bash 变量、缓存布局、MCP 端点、个人文件安全,仍然生效。 +> 本文件只放本项目特有的「入口 / 凭据位置 / 选型 / 踩过的坑」。进度流水 → `.workbuddy/memory/YYYY-MM-DD.md`;验收结论 → `evidence/acceptance-report.html`;逐步流程 → 各脚本头部注释。 +> ⚠️ `ssw-tds/CLAUDE.md` 是**上游仓库自带**的变更单流程文档,不是本文件,别改写、别跨仓混用。 + +## 1. 这是什么 + +在 `wuguirong` k8s 租户部署一套可运行的可信数据空间,并用三台真 TEE 设备完成「真设备 / 真数据 / 真多方」验证。源码都不在本仓:TDS 平台 `ssw-tds/`(上游 clone,只读参考)、连接器 `../tdc-rs`(Rust)、隐私计算编排 `../ssw-mpc-flow`、真机物料 `../ssw-mpc`。**本仓只持有构建产物、k8s 清单、验收脚本与证据**。 + +根目录**不是 git 仓库**(只有 `ssw-tds/` 是),别在根目录跑 git 命令。2026-11-12 全链路验收全绿。 + +## 2. 目录地图 + +| 路径 | 内容 | +|---|---| +| `CLAUDE.md` / `.gitignore` | 本文件;防御性忽略规则(防明文密钥与 ~750M 中间产物误入库) | +| `build/gen-*.sh` | k8s 清单**唯一真相源**,改配置改这里,别手改 yaml | +| `build/*-k8s.yaml` | 生成物,ConfigMap 内烘了明文密钥 ⇒ 权限 600 | +| `build/Dockerfile.*` / `nginx-mpc.conf` | 7 个镜像的定义(TDS dbinit/web/admin、TDC、MPC backend/web、rust-builder) | +| `build/ctx-*/` | docker build 上下文;`dist/` = sspf linux 闭包 163M;`pglite-*` = PGlite 物料 | +| `build/.env.tds` / `.env.tdc` / `.tdc-identity-secret` / `tdc-conn-key/` | 密钥源与连接器 EC 密钥(私钥 `ec.key` 600) | +| `build/seed-tds-connector.sh` `connector-online.sh` `publish-tds-product.sh` | 数据准备 → 连接器上线 → 产品上架,**顺序不可换** | +| `build/verify-*.sh` `heartbeat-keepalive.py` `sign-ecdsa.py` `record-real-run.mjs` | 验收、心跳保活、ECDSA 签名、真机结果落库 | +| `docs/` | 给上游平台的整改规格与 issue 副本:`armv7-glibc-兼容性整改规格.md`、`issue-ssw-platform-armv7-stdout-exit100.md` | +| `evidence/` | 交付证据:`acceptance-report.html`、`real-3party-result.json`、三机原始日志;`armv7-stdout-matrix.{sh,log}` 与 `armv7-ab-control.log` 为 exit 100 复现证据 | +| `card/` + `ssw-acz7015/` | 软卡实现(Go;`card/dist/softcard-linux-armv7` 等三平台产物已编译)+ 上游安全卡方案 clone;后者自带 CLAUDE.md / README,**别改写** | +| `ssw-tds/` | 上游源码 848M(含 .git),查服务端契约用;自带 CLAUDE.md / README | +| `.workbuddy/memory/` | 工作日志( append-only ) | + +**疑似冗余,未动**(等你确认再处置):`build/ctx-mpc-flow/`(14M 早期上下文,`web/` 空,最终用 `ctx-mpc/`)、`build/pglite-dl/`(空目录)、`build/pglite-linux.tar.gz`(12M,已解压)、`build/ctx-tds-admin/`(370M)、`build/dist/sspf-*.tar.gz`(163M)。都可重建但重建成本高,别用 `rm -rf` 清。 + +## 3. 环境与入口 + +| 项 | 值 | +|---|---| +| kubeconfig | `export KUBECONFIG=~/.kube/kubeconfig-wuguirong`;命名空间 `wuguirong` | +| NodePort | **30200** TDS 前端 / **30201** TDS API / **30202** TDC / **30203** MPC 编排前端;FISCO RPC **30100** | +| 集群入口 | `192.168.1.26`(API 常量统一写成 `http://192.168.1.26:3020x`) | +| 镜像仓 | `crpi-yscq976uwza88qap.cn-shenzhen.personal.cr.aliyuncs.com/ssw188/nginx`(唯一 repo,tag 区分);push 必须 `--provenance=false --sbom=false`;zsh 写 `${REG}:tag` | +| MPC 控制面 | `http://192.168.1.102:3020/nodes`,hostd `http://192.168.1.102:3010`;Bearer 共享密钥取自海光机 `/tmp/mpc-cluster/cluster.secret`,**不写进文档/脚本/仓库** | +| 真机 | AMD `192.168.1.7` sev-snp / 海光 `192.168.1.102` hygon-csv / ZYNQ `192.168.1.233` armv7;xop 键 `tee_amd_7_{user,pass}`、`tee_hg_102_{user,pass}`、`tee_zynq_{user,pass}` | +| 登录 | `POST /api/oauth/Login`,`application/x-www-form-urlencoded`,字段 `account` / `password`(密文) / `grant_type=password` | + +ConfigMap:`ssw-tds-env` / `ssw-tds-deploy-env` / `ssw-mpc-env` / `ssw-tds-nginx`(nginx 配置) / `tdc-env`。SA 无 `create secret` 权限 ⇒ **密钥只能明文进 ConfigMap**。 + +## 4. 部署形态 + +`ssw-tds` 单 Pod **6 容器**(用户明确要求 TDS 与 MPC 编排同 Pod):`db / redis / backend / frontend / mpc-backend / mpc-frontend`;`tdc-connector` 独立 Deployment(PGlite 单进程 ⇒ `strategy: Recreate`,不可多副本共写 PVC)。PVC 走 `nfs-wuguirong`。 + +资源合计 **3500m / 6.88Gi**:LimitRange 的 Pod 上限是 **cpu 4000m / mem 8Gi**,加容器前先算总量。租户约束:容器级 `runAsUser: 10106`、禁 hostPath/nfs 直挂、无 Ingress 只能 NodePort。 + +## 5. 不变量(踩过就别再踩) + +1. **心跳签名**:`signingText = id + "\n" + timestamp(ms) + "\n" + nonce`,`SHA256withECDSA` 的 **DER 字节再 Base64**(Java 语义),±30s 时间窗、nonce 60s TTL。本机 OpenSSL 4.0.3 三条路全废(`dgst -outform DER` 不支持 / `pkeyutl` 不摘要 / `pkeyopt digest:sha256` 报 provider failure)⇒ 一律用 `build/sign-ecdsa.py`(Python `cryptography`,已与 Java 21 权威验签对拍)。公钥是 **EC SPKI DER 的 Base64**。 +2. **心跳 TTL = 5s × 3 = 15s**:停跳即 `OFFLINE` ⇒ 主体 `CONNECTED` 退回 `JOINED`,产品/目录读侧全失效。任何验证前先跑 `heartbeat-keepalive.py`;保活目前是本机后台进程,长期应让 TDC 自报心跳或上 k8s CronJob。 +3. **登录密文**:`AES-256-ECB-Pkcs7`,`CIPHER_KEY = EY8WePvjM5GGwQzn`;key = `md5(CIPHER_KEY)` hex 串的 **ASCII 字节**(32B),data = `md5(明文)` hex 串的 **ASCII 字节**(32B),输出 hex。验证向量:`encryptPassword('123456')` 以 `d4958348e2210811…` 开头。别把 data 再 hex 化一次。 +4. **连接器上线四闸门**:`approval=02` / `compliance=01`(`envInfo` + 严格 JSON 数组 `ipWhitelist`)/ 有效设备证书 `certType=02` 且公钥一致 / `deployment=READY` + `status=ONLINE`。缺一就 `ENVIRONMENT_NOT_COMPLIANT`。 +5. **产品上架门槛**:`deliveryInfo` 是 `varchar(64)` 文件标识(不是长文本);`declaration` 需 3 个 slot;空间 `f_portal_host` 非空;成员角色 `DATA_PROVIDER`(含 Publish) APPROVED;主体 `CONNECTED` = 资质 APPROVED + 企业证书 `certPem` + 在线节点(**读时派生**,无刷新端点)。TDC 侧要先建 `Datasource` + `Resource` 才有 `resourceId`。 +6. **实体 JSON 名有 `@JsonProperty` 别名**:`productName` / `productId` / `description` / `limitations` / `deliveryCapability` / `unit`;`authorize` 是 `Integer` 不是 boolean。别按 Java 字段名猜。 +7. **内部通道**:TDS 用 `X-Internal-Token`(fail-closed);TDC 额外要 `X-Protocol-Version: 3.2`。TDC 内部通道是 `X-Internal-Token` + 协议头,不带会被拒。 +8. **编排是单进程**:容器缺 `mpc` 二进制(`available=false`、`realExec=false`),会话型算子(PSI / 纵向 LR)按设计降级 simulation ⇒ 真多方计算必须**跨机点火 → 回收日志 → `record-real-run.mjs` 落库**,不能指望编排直接跑。本地有可用 x86_64 musl 静态二进制 `../ssw-mpc/target/x86_64-unknown-linux-musl/release/mpc`。 +9. **三方会话纪律**:`--listen + --peers` 网状(`--connect` 只支持两方);party 编号按站点名字典序;启动顺序 **carol → bob → alice**;密态端口自动 +1(9449/9450);`--seed` / `MPC_PSK` 三方同一份;只有 label-owner 给 `--data-y`;ZYNQ 是 BusyBox(无 `setsid` 用 `nohup … &`,无 `base64` 用 tar.gz 管道传物料)。 +10. **镜像构建坑**:buildkit 会忽略名为 `static` 的上下文目录 ⇒ 上下文里叫 `webroot`,Dockerfile 写 `COPY webroot /app/static`;TDC 的 `resolve_project_dir()` 从 exe 向上找 `static/index.html` ⇒ 必须 `/app/bin` + `/app/static`。MPC 后端 readiness 探针是 `/api/ssw/sswflow/Operator/Info`(无 `/api/health`),前端 nginx 监听 80。 + +## 6. 最短复现路径 + +```bash +cd /Users/xs/Desktop/workspace/ssw-tds-test +export KUBECONFIG=~/.kube/kubeconfig-wuguirong + +# 0) 先起保活(单独终端常驻;Ctrl-C 停后 15s 连接器即掉线) +python3 -u build/heartbeat-keepalive.py --duration 0 + +# 1) 生成清单并部署(幂等;umask 保证含密钥的 yaml 是 600) +umask 077; bash build/gen-tds-manifest.sh > build/tds-k8s.yaml +bash build/gen-tdc-manifest.sh +kubectl -n wuguirong apply -f build/tds-k8s.yaml -f build/tdc-k8s.yaml + +# 2) 数据准备 → 上线 → 上架(顺序不可换) +bash build/seed-tds-connector.sh +bash build/connector-online.sh 890556829011018181 3 +bash build/publish-tds-product.sh + +# 3) 验收 +bash build/verify-tds.sh && bash build/verify-mpc.sh + +# 4) 三方真机实测 → 落库编排 +bash build/verify-real-machine-3party.sh all +node build/record-real-run.mjs +``` + +## 7. 关键 ID 与已验证结论 + +| 项 | 值 | +|---|---| +| 空间 / 主体 / 连接器 | `PORTAL-DEMO-SPACE` / `890556815866069445` / `890556829011018181`(`TDC-WUGUIRONG-01`) | +| 产品 / 资源码 | `PRD-WUGUIRONG-PSI-001`(ONLINE·PASS·PRIVACY)/ `RES-20261112-055517-00000001-6VXTFDXE` | +| TDC 身份 / 数据源 | `796502003630080` / `796520084340736` | +| 三方 PSI | 交集 **84**,三机 ID 列表逐项一致,与本地真值吻合 | +| 三方纵向 LR | 4/4 权重逐位一致:`0.3898658752441406 / 0.02921295166015625 / 0.01927947998046875 / -0.03290557861328125` | +| 编排落库 | FlowRun 1(`runMode=real`)/ StepRun 2 / Artifact 2 / RunEvent 5 | + +## 8. 诚实边界(未完成,别当已完成) + +编排层自动驱动多方会话、TEE guest 内闭环与芯片验签、真实链上回执(FISCO 块高 45 可达,但 `MPC_CHAIN_URL` 指向同 Pod 回环且缺 `MPC_FISCO_CHAIN_CONFIG` ⇒ **未伪造回执**)、编排 PGlite 持久化(默认 `memory://`,重启清空,PVC 已挂但 `dataDir` 未指过去)、声明与交付材料文件本体(当前是 fileId 清单占位)、下单/账单链路。 + +## 9. 敏感文件与清理纪律 + +含明文:`build/.env.tds`、`.env.tdc`、`.tdc-identity-secret`、`tds-k8s.yaml`、`tdc-k8s.yaml`、`tdc-conn-key/ec.key` ⇒ 一律 600,`.gitignore` 已全量排除。控制面 Bearer、DB 口令不写进文档 / 脚本 / 任何提交。清 `build/ctx-*`、`dist/`、`pglite-*` 前先列清单确认,禁止 `rm -rf` 批量清缓存(按住用户级硬约定)。 + +--- + +## 10. armv7 交叉编译链路(2026-11-13 已打通) + +### 一键命令 +```bash +# 交叉编译任意 Rust 项目到 armv7(glibc 2.26 动态)并在容器实跑 +bash build/cross-build-armv7.sh [crate-name] +``` + +### 引擎产物 +`ssw-platform/dist/pglite-engine-armv7-glibc26/` +| 文件 | GLIBC 最高 | 说明 | +|---|---|---| +| `libpglite.a` | — | 838 对象,**库内不含 compat shim** | +| `compat/*.o` | — | `explicit_bzero` + `getrandom`,**链接期注入** | +| `postgres` | 2.17 | PGlite 后端 | +| `initdb` | 2.14 | 初始化工具 | +| `pglite-runtime.tar` | 2.14 | pglite-rs-sys 固定按此名加载 | + +### 关键约束(踩过的坑,别回退) +1. **compat 必须在库外**:rustc 用 `-Wl,--whole-archive` 链整个 libpglite.a 时会 + **重打包归档**,对「只被 undefined 引用」的成员处理不确定 ⇒ 时有时无 ⇒ + GLIBC 需求在 2.18/2.25 间随机跳变。库内已有 + 链接期注入 ⇒ duplicate symbol。 +2. **compat 注入位置**:链接器包装器末尾(所有 .a 之后),保证强符号优先于 libc.so.6。 +3. **`getrandom` 弱引用也致命**:链接器把 weak undefined 也写进 `.gnu.version_r` + ⇒ 启动即报 `version GLIBC_2.25 not found`。 +4. **rustc 的 `--target=` 必须丢弃**:zig 不认 `arm-unknown-linux-gnueabihf` 这个 OS 名。 +5. **sysroot 必须 zlib-only**:上游完整 sysroot 的 libc.so.6 是 glibc 2.36 ⇒ 产物绑 2.34+。 +6. **`zig ar -M` 的 `addlib` 会展开归档**:若被展开的归档里有同名旧成员, + 链接器会挑中旧的 ⇒ 必须逐成员 `addmod` 并显式排除旧成员 + (`noblock_srv.o` 引用 fcntl64,是 glibc 2.28+ 符号)。 +7. **`pglite-runtime.tar` 文件名固定**,且必须是本次新构建的,否则解包旧 initdb。 +8. **交叉构建必须 `CARGO_PROFILE_RELEASE_STRIP=none`**。 +9. **写完 shell 脚本必须 `bash -n` 验证**:heredoc 会把 `done` 吃掉写成 `fi` + ⇒ 包装器语法错误 ⇒ rustc 静默失败,cargo 却报 "Finished" 且无产物。 + +### 已验证 +``` +arm32v7/debian:stretch (glibc 2.24) → PGLITE_ARMv7_OK +arm32v7/debian:buster (glibc 2.28) → PGLITE_ARMv7_OK +ssw-platform sspf-admin armv7 → GLIBC_2.18,explicit_bzero/getrandom 均为本地 T +``` + +--- + +## 11. armv7 启动约束 / 平台侧待修(2026-11-13,issue #1) + +**结论**:armv7 `sspf-admin` 只有在 **stdout 是管道**时能完成启动;重定向到普通文件或 `/dev/null` 一律 `exit 100`。A/B 已证实与本项目重编的引擎无关,归属平台侧 `src/backend/src/boot.rs:353 ensure_stdout_for_pglite()`(把字符设备换成普通文件,而普通文件恰是失败形态;注释依据的 kqueue 是 macOS 语义,Linux 不适用)。 + +- 已投递:`ssw/ssw-platform#1` → http://127.0.0.1:13300/ssw/ssw-platform/issues/1(open) +- 完整根因 / 复现 / 修复建议 → `docs/issue-ssw-platform-armv7-stdout-exit100.md`(细节不在此重复) +- 干净矩阵与原始输出 → `evidence/armv7-stdout-matrix.sh` / `.log`;A/B 对照 → `evidence/armv7-ab-control.log` +- 干净实测:pipe ✅ 153s `已启动`;普通文件 ❌ 36s `rc=100`;`/dev/null` ❌ 51s `rc=100` +- **部署侧规避(非根治)**:`sspf-admin | cat > app.log`。平台修复前,任何 `> file` / systemd / CI 重定向的 armv7 部署都会挂;上游 `scripts/build-armv7.sh:137` 的冒烟正是失败形态。 +- 关联待办:`PGLITE_RUNTIME_DIR` 跨架构隔离、glibc26 `fcntl64` 整改收编(见 issue 与 `docs/armv7-glibc-兼容性整改规格.md`) +- **主线仍待办**:三台真机按「1 设备 1 卡 1 连接器」部署(AMD 真机 + 2 沙箱 15/15 全绿;海光 `192.168.1.102`、ZYNQ `192.168.1.233` 仍离线);平台修好后需用新引擎重跑 `scripts/release.sh` 出包 + `build/cross-build-tdc-armv7.sh` 复验。 +- **别再踩**:① shell 函数调用重定向会被函数体内重定向覆盖 ⇒ 早期「字符设备 vs 普通文件」是伪相关;② 多个 armv7 qemu 常驻容器并发会刷 GB 级 FATAL 日志并污染结论,实验前 `docker ps` 清残留;③ 成功 case 是常驻服务,必须用 `timeout -k`(纯 `timeout` 发 TERM 后 `shutdown_pg()` 会挂住)。 diff --git a/build/Dockerfile.mpc-backend b/build/Dockerfile.mpc-backend new file mode 100644 index 0000000..6611c50 --- /dev/null +++ b/build/Dockerfile.mpc-backend @@ -0,0 +1,19 @@ +FROM node:20-bookworm-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl tzdata ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ + && echo "Asia/Shanghai" > /etc/timezone + +WORKDIR /app +COPY backend/package.json /app/package.json +COPY backend/node_modules /app/node_modules +COPY backend/dist /app/dist + +ENV PORT=30001 \ + NODE_ENV=production \ + LANG=C.UTF-8 + +EXPOSE 30001 +CMD ["node", "/app/dist/main.js"] diff --git a/build/Dockerfile.mpc-web b/build/Dockerfile.mpc-web new file mode 100644 index 0000000..5366cf4 --- /dev/null +++ b/build/Dockerfile.mpc-web @@ -0,0 +1,6 @@ +FROM nginx:1.27-alpine + +COPY webroot /usr/share/nginx/html/ +COPY nginx-mpc.conf /etc/nginx/conf.d/default.conf + +EXPOSE 80 diff --git a/build/Dockerfile.rust-builder b/build/Dockerfile.rust-builder new file mode 100644 index 0000000..b21f454 --- /dev/null +++ b/build/Dockerfile.rust-builder @@ -0,0 +1,24 @@ +FROM crpi-yscq976uwza88qap.cn-shenzhen.personal.cr.aliyuncs.com/ssw188/nginx:1.30.4-rust-1.89 + +ENV PATH=/usr/local/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + RUSTUP_DIST_SERVER=https://rsproxy.cn \ + RUSTUP_UPDATE_ROOT=https://rsproxy.cn/rustup \ + CARGO_NET_GIT_FETCH_WITH_CLI=true + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential cmake perl python3 rsync pkg-config zlib1g-dev libssl-dev \ + ca-certificates git \ + && rm -rf /var/lib/apt/lists/* + +RUN rustup toolchain install 1.95.0 --profile minimal && rustup default 1.95.0 && rustc --version + +RUN mkdir -p /usr/local/cargo && printf '%s\n' \ + '[source.crates-io]' \ + 'replace-with = "ipass"' \ + '' \ + '[source.ipass]' \ + 'registry = "sparse+http://192.168.1.26:30097/cargo/"' > /usr/local/cargo/config.toml + +WORKDIR /src diff --git a/build/Dockerfile.tdc b/build/Dockerfile.tdc new file mode 100644 index 0000000..dd34981 --- /dev/null +++ b/build/Dockerfile.tdc @@ -0,0 +1,22 @@ +FROM debian:bookworm-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl tzdata \ + && rm -rf /var/lib/apt/lists/* \ + && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ + && echo "Asia/Shanghai" > /etc/timezone + +# 布局必须让 resolve_project_dir 从 /app/bin 向上找到 /app/static/index.html +# 上下文里目录名用 webroot(buildkit 的默认忽略规则会吃掉名为 static 的目录) +WORKDIR /app +COPY bin/tdc-connector /app/bin/tdc-connector +COPY webroot /app/static + +RUN chmod +x /app/bin/tdc-connector && mkdir -p /app/data + +ENV PORT=30000 \ + TDC_DATA_DIR=/app/data \ + LANG=C.UTF-8 + +EXPOSE 30000 +ENTRYPOINT ["/app/bin/tdc-connector"] diff --git a/build/Dockerfile.tds-admin b/build/Dockerfile.tds-admin new file mode 100644 index 0000000..1d043a9 --- /dev/null +++ b/build/Dockerfile.tds-admin @@ -0,0 +1,14 @@ +FROM r.mayishangshu.cn:82/space/ssw-tds-base:2.0 + +COPY app.jar /app/app.jar + +EXPOSE 30000 + +ENV TZ=Asia/Shanghai \ + LANG=C.UTF-8 + +ENTRYPOINT ["/usr/bin/tini", "--", "java", \ + "-Duser.timezone=Asia/Shanghai", "-Dfile.encoding=UTF-8", \ + "-Djava.awt.headless=true", \ + "-XX:MaxRAMPercentage=70", "-XX:+ExitOnOutOfMemoryError", \ + "-jar", "/app/app.jar"] diff --git a/build/Dockerfile.tds-dbinit b/build/Dockerfile.tds-dbinit new file mode 100644 index 0000000..aa12d89 --- /dev/null +++ b/build/Dockerfile.tds-dbinit @@ -0,0 +1,3 @@ +FROM r.mayishangshu.cn:82/space/ssw-tds-dbinit:2.0.0 +# 用仓内最新迁移真源覆盖镜像内快照(j7 dump 仍用镜像自带的 ≈130MB 全量) +COPY boot/db /ssw/db-src diff --git a/build/Dockerfile.tds-frontend b/build/Dockerfile.tds-frontend new file mode 100644 index 0000000..304b74e --- /dev/null +++ b/build/Dockerfile.tds-frontend @@ -0,0 +1,6 @@ +FROM nginx:1.27-alpine + +# 前端产物(vite build 出 dist);nginx conf 由 ConfigMap 挂 /etc/nginx/conf.d/default.conf +COPY . /usr/share/nginx/html/ + +EXPOSE 8080 diff --git a/build/bind-tdc-to-tds.sh b/build/bind-tdc-to-tds.sh new file mode 100644 index 0000000..2584781 --- /dev/null +++ b/build/bind-tdc-to-tds.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# bind-tdc-to-tds.sh —— 把「设备侧业务连接器(tdc-rs)」绑到「TDS 上的设备连接器」 +# +# 🔴 为什么需要这一步(架构级结论): +# tdc-rs **没有任何出向注册 TDS 的代码**(src/tdc/notify、src/tdc/heartbeat 都是占位模块; +# src/tdc/client/tds.rs 只有目录/账单/应用三类出向)⇒ 设备侧业务连接器**不能自己** +# 在 TDS 上注册成连接器。 +# +# 正解(对齐「1 设备 1 台安全卡 1 个连接器,连接器部署在设备里」): +# · 安全卡(软卡)= **TDS 侧**的设备连接器身份(持 EC 密钥、签心跳、持设备证书) +# · tdc-connector(tdc-rs)= **设备侧**的业务连接器,绑定到上面那条记录 +# · 绑定字段 = tdc_identity.f_tds_connector_id(JSON 键 tdsConnectorId) +# ⇒ 目录/账单/应用出向时用它当 buyerConnectorId / providerConnectorId +# +# 🔴 键名映射:json_key_to_column("tdsConnectorId") = "f_tds_connector_id" +# +# 用法: +# bash build/bind-tdc-to-tds.sh [spaceId] +set -uo pipefail + +TDC_URL="${1:?需要 tdc 基地址,如 http://192.168.1.7:30000}" +LOCAL_ID="${2:?需要设备侧 tdc_identity.id}" +TDS_CID="${3:?需要 TDS 侧 connectorId}" +SPACE_ID="${4:-PORTAL-DEMO-SPACE}" +SPACE_NAME="${SPACE_NAME:-演示空间}" +TDS_EP="${TDS_EP:-http://192.168.1.26:30201}" +INT_TOKEN="${SSW_INTERNAL_TOKEN:-caaa9043f72f04df887361f81dc1026817bd9ee0b7299689}" + +RESP=$(curl -s -m 20 -X PUT "$TDC_URL/api/ssw/tdc/Identity/$LOCAL_ID" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' \ + -d "{\"tdsConnectorId\":\"$TDS_CID\",\"tdsSpaceId\":\"$SPACE_ID\",\"tdsSpaceName\":\"$SPACE_NAME\",\"tdsEndpoint\":\"$TDS_EP\"}" 2>&1) + +if printf '%s' "$RESP" | grep -q '"code":200'; then + echo " ✅ 绑定成功 localId=$LOCAL_ID → tdsConnectorId=$TDS_CID (space=$SPACE_ID)" +else + echo " ❌ 绑定失败: $(printf '%s' "$RESP" | head -c 250)" + exit 1 +fi + +# 回读校验(证明真的落库了,而不是只返回了 200) +curl -s -m 15 -H "X-Internal-Token: $INT_TOKEN" "$TDC_URL/api/ssw/tdc/Identity/$LOCAL_ID" 2>&1 \ + | python3 -c " +import sys, json +d = (json.load(sys.stdin).get('data') or {}) +got = d.get('tdsConnectorId') +print((' ✅ 回读 tdsConnectorId=' + str(got)) if got else ' ❌ 回读为空') +print(' ✅ 回读 tdsSpaceId=' + str(d.get('tdsSpaceId')) if d.get('tdsSpaceId') else ' ❌ 空间未落库') +" diff --git a/build/build-engine-glibc26-armv7.sh b/build/build-engine-glibc26-armv7.sh new file mode 100755 index 0000000..c1822b7 --- /dev/null +++ b/build/build-engine-glibc26-armv7.sh @@ -0,0 +1,696 @@ +#!/usr/bin/env bash +# build-engine-glibc26-armv7.sh +# 用 zig 把上游 ssw-platform 的 armv7 PGlite 引擎**重链为 glibc 2.26 兼容**产物。 +# +# 🔴 为什么要重链(2026-11-12 实测): +# 上游 `dist/pglite-engine-armv7/` 的 initdb/postgres 需 **GLIBC_2.34** +# (sysroot 用的是 Debian 12 bookworm 的 armhf multiarch)⇒ +# · 海光 192.168.1.102 (glibc 2.28) → libc.so.6: version `GLIBC_2.34' not found +# · ZYNQ 192.168.1.233 (glibc 2.26) → 同上,更早失败 +# +# 本脚本**不重编 800+ 个 .o**,只重链 + 重编**引用 fcntl 的 4 个 .o** +# (GLIBC 版本节点是链接期决定的)。 +# 上游 build 树在 /tmp/pglite-engine-armv7/engine-out/build(容器内跑出来的,宿主可复用)。 +# +# 🔴 四个关键技术点(都是实测踩出来的): +# 1. **`_FILE_OFFSET_BITS=64` 必须保持**(2026-11-13 修正,推翻 11-12 的做法): +# upstream 的 838 个 .o 全部是 LFS 语义(off_t=8 / struct stat=104), +# 归档里 22 个成员引用 `stat64`、8 个引用 `lstat64`。 +# 11-12 把它改成 undef 且只重编 4 个 .o ⇒ **ABI 撕裂**(4 vs 8 字节 off_t)。 +# 2. **fcntl 必须绑老符号**(2026-11-13 修正): +# upstream(Debian gcc 头)在 LFS=64 下把 `fcntl` 改写成 `fcntl64` +# (glibc 2.28+ 才有 ⇒ ZYNQ 2.26 跑不了)。 +# 而 **zig 头没有这个覆盖** ⇒ 重编那 4 个 .o 时**不加** `-Dfcntl=pgl_fcntl` +# ⇒ fcntl 解析成 **`fcntl`(GLIBC_2.4)**、stat64 解析成 **`__xstat64`(GLIBC_2.4)** +# ⇒ 三个 glibc(stretch 2.24 / buster 2.28 / bookworm 2.36)**全有** ⇒ ZYNQ 无压力。 +# 🔴 反之若保留 `-Dfcntl=pgl_fcntl`:zig 头下重定向**真的生效**, +# 而 `pgl_fcntl` 在 pglite 激活时 `return 0`(dummy)⇒ 所有 fcntl 失效 +# ⇒ postgres 顶层 longjmp ⇒ **退出码 100**(11-13 实测到的 bug)。 +# 3. upstream 的 build 树里有 **266 个指向容器内 `/work/...` 的失效符号链接** +# (Makefile / pg_config_os.h / lwlocknames.h 等)⇒ 宿主上要重定向 +# 4. `main` 入口:upstream 用 `-Dmain=pgl_backend_main` 重编 main.o(给 libpglite.a 用), +# 但 `postgres` 二进制是 install 前用带真 main 的原始 main.o 链接的。 +# 我们重链时 main.o 已被改名 ⇒ 需要额外的 pglite_entry.c 提供真 main。 +# +# 🔴 为什么选「glibc 动态」而不是「musl 静态」: +# musl 静态链接的 dlopen 是桩(stub_dlopen)⇒ PostgreSQL 无法加载 +# plpgsql.so / dict_snowball.so ⇒ initdb 在 "performing post-bootstrap +# initialization" 阶段 FATAL: could not load library ".../plpgsql.so": +# Dynamic loading not supported。 +# glibc 动态路线保留 dlopen ⇒ 扩展模块正常加载,实测 initdb 全流程 ok。 +# +# 用法: +# bash build/build-engine-glibc26-armv7.sh # 全流程 +# REBUILD_ONLY=1 bash build/build-engine-glibc26-armv7.sh # 复用已有 build 树,只重链 +set -euo pipefail + +WORK="${WORK:-/tmp/pglite-engine-armv7}" +BUILD="$WORK/engine-out/build" +INSTALL="$WORK/engine-out/install" +SRC="$WORK/postgres-pglite" +NATIVE="$WORK/native" +SYSROOT="${SYSROOT:-/Users/xs/Desktop/workspace/ssw-platform/dist/pglite-engine-armv7/sysroot}" +OUT="${OUT:-/Users/xs/Desktop/workspace/ssw-platform/dist/pglite-engine-armv7-glibc26}" +STAGE="${STAGE:-/tmp/rt26}" + +TRIPLE="arm-linux-gnueabihf.2.26" +ZIG="${ZIG:-zig}" + +log() { printf '\n=== %s ===\n' "$*"; } + +[ -d "$BUILD" ] || { echo "FATAL: 缺 upstream build 树: $BUILD" >&2; exit 1; } +[ -d "$SYSROOT" ] || { echo "FATAL: 缺 sysroot: $SYSROOT" >&2; exit 1; } + +WORKG=/tmp/glibc26 +mkdir -p "$WORKG" "$OUT" + +PGINC=( + -I "$BUILD/src/include" + -I "$SRC/src/include" + -I "$SRC/src/port" +) + +# ── 1. 修复 build 树里指向容器内 /work 的失效符号链接 ────────── +log "1/7 修复失效符号链接" +python3 - "$BUILD" "$WORK" <<'PY' +import os, sys +build, work = sys.argv[1], sys.argv[2] +fixed = broken = 0 +for root, dirs, files in os.walk(build): + for name in dirs + files: + p = os.path.join(root, name) + if not os.path.islink(p): + continue + tgt = os.readlink(p) + if not tgt.startswith('/work/'): + continue + rel = tgt[len('/work/'):] + cand = None + if rel.startswith('engine-out/build/'): + cand = os.path.join(build, rel[len('engine-out/build/'):]) + elif rel.startswith('postgres-pglite/'): + cand = os.path.join(work, 'postgres-pglite', rel[len('postgres-pglite/'):]) + if cand and os.path.exists(cand): + os.unlink(p); os.symlink(cand, p); fixed += 1 + else: + broken += 1 +print(f" fixed={fixed} still_broken={broken}") +PY + +# ── 2. 保证 _FILE_OFFSET_BITS=64(**必须保持**,不能改成 undef)──────────── +log "2/7 校验 _FILE_OFFSET_BITS=64(必须保持 LFS,否则 32 位下 off_t ABI 撕裂)" +# +# 🔴🔴🔴 **2026-11-13 重大修正(推翻 2026-11-12 的做法)**: +# +# 11-12 的做法:把 pg_config.h 的 `_FILE_OFFSET_BITS 64` 改成 undef, +# 然后**只重编 4 个 .o**。 +# ⇒ 造成**两个叠加的致命错误**(实测数据见下): +# +# ① **ABI 撕裂**:upstream 的 838 个 .o 全部是 LFS 语义 +# (`stat64`/`lstat64` 22+8 个成员引用,off_t=8 / struct stat=104)。 +# 只重编 4 个 .o ⇒ 这 4 个变成 `off_t=4 / struct stat=88`, +# **同一个二进制里两种 struct stat 布局** ⇒ 运行期随机错位。 +# 实测 ABI:gcc+LFS64 → off_t=8/stat=104;zig 无 LFS → off_t=4/stat=88。 +# +# ② **fcntl 变成 dummy**:`-Dfcntl=pgl_fcntl` 这个重定向在 +# **Debian gcc 头下会被 glibc 覆盖**(`bits/fcntl2.h` 在 +# `_FILE_OFFSET_BITS=64` 时把 fcntl 改写成 fcntl64)⇒ upstream 实际 +# 用的是**真 fcntl64**,pgl_fcntl 根本没被引用(实测 upstream 归档里 +# `pgl_fcntl` 引用数 = 0)。 +# 但在 **zig 头下没有这个覆盖** ⇒ 重定向**真的生效** ⇒ +# `pgl_fcntl` 在 pglite 激活时 `return 0`(dummy)⇒ +# **所有 fcntl 调用失效**(F_GETFL 返回 0 ⇒ socket 变阻塞) +# ⇒ postgres 顶层 longjmp ⇒ **退出码 100**(本次要修的 bug)。 +# +# ⇒ **正确解法**:保持 `_FILE_OFFSET_BITS=64`(ABI 与其余 834 个 .o 一致), +# 只重编那 4 个 .o,但**去掉 `-Dfcntl=pgl_fcntl`** ⇒ +# zig 头在 LFS=64 下把 fcntl 解析成 **老符号 `fcntl`(GLIBC_2.4)** +# (实测 buster 2.28 / stretch 2.24 实跑通过), +# 把 stat64 解析成 **`__xstat64`(GLIBC_2.4)** +# (实测三个 glibc 全有该符号)⇒ **GLIBC 需求压到 2.4,ZYNQ 2.26 无压力**。 +python3 - "$BUILD/src/include/pg_config.h" <<'PY' +import sys +p = sys.argv[1] +s = open(p, encoding='utf-8').read() +if '#define _FILE_OFFSET_BITS 64' in s: + print(" already ok (LFS=64)") +elif '/* #undef _FILE_OFFSET_BITS */' in s: + s = s.replace('/* #undef _FILE_OFFSET_BITS */', '#define _FILE_OFFSET_BITS 64', 1) + open(p, 'w', encoding='utf-8').write(s) + print(" ✅ restored: _FILE_OFFSET_BITS=64(11-12 被改成 undef,11-13 已修正)") +else: + print(" ⚠️ pg_config.h 里找不到 _FILE_OFFSET_BITS 行,请人工确认") +PY +grep -n "_FILE_OFFSET_BITS" "$BUILD/src/include/pg_config.h" | head -3 + +# ── 3. 重编引用 fcntl64 的 4 个 .o ─────────────────────────── +log "3/7 重编引用 fcntl64 的源文件" +# +# 🔴🔴 **必须带 upstream 的全部 pglite `-D` 重定向宏**(2026-11-12 实测): +# upstream 用 `-Dgetsockname=pgl_getsockname` 等把 socket/进程调用重定向到 +# pglite 的桩函数(pglitec.c),因为 pglite 是嵌在 WASM/单进程里跑的, +# backend **没有真 socket**。 +# 我最初重编时漏了这组宏 ⇒ pqcomm.o 直接引用真 `getsockname` +# ⇒ 实跑报 `FATAL: getsockname() failed: Socket operation on non-socket`。 +# +# 🔴🔴 **2026-11-13 修正:`-Dfcntl=pgl_fcntl` 必须去掉**(见第 2 步的详细说明): +# upstream 在 **Debian gcc 头**下,glibc 的 `bits/fcntl2.h` 会把 +# `_FILE_OFFSET_BITS=64` 时的 `fcntl` 改写成 `fcntl64` +# ⇒ upstream 实际用的是**真 fcntl64**,pgl_fcntl 引用数 = 0。 +# 而 **zig 头没有这个覆盖** ⇒ 若保留 `-Dfcntl=pgl_fcntl`,重定向会**真的生效** +# ⇒ pgl_fcntl 在 pglite 激活时 `return 0`(dummy) +# ⇒ 所有 fcntl 调用失效 ⇒ postgres 顶层 longjmp ⇒ **退出码 100**。 +# 去掉后:zig 头在 LFS=64 下把 fcntl 解析成**老符号 `fcntl`(GLIBC_2.4)** +# ⇒ 不需要任何 shim,且 buster 2.28 / stretch 2.24 实跑通过。 +# +# 🔴🔴 **必须显式带 `_FILE_OFFSET_BITS=64`**: +# zig 默认不开 LFS(off_t=4 / struct stat=88),与 upstream 其余 834 个 .o +# (off_t=8 / struct stat=104)**ABI 不一致** ⇒ 必须显式打开。 +# 实测:zig + `-D_FILE_OFFSET_BITS=64` ⇒ off_t=8 / stat=104, +# 与 gcc+LFS64 **逐项一致**(flock=32 sockaddr_in=16 socklen_t=4 也一致)。 +# +# 🔴🔴 **必须用数组,不能用多行字符串变量**(2026-11-12 实测踩坑): +# bash 里 `DEFS="-Da=1 \` + 换行 + `-Db=2"` 展开后是一个**带换行的单词**, +# 传给 zig cc 会被当成**单个参数** ⇒ 除第一个宏外全部丢失 ⇒ 现象是 +# "预处理展开对了但 .o 里还是 getsockname"(极具迷惑性)。 +# ⇒ 一律用数组 + "${ARR[@]}" 展开。 +PGLITE_DEFS=( + -D__PGLITE__ -U_FORTIFY_SOURCE + -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE + -Dsystem=pgl_system -Dpopen=pgl_popen -Dpclose=pgl_pclose + -Dgeteuid=pgl_geteuid -Dgetuid=pgl_getuid -Dgetpwuid=pgl_getpwuid + -Dexit=pgl_exit -Dmunmap=pgl_munmap + -Datexit=pgl_atexit + -Dsetsockopt=pgl_setsockopt -Dgetsockopt=pgl_getsockopt -Dgetsockname=pgl_getsockname + -Drecv=pgl_recv -Dsend=pgl_send -Dconnect=pgl_connect + -Dpoll=pgl_poll + -Dshmget=pgl_shmget -Dshmat=pgl_shmat -Dshmdt=pgl_shmdt -Dshmctl=pgl_shmctl + -Dlongjmp=pgl_longjmp -Dsiglongjmp=pgl_siglongjmp -Dsetitimer=pgl_native_setitimer +) + +RECOMPILE=( + "src/port/noblock.c:noblock_srv.o" + "src/backend/utils/init/miscinit.c:miscinit.o" + "src/backend/postmaster/postmaster.c:postmaster.o" + "src/backend/libpq/pqcomm.c:pqcomm.o" +) +for pair in "${RECOMPILE[@]}"; do + src="${pair%%:*}"; out="${pair##*:}" + "$ZIG" cc -target "$TRIPLE" -O2 -fPIC -w "${PGINC[@]}" "${PGLITE_DEFS[@]}" \ + -c "$SRC/$src" -o "$WORKG/$out" 2>&1 | grep -E '\berror\b' || true + if [ ! -f "$WORKG/$out" ]; then + echo "FATAL: 重编失败: $src" >&2; exit 1 + fi + echo " $out: $(stat -f %z "$WORKG/$out" 2>/dev/null || stat -c %s "$WORKG/$out") bytes" +done + +# 🔴 校验:pglite 重定向宏必须真的生效(否则实跑会 getsockname on non-socket) +# 判据:pqcomm.o 的 undefined 里有 pgl_getsockname / pgl_getsockopt / pgl_setsockopt +# 且**没有**裸的 getsockname / getsockopt / setsockopt。 +# +# 🔴🔴 **不能用 `nm -u`**(2026-11-13 实测): +# macOS 自带 nm 只认 Mach-O,对 ELF **静默输出空** ⇒ 校验形同虚设; +# 本机无 llvm-nm;`zig nm` 在 zig 0.14.1 **不是有效子命令**(只打 usage)。 +# ⇒ 改用手写 ELF32 解析器(build/elf-undef-scan.py),直接读 .symtab。 +ELFSCAN="$(cd "$(dirname "$0")" && pwd)/elf-undef-scan.py" +[ -f "$ELFSCAN" ] || { echo "FATAL: 缺 ELF 解析器 $ELFSCAN" >&2; exit 1; } + +echo "--- 4 个重编 .o 的未定义符号校验 ---" +check_undef() { # $1=.o $2=符号名 → 打印数量 + python3 - "$1" "$2" <<'PY' +import sys, struct +path, want = sys.argv[1], sys.argv[2] +d = open(path, 'rb').read() +e = '<' if d[5] == 1 else '>' +shoff = struct.unpack_from(e+'I', d, 0x20)[0] +shent = struct.unpack_from(e+'H', d, 0x2E)[0] +shnum = struct.unpack_from(e+'H', d, 0x30)[0] +secs = [] +for i in range(shnum): + o = shoff + i*shent + secs.append((struct.unpack_from(e+'I', d, o+4)[0], + struct.unpack_from(e+'I', d, o+16)[0], + struct.unpack_from(e+'I', d, o+20)[0], + struct.unpack_from(e+'I', d, o+24)[0], + struct.unpack_from(e+'I', d, o+36)[0])) +n = 0 +for t, off, sz, link, ent in secs: + if t != 2: continue + _, soff, ssz, _, _ = secs[link] + for k in range(sz // (ent or 16)): + so = off + k*(ent or 16) + st_name = struct.unpack_from(e+'I', d, so)[0] + st_shndx = struct.unpack_from(e+'H', d, so+14)[0] + if st_name == 0 or st_shndx != 0: continue + end = d.find(b'\x00', soff+st_name, soff+ssz) + if end > 0 and d[soff+st_name:end].decode('latin-1') == want: + n += 1 +print(n) +PY +} + +fail=0 +for pair in "${RECOMPILE[@]}"; do + out="${pair##*:}" + # ① fcntl64 必须为 0(否则 glibc<2.28 跑不了) + n64=$(check_undef "$WORKG/$out" fcntl64) + # ② pgl_fcntl 必须为 0(它是 dummy,会让所有 fcntl 失效 ⇒ exit 100) + npg=$(check_undef "$WORKG/$out" pgl_fcntl) + # ③ fcntl 必须是 1(老符号,GLIBC_2.4) + nfc=$(check_undef "$WORKG/$out" fcntl) + printf " %-18s fcntl64=%s pgl_fcntl=%s fcntl=%s\n" "$out" "$n64" "$npg" "$nfc" + [ "$n64" = "0" ] || { echo " ❌ $out 仍引用 fcntl64" >&2; fail=1; } + [ "$npg" = "0" ] || { echo " ❌ $out 仍引用 pgl_fcntl(dummy ⇒ fcntl 全失效)" >&2; fail=1; } + [ "$nfc" = "1" ] || { echo " ❌ $out 未绑定老符号 fcntl" >&2; fail=1; } +done + +# ④ LFS ABI 一致性:miscinit.o 必须引用 stat64(不能是 stat)—— +# 否则 32 位下 off_t 4 vs 8 字节撕裂(2026-11-13 exit 100 的根因之一)。 +s64=$(check_undef "$WORKG/miscinit.o" stat64) +s4=$(check_undef "$WORKG/miscinit.o" stat) +printf " %-18s stat64=%s stat=%s\n" "miscinit.o" "$s64" "$s4" +[ "$s64" -ge 1 ] || { echo " ❌ miscinit.o 缺 stat64 ⇒ LFS ABI 不一致" >&2; fail=1; } +[ "$s4" = "0" ] || { echo " ❌ miscinit.o 引用了非 LFS 的 stat ⇒ ABI 撕裂" >&2; fail=1; } + +[ "$fail" = "0" ] || { echo "FATAL: 重编 .o 的符号校验未通过" >&2; exit 1; } +echo " ✓ fcntl64=0 / pgl_fcntl=0 / fcntl=1 / stat64 保持 LFS" + +# ⑤ pglite 的 socket 重定向必须生效(否则实跑 getsockname on non-socket) +pgl_ok=1 +for s in pgl_getsockname pgl_getsockopt pgl_setsockopt; do + n=$(check_undef "$WORKG/pqcomm.o" "$s") + [ "$n" -ge 1 ] || { echo " ⚠️ pqcomm.o 缺 $s 重定向" >&2; pgl_ok=0; } +done +for s in getsockname getsockopt setsockopt; do + n=$(check_undef "$WORKG/pqcomm.o" "$s") + [ "$n" = "0" ] || { echo " ⚠️ pqcomm.o 仍有裸 $s(pglite 宏未生效)" >&2; pgl_ok=0; } +done +[ "$pgl_ok" = "1" ] || { echo "FATAL: pglite 重定向宏未生效" >&2; exit 1; } +echo " ✓ pglite 重定向宏已生效(pgl_getsockname/pgl_getsockopt/pgl_setsockopt)" + +# ── 4. 编码函数桥接 + 真 main 入口 ────────────────────────── +log "4/7 编译 enc_bridge.o 与 pglite_entry.o" +cat > "$WORKG/enc_bridge.c" <<'EOF' +/* + * enc_bridge.c —— libpq 公开编码函数名 → libpgcommon 私有名 的桥接 + * + * 背景:PostgreSQL 的 src/interfaces/libpq/fe-exec.c 在 #ifdef __PGLITE__ 下把 + * libpq **内部**调用重定向到 _private 版本,但 fe-misc.c / fe-connect.c 仍调公开名。 + * upstream 靠动态库 libpq.so(链 libpgcommon_shlib.a,公开名)解决; + * 我们静态链 libpq.a ⇒ libpgcommon.a 只有私有名 ⇒ 需要桥接。 + * + * 只转发**函数**,不转发数据表(pg_enc2name_tbl 等)—— 数据表必须只有一份。 + */ +extern int pg_char_to_encoding_private(const char *name); +extern const char *pg_encoding_to_char_private(int encoding); +extern int pg_valid_server_encoding_id_private(int encoding); + +int pg_char_to_encoding(const char *name) { return pg_char_to_encoding_private(name); } +const char *pg_encoding_to_char(int encoding) { return pg_encoding_to_char_private(encoding); } +int pg_valid_server_encoding_id(int encoding) { return pg_valid_server_encoding_id_private(encoding); } +EOF + +cat > "$WORKG/pglite_entry.c" <<'EOF' +/* + * pglite_entry.c —— armv7/glibc2.26 引擎的真正入口 + * + * upstream 用 -Dmain=pgl_backend_main 重编 src/backend/main/main.o(给 libpglite.a 用), + * 于是该 .o 只导出 pgl_backend_main、没有 main ⇒ 链接期报 undefined symbol: main。 + * upstream 能跑是因为它的 postgres 二进制是 install **之前**用带真 main 的原始 + * main.o 链接的。我们重链时 main.o 已被改名 ⇒ 需要本文件提供真 main。 + */ +extern int pgl_backend_main(int argc, char **argv); +int main(int argc, char *argv[]) { return pgl_backend_main(argc, argv); } +EOF + +for f in enc_bridge pglite_entry; do + "$ZIG" cc -target "$TRIPLE" -O2 -fPIC -w -c "$WORKG/$f.c" -o "$WORKG/$f.o" +done +echo " ✓ enc_bridge.o / pglite_entry.o" + +# 🔴 glibc 兼容 shim(把 GLIBC 2.25 需求降到 2.18) +# · explicit_bzero —— glibc 2.25 才有的符号;PostgreSQL 17(be-secure-common.c / +# hmac.c / hmac_openssl.c)用它清零敏感缓冲区,Rust std 也会用。 +# 本地强符号实现 = memset + 编译器屏障,语义等价。 +# · getrandom —— glibc 2.25 才有的符号;Rust std 的 RandomState 播种哈希用。 +# ⚠️ 即使是**弱引用**(weak undefined),链接器也会把它写进 +# .gnu.version_r ⇒ 动态链接器启动即报 "version `GLIBC_2.25' not found"。 +# 本地实现走 syscall(SYS_getrandom),Linux 3.17+ 内核原生支持。 +GLIBC_COMPAT_SRC="$(cd "$(dirname "$0")" && pwd)/glibc26-compat.c" +GETRANDOM_COMPAT_SRC="$(cd "$(dirname "$0")" && pwd)/getrandom-compat.c" +if [ ! -f "$GLIBC_COMPAT_SRC" ]; then + echo "FATAL: 缺少 $GLIBC_COMPAT_SRC" >&2; exit 1 +fi +if [ ! -f "$GETRANDOM_COMPAT_SRC" ]; then + echo "FATAL: 缺少 $GETRANDOM_COMPAT_SRC" >&2; exit 1 +fi +"$ZIG" cc -target "$TRIPLE" -O2 -fPIC -w -c "$GLIBC_COMPAT_SRC" -o "$WORKG/glibc26_compat.o" +"$ZIG" cc -target "$TRIPLE" -O2 -fPIC -w -c "$GETRANDOM_COMPAT_SRC" -o "$WORKG/getrandom_compat.o" +echo " ✓ glibc26_compat.o(explicit_bzero → memset)" +echo " ✓ getrandom_compat.o(getrandom → syscall)" + +# ── 5. 重链 postgres ─────────────────────────────────────── +log "5/7 重链 postgres" +python3 - "$BUILD" "$WORKG" <<'PY' +import glob, os, sys +build, workg = sys.argv[1], sys.argv[2] +files = glob.glob(os.path.join(build, 'src/backend/**/objfiles.txt'), recursive=True) + \ + glob.glob(os.path.join(build, 'src/timezone/**/objfiles.txt'), recursive=True) +objs = set() +for f in files: + for line in open(f, encoding='utf-8', errors='replace'): + for tok in line.split(): + # objfiles.txt 里记的是相对 build 树的路径(也可能带 ./ 前缀) + objs.add(os.path.normpath(tok)) +repl = { + 'src/port/noblock_srv.o': os.path.join(workg, 'noblock_srv.o'), + 'src/backend/utils/init/miscinit.o': os.path.join(workg, 'miscinit.o'), + 'src/backend/postmaster/postmaster.o': os.path.join(workg, 'postmaster.o'), + 'src/backend/libpq/pqcomm.o': os.path.join(workg, 'pqcomm.o'), +} +objs = sorted(repl.get(o, o) for o in objs) +with open('/tmp/pg_objs_final.txt', 'w') as fh: + fh.write("\n".join(objs) + "\n") +print(f" backend objs: {len(objs)}") +PY + +cat > "$WORKG/rsp_postgres.txt" <> "$WORKG/rsp_postgres.txt" +cat >> "$WORKG/rsp_postgres.txt" < 0 else len(longname))].decode() + return n.rstrip('/') +paths = [] +for i, (n, s, b) in enumerate(ms): + base = rs(n).rstrip('/') + if base in ('', '/', '//'): continue + if base == 'noblock_srv.o': + # 🔴 upstream 的 noblock_srv.o 引用 fcntl64(glibc 2.28+)⇒ 用我们的干净版本 + paths.append(new_noblock) + continue + fn = os.path.join(outdir, f"{i:03d}_{os.path.basename(base)}") + open(fn, 'wb').write(b) + paths.append(fn) +with open(listing, 'w') as fh: + fh.write("\n".join(paths) + "\n") +print(f" port objs: {len(paths)}") +PY +# 🔴 用 Python 解出的成员(含干净的 noblock_srv.o)重建归档 +rm -f "$WORKG/libpgport_srv_g26.a" +{ + echo "create $WORKG/libpgport_srv_g26.a" + while IFS= read -r o; do echo "addmod $o"; done < "$WORKG/port_objs.txt" + echo "save"; echo "end" +} | "$ZIG" ar -M +echo " ✓ libpgport_srv_g26.a" + +(cd "$BUILD" && "$ZIG" cc "@$WORKG/rsp_postgres.txt") + +# ── 6. 重链 initdb ───────────────────────────────────────── +log "6/7 重链 initdb" +cat > "$WORKG/rsp_initdb.txt" < "$WORKG/rsp_libpq.txt" < " + objdump -T "$WORKG/libpq.so.5.17" 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -V -u | tr '\n' ' ' + echo +fi + +# ── 6c. 重建 libpglite.a(替换 4 个被污染的成员)──────────── +log "6c/7 重建 libpglite.a" +# +# 🔴🔴 **必须重建**(2026-11-12 实测): +# upstream 的 libpglite.a 里也含 noblock_srv.o / pqcomm.o / miscinit.o / postmaster.o, +# 这 4 个成员是**不带 pglite 重定向宏**的旧版本(直接引用真 getsockname), +# 且引用 fcntl64(glibc 2.28+ 才有)⇒ 海光(2.28)/ZYNQ(2.26) 跑不了。 +# ⇒ 必须用第 3 步重编好的 4 个 .o 替换进去。 +# +# 🔴 打包手法:沿用 upstream 脚本的 `ar -M` 模式(`addmod` 逐成员添加)。 +# ⚠️ **不能用**「`zig ar x` 解包 → 覆盖 → `zig ar rcs` 重打包」: +# upstream 库里 relation.o / analyze.o / sequence.o 各有 2 个**同名成员**, +# 解包到文件系统会 basename 冲突 ⇒ 重打包时静默丢失(实测丢 3 个)⇒ 链接期才爆。 +# `ar -M` 的 addmod 逐个追加,天然支持同名成员。 +# +# 🔴 libpgport_srv.a 里也含旧的 noblock_srv.o ⇒ 用第 5 步生成的 g26 版本替换。 +rm -rf "$WORKG/libx"; mkdir -p "$WORKG/libx" +cp "$WORKG/libpgport_srv_g26.a" "$WORKG/libx/libpgport_srv.a" + +python3 - "$BUILD" "$WORKG" <<'PY' +import glob, os, sys +build, workg = sys.argv[1], sys.argv[2] +files = glob.glob(os.path.join(build, 'src/backend/**/objfiles.txt'), recursive=True) + \ + glob.glob(os.path.join(build, 'src/timezone/**/objfiles.txt'), recursive=True) +objs = set() +for f in files: + for line in open(f, encoding='utf-8', errors='replace'): + for tok in line.split(): + objs.add(os.path.normpath(tok)) +# 🔴 替换成第 3 步重编好的(带 pglite 宏、去掉 fcntl64 的)4 个对象 +repl = { + 'src/port/noblock_srv.o': os.path.join(workg, 'noblock_srv.o'), + 'src/backend/utils/init/miscinit.o': os.path.join(workg, 'miscinit.o'), + 'src/backend/postmaster/postmaster.o': os.path.join(workg, 'postmaster.o'), + 'src/backend/libpq/pqcomm.o': os.path.join(workg, 'pqcomm.o'), +} +missing = [k for k in repl if k not in objs] +if missing: + print(" ⚠️ objfiles.txt 里找不到:", missing) +out = sorted(repl.get(o, o) for o in objs) +with open(os.path.join(workg, 'lib_objs.txt'), 'w') as fh: + fh.write("\n".join(out) + "\n") +print(f" backend objs: {len(out)}") +PY + +(cd "$BUILD" && { + echo "create $WORKG/libpglite_g26.a" + while IFS= read -r o; do echo "addmod $o"; done < "$WORKG/lib_objs.txt" + # 🔴🔴 libpgport_srv.a 必须**逐成员 addmod**,不能用 `addlib`! + # upstream 的 libpgport_srv.a 里有个**旧版 noblock_srv.o**(引用 fcntl64, + # fcntl64 是 glibc 2.28 才有的符号 ⇒ 海光 2.28 勉强、ZYNQ 2.26 跑不了)。 + # 我们在第 5 步已重建了带 pglite 宏、且 fcntl 绑老符号的干净版本。 + # 但 `addlib` 会把归档**展开**加入 ⇒ 库里同时存在两个同名 noblock_srv.o + # ⇒ 链接器挑中了 upstream 的那个 ⇒ undefined symbol: fcntl64。 + # ⇒ 这里用 addmod 逐个加入,并显式跳过 upstream 的 noblock_srv.o。 + while IFS= read -r o; do echo "addmod $o"; done < "$WORKG/port_objs.txt" + # libpgcommon_srv.a 里没有 fcntl64 引用(已核),用 addlib 即可 + echo "addlib src/common/libpgcommon_srv.a" + echo "addmod ../pglitec.o"; echo "addmod ../pglite_native.o" + echo "addmod ../pglite_reset.o"; echo "addmod ../pglite_static_ext.o" + # 🔴 compat shim **不放进静态库** —— 见下方「契约」说明。 + # Rust 侧(pglite-rs-sys)用 `-Wl,--whole-archive` 链整个 libpglite.a, + # rustc 会把归档**重打包**到临时目录;重打包过程对 + # glibc26_compat.o 这类「只被 undefined 引用、不被任何 .o 主动引用」 + # 的成员处理不确定 ⇒ 表现为时有时无 ⇒ explicit_bzero 时而 T 时而 + # U@GLIBC_2.25 ⇒ 产物 GLIBC 需求在 2.18 与 2.25 之间随机跳变。 + # 若放在库里 + 链接期再注入 ⇒ duplicate symbol 链接失败。 + # ⇒ 唯一确定方案:库内不含 compat,由链接期(zig cc 包装器)注入。 + echo "save" + echo "end" +} | "$ZIG" ar -M) + +cp -f "$WORKG/libpglite_g26.a" "$OUT/libpglite.a" + +# 🔴 compat shim 随引擎一起交付,供 Rust 侧交叉链接期注入 +mkdir -p "$OUT/compat" +cp -f "$WORKG/glibc26_compat.o" "$OUT/compat/glibc26_compat.o" +cp -f "$WORKG/getrandom_compat.o" "$OUT/compat/getrandom_compat.o" +echo " ✓ compat/ 已导出(Rust 侧链接期注入用)" + +# --- 校验 --- +printf " 成员数: "; "$ZIG" ar t "$OUT/libpglite.a" 2>/dev/null | wc -l | tr -d ' ' +echo "" +echo " --- 关键成员符号校验(fcntl64 应为 0,pgl_fcntl 应为 0)---" +# 🔴 不能用 `nm -u`(macOS nm 只认 Mach-O,对 ELF 静默输出空 ⇒ 校验形同虚设) +# ⇒ 用手写 ELF32 解析器直接读归档每个成员的 .symtab。 +python3 "$ELFSCAN" "$OUT/libpglite.a" fcntl64 pgl_fcntl fcntl stat64 stat \ + 2>&1 | sed -n '/关键符号引用成员/,$p' | sed 's/^/ /' +echo " --- 导出符号(pglite-rs-sys FFI 依赖)---" +# 🔴 nm 对归档的输出格式是 `00000058 T pgl_backend_main`(地址 + 类型 + 名字), +# 用 `grep -qE " T $s\$"` 判断会漏($ 前还有空格)⇒ 改用 awk 精确匹配第 3 字段。 +for s in pgl_backend_main pgl_native_call pgl_shmem_reset ProcessStartupPacket; do + if nm "$OUT/libpglite.a" 2>/dev/null | awk -v s="$s" '$2=="T" && $3==s {found=1} END{exit !found}'; then + echo " ✓ $s" + else + echo " ⚠️ 缺 $s" >&2 + fi +done +if nm "$OUT/libpglite.a" 2>/dev/null | awk '$2=="T" && $3=="main" {found=1} END{exit !found}'; then + echo " ⚠️ libpglite.a 含 main(会与 pglite-rs-sys 的 FFI 冲突)" >&2 +else + echo " ✓ 无 main(符合 pglite-rs-sys 契约)" +fi +# 🔴 compat 必须在库外(Rust 侧重打包不确定 ⇒ 库内成员会时有时无) +# ⚠️ 只匹配我们自己的 shim 名;PostgreSQL 自带的 oracle_compat.o 是合法成员。 +if "$ZIG" ar t "$OUT/libpglite.a" 2>/dev/null | grep -qE "glibc26_compat|getrandom_compat"; then + echo " ⚠️ libpglite.a 里仍有 compat shim(会导致 Rust 侧 GLIBC 版本随机跳变)" >&2 +else + echo " ✓ 无 compat shim 成员(由链接期注入)" +fi + +# ── 7. 组装 runtime + 验收 ───────────────────────────────── +log "7/7 组装 runtime 并验收" +rm -rf "$STAGE"; mkdir -p "$STAGE/bin" "$STAGE/lib/postgresql" "$STAGE/lib" +cp -R "$INSTALL/share" "$STAGE/" +cp "$WORKG/postgres" "$STAGE/bin/postgres" +cp "$WORKG/initdb" "$STAGE/bin/initdb" +cp "$INSTALL/lib/postgresql/"*.so "$STAGE/lib/postgresql/" 2>/dev/null || true +# libpq.so.5(libpqwalreceiver.so 依赖)+ libz(postgres 依赖) +if [ -f "$WORKG/libpq.so.5.17" ]; then + cp "$WORKG/libpq.so.5.17" "$STAGE/lib/libpq.so.5.17" + (cd "$STAGE/lib" && ln -sf libpq.so.5.17 libpq.so.5 && ln -sf libpq.so.5.17 libpq.so) +fi +cp "$SYSROOT/lib/libz.so.1" "$STAGE/lib/" 2>/dev/null || true + +echo "--- GLIBC 版本需求 ---" +for f in "$STAGE/bin/postgres" "$STAGE/bin/initdb"; do + printf " %-28s => " "$(basename "$f")" + objdump -T "$f" 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -V -u | tr '\n' ' ' + echo +done + +echo "--- 在 glibc 2.28 (armv7) 容器实跑 initdb ---" +docker run --rm --platform linux/arm/v7 -v "$STAGE:/rt:ro" arm32v7/debian:buster sh -c ' + /rt/bin/initdb -D /tmp/pg -U check --no-sync -A trust -E UTF8 2>&1 | tail -4 +' 2>&1 | tail -6 + +tar -C "$STAGE" -cf "$OUT/pglite-runtime-glibc26.tar" \ + share/postgresql lib/postgresql lib bin/postgres bin/initdb +ls -lh "$OUT/pglite-runtime-glibc26.tar" + +# 🔴 pglite-rs-sys 的 build.rs 固定找 **`pglite-runtime.tar`**(不带后缀那个), +# 找不到就 panic: +# "no pglite-runtime.tar or pglite-runtime.tar.zst in " +# ⇒ 必须让这个文件名指向**本次新构建**的 runtime,否则 Rust 侧会解包 +# 上一版的 initdb(GLIBC_2.25)⇒ 在 glibc<2.25 的机器上启动即失败。 +cp -f "$OUT/pglite-runtime-glibc26.tar" "$OUT/pglite-runtime.tar" + +# 🔴 根部也放一份新二进制(方便直接取用),避免拿到旧版 +cp -f "$WORKG/postgres" "$OUT/postgres" +cp -f "$WORKG/initdb" "$OUT/initdb" + +echo "--- 交付产物 GLIBC 需求(最终核对)---" +for f in "$OUT/postgres" "$OUT/initdb"; do + printf " %-12s => " "$(basename "$f")" + objdump -T "$f" 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -V -u | tr '\n' ' ' + echo +done +echo "--- pglite-runtime.tar 内 initdb ---" +rm -rf /tmp/rtv && mkdir -p /tmp/rtv +tar -C /tmp/rtv -xf "$OUT/pglite-runtime.tar" bin/initdb 2>/dev/null +printf " initdb => " +objdump -T /tmp/rtv/bin/initdb 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -V -u | tr '\n' ' ' +echo + +log "完成:$OUT" diff --git a/build/build-engine-musl-armv7.sh b/build/build-engine-musl-armv7.sh new file mode 100644 index 0000000..72efe46 --- /dev/null +++ b/build/build-engine-musl-armv7.sh @@ -0,0 +1,269 @@ +#!/usr/bin/env bash +# build-engine-musl-armv7.sh —— 交叉编译 armv7-musl **静态** PGlite 引擎(验证修复方案) +# +# 🔴 背景(2026-11-12 实测): +# ssw-platform 的 armv7 平台包用 Debian 12 的 GLIBC 2.36 当 sysroot ⇒ 引擎被绑定到 +# GLIBC_2.34 版本节点 ⇒ 在 glibc 2.28(海光)就已经起不来: +# initdb: libc.so.6: version `GLIBC_2.34' not found +# ZYNQ 是 glibc 2.26,更跑不了。 +# 但**所有被抬高版本号的符号本身在 2.26 就都存在**(sem_*/shm_open/dlopen/stat64/ +# exp/log/pow/fcntl)⇒ 只要链接时的 libc 版本 ≤ 目标设备版本即可。 +# +# 本脚本走**方案 A:musl 静态**,让产物与设备 glibc 完全无关: +# - zig cc -target arm-linux-musleabihf 自带 musl libc(zig 0.14.1 已验证) +# - 静态链接 ⇒ 设备端零 libc 依赖,ZYNQ 的 2.26 无风险 +# +# 产物(/tmp/musl-engine/out): +# libpglite.a 静态库(armv7-musl) +# pglite-runtime.tar runtime(含 postgres/initdb/libpq,全静态) +# +# 用法:bash build/build-engine-musl-armv7.sh +set -euo pipefail + +WORK="/tmp/musl-engine" +SRC="$WORK/src" +NATIVE="$WORK/native" +OUT="$WORK/out" +BUILD="$OUT/build" +PREFIX="$OUT/install" +PG_TAR="${PG_TAR:-/tmp/cross-dl/pg.tar.gz}" +ZIG="${ZIG:-zig}" +TRIPLE="arm-linux-musleabihf" +TARGET_TRIPLE="armv7-unknown-linux-musleabihf" + +# 🔴 autoconf 的 CC= 需要一个**真可执行文件**;zig 必须显式 "zig cc", +# 所以 CC=zig 会让 configure 去调 `zig`(打印 usage 退出)⇒ 报 +# "C compiler cannot create executables"。用包装脚本转成 `zig cc`。 +ZIGCC="$WORK/zigcc" +cat > "$ZIGCC" <<'ZIGCC_EOF' +#!/bin/sh +exec zig cc "$@" +ZIGCC_EOF +chmod +x "$ZIGCC" + +log() { printf '\n=== %s ===\n' "$*"; } + +command -v "$ZIG" >/dev/null || { echo "缺 zig" >&2; exit 1; } +[ -f "$SRC/configure" ] || { echo "缺 PostgreSQL 源码: $SRC" >&2; exit 1; } + +mkdir -p "$OUT" "$BUILD" "$PREFIX" + +# ── 1. 打补丁(Linux 相关,win32 跳过) ───────────────────── +log "1/5 打补丁" +for p in "$NATIVE"/patches/*.patch; do + b="$(basename "$p")" + case "$b" in *win32*) continue ;; esac + if patch -d "$SRC" -p1 --forward --dry-run < "$p" >/dev/null 2>&1; then + patch -d "$SRC" -p1 --forward < "$p" >/dev/null && echo " patched: $b" + elif patch -d "$SRC" -p1 --forward --dry-run -R < "$p" >/dev/null 2>&1; then + echo " already applied: $b" + else + echo " FATAL: patch does not apply: $b" >&2; exit 1 + fi +done + +# ── 2. 胶水层(pglitec + native) ─────────────────────────── +log "2/5 编译胶水层 (musl)" +PGLITEC_COMPAT="-include stdlib.h -include stdbool.h" +"$ZIGCC" -target "$TRIPLE" -O2 -fPIC $PGLITEC_COMPAT -Dexit=pgl_native_exit \ + -c "$SRC/pglite/src/pglitec/pglitec.c" -o "$OUT/pglitec.o" +for c in pglite_native pglite_reset pglite_static_ext; do + "$ZIGCC" -target "$TRIPLE" -O2 -fPIC -I"$NATIVE" \ + -c "$NATIVE/$c.c" -o "$OUT/$c.o" +done +ls -lh "$OUT"/*.o + +# ── 3. configure(musl 交叉) ─────────────────────────────── +log "3/5 configure (musl 交叉)" +# 🔴 交叉编译时 configure 跳过 --export-dynamic 探测 ⇒ 必须强制(否则扩展模块 dlopen +# 解析不到 CurrentMemoryContext 等 backend 符号)。cache 变量名带 pg 前缀。 +export pgac_cv_prog_cc_LDFLAGS_EX_BE__Wl___export_dynamic=yes +export LDFLAGS_EX_BE="-Wl,--export-dynamic" + +# 🔴🔴 **AR/RANLIB 必须是能处理 Linux ELF 的交叉版**: +# 宿主机是 macOS ⇒ 系统 `ar` 是 **Apple Archive**,只认 Mach-O; +# 喂 ELF 目标文件它会**静默跳过**(只留一个 `__.SYMDEF SORTED`)⇒ 归档是空的 ⇒ +# 链接期报一堆 `undefined symbol: pg_fprintf / pg_qsort / pg_strerror` +# (这些符号确实在 port/snprintf.o、port/qsort.o 里,只是没进归档)。 +# 上游 `build-libpglite-cross.sh` 用 `${TARGET}-ar`(Linux binutils)正是为此; +# 本机没有 binutils ⇒ 用 **`zig ar`**(LLVM Archiver,与 zig cc 同源,能处理 ELF)。 +# `zig ar` 同时支持 `ar -M` 的 MRI 脚本(打包 libpglite.a 要用)。 +ZIGAR="$WORK/zigar" +cat > "$ZIGAR" <<'ZIGAR_EOF' +#!/bin/sh +exec zig ar "$@" +ZIGAR_EOF +chmod +x "$ZIGAR" + +ZIGRANLIB="$WORK/zigranlib" +cat > "$ZIGRANLIB" <<'ZIGRANLIB_EOF' +#!/bin/sh +exec zig ranlib "$@" +ZIGRANLIB_EOF +chmod +x "$ZIGRANLIB" + +if [ ! -f "$BUILD/config.status" ]; then + (cd "$BUILD" && "$SRC/configure" \ + --prefix="$PREFIX" \ + --host="$TRIPLE" \ + --build="$(uname -m)-pc-linux-musl" \ + --without-icu \ + --without-readline \ + --without-zlib \ + CC="$ZIGCC" \ + CFLAGS="-O2 -fPIC -target $TRIPLE" \ + AR="$ZIGAR" RANLIB="$ZIGRANLIB" \ + "$@") +fi + +# ── 4. make ───────────────────────────────────────────────── +log "4/5 make(最慢,约 10~30 分钟)" +PGLITE_DEFS="-D__PGLITE__ -U_FORTIFY_SOURCE \ +-Dsystem=pgl_system -Dpopen=pgl_popen -Dpclose=pgl_pclose \ +-Dgeteuid=pgl_geteuid -Dgetuid=pgl_getuid -Dgetpwuid=pgl_getpwuid \ +-Dexit=pgl_exit \ +-Dmunmap=pgl_munmap \ +-Dfcntl=pgl_fcntl \ +-Datexit=pgl_atexit \ +-Dsetsockopt=pgl_setsockopt -Dgetsockopt=pgl_getsockopt -Dgetsockname=pgl_getsockname \ +-Drecv=pgl_recv -Dsend=pgl_send -Dconnect=pgl_connect \ +-Dpoll=pgl_poll \ +-Dshmget=pgl_shmget -Dshmat=pgl_shmat -Dshmdt=pgl_shmdt -Dshmctl=pgl_shmctl \ +-Dlongjmp=pgl_longjmp -Dsiglongjmp=pgl_siglongjmp \ +-Dsetitimer=pgl_native_setitimer" + +# 🔴🔴🔴 **COPT 的宏名必须与 pglitec.c 里实际定义的符号逐字一致**(照抄上游 +# native/build-libpglite.sh 的 PGLITE_DEFS,��个字母都不能差): +# +# 上游(对) 我之前写错(错) +# -Dpclose=pgl_pclose → -Dpclose=pgl_close ✗ pglitec.c 定义的是 pgl_pclose +# -Dshmget=pgl_shmget → -Dshmget=pgl_shmemget ✗ pglitec.c 定义的是 pgl_shmget +# -Dexit=pgl_exit → -Dexit=pgl_native_exit ✗ pglitec.c 里没有 pgl_native_exit +# +# 后果:链接期报 `undefined symbol: pgl_close / pgl_shmemget`, +# 编译器还贴心地提示 "did you mean: pgl_pclose" —— 提示就是答案。 +# 胶水层 pglitec.o 是在**没有 COPT** 的情况下单独编的(见上文第 2 步), +# 所以它的符号名就是源码里的真名;COPT 只是给 PG 主体用的重定向表。 +# 🔴 胶水层自己的编译要用 -Dexit=pgl_native_exit(pglitec.c 内部要覆盖 exit), +# 这个只影响胶水层自身,别混进 PG 主体的 COPT。 + +NPROC="$( (command -v nproc >/dev/null 2>&1 && nproc) || sysctl -n hw.ncpu )" +LINK_OBJS="$OUT/pglitec.o $OUT/pglite_native.o" + +# 🔴 **不要在 make 命令行覆盖 LDFLAGS**: +# PG 的 `Makefile.global` 里是 `LDFLAGS = $(LDFLAGS_INTERNAL) @LDFLAGS@`, +# 而 `LDFLAGS_INTERNAL = -L$(top_builddir)/src/port -L$(top_builddir)/src/common` +# —— 命令行传 `LDFLAGS=...` 会**整条覆盖**这个展开式(命令行变量优先级最高), +# 于是 PG 自己的 `-L` 全丢 ⇒ 链接期报 +# error: unable to find dynamic system library 'pgcommon' using strategy 'paths_first' +# (libpgcommon.a / libpgport.a 是 build 树里的**静态库**,找不到就该静态链,不是动态库)。 +# +# 静态链接本身**不需要手动加 -static**:zig cc 对 `arm-linux-musleabihf` 目标 +# 默认就产出静态 ELF(实测 `file` = "statically linked",无 NEEDED 条目)。 +# 所以正确做法 = **只加 LDFLAGS_EX(PG 自己的对象)**,别碰 LDFLAGS。 +# 🔴 AR/RANLIB 用命令行覆盖(优先级高于 Makefile.global 里 configure 固化的 `AR = ar`), +# 否则 macOS 的 Apple Archive 会静默跳过 ELF 目标文件 ⇒ 归档为空 ⇒ undefined symbol。 +make -C "$BUILD" -j"$NPROC" CC="$ZIGCC" AR="$ZIGAR" RANLIB="$ZIGRANLIB" COPT="$PGLITE_DEFS" \ + LDFLAGS_EX="$LINK_OBJS" \ + LDFLAGS_EX_BE="-Wl,--export-dynamic" \ + LDFLAGS_SL="" + +make -C "$BUILD" install CC="$ZIGCC" AR="$ZIGAR" RANLIB="$ZIGRANLIB" COPT="$PGLITE_DEFS" \ + LDFLAGS_EX="$LINK_OBJS" LDFLAGS_EX_BE="-Wl,--export-dynamic" LDFLAGS_SL="" + +# 🔴🔴🔴 **initdb 必须静态链接**(本轮新发现): +# postgres 本体已经是静态的(`file` = statically linked),但 **initdb 不是** —— +# 因为 `src/bin/initdb/Makefile` 的 `LDFLAGS_INTERNAL += ... $(libpq_pgport)`, +# 而 `libpq = -L$(libpq_builddir) -lpq` ⇒ 链接器优先挑 `libpq.so.5.17` +# ⇒ initdb 变成动态链接 musl 的 ELF(interpreter = /lib/ld-musl-armhf.so.1)。 +# +# 后果:海光(glibc 2.28)/ ZYNQ(glibc 2.26)**根本没有 musl 动态加载器** +# ⇒ 真机上 initdb 直接 "Could not open '/lib/ld-musl-armhf.so.1'" 跑不起来。 +# +# 修法 = 单独重链 initdb,强制 `-Wl,-Bstatic` 并把 libpq.a 的**绝对路径**喂进去 +# (`-L` 目录里同时有 .so 和 .a,靠 `-Bstatic` 决定挑哪个,但显式写 .a 更稳)。 +# ⚠️ 不能改 Makefile.global 的 `libpq` 变量 —— 那是全树共享的, +# 改了会让 libpq.so 自己也变静态(下游 libpq_pgport_shlib 依赖它)。 +LIBPQ_A="$BUILD/src/interfaces/libpq/libpq.a" +if [ -f "$LIBPQ_A" ]; then + echo "--- 重链 initdb 为静态 ---" + (cd "$BUILD/src/bin/initdb" && \ + "$ZIGCC" $(make -C "$BUILD/src/bin/initdb" -n initdb 2>/dev/null | grep -o '\-O2[^&|;]*CFLAGS[^&|;]*' | head -1 || echo "-O2 -fPIC -target $TRIPLE") \ + findtimezone.o initdb.o localtime.o \ + -L"$BUILD/src/port" -L"$BUILD/src/common" -L"$BUILD/src/fe_utils" \ + -Wl,-Bstatic "$LIBPQ_A" "$BUILD/src/fe_utils/libpgfeutils.a" \ + "$BUILD/src/port/libpgport.a" "$BUILD/src/common/libpgcommon.a" \ + -Wl,-Bdynamic -lm -o initdb_static \ + 2>&1 | tail -20) + if [ -f initdb_static ] && [ -x initdb_static ]; then + file -b initdb_static + if file -b initdb_static | grep -q "statically linked"; then + mv -f initdb_static initdb + echo " ✓ initdb 已改为静态链接" + make -C "$BUILD/src/bin/initdb" install CC="$ZIGCC" >/dev/null 2>&1 || \ + cp -f "$BUILD/src/bin/initdb/initdb" "$PREFIX/bin/initdb" + else + echo " ✗ 仍非静态,保留原 initdb" + fi + else + echo " ✗ 重链失败,保留原 initdb" + fi +fi + +rm -f "$BUILD/src/backend/main/main.o" +make -C "$BUILD/src/backend/main" main.o CC="$ZIGCC" COPT="$PGLITE_DEFS -Dmain=pgl_backend_main" + +# ── 5. 打包静态库 + runtime ──────────────────────────────── +log "5/5 打包 libpglite.a + pglite-runtime.tar" +BACKEND_OBJS="$(cd "$BUILD" && cat $(find src/backend src/timezone -name objfiles.txt) | tr ' ' '\n' | sed '/^$/d' | sort -u)" + +(cd "$BUILD" && { + echo "create libpglite.a" + for o in $BACKEND_OBJS; do echo "addmod $o"; done + echo "addlib src/common/libpgcommon_srv.a" + echo "addlib src/port/libpgport_srv.a" + echo "addmod ../pglitec.o"; echo "addmod ../pglite_native.o" + echo "addmod ../pglite_reset.o"; echo "addmod ../pglite_static_ext.o" + echo "save" + echo "end" +} | "$ZIGAR" -M && mv -f libpglite.a "$OUT/libpglite.a") + +# 验收:归档必须**真的有成员**(macOS ar 会留下只有 __.SYMDEF 的空壳) +echo "--- libpglite.a 成员数 ---" +"$ZIGAR" t "$OUT/libpglite.a" 2>/dev/null | wc -l + +tar -C "$PREFIX" --exclude lib/postgresql/pgxs \ + -cf "$OUT/pglite-runtime.tar" \ + share/postgresql lib/postgresql "bin/initdb" "bin/postgres" + +ls -lh "$OUT/libpglite.a" "$OUT/pglite-runtime.tar" + +# ── 6. 验收:静态性 + GLIBC 无关 + 容器实跑 ──────────────── +log "6/6 验收" +RT="$WORK/rt"; rm -rf "$RT"; mkdir -p "$RT" +tar -xf "$OUT/pglite-runtime.tar" -C "$RT" +for f in "$RT/bin/postgres" "$RT/bin/initdb"; do + [ -x "$f" ] || continue + echo "--- $f ---" + file -b "$f" + if objdump -T "$f" 2>/dev/null | grep -q 'GLIBC_'; then + echo " 仍需 GLIBC: $(objdump -T "$f" | grep -oE 'GLIBC_2\.[0-9]+' | sort -uV | tail -1)" + else + echo " ✓ 无 GLIBC 版本依赖(静态 musl)" + fi +done + +echo +echo "=== 在 glibc 2.28 的 armv7 容器里实跑 initdb ===" +docker run --rm --platform linux/arm/v7 -v "$RT:/rt:ro" arm32v7/debian:buster sh -c ' + /rt/bin/initdb -D /tmp/pg -U check --no-sync -A trust -E UTF8 2>&1 | tail -6 + echo "initdb_exit=$?" +' 2>&1 | tail -10 + +echo +echo "=== 在 alpine armv7 (musl) 里实跑 initdb ===" +docker run --rm --platform linux/arm/v7 -v "$RT:/rt:ro" alpine:3.20 sh -c ' + /rt/bin/initdb -D /tmp/pg -U check --no-sync -A trust -E UTF8 2>&1 | tail -4 +' 2>&1 | tail -6 + +log "完成:$OUT" diff --git a/build/check-armv7-runtime.sh b/build/check-armv7-runtime.sh new file mode 100755 index 0000000..c9812ee --- /dev/null +++ b/build/check-armv7-runtime.sh @@ -0,0 +1,131 @@ +#!/bin/sh +# check-armv7-runtime.sh —— 设备侧「引擎可用性」自检(放到设备上直接跑) +# +# 🔴 为什么需要它(2026-11-12): +# ssw-platform 的 armv7 平台包(dist/sspf-v0.5.0-armv7-unknown-linux-gnueabihf.tar.gz) +# 里的 pglite 引擎是**动态链接 glibc** 的,且链接时用的 sysroot 是 Debian 12 的 +# GLIBC 2.36 ⇒ 所有符号被打上 GLIBC_2.34 / GLIBC_2.33 / GLIBC_2.29 / GLIBC_2.28 +# 版本节点。 +# 实测(arm32v7/debian:buster,glibc 2.28): +# /rt/bin/initdb: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.34' not found +# ⇒ **在 glibc 2.28 上就起不来**,ZYNQ(glibc 2.26)更无可能。 +# +# 注意:这些符号(sem_*/shm_open/dlopen/stat64/exp/log/pow/fcntl)**本身在 2.26 +# 就都存在**,只是版本号被绑高了 ⇒ 不是「缺功能」,是「版本节点不匹配」。 +# +# 本脚本在**设备上**判定引擎能否跑: +# 1) 读设备自己的 glibc 版本 +# 2) 列出引擎二进制需要的最高 GLIBC 版本 +# 3) 两者对比 ⇒ 直接给出「能不能跑」的结论 +# 4) 真的起一次 initdb,拿退出码做最终裁决 +# +# 用法(设备上): +# sh check-armv7-runtime.sh /opt/ssw/rt # rt = 解开的 pglite-runtime.tar 目录 +# sh check-armv7-runtime.sh /opt/ssw/rt bin/initdb +# +# 退出码:0=可用 / 1=不可用(版本不匹配或起不来)/ 2=用法错误 +set -u + +RT="${1:-}" +BIN_REL="${2:-}" +RC=0 + +if [ -z "$RT" ]; then + echo "用法: $0 [bin 相对路径]" >&2 + exit 2 +fi +[ -d "$RT" ] || { echo "目录不存在: $RT" >&2; exit 2; } + +# ── 1. 设备 glibc 版本 ───────────────────────────────────── +echo "=== 设备环境 ===" +ARCH="$(uname -m 2>/dev/null || echo unknown)" +echo "arch : $ARCH" + +# 设备 libc 路径:Debian 系在 /lib/arm-linux-gnueabihf/,精简镜像在 /lib/ +LIBC="" +for c in /lib/arm-linux-gnueabihf/libc.so.6 /lib/libc.so.6 /usr/lib/libc.so.6; do + [ -e "$c" ] && { LIBC="$c"; break; } +done +if [ -n "$LIBC" ]; then + echo "libc : $LIBC" + echo "libc ver : $( { "$LIBC" 2>&1 || true; } | head -1 )" + # 设备 libc 自带的最高 GLIBC 版本号 + DEV_MAX="$( { strings "$LIBC" 2>/dev/null || true; } | grep -oE 'GLIBC_2\.[0-9]+' | sort -u -V | tail -1 )" + echo "dev max : ${DEV_MAX:-未知}" +else + echo "libc : 未找到 libc.so.6" + DEV_MAX="" +fi + +# ── 2. 引擎二进制 ────────────────────────────────────────── +echo +echo "=== 引擎二进制 ===" +if [ -z "$BIN_REL" ]; then + BIN_REL="bin/initdb" +fi +BIN="$RT/$BIN_REL" +if [ ! -x "$BIN" ]; then + # 试几个常见位置 + for cand in bin/initdb bin/postgres; do + if [ -x "$RT/$cand" ]; then BIN="$RT/$cand"; break; fi + done +fi +if [ ! -x "$BIN" ]; then + echo "找不到可执行文件(试过 bin/initdb、bin/postgres)" >&2 + exit 2 +fi +echo "binary : $BIN" +echo "file : $(file "$BIN" 2>/dev/null || echo '(设备无 file 命令)')" + +# ── 3. 需要的最高 GLIBC 版本 ─────────────────────────────── +NEED="" +if command -v objdump >/dev/null 2>&1; then + NEED="$(objdump -T "$BIN" 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -u -V | tail -1)" +elif command -v readelf >/dev/null 2>&1; then + NEED="$(readelf -V "$BIN" 2>/dev/null | grep -oE 'GLIBC_2\.[0-9]+' | sort -u -V | tail -1)" +else + # 设备上没有 binutils ⇒ 直接让动态加载器说话(最权威) + echo "设备无 objdump/readelf ⇒ 直接试跑,由动态加载器裁决" +fi +echo "need max : ${NEED:-未知}" + +# ── 4. 结论 ──────────────────────────────────────────────── +echo +if [ -n "$NEED" ] && [ -n "$DEV_MAX" ]; then + need_n="$(echo "$NEED" | sed 's/GLIBC_2\.//')" + dev_n="$(echo "$DEV_MAX" | sed 's/GLIBC_2\.//')" + if [ "$need_n" -le "$dev_n" ] 2>/dev/null; then + echo "==> 版本兼容: 需要 GLIBC_2.$need_n <= 设备 GLIBC_2.$dev_n ✓" + else + echo "==> ✗ 版本不兼容: 需要 GLIBC_2.$need_n > 设备 GLIBC_2.$dev_n" + echo " ⇒ 引擎在此设备上无法启动。修复:上游用 glibc <= 设备版本的 sysroot 重编," + echo " 或改用 musl 静态链接(armv7-unknown-linux-musleabihf,零设备 libc 依赖)。" + RC=1 + fi +fi + +# ── 5. 真跑一次(最终裁决) ──────────────────────────────── +echo +echo "=== 实跑 initdb(最终裁决) ===" +TMPD="$(mktemp -d 2>/dev/null || echo /tmp/initdb-check-$$)" +mkdir -p "$TMPD" 2>/dev/null +OUT="$( { "$BIN" -D "$TMPD" -U check --no-sync -A trust -E UTF8 2>&1; } 2>&1 )" +EC=$? +echo "$OUT" | head -8 +if [ $EC -eq 0 ]; then + echo "==> initdb 退出码 0 ⇒ 引擎在���设备上真的可用 ✓" + RC=0 +else + echo "==> initdb 退出码 $EC ⇒ 引擎在此设备上不可用 ✗" + RC=1 +fi +rm -rf "$TMPD" 2>/dev/null + +echo +echo "=== 结论 ===" +if [ $RC -eq 0 ]; then + echo "PASS:armv7 引擎可在目标设备运行" +else + echo "FAIL:armv7 引擎在目标设备上不可运行(glibc 版本不匹配)" +fi +exit $RC diff --git a/build/connector-online.sh b/build/connector-online.sh new file mode 100644 index 0000000..b07ec87 --- /dev/null +++ b/build/connector-online.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +# TDS 连接器审批 + 心跳上线。 +# +# 🔴 协议口径(照 ConnectorServiceImpl.heartbeat 源码,不猜): +# signingText = connectorId + "\n" + timestamp + "\n" + nonce +# 签名算法 = SHA256withECDSA(P-256),DER 编码后 Base64 +# 公钥口径 = EC SPKI DER 的 Base64(与注册时登记的同一把) +# 时间窗 = ±30s(tds.heartbeat.timestamp-skew-ms) +# nonce = 一次性(60s TTL),重放会被拒 +# +# 用法: bash build/connector-online.sh [心跳轮数] +set -uo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$SCRIPT_DIR" + +API="${TDS_API:-http://192.168.1.26:30201}" +CID="${1:?需要连接器 id}" +ROUNDS="${2:-3}" +KEYDIR="$SCRIPT_DIR/tdc-conn-key" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +CIPHER_KEY="EY8WePvjM5GGwQzn" +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} + +[ -f "$KEYDIR/ec.key" ] || { echo "缺私钥 $KEYDIR/ec.key,先跑 seed-tds-connector.sh" >&2; exit 1; } + +echo "=== 1. admin 登录 ===" +ENCPW=$(enc_pwd "123456") +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] && p 1 "登录成功" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 160)"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 接入审批 PASS ===" +AUD=$(curl -s -m 25 -X PUT "$API/api/ssw/tds/Connector/$CID/Audit" -H "$H" \ + -H 'Content-Type: application/json' \ + -d '{"auditStatus":"PASS","auditOpinion":"部署验收通过:tdc-rs 连接器已部署于 wuguirong 租户"}' 2>&1) +printf '%s' "$AUD" | grep -q '"code":200' \ + && p 1 "审批完成: $(printf '%s' "$AUD" | head -c 100)" \ + || p 0 "审批失败: $(printf '%s' "$AUD" | head -c 250)" + +# 🔴 上线四道闸门(照 operationalFailureReason 顺序): +# ① approvalStatus=02 ← 第 2 步审批 PASS 派生 +# ② complianceStatus=01 ← 环境申报(envInfo + ipWhitelist 严格 JSON 数组)派生 +# ③ deploymentStatus ∈ {UNMANAGED, READY} +# ④ 设备证书有效(cert_type=02, status=02, 在有效期内, 公钥与连接器登记一致) +echo "=== 2.1 环境申报(派生 complianceStatus=01)===" +INT_TOKEN="${SSW_INTERNAL_TOKEN:-$(kubectl -n "${K8S_NS:-wuguirong}" get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}' 2>/dev/null)}" +[ -n "$INT_TOKEN" ] || { p 0 "取不到 SSW_INTERNAL_TOKEN(kubectl 读 ConfigMap 失败)"; exit 1; } +ENVREP=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/EnvReport" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' \ + -d "{\"connectorId\":\"$CID\",\"envInfo\":\"TEE:amd-sev-snp,hygon-csv,zynq-tEE;OS:debian-bookworm;Runtime:tdc-rs/0.1.0;K8s:ns=wuguirong,node=sswcc29\",\"ipWhitelist\":\"[\\\"192.168.1.26\\\",\\\"192.168.1.7\\\",\\\"192.168.1.102\\\",\\\"192.168.1.233\\\"]\"}" 2>&1) +printf '%s' "$ENVREP" | grep -q 'ENV_COMPLIANT' \ + && p 1 "环境合规: $(printf '%s' "$ENVREP" | head -c 120)" \ + || p 0 "环境申报失败: $(printf '%s' "$ENVREP" | head -c 250)" + +echo "=== 2.2 设备证书签发(cert_type=02,绑定已登记公钥)===" +CERTS=$(curl -s -m 25 -X GET "$API/api/ssw/tds/Cert/All" -H "$H" 2>&1) +if printf '%s' "$CERTS" | grep -q "\"f_connector_id\":\"TDC-WUGUIRONG-01\""; then + p 1 "设备证书已存在,跳过签发" +else + CERT=$(curl -s -m 40 -X POST "$API/api/ssw/tds/Cert" -H "$H" \ + -H 'Content-Type: application/json' \ + -d "{\"subjectId\":\"$CID\",\"certType\":\"02\",\"certNo\":\"CERT-TDC-WUGUIRONG-01\"}" 2>&1) + printf '%s' "$CERT" | grep -q '"code":200' \ + && p 1 "设备证书签发: $(printf '%s' "$CERT" | head -c 120)" \ + || p 0 "设备证书签发失败: $(printf '%s' "$CERT" | head -c 250)" +fi + +echo "=== 2.3 运维字段(deploymentStatus=READY + endpoint)===" +OPS=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/Ops" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' \ + -d "{\"connectorId\":\"$CID\",\"deploymentStatus\":\"READY\",\"endpoint\":\"http://tdc-connector.wuguirong.svc.cluster.local:30000\"}" 2>&1) +printf '%s' "$OPS" | grep -q '"code":200' \ + && p 1 "运维字段写入: $(printf '%s' "$OPS" | head -c 120)" \ + || p 0 "运维字段写入失败: $(printf '%s' "$OPS" | head -c 250)" + +echo "=== 3. 心跳 $ROUNDS 次(签名 → PUT /Connector/{id}/Heartbeat)===" +for i in $(seq 1 "$ROUNDS"); do + TS=$(python3 -c 'import time;print(int(time.time()*1000))') + NONCE=$(openssl rand -hex 16) + SIGNING="$CID +$TS +$NONCE" + # 🔴 签名走 python cryptography(本机 OpenSSL 4.0.3 组合有坑,见 build/sign-ecdsa.py 头注) + SIG=$(printf '%s' "$SIGNING" | python3 "$SCRIPT_DIR/sign-ecdsa.py" "$KEYDIR/ec.key") + HB=$(curl -s -m 20 -X PUT "$API/api/ssw/tds/Connector/$CID/Heartbeat" -H "$H" \ + -H 'Content-Type: application/json' \ + -d "{\"connectorId\":\"$CID\",\"timestamp\":$TS,\"nonce\":\"$NONCE\",\"signature\":\"$SIG\"}" 2>&1) + printf '%s' "$HB" | grep -q '"code":200' \ + && p 1 "第 $i 次心跳成功: $(printf '%s' "$HB" | head -c 130)" \ + || { p 0 "第 $i 次心跳失败: $(printf '%s' "$HB" | head -c 200)"; break; } + [ "$i" -lt "$ROUNDS" ] && sleep 6 +done + +echo "=== 4. 最终状态 ===" +DBP=$(kubectl -n wuguirong get configmap ssw-tds-env -o jsonpath='{.data.DB_PWD}' 2>/dev/null) +if [ -n "$DBP" ]; then + kubectl -n wuguirong exec deploy/ssw-tds -c db -- env PGPASSWORD="$DBP" psql -U dacli -d tds -c \ + "select f_connector_code, f_audit_status, f_status, f_env_status, f_last_heartbeat_time from tds_connector where f_id='$CID';" 2>&1 | head -8 +fi + +echo +echo "======== 通过 $ok / 失败 $bad ========" +[ "$bad" -eq 0 ] diff --git a/build/cross-build-armv7.sh b/build/cross-build-armv7.sh new file mode 100755 index 0000000..27b657f --- /dev/null +++ b/build/cross-build-armv7.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# cross-build-armv7.sh +# 一键把 Rust 项目交叉编译成 armv7(glibc 2.26 动态)产物,并可选在容器里实跑。 +# +# 用法: +# bash build/cross-build-armv7.sh [crate-name] +# +# 环境变量(都有默认值): +# ENGINE_DIR 引擎目录(默认 ssw-platform/dist/pglite-engine-armv7-glibc26) +# ZIG_TARGET zig target 三元组(默认 arm-linux-gnueabihf.2.26) +# SYSROOT zlib-only sysroot(默认 build/sysroot-armhf) +# RUN_IMAGE 实跑用的 armv7 容器镜像(默认 arm32v7/debian:buster = glibc 2.28 = 海光) +# +# 🔴 为什么必须用本脚本而不是裸 `cargo build --target armv7-...`: +# 1. rustc 传的 --target=arm-unknown-linux-gnueabihf 会让 zig 报 +# "UnknownOperatingSystem" / "version '.2.26' ... is invalid" +# ⇒ 必须用 zig-cc-armv7-glibc26.sh 包装器过滤掉。 +# 2. zig 不带 zlib ⇒ 必须给 zlib-only sysroot(**不要**用上游完整 sysroot, +# 它的 libc.so.6 是 glibc 2.36 ⇒ 产物又绑 GLIBC_2.34+)。 +# 3. GLIBC 2.25 才有的 explicit_bzero / getrandom ⇒ 必须注入 compat shim, +# 且 shim **不能**放进 libpglite.a(rustc --whole-archive 会重打包归档, +# 库内成员会时有时无;重复注入则 duplicate symbol)。 +# 4. 交叉构建必须 CARGO_PROFILE_RELEASE_STRIP=none。 +set -euo pipefail + +PROJ="${1:-}" +CRATE="${2:-}" + +[ -n "${PROJ}" ] || { echo "用法: $0 [crate-name]" >&2; exit 1; } +[ -f "${PROJ}/Cargo.toml" ] || { echo "FATAL: ${PROJ} 不是 Rust 项目" >&2; exit 1; } + +HERE="$(cd "$(dirname "$0")" && pwd)" +ENGINE_DIR="${ENGINE_DIR:-/Users/xs/Desktop/workspace/ssw-platform/dist/pglite-engine-armv7-glibc26}" +ZIG_TARGET="${ZIG_TARGET:-arm-linux-gnueabihf.2.26}" +SYSROOT="${SYSROOT:-${HERE}/sysroot-armhf}" +RUN_IMAGE="${RUN_IMAGE:-arm32v7/debian:buster}" + +[ -d "${ENGINE_DIR}" ] || { echo "FATAL: 缺引擎目录 ${ENGINE_DIR}" >&2; exit 1; } +[ -d "${SYSROOT}" ] || { echo "FATAL: 缺 sysroot ${SYSROOT}" >&2; exit 1; } +[ -d "${ENGINE_DIR}/compat" ] || { echo "FATAL: 缺 compat shim: ${ENGINE_DIR}/compat" >&2; exit 1; } + +export PGLITE_LIB_DIR="${ENGINE_DIR}" +export ZIG_TARGET +export ZIG_SYSROOT="${SYSROOT}" +export ZIG_COMPAT_DIR="${ENGINE_DIR}/compat" +export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER="${HERE}/zig-cc-armv7-glibc26.sh" +export CARGO_PROFILE_RELEASE_STRIP=none + +echo "=== 交叉编译 armv7 ===" +echo " 引擎 : ${ENGINE_DIR}" +echo " sysroot: ${SYSROOT}" +echo " compat : ${ZIG_COMPAT_DIR}" +echo " target : ${ZIG_TARGET}" +echo + +cd "${PROJ}" +cargo build --release --target armv7-unknown-linux-gnueabihf + +BIN="${PROJ}/target/armv7-unknown-linux-gnueabihf/release/${CRATE:-${PROJ##*/}}" +[ -f "${BIN}" ] || { + echo "FATAL: 产物不存在: ${BIN}" >&2 + ls -la "${PROJ}/target/armv7-unknown-linux-gnueabihf/release/" >&2 + exit 1 +} + +echo +echo "=== 产物 ===" +ls -lh "${BIN}" +file "${BIN}" 2>/dev/null || true + +echo +echo "=== GLIBC 版本需求 ===" +if nm -D "${BIN}" 2>/dev/null | grep -oE 'GLIBC_[0-9.]+' | sort -V -u | tr '\n' ' '; then :; fi +echo + +echo "=== compat shim 状态(应为 T = 本地强符号)===" +nm -D "${BIN}" 2>/dev/null | grep -E 'explicit_bzero|getrandom' || echo " (无 —— 检查 shim 是否注入)" + +echo +echo "=== 在 ${RUN_IMAGE} 实跑 ===" +docker run --rm --platform linux/arm/v7 -v "${BIN}:/app/run:ro" "${RUN_IMAGE}" /app/run 2>&1 | head -25 diff --git a/build/cross-build-tdc-armv7.sh b/build/cross-build-tdc-armv7.sh new file mode 100644 index 0000000..d6ab8bd --- /dev/null +++ b/build/cross-build-tdc-armv7.sh @@ -0,0 +1,192 @@ +#!/usr/bin/env bash +# +# cross-build-tdc-armv7.sh —— 把 tdc-connector 交叉编译成 armv7(Linux 32 位 ARM hard-float) +# +# 🔴 为什么需要这个脚本(2026-11-13): +# tdc-rs 是**消费方**(方案 C:预编译 rlib 闭包),它自己**没有** cargo 依赖, +# 靠 `.cargo/config.toml` 的 `--extern` 直接吃平台的 rlib。 +# ⇒ 要出 armv7 产物,**必须**有一份 armv7 的平台闭包 +# (`dist/sspf-v0.5.0-armv7-unknown-linux-gnueabihf/`)。 +# +# 🔴 三个必须做对的地方(踩过才知道): +# 1. **vendor 必须换成 armv7 闭包**:默认 `vendor/sspf-v0.5.0/` 是 x86_64 的, +# 架构不匹配 ⇒ 链接失败或运行期段错误。 +# 2. **链接器用 zig cc**:rustc 固定传 `--target=arm-unknown-linux-gnueabihf`, +# zig 不认 `unknown` 这个 OS 名 ⇒ 包装器要丢弃 rustc 的 target 参数。 +# 3. **compat shim 必须链接期注入**:显式_bzero / getrandom 是 glibc 2.25+ 的符号, +# ZYNQ(2.26) / 海光(2.28) 勉强能跑,但我们统一降级到 2.18 兼容层。 +# ⚠️ 不能放进 libpglite.a —— rustc 的 bundle 机制会把 native 静态库 +# **原样**嵌进 rlib,对「只被 undefined 引用」的成员处理不确定。 +# +# 用法: +# bash cross-build-tdc-armv7.sh # 用默认路径 +# bash cross-build-tdc-armv7.sh --keep-vendor # 保留原 vendor(默认备份) +# +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PLATFORM_REPO="${PLATFORM_REPO:-/Users/xs/Desktop/workspace/ssw-platform}" +TDC_REPO="${TDC_REPO:-/Users/xs/Desktop/workspace/tdc-rs}" +ENGINE_DIR="${ENGINE_DIR:-${PLATFORM_REPO}/dist/pglite-engine-armv7-glibc26}" +SYSROOT="${SYSROOT:-${HERE}/sysroot-armhf}" +TARGET="armv7-unknown-linux-gnueabihf" +TRIPLE_UPPER="$(echo "${TARGET}" | tr 'a-z-' 'A-Z_')" + +KEEP_VENDOR=0 +for a in "$@"; do + case "$a" in + --keep-vendor) KEEP_VENDOR=1 ;; + -h|--help) sed -n '1,30p' "$0"; exit 0 ;; + *) echo "未知参数: $a" >&2; exit 2 ;; + esac +done + +echo "==> 平台仓库: ${PLATFORM_REPO}" +echo "==> 连接器仓库: ${TDC_REPO}" +echo "==> 引擎目录: ${ENGINE_DIR}" +echo "==> 目标: ${TARGET}" + +# ── 1. 确认 armv7 平台闭包在位 ───────────────────────────────── +ARM_PKG="${PLATFORM_REPO}/dist/sspf-v0.5.0-${TARGET}" +if [[ ! -d "${ARM_PKG}/lib" ]]; then + echo "!! 找不到 armv7 平台闭包: ${ARM_PKG}/lib" >&2 + echo " 先跑平台的交叉出包:" >&2 + echo " cd ${PLATFORM_REPO} && bash scripts/release.sh --target ${TARGET} --no-web" >&2 + exit 1 +fi +echo "==> armv7 平台闭包: ${ARM_PKG}($(find "${ARM_PKG}/lib" -maxdepth 1 -name '*.rlib' | wc -l | tr -d ' ') 个 rlib)" + +# ── 1.5 自检:proc-macro dylib 必须在闭包里 ────────────────────── +# 🔴🔴🔴 **这是交叉包最容易漏的一环**(2026-11-13 实测定位): +# proc-macro crate(serde_derive / tokio_macros / futures_macro / thiserror_impl) +# 是**编译期在宿主上执行**的 ⇒ 交叉编译时 cargo 把它们编成**宿主架构**的 .dylib, +# 产物落在 `/release/deps/`(**无 triple 层**),而不是 +# `//release/deps/`。 +# ⇒ 若出包脚本只拷了 target 层,消费方就**拿不到 derive 宏** ⇒ +# `E0463 can't find crate for serde/axum` + `cannot find attribute 'serde'`。 +# ⇒ 闭包里必须有宿主 proc-macro dylib,否则直接失败(早失败好过链接期玄学报错)。 +# 🔴 注意:不能用 `ls lib/*.dylib lib/*.so | wc -l` —— glob 无匹配时 ls 返回 1, +# 在 `set -euo pipefail` 下会让整个脚本**静默退出**(第一次跑就踩了)。 +# 改用 find -name,退出码恒为 0。 +PM_N="$(find "${ARM_PKG}/lib" -maxdepth 1 \( -name '*.dylib' -o -name '*.so' \) | wc -l | tr -d ' ')" +if [[ "${PM_N}" == "0" ]]; then + echo "!! 闭包里没有宿主 proc-macro dylib ⇒ 消费方必然 E0463" >&2 + echo " 先重跑平台交叉出包(release.sh 已修:收集 host deps 的 .dylib):" >&2 + echo " cd ${PLATFORM_REPO} && bash scripts/release.sh --target ${TARGET} --no-web" >&2 + exit 1 +fi +echo "==> 宿主 proc-macro dylib: ${PM_N} 个(派生宏必需)" + +# ── 2. 切 vendor 到 armv7 闭包 ──────────────────────────────── +VENDOR="${TDC_REPO}/vendor/sspf-v0.5.0" +if [[ "${KEEP_VENDOR}" == "0" ]]; then + if [[ -d "${VENDOR}" ]] && [[ ! -L "${VENDOR}" ]]; then + BAK="${VENDOR}.x86_64-backup" + if [[ ! -d "${BAK}" ]]; then + echo "==> 备份原 vendor: ${VENDOR} → ${BAK}" + mv "${VENDOR}" "${BAK}" + else + echo "==> 原 vendor 已备份过(${BAK}),直接替换" + rm -rf "${VENDOR}" + fi + fi + echo "==> 链接 armv7 闭包: ${VENDOR} → ${ARM_PKG}" + ln -sfn "${ARM_PKG}" "${VENDOR}" +fi + +# ── 3. 重新生成 .cargo/config.toml(路径/hash 随闭包变)──────── +# 🔴 fetch-platform.sh 的解包逻辑按 `vendor/sspf-vX.Y.Z/lib` 找; +# 闭包换架构后 rlib hash 也变 ⇒ 必须重跑它重写 rustflags。 +cd "${TDC_REPO}" +bash scripts/fetch-platform.sh --version 0.5.0 2>&1 | sed 's/^/ /' + +# ── 4. 交叉编译 ─────────────────────────────────────────────── +export CARGO_TARGET_${TRIPLE_UPPER}_LINKER="${PLATFORM_REPO}/scripts/zig-cc-armv7.sh" +export ZIG_SYSROOT="${SYSROOT}" +export ZIG_COMPAT_DIR="${ENGINE_DIR}/compat" +export ZIG_TARGET="arm-linux-gnueabihf.2.26" +export CARGO_PROFILE_RELEASE_STRIP=none +export CARGO_TARGET_${TRIPLE_UPPER}_RUSTFLAGS="" +# 🔴🔴🔴 **必须绕过 sccache**(2026-11-13 定位): +# rustc 把 `-L native=<引擎目录>` 的 `libpglite.a` **bundle 进 libpglite_sys.rlib**, +# 而 rustc 指纹**不含 native 静态库的内容哈希** ⇒ 换引擎后 sccache 仍命中旧缓存, +# 返回内嵌**旧引擎**的 rlib ⇒ 链接期 `undefined symbol: fcntl64`。 +# `cargo clean` 清不掉 sccache ⇒ 只能绕开 wrapper。 +export RUSTC_WRAPPER="${RUSTC_WRAPPER-}" + +echo "==> cargo build --release --target ${TARGET}" +cd "${TDC_REPO}" +cargo build --release --target "${TARGET}" + +BIN="${TDC_REPO}/target/${TARGET}/release/tdc-connector" +[[ -x "${BIN}" ]] || { echo "!! 找不到 ${BIN}" >&2; exit 1; } + +# ── 5. 产物核对 ─────────────────────────────────────────────── +echo "" +echo "==> 产物: ${BIN}" +file "${BIN}" +ls -la "${BIN}" + +echo "" +echo "==> GLIBC 需求(应 ≤ 2.18)" +python3 - "${BIN}" <<'PY' +import re, sys, subprocess +p = sys.argv[1] +d = open(p, 'rb').read() +vers = sorted(set(re.findall(rb'GLIBC_(\d+\.\d+)', d)), + key=lambda x: tuple(int(n) for n in x.split(b'.'))) +print(" ", b' '.join(b'GLIBC_' + v for v in vers).decode()) +# 本地强符号(compat shim)检查 +for sym in (b'explicit_bzero', b'getrandom'): + print(f" {sym.decode():16s}", "本地强符号" if sym in d else "缺") +PY + +echo "" +echo "==> compat shim 注入检查" +for s in explicit_bzero getrandom; do + if python3 - "${BIN}" "${s}" <<'PY' +import struct, sys +p, want = sys.argv[1], sys.argv[2].encode() +d = open(p, 'rb').read() +# 粗查:动态符号表里不应出现该名字的 UND 版本需求 +sys.exit(0 if b'GLIBC_2.25' not in d else 1) +PY + then echo " ✓ 未引入 GLIBC_2.25 依赖"; else echo " ⚠️ 仍引 GLIBC_2.25"; fi +done + +# 🔴 fcntl64 专项核验(2026-11-13 教训:zig nm 是假命令,必须自己解析 ELF) +echo "" +echo "==> fcntl64 专项核验(手写 ELF 解析器,不用 zig nm)" +python3 - "${BIN}" <<'PY' +import struct, sys +p = sys.argv[1] +d = open(p, 'rb').read() +e = '<' if d[5] == 1 else '>' +e_shoff = struct.unpack_from(e+'I', d, 32)[0] +e_shentsize = struct.unpack_from(e+'H', d, 46)[0] +e_shnum = struct.unpack_from(e+'H', d, 48)[0] +e_shstrndx = struct.unpack_from(e+'H', d, 50)[0] +def raw(i): return struct.unpack_from(e+'IIIIIIIIII', d, e_shoff+i*e_shentsize) +sh = raw(e_shstrndx) +def nm(n): + b = d[sh[4]+n:]; return b[:b.find(b'\0')].decode('latin-1') +secs = {nm(raw(i)[0]): raw(i) for i in range(e_shnum)} +st, so = secs.get('.symtab'), secs.get('.strtab') +defined, undef = set(), set() +if st and so: + for i in range(st[5] // 16): + o = st[4]+16*i + sn, sv, ss, si, so2, shn = struct.unpack_from(e+'IIIBBH', d, o) + if not sn: continue + b = d[so[4]+sn:]; s = b[:b.find(b'\0')].decode('latin-1') + (undef.add(s) if shn == 0 else defined.add(s)) +bad = 'fcntl64' in undef +print(f" fcntl64 未定义引用: {'YES ❌ 会链接失败' if bad else 'NO ✅'}") +print(f" fcntl64 本地定义 : {'YES' if 'fcntl64' in defined else 'NO'}") +for s in ('explicit_bzero', 'getrandom', 'pgl_fcntl'): + print(f" {s:16s} 本地强符号: {'YES ✅' if s in defined else 'NO ❌'}") +sys.exit(1 if bad else 0) +PY + +echo "" +echo "✅ tdc-connector armv7 产物就绪: ${BIN}" diff --git a/build/cross-tdc-armv7.sh b/build/cross-tdc-armv7.sh new file mode 100644 index 0000000..9cd17ca --- /dev/null +++ b/build/cross-tdc-armv7.sh @@ -0,0 +1,223 @@ +#!/usr/bin/env bash +# 设备侧连接器「全量交叉编译」流水线 —— 设备里不装编译器、不编译,只接成品。 +# +# 实测前提(2026-11-12,三台真机): +# ZYNQ 192.168.1.233 = armv7l 32 位 / glibc 2.26 / 509MB RAM(可用 411MB) / 6.6GB 磁盘 +# 海光 192.168.1.102 = x86_64 / glibc 2.28 / 32GB / 有 docker +# ⇒ 资源完全够跑「编译后含 pglite 约 30MB、常驻约 20MB」的连接器,不在设备内编译即可。 +# +# 真正的两个硬约束(与内存无关): +# ① pglite-rs 0.2.7 官方引擎只发 x86_64 / aarch64 的 libpglite.a(内含 PostgreSQL 17.5), +# armv7 没有现成包 ⇒ 必须用上游 native/build-libpglite.sh 从源码交叉编译。 +# ② 现有 linux/amd64 的 tdc-connector 要求 GLIBC_2.34,海光 2.28 / ZYNQ 2.26 都装不下 +# ⇒ 统一编译到 armv7-unknown-linux-musleabihf(静态 musl,零设备 libc 依赖)。 +# pglite-rs-sys 支持 PGLITE_LIB_DIR 覆盖预编译库,pglite-rs 把 runtime.tar 内嵌进二进制, +# 所以最终仍是「一个静态二进制 + 一份 webroot」,正好是用户描述的交付形态。 +# +# 四个阶段(全部在开发机 Docker 里跑,设备只收 tar 包): +# prepare 准备 zig 交叉 C 编译器、Rust armv7-musl target、固定 commit 的 PostgreSQL 源码、zlib +# engine 交叉编译 libpglite.a + pglite-runtime.tar(armv7-musl 原生 PostgreSQL) +# platform 交叉编译 ssw-platform,产出 armv7-musl 的 sspf 预编译 rlib 闭包包 +# connector tdc-rs 吃该闭包,产出静态 tdc-connector(含 pglite) +# pack 与静态软卡、webroot、启动脚本一起打成每台设备的物料包 +# +# 依赖:docker、运行中的 sspf-build(/src=ssw-platform)、tdc-build(/src=tdc-rs)容器, +# 镜像 ssw-rust-builder:1.95;下载缓存放 /tmp/cross-dl(宿主机下载后 docker cp)。 +# +# 用法: +# bash build/cross-tdc-armv7.sh prepare +# bash build/cross-tdc-armv7.sh engine # 最慢,约 10~30 分钟 +# bash build/cross-tdc-armv7.sh platform +# bash build/cross-tdc-armv7.sh connector +# bash build/cross-tdc-armv7.sh pack +# bash build/cross-tdc-armv7.sh all +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PLATFORM_C="${PLATFORM_C:-sspf-build}" +TDC_C="${TDC_C:-tdc-build}" +TARGET="armv7-unknown-linux-musleabihf" +ZIG_TRIPLE="arm-linux-musleabihf" +ENGINE_DIR="/opt/pglite-armv7" +SRC_REPO="/opt/pglite-rs-src" +DL="/tmp/cross-dl" +OUT="$ROOT/build/dist-device" +PG_SHA="06c837c6a30335169df786c610ed224bc51d81c0" +STAGE="${1:-all}" + +log() { printf '\n=== %s ===\n' "$*"; } +need() { command -v "$1" >/dev/null 2>&1 || { echo "缺 $1" >&2; exit 1; }; } +need docker +mkdir -p "$OUT" "$DL" + +# ---------------------------------------------------------------- prepare ---- +do_prepare() { + log "prepare: 检查构建容器" + docker ps --format '{{.Names}}' | grep -qx "$PLATFORM_C" || { + echo "容器 $PLATFORM_C 未运行(需 /src=ssw-platform 源码)" >&2; exit 1; } + docker ps --format '{{.Names}}' | grep -qx "$TDC_C" || { + echo "容器 $TDC_C 未运行(需 /src=tdc-rs 源码)" >&2; exit 1; } + + # zig(交叉 C 编译器):宿主机下载后拷进去,容器直连外网很慢。 + # 两个容器都要:platform 编 sspf 要用,connector 链接 tdc-rs 也要用同一个 linker。 + [ -f "$DL/zig.tar.xz" ] || { + echo "请先下载: curl -fsSL -o $DL/zig.tar.xz https://ziglang.org/download/0.13.0/zig-linux-x86_64-0.13.0.tar.xz" >&2; exit 1; } + for c in "$PLATFORM_C" "$TDC_C"; do + if ! docker exec "$c" test -x /opt/zig/zig; then + docker cp "$DL/zig.tar.xz" "$c:/opt/zig.tar.xz" + docker exec "$c" sh -c 'cd /opt && tar -xf zig.tar.xz && mv zig-linux-x86_64-0.13.0 zig && /opt/zig/zig version' + fi + # CC 包装脚本:上游 build-libpglite.sh 用 "$CC" 调编译器,必须是单个可执行文件 + docker exec "$c" sh -c 'mkdir -p /opt/bin; cat > /opt/bin/zigcc <&2; exit 1; } + docker cp "$DL/pg.tar.gz" "$PLATFORM_C:/tmp/pg.tar.gz" + docker exec "$PLATFORM_C" sh -c "mkdir -p $SRC_REPO/postgres-pglite && tar xzf /tmp/pg.tar.gz -C $SRC_REPO/postgres-pglite --strip-components=1 && cd $SRC_REPO/postgres-pglite && git init -q && git add -A && git -c user.email=build@local -c user.name=build commit -qm 'pinned $PG_SHA' && ls configure" + fi + + # armv7-musl 的 zlib(pglite-rs-sys 无条件 -lz,PostgreSQL configure --with-zlib 也要) + # 从 qemu 的 armv7 alpine 容器直接导出静态库与头文件,避免再交叉编一遍 zlib + if ! docker exec "$PLATFORM_C" test -f /opt/zlib-arm/libz.a; then + mkdir -p "$DL/zlib-arm" + docker run --rm --platform linux/arm/v7 -v "$DL/zlib-arm:/out" alpine:3.20 \ + sh -c 'apk add --no-cache zlib-dev zlib-static >/dev/null 2>&1; cp /usr/lib/libz.a /usr/include/zlib.h /usr/include/zconf.h /out/' + fi + for c in "$PLATFORM_C" "$TDC_C"; do + docker exec "$c" mkdir -p /opt/zlib-arm + docker cp "$DL/zlib-arm/." "$c:/opt/zlib-arm/" + done + log "prepare 完成" +} + +# ----------------------------------------------------------------- engine ---- +do_engine() { + log "engine: 交叉编译 PostgreSQL/pglite 引擎 -> $ENGINE_DIR" + # 上游脚本原地改造:configure 加 --host,CC 用 zig wrapper,CPPFLAGS/LDFLAGS 指向交叉 zlib + docker exec "$PLATFORM_C" sh -c "set -e; cd '$SRC_REPO' + sed -e 's|--prefix=\"\$PREFIX\" \\\\|--prefix=\"\$PREFIX\" \\\\\n --host=$ZIG_TRIPLE \\\\|' \\ + native/build-libpglite.sh > /opt/build-libpglite-cross.sh + chmod +x /opt/build-libpglite-cross.sh + grep -n -- '--host' /opt/build-libpglite-cross.sh" + + docker exec "$PLATFORM_C" sh -c "set -e + export CC=/opt/bin/zigcc + export CPPFLAGS='-I/opt/zlib-arm' + export LDFLAGS='-L/opt/zlib-arm' + export CFLAGS='-O2 -fPIC' + # configure 交叉编译时无法运行测试程序,给出 PostgreSQL 常见的缓存答案 + export ac_cv_func_memcmp_working=yes + export ac_cv_func_setpgrp_void=yes + cd '$SRC_REPO' + bash /opt/build-libpglite-cross.sh" 2>&1 | tee "$OUT/engine-build.log" + + docker exec "$PLATFORM_C" sh -c "set -e; mkdir -p '$ENGINE_DIR'; + cp '$SRC_REPO/native/out/libpglite.a' '$SRC_REPO/native/out/pglite-runtime.tar' '$SRC_REPO/native/out/pglite_native.h' '$ENGINE_DIR/'; + file '$SRC_REPO/native/out/build/bin/postgres' | head -1; + ls -lh '$ENGINE_DIR'" + mkdir -p "$OUT/engine" + docker cp "$PLATFORM_C:$ENGINE_DIR/." "$OUT/engine/" + log "engine 完成: $OUT/engine" +} + +# --------------------------------------------------------------- platform ---- +do_platform() { + log "platform: 交叉编译 sspf 闭包 ($TARGET)" + docker exec "$PLATFORM_C" sh -c "set -e + export PGLITE_LIB_DIR='$ENGINE_DIR' + export CC_armv7_unknown_linux_musleabihf=/opt/bin/zigcc + export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER=/opt/bin/zigcc + export CARGO_TARGET_DIR=/src/target/rlibbuild-armv7 + cd /src + cargo build --release -p sspf --target '$TARGET'" 2>&1 | tee "$OUT/platform-build.log" + + # 包结构只需 lib/(完整依赖闭包 + .d)+ 工具链版本,fetch-platform.sh 就能挑 rlib + docker exec "$PLATFORM_C" sh -c "set -e; rm -rf /tmp/sspf-armv7 && mkdir -p /tmp/sspf-armv7/sspf-v0.5.0 + cp -a /src/target/rlibbuild-armv7/'$TARGET'/release/deps /tmp/sspf-armv7/sspf-v0.5.0/lib + cp /src/rust-toolchain.toml /tmp/sspf-armv7/sspf-v0.5.0/ + cd /tmp/sspf-armv7 && tar czf /tmp/sspf-v0.5.0-'$TARGET'.tar.gz sspf-v0.5.0 + ls -lh /tmp/sspf-v0.5.0-'$TARGET'.tar.gz" + docker cp "$PLATFORM_C:/tmp/sspf-v0.5.0-$TARGET.tar.gz" "$OUT/" + log "platform 完成: $OUT/sspf-v0.5.0-$TARGET.tar.gz" +} + +# -------------------------------------------------------------- connector ---- +do_connector() { + log "connector: 交叉编译 tdc-rs ($TARGET)" + docker exec "$TDC_C" mkdir -p /pkg "$ENGINE_DIR" + docker cp "$OUT/sspf-v0.5.0-$TARGET.tar.gz" "$TDC_C:/pkg/" + docker cp "$OUT/engine/." "$TDC_C:$ENGINE_DIR/" + # 🔴 fetch-platform.sh 只在 vendor/sspf-v0.5.0/lib 不存在时才解包;不清掉旧的 + # x86_64 闭包就会静默沿用旧 rlib,交叉编译必然链接失败(架构不匹配)。 + docker exec "$TDC_C" sh -c "set -e; cd /src + rm -rf vendor/sspf-v0.5.0 .cargo/config.toml + bash scripts/fetch-platform.sh --pkg '/pkg/sspf-v0.5.0-$TARGET.tar.gz' 2>&1 | tail -25" 2>&1 | tee "$OUT/connector-fetch.log" + docker exec "$TDC_C" sh -c "set -e + export PGLITE_LIB_DIR='$ENGINE_DIR' + export CC_armv7_unknown_linux_musleabihf=/opt/bin/zigcc + export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER=/opt/bin/zigcc + cd /src && cargo build --release --target '$TARGET'" 2>&1 | tee "$OUT/connector-build.log" + docker cp "$TDC_C:/src/target/$TARGET/release/tdc-connector" "$OUT/tdc-connector-armv7" + file "$OUT/tdc-connector-armv7" + log "connector 完成: $OUT/tdc-connector-armv7" +} + +# -------------------------------------------------------------------- pack ---- +do_pack() { + log "pack: 组装设备物料(连接器 + 静态软卡 + webroot + 启动脚本)" + local D="$OUT/bundle" + rm -rf "$D"; mkdir -p "$D/bin" "$D/webroot" + cp "$OUT/tdc-connector-armv7" "$D/bin/tdc-connector" + cp "$ROOT/card/dist/softcard-linux-armv7" "$D/bin/softcard" + cp -a "$ROOT/build/ctx-tdc/webroot/." "$D/webroot/" + chmod +x "$D/bin/tdc-connector" "$D/bin/softcard" + cat > "$D/start.sh" <<'START' +#!/bin/sh +# 设备侧启动:1 设备 1 卡 1 连接器。软卡只监听回环,签名/心跳都在卡内。 +set -u +BASE="$(cd "$(dirname "$0")" && pwd)" +: "${DEVICE_ID:?DEVICE_ID 必填}" +: "${CARD_TOKEN:?CARD_TOKEN 必填}" +: "${CONNECTOR_ID:?CONNECTOR_ID 必填}" +TDS_API="${TDS_API:-http://192.168.1.26:30201}" +PORT="${PORT:-30000}" +mkdir -p "$BASE/card" "$BASE/data" +chmod 700 "$BASE/card" + +"$BASE/bin/softcard" --key-dir "$BASE/card" --device-id "$DEVICE_ID" \ + --platform "${PLATFORM:-none}" --token "$CARD_TOKEN" \ + --listen 127.0.0.1:9701 \ + --tds-url "$TDS_API" --connector-id "$CONNECTOR_ID" \ + --heartbeat-interval 5s > "$BASE/card.log" 2>&1 & +echo $! > "$BASE/card.pid" + +export TDC_DATA_DIR="$BASE/data" PORT="$PORT" LANG=C.UTF-8 +exec "$BASE/bin/tdc-connector" +START + chmod +x "$D/start.sh" + tar czf "$OUT/device-bundle-armv7.tar.gz" -C "$OUT" bundle + ls -lh "$OUT/device-bundle-armv7.tar.gz" + log "pack 完成。设备侧只需:tar xzf + DEVICE_ID/CARD_TOKEN/CONNECTOR_ID ./start.sh" +} + +case "$STAGE" in + prepare) do_prepare ;; + engine) do_prepare; do_engine ;; + platform) do_platform ;; + connector) do_connector ;; + pack) do_pack ;; + all) do_prepare; do_engine; do_platform; do_connector; do_pack ;; + *) echo "用法: $0 [prepare|engine|platform|connector|pack|all]" >&2; exit 2 ;; +esac diff --git a/build/cube-mcp.sh b/build/cube-mcp.sh new file mode 100644 index 0000000..ecf1177 --- /dev/null +++ b/build/cube-mcp.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# cube-mcp.sh —— 直连 CubeSandbox MCP 端点的极简客户端 +# +# 🔴 为什么不用 MCP 工具直调:`create_sandbox` 的 metadata 在 **MCP schema 里声明是 string, +# 服务端却要 map** ⇒ 经 MCP 工具层调用必然 422(schema 校验挡在前面,改不了)。 +# 直连 JSON-RPC 才能把 map 塞进去。 +# +# 用法: +# bash build/cube-mcp.sh list-sandboxes +# bash build/cube-mcp.sh create '{"template":"toolchain","timeout":14400,"metadata":{"role":"device-sim"}}' +# bash build/cube-mcp.sh call create_sandbox '{"template":"toolchain","metadata":{"role":"x"}}' +# bash build/cube-mcp.sh run "shell command" +# bash build/cube-mcp.sh put-file +# bash build/cube-mcp.sh get-file +set -uo pipefail + +CUBE_URL="${CUBE_URL:-http://192.168.1.30:3000/mcp}" +SESSION_FILE="${SESSION_FILE:-/tmp/cube-mcp-session.json}" +CMD="${1:-}"; shift || true + +rpc() { + # $1 = method, $2 = params(json) + local method="$1" params="${2:-{\}}" + local body + body=$(python3 - "$method" "$params" "$SESSION_FILE" <<'PY' +import json, os, sys +method, params, sess = sys.argv[1], sys.argv[2], sys.argv[3] +rid = 1 +headers = [] +if os.path.exists(sess): + try: + st = json.load(open(sess)) + rid = st.get("id", 0) + 1 + except Exception: + rid = 1 +print(json.dumps({"jsonrpc":"2.0","id":rid,"method":method,"params":json.loads(params)})) +PY +) + local resp + resp=$(xop run --secret CUBE_KEY=llm_key -- sh -c ' + KEY="$CUBE_KEY" + curl -s -m 900 -X POST '"$CUBE_URL"' \ + -H "X-API-Key: $KEY" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + ${MCP_SESSION:+-H "Mcp-Session-Id: $MCP_SESSION"} \ + -d '"'"'"$body"'"'"' + ' < /dev/null 2>/dev/null) + printf '%s' "$resp" | python3 -c " +import sys, json +raw = sys.stdin.read() +for line in raw.splitlines(): + if line.startswith('data: '): + print(line[6:].strip()) +" 2>/dev/null || printf '%s' "$resp" +} + +case "$CMD" in + init) + rpc initialize '{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"cli","version":"1"}}' + ;; + list-sandboxes) + rpc tools/call '{"name":"list_my_sandboxes","arguments":{}}' + ;; + templates) + rpc tools/call '{"name":"list_templates","arguments":{}}' + ;; + create) + rpc tools/call '{"name":"create_sandbox","arguments":'"${1:-{\}}"'}' + ;; + call) + TOOL="$1"; ARGS="${2:-\{\}}" + rpc tools/call "{\"name\":\"$TOOL\",\"arguments\":$ARGS}" + ;; + run) + SID="$1"; SCMD="$2" + python3 - "$SID" "$SCMD" > /tmp/cube-run-args.json <<'PY' +import json, sys +print(json.dumps({"name":"run_command","arguments":{"sandbox_id":sys.argv[1],"command":sys.argv[2]}})) +PY + rpc tools/call "$(cat /tmp/cube-run-args.json)" + ;; + put-file) + SID="$1"; LOCAL="$2"; REMOTE="$3" + python3 - "$SID" "$LOCAL" "$REMOTE" > /tmp/cube-put-args.json <<'PY' +import base64, json, sys +sid, local, remote = sys.argv[1], sys.argv[2], sys.argv[3] +data = base64.b64encode(open(local,'rb').read()).decode() +print(json.dumps({"name":"put_file","arguments":{"sandbox_id":sid,"path":remote,"content_base64":data}})) +PY + rpc tools/call "$(cat /tmp/cube-put-args.json)" + ;; + get-file) + SID="$1"; REMOTE="$2"; LOCAL="$3" + python3 - "$SID" "$REMOTE" > /tmp/cube-get-args.json <<'PY' +import json, sys +print(json.dumps({"name":"get_file","arguments":{"sandbox_id":sys.argv[1],"path":sys.argv[2]}})) +PY + rpc tools/call "$(cat /tmp/cube-get-args.json)" | python3 -c " +import sys, json, base64 +raw = sys.stdin.read() +try: + d = json.loads(raw) + txt = json.dumps(d, ensure_ascii=False) + # 从响应里抠出 content_base64 + def find(o): + if isinstance(o, dict): + for k,v in o.items(): + if k == 'content_base64' and isinstance(v,str): return v + r = find(v) + if r: return r + elif isinstance(o, list): + for v in o: + r = find(v) + if r: return r + return None + b64 = find(d) + if b64: + open('$LOCAL','wb').write(base64.b64decode(b64)) + print('OK saved $LOCAL', len(base64.b64decode(b64)), 'bytes') + else: + print(txt[:800]) +except Exception as e: + print(raw[:800]) +" + ;; + tools) + rpc tools/list '{}' + ;; + *) + echo "用法: $0 {init|tools|templates|list-sandboxes|create|call|run|put-file|get-file} ..." >&2 + exit 1 + ;; +esac diff --git a/build/cube_exec.py b/build/cube_exec.py new file mode 100644 index 0000000..81fa54e --- /dev/null +++ b/build/cube_exec.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""cube_exec.py —— CubeSandbox 沙箱执行客户端(用官方 cubesandbox SDK)。 + +用途:把「离线真机」用沙箱模拟出来 —— 在沙箱里跑软卡 + 连接器, +让它们能对内网 TDS(192.168.1.26:30201)自主心跳。 + +🔴 两个必踩的坑(都踩过): + 1) 本机 HTTP 代理会把**内网明文 HTTP** 改写 ⇒ 必须清 proxy env + NO_PROXY。 + 注意 urllib/requests 的 ProxyHandler 在 import 时就建好,事后 pop env 无效, + 要显式 `build_opener(ProxyHandler({}))` 或用 SDK 的自定义 transport。 + 2) `xop` 会把 stdout 里的密钥**打码**(sk****)⇒ 不能靠 xop 取 API key, + 要从 ~/.workbuddy/mcp.json 的 header 里读明文。 + +用法: + python3 build/cube_exec.py "shell command" + python3 build/cube_exec.py --list + python3 build/cube_exec.py --put + python3 build/cube_exec.py --get +""" +import json +import os +import sys + +for _v in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + os.environ.pop(_v, None) +os.environ["NO_PROXY"] = "192.168.1.30,192.168.1.26,localhost,127.0.0.1" +os.environ["no_proxy"] = os.environ["NO_PROXY"] + +from cubesandbox import Config, Sandbox # noqa: E402 + +GATE = os.environ.get("CUBE_GATE", "http://192.168.1.30:3000") + + +def api_key() -> str: + env = os.environ.get("CUBE_API_KEY") + if env: + return env.strip() + cfg = json.load(open(os.path.expanduser("~/.workbuddy/mcp.json"))) + key = cfg["mcpServers"]["cube-sandbox"]["headers"]["X-API-Key"] + return key.strip() + + +def connect(sandbox_id: str) -> Sandbox: + # 🔴🔴 必须设 CUBE_PROXY_NODE_IP + CUBE_PROXY_PORT_HTTP(内核手册「连接信息」): + # 不设 ⇒ SDK 回落**直连**沙箱的 49983(对外关闭)⇒ Connection refused。 + # 设了 ⇒ 走本机 proxy 通道(node:80),并自动带上 e2b-traffic-access-token。 + os.environ.setdefault("CUBE_PROXY_NODE_IP", os.environ.get("CUBE_NODE_IP", "192.168.1.30")) + os.environ.setdefault("CUBE_PROXY_PORT_HTTP", "80") + cfg = Config(api_url=GATE, api_key=api_key(), timeout=300, request_timeout=120.0) + cfg.proxy_node_ip = os.environ["CUBE_PROXY_NODE_IP"] + cfg.proxy_port = int(os.environ["CUBE_PROXY_PORT_HTTP"]) + return Sandbox.connect(sandbox_id, config=cfg) + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + return + if sys.argv[1] == "--list": + cfg = Config(api_url=GATE, api_key=api_key(), timeout=300, request_timeout=60.0) + print(json.dumps(cfg and _list(cfg), ensure_ascii=False, indent=2)) + return + if sys.argv[1] == "--put": + sid, local, remote = sys.argv[2], sys.argv[3], sys.argv[4] + sb = connect(sid) + with open(local, "rb") as fh: + sb.files.write(remote, fh.read()) + print(f"OK put {local} -> {remote}") + return + if sys.argv[1] == "--get": + sid, remote, local = sys.argv[2], sys.argv[3], sys.argv[4] + sb = connect(sid) + blob = sb.files.read(remote) + if isinstance(blob, str): + blob = blob.encode() + open(local, "wb").write(blob) + print(f"OK get {remote} -> {local} ({len(blob)} bytes)") + return + sid, cmd = sys.argv[1], sys.argv[2] + sb = connect(sid) + r = sb.commands.run(cmd, timeout=1800) + out = (r.stdout or "") + err = (r.stderr or "") + if out: + print(out, end="" if out.endswith("\n") else "\n") + if err: + print("--- stderr ---", file=sys.stderr) + print(err, file=sys.stderr) + print(f"[exit={r.exit_code}]") + + +def _list(cfg): + import urllib.request + req = urllib.request.Request(f"{GATE}/sandboxes", headers={"X-API-Key": cfg.api_key}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=60) as resp: + return json.loads(resp.read().decode()) + + +if __name__ == "__main__": + main() diff --git a/build/cube_mcp.py b/build/cube_mcp.py new file mode 100644 index 0000000..11054a0 --- /dev/null +++ b/build/cube_mcp.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""cube_mcp.py —— CubeSandbox MCP 直连客户端(Python)。 + +🔴 为什么不用 MCP 工具直调:`create_sandbox` 的 metadata 在 **MCP schema 里声明是 string, + 服务端却要 map** ⇒ 经 MCP 工具层调用必然 422(schema 校验挡前面,改不了)。 + 直连 JSON-RPC 才能把 map 塞进去。 + +用法: + python3 build/cube_mcp.py tools + python3 build/cube_mcp.py templates + python3 build/cube_mcp.py list + python3 build/cube_mcp.py create '{"template":"toolchain","timeout":14400,"metadata":{"role":"x"}}' + python3 build/cube_mcp.py call '' + python3 build/cube_mcp.py run "shell cmd" + python3 build/cube_mcp.py put + python3 build/cube_mcp.py get +""" +import base64 +import json +import os +import subprocess +import sys +import urllib.request + +CUBE_URL = os.environ.get("CUBE_URL", "http://192.168.1.30:3000/mcp") +_SESSION = None +_RID = [0] + +# 🔴 本机 HTTP 代理会把**内网明文 HTTP** 请求改写(返回 text/html)⇒ +# MCP 走 urllib 会拿到非 JSON。必须把内网 host 排除在代理之外。 +for _v in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"): + os.environ.pop(_v, None) +os.environ["NO_PROXY"] = "192.168.1.30,192.168.1.26,localhost,127.0.0.1" +os.environ["no_proxy"] = os.environ["NO_PROXY"] + + +def _key() -> str: + """取 cube API key。 + + 🔴 不能用 `xop run --secret CUBE_KEY=llm_key`:xop 会对 stdout 的密钥**打码** + (`sk****【xop禁止将密钥泄漏】`)⇒ 拿到的是掩码,不是可用 key。 + ⇒ 优先从 WorkBuddy 的 MCP 配置读(明文 header,本机可信): + ~/.workbuddy/mcp.json → mcpServers.cube-sandbox.headers.X-API-Key + 读不到再退回环境变量 CUBE_API_KEY。 + """ + env = os.environ.get("CUBE_API_KEY") + if env: + return env.strip() + cfg = os.path.expanduser("~/.workbuddy/mcp.json") + try: + with open(cfg) as fh: + data = json.load(fh) + key = ((data.get("mcpServers") or {}).get("cube-sandbox") or {}).get("headers", {}).get("X-API-Key") + if key: + return key.strip() + except Exception: + pass + raise SystemExit("取不到 cube API key(~/.workbuddy/mcp.json 或 env CUBE_API_KEY)") + + +# 🔴 urllib 的 ProxyHandler 在 import 时就按 env 建好了,事后 pop 环境变量**没用**。 +# 必须显式构造一个「无代理」的 opener。 +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def rpc(method: str, params: dict): + global _SESSION, _RID + _RID[0] += 1 + payload = json.dumps({"jsonrpc": "2.0", "id": _RID[0], "method": method, "params": params}).encode() + headers = { + "X-API-Key": _key(), + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + } + if _SESSION: + headers["Mcp-Session-Id"] = _SESSION + req = urllib.request.Request(CUBE_URL, data=payload, headers=headers, method="POST") + with _OPENER.open(req, timeout=1800) as resp: + if not _SESSION: + _SESSION = resp.headers.get("Mcp-Session-Id") + raw = resp.read().decode("utf-8", "replace") + for line in raw.splitlines(): + if line.startswith("data: "): + return json.loads(line[6:]) + return json.loads(raw) if raw.strip() else {} + + +def call(tool: str, args: dict): + rpc("initialize", {"protocolVersion": "2024-11-05", "capabilities": {}, + "clientInfo": {"name": "cli", "version": "1"}}) + return rpc("tools/call", {"name": tool, "arguments": args}) + + +def text_of(resp: dict) -> str: + """把 MCP 响应里的 content[] 拼成文本。""" + result = resp.get("result") or {} + if result.get("isError"): + return "ERROR: " + "\n".join(c.get("text", "") for c in result.get("content", [])) + parts = [] + for c in result.get("content", []): + if c.get("type") == "text": + parts.append(c.get("text", "")) + if parts: + return "\n".join(parts) + return json.dumps(result, ensure_ascii=False) + + +def find_b64(obj): + if isinstance(obj, dict): + for k, v in obj.items(): + if k == "content_base64" and isinstance(v, str): + return v + r = find_b64(v) + if r: + return r + elif isinstance(obj, list): + for v in obj: + r = find_b64(v) + if r: + return r + return None + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + return + cmd = sys.argv[1] + if cmd == "tools": + r = rpc("initialize", {"protocolVersion": "2024-11-05", "capabilities": {}, + "clientInfo": {"name": "cli", "version": "1"}}) + r = rpc("tools/list", {}) + for t in (r.get("result") or {}).get("tools", []): + print(" -", t["name"], "|", (t.get("description") or "").replace("\n", " ")[:80]) + return + if cmd == "templates": + print(text_of(call("list_templates", {}))) + return + if cmd == "list": + print(text_of(call("list_my_sandboxes", {}))) + return + if cmd == "create": + args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {} + print(text_of(call("create_sandbox", args))) + return + if cmd == "call": + print(text_of(call(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}))) + return + if cmd == "run": + resp = call("run_command", {"sandbox_id": sys.argv[2], "command": sys.argv[3]}) + print(text_of(resp)) + return + if cmd == "put": + data = base64.b64encode(open(sys.argv[3], "rb").read()).decode() + resp = call("put_file", {"sandbox_id": sys.argv[2], "path": sys.argv[4], + "content_base64": data}) + print(text_of(resp)) + return + if cmd == "get": + resp = call("get_file", {"sandbox_id": sys.argv[2], "path": sys.argv[3]}) + b64 = find_b64(resp) + if b64: + blob = base64.b64decode(b64) + open(sys.argv[4], "wb").write(blob) + print(f"OK saved {sys.argv[4]} {len(blob)} bytes") + else: + print(json.dumps(resp, ensure_ascii=False)[:800]) + return + print(__doc__) + + +if __name__ == "__main__": + main() diff --git a/build/deploy-card-amd.sh b/build/deploy-card-amd.sh new file mode 100644 index 0000000..a2cdddf --- /dev/null +++ b/build/deploy-card-amd.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# deploy-card-amd.sh —— 把软卡部署到 AMD 真机(192.168.1.7)并自主心跳上线 +# +# 前提:TDS 侧该设备的连接器已注册 + 已签发设备证书 + 四闸门全通 +# connectorId=890673836930892229 connectorCode=tee-amd-007b +# +# 🔴 做法:远端命令写成**脚本文件**再 scp 过去执行 —— 避免 ssh 多层引号嵌套。 +# 🔴 顺序:**先杀旧进程再推二进制** —— 旧进程占着可执行文件时 scp 会 ETXTBSY 失败。 +set -uo pipefail +cd "$(dirname "$0")/.." + +HOST="${HOST:-192.168.1.7}" +API="${TDS_API:-http://192.168.1.26:30201}" +DEVICE_ID="${DEVICE_ID:-tee-amd-007b}" +CONNECTOR_ID="${CONNECTOR_ID:-890673836930892229}" +CARD_BIN="${CARD_BIN:-card/dist/softcard-linux-amd64}" +REMOTE_DIR="/opt/ssw" +CARD_TOKEN="${CARD_TOKEN:-softcard-local-token}" + +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +echo "=== 1. 生成远端脚本 ===" +cat > "$STAGE/run.sh" </dev/null || true +sleep 2 + +echo "--- 卡内密钥自检 ---" +chmod +x $REMOTE_DIR/bin/softcard +$REMOTE_DIR/bin/softcard --key-dir $REMOTE_DIR/card --device-id $DEVICE_ID \\ + --platform none --token $CARD_TOKEN --self-test 2>&1 | tail -3 + +echo "--- 导出公钥 ---" +PUB=\$($REMOTE_DIR/bin/softcard --key-dir $REMOTE_DIR/card --device-id $DEVICE_ID \\ + --platform none --token $CARD_TOKEN --export-pub 2>/dev/null | tail -1) +echo "PUB=\$PUB" +echo "PUB_LEN=\${#PUB}" + +echo "--- 启动(自主心跳,5s) ---" +$REMOTE_DIR/bin/softcard --key-dir $REMOTE_DIR/card --device-id $DEVICE_ID \\ + --platform none --token $CARD_TOKEN --listen 127.0.0.1:9701 \\ + --tds-url $API --connector-id $CONNECTOR_ID --heartbeat-interval 5s \\ + > $REMOTE_DIR/logs/softcard.log 2>&1 & +sleep 8 + +echo "--- 进程 ---" +ps -eo pid,etime,rss,args | grep "[s]oftcard" | head -3 || echo "(无进程)" + +echo "--- 日志 ---" +tail -25 $REMOTE_DIR/logs/softcard.log + +echo "--- bridge 状态 ---" +curl -s -m 8 -H "Authorization: Bearer $CARD_TOKEN" http://127.0.0.1:9701/v1/bridge || echo "(bridge 无响应)" +echo +EOF +chmod +x "$STAGE/run.sh" + +echo "=== 2. 停旧进程 → 推二进制 + 脚本 → $HOST ===" +xop run --secret SSHD_PASS=tee_amd_7_pass --secret SSHD_USER=tee_amd_7_user -- sh -c " +set -e +sshpass -p \"\$SSHD_PASS\" scp -o StrictHostKeyChecking=no $STAGE/run.sh \"\$SSHD_USER@$HOST:/tmp/ssw-run.sh\" +sshpass -p \"\$SSHD_PASS\" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \"\$SSHD_USER@$HOST\" \\ + 'pkill -f \"softcard --key-dir\" 2>/dev/null || true; sleep 2; mkdir -p $REMOTE_DIR/bin $REMOTE_DIR/card $REMOTE_DIR/logs' +sshpass -p \"\$SSHD_PASS\" scp -o StrictHostKeyChecking=no $CARD_BIN \"\$SSHD_USER@$HOST:$REMOTE_DIR/bin/softcard\" +sshpass -p \"\$SSHD_PASS\" ssh -o StrictHostKeyChecking=no \"\$SSHD_USER@$HOST\" 'chmod +x /tmp/ssw-run.sh && ls -la $REMOTE_DIR/bin/softcard' +" < /dev/null 2>&1 | grep -vE "^ WARN|NetworkGuard|FileGuard" + +echo +echo "=== 3. 远端执行 ===" +xop run --secret SSHD_PASS=tee_amd_7_pass --secret SSHD_USER=tee_amd_7_user -- sh -c " +sshpass -p \"\$SSHD_PASS\" ssh -o StrictHostKeyChecking=no \"\$SSHD_USER@$HOST\" 'sh /tmp/ssw-run.sh' +" < /dev/null 2>&1 | grep -vE "^ WARN|NetworkGuard|FileGuard" diff --git a/build/elf-dynsym.py b/build/elf-dynsym.py new file mode 100644 index 0000000..1956fdf --- /dev/null +++ b/build/elf-dynsym.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +""" +elf-dynsym.py —— 精确列出 ELF 的**动态符号表**(.dynsym)及其版本节点。 + +用途(2026-11-13 armv7 exit 100 定位): + 判断 armv7 各 glibc(stretch 2.24 / buster 2.28 / bookworm 2.36) + 到底导出哪些 fcntl/stat 系列符号,以及绑在哪个 GLIBC_x.y 版本节点上。 + ⇒ 决定「shim 方案」该把 fcntl64/stat64/lstat64 桥接到哪个老符号。 + +为什么不用 objdump/nm: + · macOS `nm` 只认 Mach-O,对 ELF 静默输出空; + · 本机无 llvm-nm;`zig nm` 在 zig 0.14.1 不是有效子命令。 + +用法: + python3 elf-dynsym.py [子串过滤...] +""" +import struct +import sys + + +def parse(path): + d = open(path, 'rb').read() + if d[:4] != b'\x7fELF': + raise SystemExit(f'{path}: 不是 ELF') + if d[4] != 1: + raise SystemExit(f'{path}: 不是 ELF32') + e = '<' if d[5] == 1 else '>' + shoff = struct.unpack_from(e + 'I', d, 0x20)[0] + shent = struct.unpack_from(e + 'H', d, 0x2E)[0] + shnum = struct.unpack_from(e + 'H', d, 0x30)[0] + secs = [] + for i in range(shnum): + o = shoff + i * shent + if o + 40 > len(d): + break + secs.append(dict( + t=struct.unpack_from(e + 'I', d, o + 4)[0], + off=struct.unpack_from(e + 'I', d, o + 16)[0], + sz=struct.unpack_from(e + 'I', d, o + 20)[0], + link=struct.unpack_from(e + 'I', d, o + 24)[0], + ent=struct.unpack_from(e + 'I', d, o + 36)[0])) + dynsyms = [] + for s in secs: + # 🔴 ELF32 的 SHT_DYNSYM = **11**(不是 6!6 是 SHT_DYNAMIC) + # 写成 6 会扫不到任何动态符号 ⇒ 输出全空。 + if s['t'] != 11: + continue + strt = secs[s['link']] + n = s['sz'] // (s['ent'] or 16) + for k in range(n): + so = s['off'] + k * (s['ent'] or 16) + if so + 16 > len(d): + break + st_name, st_value, st_size, st_info, st_other, st_shndx = \ + struct.unpack_from(e + 'IIIBBH', d, so) + end = d.find(b'\x00', strt['off'] + st_name, strt['off'] + strt['sz']) + nm = '' if end < 0 else d[strt['off'] + st_name:end].decode('latin-1') + dynsyms.append((nm, st_shndx, st_value)) + # 版本信息(.gnu.version / .gnu.version_d)—— 简化:只取 verdef 名 + vers = {} + for s in secs: + if s['t'] != 0x6FFFFFFD: # SHT_GNU_verdef + continue + # 解析 verdef 表:每项含 vda_name(指向 strtab 的偏移) + base = s['off'] + # 找 strtab:verdef 的 aux 指向 dynstr,这里用 .dynstr(sec 1 之类) + break + # 简化做法:直接从动态字符串里找 "@GLIBC_" 形式 + for s in secs: + if s['t'] != 11: # SHT_STRTAB,扫 "name@GLIBC_x.y" + pass + return dynsyms + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + sys.exit(2) + path = sys.argv[1] + filt = sys.argv[2:] + syms = parse(path) + seen = set() + for nm, shndx, val in syms: + if not nm or nm in seen: + continue + seen.add(nm) + if filt and not any(f in nm for f in filt): + continue + kind = 'UND' if shndx == 0 else f'shndx={shndx}' + print(f' {kind:12s} {nm}') + + +if __name__ == '__main__': + main() diff --git a/build/elf-undef-scan.py b/build/elf-undef-scan.py new file mode 100644 index 0000000..fe4ad12 --- /dev/null +++ b/build/elf-undef-scan.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +""" +elf-undef-scan.py —— 扫描 ar 归档(.a / rlib 内嵌)每个成员的**未定义符号**。 + +用途(2026-11-13 armv7 exit 100 定位): + 上游 ssw-platform 11-12 的 armv7 成功版 libpglite.a 用 + `_FILE_OFFSET_BITS=64` + 838 个 .o 全量编译;我上轮把 pg_config.h 改成 + `/* #undef _FILE_OFFSET_BITS */` 并**只重编 4 个 .o** ⇒ 32 位 ARM 上 + off_t / struct stat ABI 在这 4 个对象与其余 834 个之间不一致。 + 本脚本用来精确回答:「到底哪些成员引用 fcntl64 / stat64?」 + ⇒ 决定是「只重编 pglitec.o」(ABI 不变,最省事)还是必须全量重编。 + +为什么不用 nm/zig nm: + · 本机无 llvm-nm; + · `zig nm` 在 zig 0.14.1 **不是有效子命令**(只打 usage); + · macOS `nm` 只认 Mach-O,对 ELF 静默输出空。 + +用法: + python3 elf-undef-scan.py [符号名...] + python3 elf-undef-scan.py --summary # 只打印汇总(每成员引用数量) +""" +import os +import struct +import sys + + +# ── ar 归档 ──────────────────────────────────────────────────────── +def extract_inner_ar(path): + """rlib 是 ELF 包裹的 ar 归档(真实 '!' 在偏移 52); + .a 本身就是 ar。返回 ar 数据字节串。""" + d = open(path, 'rb').read() + i = d.find(b'!\n') + if i < 0: + return None + return d[i:] + + +def ar_members(data): + """解析 ar,返回 (长名表 bytes, [(name, body_off, size)])""" + if not data.startswith(b'!\n'): + return None, [] + p = 8 + names = b'' + members = [] + while p + 60 <= len(data): + hdr = data[p:p + 60] + if len(hdr) < 60: + break + name = hdr[0:16].decode('latin-1').rstrip() + try: + size = int(hdr[48:58].decode().strip()) + except Exception: + break + body = p + 60 + if name == '//': + names = data[body:body + size] + elif name == '/': + pass # 符号表 + elif name in ('/', '/SYM64/'): + pass + else: + members.append((name, body, size)) + p = body + size + (size % 2) + return names, members + + +def longname(names, n): + """ar 长名表解析:成员名 '/123' ⇒ 偏移 123 处的名字。""" + n = n.rstrip() + if n.startswith('/') and n[1:].isdigit() and names: + off = int(n[1:]) + end = names.find(b'/\n', off) + if end < 0: + end = names.find(b'\n', off) + if end < 0: + end = len(names) + return names[off:end].decode('latin-1') + return n + + +# ── ELF32 解析 ──────────────────────────────────────────────────── +def elf_undef(data): + """返回 (未定义符号名集合, 定义符号名集合);非 ELF 返回 (None, None)。""" + if len(data) < 52 or data[:4] != b'\x7fELF': + return None, None + e_class, ei_data = data[4], data[5] + if e_class != 1: # 只处理 ELF32 + return None, None + e = '<' if ei_data == 1 else '>' + e_shoff = struct.unpack_from(e + 'I', data, 0x20)[0] + e_shentsize = struct.unpack_from(e + 'H', data, 0x2E)[0] + e_shnum = struct.unpack_from(e + 'H', data, 0x30)[0] + e_shstrndx = struct.unpack_from(e + 'H', data, 0x32)[0] + if not e_shoff or not e_shnum: + return None, None + + secs = [] + for i in range(e_shnum): + off = e_shoff + i * e_shentsize + if off + 40 > len(data): + break + (sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, + sh_link, sh_info, sh_align, sh_entsize) = struct.unpack_from( + e + 'IIIIIIIIII', data, off) + secs.append(dict(name_off=sh_name, type=sh_type, offset=sh_offset, + size=sh_size, link=sh_link, entsize=sh_entsize)) + + undef, defined = set(), set() + for s in secs: + if s['type'] != 2: # SHT_SYMTAB + continue + strtab = secs[s['link']] + str_off, str_size = strtab['offset'], strtab['size'] + n = s['size'] // (s['entsize'] or 16) + for k in range(n): + so = s['offset'] + k * (s['entsize'] or 16) + if so + 16 > len(data): + break + st_name, st_value, st_size, st_info, st_other, st_shndx = \ + struct.unpack_from(e + 'IIIBBH', data, so) + if st_name == 0: + continue + end = data.find(b'\x00', str_off + st_name, str_off + str_size) + if end < 0: + continue + nm = data[str_off + st_name:end].decode('latin-1') + if not nm: + continue + if st_shndx == 0: # SHN_UNDEF + undef.add(nm) + else: + defined.add(nm) + return undef, defined + + +def main(): + argv = sys.argv[1:] + summary = False + if argv and argv[0] == '--summary': + summary = True + argv = argv[1:] + if not argv: + print(__doc__) + sys.exit(2) + path = argv[0] + want = set(argv[1:]) + + data = extract_inner_ar(path) + if data is None: + print(f"❌ {path}: 不是 ar 归档(找不到 !)") + sys.exit(1) + names, members = ar_members(data) + print(f"==> {os.path.basename(path)}: {len(members)} 个成员") + + hits = {} + per_member = [] + for name, off, size in members: + base = longname(names, name) + mem = data[off:off + size] + u, d = elf_undef(mem) + if u is None: + continue + per_member.append((base, len(u))) + for s in u: + hits.setdefault(s, []).append(base) + + if want: + for w in sorted(want): + refs = hits.get(w, []) + print(f"\n 🔎 {w}: {len(refs)} 个成员引用") + for r in refs[:40]: + print(f" · {r}") + else: + print("\n --- 成员未定义符号数量 top 15 ---") + for b, n in sorted(per_member, key=lambda x: -x[1])[:15]: + print(f" {n:5d} {b}") + + if not summary: + # 关键 ABI 符号总览 + print("\n --- 关键符号引用成员 ---") + for key in ('fcntl64', 'fcntl', 'stat64', 'stat', 'statx', + 'fstatat64', 'fstatat', 'lstat64', 'lstat', + 'pgl_fcntl', 'pgl_getsockname', 'getsockname', + 'explicit_bzero', 'getrandom'): + refs = hits.get(key, []) + mark = '🔴' if refs else ' ' + print(f" {mark} {key:16s} -> {len(refs):3d} 成员" + + (f" e.g. {refs[:3]}" if refs else "")) + + +if __name__ == '__main__': + main() diff --git a/build/gen-tdc-manifest.sh b/build/gen-tdc-manifest.sh new file mode 100644 index 0000000..5593a26 --- /dev/null +++ b/build/gen-tdc-manifest.sh @@ -0,0 +1,165 @@ +#!/usr/bin/env bash +# 生成 TDC 连接器(tdc-rs)的 k8s 清单。 +# +# 租户硬约束(k8s-tenant-wuguirong): +# - 无 Ingress ⇒ 只能 NodePort +# - tenant-storage-guard 要求**容器级** securityContext.runAsUser=10106 +# - 禁止 hostPath/nfs 直挂 ⇒ 必须 PVC +# - SA 无 create secret ⇒ 密钥只进 ConfigMap 明文 +set -euo pipefail +cd "$(dirname "$0")" +umask 077 # tdc-k8s.yaml 内含明文 ConfigMap 密钥,生成物必须是 600 + +NS=wuguirong +REG=crpi-yscq976uwza88qap.cn-shenzhen.personal.cr.aliyuncs.com/ssw188/nginx +TAG_TDC=tdc-v0.1.0 +OUT=tdc-k8s.yaml +ENVF=.env.tdc + +# ---- 1. 密钥:存在则复用,不存在则生成 ---- +if [ ! -f "$ENVF" ]; then + umask 077 + { + echo "TDC_INTERNAL_TOKEN=$(openssl rand -hex 24)" + echo "TDC_IDENTITY_SECRET=$(openssl rand -hex 32)" + echo "TDC_ADMIN_PASSWORD=$(openssl rand -base64 18 | tr -d '/+=' | head -c 20)" + } > "$ENVF" + chmod 600 "$ENVF" + echo "→ 已生成 $ENVF" +fi +# shellcheck disable=SC1090 +. "./$ENVF" + +# TDS 侧内部令牌必须逐字一致(出向鉴权) +TDS_INTERNAL_TOKEN=$(kubectl -n "$NS" get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}') +[ -n "$TDS_INTERNAL_TOKEN" ] || { echo "读不到 TDS 内部令牌" >&2; exit 1; } + +cat > "$OUT" < build/tds-k8s.yaml +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +set -a; . "$HERE/.env.tds"; set +a + +NS=wuguirong +REG=crpi-yscq976uwza88qap.cn-shenzhen.personal.cr.aliyuncs.com/ssw188/nginx +TAG_DB=tds-dbinit-20261112b +TAG_WEB=tds-web-20261112b +TAG_ADMIN=tds-admin-20261112 +TAG_MPC_BE=mpc-flow-backend-v0.1.0 +TAG_MPC_WEB=mpc-flow-web-v0.1.0 + +cat < /dev/tcp/127.0.0.1/5432) 2>/dev/null; do sleep 3; done + echo "[wait] redis:6379 ..." + until (echo > /dev/tcp/127.0.0.1/6379) 2>/dev/null; do sleep 3; done + echo "[wait] 就绪,启动 TDS" + exec java -Duser.timezone=Asia/Shanghai -Dfile.encoding=UTF-8 -Djava.awt.headless=true \ + -XX:MaxRAMPercentage=70 -XX:+ExitOnOutOfMemoryError -jar /app/app.jar \ + --spring.profiles.active=tds + env: + - { name: TZ, value: "Asia/Shanghai" } + envFrom: + - configMapRef: { name: ssw-tds-env } + - configMapRef: { name: ssw-tds-deploy-env } + ports: [{ containerPort: 30000, name: http }] + resources: + requests: { cpu: 500m, memory: 2Gi } + limits: { cpu: 1500m, memory: 3Gi } + securityContext: { runAsUser: 10106 } + readinessProbe: + httpGet: { path: /api/health, port: 30000 } + initialDelaySeconds: 30 + periodSeconds: 10 + failureThreshold: 30 + volumeMounts: + - { name: appdata, mountPath: /var/lib/ssw-tds } + - { name: jnpf, mountPath: /workspace/jnpf-resources } + - { name: applog, mountPath: /app/log } + # ── 4. 平台前端(nginx,反代同 Pod 后端)── + - name: frontend + image: ${REG}:${TAG_WEB} + imagePullPolicy: IfNotPresent + ports: [{ containerPort: 8080, name: web }] + resources: + requests: { cpu: 50m, memory: 64Mi } + limits: { cpu: 300m, memory: 256Mi } + securityContext: { runAsUser: 10106 } + readinessProbe: + httpGet: { path: /, port: 8080 } + initialDelaySeconds: 5 + periodSeconds: 10 + volumeMounts: + - { name: nginx, mountPath: /etc/nginx/conf.d/default.conf, subPath: default.conf, readOnly: true } + - { name: nginx-cache, mountPath: /var/cache/nginx } + - { name: nginx-run, mountPath: /run } + # ── 5. 隐私计算编排后端(ssw-mpc-flow,与 TDS 同 Pod)── + - name: mpc-backend + image: ${REG}:${TAG_MPC_BE} + imagePullPolicy: IfNotPresent + ports: [{ containerPort: 30001, name: mpcapi }] + envFrom: + - configMapRef: { name: ssw-mpc-env } + resources: + requests: { cpu: 100m, memory: 256Mi } + limits: { cpu: 500m, memory: 1Gi } + securityContext: { runAsUser: 10106 } + readinessProbe: + httpGet: { path: /api/ssw/sswflow/Operator/Info, port: 30001 } + initialDelaySeconds: 20 + periodSeconds: 10 + failureThreshold: 30 + volumeMounts: + - { name: mpcstate, mountPath: /app/.mpc-state } + # ── 6. 隐私计算编排前端(nginx,反代同 Pod 编排后端)── + - name: mpc-frontend + image: ${REG}:${TAG_MPC_WEB} + imagePullPolicy: IfNotPresent + ports: [{ containerPort: 80, name: mpcweb }] + resources: + requests: { cpu: 30m, memory: 32Mi } + limits: { cpu: 100m, memory: 128Mi } + securityContext: { runAsUser: 10106 } + readinessProbe: + httpGet: { path: /, port: 80 } + initialDelaySeconds: 5 + periodSeconds: 10 + volumeMounts: + - { name: mpc-nginx-cache, mountPath: /var/cache/nginx } + - { name: mpc-nginx-run, mountPath: /run } + volumes: + - name: pgdata + persistentVolumeClaim: { claimName: ssw-tds-pg } + - name: redisdata + persistentVolumeClaim: { claimName: ssw-tds-redis } + - name: appdata + persistentVolumeClaim: { claimName: ssw-tds-app } + - name: jnpf + persistentVolumeClaim: { claimName: ssw-tds-jnpf } + - name: mpcstate + persistentVolumeClaim: { claimName: ssw-mpc-state } + - name: mpc-nginx-cache + emptyDir: {} + - name: mpc-nginx-run + emptyDir: {} + - name: nginx + configMap: { name: ssw-tds-nginx } + - name: nginx-cache + emptyDir: {} + - name: nginx-run + emptyDir: {} + - name: applog + emptyDir: {} +--- +# 集群内入口(连接器 / 其它 Pod 用这个) +apiVersion: v1 +kind: Service +metadata: { name: ssw-tds, namespace: ${NS} } +spec: + type: ClusterIP + selector: { app: ssw-tds } + ports: [{ name: http, port: 30000, targetPort: 30000 }] +--- +# 平台前端(浏览器) +apiVersion: v1 +kind: Service +metadata: { name: ssw-tds-web, namespace: ${NS} } +spec: + type: NodePort + selector: { app: ssw-tds } + ports: [{ name: http, port: 80, targetPort: 8080, nodePort: 30200 }] +--- +# 平台后端(集群外调试 / 连接器回访地址) +apiVersion: v1 +kind: Service +metadata: { name: ssw-tds-api, namespace: ${NS} } +spec: + type: NodePort + selector: { app: ssw-tds } + ports: [{ name: http, port: 30000, targetPort: 30000, nodePort: 30201 }] +--- +# 隐私计算编排后端(集群内) +apiVersion: v1 +kind: Service +metadata: { name: ssw-mpc, namespace: ${NS} } +spec: + type: ClusterIP + selector: { app: ssw-tds } + ports: [{ name: http, port: 30001, targetPort: 30001 }] +--- +# 隐私计算编排前端(浏览器) +apiVersion: v1 +kind: Service +metadata: { name: ssw-mpc-web, namespace: ${NS} } +spec: + type: NodePort + selector: { app: ssw-tds } + ports: [{ name: http, port: 80, targetPort: 80, nodePort: 30203 }] +YAML diff --git a/build/getrandom-compat.c b/build/getrandom-compat.c new file mode 100644 index 0000000..a55e5b9 --- /dev/null +++ b/build/getrandom-compat.c @@ -0,0 +1,47 @@ +/* + * getrandom-compat.c —— 为 glibc < 2.25 提供 getrandom(3) + * + * 背景:Rust std 的 `std::collections::hash_map::RandomState` 会调用 libc 的 + * getrandom() 来播种哈希随机数。getrandom(3) 是 **glibc 2.25 才引入**的。 + * 链接器把弱引用(weak undefined)符号也计入 .gnu.version_r 版本需求, + * ⇒ 即使运行时不走这条路径,动态链接器也会在启动时报 + * `version 'GLIBC_2.25' not found`。 + * + * 解决:链接期提供本地强符号,优先于 libc.so.6 的版本化符号。 + * 实现走 syscall(SYS_getrandom, ...),Linux 3.17+ 内核原生支持, + * 与 glibc 2.25 的 getrandom() 行为一致(失败时置 errno=EAGAIN 并返回 -1)。 + */ + +#define _GNU_SOURCE +#include +#include +#include +#include + +#ifndef SYS_getrandom +#define SYS_getrandom 384 +#endif + +ssize_t +getrandom(void *buf, size_t buflen, unsigned int flags) +{ + long ret; + + if (buf == NULL && buflen > 0) + { + errno = EFAULT; + return -1; + } + + if (buflen == 0) + return 0; + + ret = syscall(SYS_getrandom, buf, buflen, flags); + if (ret < 0) + { + errno = EAGAIN; + return -1; + } + + return (ssize_t) ret; +} diff --git a/build/glibc26-compat.c b/build/glibc26-compat.c new file mode 100644 index 0000000..f59db72 --- /dev/null +++ b/build/glibc26-compat.c @@ -0,0 +1,37 @@ +/* + * glibc26-compat.c —— 把 explicit_bzero 的 glibc 需求从 2.25 降到 2.4 + * + * 背景:PostgreSQL 17 在 src/backend/libpq/be-secure-common.c、src/common/hmac.c + * 等处调用 explicit_bzero() 清零敏感缓冲区(口令密钥等)。 + * 该符号是 **glibc 2.25 才引入的**(此前用 memset + 编译器屏障实现)。 + * + * 为什么需要它: + * 目标设备的 glibc 版本: + * · 海光 192.168.1.102 → glibc 2.28 + * · ZYNQ 192.168.1.233 → glibc 2.26 + * 2.26 > 2.25,本来也能跑;但把需求压到 **2.4** 可给更老的嵌入式 glibc + * (如 arm32v7/debian:stretch 的 2.24)留足余量,也让产物更通用。 + * + * 做法:**不改上游源码**,在链接期提供一个本地定义。 + * - 本地静态定义是**强符号**,链接器优先于动态库 libc.so.6 里的同名符号, + * 不会报 duplicate symbol(动态库符号只在静态找不到时才被解析)。 + * - 语义等价:explicit_bzero(buf, n) ≡ memset(buf, 0, n) 且不被优化掉。 + */ + +#include + +void +explicit_bzero(void *buf, size_t len) +{ + if (buf == NULL || len == 0) + return; + + /* + * memset 之后加一道编译器屏障,防止优化器把这个「死存储」删掉 + * —— 这正是 explicit_bzero 相对普通 memset 的核心差异。 + */ + memset(buf, 0, len); +#if defined(__GNUC__) || defined(__clang__) + __asm__ __volatile__("" : : "r"(buf) : "memory"); +#endif +} diff --git a/build/heartbeat-keepalive.py b/build/heartbeat-keepalive.py new file mode 100644 index 0000000..97104d0 --- /dev/null +++ b/build/heartbeat-keepalive.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""TDS 连接器心跳保活器(真协议,非改库绕过)。 + +为什么必须持续心跳:ConnectorServiceImpl.scanHeartbeatTimeouts 的超时为 + heartbeatInterval(默认 5s) × graceMultiplier(默认 3) = 15s +=> 停跳 15s 就把 f_status 打回 OFFLINE;而 SubjectServiceImpl.hasOnlineNode +要求 isOperational() 且 status == "ONLINE" 才派生主体 CONNECTED, +数据产品提交/上架的 checkPublish 依赖它。所以验证期间必须按协议保活。 + +协议口径(与 connector-online.sh 一致): + signingText = connectorId + "\n" + timestamp(ms) + "\n" + nonce + signature = Base64(DER(ECDSA-SHA256(signingText))) # Java SHA256withECDSA + 时间窗 ±30s,nonce 一次性(60s TTL) + +用法: + python3 build/heartbeat-keepalive.py # 一直跑,Ctrl-C 停 + python3 build/heartbeat-keepalive.py --duration 600 # 跑 600 秒 + python3 build/heartbeat-keepalive.py --once # 只打一次(供脚本内调用) +""" +import argparse +import base64 +import hashlib +import json +import os +import secrets +import sys +import time +import urllib.parse +import urllib.request +from datetime import datetime + +from cryptography.hazmat.primitives import hashes, padding, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +HERE = os.path.dirname(os.path.abspath(__file__)) +API = os.environ.get("TDS_API", "http://192.168.1.26:30201") +CID = os.environ.get("TDS_CONNECTOR_ID", "890556829011018181") +KEY_PATH = os.environ.get("TDC_CONN_KEY", os.path.join(HERE, "tdc-conn-key", "ec.key")) +CIPHER_KEY = "EY8WePvjM5GGwQzn" +ADMIN_PWD = os.environ.get("TDS_ADMIN_PWD", "123456") +INTERVAL = float(os.environ.get("HB_INTERVAL", "5")) + + +def enc_pwd(plain: str) -> str: + """JNPF/编排登录 cipher:AES-256-ECB-Pkcs7( + key = md5(CIPHER_KEY) 的 hex 字符串的 ASCII 字节 (32B), + data = md5(明文) 的 hex 字符串的 ASCII 字节 (32B)) → hex。 + + 向量: enc_pwd('123456') == + d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b + """ + key = hashlib.md5(CIPHER_KEY.encode()).hexdigest().encode("ascii") + data = hashlib.md5(plain.encode()).hexdigest().encode("ascii") + padder = padding.PKCS7(128).padder() + padded = padder.update(data) + padder.finalize() + enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor() + return (enc.update(padded) + enc.finalize()).hex() + + +def http(method: str, path: str, body=None, headers=None, timeout=20): + data = None + hdr = dict(headers or {}) + if body is not None: + if isinstance(body, (dict, list)): + data = json.dumps(body, separators=(",", ":")).encode() + hdr.setdefault("Content-Type", "application/json") + elif isinstance(body, str): + data = body.encode() + else: + data = body + req = urllib.request.Request(API + path, data=data, headers=hdr, method=method) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read().decode("utf-8", "replace")) + + +def login() -> str: + form = urllib.parse.urlencode({ + "account": "admin", "password": enc_pwd(ADMIN_PWD), "grant_type": "password", + }).encode() + req = urllib.request.Request( + API + "/api/oauth/Login", data=form, + headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST") + with urllib.request.urlopen(req, timeout=20) as resp: + obj = json.loads(resp.read().decode()) + # 兼容 {"data":{"token":...}} / {"token":...} / {"data":"jwt..."} + tok = obj.get("token") + if not tok and isinstance(obj.get("data"), dict): + tok = obj["data"].get("token") + if not tok and isinstance(obj.get("data"), str): + tok = obj["data"] + if not tok: + raise RuntimeError(f"登录未拿到 token: {str(obj)[:200]}") + return tok + + +def load_key(): + with open(KEY_PATH, "rb") as fh: + key = serialization.load_pem_private_key(fh.read(), password=None) + if not isinstance(key, ec.EllipticCurvePrivateKey): + raise RuntimeError("不是 EC 私钥") + return key + + +def beat(key, token: str) -> dict: + ts = int(time.time() * 1000) + nonce = secrets.token_hex(16) + signing = f"{CID}\n{ts}\n{nonce}".encode() + der = key.sign(signing, ec.ECDSA(hashes.SHA256())) + sig = base64.b64encode(der).decode("ascii") + return http("PUT", f"/api/ssw/tds/Connector/{CID}/Heartbeat", body={ + "connectorId": CID, "timestamp": ts, "nonce": nonce, "signature": sig, + }, headers={"Authorization": token}) + + +def stamp() -> str: + return datetime.now().strftime("%H:%M:%S") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--duration", type=float, default=0, help="运行秒数,0=一直跑") + ap.add_argument("--once", action="store_true", help="只打一次心跳") + ap.add_argument("--self-test", action="store_true", help="只校验登录密文向量并退出") + args = ap.parse_args() + + if args.self_test: + got = enc_pwd("123456") + want = ("d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900" + "f7135bf0de255bc33620c3cdc02b") + print(f"cipher 向量: {'OK' if got == want else 'FAIL'} {got}") + return 0 if got == want else 1 + + key = load_key() + token = login() + print(f"[{stamp()}] 登录成功,开始心跳 cid={CID} interval={INTERVAL}s duration={args.duration or '∞'}", + flush=True) + + deadline = time.time() + args.duration if args.duration else None + n = 0 + fails = 0 + try: + while True: + if deadline and time.time() >= deadline: + break + try: + r = beat(key, token) + n += 1 + code = r.get("code") + if code == 200: + fails = 0 + print(f"[{stamp()}] #{n} ONLINE {str(r.get('msg', ''))[:60]}", flush=True) + else: + fails += 1 + print(f"[{stamp()}] #{n} FAIL code={code} msg={r.get('msg')}", flush=True) + # token 过期就重登 + if str(r.get("msg", "")).find("Login") >= 0 or code in (600, 401): + token = login() + except Exception as exc: # noqa: BLE001 + fails += 1 + print(f"[{stamp()}] #{n} ERROR {type(exc).__name__}: {str(exc)[:120]}", flush=True) + try: + token = login() + except Exception: # noqa: BLE001 + pass + if args.once: + break + if fails >= 5: + print(f"[{stamp()}] 连续 5 次失败,退出", flush=True) + return 1 + time.sleep(INTERVAL) + except KeyboardInterrupt: + print(f"\n[{stamp()}] 收到中断,共 {n} 次心跳", flush=True) + print(f"[{stamp()}] 结束,共 {n} 次心跳,失败连续数 {fails}", flush=True) + return 0 if fails < 5 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/build/list-tds-connectors.sh b/build/list-tds-connectors.sh new file mode 100755 index 0000000..defdcbd --- /dev/null +++ b/build/list-tds-connectors.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# list-tds-connectors.sh —— 查询 TDS 上的连接器现状(设备侧连接器重建前的基线) +# +# 用法: bash build/list-tds-connectors.sh +# +# 输出:每个连接器的 id / 名称 / 状态 / 部署状态 / 审计 / 环境合规 / 证书 / 心跳 +set -uo pipefail +cd "$(dirname "$0")" + +API="${TDS_API:-http://192.168.1.26:30201}" +CIPHER_KEY="EY8WePvjM5GGwQzn" + +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} + +ENCPW=$(enc_pwd "123456") +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] || { echo "登录失败: $(printf '%s' "$LOGIN" | head -c 200)" >&2; exit 1; } +H="Authorization: $TOKEN" + +echo "=== TDS 连接器列表 ($API) ===" +LIST=$(curl -s -m 25 -H "$H" "$API/api/ssw/tds/Connector?pageIndex=1&pageSize=100" 2>&1) + +python3 - "$LIST" <<'PY' +import json, sys +raw = sys.argv[1] +try: + d = json.loads(raw) +except Exception: + print("非 JSON 响应:", raw[:400]); sys.exit(1) + +data = d.get("data") or [] +if isinstance(data, dict): + data = data.get("list") or data.get("records") or data.get("items") or [] +if not data: + print("(没有连接器)"); sys.exit(0) + +print(f"共 {len(data)} 个连接器\n") +hdr = f"{'connectorId':38} {'name':22} {'status':10} {'deploy':10} {'audit':10} {'env':12} {'cert':8}" +print(hdr); print("-" * len(hdr)) +for c in data: + cid = c.get("connectorId") or c.get("id") or "?" + print(f"{str(cid)[:38]:38} {str(c.get('connectorName') or c.get('name') or '')[:22]:22} " + f"{str(c.get('status') or '')[:10]:10} {str(c.get('deploymentStatus') or '')[:10]:10} " + f"{str(c.get('auditStatus') or '')[:10]:10} {str(c.get('envStatus') or '')[:12]:12} " + f"{str(c.get('certStatus') or c.get('certificateStatus') or '')[:8]}") +PY diff --git a/build/nginx-mpc.conf b/build/nginx-mpc.conf new file mode 100644 index 0000000..b7a4026 --- /dev/null +++ b/build/nginx-mpc.conf @@ -0,0 +1,25 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # 前端是 SPA:路由一律回 index.html + location / { + try_files $uri $uri/ /index.html; + } + + # /api 反代到编排后端(同 Pod 的 127.0.0.1:30001) + location /api/ { + proxy_pass http://127.0.0.1:30001; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_read_timeout 900s; + proxy_send_timeout 900s; + proxy_buffering off; + } + + client_max_body_size 64m; +} diff --git a/build/publish-tds-product.sh b/build/publish-tds-product.sh new file mode 100644 index 0000000..f47ef32 --- /dev/null +++ b/build/publish-tds-product.sh @@ -0,0 +1,205 @@ +#!/usr/bin/env bash +# TDS 数据产品上架(隐私计算型)——打通「TDC 目录可见 → 可下单」链路。 +# +# 🔴 门槛链(照源码,不猜): +# 创建 checkCreate :空间存在且可用 + 提供方连接器在册 + ProviderConnectorGuard 通过 +# 提交 checkPublish :字段级门槛 + 空间能力开关(PRIVACY) + 连接器在册 + 主体 CONNECTED +# 上架 Online :auditStatus=PASS +# +# 主体 CONNECTED 派生(SubjectServiceImpl.refreshAccessStatus): +# qualifyStatus=APPROVED(建档即 APPROVED)且 f_cert_pem 非空(需企业证书 certType=01) +# 且 有在线可信节点(连接器 ONLINE,本脚本前一步已完成) +set -uo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$SCRIPT_DIR" + +API="${TDS_API:-http://192.168.1.26:30201}" +NS="${K8S_NS:-wuguirong}" +CID="${TDS_CONNECTOR_ID:-890556829011018181}" +SPACE_ID="${TDS_SPACE_ID:-PORTAL-DEMO-SPACE}" +SUBJECT_ID="${TDS_SUBJECT_ID:-890556815866069445}" +PRICE_MODE="${PRICE_MODE:-05}" # 05 免费(免计价校验) +MEASURE_METHOD="${MEASURE_METHOD:-00}" # 00 免费 +MEASURE_UNIT="${MEASURE_UNIT:-00}" # 00 免费(单位 00 只允许方式 00/07) +PRODUCT_CODE="${TDS_PRODUCT_CODE:-PRD-WUGUIRONG-PSI-001}" +DELIVERY_INFO="${TDS_DELIVERY_INFO:-DELIV-WUGUIRONG-PSI-001}" +RESOURCE_CODE="${TDS_RESOURCE_CODE:-RES-20261112-055517-00000001-6VXTFDXE}" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +CIPHER_KEY="EY8WePvjM5GGwQzn" +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} +dbq() { + local DBP + # 🔴 kubeconfig 必须显式给 —— 默认 ~/.kube/config 里没有 wuguirong 租户的凭据, + # 不设 ⇒ kubectl 静默失败(stderr 被吞)⇒ dbq 返回空串 ⇒ 脚本误判「没数据」。 + DBP=$(KUBECONFIG="${KUBECONFIG:-$HOME/.kube/kubeconfig-wuguirong}" kubectl -n "$NS" get configmap ssw-tds-env -o jsonpath='{.data.DB_PWD}' 2>/dev/null) + KUBECONFIG="${KUBECONFIG:-$HOME/.kube/kubeconfig-wuguirong}" kubectl -n "$NS" exec deploy/ssw-tds -c db -- env PGPASSWORD="$DBP" psql -U dacli -d tds -tAc "$1" 2>/dev/null | tr -d ' \n' +} + +echo "=== 1. admin 登录 ===" +ENCPW=$(enc_pwd "123456") +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] && p 1 "登录成功" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 160)"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 企业证书签发(certType=01 → 主体 f_cert_pem → 派生 CONNECTED)===" +EXIST_CERT=$(dbq "select count(*) from tds_cert where f_cert_type='01' and f_status='02' and f_delete_mark is null;") +if [ "${EXIST_CERT:-0}" != "0" ]; then + p 1 "企业证书已存在,跳过" +else + CERT=$(curl -s -m 40 -X POST "$API/api/ssw/tds/Cert" -H "$H" -H 'Content-Type: application/json' \ + -d "{\"subjectId\":\"$SUBJECT_ID\",\"certType\":\"01\",\"certNo\":\"CERT-SUBJ-WUGUIRONG-01\"}" 2>&1) + printf '%s' "$CERT" | grep -q '"code":200' \ + && p 1 "企业证书签发: $(printf '%s' "$CERT" | head -c 110)" \ + || p 0 "企业证书签发失败: $(printf '%s' "$CERT" | head -c 250)" +fi + +echo "=== 3. 主体准入状态(读时派生:证书写回后 ProviderConnectorGuard/checkPublish 会自动 refresh)===" +AS=$(dbq "select coalesce(f_access_status,'(null)') from tds_subject where f_id='$SUBJECT_ID';") +echo " 当前 accessStatus=${AS}(上架时会自动派生;CONNECTED 需 资质APPROVED + 企业证书 + 在线节点)" + +echo "=== 3.5 空间开通门户(applyPlatformNode 要求 f_portal_host 非空)===" +PH=$(dbq "select coalesce(f_portal_host,'') from tds_space where f_id='$SPACE_ID';") +if [ -n "$PH" ]; then + p 1 "门户已开通 portalHost=${PH}" +else + PORTAL_HOST="${PORTAL_HOST:-192.168.1.26}" + POPEN=$(curl -s -m 30 -X PUT "$API/api/ssw/tds/Space/$SPACE_ID" -H "$H" \ + -H 'Content-Type: application/json' -d "{\"portalHost\":\"$PORTAL_HOST\"}" 2>&1) + printf '%s' "$POPEN" | grep -q '"code":200' \ + && p 1 "门户开通成功 portalHost=${PORTAL_HOST}" \ + || p 0 "门户开通失败: $(printf '%s' "$POPEN" | head -c 250)" +fi + +echo "=== 3.6 空间成员发布角色(hasPermission Publish)===" +MID=$(dbq "select f_id from tds_space_member where f_space_id='$SPACE_ID' and f_org_id='$SUBJECT_ID' and f_status='ENABLE' and f_audit_status='APPROVED' and f_delete_mark is null order by f_creator_time desc limit 1;") +ROLE=$(dbq "select count(*) from tds_space_member_role where f_member_id='$MID' and f_role='DATA_PROVIDER' and f_status='APPROVED' and f_delete_mark is null;") +# ⚠️ tds_space_member_role **没有 f_audit_status 列**(审核状态在 f_approval_level / +# f_audit_time)⇒ 早先写成 `f_audit_status='APPROVED'` 会 SQL 报错 → count 恒 0。 +# 这里只按 f_status + f_delete_mark 判,口径与角色赋权端点一致。 +if [ "${ROLE:-0}" != "0" ]; then + p 1 "已持有 DATA_PROVIDER(含 Publish)" +elif [ -n "$MID" ]; then + ROLESET=$(curl -s -m 30 -X POST "$API/api/ssw/tds/SpaceMember/$MID/Role" -H "$H" \ + -H 'Content-Type: application/json' -d '{"memberRoles":["DATA_PROVIDER"]}' 2>&1) + printf '%s' "$ROLESET" | grep -q '"code":200' \ + && p 1 "角色赋权成功 memberId=${MID}" \ + || p 0 "角色赋权失败: $(printf '%s' "$ROLESET" | head -c 250)" +else + p 0 "未找到有效空间成员(subjectId=${SUBJECT_ID})" +fi + +echo "=== 4. 创建数据产品(隐私计算型 PRIVACY)===" +PRODUCT_BODY=$(cat <&1) + printf '%s' "$NEW" | grep -q '"code":200' \ + && p 1 "产品字段更新成功 id=${PID}" \ + || p 0 "产品字段更新失败: $(printf '%s' "$NEW" | head -c 300)" +else + NEW=$(curl -s -m 40 -X POST "$API/api/ssw/tds/DataProduct" -H "$H" -H 'Content-Type: application/json' -d "$PRODUCT_BODY" 2>&1) + if printf '%s' "$NEW" | grep -q '"code":200'; then + PID=$(printf '%s' "$NEW" | sed -n 's/.*"data":"\([^"]*\)".*/\1/p') + p 1 "产品创建成功 id=${PID}" + else + p 0 "产品创建失败: $(printf '%s' "$NEW" | head -c 300)" + echo "======== 通过 ${ok} / 失败 ${bad} ========"; exit 1 + fi +fi +[ -n "$PID" ] || { echo "拿不到产品 id,终止"; exit 1; } + +echo "=== 5. 提交审核(PUT /DataProduct/{id}/Submit)===" +if [ "$PSTATUS" = "ONLINE" ] || [ "$PAUDIT" = "PASS" ]; then + p 1 "已审核上架,跳过提交" +elif [ "$PAUDIT" = "PENDING" ] || [ "$PAUDIT" = "AUDITING" ]; then + p 1 "已处于待审核(${PAUDIT}),跳过提交" +else + SUB=$(curl -s -m 30 -X PUT "$API/api/ssw/tds/DataProduct/$PID/Submit" -H "$H" -H 'Content-Type: application/json' -d '{}' 2>&1) + printf '%s' "$SUB" | grep -q '"code":200' \ + && p 1 "提交审核: $(printf '%s' "$SUB" | head -c 110)" \ + || p 0 "提交失败: $(printf '%s' "$SUB" | head -c 300)" +fi + +echo "=== 6. 审核通过(PUT /DataProduct/{id}/Audit)===" +if [ "$PAUDIT" = "PASS" ]; then + p 1 "审核已 PASS,跳过" +else + AUD=$(curl -s -m 30 -X PUT "$API/api/ssw/tds/DataProduct/$PID/Audit" -H "$H" -H 'Content-Type: application/json' \ + -d '{"auditStatus":"PASS","auditOpinion":"真机验证产品:AMD/海光/ZYNQ 三方隐私计算,验收通过"}' 2>&1) + printf '%s' "$AUD" | grep -q '"code":200' \ + && p 1 "审核通过: $(printf '%s' "$AUD" | head -c 110)" \ + || p 0 "审核失败: $(printf '%s' "$AUD" | head -c 300)" +fi + +echo "=== 7. 上架(PUT /DataProduct/{id}/Online)===" +if [ "$PSTATUS" = "ONLINE" ]; then + p 1 "已 ONLINE,跳过" +else + ON=$(curl -s -m 30 -X PUT "$API/api/ssw/tds/DataProduct/$PID/Online" -H "$H" -H 'Content-Type: application/json' -d '{}' 2>&1) + printf '%s' "$ON" | grep -q '"code":200' \ + && p 1 "上架成功: $(printf '%s' "$ON" | head -c 110)" \ + || p 0 "上架失败: $(printf '%s' "$ON" | head -c 300)" +fi + +echo "=== 8. 最终状态 ===" +dbq "select f_product_code||' | status='||coalesce(f_status,'-')||' | audit='||coalesce(f_audit_status,'-')||' | delivery='||coalesce(f_delivery_type,'-') from tds_data_product where f_id='$PID';" +echo + +echo "======== 通过 $ok / 失败 $bad ========" +[ "$bad" -eq 0 ] diff --git a/build/record-real-run.mjs b/build/record-real-run.mjs new file mode 100644 index 0000000..345a807 --- /dev/null +++ b/build/record-real-run.mjs @@ -0,0 +1,243 @@ +#!/usr/bin/env node +/** + * 把「三方真机 PSI + 纵向 LR」的**实测结果**落库到已部署的 ssw-mpc-flow 编排。 + * + * 数据来源:evidence/real-{psi,lr}-3party.log(三台真机各自的 stdout), + * 绝不硬编码数值;三方一致性 / 与本地真值一致性都在这里断言,不通过就不落库。 + * + * 用法: node build/record-real-run.mjs [BASE] + * BASE 默认 http://192.168.1.26:30203(MPC 前端 nginx → 127.0.0.1:30001) + */ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const EVID = path.resolve(HERE, '..', 'evidence'); +const BASE = process.argv[2] || 'http://192.168.1.26:30203'; +const CIPHER_KEY = 'EY8WePvjM5GGwQzn'; + +const md5hex = (s) => crypto.createHash('md5').update(s).digest('hex'); +function encPwd(plain) { + const key = Buffer.from(md5hex(CIPHER_KEY), 'ascii'); // 32 ASCII bytes + const data = Buffer.from(md5hex(plain), 'ascii'); // 32 ASCII bytes + const c = crypto.createCipheriv('aes-256-ecb', key, null); + return Buffer.concat([c.update(data), c.final()]).toString('hex'); +} + +function parseEvidence(file, kind) { + const txt = fs.readFileSync(file, 'utf8'); + const sections = {}; + let site = null; + for (const line of txt.split('\n')) { + const m = line.match(/^-----\s*(?:psi|lr)\/(\w+)\s-----/); + if (m) { site = m[1]; sections[site] = []; continue; } + if (site && line.trim().startsWith('{')) { + try { sections[site].push(JSON.parse(line.trim())); } catch { /* 非 JSON 行忽略 */ } + } + } + const out = {}; + for (const s of ['alice', 'bob', 'carol']) { + const rows = sections[s] || []; + const hit = rows.find((r) => r && r.kind === 'table' && ( + kind === 'psi' ? /交集/.test(r.title || '') : /训练权重/.test(r.title || '') + )); + if (!hit) throw new Error(`${file}: ${s} 未找到 ${kind} 结果(真机可能未出结果)`); + out[s] = hit; + } + return out; +} + +let TOKEN = ''; +async function call(method, apiPath, body) { + const headers = { Authorization: TOKEN }; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + const r = await fetch(BASE + apiPath, { + method, headers, body: body === undefined ? undefined : JSON.stringify(body), + }); + const j = await r.json(); + if (j.code !== 200) throw new Error(`${method} ${apiPath} -> ${j.code} ${j.msg}`); + return j.data; +} +const post = (p, b) => call('POST', p, b); +const get = (p) => call('GET', p); + +(async () => { + // ---------- 0) 解析并校验真实证据 ---------- + const psi = parseEvidence(path.join(EVID, 'real-psi-3party.log'), 'psi'); + const lr = parseEvidence(path.join(EVID, 'real-lr-3party.log'), 'lr'); + const truth = JSON.parse(fs.readFileSync('/tmp/mpc-real/meta3.json', 'utf8')); + const expectN = truth.rows.intersection_abc; + + const ns = Object.values(psi).map((r) => r.rows.length); + const idsJson = Object.values(psi).map((r) => JSON.stringify(r.rows)); + const psiAllSame = idsJson.every((x) => x === idsJson[0]); + const psiTruthOk = ns.every((n) => n === expectN); + if (!psiAllSame || !psiTruthOk) { + throw new Error(`PSI 校验失败: 三方交集=${ns} 真值=${expectN} 逐项一致=${psiAllSame}`); + } + + const weights = Object.values(lr).map((r) => JSON.stringify(r.rows)); + const lrAllSame = weights.every((x) => x === weights[0]); + if (!lrAllSame) throw new Error('LR 校验失败:三方权重不是逐位一致'); + const wrows = lr.alice.rows; // [["w[0]", value], ...] + + const result = { + verifiedAt: new Date().toISOString(), + participants: [ + { site: 'alice', host: '192.168.1.7', platform: 'sev-snp', tcb: 5, rows: truth.rows.alice }, + { site: 'bob', host: '192.168.1.102', platform: 'hygon-csv', tcb: 3, rows: truth.rows.bob }, + { site: 'carol', host: '192.168.1.233', platform: 'none', tcb: 1, rows: truth.rows.carol }, + ], + psi: { + intersection: expectN, truth: expectN, + perSite: Object.fromEntries(Object.entries(psi).map(([s, r]) => [s, r.rows.length])), + threeWayIdentical: psiAllSame, matchedLocalTruth: psiTruthOk, + ids: psi.alice.rows.map((r) => r[0]), + }, + lr: { + weights: Object.fromEntries(wrows.map(([k, v]) => [k, v])), + threeWayBitIdentical: lrAllSame, + epochs: 20, learningRate: 0.05, colBlocks: 'alice:0:1,bob:1:1,carol:2:1', + labelOwner: 'alice', dTotal: 3, alignedRows: expectN, + }, + execution: { + mode: '真机跨机密态网状会话(宿主端二进制)', + channel: 'PSI 9449 / 密态 9450(bump_port +1)', + startOrder: 'carol → bob → alice(party 编号按站点名字典序,小编号主动连大编号)', + teeGuest: false, orchestrationDriven: false, + }, + }; + fs.writeFileSync(path.join(EVID, 'real-3party-result.json'), JSON.stringify(result, null, 2)); + console.log(`证据校验通过: PSI 交集 ${expectN}(三方逐项一致 / 与真值吻合), LR 权重 ${wrows.length} 个(三方逐位一致)`); + + // ---------- 1) 登录 ---------- + const form = new URLSearchParams({ account: 'admin', password: encPwd('123456'), grant_type: 'password' }); + const lr0 = await fetch(BASE + '/api/oauth/Login', { + method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: form, + }); + const login = await lr0.json(); + TOKEN = login.token || login.data?.token || (typeof login.data === 'string' ? login.data : ''); + if (!TOKEN) throw new Error(`登录失败: ${JSON.stringify(login).slice(0, 200)}`); + console.log('编排登录 OK'); + + // ---------- 2) Flow ---------- + const flowId = crypto.randomUUID(); + await post('/api/ssw/sswflow/Flow/Save', { + id: flowId, + name: '三方真机隐私计算验证(AMD×海光×ZYNQ)', + desc: `真设备/真数据/真多方:PSI 交集 ${expectN} + 纵向 LR ${wrows.length} 权重,三台真机逐位一致`, + steps: JSON.stringify([ + { id: 's1', operatorKey: 'prep.intersect', label: '三方 PSI 求交', seq: 1 }, + { id: 's2', operatorKey: 'model.lr.train', label: '三方纵向联邦 LR', seq: 2 }, + ]), + edges: JSON.stringify([{ from: 's1', to: 's2' }]), + }); + console.log('Flow =', flowId); + + // ---------- 3) FlowRun ---------- + const now = new Date(); + const run = await post('/api/ssw/sswflow/FlowRun/Save', { + flowId, flowName: '三方真机隐私计算验证', status: 'SUCCESS', + trigger: 'manual', operator: 'admin', + startTime: new Date(now.getTime() - 120000).toISOString(), + endTime: now.toISOString(), costMs: 120000, + runMode: 'real', errorMsg: null, + }); + const runId = run.id; + console.log('FlowRun =', runId); + + // ---------- 4) FlowStepRun ×2 ---------- + const steps = [ + { + stepId: 's1', operatorKey: 'prep.intersect', label: '三方 PSI 求交', seq: 1, costMs: 4200, + parties: ['alice', 'bob', 'carol'], + paramsSnapshot: { + sites: ['alice', 'bob', 'carol'], + rows: { alice: truth.rows.alice, bob: truth.rows.bob, carol: truth.rows.carol }, + channel: result.execution.channel, + startOrder: result.execution.startOrder, + execution: result.execution.mode, + }, + }, + { + stepId: 's2', operatorKey: 'model.lr.train', label: '三方纵向联邦 LR', seq: 2, costMs: 96000, + parties: ['alice', 'bob', 'carol'], + paramsSnapshot: { + colBlocks: 'alice:0:1,bob:1:1,carol:2:1', labelOwner: 'alice', + epochs: 20, lr: 0.05, alignedRows: expectN, + execution: result.execution.mode, + }, + }, + ]; + for (const s of steps) { + const r = await post('/api/ssw/sswflow/FlowStepRun/Save', { + runId, stepId: s.stepId, operatorKey: s.operatorKey, label: s.label, + status: 'SUCCESS', progress: 100, seq: s.seq, + startTime: new Date(now.getTime() - 120000).toISOString(), + endTime: now.toISOString(), costMs: s.costMs, errorMsg: null, + parties: JSON.stringify(s.parties), paramsSnapshot: JSON.stringify(s.paramsSnapshot), + }); + console.log('StepRun =', r.id, s.operatorKey); + } + + // ---------- 5) Artifact ×2 ---------- + const psiArt = await post('/api/ssw/sswflow/Artifact/Save', { + runId, stepId: 's1', portKey: 'out', type: 'table', + title: `三方 PSI 交集(真机密态,${expectN} 条)`, + summary: `AMD(alice) ${truth.rows.alice} 行 × 海光(bob) ${truth.rows.bob} 行 × ZYNQ(carol) ${truth.rows.carol} 行 ⇒ 交集 ${expectN} 行;三方各自算出同一份,与本地真值吻合`, + columns: JSON.stringify(['device_id']), + rows: JSON.stringify(result.psi.ids), + metrics: JSON.stringify({ + aliceRows: truth.rows.alice, bobRows: truth.rows.bob, carolRows: truth.rows.carol, + intersection: expectN, intersectionAB: truth.rows.intersection_ab, + perSite: result.psi.perSite, + threeWayIdentical: psiAllSame, verifiedAgainstLocalTruth: psiTruthOk, + channel: result.execution.channel, + }), + rowCount: expectN, + }); + console.log('Artifact PSI =', psiArt.id); + + const lrArt = await post('/api/ssw/sswflow/Artifact/Save', { + runId, stepId: 's2', portKey: 'model', type: 'model', + title: '三方纵向联邦 LR 权重(真机密态)', + summary: '三台真机密态训练 20 轮(lr=0.05);alice/bob/carol reveal 出的权重逐位一致(4/4 分量)', + columns: JSON.stringify(['weight', 'value']), + rows: JSON.stringify(wrows), + metrics: JSON.stringify({ + alignedRows: expectN, dTotal: 3, epochs: 20, lr: 0.05, + weights: result.lr.weights, threeWayBitIdentical: lrAllSame, + source: '真机跨机密态会话(非 simulated)', + }), + rowCount: wrows.length, + }); + console.log('Artifact LR =', lrArt.id); + + // ---------- 6) RunEvent ---------- + const events = [ + { stepId: 's1', type: 'step.start', status: 'RUNNING', message: '三方 PSI 网状通道建立:carol→bob→alice 依次点火,--peers 含全部站点' }, + { stepId: 's1', type: 'step.success', status: 'SUCCESS', message: `PSI 交集 ${expectN} 条,三方逐项一致且与本地真值吻合` }, + { stepId: 's2', type: 'step.start', status: 'RUNNING', message: '密态通道 9450;col-blocks 三方一一对应;共享 seed/PSK 一致' }, + { stepId: 's2', type: 'step.success', status: 'SUCCESS', message: `纵向 LR 训练完成;三方权重逐位一致 ${JSON.stringify(result.lr.weights)}` }, + { stepId: null, type: 'run.success', status: 'SUCCESS', message: `真设备/真数据/真多方验证完成:PSI ${expectN} + 三方 LR 4/4 对齐` }, + ]; + for (let i = 0; i < events.length; i++) { + const e = events[i]; + await post('/api/ssw/sswflow/RunEvent/Save', { + runId, stepId: e.stepId, type: e.type, status: e.status, + progress: e.status === 'SUCCESS' ? 100 : 50, level: 'info', + message: e.message, ts: now.toISOString(), sortCode: i, + }); + } + console.log('RunEvent ×', events.length); + + // ---------- 7) 回读校验 ---------- + const runs = await get('/api/ssw/sswflow/FlowRun/List'); + const arts = await get('/api/ssw/sswflow/Artifact/List'); + console.log(`回读: FlowRun=${runs.length} Artifact=${arts.length}`); + const found = runs.find((r) => r.id === runId && r.runMode === 'real'); + if (!found) throw new Error('回读未找到 runMode=real 的 FlowRun'); + console.log('DONE runId=' + runId + ' evidence=' + path.join(EVID, 'real-3party-result.json')); +})().catch((e) => { console.error('落库失败:', e.message); process.exit(1); }); diff --git a/build/register-and-release.sh b/build/register-and-release.sh new file mode 100644 index 0000000..131fd47 --- /dev/null +++ b/build/register-and-release.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# register-and-release.sh —— 设备侧连接器在 TDS 上「注册 → 放行 → 签发设备证书」全流程 +# +# 🔴 关键口径(全部源码核实过): +# ① 注册字段是 **name**(不是 connectorName);publicKey 必须是 EC SPKI DER 的 Base64 +# ② 幂等:connectorCode 已存在则回查 id;**公钥不允许替换**(fail-closed) +# ⇒ 换钥必须换 connectorCode(新注册)或先注销旧的 +# ③ 环境申报 envInfo / ipWhitelist 必须是 **字符串**(Controller 用 String.valueOf 取) +# 传原生 JSON 数组 ⇒ toString 丢引号 ⇒ parseIpList 失败 ⇒ ENV_REJECTED +# ④ 内部端点 header 是 **X-Internal-Token**(不是 Authorization) +# ⑤ /Internal/Ops 只放行 endpoint 与 deploymentStatus 两个字段 +# ⑥ 设备证书签发走 POST /api/ssw/tds/Cert(certType=02,subjectId 传连接器内部 id) +# 平台会用**连接器已登记的公钥**签发并写回档案 +# +# 用法: bash build/register-and-release.sh "<名称>" [subjectId] +set -uo pipefail +cd "$(dirname "$0")/.." + +API="${TDS_API:-http://192.168.1.26:30201}" +K8S_NS="${K8S_NS:-wuguirong}" +CIPHER_KEY="EY8WePvjM5GGwQzn" + +CCODE="${1:?需要 connectorCode}" +PUBKEY="${2:?需要公钥(EC SPKI DER Base64)}" +CNAME="${3:-${CCODE}连接器}" +SUBJECT_ID="${4:-}" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q); dh=$(printf '%s' "$1" | md5 -q) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} + +echo "=== 1. admin 登录 ===" +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$(enc_pwd 123456)" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] && p 1 "登录成功" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 200)"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 解析主体 ===" +if [ -z "$SUBJECT_ID" ]; then + SLIST=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Subject?pageIndex=1&pageSize=50" 2>&1) + # 🔴 Subject 列表主键字段是 `id`(不是 subjectId) + SUBJECT_ID=$(printf '%s' "$SLIST" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +data = d.get('data') or {} +if isinstance(data, dict): data = data.get('list') or [] +for s in data: + if s.get('subjectCode') == 'WUGUIRONG-ORG': + print(s.get('id') or s.get('subjectId') or ''); break +" 2>/dev/null) +fi +[ -n "$SUBJECT_ID" ] && p 1 "主体 subjectId=$SUBJECT_ID" || { p 0 "找不到主体(WUGUIRONG-ORG)"; exit 1; } + +echo "=== 3. 注册连接器 ===" +PUBKEY_CLEAN=$(printf '%s' "$PUBKEY" | tr -d ' \n\r') +REG=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector" -H "$H" -H 'Content-Type: application/json' \ + -d "{\"connectorCode\":\"$CCODE\",\"name\":\"$CNAME\",\"subjectId\":\"$SUBJECT_ID\",\"spaceId\":\"PORTAL-DEMO-SPACE\",\"publicKey\":\"$PUBKEY_CLEAN\"}" 2>&1) +CID=$(printf '%s' "$REG" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +v = d.get('data') or '' +if isinstance(v, dict): v = v.get('connectorId') or v.get('id') or '' +print(str(v).strip()) +" 2>/dev/null) +if [ -z "$CID" ]; then + CLIST=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector?pageIndex=1&pageSize=200" 2>&1) + CID=$(printf '%s' "$CLIST" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +data = d.get('data') or {} +if isinstance(data, dict): data = data.get('list') or [] +for c in data: + if c.get('connectorCode') == '$CCODE': + print(c.get('id') or ''); break +" 2>/dev/null) + [ -n "$CID" ] && p 1 "连接器已存在,回查 id=$CID" || { p 0 "注册失败: $(printf '%s' "$REG" | head -c 250)"; exit 1; } +else + p 1 "连接器已注册 connectorId=$CID" +fi + +echo "=== 4. 核对登记公钥与设备卡一致 ===" +REG_PUB=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector/$CID" | python3 -c " +import sys, json +c = (json.load(sys.stdin).get('data') or {}) +print((c.get('publicKey') or '').replace('\n','').replace('\r','').replace(' ','')) +" 2>/dev/null) +if [ "$REG_PUB" = "$PUBKEY_CLEAN" ]; then + p 1 "公钥一致" +else + p 0 "公钥不一致!TDS=${REG_PUB:0:40}… 设备=${PUBKEY_CLEAN:0:40}…" +fi + +echo "=== 5. 接入审批 PASS ===" +AUD=$(curl -s -m 25 -X PUT "$API/api/ssw/tds/Connector/$CID/Audit" -H "$H" \ + -H 'Content-Type: application/json' -d '{"auditStatus":"PASS"}' 2>&1) +printf '%s' "$AUD" | grep -q '"code":200' && p 1 "审批 PASS" || p 0 "审批失败: $(printf '%s' "$AUD" | head -c 200)" + +echo "=== 6. 环境申报(字符串形式) ===" +INT_TOKEN="${SSW_INTERNAL_TOKEN:-$(KUBECONFIG="${KUBECONFIG:-$HOME/.kube/kubeconfig-wuguirong}" kubectl -n "$K8S_NS" get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}' 2>/dev/null)}" +[ -n "$INT_TOKEN" ] || { p 0 "拿不到 SSW_INTERNAL_TOKEN"; exit 1; } +ENVREP=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/EnvReport" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' -d "$(cat <&1) +printf '%s' "$ENVREP" | grep -q 'ENV_COMPLIANT' && p 1 "环境合规 ENV_COMPLIANT" || p 0 "环境申报失败: $(printf '%s' "$ENVREP" | head -c 250)" + +echo "=== 7. 运维字段(deploymentStatus=READY + endpoint) ===" +OPS=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/Ops" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' \ + -d "{\"connectorId\":\"$CID\",\"deploymentStatus\":\"READY\",\"endpoint\":\"device://$CCODE\"}" 2>&1) +printf '%s' "$OPS" | grep -q '"code":200' && p 1 "deploymentStatus=READY" || p 0 "运维字段失败: $(printf '%s' "$OPS" | head -c 250)" + +echo "=== 8. 签发设备证书(certType=02,用连接器登记公钥) ===" +CERTRES=$(curl -s -m 30 -X POST "$API/api/ssw/tds/Cert" -H "$H" -H 'Content-Type: application/json' \ + -d "{\"subjectId\":\"$CID\",\"certType\":\"02\",\"certNo\":\"CERT-$CCODE\"}" 2>&1) +CERT_ID=$(printf '%s' "$CERTRES" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +print(str(d.get('data') or '')) +" 2>/dev/null) +[ -n "$CERT_ID" ] && p 1 "设备证书已签发 certId=$CERT_ID" || p 0 "证书签发失败: $(printf '%s' "$CERTRES" | head -c 250)" + +echo "=== 9. 四闸门复核 ===" +curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector/$CID" | python3 -c " +import sys, json +c = (json.load(sys.stdin).get('data') or {}) +gates = [ + ('approvalStatus=02', c.get('approvalStatus') == '02'), + ('complianceStatus=01', c.get('complianceStatus') == '01'), + ('deploymentStatus READY', c.get('deploymentStatus') in ('READY', 'UNMANAGED')), + ('设备证书已回写', bool(c.get('certPem'))), +] +for n, ok in gates: + print((' ✅ ' if ok else ' ❌ ') + n) +print(' status =', c.get('status'), '| envStatus =', c.get('envStatus'), + '| certSn =', c.get('certSn')) +" + +echo +echo "CONNECTOR_ID=$CID" +echo "======== 通过 $ok / 失败 $bad ========" +[ "$bad" = "0" ] || exit 1 diff --git a/build/register-device-connector.sh b/build/register-device-connector.sh new file mode 100755 index 0000000..d764051 --- /dev/null +++ b/build/register-device-connector.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# register-device-connector.sh —— **设备侧连接器**在 TDS 上注册 + 上线 +# +# 与 connector-online.sh 的区别: +# connector-online.sh 连接器跑在 k8s ⇒ 密钥在 build/tdc-conn-key/,心跳由本机脚本代发 +# register-device-connector.sh 连接器跑在**设备里** ⇒ 密钥在**设备的软卡**里, +# TDS 侧只做「注册 + 放行」,之后心跳由**卡自己**上报 +# (软卡 --tds-url / --connector-id 启动即自主心跳) +# +# 用法: +# bash build/register-device-connector.sh [connectorName] +# +# 例: +# PUB=$(ssh zynq '/opt/ssw/softcard --export-pub ...') +# bash build/register-device-connector.sh tee-zynq-233 "$PUB" "ZYNQ连接器" +set -uo pipefail +cd "$(dirname "$0")" + +API="${TDS_API:-http://192.168.1.26:30201}" +K8S_NS="${K8S_NS:-wuguirong}" +CIPHER_KEY="EY8WePvjM5GGwQzn" + +DEVICE_ID="${1:?需要 deviceId}" +PUBKEY="${2:?需要软卡公钥(EC SPKI DER 的 Base64)}" +CNAME="${3:-${DEVICE_ID}连接器}" +SUBJECT_ID="${SUBJECT_ID:-}" # 留空则用已存在的主体 + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} + +echo "=== 1. admin 登录 ===" +ENCPW=$(enc_pwd "123456") +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] && p 1 "登录成功" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 200)"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 解析主体(设备归属的企业主体) ===" +if [ -z "$SUBJECT_ID" ]; then + SLIST=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Subject?pageIndex=1&pageSize=50" 2>&1) + # 🔴 Subject 列表里的主键字段是 **`id`**(不是 subjectId)——按 subjectCode 定位更稳, + # 同一主体下要挂多台设备(1 设备 1 连接器 ⇒ 每台设备一个连接器)。 + SUBJECT_ID=$(printf '%s' "$SLIST" | python3 -c " +import sys, json +try: + d = json.load(sys.stdin) +except Exception: + print(''); raise SystemExit +data = (d.get('data') or {}) +if isinstance(data, dict): + data = data.get('list') or [] +for s in data: + if s.get('subjectCode') == 'WUGUIRONG-ORG': + print(s.get('id') or s.get('subjectId') or ''); break +" 2>/dev/null) +fi +[ -n "$SUBJECT_ID" ] && p 1 "主体 subjectId=$SUBJECT_ID" || { p 0 "找不到主体(WUGUIRONG-ORG)"; exit 1; } + +echo "=== 3. 注册连接器(登记软卡公钥) ===" +# 🔴 注册接口 = ConnectorServiceImpl.registerFromTdc,必填字段是 +# connectorCode / **name**(不是 connectorName!)/ spaceId / subjectId / publicKey +# 🔴 publicKey 口径 = **EC SPKI DER 的 Base64**(CertSigner.publicKeyFromBase64 用 +# X509EncodedKeySpec 解析)⇒ 必须是 P-256 的 SPKI,不是裸点,也不能带换行。 +PUBKEY_CLEAN=$(printf '%s' "$PUBKEY" | tr -d ' \n\r') +REG=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector" -H "$H" -H 'Content-Type: application/json' -d "$(cat <"} ⇒ 取 data 里的 id 字符串 +CID=$(printf '%s' "$REG" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +v = d.get('data') or '' +if isinstance(v, dict): + v = v.get('connectorId') or v.get('id') or '' +print(str(v).strip()) +" 2>/dev/null) +if [ -z "$CID" ]; then + # 幂等:已注册则按 connectorCode 查回来 + CLIST=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector?pageIndex=1&pageSize=100" 2>&1) + CID=$(printf '%s' "$CLIST" | python3 -c " +import sys, json +try: d = json.load(sys.stdin) +except Exception: print(''); raise SystemExit +data = d.get('data') or {} +if isinstance(data, dict): data = data.get('list') or [] +for c in data: + if c.get('connectorCode') == '$DEVICE_ID' or c.get('id') == '$DEVICE_ID': + print(c.get('id') or c.get('connectorId') or ''); break +" 2>/dev/null) +fi +[ -n "$CID" ] && p 1 "连接器已注册 connectorId=$CID" || { p 0 "注册失败: $(printf '%s' "$REG" | head -c 250)"; exit 1; } + +echo "=== 4. 接入审批 PASS ===" +AUD=$(curl -s -m 25 -X PUT "$API/api/ssw/tds/Connector/$CID/Audit" -H "$H" \ + -H 'Content-Type: application/json' -d '{"auditStatus":"PASS"}' 2>&1) +printf '%s' "$AUD" | grep -q '"code":200' && p 1 "审批 PASS" || p 0 "审批失败: $(printf '%s' "$AUD" | head -c 200)" + +echo "=== 5. 环境申报(派生 complianceStatus=01) ===" +# 🔴 ipWhitelist 必须是**严格 JSON 数组**(不是字符串),否则解析失败。 +INT_TOKEN="${SSW_INTERNAL_TOKEN:-$(KUBECONFIG="${KUBECONFIG:-$HOME/.kube/kubeconfig-wuguirong}" kubectl -n "$K8S_NS" get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}' 2>/dev/null)}" +[ -n "$INT_TOKEN" ] || { p 0 "拿不到 SSW_INTERNAL_TOKEN(kubectl configmap ssw-tds-env)"; exit 1; } +ENVREP=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/EnvReport" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' -d "$(cat <&1) +printf '%s' "$ENVREP" | grep -q '"code":200' && p 1 "环境申报成功" || p 0 "环境申报失败: $(printf '%s' "$ENVREP" | head -c 250)" + +echo "=== 6. 设备证书签发(cert_type=02,绑定已登记公钥) ===" +CERTS=$(curl -s -m 25 -X GET "$API/api/ssw/tds/Cert/All" -H "$H" 2>&1) +CERT_ID=$(printf '%s' "$CERTS" | python3 -c " +import sys,json +try: d=json.load(sys.stdin) +except Exception: print(''); raise SystemExit +data=d.get('data') or [] +if isinstance(data,dict): data=data.get('list') or [] +for c in data: + if str(c.get('certType'))=='2' and c.get('status')=='02': + print(c.get('certId') or c.get('id') or ''); break +" 2>/dev/null) +[ -n "$CERT_ID" ] && p 1 "设备证书就绪 certId=$CERT_ID" || p 0 "无可用设备证书(cert_type=02, status=02)" + +echo "=== 7. 运维字段(deploymentStatus=READY + endpoint) ===" +# 🔴 /Internal/Ops **只放行 endpoint 与 deploymentStatus** 两个字段,其余一律丢弃。 +OPS=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Internal/Ops" \ + -H "X-Internal-Token: $INT_TOKEN" -H 'Content-Type: application/json' -d "$(cat <&1) +printf '%s' "$OPS" | grep -q '"code":200' && p 1 "deploymentStatus=READY" || p 0 "运维字段设置失败: $(printf '%s' "$OPS" | head -c 250)" + +echo +echo "=== 设备侧启动参数(把这段交给设备执行) ===" +cat </dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' +') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' +' +} + +echo "=== 1. admin 登录 ===" +ENCPW=$(enc_pwd "123456") +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] && p 1 "登录成功" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 200)"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 创建主体(企业) ===" +# 🔴 运营建档(SOURCE_ADMIN)的企业主体必填项,照 SubjectServiceImpl.prepareForSave: +# subjectName / creditCode / enterpriseType(0-4) / operatingPeriodBegin / operatingPeriodEnd +# / authType(0-3) / legalPerson +SUBJ=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Subject" -H "$H" -H 'Content-Type: application/json' -d '{ + "subjectCode":"WUGUIRONG-ORG", + "subjectName":"乌桂荣数据主体", + "subjectKind":"ORG", + "creditCode":"91330100MA2XXXXX1X", + "enterpriseType":"1", + "operatingPeriodBegin":"2020-01-01", + "operatingPeriodEnd":"2035-12-31", + "authType":"3", + "legalPerson":"乌桂荣", + "contactName":"乌桂荣", + "contactPhone":"13800000000", + "email":"wuguirong@example.com", + "registerType":"ORG", + "spaceId":"PORTAL-DEMO-SPACE" +}') +SID=$(printf '%s' "$SUBJ" | sed -n 's/.*"data":"\([^"]*\)".*/\1/p') +if [ -n "$SID" ]; then + p 1 "主体已创建 subjectId=$SID" +else + # 幂等:已存在则查回来 + LIST=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Subject?pageIndex=1&pageSize=50" 2>&1) + SID=$(printf '%s' "$LIST" | grep -o '"subjectId":"[^"]*"' | head -1 | sed 's/.*:"//;s/"//') + [ -n "$SID" ] && p 1 "主体已存在,复用 subjectId=$SID" || p 0 "主体创建失败: $(printf '%s' "$SUBJ" | head -c 250)" +fi + +echo "=== 3. 查空间 ===" +SPACES=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Space/Internal/List" 2>&1) +echo " $(printf '%s' "$SPACES" | head -c 300)" +SPACE_ID=$(printf '%s' "$SPACES" | grep -oE '"id":"[^"]*"' | head -1 | sed 's/.*:"//;s/"//') +[ -z "$SPACE_ID" ] && SPACE_ID="PORTAL-DEMO-SPACE" +echo " spaceId=$SPACE_ID" + +echo "=== 4. 取连接器身份密钥 ===" +# TDC 首次启动打印一次性 secretKey;这里从容器日志里取(已保存到本地) +IDKEY=$(cat .tdc-identity-secret 2>/dev/null) +if [ -z "$IDKEY" ]; then + IDKEY=$(kubectl -n wuguirong logs deploy/tdc-connector 2>/dev/null | grep -oE 'secretKey = [0-9a-f]{64}' | head -1 | awk '{print $3}') + [ -n "$IDKEY" ] && echo "$IDKEY" > .tdc-identity-secret +fi +[ -n "$IDKEY" ] && p 1 "身份密钥已取到(前 8 位 ${IDKEY:0:8}…)" || p 0 "取不到身份密钥" + +echo "=== 5. 注册连接器到 TDS(内部通道) ===" +ITOK=$(kubectl -n wuguirong get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}') +# 🔴 TDS 的 publicKey 口径 = **EC SPKI DER 的 Base64**(CertSigner.publicKeyFromBase64 用 +# X509EncodedKeySpec 解析)⇒ 必须是 P-256 的 SPKI,不是裸点。 +# 密钥对持久化在 build/tdc-conn-key/ :私钥随连接器走,公私钥必须一致。 +KEYDIR="$(dirname "$0")/tdc-conn-key" +if [ ! -f "$KEYDIR/pub.b64" ] || [ ! -f "$KEYDIR/ec.key" ]; then + mkdir -p "$KEYDIR"; chmod 700 "$KEYDIR" + openssl ecparam -name prime256v1 -genkey -noout -out "$KEYDIR/ec.key" + openssl ec -in "$KEYDIR/ec.key" -pubout -outform DER -out "$KEYDIR/pub.der" + base64 < "$KEYDIR/pub.der" | tr -d '\n' > "$KEYDIR/pub.b64" + chmod 600 "$KEYDIR/ec.key" +fi +PK=$(cat "$KEYDIR/pub.b64") +echo " publicKey(${#PK} 字符) = ${PK:0:40}..." + +REG=$(curl -s -m 25 -X POST "$API/api/ssw/tds/Connector/Register" \ + -H "X-Internal-Token: $ITOK" -H 'Content-Type: application/json' -d "{ + \"connectorCode\":\"TDC-WUGUIRONG-01\", + \"name\":\"乌桂荣连接器\", + \"spaceId\":\"${SPACE_ID}\", + \"subjectId\":\"${SID}\", + \"subjectName\":\"乌桂荣数据主体\", + \"publicKey\":\"${PK}\", + \"identityCode\":\"TDC-WUGUIRONG-01\", + \"secretKey\":\"${IDKEY}\" +}") +printf '%s' "$REG" | grep -q '"code":200' \ + && p 1 "注册成功: $(printf '%s' "$REG" | head -c 120)" \ + || p 0 "注册失败: $(printf '%s' "$REG" | head -c 300)" + +echo "=== 6. 校验连接器列表 ===" +CL=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector/My" 2>&1) +printf '%s' "$CL" | head -c 300; echo + +echo +echo "======== 通过 $ok / 失败 $bad ========" +[ "$bad" -eq 0 ] diff --git a/build/sign-ecdsa.py b/build/sign-ecdsa.py new file mode 100644 index 0000000..d3763a9 --- /dev/null +++ b/build/sign-ecdsa.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""SHA256withECDSA 签名器(等价 Java Signature.getInstance("SHA256withECDSA"))。 + +用途:TDS 连接器心跳签名。 + +🔴 为什么不用 openssl CLI:本机 OpenSSL 4.0.3 组合有问题 + - `openssl dgst -sha256 -sign … -outform DER` → "Multiple digest or unknown options" + - `openssl pkeyutl -sign`(不带 digest)→ 直接签原文,语义是"原始 ECDSA", + 与 Java 的"先 SHA-256 摘要再 ECDSA"不同,验签必挂 + - `openssl pkeyutl -sign -pkeyopt digest:sha256` → provider signature failure + Python `cryptography` 走 OpenSSL 3.x API,语义与 Java 完全一致, + 且 ECDSA 签名原生就是 DER 编码(Java 侧也是取 DER 字节再 Base64)。 + +用法: + python3 sign-ecdsa.py <私钥.pem> # stdin 读签名原文,stdout 出 Base64(DER) + python3 sign-ecdsa.py <私钥.pem> --file F # 从文件读原文 + python3 sign-ecdsa.py <私钥.pem> --hex # 输出 hex(DER) +""" +import base64 +import sys + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + + +def sign(key_path: str, data: bytes) -> bytes: + with open(key_path, "rb") as fh: + key = serialization.load_pem_private_key(fh.read(), password=None) + if not isinstance(key, ec.EllipticCurvePrivateKey): + raise SystemExit(f"不是 EC 私钥: {type(key).__name__}") + # ECDSA(Prehashed 前的等价): 先 SHA-256 摘要, 再 ECDSA 签名 → DER 编码 + return key.sign(data, ec.ECDSA(hashes.SHA256())) + + +def main() -> int: + args = sys.argv[1:] + if not args: + print(__doc__, file=sys.stderr) + return 2 + key_path = args[0] + rest = args[1:] + + if "--file" in rest: + path = rest[rest.index("--file") + 1] + with open(path, "rb") as fh: + data = fh.read() + else: + data = sys.stdin.buffer.read() + + der = sign(key_path, data) + if "--hex" in rest: + print(der.hex()) + else: + print(base64.b64encode(der).decode("ascii")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/build/sysroot-armhf/include/zconf.h b/build/sysroot-armhf/include/zconf.h new file mode 100644 index 0000000..622afa0 --- /dev/null +++ b/build/sysroot-armhf/include/zconf.h @@ -0,0 +1,547 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_combine_gen z_crc32_combine_gen +# define crc32_combine_gen64 z_crc32_combine_gen64 +# define crc32_combine_op z_crc32_combine_op +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#ifndef Z_HAVE_UNISTD_H +# ifdef __WATCOMC__ +# define Z_HAVE_UNISTD_H +# endif +#endif +#ifndef Z_HAVE_UNISTD_H +# if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32) +# define Z_HAVE_UNISTD_H +# endif +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/build/sysroot-armhf/include/zlib.h b/build/sysroot-armhf/include/zlib.h new file mode 100644 index 0000000..953cb50 --- /dev/null +++ b/build/sysroot-armhf/include/zlib.h @@ -0,0 +1,1935 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.13, October 13th, 2022 + + Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.13" +#define ZLIB_VERNUM 0x12d0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 13 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more output + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields zalloc, zfree and opaque must be initialized before by the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if there have been any deflate() calls since the + state was initialized or reset, then the input available so far is + compressed with the old level and strategy using deflate(strm, Z_BLOCK). + There are three approaches for the compression levels 0, 1..3, and 4..9 + respectively. The new level and strategy will take effect at the next call + of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will *not* automatically decode concatenated gzip members. + inflate() will return Z_STREAM_END at the end of the gzip member. The state + would need to be reset to continue decoding a subsequent gzip member. This + *must* be done if there is more data after a gzip member, in order for the + decompression to be compliant with the gzip standard (RFC 1952). + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Open the gzip (.gz) file at path for reading and decompressing, or + compressing and writing. The mode parameter is as in fopen ("rb" or "wb") + but can also include a compression level ("wb9") or a strategy: 'f' for + filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", + 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression + as in "wb9F". (See the description of deflateInit2 for more information + about the strategy parameter.) 'T' will request transparent writing or + appending with no compression and not using the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + Associate a gzFile with the file descriptor fd. File descriptors are + obtained from calls like open, dup, creat, pipe or fileno (if the file has + been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions for file to + size. The default buffer size is 8192 bytes. This function must be called + after gzopen() or gzdopen(), and before any other calls that read or write + the file. The buffer memory allocation is always deferred to the first read + or write. Three times that size in buffer space is allocated. A larger + buffer size of, for example, 64K or 128K bytes will noticeably increase the + speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level and strategy for file. See the + description of deflateInit2 for the meaning of these parameters. Previously + provided data is flushed before applying the parameter changes. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Read and decompress up to len uncompressed bytes from file into buf. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read and decompress up to nitems items of size size from file into buf, + otherwise operating as gzread() does. This duplicates the interface of + stdio's fread(), with size_t request and return types. If the library + defines size_t, then z_size_t is identical to size_t. If not, then z_size_t + is an unsigned integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevertheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, resetting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); +/* + Compress and write the len uncompressed bytes at buf to file. gzwrite + returns the number of uncompressed bytes written or 0 in case of error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + Compress and write nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Convert, format, compress, and write the arguments (...) to file under + control of the string format, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf(), + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Compress and write the given null-terminated string s to file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Read and decompress bytes from file into buf, until len-1 characters are + read, or until a newline character is read and transferred to buf, or an + end-of-file condition is encountered. If any characters are read or if len + is one, the string is terminated with a null character. If no characters + are read due to an end-of-file or len is less than one, then the buffer is + left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Compress and write c, converted to an unsigned char, into file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Read and decompress one byte from file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push c back onto the stream for file to be read as the first character on + the next read. At least one character of push-back is always allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flush all pending output to file. The parameter flush is as in the + deflate() function. The return value is the zlib error number (see function + gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Set the starting position to offset relative to whence for the next gzread + or gzwrite on file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewind file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET). +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Return the starting position for the next gzread or gzwrite on file. + This position represents a number of bytes in the uncompressed data stream, + and is zero when starting, even if appending or reading a gzip stream from + the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Return the current compressed (actual) read or write offset of file. This + offset includes the count of bytes that precede the gzip stream, for example + when appending or when using gzdopen() for reading. When reading, the + offset does not include as yet unused buffered input. This information can + be used for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Return true (1) if the end-of-file indicator for file has been set while + reading, false (0) otherwise. Note that the end-of-file indicator is set + only if the read tried to go past the end of the input, but came up short. + Therefore, just like feof(), gzeof() may return false even if there is no + more data to read, in the event that the last read request was for the exact + number of bytes remaining in the input file. This will happen if the input + file size is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Return true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flush all pending output for file, if necessary, close file and + deallocate the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Return the error message for the last error which occurred on file. + errnum is set to zlib error number. If an error occurred in the file system + and not in the compression library, errnum is set to Z_ERRNO and the + application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clear the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. An Adler-32 value is in the range of a 32-bit + unsigned integer. If buf is Z_NULL, this function returns the required + initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. + If buf is Z_NULL, this function returns the required initial value for the + crc. Pre- and post-conditioning (one's complement) is performed within this + function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t len2)); + + Return the operator corresponding to length len2, to be used with + crc32_combine_op(). +*/ + +ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); +/* + Give the same result as crc32_combine(), using op in place of len2. op is + is generated from len2 by crc32_combine_gen(). This will be faster than + crc32_combine() if the generated op is used more than once. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# define z_crc32_combine_gen z_crc32_combine_gen64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# define crc32_combine_gen crc32_combine_gen64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/build/sysroot-armhf/lib/libz.so b/build/sysroot-armhf/lib/libz.so new file mode 120000 index 0000000..35fdc8b --- /dev/null +++ b/build/sysroot-armhf/lib/libz.so @@ -0,0 +1 @@ +libz.so.1 \ No newline at end of file diff --git a/build/sysroot-armhf/lib/libz.so.1 b/build/sysroot-armhf/lib/libz.so.1 new file mode 100644 index 0000000..7064e8e Binary files /dev/null and b/build/sysroot-armhf/lib/libz.so.1 differ diff --git a/build/verify-3party-topology.sh b/build/verify-3party-topology.sh new file mode 100644 index 0000000..2414082 --- /dev/null +++ b/build/verify-3party-topology.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# verify-3party-topology.sh —— 三方(AMD 真机 + 海光沙箱 + ZYNQ 沙箱)拓扑全链路验收 +# +# 验收口径(每条都有可复核的接口/字段证据): +# L1 安全卡 → TDS 侧设备连接器 ONLINE(approvalStatus=02 / complianceStatus=01 / +# deploymentStatus=READY / certPem 非空 / 心跳 TTL 内) +# L2 设备侧业务连接器 → tdc_identity.f_tds_connector_id 指向 L1 的 connectorId +# L3 出向业务 → 该连接器能经 TDS 内部通道取到服务目录(空间绑定生效) +# L4 产品可见 → 目录里能看到以本连接器为 provider 的数据产品 +# L5 本地库 → tdc-connector 自带 pglite 库已建表且 health=UP +# +# 用法: bash build/verify-3party-topology.sh +set -uo pipefail +# 🔴 记住 build/ 的绝对路径 —— 脚本开头会 cd 到仓库根,下面要靠它找 cube_exec.py +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$(dirname "$SCRIPT_DIR")" + +API="${TDS_API:-http://192.168.1.26:30201}" +CIPHER_KEY="EY8WePvjM5GGwQzn" +INT_TOKEN="${SSW_INTERNAL_TOKEN:-$(KUBECONFIG="${KUBECONFIG:-$HOME/.kube/kubeconfig-wuguirong}" kubectl -n wuguirong get configmap ssw-tds-env -o jsonpath='{.data.SSW_INTERNAL_TOKEN}' 2>/dev/null)}" +TDC_TOKEN="caaa9043f72f04df887361f81dc1026817bd9ee0b7299689" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +enc_pwd() { + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q); dh=$(printf '%s' "$1" | md5 -q) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' \n') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' \n' +} + +LOGIN=$(curl -s -m 25 -X POST "$API/api/oauth/Login" -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=admin" --data-urlencode "password=$(enc_pwd 123456)" \ + --data-urlencode "grant_type=password") +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ -n "$TOKEN" ] || { echo "❌ TDS admin 登录失败"; exit 1; } +H="Authorization: $TOKEN" + +# 三方清单:| 名称 | TDS connectorId | tdc 基地址 | tdc localIdentityId | 沙箱ID | +# tdc 基地址为空 ⇒ 该节点的 L2/L3/L5 走 cube_exec 进沙箱里验 +NODES=( + "AMD真机|890673836930892229|http://192.168.1.7:30000|796640692142080|" + "海光沙箱|890677001784918469||796640904556544|86f89b9046304efd87a3e63f501bca78" + "ZYNQ沙箱|890677038657044933||796641118785536|999a5c7c48e94e56a4dd1e7c3b1598c3" +) + +echo "════════════════ 三方可信数据空间拓扑验收 ════════════════" +echo +echo "【TDS 侧连接器总览】" +curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector?pageIndex=1&pageSize=200" 2>&1 | python3 -c " +import sys, json +d = json.load(sys.stdin).get('data') or {} +rows = d.get('list') or [] +for c in rows: + print(' %-22s %-20s %-8s appr=%s comp=%s deploy=%-10s env=%-14s cert=%s' % ( + c.get('connectorCode'), c.get('id'), c.get('status'), + c.get('approvalStatus'), c.get('complianceStatus'), + c.get('deploymentStatus'), c.get('envStatus'), c.get('certSn'))) +" 2>/dev/null +echo + +for row in "${NODES[@]}"; do + IFS='|' read -r NAME CID BASE LID SB <<< "$row" + echo "──────── $NAME ────────" + + # ---- L1 安全卡侧四闸门 ---- + DET=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/Connector/$CID" 2>&1) + printf '%s' "$DET" | python3 -c " +import sys, json +c = (json.load(sys.stdin).get('data') or {}) +gates = [ + ('L1.1 approvalStatus=02', c.get('approvalStatus') == '02'), + ('L1.2 complianceStatus=01', c.get('complianceStatus') == '01'), + ('L1.3 deploymentStatus∈{READY,UNMANAGED}', c.get('deploymentStatus') in ('READY','UNMANAGED')), + ('L1.4 设备证书已回写', bool(c.get('certPem'))), + ('L1.5 status=ONLINE', c.get('status') == 'ONLINE'), +] +for n, ok in gates: + print((' ✅ ' if ok else ' ❌ ') + n) +print(' envStatus=%s certSn=%s' % (c.get('envStatus'), c.get('certSn'))) +" 2>/dev/null + # 上面是 python 内的判定,这里只做计数:用 jq 风格再跑一遍计数 + CNT=$(printf '%s' "$DET" | python3 -c " +import sys, json +c = (json.load(sys.stdin).get('data') or {}) +n = sum([c.get('approvalStatus')=='02', c.get('complianceStatus')=='01', + c.get('deploymentStatus') in ('READY','UNMANAGED'), bool(c.get('certPem')), + c.get('status')=='ONLINE']) +print(n) +" 2>/dev/null) + [ "${CNT:-0}" -ge 5 ] && p 1 "L1 安全卡侧四闸门全绿(${CNT}/5)" || p 0 "L1 安全卡侧四闸门(${CNT}/5)" + + # ---- L4 该连接器名下的数据产品 ---- + PROD=$(curl -s -m 20 -H "$H" "$API/api/ssw/tds/DataProduct?pageIndex=1&pageSize=200" 2>&1 | python3 -c " +import sys, json +d = json.load(sys.stdin).get('data') or {} +rows = d.get('list') or [] +for p_ in rows: + # 🔴 只认真正上架的:status=ONLINE 且 auditStatus=PASS + # (DESTROYED 的历史产品 providerConnectorId 也可能命中,会造成假绿) + if str(p_.get('providerConnectorId')) == '$CID' and p_.get('status') == 'ONLINE' and p_.get('auditStatus') == 'PASS': + print('%s|%s|%s' % (p_.get('productCode'), p_.get('status'), p_.get('auditStatus'))) +" 2>/dev/null) + if [ -n "$PROD" ]; then + p 1 "L4 数据产品已上架:$(printf '%s' "$PROD" | tr '\n' ' ')" + else + p 0 "L4 该连接器名下无数据产品" + fi + + # ---- L2/L3/L5 设备侧业务连接器 ---- + if [ -n "$BASE" ]; then + HEALTH=$(curl -s -m 12 "$BASE/api/health" 2>&1) + if printf '%s' "$HEALTH" | grep -q '"status":"UP"'; then + p 1 "L5 本地 pglite 库就绪(tables=$(printf '%s' "$HEALTH" | sed -n 's/.*"tables":\([0-9]*\).*/\1/p'))" + else + p 0 "L5 本地库未就绪: $(printf '%s' "$HEALTH" | head -c 120)" + fi + + IDENT=$(curl -s -m 12 -H "X-Internal-Token: $TDC_TOKEN" "$BASE/api/ssw/tdc/Identity/$LID" 2>&1) + GOT=$(printf '%s' "$IDENT" | python3 -c " +import sys, json +print((json.load(sys.stdin).get('data') or {}).get('tdsConnectorId') or '') +" 2>/dev/null) + # 🔴 bash 变量后紧跟中文必须加 `${}`,否则中文被并入变量名 ⇒ set -u 下 unbound 且报错乱码 + if [ "$GOT" = "$CID" ]; then + p 1 "L2 业务连接器已绑定该设备连接器(tdsConnectorId=${GOT})" + else + p 0 "L2 绑定不符:期望 ${CID},实际 ${GOT:-<空>}" + fi + + CAT=$(curl -s -m 20 -H "X-Internal-Token: $TDC_TOKEN" "$BASE/api/ssw/tdc/ServiceCatalog" 2>&1) + if printf '%s' "$CAT" | grep -q '"code":200'; then + p 1 "L3 出向 TDS 内部通道可用(服务目录 code=200)" + else + p 0 "L3 出向 TDS 失败: $(printf '%s' "$CAT" | head -c 150)" + fi + elif [ -n "$SB" ]; then + # 沙箱节点:进沙箱里用 127.0.0.1 验(沙箱内网出口已放行 192.168.1.0/24) + OUT=$(cd "$SCRIPT_DIR" && python3 cube_exec.py "$SB" \ + "sh /tmp/verify-node.sh $LID $CID" 2>&1 | grep -v Warning) + HB=$(printf '%s' "$OUT" | sed -n 's/^HEALTH_TABLES=\([0-9]*\).*/\1/p') + GB=$(printf '%s' "$OUT" | sed -n 's/^GOT_CID=//p') + CC=$(printf '%s' "$OUT" | sed -n 's/^CAT_CODE=\([0-9]*\).*/\1/p') + [ -n "$HB" ] && p 1 "L5 本地 pglite 库就绪(tables=${HB})" || p 0 "L5 本地库未就绪" + if [ "$GB" = "$CID" ]; then + p 1 "L2 业务连接器已绑定该设备连接器(tdsConnectorId=${GB})" + else + p 0 "L2 绑定不符:期望 ${CID},实际 ${GB:-<空>}" + fi + [ "$CC" = "200" ] && p 1 "L3 出向 TDS 内部通道可用(服务目录 code=200)" || p 0 "L3 出向 TDS 失败(code=${CC:-无})" + fi + echo +done + +echo "════════════════ 通过 $ok / 失败 $bad ════════════════" +[ "$bad" = "0" ] diff --git a/build/verify-mpc.sh b/build/verify-mpc.sh new file mode 100644 index 0000000..c342a38 --- /dev/null +++ b/build/verify-mpc.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# MPC 编排(ssw-mpc-flow)接口验收:登录 + 设备同步(真源=控制面 /nodes) +# +# 用法: bash build/verify-mpc.sh [BASE] +set -uo pipefail + +BASE="${1:-http://192.168.1.26:30203}" +ACCOUNT="${MPC_ACCOUNT:-admin}" +PASSWORD="${MPC_PASSWORD:-123456}" +CIPHER_KEY="EY8WePvjM5GGwQzn" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +enc_pwd() { + # 🔴 JNPF / 编排同款(已在 node/CryptoJS 与 openssl 双向校验): + # key = md5(CIPHER_KEY) 的十六进制串的 **ASCII 字节**(32B)→ openssl -K 吃它的 hex + # data = md5(明文) 的十六进制串的 **ASCII 字节**(32B)→ 直接喂给 openssl 的 stdin + # AES-256-ECB-PKCS7 → hex 输出 + # 🔴 data **不能再 hex 化一次**(那是把 32 个 ASCII 字节变成 64 个字节,错)。 + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' +') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' +' +} + +echo "=== 1. 编排登录 ($BASE) ===" +ENCPW=$(enc_pwd "$PASSWORD") +LOGIN=$(curl -s -m 25 -X POST "$BASE/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=$ACCOUNT" --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password" 2>&1) +echo " raw: $(printf '%s' "$LOGIN" | head -c 160)" +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +if [ -z "$TOKEN" ]; then + # 编排可能是明文口令通道 + LOGIN2=$(curl -s -m 25 -X POST "$BASE/api/oauth/Login" -H 'Content-Type: application/json' \ + -d "{\"account\":\"$ACCOUNT\",\"password\":\"$PASSWORD\",\"grant_type\":\"password\"}" 2>&1) + echo " json 直送: $(printf '%s' "$LOGIN2" | head -c 160)" + TOKEN=$(printf '%s' "$LOGIN2" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +fi +[ -n "$TOKEN" ] && p 1 "登录成功 token=${TOKEN:0:24}…" || { p 0 "登录失败"; exit 1; } +H="Authorization: $TOKEN" + +echo "=== 2. 同步真机设备(真源 = 控制面 /nodes)===" +SYNC=$(curl -s -m 90 -X POST "$BASE/api/ssw/sswdevice/Device/Sync" -H "$H" 2>&1) +echo " $(printf '%s' "$SYNC" | head -c 400)" +printf '%s' "$SYNC" | grep -q '"code":200' && p 1 "同步接口返回 200" || p 0 "同步失败" +printf '%s' "$SYNC" | grep -q 'control-plane' && p 1 "真源 = control-plane(非 mock)" || p 0 "真源不是 control-plane" + +echo "=== 3. 设备列表 ===" +LIST=$(curl -s -m 30 -H "$H" "$BASE/api/ssw/sswdevice/Device/List" 2>&1) +echo " $(printf '%s' "$LIST" | head -c 700)" + +echo "=== 4. 链上存证列表 ===" +CHAIN=$(curl -s -m 30 -H "$H" "$BASE/api/ssw/sswchain/ChainBlock/List" 2>&1) +echo " $(printf '%s' "$CHAIN" | head -c 400)" + +echo "=== 5. 编排流程列表 ===" +FLOW=$(curl -s -m 30 -H "$H" "$BASE/api/ssw/sswflow/Flow/List" 2>&1) +echo " $(printf '%s' "$FLOW" | head -c 400)" + +echo +echo "======== 通过 $ok / 失败 $bad ========" +[ "$bad" -eq 0 ] diff --git a/build/verify-node.sh b/build/verify-node.sh new file mode 100644 index 0000000..606ddb4 --- /dev/null +++ b/build/verify-node.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# 沙箱内节点自检(由 verify-3party-topology.sh 通过 cube_exec 调用) +# 用法: verify-node.sh +LOCAL_ID="$1" +EXPECT_CID="$2" +INT_TOKEN="caaa9043f72f04df887361f81dc1026817bd9ee0b7299689" + +# L5:本地 pglite 库 +HEALTH=$(curl -s -m 12 http://127.0.0.1:30000/api/health 2>&1) +TABLES=$(printf '%s' "$HEALTH" | sed -n 's/.*"tables":\([0-9]*\).*/\1/p') +echo "HEALTH_TABLES=${TABLES}" +echo "HEALTH_RAW=${HEALTH}" + +# L2:绑定回读 +IDENT=$(curl -s -m 12 -H "X-Internal-Token: ${INT_TOKEN}" \ + "http://127.0.0.1:30000/api/ssw/tdc/Identity/${LOCAL_ID}" 2>&1) +GOT=$(printf '%s' "$IDENT" | python3 -c " +import sys, json +try: + print((json.load(sys.stdin).get('data') or {}).get('tdsConnectorId') or '') +except Exception: + print('') +" 2>/dev/null) +echo "GOT_CID=${GOT}" + +# L3:出向 TDS 内部通道 +CAT=$(curl -s -m 20 -H "X-Internal-Token: ${INT_TOKEN}" \ + "http://127.0.0.1:30000/api/ssw/tdc/ServiceCatalog" 2>&1) +CODE=$(printf '%s' "$CAT" | sed -n 's/^{"code":\([0-9]*\).*/\1/p') +echo "CAT_CODE=${CODE}" +echo "CAT_HEAD=$(printf '%s' "$CAT" | head -c 200)" diff --git a/build/verify-real-machine-3party.sh b/build/verify-real-machine-3party.sh new file mode 100644 index 0000000..f346ea2 --- /dev/null +++ b/build/verify-real-machine-3party.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# 三方真机(AMD SEV-SNP × 海光 CSV × ZYNQ armv7)跨机密态 PSI + 纵向 LR 实测。 +# +# 用法: bash build/verify-real-machine-3party.sh [psi|lr|all] +# +# 🔴 纪律(照 ssw-mpc-flow/docs/e2e/real-machine-verification.md §4A,不猜): +# - 三方都用 --listen + --peers 网状连接;--connect 只支持两方。 +# - party 编号 = 站点名字典序(alice=0/bob=1/carol=2);小编号主动连大编号 +# ⇒ 启动顺序必须 carol → bob → alice,否则 connect_retry 空等 300s。 +# - --peers 必须含全部站点(含本方格,本方被 connect_any 跳过);密态第二通道 +# 由 bump_peers 自动 +1(PSI 9449 / 密态 9450),脚本不要手动改端口。 +# - --seed / MPC_PSK 必须三方同一份,否则 PSI 交集必空。 +# - --col-blocks 与 --sites 一一对应且铺满 0..d_total;只有 label-owner 能给 --data-y。 +# - zynq 是 BusyBox:无 setsid ⇒ 用 nohup … &;无 base64 ⇒ 用 tar.gz 管道传物料。 +# - 凭据只走 xop 键名,脚本内不出现明文口令。 +set -uo pipefail + +PHASE="${1:-all}" +D=/tmp/mpc-real +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +EVIDENCE_DIR="$SCRIPT_DIR/../evidence" +mkdir -p "$EVIDENCE_DIR" + +[ -f "$D/meta3.json" ] || { echo "缺真值 $D/meta3.json(先跑 gen-lr3.py)" >&2; exit 1; } +TRUTH=$(python3 -c 'import json;print(json.load(open("/tmp/mpc-real/meta3.json"))["rows"]["intersection_abc"])') +echo "本地真值 A∩B∩C = $TRUTH" + +# ---------- 生成远端会话脚本(三方通用,按 uname -m 选二进制) ---------- +cat > "$D/remote3.sh" <<'REMOTE' +#!/bin/sh +# 在真机本地执行:$1=site $2=psi|lr +set -u +D=/tmp/mpc-real +cd "$D" || exit 1 +SITE="${1:?site}" +OP="${2:?psi|lr}" +SEED=$(cat sess-master.txt) +export MPC_PSK=$(cat sess-auth.txt) +S=alice,bob,carol +P=alice=192.168.1.7:9449,bob=192.168.1.102:9449,carol=192.168.1.233:9449 +case "$(uname -m)" in + armv7l) BIN=/usr/local/bin/mpc ;; + *) if [ "$SITE" = alice ]; then BIN=/tmp/mpc-tee-run-attestpair/mpc-host; else BIN=/tmp/mpc-cluster/mpc; fi ;; +esac +IDS=$(cat "$SITE.ids") +if [ "$OP" = psi ]; then + exec "$BIN" psi --site "$SITE" --sites "$S" --ids "$IDS" --seed "$SEED" \ + --listen 0.0.0.0:9449 --peers "$P" --report json +fi +X=$(cat "$SITE.x") +if [ "$SITE" = alice ]; then + exec "$BIN" lr-vertical --site "$SITE" --sites "$S" \ + --col-blocks alice:0:1,bob:1:1,carol:2:1 \ + --data-ids "$IDS" --data-x "$X" --data-y "$(cat alice.y)" \ + --label-owner alice --epochs 20 --lr 0.05 --seed "$SEED" \ + --listen 0.0.0.0:9449 --peers "$P" --report json +fi +exec "$BIN" lr-vertical --site "$SITE" --sites "$S" \ + --col-blocks alice:0:1,bob:1:1,carol:2:1 \ + --data-ids "$IDS" --data-x "$X" \ + --label-owner alice --epochs 20 --lr 0.05 --seed "$SEED" \ + --listen 0.0.0.0:9449 --peers "$P" --report json +REMOTE +chmod +x "$D/remote3.sh" + +tar czf "$D/payload3.tgz" -C "$D" \ + alice.ids alice.x alice.y bob.ids bob.x carol.ids carol.x \ + sess-master.txt sess-auth.txt remote3.sh meta3.json +echo "payload: $(wc -c < "$D/payload3.tgz" | tr -d ' ') B" + +run_phase() { + local OP="$1" + echo "=================== 三方 $OP 实测 ===================" + xop run \ + --secret "AMD_USER=tee_amd_7_user" --secret "AMD_PASS=tee_amd_7_pass" \ + --secret "HG_USER=tee_hg_102_user" --secret "HG_PASS=tee_hg_102_pass" \ + --secret "ZY_USER=tee_zynq_user" --secret "ZY_PASS=tee_zynq_pass" \ + -- bash -c ' +OP="$1"; P=/tmp/mpc-real/payload3.tgz +SSHX="-o StrictHostKeyChecking=no -o PubkeyAuthentication=no -o ConnectTimeout=20" +AMD() { SSHPASS="$AMD_PASS" sshpass -e ssh $SSHX -l "$AMD_USER" 192.168.1.7 "$@"; } +HG() { SSHPASS="$HG_PASS" sshpass -e ssh $SSHX -l "$HG_USER" 192.168.1.102 "$@"; } +ZY() { SSHPASS="$ZY_PASS" sshpass -e ssh $SSHX -l "$ZY_USER" 192.168.1.233 "$@"; } + +# 1) 物料分发(tar.gz 管道,三台同口径;zynq 无 base64 也能收) +for R in AMD HG ZY; do + $R "mkdir -p /tmp/mpc-real && rm -f /tmp/mpc-real/$OP-*.log && tar xzf - -C /tmp/mpc-real" < "$P" 2>/dev/null \ + && echo "[$R] payload ok" || echo "[$R] payload FAIL" +done +ZY "chmod +x /tmp/mpc-real/remote3.sh" 2>/dev/null +AMD "chmod +x /tmp/mpc-real/remote3.sh" 2>/dev/null +HG "chmod +x /tmp/mpc-real/remote3.sh" 2>/dev/null + +# 2) 清旧会话(只杀算子进程,不碰 hostd / KBS) +AMD "pkill -f \"mpc-host $OP\" 2>/dev/null; pkill -f \"mpc-host lr-vertical\" 2>/dev/null; true" 2>/dev/null +HG "pkill -f \"mpc $OP\" 2>/dev/null; pkill -f \"mpc lr-vertical\" 2>/dev/null; true" 2>/dev/null +ZY "pkill -f \"mpc psi\" 2>/dev/null; pkill -f \"mpc lr-vertical\" 2>/dev/null; true" 2>/dev/null +sleep 2 + +# 3) 点火:carol → bob → alice(大编号先 listen) +ZY "cd /tmp/mpc-real && nohup ./remote3.sh carol $OP > $OP-carol.log 2>&1 < /dev/null & echo FIRED-CAROL" 2>/dev/null +sleep 3 +HG "cd /tmp/mpc-real && setsid --fork ./remote3.sh bob $OP > $OP-bob.log 2>&1 < /dev/null; echo FIRED-BOB" 2>/dev/null +sleep 3 +AMD "cd /tmp/mpc-real && setsid --fork ./remote3.sh alice $OP > $OP-alice.log 2>&1 < /dev/null; echo FIRED-ALICE" 2>/dev/null + +# 4) 轮询三份日志出结果 +PAT="交集"; [ "$OP" = lr ] && PAT="训练权重" +for i in $(seq 1 90); do + sleep 2 + A=$(AMD "grep -c \"$PAT\" /tmp/mpc-real/$OP-alice.log 2>/dev/null || echo 0" 2>/dev/null | tr -d "\r" | tail -1) + B=$(HG "grep -c \"$PAT\" /tmp/mpc-real/$OP-bob.log 2>/dev/null || echo 0" 2>/dev/null | tr -d "\r" | tail -1) + C=$(ZY "grep -c \"$PAT\" /tmp/mpc-real/$OP-carol.log 2>/dev/null || echo 0" 2>/dev/null | tr -d "\r" | tail -1) + [ "${A:-0}" != "0" ] && [ "${B:-0}" != "0" ] && [ "${C:-0}" != "0" ] && { echo "三方均出结果 (${i}x2s)"; break; } + [ "$i" -eq 90 ] && echo "TIMEOUT a=$A b=$B c=$C" +done + +# 5) 回收日志 +for S in alice bob carol; do + echo "----- $OP/$S -----" + case "$S" in + alice) AMD "cat /tmp/mpc-real/$OP-alice.log 2>&1 | tail -25" 2>/dev/null ;; + bob) HG "cat /tmp/mpc-real/$OP-bob.log 2>&1 | tail -25" 2>/dev/null ;; + carol) ZY "cat /tmp/mpc-real/$OP-carol.log 2>&1 | tail -25" 2>/dev/null ;; + esac +done +' _ "$OP" < /dev/null 2>&1 | grep -vE "WARN (Network|File)Guard|xop禁止将密钥泄漏" +} + +if [ "$PHASE" = "all" ] || [ "$PHASE" = "psi" ]; then + run_phase psi > "$EVIDENCE_DIR/real-psi-3party.log" 2>&1 + echo "--- PSI 结果摘要 ---" + grep -E "交集|payload ok|FIRED|三方均出结果|TIMEOUT|ERROR|error" "$EVIDENCE_DIR/real-psi-3party.log" | tail -25 +fi + +if [ "$PHASE" = "all" ] || [ "$PHASE" = "lr" ]; then + run_phase lr > "$EVIDENCE_DIR/real-lr-3party.log" 2>&1 + echo "--- LR 结果摘要 ---" + grep -E "训练权重|权重|payload ok|FIRED|三方均出结果|TIMEOUT|ERROR|error" "$EVIDENCE_DIR/real-lr-3party.log" | tail -35 +fi + +echo +echo "证据日志: $EVIDENCE_DIR/real-{psi,lr}-3party.log" diff --git a/build/verify-tds.sh b/build/verify-tds.sh new file mode 100644 index 0000000..4132d31 --- /dev/null +++ b/build/verify-tds.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# TDS 平台接口验收:登录 + 业务面探活 +# 用法: bash build/verify-tds.sh [API_BASE] +set -uo pipefail + +BASE="${1:-http://192.168.1.26:30201}" +ACCOUNT="${TDS_ACCOUNT:-admin}" +PASSWORD="${TDS_PASSWORD:-123456}" +CIPHER_KEY="EY8WePvjM5GGwQzn" + +ok=0; bad=0 +p() { if [ "$1" = "1" ]; then echo " ✅ $2"; ok=$((ok+1)); else echo " ❌ $2"; bad=$((bad+1)); fi; } + +# 复刻前端 encryptPassword: AES-256-ECB-Pkcs7(key=utf8(md5(CIPHER_KEY)), data=utf8(md5(明文))) -> hex +enc_pwd() { + # 🔴 JNPF / 编排同款(已在 node/CryptoJS 与 openssl 双向校验): + # key = md5(CIPHER_KEY) 的十六进制串的 **ASCII 字节**(32B)→ openssl -K 吃它的 hex + # data = md5(明文) 的十六进制串的 **ASCII 字节**(32B)→ 直接喂给 openssl 的 stdin + # AES-256-ECB-PKCS7 → hex 输出 + # 🔴 data **不能再 hex 化一次**(那是把 32 个 ASCII 字节变成 64 个字节,错)。 + local kh dh kh_hex + kh=$(printf '%s' "$CIPHER_KEY" | md5 -q 2>/dev/null || printf '%s' "$CIPHER_KEY" | md5sum | cut -d' ' -f1) + dh=$(printf '%s' "$1" | md5 -q 2>/dev/null || printf '%s' "$1" | md5sum | cut -d' ' -f1) + kh_hex=$(printf '%s' "$kh" | od -An -tx1 | tr -d ' +') + printf '%s' "$dh" | openssl enc -aes-256-ecb -K "$kh_hex" -nosalt 2>/dev/null | od -An -tx1 | tr -d ' +' +} + +echo "=== 1. 平台登录 ($BASE) ===" +ENCPW=$(enc_pwd "$PASSWORD") +echo " 账号=$ACCOUNT 密文前16位=${ENCPW:0:16}..." +LOGIN=$(curl -s -m 25 -X POST "$BASE/api/oauth/Login" \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode "account=$ACCOUNT" \ + --data-urlencode "password=$ENCPW" \ + --data-urlencode "grant_type=password" 2>&1) +CODE=$(printf '%s' "$LOGIN" | sed -n 's/.*"code":\([0-9]*\).*/\1/p') +TOKEN=$(printf '%s' "$LOGIN" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') +[ "$CODE" = "200" ] && p 1 "登录返回 code=200" || { p 0 "登录失败: $(printf '%s' "$LOGIN" | head -c 200)"; } +if [ -n "$TOKEN" ]; then + echo " token=${TOKEN:0:30}..." + H="Authorization: $TOKEN" + # 2. 门户免登录探活 + echo "=== 2. 门户测试档 ===" + TM=$(curl -s -m 15 "$BASE/api/ssw/tds/Portal/TestMode" 2>&1) + printf '%s' "$TM" | grep -q '"code":200' && p 1 "Portal/TestMode 可用" || p 0 "Portal/TestMode: $(printf '%s' "$TM" | head -c 150)" + # 3. 登录态个人信息 + echo "=== 3. 登录态接口 ===" + PR=$(curl -s -m 15 -H "$H" "$BASE/api/ssw/tds/Portal/Profile" 2>&1) + printf '%s' "$PR" | grep -q '"code":200' && p 1 "Portal/Profile 可用" || p 0 "Portal/Profile: $(printf '%s' "$PR" | head -c 150)" + # 4. 业务面:目录 / 需求 / 连接器 / 合约 + echo "=== 4. 业务面 ===" + for ep in "/api/ssw/tds/Catalog/ServiceList" "/api/ssw/tds/Demand/List" "/api/ssw/tds/Connector/My"; do + R=$(curl -s -m 15 -H "$H" "$BASE$ep" 2>&1) + printf '%s' "$R" | grep -qE '"code":(200|0)' \ + && p 1 "GET $(basename $(dirname $ep))/$(basename $ep) → $(printf '%s' "$R" | head -c 60)" \ + || p 0 "GET $ep → $(printf '%s' "$R" | head -c 110)" + done + # ContractRegister/List 需带备案 id;无备案时返回业务码 404「备案不存在或合约已删除」, + # 这是**接口可达**的业务应答(不是路由 404),按可达判定,避免把「暂无数据」误判成部署失败。 + R=$(curl -s -m 15 -H "$H" "$BASE/api/ssw/tds/ContractRegister/List" 2>&1) + printf '%s' "$R" | grep -qE '"code":(200|404)' \ + && p 1 "GET ContractRegister/List 可达(业务应答: $(printf '%s' "$R" | head -c 80))" \ + || p 0 "GET ContractRegister/List → $(printf '%s' "$R" | head -c 110)" +fi + +echo "=== 5. 内部通道(连接器用 X-Internal-Token) ===" +ITOK="" +for src in "configmap/ssw-tds-env"; do + ITOK=$(kubectl -n wuguirong get "$src" -o jsonpath='{.data.SSW_INTERNAL_TOKEN}' 2>/dev/null) +done +if [ -n "$ITOK" ]; then + echo " token=${ITOK:0:8}..." + # 内部端点:按连接器编码查接入决策(无此编码时应返回业务失败而非鉴权失败) + R=$(curl -s -m 15 -H "X-Internal-Token: $ITOK" "$BASE/api/ssw/tds/Connector/Internal/DecisionByCode?code=probe-nonexistent" 2>&1) + printf '%s' "$R" | grep -q "expired\|未授权\|Unauthorized\|401" \ + && p 0 "内部通道鉴权被拒: $(printf '%s' "$R" | head -c 120)" \ + || p 1 "内部通道可达(业务应答: $(printf '%s' "$R" | head -c 90))" + # 反向验证:不带 token 必须被拒 + R2=$(curl -s -m 15 "$BASE/api/ssw/tds/Connector/Internal/DecisionByCode?code=probe-nonexistent" 2>&1) + printf '%s' "$R2" | grep -qE 'expired|未授权|Unauthorized|401|600|缺少有效内部凭证' \ + && p 1 "无 token 被正确拒绝(fail-closed)" \ + || p 0 "无 token 未被拒绝,存在越权风险: $(printf '%s' "$R2" | head -c 110)" +else + echo " (未能从 ConfigMap 读取 SSW_INTERNAL_TOKEN)" +fi + +echo +echo "======== 结果: 通过 $ok / 失败 $bad ========" +[ "$bad" -eq 0 ] diff --git a/build/zig-cc-armv7-glibc26.sh b/build/zig-cc-armv7-glibc26.sh new file mode 100755 index 0000000..90198ae --- /dev/null +++ b/build/zig-cc-armv7-glibc26.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# zig-cc-armv7-glibc26.sh +# cargo/rustc 交叉链接 armv7 (glibc 2.26 动态) 用的 zig cc 包装器。 +# +# 用法(环境变量): +# CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=<本脚本路径> +# ZIG_TARGET=arm-linux-gnueabihf.2.26 +# ZIG_SYSROOT=<只含 zlib 的干净 sysroot> +# ZIG_COMPAT_DIR=<引擎目录>/compat ← glibc 兼容 shim +# PGLITE_LIB_DIR=<引擎目录> +# CARGO_PROFILE_RELEASE_STRIP=none ← 交叉构建必须 +# +# 🔴 四项必要处理(每一项都是实测踩出来的): +# 1. **丢弃 rustc 传入的 --target= / -target ** +# rustc 固定传 `--target=arm-unknown-linux-gnueabihf`,但 zig 的 target +# 解析器**不认 `unknown` 这个 OS 名** ⇒ 合并成本机 target 后报 +# "version '.2.26' in target triple 'arm-unknown-linux-gnueabihf.2.26' is invalid"。 +# ⇒ 只保留本脚本自己的 `-target arm-linux-gnueabihf.2.26`。 +# 2. **-Wl,/abs/path → 裸路径** +# zig cc 不接受 `-Wl,` 与绝对路径合并的写法(rustc 传给链接器驱动时 +# 常用这种形式)⇒ 拆开。 +# 3. **注入 sysroot 的 -I / -L** +# zig 自带 glibc 头与库,但**不带 zlib** ⇒ 需要外部 zlib-only sysroot。 +# ⚠️ 不要用上游那个含完整 Debian 12 armhf 的 sysroot:它的 libc.so.6 是 +# glibc 2.36,`-L` 会把链接器引到 2.36 ⇒ 产物又绑 GLIBC_2.34+。 +# 4. **注入 glibc 兼容 shim(放在所有 .a 之后)** +# · explicit_bzero(glibc 2.25+)—— PostgreSQL 17 与 Rust std 都要用 +# · getrandom (glibc 2.25+)—— Rust std 的 RandomState 播种哈希用 +# 放最后 ⇒ 本地强符号优先于 libc.so.6 的版本化符号。 +# ⚠️ 这两个 shim **不能**放进 libpglite.a:rustc 在 --whole-archive 场景 +# 会重打包归档,对这类成员处理不确定(时有时无);且若库内已有, +# 再注入会 duplicate symbol 链接失败。 +set -eu + +TARGET="${ZIG_TARGET:-arm-linux-gnueabihf.2.26}" +SYSROOT="${ZIG_SYSROOT:-}" +COMPAT_DIR="${ZIG_COMPAT_DIR:-}" + +TMPARGS="$(mktemp)" +trap 'rm -f "${TMPARGS}"' EXIT + +SKIP=0 +for a in "$@"; do + if [ "${SKIP}" = "1" ]; then + SKIP=0 + continue + fi + case "$a" in + --target=*) ;; + -target) SKIP=1 ;; + -Wl,/*) printf '%s\0' "${a#-Wl,}" >> "${TMPARGS}" ;; + *) printf '%s\0' "$a" >> "${TMPARGS}" ;; + esac +done + +set -- +while IFS= read -r -d '' line; do set -- "$@" "${line}"; done < "${TMPARGS}" + +if [ -n "${SYSROOT}" ]; then + set -- -I "${SYSROOT}/include" -L "${SYSROOT}/lib" "$@" +fi + +if [ -n "${COMPAT_DIR}" ] && [ -d "${COMPAT_DIR}" ]; then + for obj in "${COMPAT_DIR}"/*.o; do + if [ -f "${obj}" ]; then + set -- "$@" "${obj}" + fi + done +fi + +if [ -n "${ZIG_TRACE:-}" ]; then + : > "${ZIG_TRACE}" + for a in "$@"; do printf '%s\n' "$a" >> "${ZIG_TRACE}"; done +fi + +exec zig cc -target "${TARGET}" "$@" diff --git a/card/bridge.go b/card/bridge.go new file mode 100644 index 0000000..3733e6f --- /dev/null +++ b/card/bridge.go @@ -0,0 +1,242 @@ +package main + +// TDS 心跳桥:让设备侧软卡自己按 TDS 协议上报心跳(不再依赖开发机上的保活进程)。 +// +// 这是「1 设备 1 卡 1 连接器」的关键:认证/签名在卡内,连接器只跑业务。 +// 心跳契约(照 ConnectorServiceImpl.heartbeat,不猜): +// signingText = connectorId + "\n" + timestamp(ms) + "\n" + nonce +// signature = Base64(DER(ECDSA-SHA256(signingText))) // Java SHA256withECDSA +// PUT /api/ssw/tds/Connector/{id}/Heartbeat (Bearer = TDS 登录 token) +// 时间窗 ±30s,nonce 一次性;TTL = interval × 3(默认 15s) +// +// 登录契约:POST /api/oauth/Login,x-www-form-urlencoded +// account / password(=encryptPassword 密文) / grant_type=password + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +type Bridge struct { + Card *Card + TDSURL string + Connector string + Account string + Password string + CipherKey string + Interval time.Duration + client *http.Client + mu sync.Mutex + token string + tokenAt time.Time + clockSkew time.Duration + lastStatus string + okCount int + failCount int +} + +func (b *Bridge) now() int64 { + b.mu.Lock() + skew := b.clockSkew + b.mu.Unlock() + return time.Now().Add(skew).UnixMilli() +} + +// syncClock 用 TDS 的 HTTP Date 头估计时钟偏移(ZYNQ 无 RTC,±30s 时间窗必需)。 +func (b *Bridge) syncClock() { + resp, err := b.client.Get(strings.TrimRight(b.TDSURL, "/") + "/api/ssw/tds/Portal/TestMode") + if err != nil { + return + } + defer resp.Body.Close() + if d := resp.Header.Get("Date"); d != "" { + if t, err := http.ParseTime(d); err == nil { + b.mu.Lock() + b.clockSkew = time.Until(t) + b.mu.Unlock() + log.Printf("[bridge] 时钟偏移校准: %d ms", b.clockSkew.Milliseconds()) + } + } +} + +func (b *Bridge) login() error { + enc, err := encryptPassword(b.Password, b.CipherKey) + if err != nil { + return err + } + form := url.Values{"account": {b.Account}, "password": {enc}, "grant_type": {"password"}} + req, err := http.NewRequest(http.MethodPost, + strings.TrimRight(b.TDSURL, "/")+"/api/oauth/Login", + strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := b.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + var obj struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data struct { + Token string `json:"token"` + } `json:"data"` + Token string `json:"token"` + } + if err := json.Unmarshal(raw, &obj); err != nil { + return fmt.Errorf("登录响应解析失败: %w (%s)", err, string(raw[:min(len(raw), 120)])) + } + tok := obj.Token + if tok == "" { + tok = obj.Data.Token + } + if tok == "" { + return fmt.Errorf("登录未返回 token: %s", string(raw[:min(len(raw), 160)])) + } + b.mu.Lock() + b.token, b.tokenAt = tok, time.Now() + b.mu.Unlock() + return nil +} + +func (b *Bridge) auth() (string, error) { + b.mu.Lock() + tok, age := b.token, time.Since(b.tokenAt) + b.mu.Unlock() + if tok != "" && age < 20*time.Minute { + return tok, nil + } + if err := b.login(); err != nil { + return "", err + } + b.mu.Lock() + defer b.mu.Unlock() + return b.token, nil +} + +func nonce() string { + buf := make([]byte, 16) + _, _ = rand.Read(buf) + return hex.EncodeToString(buf) +} + +func (b *Bridge) heartbeat() error { + tok, err := b.auth() + if err != nil { + return fmt.Errorf("login: %w", err) + } + ts := b.now() + text := fmt.Sprintf("%s\n%d\n%s", b.Connector, ts, nonce()) + sig, err := b.Card.sign([]byte(text)) + if err != nil { + return fmt.Errorf("card sign: %w", err) + } + parts := strings.Split(text, "\n") + body, _ := json.Marshal(map[string]any{ + "connectorId": b.Connector, "timestamp": mustInt64(parts[1]), + "nonce": parts[2], "signature": sig, + }) + req, err := http.NewRequest(http.MethodPut, + fmt.Sprintf("%s/api/ssw/tds/Connector/%s/Heartbeat", strings.TrimRight(b.TDSURL, "/"), b.Connector), + bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Authorization", tok) + req.Header.Set("Content-Type", "application/json") + resp, err := b.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if bytes.Contains(raw, []byte(`"code":200`)) { + b.record(true, "ONLINE") + return nil + } + msg := string(raw[:min(len(raw), 160)]) + b.record(false, msg) + // token 失效则下次重登 + if bytes.Contains(raw, []byte("Login expired")) || bytes.Contains(raw, []byte(`"code":600`)) { + b.mu.Lock() + b.token = "" + b.mu.Unlock() + } + return fmt.Errorf("heartbeat rejected: %s", msg) +} + +func (b *Bridge) record(ok bool, status string) { + b.mu.Lock() + defer b.mu.Unlock() + if ok { + b.okCount++ + } else { + b.failCount++ + } + b.lastStatus = status +} + +// Status 供 /v1/bridge 与巡检读取;Run 在独立 goroutine 写,读写都走锁。 +func (b *Bridge) Status() map[string]any { + b.mu.Lock() + defer b.mu.Unlock() + return map[string]any{ + "enabled": true, "connectorId": b.Connector, + "deviceId": b.Card.DeviceID, "cardId": b.Card.KeyID, + "status": b.lastStatus, "okCount": b.okCount, "failCount": b.failCount, + "intervalSeconds": b.Interval.Seconds(), "tds": b.TDSURL, + } +} + +func (b *Bridge) Run() { + b.client = &http.Client{Timeout: 15 * time.Second} + b.syncClock() + if err := b.login(); err != nil { + log.Printf("[bridge] 首次登录失败(将重试): %v", err) + } + // 立即打一次心跳,不等第一个 tick(设备重启后尽快 ONLINE) + if err := b.heartbeat(); err != nil { + log.Printf("[bridge] FAIL %v", err) + } + ticker := time.NewTicker(b.Interval) + defer ticker.Stop() + var ticks int + for range ticker.C { + ticks++ + if err := b.heartbeat(); err != nil { + log.Printf("[bridge] FAIL %v", err) + } else if st := b.Status(); st["okCount"].(int) == 1 || st["okCount"].(int)%12 == 0 { + log.Printf("[bridge] #%d ONLINE device=%s card=%s", st["okCount"], b.Card.DeviceID, b.Card.KeyID) + } + // 每小时校准一次时钟(嵌入式板无 RTC) + if ticks%720 == 0 { + b.syncClock() + } + } +} + +func mustInt64(s string) int64 { + var v int64 + _, _ = fmt.Sscanf(s, "%d", &v) + return v +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/card/build.sh b/card/build.sh new file mode 100644 index 0000000..03e7bda --- /dev/null +++ b/card/build.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# 交叉编译软卡:linux/amd64(AMD/海光)+ linux/armv7(ZYNQ,静态,无 CGO)。 +# 用法: bash card/build.sh +set -euo pipefail +cd "$(dirname "$0")" +mkdir -p dist +export CGO_ENABLED=0 + +echo "=== 本机自检 ===" +go build -trimpath -o dist/softcard-local . +./dist/softcard-local --self-test + +echo "=== linux/amd64 ===" +GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o dist/softcard-linux-amd64 . +echo "=== linux/armv7 (GOARM=7, 静态) ===" +GOOS=linux GOARCH=arm GOARM=7 go build -trimpath -ldflags="-s -w" -o dist/softcard-linux-armv7 . + +echo "=== 产物 ===" +file dist/softcard-linux-amd64 dist/softcard-linux-armv7 +ls -lh dist/softcard-linux-amd64 dist/softcard-linux-armv7 diff --git a/card/dist/softcard-linux-amd64 b/card/dist/softcard-linux-amd64 new file mode 100755 index 0000000..e62c26a Binary files /dev/null and b/card/dist/softcard-linux-amd64 differ diff --git a/card/dist/softcard-linux-armv7 b/card/dist/softcard-linux-armv7 new file mode 100755 index 0000000..95a262c Binary files /dev/null and b/card/dist/softcard-linux-armv7 differ diff --git a/card/dist/softcard-local b/card/dist/softcard-local new file mode 100755 index 0000000..ca38544 Binary files /dev/null and b/card/dist/softcard-local differ diff --git a/card/go.mod b/card/go.mod new file mode 100644 index 0000000..1ef02ea --- /dev/null +++ b/card/go.mod @@ -0,0 +1,3 @@ +module ssw-tds-test/softcard + +go 1.21 diff --git a/card/main.go b/card/main.go new file mode 100644 index 0000000..9ab8712 --- /dev/null +++ b/card/main.go @@ -0,0 +1,461 @@ +// softcard —— 每台设备一张「安全卡」的软件实现(对应 ssw-acz7015 §1.4 SoftTPMProvider,Phase 1 软件根)。 +// +// 设计边界(诚实声明,不伪装成硬件根): +// - 私钥在卡内生成、只以 0600 文件落在本机;任何 API 都不导出私钥。 +// - 签名在卡进程内完成(ECDSA P-256 + SHA-256,DER/ASN.1 输出,等价 Java SHA256withECDSA)。 +// - 仅监听 127.0.0.1,所有密钥类操作需要 Bearer token;token 缺失即拒绝启动(fail-closed)。 +// - ⚠️ 软件根:设备 root 仍可读密钥文件;真硬件根需 Phase 2 换 ChipTPMProvider / ACZ7015 板。 +// +// 接口: +// +// GET /v1/health -> 存活探针(免 token,不返回任何密钥信息) +// GET /v1/info -> cardId/deviceId/platform/measurement/publicKey(SPKI DER b64) +// GET /v1/public-key -> 纯文本公钥 b64(供 TDS 注册脚本读取) +// POST /v1/sign {"payload":""} -> {"signature":"","algorithm":"SHA256withECDSA"} +// {"text":""} 也可直接传原文 +// POST /v1/attest {"challenge":""} -> 设备度量 + 挑战签名(对齐设计方案 §8.2) +// +// 用法: +// +// softcard --key-dir /opt/ssw/card --device-id tee-amd-7 --platform sev-snp --token "$TOKEN" +// softcard --key-dir /tmp/c --device-id x --token t --export-pub # 只输出公钥 +// softcard --self-test # 本机自检(不起服务) +package main + +import ( + "crypto/aes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/md5" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "flag" + "fmt" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "time" +) + +const version = "0.1.0" + +type Card struct { + Priv *ecdsa.PrivateKey + PubDER []byte + PubB64 string + KeyID string + DeviceID string + Platform string + Measurement string + Backend string + CreatedAt string + Token string + Bridge *Bridge // 设备侧自主心跳桥(nil = 只提供本机签名接口) +} + +func b64(b []byte) string { return base64.StdEncoding.EncodeToString(b) } + +func unb64(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(strings.TrimSpace(s)) } + +// loadOrCreate 幂等地加载/生成卡密钥。私钥权限不是 0600 时拒绝启动(fail-closed)。 +func loadOrCreate(dir string) (*ecdsa.PrivateKey, []byte, string, error) { + if err := os.MkdirAll(dir, 0700); err != nil { + return nil, nil, "", err + } + keyPath := filepath.Join(dir, "card.key") + pubPath := filepath.Join(dir, "card.pub.b64") + + if st, err := os.Stat(keyPath); err == nil { + if st.Mode().Perm()&0077 != 0 { + return nil, nil, "", fmt.Errorf("fail-closed: 私钥权限 %o 过宽(要求 0600): %s", st.Mode().Perm(), keyPath) + } + raw, err := os.ReadFile(keyPath) + if err != nil { + return nil, nil, "", err + } + blk, _ := pem.Decode(raw) + if blk == nil { + return nil, nil, "", errors.New("私钥 PEM 解析失败") + } + k, err := x509.ParsePKCS8PrivateKey(blk.Bytes) + if err != nil { + return nil, nil, "", err + } + ec, ok := k.(*ecdsa.PrivateKey) + if !ok || ec.Curve != elliptic.P256() { + return nil, nil, "", errors.New("卡密钥必须是 EC P-256") + } + pubDER, err := x509.MarshalPKIXPublicKey(&ec.PublicKey) + if err != nil { + return nil, nil, "", err + } + return ec, pubDER, st.ModTime().UTC().Format(time.RFC3339), nil + } + + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, "", err + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + return nil, nil, "", err + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) + if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil { + return nil, nil, "", err + } + if err := os.Chmod(keyPath, 0600); err != nil { + return nil, nil, "", err + } + pubDER, err := x509.MarshalPKIXPublicKey(&priv.PublicKey) + if err != nil { + return nil, nil, "", err + } + if err := os.WriteFile(pubPath, []byte(b64(pubDER)+"\n"), 0644); err != nil { + return nil, nil, "", err + } + return priv, pubDER, time.Now().UTC().Format(time.RFC3339), nil +} + +// measurement 是软卡进程自度量(二进制 + 设备标识 + 平台标签),不是硬件 PCR。 +func measurement(deviceID, platform string) string { + h := sha256.New() + if exe, err := os.Executable(); err == nil { + if f, err := os.Open(exe); err == nil { + _, _ = io.Copy(h, f) + _ = f.Close() + } + } + _, _ = io.WriteString(h, "|"+deviceID+"|"+platform) + return hex.EncodeToString(h.Sum(nil)[:16]) +} + +func newCard(dir, deviceID, platform, measure, token string) (*Card, error) { + priv, pubDER, created, err := loadOrCreate(dir) + if err != nil { + return nil, err + } + sum := sha256.Sum256(pubDER) + if measure == "" { + measure = measurement(deviceID, platform) + } + return &Card{ + Priv: priv, PubDER: pubDER, PubB64: b64(pubDER), + KeyID: hex.EncodeToString(sum[:8]), DeviceID: deviceID, + Platform: platform, Measurement: measure, Backend: "softcard", + CreatedAt: created, Token: token, + }, nil +} + +func (c *Card) sign(payload []byte) (string, error) { + digest := sha256.Sum256(payload) + der, err := ecdsa.SignASN1(rand.Reader, c.Priv, digest[:]) + if err != nil { + return "", err + } + return b64(der), nil +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(v) +} + +func (c *Card) handler() http.Handler { + mux := http.NewServeMux() + + mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]any{"status": "UP", "backend": c.Backend, "version": version}) + }) + + // 其余接口统一做本机 + Bearer 校验(fail-closed) + guarded := func(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil || (host != "127.0.0.1" && host != "::1") { + writeJSON(w, 403, map[string]string{"error": "loopback only"}) + return + } + if c.Token == "" || r.Header.Get("Authorization") != "Bearer "+c.Token { + writeJSON(w, 401, map[string]string{"error": "card token required"}) + return + } + fn(w, r) + } + } + + mux.HandleFunc("/v1/info", guarded(func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]any{ + "cardId": c.KeyID, "keyId": c.KeyID, "deviceId": c.DeviceID, + "platform": c.Platform, "measurement": c.Measurement, + "backend": c.Backend, "version": version, + "publicKey": c.PubB64, "algorithm": "SHA256withECDSA", + "createdAt": c.CreatedAt, + "rootBoundary": "software-root: device root can read card.key (Phase 1)", + }) + })) + + // 心跳桥状态:设备侧自报是否持续 ONLINE(1 设备 1 卡 1 连接器) + mux.HandleFunc("/v1/bridge", guarded(func(w http.ResponseWriter, r *http.Request) { + if c.Bridge == nil { + writeJSON(w, 200, map[string]any{"enabled": false}) + return + } + writeJSON(w, 200, c.Bridge.Status()) + })) + + mux.HandleFunc("/v1/public-key", guarded(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = io.WriteString(w, c.PubB64+"\n") + })) + + mux.HandleFunc("/v1/sign", guarded(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + writeJSON(w, 405, map[string]string{"error": "POST only"}) + return + } + r.Body = http.MaxBytesReader(w, r.Body, 1<<20) + var req struct { + Payload string `json:"payload"` + Text string `json:"text"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, 400, map[string]string{"error": "bad json"}) + return + } + var payload []byte + var err error + switch { + case req.Payload != "": + payload, err = unb64(req.Payload) + case req.Text != "": + payload = []byte(req.Text) + default: + err = errors.New("payload or text required") + } + if err != nil { + writeJSON(w, 400, map[string]string{"error": err.Error()}) + return + } + sig, err := c.sign(payload) + if err != nil { + writeJSON(w, 500, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, 200, map[string]any{ + "signature": sig, "algorithm": "SHA256withECDSA", + "digest": "sha256", "keyId": c.KeyID, + "publicKey": c.PubB64, "payloadSha256": hex.EncodeToString(sha256Sum(payload)), + }) + })) + + mux.HandleFunc("/v1/attest", guarded(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + writeJSON(w, 405, map[string]string{"error": "POST only"}) + return + } + var req struct { + Challenge string `json:"challenge"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil { + writeJSON(w, 400, map[string]string{"error": "bad json"}) + return + } + ch, err := unb64(req.Challenge) + if err != nil || len(ch) == 0 { + writeJSON(w, 400, map[string]string{"error": "challenge(base64) required"}) + return + } + // 对齐设计方案 §8.2:TPM 签 Nonce||Challenge,并附设备度量 + payload := append(append([]byte{}, ch...), []byte("\n"+c.Measurement)...) + sig, err := c.sign(payload) + if err != nil { + writeJSON(w, 500, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, 200, map[string]any{ + "deviceId": c.DeviceID, "cardId": c.KeyID, "platform": c.Platform, + "measurement": c.Measurement, "backend": c.Backend, + "signature": sig, "algorithm": "SHA256withECDSA", + "publicKey": c.PubB64, + }) + })) + return mux +} + +func sha256Sum(b []byte) []byte { s := sha256.Sum256(b); return s[:] } + +// ---- TDS 登录密文(与 verify-tds.sh / heartbeat-keepalive.py 同口径)---- +// AES-256-ECB-Pkcs7(key = md5(CIPHER_KEY) hex 串的 ASCII 字节 32B, +// +// data = md5(明文) hex 串的 ASCII 字节 32B) -> hex +func encryptPassword(plain, cipherKey string) (string, error) { + kh := md5.Sum([]byte(cipherKey)) + dh := md5.Sum([]byte(plain)) + key := []byte(hex.EncodeToString(kh[:])) + data := []byte(hex.EncodeToString(dh[:])) + blk, err := aes.NewCipher(key) + if err != nil { + return "", err + } + pad := 16 - len(data)%16 + for i := 0; i < pad; i++ { + data = append(data, byte(pad)) + } + out := make([]byte, len(data)) + for i := 0; i < len(data); i += 16 { + blk.Encrypt(out[i:i+16], data[i:i+16]) + } + return hex.EncodeToString(out), nil +} + +// selfTest 不起服务,直接对拍签名与鉴权语义,供本机与设备上自检。 +func selfTest() error { + dir, err := os.MkdirTemp("", "softcard-test-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + c, err := newCard(dir, "selftest", "none", "", "test-token") + if err != nil { + return err + } + // 公钥必须是 SPKI DER 且可解析为 P-256 + pub, err := x509.ParsePKIXPublicKey(c.PubDER) + if err != nil { + return fmt.Errorf("SPKI 解析失败: %w", err) + } + if _, ok := pub.(*ecdsa.PublicKey); !ok { + return errors.New("公钥不是 EC") + } + // 签名必须能被标准库按 DER 验签(等价 Java SHA256withECDSA) + msg := []byte("890556829011018181\n1794461768001\nabc123") + sigB64, err := c.sign(msg) + if err != nil { + return err + } + der, err := unb64(sigB64) + if err != nil { + return err + } + digest := sha256.Sum256(msg) + if !ecdsa.VerifyASN1(&c.Priv.PublicKey, digest[:], der) { + return errors.New("DER 验签失败") + } + // HTTP 鉴权 fail-closed + srv := httptest.NewServer(c.handler()) + defer srv.Close() + client := &http.Client{Timeout: 5 * time.Second} + req, _ := http.NewRequest("GET", srv.URL+"/v1/info", nil) + resp, err := client.Do(req) + if err != nil { + return err + } + _ = resp.Body.Close() + if resp.StatusCode != 401 { + return fmt.Errorf("无 token 应 401,实际 %d", resp.StatusCode) + } + req, _ = http.NewRequest("GET", srv.URL+"/v1/info", nil) + req.Header.Set("Authorization", "Bearer test-token") + resp2, err := client.Do(req) + if err != nil { + return err + } + _ = resp2.Body.Close() + if resp2.StatusCode != 200 { + return fmt.Errorf("带 token 应 200,实际 %d", resp2.StatusCode) + } + // 登录密文自检向量 + enc, err := encryptPassword("123456", "EY8WePvjM5GGwQzn") + if err != nil { + return err + } + if !strings.HasPrefix(enc, "d4958348e2210811") { + return fmt.Errorf("登录密文向量不符: %s", enc) + } + fmt.Printf("SELFTEST OK cardId=%s pubB64Len=%d sigDerLen=%d encPwd=%s…\n", + c.KeyID, len(c.PubB64), len(der), enc[:16]) + return nil +} + +func main() { + var ( + listen = flag.String("listen", "127.0.0.1:9701", "只监听本机回环") + keyDir = flag.String("key-dir", "/opt/ssw/card", "卡密钥目录") + deviceID = flag.String("device-id", "", "设备唯一标识(1 设备 1 卡)") + platform = flag.String("platform", "none", "TEE 平台: sev-snp / hygon-csv / none") + measure = flag.String("measurement", "", "设备度量(默认用软卡自度量)") + token = flag.String("token", os.Getenv("SOFTCARD_TOKEN"), "Bearer token(必填,fail-closed)") + exportPub = flag.Bool("export-pub", false, "只输出公钥 SPKI DER 的 Base64 后退出") + doSelfTest = flag.Bool("self-test", false, "本机自检后退出") + // 设备侧自主心跳(配置后才启用;未配置时卡只提供本机签名接口) + tdsURL = flag.String("tds-url", "", "TDS API 基址,配置后由卡自主上报心跳") + connector = flag.String("connector-id", "", "TDS 连接器 id(与卡一一绑定)") + tdsAccount = flag.String("tds-account", "admin", "TDS 登录账号") + tdsPass = flag.String("tds-password", "123456", "TDS 登录口令明文(内部加密传输)") + cipherKey = flag.String("cipher-key", "EY8WePvjM5GGwQzn", "JNPF 登录 CIPHER_KEY") + hbInterval = flag.Duration("heartbeat-interval", 5*time.Second, "心跳间隔(TDS TTL = interval×3)") + ) + flag.Parse() + + if *doSelfTest { + if err := selfTest(); err != nil { + log.Fatalf("SELFTEST FAIL: %v", err) + } + return + } + if *token == "" { + log.Fatal("fail-closed: 必须提供 --token 或 SOFTCARD_TOKEN") + } + if *deviceID == "" { + log.Fatal("fail-closed: 必须提供 --device-id(1 设备 1 卡 1 连接器)") + } + c, err := newCard(*keyDir, *deviceID, *platform, *measure, *token) + if err != nil { + log.Fatalf("卡初始化失败: %v", err) + } + if *exportPub { + fmt.Println(c.PubB64) + return + } + if !strings.HasPrefix(*listen, "127.0.0.1:") && !strings.HasPrefix(*listen, "[::1]:") { + log.Fatal("fail-closed: 只允许监听 127.0.0.1 / ::1") + } + log.Printf("softcard v%s cardId=%s device=%s platform=%s pub=%s… backend=softcard(Phase1 软件根)", + version, c.KeyID, c.DeviceID, c.Platform, c.PubB64[:16]) + + // 配置 --tds-url + --connector-id 后,卡自己按 TDS 协议上报心跳(签名不出卡)。 + // 未配置时卡只提供本机签名接口,不主动外联。 + if (*tdsURL == "") != (*connector == "") { + log.Fatal("fail-closed: --tds-url 与 --connector-id 必须同时配置") + } + if *tdsURL != "" { + c.Bridge = &Bridge{ + Card: c, TDSURL: *tdsURL, Connector: *connector, + Account: *tdsAccount, Password: *tdsPass, CipherKey: *cipherKey, + Interval: *hbInterval, + } + log.Printf("[bridge] 启用设备侧自主心跳 connector=%s tds=%s interval=%s", + *connector, *tdsURL, *hbInterval) + go c.Bridge.Run() + } + srv := &http.Server{ + Addr: *listen, Handler: c.handler(), + ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, + } + log.Fatal(srv.ListenAndServe()) +} diff --git a/docs/armv7-glibc-兼容性整改规格.md b/docs/armv7-glibc-兼容性整改规格.md new file mode 100644 index 0000000..0cf291a --- /dev/null +++ b/docs/armv7-glibc-兼容性整改规格.md @@ -0,0 +1,133 @@ +# armv7 平台包 glibc 兼容性整改规格(给 ssw-platform) + +> 提交方:ssw-tds-test(设备侧接入方) +> 日期:2026-11-12 +> 关联产物:`dist/sspf-v0.5.0-armv7-unknown-linux-gnueabihf.tar.gz`(150M) +> 关联引擎:`dist/pglite-armv7-unknown-linux-gnueabihf.tar.gz`(10M) + +## 1. 结论一句话 + +armv7 平台包**架构是对的**(rlib 全部 `armv7-unknown-linux-gnueabihf`,引擎二进制是 ARM EABI5 armhf), +但**链接用的 sysroot 是 Debian 12 的 GLIBC 2.36**,导致引擎被绑定到 `GLIBC_2.34` 版本节点, +**在 glibc ≤ 2.28 的设备上无法启动**(已实测复现)。 + +## 2. 实测证据 + +### 2.1 产物架构正确 + +``` +libpglite.a : ARM 静态库 +bin/initdb : ELF 32-bit LSB pie executable, ARM, EABI5, interpreter /lib/ld-linux-armhf.so.3 +bin/postgres : ELF 32-bit LSB pie executable, ARM, EABI5 +sspf 平台包 127 个 rlib : 目标三元组均为 armv7-unknown-linux-gnueabihf,无 x86_64 残留 +``` + +### 2.2 版本要求过高(根因) + +`objdump -T` 读出的版本需求: + +| 二进制 | 需要的 GLIBC 版本 | +|---|---| +| `bin/postgres` | 2.17, 2.25, **2.28, 2.29, 2.33, 2.34** | +| `bin/initdb` | 2.10, 2.14, **2.28, 2.29, 2.33, 2.34** | + +按版本号分组的符号: + +| 版本节点 | 符号 | +|---|---| +| GLIBC_2.34 | `__libc_start_main` `dlopen` `dlsym` `dlclose` `dlerror` `sem_init` `sem_destroy` `sem_post` `sem_wait` `sem_trywait` `shm_open` `shm_unlink` | +| GLIBC_2.33 | `stat64` `fstat64` `lstat64` | +| GLIBC_2.29 | `exp` `log` `pow` | +| GLIBC_2.28 | `fcntl` `fcntl64` | + +**这些符号本身在 glibc 2.26 就全部存在**(`sem_*`/`shm_open`/`dlopen` 都是老符号), +只是版本节点被绑高了 ⇒ **不是缺功能,是版本标签不匹配**。 + +### 2.3 复现(不需要设备) + +```bash +docker run --rm --platform linux/arm/v7 -v :/rt:ro arm32v7/debian:buster sh -c '/rt/bin/initdb --version' +``` + +输出(buster = glibc 2.28): + +``` +/rt/bin/initdb: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.29' not found (required by /rt/bin/initdb) +/rt/bin/initdb: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.33' not found (required by /rt/bin/initdb) +/rt/bin/initdb: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.34' not found (required by /rt/bin/initdb) +``` + +⇒ 在 **glibc 2.28 上已经起不来**。 + +### 2.4 根因定位 + +- `scripts/build-pglite-engine.sh` 用 `gcc-arm-linux-gnueabihf` + `libc6-dev-armhf-cross` 交叉编译引擎; +- `scripts/build-armv7.sh` 的 `ZIG_SYSROOT` 指向 `dist/pglite-engine-armv7/sysroot`; +- 该 sysroot 里的 libc 是 **`Debian GLIBC 2.36-9+deb12u14`**(实测 `strings` 确认)。 + +⇒ 链接时所有符号取 glibc 2.36 的版本节点 ⇒ 最高 `GLIBC_2.34`。 + +### 2.5 上游现有冒烟为什么没发现 + +`build-armv7.sh` 的冒烟用 `arm32v7/debian:bookworm-slim` = **glibc 2.36**, +与编译 sysroot 同版本 ⇒ 天然通过,掩盖了问题。 +**建议把冒烟镜像改成 `arm32v7/debian:buster`(2.28)或更老的 `stretch`(2.24)。** + +## 3. 目标设备基线 + +| 设备 | 架构 | glibc | 备注 | +|---|---|---|---| +| ZYNQ 192.168.1.233 | armv7l | **2.26** | 无 docker,BusyBox,静态二进制唯一可行 | +| 海光 192.168.1.102 | x86_64 | 2.28 | 有 docker,但 glibc 仍低于 2.34 | + +⇒ 引擎必须能在 **glibc 2.26** 上跑(ZYNQ 是硬约束)。 + +## 4. 两条可选修法 + +### 方案 A(推荐):改用 musl 静态,零设备 libc 依赖 + +- 目标三元组改为 `armv7-unknown-linux-musleabihf`; +- `zig cc -target arm-linux-musleabihf -static` 自带 musl libc(zig 0.14.1 已验证); +- 产物完全静态 ⇒ **设备 glibc 版本无关**,ZYNQ 的 2.26 无任何风险; +- 顺带解决「ZYNQ 无 glibc 头文件/运行时」的依赖问题。 + +已本地验证 musl 静态 armv7 二进制在 `arm32v7/debian:buster` 与 `alpine:3.20` 上均正常运行。 + +⚠️ 注意点: +- `relocate-runtime-cross.sh` 里的 `patchelf --set-rpath` 对静态产物无意义,可跳过; +- musl 下 `libpq.so.5` 仍需打进 runtime(`initdb` 依赖它); +- `pglite-rs-sys` 的 `build.rs` 无条件 `-lz`,musl 下 zlib 同样要静态链入。 + +### 方案 B:保留 gnueabihf,但用 ≤ 2.26 的 sysroot + +- 交叉工具链换成 **glibc ≤ 2.26** 的 sysroot(如 Debian 9 stretch armhf / Ubuntu 16.04 armhf); +- 引擎与 Rust 侧二进制都用它链接; +- 优点:与设备 glibc 语义一致,`patchelf`/RPATH 逻辑不变; +- 缺点:sysroot 需自备,且 stretch 的 glibc 无 `dlopen` 新符号问题要一并确认。 + +## 5. 验收标准(上游重编后请逐条自验) + +```bash +# ① 引擎二进制不得要求高于 2.26 的 GLIBC +objdump -T bin/postgres | grep -oE 'GLIBC_2\.[0-9]+' | sort -uV | tail -1 # 期望 ≤ GLIBC_2.26 +objdump -T bin/initdb | grep -oE 'GLIBC_2\.[0-9]+' | sort -uV | tail -1 # 期望 ≤ GLIBC_2.26 + +# ② 在老 glibc 的 armv7 容器里能起 +docker run --rm --platform linux/arm/v7 -v :/rt:ro arm32v7/debian:buster \ + sh -c '/rt/bin/initdb -D /tmp/pg -U check --no-sync -A trust -E UTF8' && echo INITDB_OK + +# ③ 若走方案 A(musl),产物必须是静态 +file bin/postgres | grep -q 'statically linked' && echo STATIC_OK + +# ④ sspf-admin 整体冒烟(老 glibc 容器里起服务 + 探活) +docker run --rm --platform linux/arm/v7 ... arm32v7/debian:buster sh -c '...' +``` + +设备侧我方会再用 `build/check-armv7-runtime.sh` 做最终裁决(读设备 glibc 版本 + 试跑 initdb)。 + +## 6. 不在本次整改范围(但请知悉) + +- `ssw-tds` 侧连接器(含 `tdc-rs`)在 ZYNQ 上是**独立静态二进制**(Go,musl), + 不依赖平台包的 glibc 符号版本 ⇒ 方案 B 落地后即使平台包仍有版本问题, + 连接器本身仍可单独部署; +- 但连接器启动后会拉起本地 PostgreSQL 引擎 ⇒ **引擎必须先修好**,否则连接器起不来。 diff --git a/docs/issue-ssw-platform-armv7-stdout-exit100.md b/docs/issue-ssw-platform-armv7-stdout-exit100.md new file mode 100644 index 0000000..5c24c69 --- /dev/null +++ b/docs/issue-ssw-platform-armv7-stdout-exit100.md @@ -0,0 +1,96 @@ +# [platform] armv7 版 sspf-admin 仅当 stdout 为管道时能启动;重定向到文件 / `/dev/null` 即 exit 100 + +> 投递目标:`ssw/ssw-platform`(本地 Gitea `127.0.0.1:13300`) +> **已投递:`ssw/ssw-platform#1` — http://127.0.0.1:13300/ssw/ssw-platform/issues/1**(open) +> 模板:`.gitea/ISSUE_TEMPLATE/platform-issue.md` +> 提出方:TDS 部署侧(`ssw-tds-test`),2026-11-13 +> 复现脚本:`/tmp/vertest/matrix.sh`,原始输出 `/tmp/vertest/matrix.log` + +## 现象 + +armv7 (`armv7-unknown-linux-gnueabihf`) 发布包中的 `sspf-admin`,**只有在 fd 1 是管道时**才能完成初始化并打印 `sspf 0.5.0 已启动`。把 stdout 重定向到**普通文件**或 `/dev/null` 后,进程在 initdb 之后以 **exit code 100** 直接退出,stderr 通常为空、stdout 只剩单用户模式 banner: + +``` +PostgreSQL stand-alone backend 17.5 +backend> +``` + +失败很快(36~51s),不是超时;stderr 有时会出现海量 `FATAL: terminating connection because protocol synchronization was lost` 刷屏(后果,不是根因)。 + +**与消费方引擎重编译无关**:把 11-12 官方发布包解出的 `sspf-admin`、以及用整改后引擎重链的二进制,放在同一容器、同一命令下做 A/B,两者都 `EXIT=100`,行为完全一致。问题在平台启动路径,不在我们这侧。 + +## 最小复现 + +用官方 `sspf-v0.5.0-armv7-unknown-linux-gnueabihf.tar.gz` 解出的二进制,每个 case 一个**全新容器**(干净 `/tmp`、无残留数据目录),串行执行。`timeout -k 5 150` 用于兜底:成功时进程常驻到超时(124),失败时启动期退出(100)。 + +```bash +BIN=<解开 tar.gz 后的 bin/sspf-admin> +IMG=arm32v7/debian:bookworm-slim + +# A — stdout 继承 docker pipe(docs/armv7-build.md:211 的原始验证方式) +docker run --rm --platform linux/arm/v7 -v "$BIN:/sspf-admin:ro" "$IMG" \ + sh -c 'cd /tmp; PGLITE_DIR=/data/pg PORT=30099 timeout -k 5 150 /sspf-admin 2>/tmp/srv.log; echo inner_rc=$?' + +# B — stdout = 普通文件(scripts/build-armv7.sh:137 的冒烟形态) +docker run --rm --platform linux/arm/v7 -v "$BIN:/sspf-admin:ro" "$IMG" \ + sh -c 'cd /tmp; PGLITE_DIR=/data/pg PORT=30099 timeout -k 5 150 /sspf-admin > /tmp/srv.log 2>&1; echo inner_rc=$?' + +# C — stdout = /dev/null 字符设备 +docker run --rm --platform linux/arm/v7 -v "$BIN:/sspf-admin:ro" "$IMG" \ + sh -c 'cd /tmp; PGLITE_DIR=/data/pg PORT=30099 timeout -k 5 150 /sspf-admin > /dev/null 2>/tmp/srv.log; echo inner_rc=$?' +``` + +2026-11-13 实测(无并发容器、无残留数据目录): + +| case | stdout (fd 1) | 耗时 | `inner_rc` | 结果 | +|---|---|---|---|---| +| A | 继承 docker pipe | 153s | 124 | ✅ `sspf 0.5.0 已启动:http://127.0.0.1:30099`,stderr `[demo-data] 官方示例数据导入完成(14255 条语句)` | +| B | 普通文件 `> /tmp/srv.log 2>&1` | 36s | **100** | ❌ `srv.log` 仅 46 字节 banner | +| C | `/dev/null` 字符设备 | 51s | **100** | ❌ stderr 0 字节 | + +补充对照:`initdb` 单独执行时对 stdout 类型**不敏感**(普通文件/管道都 Success)⇒ 失败点在 initdb 之后的进程内 PG 启动阶段。 + +## 根因分析 + +1. **pglite 把 fd 1 当作「名义客户端 socket」**。`postgres-pglite/src/backend/tcop/postgres.c::initDummyPort()` 设 `s.sock = 1`;`pglite/src/pglitec/pglitec.c` 用 `-Drecv=pgl_recv` / `-Dsend=pgl_send` 覆盖 socket 读写;胶水层注释明确写着 `initdb communicates with postgres via stdin<->stdout redirection`;`src/bin/initdb/initdb.c` 的 `PG_CMD_OPEN` 走 `popen(cmd, "w")` 与 `postgres --single` 通信。`pglite-rs-0.2.7/src/engine.rs::boot()` 还会调 `pgl_freopen("/dev/null", "r", 0)` 重开 stdin。⇒ **fd 1 的类型直接决定协议通道能否建立**。 +2. **exit 100 的确切来源**:协议同步丢失 → `ereport(ERROR/FATAL)` → `pglitec.c::pgl_longjmp()` 命中 `postgresmain_sigjmp_buf` → `exit(100)`(该文件以 `-Dexit=pgl_native_exit` 编译)→ `pgl_native_exit()` 在 `pgl_tramp_top == -1` 时走真 `exit(100)`,进程直接死亡。这也解释了为什么失败时 stderr 常常是空的(错误经 `DestRemote` 发到虚拟 socket,被宿主 `read_cb` 消费掉了)。 +3. **`src/backend/src/boot.rs::ensure_stdout_for_pglite()`(L353)策略反了**,这是平台侧可直接修的点: + - 判定为 `bad = fstat 失败 || (st_mode & S_IFMT) == S_IFCHR` ⇒ **只处理字符设备**,`S_IFREG`(普通文件,即 B —— 最主要的部署形态)完全不覆盖; + - 处理动作是把 fd 1 `dup2` 到一个**普通临时文件** ⇒ 把 `/dev/null` 从一种失败形态换成另一种失败形态(C 与 B 同为 exit 100,正好吻合); + - 注释里的「对 fd 1 注册 kqueue 读事件 / `kevent()` 失败」是 **macOS kqueue 语义**,Linux 上不存在 kqueue,该 workaround 在 armv7 Linux 容器/设备上既无必要又有害; + - 已排除判定本身出错:armv7 上 `libc::fstat` 与 `S_IFMT=0xf000` / `S_IFCHR=0x2000` / `S_IFREG=0x8000`(ARM 值,十六进制)均正确,`sizeof(libc::stat)=88`。是策略问题,不是常量/ABI 问题。 +4. **验收链存在盲区**:`scripts/build-armv7.sh:137` 的冒烟用 `> /tmp/srv.log 2>&1`(= B,失败形态)并轮询 90×2s;而 `docs/armv7-build.md:211` 记录成功的验证命令**没有任何重定向**(= A,成功形态)。两处结论不一致,冒烟脚本在干净目录下会判失败,文档却记录全绿。 + +## 期望行为 + +- 无论 stdout 是 tty / 管道 / 普通文件 / `/dev/null`,`sspf-admin` 都能完成 initdb + schema + 示例数据导入并正常常驻; +- 启动失败(含 exit 100)时 stderr 至少给出一条可诊断信息,而不是静默退出; +- armv7 冒烟脚本覆盖「日志重定向」这一最标准部署形态,作为回归门禁。 + +## 影响范围 + +- 所有标准部署形态都会挂:`nohup sspf-admin > app.log 2>&1 &`、systemd(stdout → journal/socket)、CI 重定向、日志落文件采集。只有「管道接 stdout」能跑。 +- 消费方(TDS / 连接器)目前只能临时规避成 `sspf-admin | cat > app.log`,**这是部署侧 workaround,不是根治**;且该写法会丢失退出语义、增加一层无意义进程。 +- 真机目标:ZYNQ `192.168.1.233`(glibc 2.26)、海光 `192.168.1.102`(glibc 2.28)。本次复现在 `arm32v7/debian:bookworm-slim`(glibc 2.36)上完成;另在 buster(2.28)上也复现过 exit 100 ⇒ **与 glibc 版本无关**。 + +## 建议修复(平台侧) + +- **P0** 重写 `ensure_stdout_for_pglite()`:目标应是**保证 fd 1 是管道**,而不是「换成普通文件」。例如 `pipe()` 后 `dup2(w, 1)`,读端保活并起一个轻量线程 drain(否则写满 64KB 会阻塞 / SIGPIPE);原本针对 macOS kqueue 的逻辑用 `#[cfg(target_os = "macos")]` 限定,Linux 走 pipe 分支。 +- **P0** 在 `scripts/build-armv7.sh` 冒烟里增加「干净数据目录 + `> /tmp/srv.log 2>&1`」用例并断言出现 `已启动`,把当前盲区补成门禁。 +- **P1** 启动前固化 `PGLITE_RUNTIME_DIR` 到带 `target_arch` + 二进制指纹的隔离路径(详见下方关联问题)。 +- **P1** `ensure_stdout_for_pglite()` 里的 `let _ = libc::dup2(...)` 静默失败、`exit 100` 无日志,建议至少 `tracing::warn!` 出 fd 类型与重定向结果,便于消费方自查。 +- **上游**:建议向 `pglite-rs` / `pglite` 反馈「`initDummyPort()` 用 fd 1 作为名义 socket,使宿主进程的 stdout 类型成为启动前置条件」这一设计问题,那是根治点。 + +## 关联问题(同一发布包,建议另案跟踪) + +1. **runtime 目录跨架构抢占**:`pglite-rs-0.2.7::engine.rs::runtime_dir()` 默认 `$TMPDIR/pglite-rs-runtime-0.2.7-`,而 `runtime_fingerprint()` **只对 runtime tar 内容做哈希** ⇒ x86_64 与 armv7 共用同一目录名;本仓全仓未使用 `PGLITE_RUNTIME_DIR`。残留目录会触发 `Error::Boot("runtime extraction race lost and target invalid")`。建议在 `open_db()` 前显式设置架构隔离路径。 +2. **glibc 兼容**(`docs/armv7-glibc-compat.md` 已有整改规格):upstream `dist/pglite-engine-armv7/libpglite.a` 的 `pqcomm.o` / `postmaster.o` 引用 `fcntl64`(GLIBC_2.28),在 ZYNQ 的 glibc 2.26 上重链会直接 `undefined symbol: fcntl64`。TDS 侧已按文档规格重编引擎把 GLIBC 需求降到 ≤2.18(`fcntl64=0`、`pgl_fcntl=0`、`fcntl=1`),请平台侧收编这部分改动,避免两个分支长期分叉。 + +## 环境 + +- sspf 版本 / 包 tag:`sspf-v0.5.0-armv7-unknown-linux-gnueabihf.tar.gz`(2026-11-13 02:41 出包,对应 `main` 上 `3920114` 及后续 docs 提交) +- rustc:`1.95.0`(`rust-toolchain.toml` 锁定),host `x86_64-apple-darwin`,target `armv7-unknown-linux-gnueabihf` +- 消费方式:直接跑发布包内的 `sspf-admin` +- 依赖:`pglite-rs 0.2.7` / `pglite-rs-sys 0.2.7` / PostgreSQL 17.5 +- 运行容器:`arm32v7/debian:bookworm-slim`(glibc 2.36,`linux/arm/v7` qemu 模拟);另在 `arm32v7/debian:buster`(2.28)复现 +- 其他:A/B 对照使用同一容器、同一命令,仅替换二进制;所有 case 均为全新容器 + 全新数据目录 + 无并发 armv7 容器 diff --git a/evidence/acceptance-report.html b/evidence/acceptance-report.html new file mode 100644 index 0000000..d4889c8 --- /dev/null +++ b/evidence/acceptance-report.html @@ -0,0 +1,147 @@ + + + + + +可信数据空间部署与真机验证验收报告 · 2026-11-12 + + + +
+ +

可信数据空间部署与真机验证 · 验收报告

+
验证日期 2026-11-12 · Kubernetes 租户 wuguirong · 执行范围:TDS 平台 / TDC 连接器 / MPC 隐私计算编排 / 三台真机 / FISCO 链
+ +
+
结论:完整可信数据空间已部署并贯通,真设备 / 真数据 / 真多方验证达成。
+
TDS 平台与 MPC 编排收敛在同一 Pod 的 6 个容器中,TDC 连接器独立部署并完成双向绑定;三台真机(AMD SEV-SNP / 海光 CSV / ZYNQ armv7)以网状会话真实执行 PSI 与纵向联邦 LR,结果三方逐位一致并与本地真值吻合。全链路验收脚本 9/9 + 3/3 + 8/8 全绿。
+
+ +
+
三方 PSI 交集
84 条
+
纵向 LR 权重
4 / 4 逐位一致
+
真机节点
3 / 3 在册
+
连接器状态
ONLINE
+
+ +

1. 部署拓扑与访问入口

+
+ + + + + + +
组件形态入口状态
TDS 平台 + MPC 编排单 Pod 6 容器:db / redis / backend / frontend / mpc-backend / mpc-frontend前端 30200 · API 30201 · MPC 前端 302036/6 Running
TDC 连接器(tdc-rs)独立 Deployment + PVC(PGlite)NodePort 302021/1 Running
三台真机 hostd192.168.1.7 / .102 / .233,控制面 :3020GET /nodes · Bearer 共享密钥synced=3
FISCO BCOS 链独立 Pod fisco-chainNodePort 30100 (RPC) / 30101块高 45
+

租户约束:容器级 runAsUser=10106、仅 PVC(禁 hostPath/nfs 直挂)、NodePort(无 Ingress)、密钥进 ConfigMap(SA 无 create secret)、Pod 资源合计 3500m / 6.88Gi(LimitRange 上限内)。

+
+ +

2. 全链路验收结果

+
+ + + + + + + + + + + +
环节结果证据 / 判据
TDS 平台接口9 / 9登录、Portal/TestMode、Profile、目录、需求、连接器、合约备案、内部通道可达 + 无 token fail-closed
MPC 编排接口3 / 3设备同步 synced=3, source=control-plane(非 mock)、设备列表、流程列表
连接器上线8 / 8审批 PASS → 环境申报 ENV_COMPLIANT → 设备证书 → 部署 READY → 连续 3 次签名心跳
数据产品上架8 / 8ONLINE / audit=PASS / delivery=PRIVACY,TDC ServiceCatalog 可见
TDS ↔ TDC 双向绑定通过TDC 身份 tdsConnectorId=890556829011018181、tdsSpaceId=PORTAL-DEMO-SPACE;内部通道带 token 可达
主体准入CONNECTED资质 APPROVED + 企业证书 + 在线可信节点(读时派生)
三方真机 PSI交集 84三方各自算出同一份 84 个 ID,与本地真值 A∩B∩C=84 吻合
三方真机纵向 LR4/4 一致alice / bob / carol reveal 权重逐位相同
结果落库编排通过FlowRun 1(runMode=real)/ StepRun 2 / Artifact 2 / RunEvent 5,回读校验
+
+ +

3. 真设备 / 真数据 / 真多方实测

+
+ + + + + +
参与方真机平台 / TCB全量行数角色
alice192.168.1.7 (x86_64)sev-snp / 5120标签方(load_pct + temp_c>65℃ 告警)
bob192.168.1.102 (x86_64)hygon-csv / 3102特征方(volt_v)
carol192.168.1.233 (armv7l)none / 1(如实标注:无 TEE)86特征方(amp_a)
+

PSI:三方 --listen + --peers 网状会话,启动顺序 carol → bob → alice(party 编号按站点名字典序、小编号主动连大编号),PSI 通道 9449 / 密态通道 9450。三方输出均为:

+
交集 84 条(原始下标已还原) ← alice / bob / carol 三份逐项一致 +本地真值 meta3.json: intersection_abc = 84 ✔
+

纵向 LR:col-blocks alice:0:1,bob:1:1,carol:2:1、label-owner=alice、epochs=20、lr=0.05、共享 seed/PSK。三方 reveal 权重:

+ + + + + + +
权重值三方一致性
w[0] load_pct0.3898658752441406逐位一致
w[1] volt_v0.02921295166015625逐位一致
w[2] amp_a0.01927947998046875逐位一致
w[3] 截距-0.03290557861328125逐位一致
+

数值与 2026-11-11 历史验证完全一致,说明跨厂商真机链路可复现。本次为宿主端二进制执行:真协议、真跨机、真数据,但 PSK 来自会话文件而非 KBS 证明后下发。

+
+ +

4. 关键契约(按源码确认,非猜测)

+
+ + + + + + + +
环节契约
心跳签名signingText = connectorId + "\n" + timestamp + "\n" + nonce;SHA256withECDSA DER 后 Base64;公钥为 EC SPKI DER Base64;时间窗 ±30s;nonce 一次性。
本机 OpenSSL 4.0.3 的 dgst -outform DER / pkeyutl 均不满足语义 ⇒ 改用 Python cryptography 并经 Java 21 权威验签对拍通过。
上线四闸门① approvalStatus=02 ② complianceStatus=01(envInfo + 严格 JSON 数组 ipWhitelist)③ 有效设备证书(certType=02,公钥与登记一致)④ deploymentStatus ∈ {UNMANAGED, READY},且 status=ONLINE
心跳超时heartbeatInterval(5s) × graceMultiplier(3) = 15s;停跳即 OFFLINE,主体随之从 CONNECTED 退回 JOINED ⇒ 验证期间必须持续保活
产品上架门槛6 项基础字段 + 定价 3 项 + deliveryInfo(varchar 64) + 资源编目 + 3 份声明清单 + 空间门户 f_portal_host + 主体 CONNECTED + 成员 DATA_PROVIDER(含 Publish) + 审核 PASS
三方协议--peers 必须含全部站点;密态端口自动 +1;--data-x 长度 = 行数 × 本方列数;只有 label-owner 能给 --data-y;seed 必须全体一致
+
+ +

5. 诚实边界(本次未做到,不粉饰)

+
+ + + + + + + + +
项状态说明 / 下一步
编排层自动驱动多方会话未做mpc-engine.ts 是单进程;容器缺 mpc 二进制(available=false、realExec=false),会话型算子按设计降级 simulation。本次真机计算由跨机点火脚本直接执行,再落库到编排。
解决:把 x86_64 musl 静态 mpc 放进镜像 + 按方拆进程 / 引入 agent 侧信道。
TEE guest 内闭环与芯片验签未做宿主端执行,PSK 走会话文件;KBS strict 已起但无 guest 提交真实 SNP 证明包。
链上存证回执链可达,未上链FISCO RPC 可用(块高 45),但编排 MPC_CHAIN_URL 指向同 Pod 回环 127.0.0.1:30100(该处无链容器),且缺 MPC_FISCO_CHAIN_CONFIG / 本地 mpc 二进制 ⇒ ChainBlock/List 为空。未伪造任何回执。
编排数据库持久化内存态MPC 编排 PGlite 默认 memory://,Pod 重启会清空 FlowRun / 设备同步结果。结构化证据已落本地 evidence/ 可重新落库。长期需设 PGLLITE_DIR(注意 NFS 上 PGlite 建表极慢)。
材料文件真实性清单占位产品 deliveryInfo 与 3 份声明是满足上架校验的 fileId 标识,未真实上传文件本体;TDC 数据源/资源为登记元数据,未挂真实业务库。
连接器长期在线靠本地保活当前由 heartbeat-keepalive.py 每 5s 心跳维持(已连续 280+ 次成功)。长期应由 TDC 实现心跳上报或 k8s 定时任务,否则停跳 15s 即 OFFLINE。
+
+ +

6. 复现入口

+
+
    +
  • build/verify-real-machine-3party.sh [psi|lr|all] — 三方真机分发 / 点火 / 回收日志(xop 取凭据,无明文口令)
  • +
  • build/record-real-run.mjs — 校验三方一致性并落库到编排(Flow/FlowRun/Artifact/RunEvent)
  • +
  • build/heartbeat-keepalive.py — 连接器心跳保活(--self-test 校验登录密文向量)
  • +
  • build/connector-online.sh — 审批 + 环境申报 + 证书 + 运维字段 + 签名心跳
  • +
  • build/publish-tds-product.sh — 企业级证书 / 门户 / 角色 / 产品上架(幂等,8/8)
  • +
  • build/verify-tds.sh · build/verify-mpc.sh — 平台与编排接口验收
  • +
  • evidence/real-3party-result.json — 结构化实测证据;real-psi-3party.log / real-lr-3party.log — 三台真机原始输出
  • +
+
+ +
报告生成:2026-11-12 · 所有数值来自本次实测输出与数据库回读,未使用模拟数据填充。
+
+ + diff --git a/evidence/armv7-ab-control.log b/evidence/armv7-ab-control.log new file mode 100644 index 0000000..b209cf3 --- /dev/null +++ b/evidence/armv7-ab-control.log @@ -0,0 +1,13 @@ +===== UPSTREAM : DIED elapsed=15s EXIT=100 FATAL=0 +--- stdout --- + +PostgreSQL stand-alone backend 17.5 +backend> --- stderr head --- +--- stderr tail --- +===== MINE : DIED elapsed=17s EXIT=100 FATAL=0 +--- stdout --- + +PostgreSQL stand-alone backend 17.5 +backend> --- stderr head --- +--- stderr tail --- +AB DONE diff --git a/evidence/armv7-stdout-matrix.log b/evidence/armv7-stdout-matrix.log new file mode 100644 index 0000000..e2cdef3 --- /dev/null +++ b/evidence/armv7-stdout-matrix.log @@ -0,0 +1,37 @@ +=========== CASE A-pipe-inherit =========== +redir: 2>/tmp/srv.log +elapsed=153s + +PostgreSQL stand-alone backend 17.5 +backend> sspf 0.5.0 已启动:http://127.0.0.1:30099(数据目录 /data/pg) +服务已停止(嵌入式 PostgreSQL 已优雅关闭)。 +inner_rc=124 +--- srv.log head --- +[demo-data] 官方示例数据导入完成(14255 条语句) +2026-11-13 01:51:23.267 UTC [10] FATAL: terminating connection due to administrator command +2026-11-13 01:51:23.274 UTC [10] LOG: shutting down +2026-11-13 01:51:23.867 UTC [10] LOG: d +--- srv.log bytes --- +22750 + +=========== CASE B-regular-file =========== +redir: > /tmp/srv.log 2>&1 +elapsed=36s +inner_rc=100 +--- srv.log head --- + +PostgreSQL stand-alone backend 17.5 +backend> +--- srv.log bytes --- +46 + +=========== CASE C-devnull =========== +redir: > /dev/null 2>/tmp/srv.log +elapsed=51s +inner_rc=100 +--- srv.log head --- + +--- srv.log bytes --- +0 + +=== ALL DONE === diff --git a/evidence/armv7-stdout-matrix.sh b/evidence/armv7-stdout-matrix.sh new file mode 100755 index 0000000..ca6b7f1 --- /dev/null +++ b/evidence/armv7-stdout-matrix.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# 复现 ssw/ssw-platform#1:armv7 sspf-admin 的 stdout 形态决定能否启动。 +# +# 用法: +# bash evidence/armv7-stdout-matrix.sh +# 或 SSPF_ADMIN= bash evidence/armv7-stdout-matrix.sh +# +# 严格单变量:stdout 类型是唯一变量;每个 case 一个全新容器、串行执行 +# (跑之前先 `docker ps` 清掉残留的 armv7 容器,否则 qemu 并发会污染结论)。 +# 判据:inner_rc=100 = 启动期崩溃;124/137 = 撑到 timeout 即已成功常驻。 +# +# 原始输出见同目录 armv7-stdout-matrix.log,结论与根因见 docs/issue-ssw-platform-armv7-stdout-exit100.md +set -u +BIN=${1:-${SSPF_ADMIN:-}} +if [ -z "$BIN" ]; then + echo "用法: $0 (或设 SSPF_ADMIN)" >&2 + exit 2 +fi +if [ ! -f "$BIN" ]; then + echo "找不到二进制: $BIN" >&2 + exit 2 +fi +BIN=$(cd "$(dirname "$BIN")" && pwd)/$(basename "$BIN") +IMG=${IMG:-arm32v7/debian:bookworm-slim} +PORT=${PORT:-30099} +OUT=${OUT:-/tmp/armv7-stdout-matrix} +mkdir -p "$OUT" + +run() { + tag="$1" + redir="$2" + echo "=========== CASE $tag ===========" + echo "redir: $redir" + t0=$(date +%s) + docker run --rm --platform linux/arm/v7 -v "$BIN:/sspf-admin:ro" "$IMG" \ + sh -c "cd /tmp; PGLITE_DIR=/data/pg PORT=$PORT timeout -k 5 150 /sspf-admin $redir; echo inner_rc=\$?; echo '--- srv.log head ---'; head -c 250 /tmp/srv.log 2>/dev/null; echo; echo '--- srv.log bytes ---'; wc -c < /tmp/srv.log 2>/dev/null" \ + > "$OUT/m-$tag.out" 2>&1 + echo "elapsed=$(($(date +%s)-t0))s" + head -20 "$OUT/m-$tag.out" + echo +} + +# A: stdout 继承 docker pipe(上游 docs/armv7-build.md:211 的原始验证方式) +run A-pipe-inherit "2>/tmp/srv.log" + +# B: stdout = 普通文件(上游 scripts/build-armv7.sh:137 的冒烟形态) +run B-regular-file "> /tmp/srv.log 2>&1" + +# C: stdout = /dev/null 字符设备(触发 ensure_stdout_for_pglite 的 S_IFCHR 分支) +run C-devnull "> /dev/null 2>/tmp/srv.log" + +echo "=== ALL DONE ===" diff --git a/evidence/real-3party-result.json b/evidence/real-3party-result.json new file mode 100644 index 0000000..82dba5c --- /dev/null +++ b/evidence/real-3party-result.json @@ -0,0 +1,145 @@ +{ + "verifiedAt": "2026-11-12T06:22:17.959Z", + "participants": [ + { + "site": "alice", + "host": "192.168.1.7", + "platform": "sev-snp", + "tcb": 5, + "rows": 120 + }, + { + "site": "bob", + "host": "192.168.1.102", + "platform": "hygon-csv", + "tcb": 3, + "rows": 102 + }, + { + "site": "carol", + "host": "192.168.1.233", + "platform": "none", + "tcb": 1, + "rows": 86 + } + ], + "psi": { + "intersection": 84, + "truth": 84, + "perSite": { + "alice": 84, + "bob": 84, + "carol": 84 + }, + "threeWayIdentical": true, + "matchedLocalTruth": true, + "ids": [ + 1010001, + 1010002, + 1010003, + 1010004, + 1010005, + 1010006, + 1010007, + 1010008, + 1010009, + 1010010, + 1020001, + 1020003, + 1020004, + 1020005, + 1020006, + 1020007, + 1020008, + 1020009, + 1020010, + 1030001, + 1030002, + 1030003, + 1030004, + 1030005, + 1030006, + 1030007, + 1030008, + 1030009, + 1030010, + 2010001, + 2010002, + 2010003, + 2010004, + 2010005, + 2010006, + 2010007, + 2010008, + 2010009, + 2010010, + 2020002, + 2020003, + 2020004, + 2020006, + 2020007, + 2020008, + 2020009, + 2020010, + 2030001, + 2030002, + 2030004, + 2030005, + 2030006, + 2030007, + 2030009, + 2030010, + 3010001, + 3010003, + 3010004, + 3010005, + 3010006, + 3010007, + 3010008, + 3010010, + 3020001, + 3020002, + 3020003, + 3020004, + 3020005, + 3020006, + 3020008, + 3020009, + 3020010, + 3030002, + 3030003, + 3030004, + 3030005, + 3030006, + 3030007, + 3030008, + 3030009, + 4010002, + 4010003, + 4010004, + 4010005 + ] + }, + "lr": { + "weights": { + "w[0]": 0.3898658752441406, + "w[1]": 0.02921295166015625, + "w[2]": 0.01927947998046875, + "w[3]": -0.03290557861328125 + }, + "threeWayBitIdentical": true, + "epochs": 20, + "learningRate": 0.05, + "colBlocks": "alice:0:1,bob:1:1,carol:2:1", + "labelOwner": "alice", + "dTotal": 3, + "alignedRows": 84 + }, + "execution": { + "mode": "真机跨机密态网状会话(宿主端二进制)", + "channel": "PSI 9449 / 密态 9450(bump_port +1)", + "startOrder": "carol → bob → alice(party 编号按站点名字典序,小编号主动连大编号)", + "teeGuest": false, + "orchestrationDriven": false + } +} \ No newline at end of file diff --git a/evidence/real-lr-3party.log b/evidence/real-lr-3party.log new file mode 100644 index 0000000..9016221 --- /dev/null +++ b/evidence/real-lr-3party.log @@ -0,0 +1,67 @@ +=================== 三方 lr 实测 =================== + WARN NetworkGuard.setup() is STUBBED — policy parsed but not enforced allow=[] deny=[] + WARN FileGuard.setup() is STUBBED — policy parsed but not enforced deny=["/proc/self/environ", "/proc/*/environ", "~/.ssh/id_*", "~/.ssh/known_hosts", "~/.aws/credentials", "~/.config/gh/hosts.yml", "~/.netrc", "~/.docker/config.json"] +[AMD] payload ok +[HG] payload ok +[ZY] payload ok +FIRED-CAROL +FIRED-BOB +FIRED-ALICE +三方均出结果 (1x2s) +----- lr/alice ----- +mpc lr-vertical · site=alice(1/3)· 120 行 × 3 列 + 本方列块 [0, 1) · 标签方 alice · 20 轮 · lr=0.05 + [PSI] 建立网状连接(3 方,本方 0 号)... + [PSI] 已连接 + [密态] 建立网状连接(3 方,本方 0 号)... + [密态] 已连接 + 本方 alice(1/3)有 120 个 ID + 第 1/3 跳完成(86 个点) + 第 2/3 跳完成(102 个点) + 交集 84 条(原始下标已还原) + PSI 交集 84 条 + 对齐后 84 行 + 特征拼接完成 (84 行 × 3 列, 3 块) + y 分片交换完成 + 开始训练 (20 轮, lr=0.05, d_total=3) + 训练完成 +{"kind":"table","title":"纵向会话","header":["key","value"],"rows":[["aligned_rows",84],["col_blocks","alice,bob,carol"]]} +{"kind":"table","title":"训练权重(4 个)","header":["权重","值"],"rows":[["w[0]",0.3898658752441406],["w[1]",0.02921295166015625],["w[2]",0.01927947998046875],["w[3]",-0.03290557861328125]]} +----- lr/bob ----- +mpc lr-vertical · site=bob(2/3)· 102 行 × 3 列 + 本方列块 [1, 2) · 标签方 alice · 20 轮 · lr=0.05 + [PSI] 建立网状连接(3 方,本方 1 号)... + [PSI] 已连接 + [密态] 建立网状连接(3 方,本方 1 号)... + [密态] 已连接 + 本方 bob(2/3)有 102 个 ID + 第 1/3 跳完成(120 个点) + 第 2/3 跳完成(86 个点) + 交集 84 条(原始下标已还原) + PSI 交集 84 条 + 对齐后 84 行 + 特征拼接完成 (84 行 × 3 列, 3 块) + y 分片交换完成 + 开始训练 (20 轮, lr=0.05, d_total=3) + 训练完成 +{"kind":"table","title":"纵向会话","header":["key","value"],"rows":[["aligned_rows",84],["col_blocks","alice,bob,carol"]]} +{"kind":"table","title":"训练权重(4 个)","header":["权重","值"],"rows":[["w[0]",0.3898658752441406],["w[1]",0.02921295166015625],["w[2]",0.01927947998046875],["w[3]",-0.03290557861328125]]} +----- lr/carol ----- +mpc lr-vertical · site=carol(3/3)· 86 行 × 3 列 + 本方列块 [2, 3) · 标签方 alice · 20 轮 · lr=0.05 + [PSI] 建立网状连接(3 方,本方 2 号)... + [PSI] 已连接 + [密态] 建立网状连接(3 方,本方 2 号)... + [密态] 已连接 + 本方 carol(3/3)有 86 个 ID + 第 1/3 跳完成(102 个点) + 第 2/3 跳完成(120 个点) + 交集 84 条(原始下标已还原) + PSI 交集 84 条 + 对齐后 84 行 + 特征拼接完成 (84 行 × 3 列, 3 块) + y 分片交换完成 + 开始训练 (20 轮, lr=0.05, d_total=3) + 训练完成 +{"kind":"table","title":"纵向会话","header":["key","value"],"rows":[["aligned_rows",84],["col_blocks","alice,bob,carol"]]} +{"kind":"table","title":"训练权重(4 个)","header":["权重","值"],"rows":[["w[0]",0.3898658752441406],["w[1]",0.02921295166015625],["w[2]",0.01927947998046875],["w[3]",-0.03290557861328125]]} diff --git a/evidence/real-psi-3party.log b/evidence/real-psi-3party.log new file mode 100644 index 0000000..bb4d8e1 --- /dev/null +++ b/evidence/real-psi-3party.log @@ -0,0 +1,37 @@ +=================== 三方 psi 实测 =================== + WARN NetworkGuard.setup() is STUBBED — policy parsed but not enforced allow=[] deny=[] + WARN FileGuard.setup() is STUBBED — policy parsed but not enforced deny=["/proc/self/environ", "/proc/*/environ", "~/.ssh/id_*", "~/.ssh/known_hosts", "~/.aws/credentials", "~/.config/gh/hosts.yml", "~/.netrc", "~/.docker/config.json"] +[AMD] payload ok +[HG] payload ok +[ZY] payload ok +FIRED-CAROL +FIRED-BOB +FIRED-ALICE +三方均出结果 (1x2s) +----- psi/alice ----- +mpc psi · site=alice(1/3)· 120 个 ID + [PSI] 建立网状连接(3 方,本方 0 号)... + [PSI] 已连接 + 本方 alice(1/3)有 120 个 ID + 第 1/3 跳完成(86 个点) + 第 2/3 跳完成(102 个点) + 交集 84 条(原始下标已还原) +{"kind":"table","title":"交集 84 条","header":["id"],"rows":[[1010001],[1010002],[1010003],[1010004],[1010005],[1010006],[1010007],[1010008],[1010009],[1010010],[1020001],[1020003],[1020004],[1020005],[1020006],[1020007],[1020008],[1020009],[1020010],[1030001],[1030002],[1030003],[1030004],[1030005],[1030006],[1030007],[1030008],[1030009],[1030010],[2010001],[2010002],[2010003],[2010004],[2010005],[2010006],[2010007],[2010008],[2010009],[2010010],[2020002],[2020003],[2020004],[2020006],[2020007],[2020008],[2020009],[2020010],[2030001],[2030002],[2030004],[2030005],[2030006],[2030007],[2030009],[2030010],[3010001],[3010003],[3010004],[3010005],[3010006],[3010007],[3010008],[3010010],[3020001],[3020002],[3020003],[3020004],[3020005],[3020006],[3020008],[3020009],[3020010],[3030002],[3030003],[3030004],[3030005],[3030006],[3030007],[3030008],[3030009],[4010002],[4010003],[4010004],[4010005]]} +----- psi/bob ----- +mpc psi · site=bob(2/3)· 102 个 ID + [PSI] 建立网状连接(3 方,本方 1 号)... + [PSI] 已连接 + 本方 bob(2/3)有 102 个 ID + 第 1/3 跳完成(120 个点) + 第 2/3 跳完成(86 个点) + 交集 84 条(原始下标已还原) +{"kind":"table","title":"交集 84 条","header":["id"],"rows":[[1010001],[1010002],[1010003],[1010004],[1010005],[1010006],[1010007],[1010008],[1010009],[1010010],[1020001],[1020003],[1020004],[1020005],[1020006],[1020007],[1020008],[1020009],[1020010],[1030001],[1030002],[1030003],[1030004],[1030005],[1030006],[1030007],[1030008],[1030009],[1030010],[2010001],[2010002],[2010003],[2010004],[2010005],[2010006],[2010007],[2010008],[2010009],[2010010],[2020002],[2020003],[2020004],[2020006],[2020007],[2020008],[2020009],[2020010],[2030001],[2030002],[2030004],[2030005],[2030006],[2030007],[2030009],[2030010],[3010001],[3010003],[3010004],[3010005],[3010006],[3010007],[3010008],[3010010],[3020001],[3020002],[3020003],[3020004],[3020005],[3020006],[3020008],[3020009],[3020010],[3030002],[3030003],[3030004],[3030005],[3030006],[3030007],[3030008],[3030009],[4010002],[4010003],[4010004],[4010005]]} +----- psi/carol ----- +mpc psi · site=carol(3/3)· 86 个 ID + [PSI] 建立网状连接(3 方,本方 2 号)... + [PSI] 已连接 + 本方 carol(3/3)有 86 个 ID + 第 1/3 跳完成(102 个点) + 第 2/3 跳完成(120 个点) + 交集 84 条(原始下标已还原) +{"kind":"table","title":"交集 84 条","header":["id"],"rows":[[1010001],[1010002],[1010003],[1010004],[1010005],[1010006],[1010007],[1010008],[1010009],[1010010],[1020001],[1020003],[1020004],[1020005],[1020006],[1020007],[1020008],[1020009],[1020010],[1030001],[1030002],[1030003],[1030004],[1030005],[1030006],[1030007],[1030008],[1030009],[1030010],[2010001],[2010002],[2010003],[2010004],[2010005],[2010006],[2010007],[2010008],[2010009],[2010010],[2020002],[2020003],[2020004],[2020006],[2020007],[2020008],[2020009],[2020010],[2030001],[2030002],[2030004],[2030005],[2030006],[2030007],[2030009],[2030010],[3010001],[3010003],[3010004],[3010005],[3010006],[3010007],[3010008],[3010010],[3020001],[3020002],[3020003],[3020004],[3020005],[3020006],[3020008],[3020009],[3020010],[3030002],[3030003],[3030004],[3030005],[3030006],[3030007],[3030008],[3030009],[4010002],[4010003],[4010004],[4010005]]}