fix: 帳號伺服器的明文規則管到每一個帶密碼或金鑰的連線,在開連線那一刻查;Tailscale 通道認得更準

第三輪(新的獨立審查:兩個早就有的 P1,和幾個 P2):

- A:「從帳號備份還原」不經 relay_join,原本 http 檢查管不到。現在帶帳號密碼、配對碼或這台電腦金鑰
  的請求都經 relay_post/relay_agent:登入、建立帳號、兩步驗證、還原、配對、通知、網站、成員、備份、
  和大腦同步、手腳的指令、還有備用連線(workers)。
- B:http 的帳號伺服器原本只在登入時查一次,之後長連線每次重連都直接連。現在 tunnel::open 每次
  (重)連都對要連的位址查,不符合就不連、狀態寫原因、照原本的退避再試;workers 每一輪也一樣。
- 1(DNS 兩次查):選「釘住」——http 的帳號伺服器用自己的 ureq client,resolver 在開連線那一刻對
  查到的位址做檢查,只連通過的那幾個(web_fetch 已經用同一種做法);長連線也是查完就連那幾個位址。
  名字可以照常用,不必限定 IP 或 *.ts.net。這個 client 不走代理(代理會照它自己的路把明文轉出去)。
- 2:host_port 改用 ureq 自己的 URL 解析(http::Uri),`?`、`#` 後面不是主機;長連線也用它。
  model_fetch_here 的私有位址檢查一起修好。
- 3:Tailscale 通道要「叫 tailscale…」或「點對點介面+Tailscale IPv6(fd7a:115c:a1e0::/48)」,
  Windows 看介面卡名字;PPPoE、電信 NAT、WARP 的 100.x 不算,ip -o addr 的 /32 不再算。ifconfig 找不到
  通道(busybox、舊 net-tools 的 inet addr:)時也問 ip。
- 4:沒有 IPv6 的電腦上,*.ts.net 的 IPv6 位址沒有路由就略過、用 IPv4(原本整個拒絕)。
- 5:介面資料 30 秒更新一次,第一次之後都在背景讀,設定頁每一幀拿快取(Windows 不會在 UI 執行緒跑
  ipconfig);remote::addresses 也用同一份,不再每一幀跑 ifconfig。
- 6:綁不到連接埠時分開說:位址不在、不准用(1024 以下、系統保留)、被占用、其他;65535 會試,不再說
  「65535–65534」。
- 文件照程式寫:SECURITY.md(帳號伺服器的規則管到哪些請求、每次開連線查、釘住、不走代理、一個字的
  名字在一般網路上的風險、通道怎麼認)、phone.md、FEATURES.md。

已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(652 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets
  -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到(10 個):relay_post
  不查、長連線開連線不查、workers 用一般 client、resolver 放行一切、host_port 改回手寫切法、任何點對點
  100.x 都算通道、沒路由的位址算拒絕、介面過期時在呼叫的執行緒重讀、不准用說成被占用、65535 不試。
  實機(verify-anybot,這台 Mac 的 utun4 有 100.84.144.91 和 fd7a:115c:a1e0::d738:905c):phone 區範例旅程
  照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、區網 http 308)。
未驗證: 帳號伺服器的部分沒有接真的帳號伺服器跑——用單元測試走 relay_join、restore、relay_worker、
  tunnel::run 和 http client 的真程式碼(scratch 不准帶 ANYBOT_ACCOUNT,也不手寫含金鑰的設定檔);
  Wi-Fi 自己發 100.64.x 的網路、PPPoE、WARP、busybox 的 ifconfig 只有樣本測試;Linux、Windows 實機沒跑
  (Windows 的 ipconfig 只有樣本;cargo check --target x86_64-pc-windows-msvc 卡在 ring 要 Windows SDK 的 C 標頭,cfg(windows) 那幾行沒編譯過);設定頁顯示快取的那一行沒有開視窗看。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-18 11:35:43 +08:00
parent afb1bff057
commit 0c250d5a41
6 changed files with 434 additions and 145 deletions

View File

@ -502,7 +502,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 - **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。
- **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。 - **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。
- **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 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 秒自己再試,不用關掉再開。 - **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——登入、從帳號備份還原、長連線每次重連、備份和同步都在開連線那一刻對真正要連的位址查,不符合就不連、狀態寫原因、之後再試;http 的帳號伺服器不走代理。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 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 裡)照樣讀得進來,下次存檔就分開。

View File

@ -43,8 +43,9 @@ 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 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`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。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。
- 帳號伺服器用 `http://` 時,只有這台電腦、Docker 網路裡的名字,或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」才會把帳號密碼送過去;其他(包括 Wi-Fi 上的 100.x)要 `https://`。 - 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在每次開連線時,對真正要連的那幾個位址做(名字第二次查可能答不一樣),長連線每次重連都重查;不符合就不連,狀態寫原因,之後再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。
- 一個字的名字是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS 或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。
## 已知限制(誠實清單) ## 已知限制(誠實清單)

View File

@ -4,7 +4,7 @@
## 子功能 ## 子功能
- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、Docker 網路裡的名字,或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。 - AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每一次連線都照這個查;不符合就先不連,「AnyBot 帳號」的狀態寫原因,之後自己再試。
- 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 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),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。 - 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)、連接埠都被占用或不准用(1024 以下要管理員權限)時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。
- Tailscale 通道從 ifconfig、ip -o addr(Linux)、ipconfig(Windows,看名字有 Tailscale 的介面卡)認;認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 - Tailscale 通道:macOS 是帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::)的 utun,Linux 是 tailscale… 介面,Windows 是名字有 Tailscale 的介面卡;只有 100.x 的其他通道(PPPoE、電信 NAT、Cloudflare WARP)不算。認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
- 換手機密碼會把所有直接連線的手機登出。 - 換手機密碼會把所有直接連線的手機登出。
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。

View File

@ -7,7 +7,7 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
@ -91,21 +91,57 @@ fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool {
peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical())) peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical()))
} }
/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel) /// What the interfaces look like now: the text `ifconfig` (macOS, Linux net-tools), `ip -o addr`
/// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from /// (Linux) or `ipconfig` (Windows) printed, and this machine's Tailscale addresses in it.
/// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most #[derive(Clone, Default)]
/// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to pub struct Interfaces {
/// https like the rest. pub text: String,
pub fn tunnel_addrs() -> Vec<IpAddr> { pub tunnels: Vec<IpAddr>,
#[cfg(test)] }
if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() {
return v; /// The interfaces, read at most every 30 seconds — and never on the caller's thread after the
/// first time: an older answer is served while a fresh one is read in the background (設定 asks
/// every frame; on Windows each read starts `ipconfig`).
pub fn interfaces() -> Interfaces {
static CACHE: Snapshot = Snapshot::new();
CACHE.get(Duration::from_secs(30), read_interfaces)
}
/// A value read now and then: the first read on the caller's thread, then the last one served
/// while a new one is read on a thread of its own once it is `max_age` old.
pub struct Snapshot {
value: Mutex<Option<(std::time::Instant, Interfaces)>>,
reading: AtomicBool,
}
impl Snapshot {
pub const fn new() -> Snapshot {
Snapshot { value: Mutex::new(None), reading: AtomicBool::new(false) }
} }
static CACHE: Mutex<Option<(std::time::Instant, Vec<IpAddr>)>> = Mutex::new(None);
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); pub fn get(&'static self, max_age: Duration, read: fn() -> Interfaces) -> Interfaces {
if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) { let cached = self.value.lock().unwrap_or_else(|e| e.into_inner()).clone();
return v.clone(); match cached {
Some((at, v)) => {
if at.elapsed() >= max_age && !self.reading.swap(true, Ordering::SeqCst) {
std::thread::spawn(move || {
let fresh = read();
*self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh));
self.reading.store(false, Ordering::SeqCst);
});
}
v
}
None => {
let fresh = read();
*self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh.clone()));
fresh
}
}
} }
}
fn read_interfaces() -> Interfaces {
let run = |cmd: &str, args: &[&str]| { let run = |cmd: &str, args: &[&str]| {
let mut c = std::process::Command::new(cmd); let mut c = std::process::Command::new(cmd);
c.args(args); c.args(args);
@ -117,17 +153,31 @@ pub fn tunnel_addrs() -> Vec<IpAddr> {
} }
c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default() c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default()
}; };
let v = if cfg!(windows) { if cfg!(windows) {
parse_ipconfig_tunnels(&run("ipconfig", &[])) let text = run("ipconfig", &[]);
} else { let tunnels = parse_ipconfig_tunnels(&text);
let mut text = run("ifconfig", &[]); return Interfaces { text, tunnels };
if text.trim().is_empty() { }
text = run("ip", &["-o", "addr"]); let text = run("ifconfig", &[]);
} let tunnels = parse_tunnel_addrs(&text);
parse_tunnel_addrs(&text) if !tunnels.is_empty() {
}; return Interfaces { text, tunnels };
*cache = Some((std::time::Instant::now(), v.clone())); }
v // No ifconfig, or one that prints the old way (busybox, old net-tools: "inet addr:…"):
// ask `ip` too, and keep its text when ifconfig said nothing.
let ip = run("ip", &["-o", "addr"]);
let tunnels = parse_tunnel_addrs(&ip);
Interfaces { text: if text.trim().is_empty() { ip } else { text }, tunnels }
}
/// This machine's Tailscale addresses (see `parse_tunnel_addrs`, `parse_ipconfig_tunnels`). Where
/// none can be read there are none, and plain HTTP over Tailscale is sent to https like the rest.
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;
}
interfaces().tunnels
} }
/// Tests that need to say which addresses are this machine's tunnel's (one at a time). /// Tests that need to say which addresses are this machine's tunnel's (one at a time).
@ -153,11 +203,24 @@ pub fn source_for(dest: IpAddr) -> Option<IpAddr> {
s.local_addr().ok().map(|a| a.ip().to_canonical()) 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 /// The addresses of a server reached through this machine's Tailscale tunnel, to connect to:
/// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x /// every address is a Tailscale one, and every one with a route at all leaves from a tunnel
/// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale. /// address (`source` says from where). One with no route (IPv6 on a machine without it) is left
pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option<IpAddr>) -> bool { /// out — it can't be reached, so nothing goes to it. None: not Tailscale (a 100.x address on a
!addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical()))) /// Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi), or nothing left to connect to.
pub fn tunnel_route(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option<IpAddr>) -> Option<Vec<IpAddr>> {
let mut keep = vec![];
for &a in addrs {
if !tailscale_range(a) {
return None;
}
match source(a) {
None => {}
Some(s) if tunnels.contains(&s.to_canonical()) => keep.push(a),
Some(_) => return None,
}
}
(!keep.is_empty()).then_some(keep)
} }
/// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at /// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at
@ -188,45 +251,66 @@ fn parse_ipconfig_tunnels(text: &str) -> Vec<IpAddr> {
out out
} }
/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags: /// The Tailscale addresses in `ifconfig` output (an interface starts at the left margin, its
/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a /// addresses indented under it) or `ip -o addr` output (one address a line, the interface's name
/// /32 or /128 of its own). /// second). An interface is Tailscale's when it is named tailscale… (Linux), or when it is a
/// point-to-point tunnel that also carries a Tailscale IPv6 address (fd7a:115c:a1e0::/48 —
/// macOS's utun): a 100.64.0.0/10 address alone isn't, since PPPoE, a phone's carrier NAT and
/// Cloudflare WARP use that range too. `ip -o addr` has no flags: tailscale… or the IPv6 address.
fn parse_tunnel_addrs(text: &str) -> Vec<IpAddr> { fn parse_tunnel_addrs(text: &str) -> Vec<IpAddr> {
let mut out = vec![]; // (interface, point-to-point, its Tailscale-range addresses)
let mut tunnel = false; let mut ifaces: Vec<(String, bool, Vec<IpAddr>)> = vec![];
let mut at = |name: &str, p2p: bool| -> usize {
match ifaces.iter().position(|(n, _, _)| n == name) {
Some(i) => i,
None => {
ifaces.push((name.to_string(), p2p, vec![]));
ifaces.len() - 1
}
}
};
let mut current: Option<usize> = None;
let mut found: Vec<(usize, IpAddr)> = vec![];
for line in text.lines() { for line in text.lines() {
let words: Vec<&str> = line.split_whitespace().collect(); let words: Vec<&str> = line.split_whitespace().collect();
let is_family = |w: &&str| *w == "inet" || *w == "inet6"; let family = |w: &&str| *w == "inet" || *w == "inet6";
// `ip -o addr`: "4: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …". let address = |w: &str| w.split(['%', '/']).next().unwrap_or(w).parse::<IpAddr>().ok();
let numbered = words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::<u32>().is_ok()); // `ip -o addr`: "5: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …".
if numbered { if words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::<u32>().is_ok()) {
if let (Some(name), Some(i)) = (words.get(1), words.iter().position(is_family)) { if let (Some(name), Some(i)) = (words.get(1), words.iter().position(family)) {
let addr = words.get(i + 1).copied().unwrap_or(""); let i_face = at(name.trim_end_matches(':'), false);
let (ip, prefix) = addr.split_once('/').unwrap_or((addr, "")); if let Some(ip) = words.get(i + 1).and_then(|w| address(w)) {
if let Ok(ip) = ip.parse::<IpAddr>() { found.push((i_face, ip));
if tailscale_range(ip) && (name.starts_with("tailscale") || prefix == "32" || prefix == "128") {
out.push(ip.to_canonical());
}
} }
} }
continue; continue;
} }
// `ifconfig`: an interface starts at the left margin; its addresses are indented under it.
if !line.is_empty() && !line.starts_with(char::is_whitespace) { if !line.is_empty() && !line.starts_with(char::is_whitespace) {
tunnel = line.contains("POINTOPOINT"); let name = line.split(':').next().unwrap_or("").trim();
current = Some(at(name, line.contains("POINTOPOINT")));
continue; continue;
} }
if let (true, Some(family), Some(addr)) = (tunnel, words.first(), words.get(1)) { if let (Some(i_face), Some(w), Some(addr)) = (current, words.first(), words.get(1)) {
let addr = addr.split(['%', '/']).next().unwrap_or(addr); if family(w) {
if is_family(family) { if let Some(ip) = address(addr) {
if let Ok(ip) = addr.parse::<IpAddr>() { found.push((i_face, ip));
if tailscale_range(ip) {
out.push(ip.to_canonical());
}
} }
} }
} }
} }
for (i, ip) in found {
if tailscale_range(ip) {
ifaces[i].2.push(ip.to_canonical());
}
}
let ula = |ip: &IpAddr| matches!(ip, IpAddr::V6(_));
let mut out = vec![];
for (name, p2p, addrs) in ifaces {
let has_ula = addrs.iter().any(ula);
if name.starts_with("tailscale") || (has_ula && (p2p || !text.contains("flags="))) {
out.extend(addrs);
}
}
out.dedup(); out.dedup();
out out
} }
@ -523,6 +607,41 @@ mod tests {
5: tailscale0 inet6 fd7a:115c:a1e0::3/128 scope global \\ valid_lft forever preferred_lft forever\n"; 5: tailscale0 inet6 fd7a:115c:a1e0::3/128 scope global \\ valid_lft forever preferred_lft forever\n";
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());
// Other tunnels in the same range aren't Tailscale: PPPoE or a phone's carrier NAT
// (POINTOPOINT, 100.x, no Tailscale IPv6), Cloudflare WARP (utun, 100.96.x, its own IPv6),
// and on `ip -o addr` a /32 that isn't on tailscale0 and has no Tailscale IPv6.
let others = "ppp0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500\n\tinet 100.72.9.1 --> 100.64.0.1 netmask 0xffffffff\n\
utun7: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280\n\tinet 100.96.0.5 --> 100.96.0.5 netmask 0xffffffff\n\tinet6 2606:4700:110:8a1c::5 prefixlen 128\n";
assert!(parse_tunnel_addrs(others).is_empty(), "{:?}", parse_tunnel_addrs(others));
let iproute_others = "3: wwan0 inet 100.72.9.1/32 scope global wwan0\\ valid_lft forever preferred_lft forever\n";
assert!(parse_tunnel_addrs(iproute_others).is_empty());
// busybox / old net-tools print "inet addr:…": nothing here, so ip -o addr is asked too.
let busybox = "tailscale0 Link encap:UNSPEC HWaddr 00-00\n inet addr:100.101.2.3 P-t-P:100.101.2.3 Mask:255.255.255.255\n UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1280\n";
assert!(parse_tunnel_addrs(busybox).is_empty());
}
/// The interfaces are read on the caller's thread only the first time; after that an old
/// answer comes back at once and the new one is read on a thread of its own (設定 asks every
/// frame; a read is a program started).
#[test]
fn interfaces_are_read_off_the_callers_thread_after_the_first_time() {
static SNAP: Snapshot = Snapshot::new();
static READS: AtomicUsize = AtomicUsize::new(0);
fn slow() -> Interfaces {
std::thread::sleep(Duration::from_millis(300));
let n = READS.fetch_add(1, Ordering::SeqCst) + 1;
Interfaces { text: format!("read {n}"), tunnels: vec![] }
}
assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "the first read is waited for");
std::thread::sleep(Duration::from_millis(80));
let t = std::time::Instant::now();
assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "an old answer, at once");
assert!(t.elapsed() < Duration::from_millis(150), "waited {:?} on the caller's thread", t.elapsed());
let t = std::time::Instant::now();
while SNAP.get(Duration::from_secs(60), slow).text != "read 2" {
assert!(t.elapsed() < Duration::from_secs(3), "the new answer never came");
std::thread::sleep(Duration::from_millis(20));
}
} }
/// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a /// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a
@ -545,12 +664,17 @@ mod tests {
let tunnels = [ip("100.84.144.91")]; let tunnels = [ip("100.84.144.91")];
let via_tunnel = |_| Some(ip("100.84.144.91")); let via_tunnel = |_| Some(ip("100.84.144.91"));
let via_wifi = |_| Some(ip("100.70.0.5")); let via_wifi = |_| Some(ip("100.70.0.5"));
assert!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel)); assert_eq!(tunnel_route(&[ip("100.82.106.34")], &tunnels, via_tunnel), Some(vec![ip("100.82.106.34")]));
assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses"); assert_eq!(tunnel_route(&[ip("100.70.0.10")], &tunnels, via_wifi), None, "a Wi-Fi of 100.x addresses");
assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here"); assert_eq!(tunnel_route(&[ip("100.82.106.34")], &[], via_tunnel), None, "no Tailscale here");
assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one"); assert_eq!(tunnel_route(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), None, "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_eq!(tunnel_route(&[ip("192.168.1.10")], &tunnels, via_tunnel), None, "a subnet behind the tailnet is not a Tailscale address");
assert!(!tailscale_server(&[], &tunnels, via_tunnel)); assert_eq!(tunnel_route(&[], &tunnels, via_tunnel), None);
// A machine without IPv6: the server's IPv6 address has no route at all, so it is left
// out and the IPv4 one is used (it used to refuse the server).
let no_v6 = |a: IpAddr| if a.is_ipv6() { None } else { Some(ip("100.84.144.91")) };
assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5"), ip("100.82.106.34")], &tunnels, no_v6), Some(vec![ip("100.82.106.34")]));
assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5")], &tunnels, no_v6), None, "nothing left to connect to");
// The route really is asked: to this machine itself it leaves from loopback. // 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"))); assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1")));
} }

View File

@ -1396,27 +1396,19 @@ fn private_host(host: &str) -> bool {
} }
} }
/// The host (an IPv6 address without its brackets) and port of a URL. /// The host (an IPv6 address without its brackets) and port of a URL — read by the parser the
fn host_port(url: &str) -> Option<(String, u16)> { /// HTTP client (ureq) itself uses, so the address checked is the address connected to. (A
let (scheme, rest) = url.split_once("://")?; /// hand-made split read `http://100.70.0.10:8780?@relay` as the host `relay`; ureq connects to
let auth = rest.split('/').next()?; /// 100.70.0.10.) None: not a URL the client would open.
let auth = auth.rsplit('@').next()?; pub(crate) fn host_port(url: &str) -> Option<(String, u16)> {
let usual = if scheme == "https" { 443 } else { 80 }; let uri: ureq::http::Uri = url.trim().parse().ok()?;
// An IPv6 address comes in brackets (its own colons aren't the port's); it is given back let scheme = uri.scheme_str()?.to_ascii_lowercase();
// without them — bracketed, it would go into the 區網 certificate as a name, not an address. let host = uri.host()?.trim_start_matches('[').trim_end_matches(']').to_string();
if let Some(rest) = auth.strip_prefix('[') { let port = uri.port_u16().unwrap_or(match scheme.as_str() {
let (h, after) = rest.split_once(']')?; "https" | "wss" => 443,
let p = match after.strip_prefix(':') { _ => 80,
Some(p) => p.parse().ok()?, });
None if after.is_empty() => usual, (!host.is_empty()).then_some((host, port))
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
@ -1575,19 +1567,41 @@ fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) {
std::thread::spawn(move || lan_up(gen, bind, start, every)); std::thread::spawn(move || lan_up(gen, bind, start, every));
} }
/// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定). /// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定):
/// the address isn't on this computer, the ports aren't allowed (below 1024 without the
/// administrator; a range Windows keeps for itself), or another program has them.
fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result<std::net::TcpListener, String> { fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result<std::net::TcpListener, String> {
let end = start.saturating_add(10); let last = start.saturating_add(9);
for p in start..end { let mut errors = vec![];
for p in start..=last {
match std::net::TcpListener::bind((bind, p)) { match std::net::TcpListener::bind((bind, p)) {
Ok(l) => return Ok(l), Ok(l) => return Ok(l),
Err(e) if e.kind() == std::io::ErrorKind::AddrNotAvailable => { Err(e) => {
return Err(format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開")); let missing = e.kind() == std::io::ErrorKind::AddrNotAvailable;
errors.push(e);
if missing {
break;
}
} }
Err(_) => {}
} }
} }
Err(format!("連接埠 {start}–{} 都被別的程式占用:空出來就會自動打開", end - 1)) Err(bind_problem(bind, start, &errors))
}
/// Why no port of start…start+9 could be had, from what each try said.
fn bind_problem(bind: std::net::IpAddr, start: u16, errors: &[std::io::Error]) -> String {
use std::io::ErrorKind as K;
let last = start.saturating_add(9);
let ports = if last == start { format!("連接埠 {start}") } else { format!("連接埠 {start}–{last}") };
if errors.iter().any(|e| e.kind() == K::AddrNotAvailable) {
format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開")
} else if errors.iter().any(|e| e.kind() == K::PermissionDenied) {
format!("{ports} 不准這個程式用(1024 以下要管理員權限,或被系統保留了):用 ANYBOT_PHONE_PORT 換一個起始連接埠")
} else if let Some(e) = errors.iter().find(|e| e.kind() != K::AddrInUse) {
format!("{ports} 開不起來({e}):之後會自動再試")
} else {
format!("{ports} 都被別的程式占用:空出來就會自動打開")
}
} }
/// Take the port for generation `gen`, then serve. The listener of the generation before gives /// Take the port for generation `gen`, then serve. The listener of the generation before gives
@ -1775,14 +1789,12 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) {
/// Addresses a phone can open (local network and Tailscale), or just the one ANYBOT_PHONE_BIND /// Addresses a phone can open (local network and Tailscale), or just the one ANYBOT_PHONE_BIND
/// names. /// names.
pub fn addresses(port: u16) -> Vec<String> { pub fn addresses(port: u16) -> Vec<String> {
// macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -4 -o addr` ("… inet 192.168.1.5/24 …"). // macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -o addr` ("… inet 192.168.1.5/24 …").
let mut out = std::process::Command::new("ifconfig").output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); // (Read at most every 30 s, off this thread after the first time: 設定 asks every frame.)
if out.trim().is_empty() { let found = crate::lantls::interfaces();
out = std::process::Command::new("ip").args(["-4", "-o", "addr"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
}
// (set_lan has already refused an ANYBOT_PHONE_BIND that isn't an address.) // (set_lan has already refused an ANYBOT_PHONE_BIND that isn't an address.)
let bind = lan_bind().unwrap_or(std::net::Ipv4Addr::UNSPECIFIED.into()); let bind = lan_bind().unwrap_or(std::net::Ipv4Addr::UNSPECIFIED.into());
listed(&out, port, bind, lan_fingerprint().is_some(), &crate::lantls::tunnel_addrs()) listed(&found.text, port, bind, lan_fingerprint().is_some(), &crate::lantls::tunnel_addrs())
} }
/// The addresses in `ifconfig` / `ip -4 -o addr` output as links: https where the certificate /// The addresses in `ifconfig` / `ip -4 -o addr` output as links: https where the certificate
@ -1823,6 +1835,12 @@ fn agent(secs: u64) -> ureq::Agent {
pub fn why_unreachable(e: &ureq::Error) -> String { pub fn why_unreachable(e: &ureq::Error) -> String {
use std::io::ErrorKind as K; use std::io::ErrorKind as K;
use ureq::Error as E; use ureq::Error as E;
// The plain-http check refused (relay_agent): its own words.
if let E::Io(io) = e {
if io.kind() == K::PermissionDenied && io.to_string().contains("http://") {
return io.to_string();
}
}
let text = e.to_string().to_lowercase(); let text = e.to_string().to_lowercase();
// A TLS failure often comes wrapped as an I/O error: look at the words first. // A TLS failure often comes wrapped as an I/O error: look at the words first.
// A certificate no one this computer trusts has signed: usually a server that signs its own. // A certificate no one this computer trusts has signed: usually a server that signs its own.
@ -1865,8 +1883,13 @@ pub fn why_refused(st: u16, v: &Value, whom: &str) -> String {
} }
} }
/// Every request that carries the account password (sign in, sign up, 兩步驗證, 配對) or this
/// computer's key goes to the account server through here or through `relay_agent`.
pub fn relay_post(url: &str, bearer: &str, body: &Value) -> Result<Value, String> { pub fn relay_post(url: &str, bearer: &str, body: &Value) -> Result<Value, String> {
let mut r = agent(30).post(url).header("Content-Type", "application/json"); if let Some(why) = relay_plain_problem(url) {
return Err(why);
}
let mut r = relay_agent(30, url).post(url).header("Content-Type", "application/json");
if !bearer.is_empty() { if !bearer.is_empty() {
r = r.header("Authorization", &format!("Bearer {bearer}")); r = r.header("Authorization", &format!("Bearer {bearer}"));
} }
@ -1884,23 +1907,90 @@ 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 /// Whether an http:// account server is off the air, so the account password and this
/// unencrypted: this machine, a name inside one Docker network (http://relay:8080), or a server /// computer's key may go to it unencrypted. `host` is the name in the URL and `addrs` what it
/// reached through this machine's Tailscale tunnel — every address the name has is a Tailscale /// resolved to — the very addresses about to be connected to (a name can answer differently the
/// one and the route to it leaves from the tunnel (lantls::tailscale_server). An address in /// second time, so the check is made at the moment of connecting, on what it answered then).
/// 100.64.0.0/10 alone isn't Tailscale: a Wi-Fi can hand those out. /// Off the air: this machine (localhost, loopback); a one-word name, taken to be another
fn plain_relay_ok(url: &str) -> bool { /// container of the same Docker network (http://relay:8080 — see SECURITY.md about such names on
/// an ordinary network); or a server reached through this machine's Tailscale tunnel
/// (lantls::tunnel_route: Tailscale addresses whose route leaves from the tunnel; one with no
/// route at all, IPv6 on a machine without it, is left out). An address in 100.64.0.0/10 alone
/// isn't Tailscale: a Wi-Fi can hand those out. The answer is the addresses to connect to.
pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result<Vec<std::net::SocketAddr>, String> {
let host = host.trim_start_matches('[').trim_end_matches(']');
let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連(之後會再試)。請改用 https://,或等 Tailscale 連上"));
if host.eq_ignore_ascii_case("localhost") || (!addrs.is_empty() && addrs.iter().all(|a| a.ip().to_canonical().is_loopback())) {
return Ok(addrs.to_vec());
}
if !host.is_empty() && !host.contains('.') && host.parse::<std::net::IpAddr>().is_err() {
return Ok(addrs.to_vec());
}
let ips: Vec<std::net::IpAddr> = addrs.iter().map(|a| a.ip()).collect();
match crate::lantls::tunnel_route(&ips, &crate::lantls::tunnel_addrs(), crate::lantls::source_for) {
Some(keep) => Ok(addrs.iter().filter(|a| keep.contains(&a.ip())).copied().collect()),
None => refuse(),
}
}
/// Why the account server at `url` (its address or anything under it) won't be sent anything
/// right now, or None (https, or an http:// one off the air — `plain_hop`). For saying so: what
/// actually holds is the same check made where the connection is opened (`relay_agent`'s
/// resolver, tunnel::open).
pub(crate) fn relay_plain_problem(url: &str) -> Option<String> {
use std::net::ToSocketAddrs; use std::net::ToSocketAddrs;
let Some((host, port)) = host_port(url) else { return false }; let Some((host, port)) = host_port(url) else { return Some(format!("帳號伺服器的網址看不懂:{url}")) };
let ip = host.parse::<std::net::IpAddr>().ok(); if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) {
if host == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) { return None;
return true;
} }
if ip.is_none() && !host.is_empty() && !host.contains('.') { let addrs: Vec<std::net::SocketAddr> = (host.as_str(), port).to_socket_addrs().map(|a| a.collect()).unwrap_or_default();
return true; if addrs.is_empty() {
return None; // (Can't be found: the request fails the ordinary way, saying so.)
}
plain_hop(&host, &addrs).err()
}
/// The client for a request to the account server at `url`. An https:// one is the common
/// client. An http:// one gets a client that makes the `plain_hop` check on the addresses it is
/// about to connect to, and goes there directly — not through a proxy, which would carry the
/// password on in the clear wherever it routes.
pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent {
if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) {
return agent(secs);
}
static AGENTS: OnceLock<Mutex<HashMap<u64, ureq::Agent>>> = OnceLock::new();
AGENTS
.get_or_init(Mutex::default)
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(secs)
.or_insert_with(|| {
let config = crate::net::config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).proxy(None).build();
ureq::Agent::with_parts(config, ureq::unversioned::transport::DefaultConnector::new(), OffTheAir(Default::default()))
})
.clone()
}
/// Looks names up like the default resolver, then keeps only addresses `plain_hop` allows — or
/// refuses, before a byte is sent.
#[derive(Debug)]
struct OffTheAir(ureq::unversioned::resolver::DefaultResolver);
impl ureq::unversioned::resolver::Resolver for OffTheAir {
fn resolve(&self, uri: &ureq::http::Uri, config: &ureq::config::Config, timeout: ureq::unversioned::transport::NextTimeout) -> Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
let addrs = self.0.resolve(uri, config, timeout)?;
let found: Vec<std::net::SocketAddr> = addrs.iter().copied().collect();
match plain_hop(uri.host().unwrap_or(""), &found) {
Ok(keep) => {
let mut out = self.empty();
for a in keep {
out.push(a);
}
Ok(out)
}
Err(why) => Err(ureq::Error::Io(std::io::Error::new(std::io::ErrorKind::PermissionDenied, why))),
}
} }
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
@ -1938,8 +2028,8 @@ 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);
if !url.starts_with("https://") && !plain_relay_ok(&url) { if let Some(why) = relay_plain_problem(&url) {
return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into()); return Err(why);
} }
if create { if create {
if let Err(e) = relay_post(&format!("{url}/relay/signup"), "", &json!({"user": user, "password": password, "invite": invite})) { if let Err(e) = relay_post(&format!("{url}/relay/signup"), "", &json!({"user": user, "password": password, "invite": invite})) {
@ -1998,7 +2088,8 @@ fn alive(gen: u64) -> bool {
fn relay_worker(url: &str, token: &str, gen: u64) { fn relay_worker(url: &str, token: &str, gen: u64) {
let mut backoff = 1u64; let mut backoff = 1u64;
while alive(gen) { while alive(gen) {
let r = agent(40).get(&format!("{url}/relay/host/next")).header("Authorization", &format!("Bearer {token}")).call(); let next = format!("{url}/relay/host/next");
let r = relay_agent(40, &next).get(&next).header("Authorization", &format!("Bearer {token}")).call();
let mut resp = match r { let mut resp = match r {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
@ -2042,7 +2133,8 @@ fn relay_worker(url: &str, token: &str, gen: u64) {
let (url, token) = (url.to_string(), token.to_string()); let (url, token) = (url.to_string(), token.to_string());
std::thread::spawn(move || { std::thread::spawn(move || {
let resp = handle(req, true); let resp = handle(req, true);
let _ = agent(60).post(&format!("{url}/relay/host/reply/{id}")).header("Authorization", &format!("Bearer {token}")).header("Content-Type", "application/json").send(resp_to_json(&resp).to_string().as_bytes()); let reply = format!("{url}/relay/host/reply/{id}");
let _ = relay_agent(60, &reply).post(&reply).header("Authorization", &format!("Bearer {token}")).header("Content-Type", "application/json").send(resp_to_json(&resp).to_string().as_bytes());
}); });
} }
} }
@ -2076,7 +2168,7 @@ pub fn resp_to_json(r: &Resp) -> Value {
pub fn backup_now(s: &Settings, state_json: &[u8]) -> Result<usize, String> { pub fn backup_now(s: &Settings, state_json: &[u8]) -> Result<usize, String> {
let key = key_of(&s.backup_key).ok_or("還沒登入帳號")?; let key = key_of(&s.backup_key).ok_or("還沒登入帳號")?;
let sealed = httpd::seal(&key, state_json); let sealed = httpd::seal(&key, state_json);
let mut resp = agent(120) let mut resp = relay_agent(120, &s.relay_url)
.put(&format!("{}/relay/backup", s.relay_url)) .put(&format!("{}/relay/backup", s.relay_url))
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/octet-stream") .header("Content-Type", "application/octet-stream")
@ -2096,7 +2188,7 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result<Vec<
let user = user.as_str(); let user = user.as_str();
let url = base(url); let url = base(url);
let session = relay_login(&url, user, password, "還原備份", code)?; let session = relay_login(&url, user, password, "還原備份", code)?;
let mut resp = agent(120).get(&format!("{url}/relay/backup")).header("Authorization", &format!("Bearer {session}")).call().map_err(|e| e.to_string())?; let mut resp = relay_agent(120, &url).get(&format!("{url}/relay/backup")).header("Authorization", &format!("Bearer {session}")).call().map_err(|e| why_unreachable(&e))?;
let _ = relay_post(&format!("{url}/relay/logout"), &session, &json!({})); let _ = relay_post(&format!("{url}/relay/logout"), &session, &json!({}));
if resp.status().as_u16() == 404 { if resp.status().as_u16() == 404 {
return Err("這個帳號還沒有備份".into()); return Err("這個帳號還沒有備份".into());
@ -2128,7 +2220,7 @@ pub fn run_on_device(host_id: &str, tool: &str, args: &str, who: &str) -> Result
return r.map_err(|e| format!("連不到那台電腦:{e}")).and_then(|a| answer_value(a.status, &a.body, "那台電腦")); return r.map_err(|e| format!("連不到那台電腦:{e}")).and_then(|a| answer_value(a.status, &a.body, "那台電腦"));
} }
let url = format!("{}/relay/hosts/{host_id}/api/device/run", s.relay_url); let url = format!("{}/relay/hosts/{host_id}/api/device/run", s.relay_url);
let mut resp = agent(45) let mut resp = relay_agent(45, &url)
.post(&url) .post(&url)
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
@ -2201,7 +2293,7 @@ fn to_brain_any(s: &Settings, method: &str, rest: &str, query: &[(&str, String)]
let q: Vec<String> = query.iter().map(|(k, v)| format!("{k}={}", httpd::url_encode(v))).collect(); let q: Vec<String> = query.iter().map(|(k, v)| format!("{k}={}", httpd::url_encode(v))).collect();
let url = brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?; let url = brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?;
let auth = format!("Bearer {}", s.host_token); let auth = format!("Bearer {}", s.host_token);
let r = if method == "GET" { agent(secs).get(&url).header("Authorization", &auth).call() } else { agent(secs).post(&url).header("Authorization", &auth).header("Content-Type", "application/octet-stream").send(body) }; let r = if method == "GET" { relay_agent(secs, &url).get(&url).header("Authorization", &auth).call() } else { relay_agent(secs, &url).post(&url).header("Authorization", &auth).header("Content-Type", "application/octet-stream").send(body) };
let mut resp = r.map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; let mut resp = r.map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?;
let st = resp.status().as_u16(); let st = resp.status().as_u16();
let bytes = resp.body_mut().with_config().limit(200 * 1024 * 1024).read_to_vec().map_err(|_| "和大腦的連線到一半斷掉了".to_string())?; let bytes = resp.body_mut().with_config().limit(200 * 1024 * 1024).read_to_vec().map_err(|_| "和大腦的連線到一半斷掉了".to_string())?;
@ -2261,7 +2353,7 @@ pub fn screen_ticket(s: &Settings) -> Result<String, String> {
return Err("這台沒有連到帳號的大腦".into()); return Err("這台沒有連到帳號的大腦".into());
} }
let url = format!("{}/relay/screen-ticket", s.relay_url.trim_end_matches('/')); let url = format!("{}/relay/screen-ticket", s.relay_url.trim_end_matches('/'));
let mut r = agent(15) let mut r = relay_agent(15, &url)
.post(&url) .post(&url)
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
@ -2440,7 +2532,7 @@ pub fn publish_site(name: &str, local: &std::path::Path) -> Result<String, Strin
/// 團隊: who else this AnyBot is shared with (user, role). /// 團隊: who else this AnyBot is shared with (user, role).
/// The team: (account, role). A role ending in 「?」 was invited and hasn't accepted yet. /// The team: (account, role). A role ending in 「?」 was invited and hasn't accepted yet.
pub fn members(s: &Settings) -> Result<Vec<(String, String)>, String> { pub fn members(s: &Settings) -> Result<Vec<(String, String)>, String> {
let mut r = agent(10).get(&format!("{}/relay/host/members", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| e.to_string())?; let mut r = relay_agent(10, &s.relay_url).get(&format!("{}/relay/host/members", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| e.to_string())?;
let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null);
Ok(v["members"].as_array().map(|a| a.iter().map(|m| (m["user"].as_str().unwrap_or("").to_string(), format!("{}{}", m["role"].as_str().unwrap_or(""), if m["pending"] == true { "?" } else { "" }))).collect()).unwrap_or_default()) Ok(v["members"].as_array().map(|a| a.iter().map(|m| (m["user"].as_str().unwrap_or("").to_string(), format!("{}{}", m["role"].as_str().unwrap_or(""), if m["pending"] == true { "?" } else { "" }))).collect()).unwrap_or_default())
} }
@ -2483,7 +2575,7 @@ pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result<Set
/// The account's AnyBots as the account server sees them (for choosing a brain). /// The account's AnyBots as the account server sees them (for choosing a brain).
pub fn peers(s: &Settings) -> Result<Vec<Value>, String> { pub fn peers(s: &Settings) -> Result<Vec<Value>, String> {
let mut r = agent(15).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; let mut r = relay_agent(15, &s.relay_url).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?;
let st = r.status().as_u16(); let st = r.status().as_u16();
let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null);
if !(200..300).contains(&st) { if !(200..300).contains(&st) {
@ -2608,7 +2700,7 @@ pub fn devices_online(s: &Settings) -> Vec<(String, String, bool)> {
if s.relay_url.is_empty() { if s.relay_url.is_empty() {
return vec![]; return vec![];
} }
let Ok(mut r) = agent(10).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call() else { return vec![] }; let Ok(mut r) = relay_agent(10, &s.relay_url).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call() else { return vec![] };
let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null);
*peer_rows().lock().unwrap() = v["hosts"] *peer_rows().lock().unwrap() = v["hosts"]
.as_array() .as_array()
@ -3042,26 +3134,92 @@ mod tests {
assert_eq!(lan_port(), None); assert_eq!(lan_port(), None);
} }
/// Why the phone page can't listen, said as it is: not 「被別的程式占用」 for ports the
/// system doesn't allow, and no 「65535–65534」 at the top of the range.
#[test]
fn bind_problems_are_said_as_they_are() {
use std::io::{Error, ErrorKind as K};
let lo: std::net::IpAddr = "127.0.0.1".parse().unwrap();
let said = |start, kinds: &[K]| bind_problem(lo, start, &kinds.iter().map(|k| Error::from(*k)).collect::<Vec<_>>());
assert!(said(80, &[K::PermissionDenied; 10]).contains("不准"), "{}", said(80, &[K::PermissionDenied; 10]));
assert!(said(8793, &[K::AddrInUse; 10]).contains("連接埠 8793–8802 都被別的程式占用"));
assert!(said(8793, &[K::AddrInUse, K::PermissionDenied]).contains("不准"));
assert!(said(8793, &[K::AddrNotAvailable]).contains("沒有 127.0.0.1 這個位址"));
let top = said(65535, &[K::AddrInUse]);
assert!(top.contains("連接埠 65535 都被") && !top.contains("65534"), "{top}");
// The top port is tried, not an empty range.
if let Ok(free) = std::net::TcpListener::bind(("127.0.0.1", 65535)) {
drop(free);
assert_eq!(bind_lan(lo, 65535).unwrap().local_addr().unwrap().port(), 65535);
}
}
/// The account password goes to an http:// account server only off the air: this computer, /// 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 /// 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. /// any 100.64.0.0/10 address (a Wi-Fi can hand those out), nor an IPv6 address taken for a
/// name, nor a host the HTTP client wouldn't read as the host.
#[test] #[test]
fn plain_http_to_an_account_server_only_off_the_air() { fn plain_http_to_an_account_server_only_off_the_air() {
let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap(); 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")); for ok in ["http://127.0.0.1:8780", "http://localhost:8780", "http://[::1]:8780", "http://relay:8080", "https://100.70.0.10"] {
assert_eq!(relay_plain_problem(ok), None, "{ok}");
}
crate::lantls::with_tunnels(&[], || { crate::lantls::with_tunnels(&[], || {
assert!(!plain_relay_ok("http://100.70.0.10:8080")); for bad in ["http://100.70.0.10:8080", "http://[fd00::5]:8080", "http://10.0.0.5:8080", "http://100.70.0.10:8780?@relay", "http://100.70.0.10:8780#@relay"] {
assert!(!plain_relay_ok("http://[fd00::5]:8080"), "an IPv6 address isn't a Docker name"); assert!(relay_plain_problem(bad).is_some_and(|w| w.contains("http://")), "{bad}");
assert!(!plain_relay_ok("http://10.0.0.5:8080")); }
// Refused before the password is sent anywhere. // Refused before the password is sent anywhere: signing in, and 從帳號備份還原.
let e = relay_join(&Settings::default(), "http://100.70.0.10:8080", "dan", "pw-123", false, "", "").unwrap_err(); let e = relay_join(&Settings::default(), "http://100.70.0.10:8080", "dan", "pw-123", false, "", "").unwrap_err();
assert!(e.contains("https://"), "{e}"); assert!(e.contains("http://") && e.contains("Tailscale"), "{e}");
let e = restore("http://100.70.0.10:8080", "dan", "pw-123", "").unwrap_err();
assert!(e.contains("http://") && e.contains("Tailscale"), "{e}");
}); });
// Where the route to a Tailscale address leaves from is this machine's tunnel: fine. // 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")) { 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"))); crate::lantls::with_tunnels(&[src], || assert_eq!(relay_plain_problem("http://100.101.2.3:8080"), None));
} }
} }
/// The URL is read the way the HTTP client reads it: the host stops at '?' and '#', so what is
/// checked is what is connected to (the private-address check of model requests too).
#[test]
fn urls_are_read_like_the_client_reads_them() {
assert_eq!(host_port("http://100.70.0.10:8780?@relay"), Some(("100.70.0.10".into(), 8780)));
assert_eq!(host_port("http://100.70.0.10#@relay/"), Some(("100.70.0.10".into(), 80)));
assert_eq!(host_port("http://user@10.0.0.5:8000/v1"), Some(("10.0.0.5".into(), 8000)));
assert_eq!(host_port("http://169.254.169.254\\@10.0.0.5/"), None, "the client won't open it either");
assert_eq!(model_fetch_here(&json!({"url": "http://169.254.169.254?@10.0.0.5/"}).to_string()).status, 403);
}
/// What holds is the check where the connection is opened: the http client for the account
/// server refuses an address off the tunnel before sending (and says so), the workers wait and
/// say why on every round, and the long connection re-checks on every (re)connect — a Wi-Fi of
/// 100.x addresses later, with Tailscale down, gets neither this computer's key nor control.
#[test]
fn an_http_account_server_off_the_tunnel_is_held_on_every_connect() {
crate::lantls::with_tunnels(&[], || {
let url = "http://100.70.0.10:8780";
let e = relay_agent(5, url).get(&format!("{url}/relay/host/next")).call().unwrap_err();
assert!(why_unreachable(&e).contains("Tailscale"), "{}", why_unreachable(&e));
// The workers (an account server without the long connection).
let gen = RELAY_GEN.load(Ordering::SeqCst);
let worker = std::thread::spawn(move || relay_worker(url, "key", gen));
let t = Instant::now();
while !hub().relay_status().contains("Tailscale") {
assert!(t.elapsed() < Duration::from_secs(10), "worker status: {}", hub().relay_status());
std::thread::sleep(Duration::from_millis(20));
}
RELAY_GEN.fetch_add(1, Ordering::SeqCst);
worker.join().unwrap();
// The long connection: refused at every try, and it keeps trying until stopped.
let said: Mutex<Vec<String>> = Mutex::new(vec![]);
let tries = std::sync::atomic::AtomicUsize::new(0);
crate::tunnel::run(url, "key", &|| tries.fetch_add(1, Ordering::SeqCst) < 40 && said.lock().unwrap().len() < 2, &|m| said.lock().unwrap().push(m.to_string()));
let said = said.into_inner().unwrap();
assert!(said.len() >= 2 && said.iter().all(|m| m.contains("Tailscale")), "{said:?}");
});
}
} }
/// Where the one-step installer lives (it also installs AnyBot on a computer that has nothing yet). /// Where the one-step installer lives (it also installs AnyBot on a computer that has nothing yet).

View File

@ -208,17 +208,23 @@ struct NoLink {
fn open(url: &str, token: &str) -> Result<WebSocket<Stream>, NoLink> { fn open(url: &str, token: &str) -> Result<WebSocket<Stream>, NoLink> {
use tungstenite::client::IntoClientRequest; use tungstenite::client::IntoClientRequest;
let fail = |why: &str| NoLink { old: false, why: why.to_string() }; let fail = |why: &str| NoLink { old: false, why: why.to_string() };
let (tls, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) { let tls = match (url.starts_with("https://"), url.starts_with("http://")) {
(Some(r), _) => (true, r), (true, _) => true,
(_, Some(r)) => (false, r), (_, true) => false,
_ => return Err(fail("帳號伺服器的網址不對")), _ => return Err(fail("帳號伺服器的網址不對")),
}; };
let hostport = rest.split('/').next().unwrap_or(""); // (Read by the same parser the other requests use: the address checked is the one connected to.)
let (host, port) = match hostport.rsplit_once(':') { let (host, port) = crate::remote::host_port(url).ok_or_else(|| fail("帳號伺服器的網址不對"))?;
Some((h, p)) if p.parse::<u16>().is_ok() => (h, p.parse().unwrap_or(443)), let host = host.as_str();
_ => (hostport, if tls { 443 } else { 80 }), let hostport = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
}; let mut addrs: Vec<_> = (host, port).to_socket_addrs().map_err(|_| fail("找不到伺服器:這台電腦可能沒連上網路,或伺服器網址打錯了"))?.collect();
let addrs: Vec<_> = (host, port).to_socket_addrs().map_err(|_| fail("找不到伺服器:這台電腦可能沒連上網路,或伺服器網址打錯了"))?.collect(); // http:// carries this computer's key in the clear, and whoever answers gets to run things
// here as the account's owner: only to a server off the air (remote::plain_hop), checked on
// every (re)connect against exactly the addresses connected to below. Refused, it says why and
// tries again later, like any connection that failed.
if !tls {
addrs = crate::remote::plain_hop(host, &addrs).map_err(|why| fail(&why))?;
}
// Each address in turn ("localhost" is both ::1 and 127.0.0.1). // Each address in turn ("localhost" is both ::1 and 127.0.0.1).
let mut last = None; let mut last = None;
let mut tcp = None; let mut tcp = None;