108 lines
16 KiB
Markdown
108 lines
16 KiB
Markdown
# b03g 掃描筆記:pty / x11 / wl / portal / desk / landlock / win / egress
|
||
|
||
掃描日期:2026-02-08。只記代碼觀察事實。
|
||
|
||
## pty.rs(195 行)— 互動終端機
|
||
|
||
- 常數:`ROWS=40`、`COLS=120`、`SCROLLBACK=2000`。
|
||
- `Screen{parser: Mutex<vt100::Parser>, writer: Mutex<Box<dyn Write>>, _master: Mutex<Box<dyn MasterPty>>, bytes: AtomicU64, last_ms: AtomicU64, born: Instant}`。`_master` 必須留著(關掉控制端會掛斷程式)。
|
||
- `text()`:去尾空行、去每行尾空白、連續空行併成一行(全螢幕程式填滿 40 行,空行佔掉_bot 讀到的大部分)。
|
||
- `spawn(command)`:portable_pty native_pty_system,PtySize 40×120;把 Command 的 program/args/envs(含 env_remove)/cwd 全部搬進 CommandBuilder;`TERM=xterm-256color`、`env_remove("NO_COLOR")`;spawn 後 `drop(pair.slave)`(程式結束時讀端才看到結束);讀執行緒 8192 chunk → parser.process + bytes += + last_ms。
|
||
- `key(name)`:名字正規化(小寫、_和空白→-);enter/tab/shift-tab(`\x1b[Z`)/esc/backspace(`\x7f`)/delete(`\x1b[3~`)/space/方向/home/end/pageup(`\x1b[5~`)/pagedown;`ctrl-字母`→1–26。未知名字回給可用鍵清單的錯誤。
|
||
- `settle(screen, since, max, quiet, until, ended, stop)`:輪詢 50ms;`until` 非空→看文字含它;否则 bytes 增加且 quiet_for≥quiet 才算定;ended/stop 先睡 120ms 再回(最後寫的到達畫面);max 到即回。
|
||
- 普通命令不來這裡:tools::run_command 關掉 input(讀到 EOF 的程式會結束不會死等)。
|
||
|
||
## x11.rs(568 行)— X11 看與操
|
||
|
||
- `CONN: Mutex<Option<X{conn, root, width, height}>>`;`with()` 懒連 `x11rb::connect(None)`;回 None 時用 get_input_focus 探活,死了設回 None 下次重連(X server 重啟情境)。
|
||
- `capture()`:GetImage Z_PIXMAP 整個 root;depth 對 pixmap_formats 找 bpp,`bpp!=32` 直接失败;LSB_FIRST→[px2,px1,px0],否則[px1,px2,px3]。失败訊息点名 Wayland 要選 Xorg。
|
||
- 全部輸入走 XTEST `xtest_fake_input(kind, detail, 0, root, px, py, 0)`;`flush()`=flush+get_input_focus roundtrip;`gap()=8ms`。
|
||
- click/drag/scroll 用 computer 共用常數(CLICK_REPEAT_GAP_SECS/CLICK_HOLD_SECS/DRAG_HOLD_SECS/SCROLL_PIXELS_PER_STEP/drag_points)。滾輪=按鈕 4/5(垂直)、6/7(水平),每格 12ms。
|
||
- `modifier_keysyms`:⌘(FLAG_CMD)和 ⌃ 都→XK_CONTROL_L(Linux 上 ⌘C=Ctrl+C);⇧→XK_SHIFT_L;⌥→XK_ALT_L。
|
||
- `keysym_of_mac_code`:30 條命名表(36→0xff0d…F1-12 0xffbe~0xffc9);其他字母數字標點用 `computer::key_code` 反查字元。
|
||
- `type_text`:找空 keycap(由鍵盤映射尾部往回找全 0 的 keycode)→每字元 change_keyboard_mapping 貼上符號、壓放(12/8/8ms),最後還原全 0。已修踩坑:早期 `?` 提前离开會把字元永久黏在真實鍵上——現在失敗 break 後照樣還原。
|
||
- 視窗:`_NET_CLIENT_LIST_STACKING`(空則 query_tree children)反轉=從前到後;map_state VIEWABLE 且 >1×1 才算。app_of:WM_CLASS class 最後段,無則 `/proc/{pid}/comm`;pid 從 `_NET_WM_PID`。front_app 用 `_NET_ACTIVE_WINDOW`。
|
||
- _idle/screensaver:MIT-SCREEN-SAVER query_info(ms_since_user_input;state==1=黑屏)。
|
||
- `record()`(RECORD 擴充,示範錄输入):兩條連線(ctrl+data,RECORD 需要專聽的);range KEY_PRESS..BUTTON_PRESS;32 位元組事件解析:滑鼠座標 ev[20..23]、keycode→keysym 查映射(level0/1,Shift 取 shifted);mods 位元 1 shift/4 ctrl/8 alt/64 super。 watchdog 執行緒 150ms 輪詢 keep_going→disable+free context。已修踩坑兩個:enable 失敗必須停 watchdog(舊碼永久空轉抱著 X 連線);串流斷掉要先發 stop 再 join(舊碼等一個永遠輪詢的執行緒=整個凍住)。
|
||
- 測試:`keys_map_to_x`;`x11_live` #[ignore](Xvfb :99,錄到 Click/text/keysym mods=4/Scroll)。
|
||
|
||
## wl.rs(669 行)— wlroots Wayland 原生協定
|
||
|
||
- 協定:wlr-screencopy(截圖)、wlr-virtual-pointer(滑鼠)、zwp virtual-keyboard(鍵盤)、wlr-foreign-toplevel(視窗)、ext-idle-notify(空閒)。sway/Hyprland/river/labwc/Wayfire 有;GNOME/KDE 沒有(走 portal)。
|
||
- `WL: Mutex<Option<Wl>>`;connect:bind shm v1、seat v1、copy v1..=3(記 version)、pointer mgr v1..=2、kb mgr v1、xdg-output 與 tops 可選;bind 所有 wl_output(v≤4)+ xdg-output;roundtrip×2;outs 空→None。
|
||
- `set_read_timeout(fd, SO_RCVTIMEO, 60s)`:已修踩坑——compositor 不回話時 blocking_dispatch 在全域 Wayland 鎖裡永久卡住(所有畫面動作連 UI 全凍);逾時讀錯誤→連線當死、下次重建。
|
||
- `MODS` 常數:前 4 鍵=Shift/Control/Mod1/Mod4 keysyms + xkb 位元 1/4/8/64。
|
||
- `scratch_file(len)`:**memfd_create("anybot-wl")**優先,fallback XDG_RUNTIME_DIR `create_new`+立刻 unlink;`reserve()`=posix_fallocate(EOPNOTSUPP/EINVAL 時手寫 1MB 零塊迴圈)。已修踩坑:舊版放 /run/user 的檔案,空間爆掉時是 **compositor 收 SIGBUS 整個 Hyprland 桌面倒下**。memfd 让截圖在此處失败而已。
|
||
- `keymap_text(keys)`:自製 xkb keymap,一鍵一 keysym,前四是 modifier_map。`key_for`:新 keysym 附加上傳(>200 鍵截斷回 4),roundtrip。→任何字元(含中文)直接打,如 wtype。
|
||
- 截圖:每 output capture_output;**frame.destroy() 必過**(已修:失敗路徑曾每次洩漏 compositor 端物件);grab 死線 5s;SHM pool/buffer 用 scratch_file(stride*h);memmap2 讀→`to_rgba`(Xrgb/Argb=BGRX、Xbgr/Abgr=RGBX;y_invert 反行;**byte 運算用 usize:極高解析度 u32 乘積在 debug build panic**)。多螢幕拼成 canvas(pixel_scale=max scale、Resize Triangle、replace)。
|
||
- 滑鼠:motion_absolute(clamp 到 layout,w-1/h-1)+frame;按鈕 code 0x110/0x111/0x112;wheel axis_discrete `-15.0*n, -n`。
|
||
- `type_text`:用 `x11::keysym_for_char`,8ms 按放。front_app:tops 中 active 且 app 非空(app_id,pid 恆 0)。
|
||
- 閒置:`IDLE: Mutex<Option<Option<Instant>>>` + Once 起執行緒 **loop 重連**(已修:舊版斷一次就永久退出,idle_secs 永遠瞎);**get_idle_notification 回值必須活著**(wayland-client 最後句柄掉=物件消,丟掉回值→Idled 事件永遠不來、idle_secs 永遠 0)。
|
||
- 測試:keymap_and_pixels;`screenshot_buffer_is_allocated_up_front`(st_blocks≥len、/proc/self/fd 指 /memfd:)。
|
||
|
||
## portal.rs(375 行)— GNOME/KDE 桌面 portal(ashpd)
|
||
|
||
- RemoteDesktop+Screencast+Screenshot portal。第一次系統問人(「AnyBot 想操作你的畫面」),restore token 存 `<資料夾父層>/wayland-remote-token.txt`,之後不再問(portal v2+;Ubuntu 22.04 這類舊桌面每次起始都問)。
|
||
- 鎖:`LIVE`、`LAST_ERROR`、**`ENSURE`(已修踩坑:兩個並發 ensure() 開兩個 portal session,先結束的那個清掉第二個的 LIVE→畫面全瞎)**;`NEXT_SESSION` id:只有當前 id 的執行緒能退 LIVE slot。
|
||
- ensure 流程:create_session→select_devices(Keyboard|Pointer, v2 加 PersistMode::ExplicitlyRevoked+restore_token)→screencast select_sources(Monitor, multiple)→start。人拒→「你在系統視窗裡沒有允許…」;**GNOME 的「允許遠端操作」開關預設關**:res.devices 缺 Pointer/Keyboard→關 session+指定話術(先打開再按分享)。restore_token 寫檔;screens=streams 的 PipeWire node+position/size;空→「系統沒有給 AnyBot 任何螢幕」。
|
||
- ready_rx.recv_timeout **120s**→「等太久了,系統的允許視窗沒有回應」。
|
||
- **GNOME 丟棄新虛擬鍵盤的第一個事件**:起手 Shift 按放(無可見效果)+150ms。
|
||
- 服務迴圈:rx.recv 逐條發;**motion 發兩次**(新虛擬指標會漏第一次移動,點擊絕不能落在舊位置)。`send()` 每條後睡 4ms(保按放次序)。
|
||
- capture:Screenshot.request interactive(false) modal(false)→file:// URI(% 解碼)→image::open→**刪掉桌面存的檔**(它只為 bot 用);PIXELS 快取dims。
|
||
- type_text:typable(\n、\t、空格~波浪號)直接 tap;其他字元(中文)→**剪貼簿+Ctrl+V**:wl-paste 存舊 mime+bytes→wl-copy→0xffe3 按住+tap 0x76→60/250ms→還原舊 mime 或 --clear。缺 wl-clipboard→LAST_ERROR「要打中文需要 wl-clipboard(sudo apt install wl-clipboard)」。
|
||
|
||
## desk.rs(323 行)— Linux 畫面統一门面
|
||
|
||
- `Kind{X11,Wlr,Portal,None}` OnceLock 一次決定:`ANYBOT_DESK=x11` 可強制;WAYLAND_DISPLAY 有→wl 優先、portal 次之;否则 x11。
|
||
- `describe()`:每 Kind 給 bot/設定頁話術(Portal 講兩個第一次視窗;None+Wayland 教裝 xdg-desktop-portal-gnome/kde 或改選 Xorg)。
|
||
- capture/screen_points/screen_pixels 按 Kind 分派;X11 的 click/drag/scroll/press/move_to 直走 x11,Wayland 用 motion/button/key/wheel 原語重組(同樣用 computer 常數與 with_mods=x11::modifier_keysyms)。
|
||
- window_at:只有 X11 能答(Wayland 不給視窗位置);front_app X11/Wlr。
|
||
- `program_of(pid)`:/proc/{pid}/exe file_name,trim「 (deleted)」(Snap firefox_firefox→firefox)。
|
||
- `accessibility_switched_on()`:zbus org.a11y.Bus Status IsEnabled Off→On 回 true(沒開多數 app 不給控件=bot 拿不到編號)。
|
||
- idle_secs:X11 直;Wayland GNOME `org.gnome.Mutter.IdleMonitor.GetIdletime`→wl::idle_secs。
|
||
- screensaver_on:GNOME `org.gnome.ScreenSaver.GetActive`→freedesktop `org.freedesktop.ScreenSaver.IsActive` at `/ScreenSaver`。已修踩坑:舊 fallback 問的路徑/方法根本不存在→KDE 上永遠答「螢幕是空的」。
|
||
|
||
## landlock.rs(432 行)— Linux 指令沙盒(R6)
|
||
|
||
- `ARG="__anybot_sandbox"`:macOS 用 sandbox-exec,Linux 沒有——指令由 `/proc/self/exe __anybot_sandbox -h… -C… -- /bin/sh -c 指令` 啟動:自我封鎖後 exec 成 shell(pty 互動終端也一起封,pty 只複製程式+參數)。
|
||
- access 16 位元;`handled(abi)`:v2+REFER、v3+TRUNCATE、v5+IOCTL_DEV。READ=EXECUTE|READ_FILE;WRITE=13 位元;FILE_ONLY=5 位元(檔案規則只能帶這些)。
|
||
- Landlock 只能「允許」→**macOS 拒絕的,從允許裡留掉**:保護資料夾沿途每項逐一允許、保護那項跳過。後果(註解明言):家目錄/~/.config/~/.local/share 最上層不能新增(裡面的其他資料夾可以);工作區 .git/hooks 保持可寫(macOS 是拒的)。
|
||
- `Spec{hidden, readable, no_write, work}`;to_args/from_args `-h/-r/-w/-C`+`--` 往返(from_args 缺 --/缺路徑/看不懂 flag 皆錯)。
|
||
- `real()`:canonicalize;不存在則遞迴父層 join name。`around(dir, avoid)`:symlink 跳過;沿途 dir 遞迴;其餘整項 grant。
|
||
- `plan(spec, abi)`:`/`=READ_DIR(列名字處處可以);READ 環绕 hidden;WRITE 環绕 hidden+no_write;work **whole** 條件=沒有 hidden 嵌套其中(家目錄當工作區時 ~/.ssh 在內→逐項);readable 只有「在 hidden 內且存在」才加(附件、~/.ssh 唯讀);no_write 中落在 whole work 內的被剔掉;規則 `r & handled & (dir?全:FILE_ONLY)`,0 濾掉。
|
||
- `helper()`=/proc/self/exe;**cfg!(test) 時=test runner 不能當沙盒,指令不包,除非設 ANYBOT_TEST_SANDBOX_EXE**。
|
||
- `abi()` OnceLock 一次;無 Landlock(<5.13 或未開 /sys/kernel/security/lsm)→`NONE` 話術給 /doctor+log,**指令照跑不假裝有沙盒**。`active()`=linux+abi+helper。`wrap()`:inactive 或 hidden 空→None(照舊跑);路徑先 std::path::absolute。
|
||
- `run_helper`:任何一步失敗→**exit 126,絕不在沒沙盒的情況下跑**;restrict 成功→exec 程式(exec 失敗 exit 127)。`NOTE`:指令失敗時給 bot 的沙盒說明全文。
|
||
- sys:landlock_create_ruleset/add_rule(PathBeneath packed+O_PATH fd)/restrict_self + PR_SET_NO_NEW_PRIVS。
|
||
- 測試:plan 逐案(state.json HIDDEN、attachments 唯讀、.bashrc 唯讀、work 整區可寫含 .git/hooks、~/.gnupg 不存在不能造);abi 截斷;args 往返;**landlock_keeps_a_command_out**(真線程 restrict 後 sh 五條:HIDDEN/photo/KEPT/hi/WROTE)。
|
||
|
||
## win.rs(303 行,`#![cfg(target_os="windows")]`)— Windows 手眼
|
||
|
||
- 滑鼠鍵盤=SendInput;截圖=GDI BitBlt+GetDIBits(biHeight -h=由上往下;32bpp → put_pixel [i+2,i+1,i]);控件樹來自 agent-desktop-windows(elements() 語言同 macOS accessibility)。
|
||
- `norm()`:SM_CXSCREEN/SM_CYSCREEN 單螢幕 →0..65535(多螢幕虛擬邊界「以後」——未實作,記為事實)。
|
||
- `keys(unicode)`:KEYEVENTF_UNICODE 按+放成對。已修踩坑:字元曾「down 發兩次、沒有 up」→每個字打兩次。
|
||
- `vk_of`:66 條 mac code→VK 表;無對應=0(press 直接 return)。
|
||
- `modifiers(flags)` 用 Windows 自己的位元:0x20000=shift(0x10)、0x40000=ctrl(0x11)、0x80000=alt(0x12)、0x100000=win(0x5B)——與 computer 的 FLAG_* 數值不同,是 win.rs 本地定義。`holding()` 滑鼠動作期間按住(已修:舊版丟掉 modifier,shift-click/ctrl-scroll 全變普通動作)。
|
||
- click:down/up 中間 30ms、連點間 80ms(**硬編碼,未用 computer 常數**——x11/desk 用了,win 沒用,記為平台差異事實)。drag:逐點 20ms。scroll:`pixels/SCROLL_PIXELS_PER_STEP*120`;已修踩坑:dy/dx 曾讀反且垂直被丟(上下沒反應、左右滾上下)。
|
||
- window_at:WindowFromPoint→GetWindowThreadProcessId;名=視窗標題,空則 process_name(QueryFullProcessImageNameW 的 file_stem)。front_app=GetForegroundWindow 同邏輯。
|
||
- `screen_capture_allowed()/screen_capture_preflight()` 恆 true。
|
||
|
||
## egress.rs(326 行)— 「網路流量改走你的電腦」
|
||
|
||
- 本機 Mac/Linux 上的小 HTTP/HTTPS proxy,給雲端 boxes 的指令經 HTTP(S)_PROXY 出口(原設計 8791 端口、僅新連線生效、管理者可關)。`PORT=8791`,被占則找 PORT..PORT+20;HEAD_MAX=64KB;RUNNING/BOUND/CONNECTIONS 原子。
|
||
- `bind_addrs()`:127.0.0.1 + Linux 各 Docker bridge 閘道位址(`ip -o -4 addr show` 解析);`bridge_iface`=docker0/docker_gwbridge/`br-<12 hex>`(用戶 br-lan 不算);只有 172.16–31 前綴記進 BOUND_PREFIXES。**絕不綁 0.0.0.0**(開放 LAN proxy=開門)。無 `ip` 指令→只留 loopback,讓 box 指令失败、請人關設定(比靜默服整個 LAN 好)。
|
||
- `allowed_peer`(第二道牆):loopback、172.17.0.0/16、本程序啟動時綁過的 br-* 前綴;172.16-31 其餘(常是企業 LAN)不服。
|
||
- `route()`:CONNECT host:port→tunnel;`GET http://host[:port]/path` 絕對形式→改寫成 path 請求 preamble,丟 hop-by-hop(Proxy-Connection/Proxy-Authorization);其他 scheme→錯。
|
||
- `handle_with(public_only)`:host==localhost 或 `.localhost` 尾→403;解析後**任何一個位址非 public(web::public_addr:loopback/LAN/169.254.169.254)→403**(不讓 box 拐回本機服務、NAS、雲 metadata=SSRF 閘)。已修踩坑:plain TcpStream::connect 死位址掛 ~2 分鐘、排隊的 box 請求全堆在後面→改 connect_timeout 10s + 502。
|
||
- 隧道:200 Connection established;head 之後的位元組先轉;雙向 io::copy(上行開執行緒);**兩端讀逾時 30 分鐘**(已修:死對端曾永久釘住 copy 迴圈和執行緒)。400/502 回應。
|
||
- 測試:binds_bridge_gateways(eth0/virbr0 不是 Docker 的)、routes、proxies_real_request(真 listener 對 127.0.0.1/localhost/169.254.169.254/192.168 全 403;handle_with(…,false) 測本地 origin 轉發)、only_this_machine_and_containers。
|
||
|
||
## 遷徙對應(b03g)
|
||
|
||
- pty.rs → `platform::exec::pty`
|
||
- x11.rs、wl.rs、portal.rs、desk.rs → `platform-linux`(desk 是门面;x11::keysym_for_char/modifier_keysyms 被 wl/portal 共用,留 platform-linux 公開)
|
||
- landlock.rs → `platform-linux::sandbox`(與 macOS sandbox-exec 同在一個 `platform::exec` 沙盒層下)
|
||
- win.rs → `platform-win`
|
||
- egress.rs → `net::egress`(依賴 `web::public_addr`→隨 b03d 進 `core::net_rules`)
|
||
- computer 共用時序常數(CLICK_HOLD/DRAG_HOLD/SCROLL_PIXELS_PER_STEP/drag_points)被 x11/desk 使用 → 隨 b03b 進 `platform::exec::screen_act`,Windows 硬編碼差異如上述保留原樣(純搬不修)。
|