fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證
第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
413aab7d19
commit
afb1bff057
|
|
@ -501,7 +501,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
|
||||||
- **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。
|
- **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。
|
||||||
- **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。
|
- **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。
|
||||||
- **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。
|
- **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。
|
||||||
- **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己和 Tailscale(100.x,本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。
|
- **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。
|
||||||
|
- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi 自己就發這一段。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http;帳號伺服器用 http:// 時,要它的位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去,才把帳號密碼送過去(不然要 https://)。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。
|
||||||
- **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,6 位配對碼後面多一段密鑰(`135790-abc…`)。密鑰只在兩台電腦上,不會傳給帳號伺服器;之後大腦給這台手腳的每個指令都帶簽章(綁定是哪台電腦、時間、只能用一次),手腳驗不過就拒絕。所以帳號伺服器(或攻進去的人)不能自己造指令、也不能重放。用手機產生的配對碼、或是當「另一個大腦的螢幕」時產生的,沒有密鑰(跟以前一樣,沒有簽章)。舊版 AnyBot 讀到新格式只取 6 位數字,照舊配對。
|
- **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,6 位配對碼後面多一段密鑰(`135790-abc…`)。密鑰只在兩台電腦上,不會傳給帳號伺服器;之後大腦給這台手腳的每個指令都帶簽章(綁定是哪台電腦、時間、只能用一次),手腳驗不過就拒絕。所以帳號伺服器(或攻進去的人)不能自己造指令、也不能重放。用手機產生的配對碼、或是當「另一個大腦的螢幕」時產生的,沒有密鑰(跟以前一樣,沒有簽章)。舊版 AnyBot 讀到新格式只取 6 位數字,照舊配對。
|
||||||
- **更新要驗簽章**:`make sign-setup`(作者做一次)讓之後每個 commit 用 SSH 金鑰簽章,公鑰記在 `deploy/allowed_signers`。安裝時把它記到原始碼資料夾外面(`~/.config/anybot/allowed_signers`);之後 `make update`/重跑安裝腳本,新版不是那把金鑰簽的就不裝(Mac、Linux、Windows 都一樣)。換金鑰:用舊金鑰簽一個把新公鑰加進名單的 commit。確定要跳過一次:`ANYBOT_UNSIGNED=1`。還沒有 `deploy/allowed_signers` 時跟以前一樣不檢查。
|
- **更新要驗簽章**:`make sign-setup`(作者做一次)讓之後每個 commit 用 SSH 金鑰簽章,公鑰記在 `deploy/allowed_signers`。安裝時把它記到原始碼資料夾外面(`~/.config/anybot/allowed_signers`);之後 `make update`/重跑安裝腳本,新版不是那把金鑰簽的就不裝(Mac、Linux、Windows 都一樣)。換金鑰:用舊金鑰簽一個把新公鑰加進名單的 commit。確定要跳過一次:`ANYBOT_UNSIGNED=1`。還沒有 `deploy/allowed_signers` 時跟以前一樣不檢查。
|
||||||
- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫。Bot 工作時每兩秒存一次的不再是整份幾十 MB;刪掉 Bot 時它的聊天檔一起刪。舊版存的(聊天在 state.json 裡)照樣讀得進來,下次存檔就分開。
|
- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫。Bot 工作時每兩秒存一次的不再是整份幾十 MB;刪掉 Bot 時它的聊天檔一起刪。舊版存的(聊天在 state.json 裡)照樣讀得進來,下次存檔就分開。
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,8 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的
|
||||||
|
|
||||||
- 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。
|
- 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。
|
||||||
- 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。
|
- 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。
|
||||||
- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback)和從 Tailscale 連到這台 Tailscale 通道位址的——看的是連到哪個介面,不是來源位址像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。
|
- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。
|
||||||
|
- 帳號伺服器用 `http://` 時,只有這台電腦、Docker 網路裡的名字,或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」才會把帳號密碼送過去;其他(包括 Wi-Fi 上的 100.x)要 `https://`。
|
||||||
|
|
||||||
## 已知限制(誠實清單)
|
## 已知限制(誠實清單)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
## 子功能
|
## 子功能
|
||||||
|
|
||||||
- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。
|
- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、Docker 網路裡的名字,或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。
|
||||||
- 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。
|
- 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。
|
||||||
- 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。
|
- 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。
|
||||||
- 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。
|
- 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。
|
||||||
|
|
@ -41,8 +41,8 @@
|
||||||
- App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。
|
- App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。
|
||||||
- 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。
|
- 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。
|
||||||
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
|
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
|
||||||
- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線。`ANYBOT_PHONE_PORT` 換起始的連接埠。
|
- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。
|
||||||
- 讀不到網路介面的電腦(Windows)認不出 Tailscale 通道:用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。
|
- Tailscale 通道從 ifconfig、ip -o addr(Linux)、ipconfig(Windows,看名字有 Tailscale 的介面卡)認;認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。
|
||||||
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
|
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
|
||||||
- 換手機密碼會把所有直接連線的手機登出。
|
- 換手機密碼會把所有直接連線的手機登出。
|
||||||
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。
|
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。
|
||||||
|
|
|
||||||
|
|
@ -6599,12 +6599,8 @@ impl App {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
app.serve_join();
|
app.serve_join();
|
||||||
|
// (「手機可以打開 …」 is logged by remote::set_lan once the phone page is listening.)
|
||||||
app.background(ctx);
|
app.background(ctx);
|
||||||
if let Some(port) = crate::remote::lan_port() {
|
|
||||||
for a in crate::remote::addresses(port) {
|
|
||||||
log::info!("AnyBot:手機可以打開 {a}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !app.state.remote.relay_url.is_empty() {
|
if !app.state.remote.relay_url.is_empty() {
|
||||||
log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url);
|
log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -937,6 +937,9 @@ impl App {
|
||||||
} else {
|
} else {
|
||||||
ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(FONT_XS).color(p.danger));
|
ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(FONT_XS).color(p.danger));
|
||||||
}
|
}
|
||||||
|
} else if let Some(why) = remote::lan_problem() {
|
||||||
|
// Not listening yet (the address isn't there, the ports are taken): it keeps trying.
|
||||||
|
ui.label(RichText::new(why).size(FONT_XS).color(p.danger));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ui.add_space(4.0);
|
ui.add_space(4.0);
|
||||||
|
|
|
||||||
169
src/lantls.rs
169
src/lantls.rs
|
|
@ -92,25 +92,102 @@ fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel)
|
/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel)
|
||||||
/// interface — macOS's utun, Linux's tailscale0. Read from `ifconfig` (macOS, Linux net-tools)
|
/// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from
|
||||||
/// or `ip -o addr` (Linux), at most every 30 seconds. Where neither answers (Windows) there are
|
/// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most
|
||||||
/// none, and plain HTTP over Tailscale is sent to https like the rest.
|
/// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to
|
||||||
|
/// https like the rest.
|
||||||
pub fn tunnel_addrs() -> Vec<IpAddr> {
|
pub fn tunnel_addrs() -> Vec<IpAddr> {
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
static CACHE: Mutex<Option<(std::time::Instant, Vec<IpAddr>)>> = Mutex::new(None);
|
static CACHE: Mutex<Option<(std::time::Instant, Vec<IpAddr>)>> = Mutex::new(None);
|
||||||
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) {
|
if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) {
|
||||||
return v.clone();
|
return v.clone();
|
||||||
}
|
}
|
||||||
let run = |cmd: &str, args: &[&str]| std::process::Command::new(cmd).args(args).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
|
let run = |cmd: &str, args: &[&str]| {
|
||||||
let mut text = run("ifconfig", &[]);
|
let mut c = std::process::Command::new(cmd);
|
||||||
if text.trim().is_empty() {
|
c.args(args);
|
||||||
text = run("ip", &["-o", "addr"]);
|
#[cfg(windows)]
|
||||||
}
|
{
|
||||||
let v = parse_tunnel_addrs(&text);
|
use std::os::windows::process::CommandExt;
|
||||||
|
// (No console window flashing up.)
|
||||||
|
c.creation_flags(0x0800_0000);
|
||||||
|
}
|
||||||
|
c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let v = if cfg!(windows) {
|
||||||
|
parse_ipconfig_tunnels(&run("ipconfig", &[]))
|
||||||
|
} else {
|
||||||
|
let mut text = run("ifconfig", &[]);
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
text = run("ip", &["-o", "addr"]);
|
||||||
|
}
|
||||||
|
parse_tunnel_addrs(&text)
|
||||||
|
};
|
||||||
*cache = Some((std::time::Instant::now(), v.clone()));
|
*cache = Some((std::time::Instant::now(), v.clone()));
|
||||||
v
|
v
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tests that need to say which addresses are this machine's tunnel's (one at a time).
|
||||||
|
#[cfg(test)]
|
||||||
|
static TEST_TUNNELS: Mutex<Option<Vec<IpAddr>>> = Mutex::new(None);
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn with_tunnels<R>(tunnels: &[IpAddr], f: impl FnOnce() -> R) -> R {
|
||||||
|
static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
|
||||||
|
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
*TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = Some(tunnels.to_vec());
|
||||||
|
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
|
||||||
|
*TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||||
|
r.unwrap_or_else(|p| std::panic::resume_unwind(p))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The address this computer would send from to reach `dest` — which interface the routing table
|
||||||
|
/// picks (a UDP socket's connect sends nothing). None: no route.
|
||||||
|
pub fn source_for(dest: IpAddr) -> Option<IpAddr> {
|
||||||
|
let any: SocketAddr = if dest.is_ipv4() { (std::net::Ipv4Addr::UNSPECIFIED, 0).into() } else { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() };
|
||||||
|
let s = std::net::UdpSocket::bind(any).ok()?;
|
||||||
|
s.connect((dest, 9)).ok()?;
|
||||||
|
s.local_addr().ok().map(|a| a.ip().to_canonical())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A server reached through this machine's Tailscale tunnel: every one of its addresses is a
|
||||||
|
/// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x
|
||||||
|
/// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale.
|
||||||
|
pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option<IpAddr>) -> bool {
|
||||||
|
!addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical())))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at
|
||||||
|
/// the left margin ("Unknown adapter Tailscale:", 「未知的介面卡 Tailscale:」); its values are
|
||||||
|
/// indented, after the last ": " ("IPv4 Address. . . : 100.101.2.3", 「IPv4 位址 . . . : …」),
|
||||||
|
/// sometimes with "(Preferred)" after them. The labels are in the system's language; the
|
||||||
|
/// adapter's name and the addresses aren't.
|
||||||
|
fn parse_ipconfig_tunnels(text: &str) -> Vec<IpAddr> {
|
||||||
|
let mut out = vec![];
|
||||||
|
let mut tunnel = false;
|
||||||
|
for line in text.lines() {
|
||||||
|
if line.trim().is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !line.starts_with(char::is_whitespace) {
|
||||||
|
tunnel = line.to_ascii_lowercase().contains("tailscale");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some((_, value)) = line.rsplit_once(": ") else { continue };
|
||||||
|
let value = value.trim().split(['(', '%']).next().unwrap_or("").trim();
|
||||||
|
if let Ok(ip) = value.parse::<IpAddr>() {
|
||||||
|
if tunnel && tailscale_range(ip) {
|
||||||
|
out.push(ip.to_canonical());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.dedup();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags:
|
/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags:
|
||||||
/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a
|
/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a
|
||||||
/// /32 or /128 of its own).
|
/// /32 or /128 of its own).
|
||||||
|
|
@ -447,4 +524,78 @@ mod tests {
|
||||||
assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]);
|
assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]);
|
||||||
assert!(parse_tunnel_addrs("").is_empty());
|
assert!(parse_tunnel_addrs("").is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a
|
||||||
|
/// Wi-Fi with a 100.70.0.5 address isn't it.
|
||||||
|
#[test]
|
||||||
|
fn windows_finds_the_tailscale_adapter_in_ipconfig() {
|
||||||
|
let ip = |s: &str| s.parse::<IpAddr>().unwrap();
|
||||||
|
let en = "\r\nWindows IP Configuration\r\n\r\n\r\nUnknown adapter Tailscale:\r\n\r\n Connection-specific DNS Suffix . : tail1234.ts.net\r\n IPv6 Address. . . . . . . . . . . : fd7a:115c:a1e0::1234\r\n Link-local IPv6 Address . . . . . : fe80::abcd:1%5\r\n IPv4 Address. . . . . . . . . . . : 100.101.2.3\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.255\r\n Default Gateway . . . . . . . . . :\r\n\r\nWireless LAN adapter Wi-Fi:\r\n\r\n IPv4 Address. . . . . . . . . . . : 100.70.0.5(Preferred)\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\r\n";
|
||||||
|
assert_eq!(parse_ipconfig_tunnels(en), vec![ip("fd7a:115c:a1e0::1234"), ip("100.101.2.3")]);
|
||||||
|
let zh = "Windows IP 設定\r\n\r\n未知的介面卡 Tailscale:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 100.101.2.3\r\n 子網路遮罩 . . . . . . . . . . . : 255.255.255.255\r\n\r\n無線區域網路介面卡 Wi-Fi:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 192.168.1.9\r\n";
|
||||||
|
assert_eq!(parse_ipconfig_tunnels(zh), vec![ip("100.101.2.3")]);
|
||||||
|
assert!(parse_ipconfig_tunnels("").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A server is reached through Tailscale when its address is a Tailscale one and the route
|
||||||
|
/// to it leaves from the tunnel's address — not when a Wi-Fi hands out 100.x addresses.
|
||||||
|
#[test]
|
||||||
|
fn a_server_is_tailscale_when_the_route_goes_through_the_tunnel() {
|
||||||
|
let ip = |s: &str| s.parse::<IpAddr>().unwrap();
|
||||||
|
let tunnels = [ip("100.84.144.91")];
|
||||||
|
let via_tunnel = |_| Some(ip("100.84.144.91"));
|
||||||
|
let via_wifi = |_| Some(ip("100.70.0.5"));
|
||||||
|
assert!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel));
|
||||||
|
assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses");
|
||||||
|
assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here");
|
||||||
|
assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one");
|
||||||
|
assert!(!tailscale_server(&[ip("192.168.1.10")], &tunnels, via_tunnel), "a subnet behind the tailnet is not a Tailscale address");
|
||||||
|
assert!(!tailscale_server(&[], &tunnels, via_tunnel));
|
||||||
|
// The route really is asked: to this machine itself it leaves from loopback.
|
||||||
|
assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The front decides plain-or-https by the connection's own two ends: who sent it (`peer`),
|
||||||
|
/// the address of this machine it arrived at, and this machine's tunnel addresses. A plain
|
||||||
|
/// request from a Tailscale address that arrived at a tunnel address goes through; arriving
|
||||||
|
/// anywhere else it is sent to https.
|
||||||
|
#[test]
|
||||||
|
fn the_front_uses_where_the_connection_arrived() {
|
||||||
|
let ip = |s: &str| s.parse::<IpAddr>().unwrap();
|
||||||
|
let dir = std::env::temp_dir().join(format!("anybot-lantls-carry-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let (cert, key) = identity(&dir, &[]).unwrap();
|
||||||
|
let cfg = config(cert, key).unwrap();
|
||||||
|
let inner = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let inner_addr = inner.local_addr().unwrap();
|
||||||
|
let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||||
|
let alive: Arc<dyn Fn() -> bool + Send + Sync> = { let on = on.clone(); Arc::new(move || on.load(Ordering::SeqCst)) };
|
||||||
|
let handler: crate::httpd::Handler = Arc::new(|r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer})));
|
||||||
|
std::thread::spawn(move || crate::httpd::serve(inner, handler, alive));
|
||||||
|
// One plain request through `carry`, as if it came from `peer` (this test's connection
|
||||||
|
// arrives at 127.0.0.1).
|
||||||
|
let ask = |peer: IpAddr| {
|
||||||
|
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let addr = l.local_addr().unwrap();
|
||||||
|
let cfg = cfg.clone();
|
||||||
|
let t = std::thread::spawn(move || carry(l.accept().unwrap().0, peer, inner_addr, cfg));
|
||||||
|
let mut c = TcpStream::connect(addr).unwrap();
|
||||||
|
c.write_all(format!("GET /x HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap();
|
||||||
|
let mut out = String::new();
|
||||||
|
let _ = c.read_to_string(&mut out);
|
||||||
|
t.join().unwrap();
|
||||||
|
out
|
||||||
|
};
|
||||||
|
let from_tailnet = ip("100.101.2.3");
|
||||||
|
// 127.0.0.1 standing for this machine's tunnel address: plain goes through.
|
||||||
|
let out = with_tunnels(&[ip("127.0.0.1")], || ask(from_tailnet));
|
||||||
|
assert!(out.starts_with("HTTP/1.1 200") && out.contains("100.101.2.3"), "{out}");
|
||||||
|
// The same connection when that address isn't a tunnel's (a Wi-Fi of 100.x addresses).
|
||||||
|
let out = with_tunnels(&[ip("100.84.144.91")], || ask(from_tailnet));
|
||||||
|
assert!(out.contains("308"), "{out}");
|
||||||
|
let out = with_tunnels(&[], || ask(from_tailnet));
|
||||||
|
assert!(out.contains("308"), "{out}");
|
||||||
|
on.store(false, Ordering::SeqCst);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
282
src/remote.rs
282
src/remote.rs
|
|
@ -1129,9 +1129,16 @@ fn content_type(f: &std::path::Path) -> &'static str {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The address in a peer written as an address ("fd7a:115c:a1e0::1") or an address and port
|
||||||
|
/// ("192.168.1.66:5000", "[::1]:5000").
|
||||||
|
fn peer_ip(peer: &str) -> String {
|
||||||
|
peer.parse::<std::net::SocketAddr>().map(|a| a.ip()).or_else(|_| peer.parse::<std::net::IpAddr>()).map(|ip| ip.to_canonical().to_string()).unwrap_or_else(|_| peer.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
fn login(req: &Req) -> Resp {
|
fn login(req: &Req) -> Resp {
|
||||||
// One counter per source address, cleaned as it is touched.
|
// One counter per source address, cleaned as it is touched. (The peer is an address, or an
|
||||||
let ip = req.peer.split(':').next().unwrap_or(&req.peer).to_string();
|
// address and port; an IPv6 one has colons of its own, so it is read, not cut at ':'.)
|
||||||
|
let ip = peer_ip(&req.peer);
|
||||||
{
|
{
|
||||||
let mut f = hub().fails.lock().unwrap();
|
let mut f = hub().fails.lock().unwrap();
|
||||||
f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(60));
|
f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(60));
|
||||||
|
|
@ -1389,15 +1396,27 @@ fn private_host(host: &str) -> bool {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The host (an IPv6 address without its brackets) and port of a URL.
|
||||||
fn host_port(url: &str) -> Option<(String, u16)> {
|
fn host_port(url: &str) -> Option<(String, u16)> {
|
||||||
let (scheme, rest) = url.split_once("://")?;
|
let (scheme, rest) = url.split_once("://")?;
|
||||||
let auth = rest.split('/').next()?;
|
let auth = rest.split('/').next()?;
|
||||||
let auth = auth.rsplit('@').next()?;
|
let auth = auth.rsplit('@').next()?;
|
||||||
let (h, p) = match auth.rsplit_once(':') {
|
let usual = if scheme == "https" { 443 } else { 80 };
|
||||||
Some((h, p)) if !h.ends_with(']') || auth.starts_with('[') => (h.to_string(), p.parse().ok()?),
|
// An IPv6 address comes in brackets (its own colons aren't the port's); it is given back
|
||||||
_ => (auth.to_string(), if scheme == "https" { 443 } else { 80 }),
|
// without them — bracketed, it would go into the 區網 certificate as a name, not an address.
|
||||||
};
|
if let Some(rest) = auth.strip_prefix('[') {
|
||||||
Some((h, p))
|
let (h, after) = rest.split_once(']')?;
|
||||||
|
let p = match after.strip_prefix(':') {
|
||||||
|
Some(p) => p.parse().ok()?,
|
||||||
|
None if after.is_empty() => usual,
|
||||||
|
None => return None,
|
||||||
|
};
|
||||||
|
return Some((h.to_string(), p));
|
||||||
|
}
|
||||||
|
match auth.rsplit_once(':') {
|
||||||
|
Some((h, p)) => Some((h.to_string(), p.parse().ok()?)),
|
||||||
|
None => Some((auth.to_string(), usual)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The hands to send a model request through: the model is at a private address this brain
|
/// The hands to send a model request through: the model is at a private address this brain
|
||||||
|
|
@ -1498,10 +1517,16 @@ fn model_fetch_here(args: &str) -> Resp {
|
||||||
// ---------- the local server ----------
|
// ---------- the local server ----------
|
||||||
|
|
||||||
static LAN_GEN: AtomicU64 = AtomicU64::new(0);
|
static LAN_GEN: AtomicU64 = AtomicU64::new(0);
|
||||||
static LAN_BOUND: Mutex<Option<u16>> = Mutex::new(None);
|
static LAN_BOUND: Mutex<Option<std::net::SocketAddr>> = Mutex::new(None);
|
||||||
|
static LAN_PROBLEM: Mutex<Option<String>> = Mutex::new(None);
|
||||||
|
|
||||||
pub fn lan_port() -> Option<u16> {
|
pub fn lan_port() -> Option<u16> {
|
||||||
*LAN_BOUND.lock().unwrap()
|
LAN_BOUND.lock().unwrap().map(|a| a.port())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the phone page isn't answering although 同一個網路直接連 is on (it keeps trying).
|
||||||
|
pub fn lan_problem() -> Option<String> {
|
||||||
|
LAN_PROBLEM.lock().unwrap().clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The address the phone page listens on: every one of this computer's (the phone on the Wi-Fi
|
/// The address the phone page listens on: every one of this computer's (the phone on the Wi-Fi
|
||||||
|
|
@ -1520,45 +1545,109 @@ fn lan_bind_from(v: Option<&str>) -> Result<std::net::IpAddr, String> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start (or stop) answering phones on the local network.
|
/// Start (or stop) answering phones on the local network. It returns at once: the port is taken
|
||||||
pub fn set_lan(on: bool) -> Result<u16, String> {
|
/// on a thread of its own, which keeps trying while the address isn't there yet (a Tailscale
|
||||||
|
/// address at boot) or the ports are taken — the log and 設定 (lan_problem) say why meanwhile.
|
||||||
|
/// Only an ANYBOT_PHONE_BIND that isn't an address is an error here.
|
||||||
|
pub fn set_lan(on: bool) -> Result<(), String> {
|
||||||
|
let gen = lan_stop();
|
||||||
|
if !on {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let bind = lan_bind().inspect_err(|e| {
|
||||||
|
log::warn!("AnyBot:{e}");
|
||||||
|
*LAN_PROBLEM.lock().unwrap() = Some(e.clone());
|
||||||
|
})?;
|
||||||
|
let port_env: Option<u16> = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok());
|
||||||
|
lan_start(gen, bind, port_env.unwrap_or(LAN_PORT), Duration::from_secs(5));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new generation: what listened before stops (within 50 ms). Its number.
|
||||||
|
fn lan_stop() -> u64 {
|
||||||
let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1;
|
let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1;
|
||||||
*LAN_BOUND.lock().unwrap() = None;
|
*LAN_BOUND.lock().unwrap() = None;
|
||||||
if !on {
|
*LAN_PROBLEM.lock().unwrap() = None;
|
||||||
return Ok(0);
|
gen
|
||||||
}
|
}
|
||||||
let bind = lan_bind()?;
|
|
||||||
let port_env: Option<u16> = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok());
|
fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) {
|
||||||
let start = port_env.unwrap_or(LAN_PORT);
|
std::thread::spawn(move || lan_up(gen, bind, start, every));
|
||||||
// The old listener notices the new generation within 50 ms; give it the port back.
|
}
|
||||||
let listener = (0..40)
|
|
||||||
.find_map(|_| {
|
/// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定).
|
||||||
let l = (start..start + 10).find_map(|p| std::net::TcpListener::bind((bind, p)).ok());
|
fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result<std::net::TcpListener, String> {
|
||||||
if l.is_none() {
|
let end = start.saturating_add(10);
|
||||||
std::thread::sleep(Duration::from_millis(60));
|
for p in start..end {
|
||||||
|
match std::net::TcpListener::bind((bind, p)) {
|
||||||
|
Ok(l) => return Ok(l),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AddrNotAvailable => {
|
||||||
|
return Err(format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開"));
|
||||||
}
|
}
|
||||||
l
|
Err(_) => {}
|
||||||
})
|
}
|
||||||
.ok_or("找不到可用的連接埠")?;
|
}
|
||||||
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
Err(format!("連接埠 {start}–{} 都被別的程式占用:空出來就會自動打開", end - 1))
|
||||||
*LAN_BOUND.lock().unwrap() = Some(port);
|
}
|
||||||
|
|
||||||
|
/// Take the port for generation `gen`, then serve. The listener of the generation before gives
|
||||||
|
/// its port back within 50 ms, so the first couple of seconds try often and quietly; after that,
|
||||||
|
/// why it can't is said once (log and 設定) and it tries again every `every` until it works or
|
||||||
|
/// 同一個網路直接連 is turned off.
|
||||||
|
fn lan_up(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) {
|
||||||
|
let current = || LAN_GEN.load(Ordering::SeqCst) == gen;
|
||||||
|
let (mut tries, mut said) = (0u32, String::new());
|
||||||
|
while current() {
|
||||||
|
match bind_lan(bind, start) {
|
||||||
|
Ok(l) => return serve_lan(gen, l),
|
||||||
|
Err(why) => {
|
||||||
|
tries += 1;
|
||||||
|
if tries > 40 {
|
||||||
|
if why != said {
|
||||||
|
log::warn!("AnyBot:手機直接連線還沒打開:{why}");
|
||||||
|
said.clone_from(&why);
|
||||||
|
}
|
||||||
|
let mut p = LAN_PROBLEM.lock().unwrap();
|
||||||
|
if current() {
|
||||||
|
*p = Some(why);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(if tries <= 40 { Duration::from_millis(60) } else { every });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve_lan(gen: u64, listener: std::net::TcpListener) {
|
||||||
|
let Ok(addr) = listener.local_addr() else { return };
|
||||||
|
let port = addr.port();
|
||||||
let alive: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen);
|
let alive: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen);
|
||||||
// HTTPS on that port (lantls), with the plain server behind it on this machine only. If the
|
// HTTPS on that port (lantls), with the plain server behind it on this machine only. If the
|
||||||
// certificate can't be made, it is the plain server as before — and 設定 says so.
|
// certificate can't be made, it is the plain server as before — and 設定 says so.
|
||||||
*LAN_CERT.lock().unwrap() = None;
|
let tls = lan_tls(port).and_then(|(behind, cfg, print)| Some((behind.local_addr().ok()?, behind, cfg, print)));
|
||||||
let mut served = Some(listener);
|
{
|
||||||
if let Some((behind, cfg, print)) = lan_tls(port) {
|
let mut bound = LAN_BOUND.lock().unwrap();
|
||||||
if let (Some(l), Ok(to)) = (served.take(), behind.local_addr()) {
|
if LAN_GEN.load(Ordering::SeqCst) != gen {
|
||||||
*LAN_CERT.lock().unwrap() = Some(print);
|
return;
|
||||||
let alive2 = alive.clone();
|
|
||||||
std::thread::spawn(move || crate::lantls::front(l, to, cfg, alive2));
|
|
||||||
served = Some(behind);
|
|
||||||
}
|
}
|
||||||
|
*LAN_CERT.lock().unwrap() = tls.as_ref().map(|t| t.3.clone());
|
||||||
|
*bound = Some(addr);
|
||||||
|
*LAN_PROBLEM.lock().unwrap() = None;
|
||||||
}
|
}
|
||||||
if let Some(l) = served {
|
// (The window shows these in 設定; under --serve the log is where they are. Said before the
|
||||||
std::thread::spawn(move || httpd::serve_upgrade(l, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive));
|
// first answer: the port is already taken, connections wait for the threads below.)
|
||||||
|
for a in addresses(port) {
|
||||||
|
log::info!("AnyBot:手機可以打開 {a}");
|
||||||
}
|
}
|
||||||
Ok(port)
|
let served = match tls {
|
||||||
|
Some((to, behind, cfg, _)) => {
|
||||||
|
let alive2 = alive.clone();
|
||||||
|
std::thread::spawn(move || crate::lantls::front(listener, to, cfg, alive2));
|
||||||
|
behind
|
||||||
|
}
|
||||||
|
None => listener,
|
||||||
|
};
|
||||||
|
std::thread::spawn(move || httpd::serve_upgrade(served, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive));
|
||||||
}
|
}
|
||||||
|
|
||||||
static LAN_CERT: Mutex<Option<String>> = Mutex::new(None);
|
static LAN_CERT: Mutex<Option<String>> = Mutex::new(None);
|
||||||
|
|
@ -1795,6 +1884,25 @@ fn base(url: &str) -> String {
|
||||||
url.trim().trim_end_matches('/').to_string()
|
url.trim().trim_end_matches('/').to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether an http:// account server is off the air, so the account password may go to it
|
||||||
|
/// unencrypted: this machine, a name inside one Docker network (http://relay:8080), or a server
|
||||||
|
/// reached through this machine's Tailscale tunnel — every address the name has is a Tailscale
|
||||||
|
/// one and the route to it leaves from the tunnel (lantls::tailscale_server). An address in
|
||||||
|
/// 100.64.0.0/10 alone isn't Tailscale: a Wi-Fi can hand those out.
|
||||||
|
fn plain_relay_ok(url: &str) -> bool {
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
|
let Some((host, port)) = host_port(url) else { return false };
|
||||||
|
let ip = host.parse::<std::net::IpAddr>().ok();
|
||||||
|
if host == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if ip.is_none() && !host.is_empty() && !host.contains('.') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let addrs: Vec<std::net::IpAddr> = (host.as_str(), port).to_socket_addrs().map(|a| a.map(|a| a.ip()).collect()).unwrap_or_default();
|
||||||
|
crate::lantls::tailscale_server(&addrs, &crate::lantls::tunnel_addrs(), crate::lantls::source_for)
|
||||||
|
}
|
||||||
|
|
||||||
/// How the refusal starts when the account has 兩步驗證 on and no code came with the password
|
/// How the refusal starts when the account has 兩步驗證 on and no code came with the password
|
||||||
/// (the forms look for it to show their 驗證碼 field).
|
/// (the forms look for it to show their 驗證碼 field).
|
||||||
pub const NEED_CODE: &str = "這個帳號開了兩步驗證";
|
pub const NEED_CODE: &str = "這個帳號開了兩步驗證";
|
||||||
|
|
@ -1830,12 +1938,7 @@ pub fn relay_join(base_settings: &Settings, url: &str, user: &str, password: &st
|
||||||
let user = user.as_str();
|
let user = user.as_str();
|
||||||
let host_name = base_settings.host_name.as_str();
|
let host_name = base_settings.host_name.as_str();
|
||||||
let url = base(url);
|
let url = base(url);
|
||||||
// Plain http only inside one machine or one Docker network (e.g. http://relay:8080).
|
if !url.starts_with("https://") && !plain_relay_ok(&url) {
|
||||||
let host = url.strip_prefix("http://").map(|r| r.split(['/', ':']).next().unwrap_or("")).unwrap_or("");
|
|
||||||
// Tailscale (100.64.0.0/10 and *.ts.net) is already encrypted end to end.
|
|
||||||
let tailscale = host.ends_with(".ts.net") || host.split('.').collect::<Vec<_>>().as_slice().first().map(|a| *a == "100").unwrap_or(false) && host.split('.').nth(1).and_then(|b| b.parse::<u8>().ok()).map(|b| (64..128).contains(&b)).unwrap_or(false);
|
|
||||||
let internal = host == "127.0.0.1" || host == "localhost" || tailscale || (!host.is_empty() && !host.contains('.'));
|
|
||||||
if !url.starts_with("https://") && !internal {
|
|
||||||
return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into());
|
return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into());
|
||||||
}
|
}
|
||||||
if create {
|
if create {
|
||||||
|
|
@ -2648,6 +2751,8 @@ mod tests {
|
||||||
assert!(!private_host("169.254.169.254") && !private_host("169.254.0.1"));
|
assert!(!private_host("169.254.169.254") && !private_host("169.254.0.1"));
|
||||||
assert_eq!(host_port("http://10.184.10.252:8000/v1"), Some(("10.184.10.252".into(), 8000)));
|
assert_eq!(host_port("http://10.184.10.252:8000/v1"), Some(("10.184.10.252".into(), 8000)));
|
||||||
assert_eq!(host_port("https://api.x.ai/v1"), Some(("api.x.ai".into(), 443)));
|
assert_eq!(host_port("https://api.x.ai/v1"), Some(("api.x.ai".into(), 443)));
|
||||||
|
assert_eq!(host_port("https://[::1]:8800/"), Some(("::1".into(), 8800)));
|
||||||
|
assert_eq!(host_port("http://[fd7a:115c:a1e0::3]/"), Some(("fd7a:115c:a1e0::3".into(), 80)));
|
||||||
assert_eq!(model_fetch_here(&json!({"url": "https://api.x.ai/v1/chat/completions"}).to_string()).status, 403);
|
assert_eq!(model_fetch_here(&json!({"url": "https://api.x.ai/v1/chat/completions"}).to_string()).status, 403);
|
||||||
assert_eq!(model_fetch_here(&json!({"url": "http://169.254.169.254/latest/meta-data/"}).to_string()).status, 403);
|
assert_eq!(model_fetch_here(&json!({"url": "http://169.254.169.254/latest/meta-data/"}).to_string()).status, 403);
|
||||||
assert_eq!(model_fetch_here(&json!({"url": "http://127.0.0.1:8793/api/state"}).to_string()).status, 403);
|
assert_eq!(model_fetch_here(&json!({"url": "http://127.0.0.1:8793/api/state"}).to_string()).status, 403);
|
||||||
|
|
@ -2679,6 +2784,15 @@ mod tests {
|
||||||
// …while every other device on the LAN can still sign in.
|
// …while every other device on the LAN can still sign in.
|
||||||
let ok = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-123"}"#.to_vec(), peer: "192.168.1.77:5001".into(), ..Default::default() }, false);
|
let ok = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-123"}"#.to_vec(), peer: "192.168.1.77:5001".into(), ..Default::default() }, false);
|
||||||
assert_eq!(ok.status, 200);
|
assert_eq!(ok.status, 200);
|
||||||
|
// The same over IPv6 (ANYBOT_PHONE_BIND=::), where a peer is an address full of colons:
|
||||||
|
// locking one device mustn't lock every one that shares its first group.
|
||||||
|
for _ in 0..MAX_FAILS {
|
||||||
|
assert_eq!(bad("fd7a:115c:a1e0::66").status, 401);
|
||||||
|
}
|
||||||
|
assert_eq!(bad("fd7a:115c:a1e0::66").status, 429);
|
||||||
|
assert_eq!(bad("[fd7a:115c:a1e0::66]:5000").status, 429, "with a port it is the same device");
|
||||||
|
let ok6 = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-123"}"#.to_vec(), peer: "fd7a:115c:a1e0::77".into(), ..Default::default() }, false);
|
||||||
|
assert_eq!(ok6.status, 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -2869,6 +2983,84 @@ mod tests {
|
||||||
assert_eq!(listed(ifconfig, 8800, ip("127.0.0.1"), true, &tunnels), vec!["https://127.0.0.1:8800"]);
|
assert_eq!(listed(ifconfig, 8800, ip("127.0.0.1"), true, &tunnels), vec!["https://127.0.0.1:8800"]);
|
||||||
assert_eq!(listed(ifconfig, 8793, ip("100.84.144.91"), true, &tunnels), vec!["http://100.84.144.91:8793"]);
|
assert_eq!(listed(ifconfig, 8793, ip("100.84.144.91"), true, &tunnels), vec!["http://100.84.144.91:8793"]);
|
||||||
assert_eq!(listed("", 8793, ip("::1"), true, &[]), vec!["https://[::1]:8793"]);
|
assert_eq!(listed("", 8793, ip("::1"), true, &[]), vec!["https://[::1]:8793"]);
|
||||||
|
// The certificate names an IPv6 address as an address (what lan_tls does: the listed
|
||||||
|
// links' hosts), not as the name "[fd7a:…]" a browser would never match.
|
||||||
|
let hosts: Vec<String> = listed("", 8793, ip("fd7a:115c:a1e0::3"), true, &[]).iter().filter_map(|a| host_port(a).map(|(h, _)| h)).collect();
|
||||||
|
assert_eq!(hosts, vec!["fd7a:115c:a1e0::3"]);
|
||||||
|
let dir = std::env::temp_dir().join(format!("anybot-lan-cert-v6-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let (cert, _) = crate::lantls::identity(&dir, &hosts).unwrap();
|
||||||
|
let std::net::IpAddr::V6(v6) = ip("fd7a:115c:a1e0::3") else { unreachable!() };
|
||||||
|
assert!(cert.windows(16).any(|w| w == v6.octets()), "an IP address in the certificate");
|
||||||
|
assert!(!cert.windows(5).any(|w| w == b"[fd7a"), "not a bracketed name");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The listener really is on the address it is given; an address this computer doesn't have
|
||||||
|
/// yet (a Tailscale address at boot) and ports all taken are said as they are, and it comes
|
||||||
|
/// up by itself once it can — nobody has to turn 同一個網路直接連 off and on.
|
||||||
|
#[test]
|
||||||
|
fn the_phone_page_binds_where_told_and_keeps_trying() {
|
||||||
|
let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap();
|
||||||
|
let wait = |what: &str, f: &dyn Fn() -> bool| {
|
||||||
|
let t = Instant::now();
|
||||||
|
while !f() {
|
||||||
|
assert!(t.elapsed() < Duration::from_secs(10), "waited 10 s for: {what} (problem: {:?})", lan_problem());
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let every = Duration::from_millis(200);
|
||||||
|
// 127.0.0.1 is where it listens, and it answers there.
|
||||||
|
let start = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||||
|
lan_start(lan_stop(), ip("127.0.0.1"), start, every);
|
||||||
|
wait("listening", &|| lan_port().is_some());
|
||||||
|
let bound = LAN_BOUND.lock().unwrap().unwrap();
|
||||||
|
assert_eq!(bound.ip(), ip("127.0.0.1"), "bound to {bound}, not where it was told");
|
||||||
|
let mut c = std::net::TcpStream::connect(bound).unwrap();
|
||||||
|
std::io::Write::write_all(&mut c, b"GET /api/hello HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n").unwrap();
|
||||||
|
let mut out = String::new();
|
||||||
|
let _ = std::io::Read::read_to_string(&mut c, &mut out);
|
||||||
|
assert!(out.contains("\"app\":\"anybot\""), "{out}");
|
||||||
|
// An address that isn't on this computer (TEST-NET): said so, not 「找不到可用的連接埠」.
|
||||||
|
lan_start(lan_stop(), ip("192.0.2.1"), start, every);
|
||||||
|
wait("the missing address said", &|| lan_problem().is_some_and(|p| p.contains("192.0.2.1")));
|
||||||
|
assert_eq!(lan_port(), None);
|
||||||
|
// Every port taken: said so; freed, it comes up without being asked again.
|
||||||
|
let (start, blockers) = (0..50)
|
||||||
|
.find_map(|_| {
|
||||||
|
let p = std::net::TcpListener::bind("127.0.0.1:0").ok()?.local_addr().ok()?.port().min(65_000);
|
||||||
|
let ls: Vec<_> = (p..p + 10).filter_map(|q| std::net::TcpListener::bind(("127.0.0.1", q)).ok()).collect();
|
||||||
|
(ls.len() == 10).then_some((p, ls))
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lan_start(lan_stop(), ip("127.0.0.1"), start, every);
|
||||||
|
wait("the taken ports said", &|| lan_problem().is_some_and(|p| p.contains("占用")));
|
||||||
|
drop(blockers);
|
||||||
|
wait("up once the ports are free", &|| lan_port() == Some(start));
|
||||||
|
assert_eq!(lan_problem(), None);
|
||||||
|
set_lan(false).unwrap();
|
||||||
|
assert_eq!(lan_port(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The account password goes to an http:// account server only off the air: this computer,
|
||||||
|
/// a Docker network's name, or a server whose route leaves through the Tailscale tunnel — not
|
||||||
|
/// any 100.64.0.0/10 address (a Wi-Fi can hand those out), nor an IPv6 address taken for a name.
|
||||||
|
#[test]
|
||||||
|
fn plain_http_to_an_account_server_only_off_the_air() {
|
||||||
|
let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap();
|
||||||
|
assert!(plain_relay_ok("http://127.0.0.1:8780") && plain_relay_ok("http://localhost:8780") && plain_relay_ok("http://[::1]:8780") && plain_relay_ok("http://relay:8080"));
|
||||||
|
crate::lantls::with_tunnels(&[], || {
|
||||||
|
assert!(!plain_relay_ok("http://100.70.0.10:8080"));
|
||||||
|
assert!(!plain_relay_ok("http://[fd00::5]:8080"), "an IPv6 address isn't a Docker name");
|
||||||
|
assert!(!plain_relay_ok("http://10.0.0.5:8080"));
|
||||||
|
// Refused before the password is sent anywhere.
|
||||||
|
let e = relay_join(&Settings::default(), "http://100.70.0.10:8080", "dan", "pw-123", false, "", "").unwrap_err();
|
||||||
|
assert!(e.contains("https://"), "{e}");
|
||||||
|
});
|
||||||
|
// Where the route to a Tailscale address leaves from is this machine's tunnel: fine.
|
||||||
|
if let Some(src) = crate::lantls::source_for(ip("100.101.2.3")) {
|
||||||
|
crate::lantls::with_tunnels(&[src], || assert!(plain_relay_ok("http://100.101.2.3:8080")));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue