PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
修复断线后内容发不过去、中转后不再换直连,发布 1.1.1
baiyuze3d7f1f69c976
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6498e62..f00d161 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,25 @@# 更新记录 / Changelog+## 1.1.1 — 2026-10-09++- **修复:对方断线后,复制的内容发不过去。**连接悄悄断了(对方睡眠、断网、重启),本端却以为还连着,+ 不重连,复制的内容全部发进一条死连接,日志还记成「已发送」。现在连接失效会立即关闭并重连;对方重建了+ 连接,本端也随之换新;没真正送达的不再算成功。+ **Fixed: items copied after the other Mac dropped off never arrived.** A connection that died silently was+ never closed or reconnected, and everything copied afterwards went into it. Dead connections are now closed+ and rebuilt, and a transfer only counts once the data has actually left.+- **补发**:复制时对方连不上,就记下最近 20 条,连接恢复后补发。补发的只进复制记录,不写进对方的剪贴板。+ **Catch-up:** items copied while the other Mac is unreachable (latest 20) are sent when it reconnects. They go+ into its history, not its clipboard.+- **先中转,再换直连**:对端刚启动时出口地址可能晚到,第一次握手落到中转后就一直中转。现在中转时由发起方+ 在空闲时用 ICE 重启再打一次洞,打通就换成直连(10 秒后第一次,之后间隔逐步拉长到 15 分钟)。+ **Relay first, direct later:** a connection that lands on the relay now retries the direct path with an ICE+ restart while idle, and switches when it works.+- 出口探测并发解析域名,整轮从约 1.6 秒降到 0.2 秒以内;中转等待从 3 秒放宽到 5 秒。+ Uplink probing resolves hostnames in parallel (about 1.6 s down to under 0.2 s); the relay wait is now 5 s.+- NAT 打洞实验室新增「一开始打不通,先中转后换直连」场景,共 9 种。 The NAT lab adds a relay-then-direct scenario (9 in total).+- 协议:`ClipOffer` 新增 `backlog` 字段。服务器不需要升级。 Protocol: `ClipOffer.backlog`. No server upgrade needed.+## 1.1.0 — 2026-10-08- **多出口网络也能直连**:公司双线、运营商 NAT 地址池这类网络有多个出口,并按目标地址选出口。diff --git a/README.en.md b/README.en.mdindex 87d7cb1..c82d45e 100644--- a/README.en.md+++ b/README.en.md@@ -158,7 +158,51 @@ flowchart LR2. On a change it reads the content and picks a transport: text is inlined in the message; images and files under 50 MB are streamed right away (tar + zstd); anything larger is announced as a record only.3. The receiving Mac writes the data to a local cache and then onto its clipboard, so `⌘V` pastes real local files.-**How the connection is made:** devices connect to the signaling server over WebSocket and use WebRTC ICE to try a direct path (LAN addresses, then public addresses discovered via STUN), falling back to a TURN relay address. Data flows over WebRTC data channels, encrypted with DTLS.+**How the connection is made:**++1. Devices connect to the signaling server over WebSocket and receive STUN and TURN addresses.+2. All connections share one local UDP port. The background service probes several servers from that port to learn its public address, one per uplink on networks with several (see the next section).+3. During the handshake each side sends its LAN addresses, its public address on every uplink, and its TURN relay address; both sides try each other with WebRTC ICE at the same time.+4. A direct path wins if it works; relay paths must wait 5 seconds before they can be selected.+5. Once connected, each side tells the other whether it is relayed, and both show "relay" if either is.+6. If the connection still lands on the relay, the side that started it runs an ICE restart while idle to punch again, and moves to the direct path if that works (first after 10 seconds, then at intervals growing to 15 minutes).++Data flows over WebRTC data channels, encrypted with DTLS.++### Hole punching on networks with several uplinks++Office networks with two ISPs, or carriers with a pool of NAT addresses, have several uplinks and choose one per destination IP. One office network we measured had four:++| Uplink | Probe servers that landed on it | Public port |+|---|---|---|+| Uplink A | Our own server, Twilio | Unchanged |+| Uplink B | Bilibili, Google, Nextcloud | Unchanged |+| Uplink C | Cloudflare, FreeSWITCH | Rewritten, same for every destination |+| Uplink D | A service on Alibaba Cloud | Rewritten |++Asking one server reveals only one of these addresses. Packets to the peer may leave through another uplink, the peer sees an address it was never told about, and its router drops them. That is why CopySync 1.0 could only relay on such networks.++What 1.1 does:++- **One shared port.** pion used to open a new port for each STUN server, so each answer only applied to its own port. All connections now share one port, and every probe result applies to it.+- **Probe every uplink.** CopySync queries IP-diverse servers from that port in parallel (your own server plus public STUN servers such as Bilibili and Cloudflare), deduplicates by IP and drops addresses poisoned by DNS.+- **Tell the peer all of them.** Each uplink's address goes to the peer as a candidate; the peer checks each one, and the one matching the real uplink gets through. Uplinks that rewrite ports report their real mapping.+- **Remember uplinks.** If a round misses an uplink that preserves ports, its address is filled in as uplink IP plus local port.++A Mac behind that 4-uplink office network now connects directly to a home connection, about 3 seconds after reaching the server. The full design, measurements and validation are in [NAT traversal on multi-uplink networks](design/nat-traversal.md) (Chinese).++The **NAT lab** (`tools/natlab`) builds real topologies with Linux network namespaces and iptables and runs CopySync's actual connection code through nine scenarios on every commit:++| Scenario | Result |+|---|---|+| Single uplink ↔ home router | Direct |+| Two uplinks, previous version (control) | Relay |+| Two uplinks ↔ home router | Direct |+| Four uplinks ↔ home router | Direct |+| Two uplinks, second one not probed: no history / with history | Relay / Direct |+| Two uplinks ↔ two uplinks | Direct |+| Two uplinks ↔ NAT that randomizes ports | Relay |+| Blocked at first, network recovers later | Relay first, then direct |### Security model@@ -176,6 +220,9 @@ flowchart LR| No direct path (symmetric NAT, corporate firewall) | Switches to the TURN relay on your server, still encrypted; the app shows "relay" || Public STUN servers unreliable (common in mainland China) | The server runs its own STUN and clients prefer it || Multi-uplink networks that pick an uplink per destination (common in offices) | All connections share one local port; CopySync probes several servers from it to learn its address on every uplink and sends them all to the peer, filling gaps from history. See `copysync-cli nat` |+| Landed on the relay although a direct path works (the peer just started, its addresses arrived a moment late) | While idle, the side that started the connection runs an ICE restart to punch again and switches to direct if it works; never during a transfer. The connection stays up and only pauses for a few seconds |+| The other Mac sleeps, loses its network or restarts, and the connection dies silently | The dead connection is closed and reconnected right away; if the other side rebuilt its connection, this side follows |+| The other Mac can't be reached when you copy | The latest 20 items are kept and sent once the connection is back. They only go into the history and never overwrite what's on the other Mac's clipboard now || Signaling connection drops | Reconnects with exponential backoff (1 s up to 30 s, with jitter); status is shown live || Pairing confirmed on one side before the other | Early handshake messages are held and replayed once the other side confirms; the direct link is up within tens of milliseconds || Large files | Above the limit only a record is synced; if the source file is gone when you pull, you get a clear message |@@ -192,13 +239,19 @@ Each of these was found by testing and has a regression test. The full investiga- **macOS clipboard calls must run on the main thread.** With the privacy features on, the clipboard API talks to a system UI service through the run loop; calling it from a plain thread crashes. The service locks the main thread at startup and dedicates it to the clipboard.- **"Transfer only when the other side pastes" isn't possible on macOS.** The system resolves promised clipboard data about 0.1 s after it's written and caches it, and there is no notification that the clipboard was read. That's why small items are pushed ahead of time and large files are pulled on demand.- **Three pitfalls in the pion WebRTC library:** `DetachDataChannels()` is a global switch that breaks regular send/receive on every channel; `OnMessage` doesn't buffer, so messages arriving before the handler is set are dropped (202 bytes sent, 0 received); `OnBufferedAmountLow` is edge-triggered, so a waiter that arrives late never wakes up (a 20 MB transfer stalled at 786 KB).+- **pion opens a separate port per STUN server**, so the answers don't apply to each other. Adding STUN servers can't fix multi-uplink networks; all connections now share one port and CopySync probes it itself.+- **One side can't tell on its own whether a connection is relayed.** When one side sends through TURN, the other may just see an ordinary address; once one Mac showed "direct" and the other "relay". Both sides now tell each other after connecting.+- **pion never switches paths once it has picked one.** The relay handshake is fast, and if it wins that race the whole connection stays relayed. We saw exactly that after the peer restarted: its addresses arrived after the relay wait had expired. The relay wait is now 5 seconds, probe hostnames resolve in parallel (a probe round went from about 1.6 s to under 0.2 s), and relayed connections retry the direct path with an ICE restart.+- **A dead connection has to be cleaned up by hand.** When pion reports "failed" it doesn't close the connection; the control channel still looks open and whatever is written to it is lost, and the layer above thinks it's connected and never reconnects. In 1.1.0 this sent six files into a dead connection after the other Mac dropped off, and none arrived.+- **Public STUN domains can be poisoned by DNS**, resolving to `192.0.2.42` in our tests. Reserved ranges and proxy fake-IP ranges are filtered before probing.+- **Simulated routers need a firewall.** When both sides punch at once, a packet let through to the router itself leaves a Linux conntrack entry, the outgoing flow then gets a new port, and punching fails. Real routers drop such packets, and the lab does too.Measured on a LAN with a direct connection: a 20 MB file transfers in about 330 ms with matching checksums.## Limitations- **Not notarized by Apple**, so the first launch needs one manual approval.-- **Both Macs need to be online at the same time.** The server stores nothing, so there's no store-and-forward.+- **Items aren't resent after a long absence.** The server stores nothing. While the other Mac is unreachable, this Mac keeps the latest 20 items (from the last 24 hours) in memory, and they're lost if its background service restarts.- **Relayed transfers are limited by your server's bandwidth.** Direct connections aren't.- macOS only for now. The interface is in Simplified Chinese.@@ -215,7 +268,7 @@ During development:```bashcd client-core && go test ./... # service tests-./tools/natlab/docker.sh # NAT lab: direct vs relay across 8 network topologies+./tools/natlab/docker.sh # NAT lab: direct vs relay across 9 network topologiescd ui && flutter test # app tests./scripts/install-macos.sh # install the service from dist/ as a login item./dist/copysync-cli status # service status@@ -234,6 +287,8 @@ server/ signaling + TURN relay server (Go); deployment files in server/dproto/ message definitions and device ID derivation, shared by all threedocs/ website (GitHub Pages)spikes/ technical validation done before development+design/ design documents+tools/natlab/ NAT traversal lab```## Troubleshooting@@ -245,7 +300,7 @@ The system pasteboard service may be stuck: an app declared clipboard content anCheck **设置 → 连接状态** (Settings → Connection) on both Macs. If it isn't connected, verify the server address and that port 8787 is reachable.**Always "relay", never "direct"**-NAT traversal didn't succeed, which is common with NATs that randomize ports or strict firewalls. Everything still works; speed is limited by the server's bandwidth. Run `copysync-cli nat` to see how many uplinks were found; zero means UDP is blocked.+Showing "relay" right after connecting and "direct" a little later is normal: the relay makes things work first, and the direct path takes over when the link is idle. If it stays "relay", NAT traversal didn't succeed, which is common with NATs that randomize ports or strict firewalls. Everything still works; speed is limited by the server's bandwidth. Run `copysync-cli nat` to see how many uplinks were found; zero means UDP is blocked.**Logs**The background service logs to `~/Library/Logs/CopySync/daemon.log`. On the server, use `journalctl -u copysync-server -f`.diff --git a/README.md b/README.mdindex be930f9..83565d0 100644--- a/README.md+++ b/README.md@@ -156,7 +156,51 @@ flowchart LR2. 发现变化后读取内容,按类型和大小决定怎么传:文本直接内联在消息里;50 MB 以内的图片与文件打包成流(tar + zstd)立即推送;更大的只发一条记录。3. 对端收到后先写入本地缓存,再写入剪贴板。在那台 Mac 上 `⌘V` 粘贴出来的,就是本地的真实文件。-**连接是怎么建立的:**设备通过 WebSocket 连上信令服务器,用 WebRTC 的 ICE 尝试直连(局域网地址、经 STUN 探测到的公网地址),都失败时使用 TURN 中转地址。数据走 WebRTC 数据通道,DTLS 加密。+**连接是怎么建立的:**++1. 设备通过 WebSocket 连上信令服务器,拿到 STUN 与 TURN 的地址。+2. 所有连接共用一个本地 UDP 端口。后台服务在这个端口上向多台服务器探测本机的公网地址,网络有几个出口就能拿到几个地址(见下一节)。+3. 握手时把局域网地址、每个出口的公网地址、TURN 中转地址都发给对端,两边用 WebRTC 的 ICE 同时互相尝试。+4. 直连打通就走直连;中转路径至少等 5 秒才允许被选中,给直连留出时间。+5. 连上后两端互相告知自己是否经过中转,任一端经中转,两边都显示「中转」。+6. 若还是先落到了中转,发起连接的一方会在空闲时用 ICE 重启再打一次洞,打通就换成直连(10 秒后第一次,之后间隔逐步拉长到 15 分钟)。++数据走 WebRTC 数据通道,DTLS 加密。++### 多出口网络的打洞++公司双线、运营商 NAT 地址池这类网络有多个出口,按目标 IP 选择走哪一个。实测一个公司网络有 4 个出口:++| 出口 | 落在这个出口上的探测服务器 | 公网端口 |+|---|---|---|+| 出口 A | 自己的服务器、Twilio | 不变 |+| 出口 B | B 站、Google、Nextcloud | 不变 |+| 出口 C | Cloudflare、FreeSWITCH | 改写,但对不同目标相同 |+| 出口 D | 阿里云上的服务 | 改写 |++只问一台服务器,就只知道其中一个出口的地址;发往对端的包按目标 IP 很可能从另一个出口出去,对端收到的源地址对不上,被它的路由器丢弃。CopySync 1.0 就是这样只能走中转。++1.1 的做法:++- **共用一个端口**:之前 pion 每问一台 STUN 服务器就开一个新端口,问到的地址只对那个端口成立。现在所有连接共用一个端口,探测结果对它全部成立。+- **探测每个出口**:在这个端口上并发探测 IP 分散的服务器(自己的服务器,加上 B 站、Cloudflare 等公共 STUN),按 IP 去重,过滤被 DNS 污染的地址。+- **全部告诉对端**:每个出口的地址都作为候选地址发给对端,对端逐个检查,与实际出口吻合的那个能打通。会改写端口的出口拿到的是真实映射。+- **记住见过的出口**:某一轮漏掉的出口,若它不改端口,就按「出口 IP + 本地端口」推算补上。++实测公司 4 个出口与家用宽带之间直连,连上服务器后约 3 秒建立。设计细节、测量过程与验证见 [多出口网络的 NAT 打洞](design/nat-traversal.md)。++**NAT 打洞实验室**(`tools/natlab`)用 Linux 网络命名空间与 iptables 搭出真实拓扑,用 CopySync 真实的连接代码验证 9 种场景,每次提交都在 CI 里运行:++| 场景 | 结果 |+|---|---|+| 单出口 ↔ 家用路由器 | 直连 |+| 两个出口,旧版本(对照) | 中转 |+| 两个出口 ↔ 家用路由器 | 直连 |+| 四个出口 ↔ 家用路由器 | 直连 |+| 两个出口,第二条没探测到:无历史 / 有历史 | 中转 / 直连 |+| 两个出口 ↔ 两个出口 | 直连 |+| 两个出口 ↔ 端口随机分配的 NAT | 中转 |+| 一开始打不通,之后网络恢复 | 先中转,随后换成直连 |### 安全模型@@ -174,6 +218,9 @@ flowchart LR| 两端打不通直连(对称 NAT、公司防火墙) | 自动改走服务器的 TURN 中转,内容依然加密;界面上显示「中转」 || 公共 STUN 在国内时通时断 | 服务器自带 STUN,客户端优先用它 || 公司双线等多出口网络(按目标地址选出口) | 所有连接共用一个本地端口,在这个端口上向多台服务器探测每个出口的地址,全部发给对端由它逐个尝试;探测漏掉的出口按历史推算。`copysync-cli nat` 可以看到探测结果 |+| 先落到了中转,其实打得通(对端刚启动、出口地址晚到一步) | 发起方在空闲时用 ICE 重启再打一次洞,打通就换成直连;有传输在进行时不重启。重启期间连接不断,只停顿几秒 |+| 对方睡眠、断网、重启,连接悄悄断了 | 发现连接失效立即关闭、重连;对方重建了连接,本端也随之换新 |+| 复制时对方连不上 | 记下最近 20 条,连接恢复后补发。补发的只进复制记录,不写进对方的剪贴板,免得覆盖对方此刻正在用的内容 || 信令服务器断开 | 指数退避自动重连(1 秒起,最长 30 秒,带随机抖动),界面实时显示连接状态 || 配对时两端确认有先后 | 先确认一方发来的握手消息会被暂存,另一方确认后重放,配对完成几十毫秒内即可直连 || 大文件 | 超过阈值只同步记录,按需拉取;拉取时源文件已被删除会明确提示,而不是失败得不明不白 |@@ -190,13 +237,19 @@ flowchart LR- **macOS 的剪贴板调用必须在主线程。**开启隐私机制后,剪贴板 API 要经系统 UI 服务通信,依赖 run loop,在普通线程上调用会直接崩溃。后台服务启动时就把主线程锁住,专门留给剪贴板,业务逻辑投递过去执行。- **"对方按下粘贴键才传输"在 macOS 上做不到。**系统在写入剪贴板后约 0.1 秒就会把延迟提供的数据兑现并缓存,真正按下 `⌘V` 时不再回调,也没有"剪贴板被读取"的通知。所以小文件是预先推送的,大文件改为手动拉取。- **WebRTC 库(pion)的三个坑**:`DetachDataChannels()` 是全局开关,开了以后所有通道的普通收发都失效;`OnMessage` 不缓冲,回调设置之前到达的消息直接丢弃(实测发 202 字节,收到 0 字节);`OnBufferedAmountLow` 是边沿触发,等待方晚一步进入等待就再也等不到唤醒(20 MB 传到 786 KB 卡死)。+- **pion 为每台 STUN 服务器单独开端口**,问到的地址互相用不上。多出口网络里多配几台 STUN 也打不通,所以改为所有连接共用一个端口、由自己探测。+- **单靠一端判断不了是否中转。**一端经 TURN 发送时,另一端看到的可能只是个普通地址,曾出现一台显示直连、一台显示中转。现在连接就绪后两端互相告知。+- **pion 选定线路后就不再更换。**中转握手快,一旦赢了这场赛跑,整个连接期间都走中转。实测对端重启后的第一次握手,出口地址比中转的等待时限晚到,就这样一直中转。现在中转等待放宽到 5 秒、探测时并发解析域名(整轮从约 1.6 秒降到 0.2 秒以内),并在中转时用 ICE 重启再试直连。+- **连接失效后要自己清理。**pion 报告「失败」后不会关闭连接,控制通道看上去还是打开的,写进去的消息石沉大海;上层以为连接还在,也不会重连。1.1.0 曾因此在对方断线后,把 6 个文件「发」进了一条死连接,对方一个也没收到。+- **公共 STUN 域名可能被 DNS 污染**,实测被解析到 `192.0.2.42`。这类保留地址和代理软件的 fake-ip 网段在探测前就过滤掉。+- **测试用的模拟路由器要有防火墙。**两端同时打洞时,对方的包若被放行到路由器本机,Linux 会为它留下一条连接记录,本端随后往外发时只好换端口,打洞就失败了。真实路由器直接丢弃这类包,实验室也照此配置。局域网直连实测:20 MB 文件约 330 毫秒传完,校验和一致。## 已知限制- **没有经过 Apple 公证**,第一次打开需要手动放行一次。-- **两台设备需要同时在线**。服务器不存数据,所以没有"离线时先存着、上线再取"。+- **对方离线太久的内容不会补发**。服务器不存数据;对方暂时连不上时,本机只在内存里记下最近 20 条(24 小时内的),本机的后台服务重启后就清空了。- **中转模式的速度取决于服务器带宽**。直连时不受影响。- 目前只有 macOS 客户端。@@ -213,7 +266,7 @@ flowchart LR```bashcd client-core && go test ./... # 后台服务的测试-./tools/natlab/docker.sh # NAT 打洞实验室:8 种网络拓扑下的直连与中转+./tools/natlab/docker.sh # NAT 打洞实验室:9 种网络拓扑下的直连与中转cd ui && flutter test # 界面的测试./scripts/install-macos.sh # 把 dist/ 里的后台服务装成登录项./dist/copysync-cli status # 查看后台服务状态@@ -232,6 +285,8 @@ server/ 信令 + TURN 中转服务器(Go),部署文件在 server/dproto/ 消息定义与设备 ID 派生规则,三方共用docs/ 项目主页(GitHub Pages)spikes/ 开工前的技术验证+design/ 技术方案文档+tools/natlab/ NAT 打洞实验室```## 排障@@ -243,7 +298,7 @@ spikes/ 开工前的技术验证检查两台 Mac 的 **设置 → 连接状态** 是否都是「已连接」。不是的话,确认服务器地址正确、8787 端口可以访问。**一直显示「中转」而不是「直连」**-NAT 打洞没成功,常见于端口随机分配的 NAT 或严格的防火墙。功能不受影响,只是速度受服务器带宽限制。运行 `copysync-cli nat` 看本机探测到了几个出口:出口为 0 说明 UDP 被拦截了。+刚连上时显示中转、过一会儿变成直连是正常的:先用中转保证能用,空闲时再换直连。一直是中转,说明 NAT 打洞没成功,常见于端口随机分配的 NAT 或严格的防火墙。功能不受影响,只是速度受服务器带宽限制。运行 `copysync-cli nat` 看本机探测到了几个出口:出口为 0 说明 UDP 被拦截了。**查看日志**后台服务的日志在 `~/Library/Logs/CopySync/daemon.log`,服务器的日志用 `journalctl -u copysync-server -f` 查看。diff --git a/client-core/cmd/copysyncd/main.go b/client-core/cmd/copysyncd/main.goindex 7810c27..6121dba 100644--- a/client-core/cmd/copysyncd/main.go+++ b/client-core/cmd/copysyncd/main.go@@ -204,6 +204,11 @@ func run(dataDir string) error {engine.HandlePeerStream(deviceID, label, stream)}},+ OnPeerReady: func(deviceID string) {+ if engine != nil {+ go engine.PeerReady(ctx, deviceID)+ }+ },})if err != nil {return err@@ -218,17 +223,14 @@ func run(dataDir string) error {DeviceName: func() string { return loadCfg().DeviceName },LoadConfig: loadCfg,Send: peerMgr.P2P().Send,- Broadcast: peerMgr.P2P().Broadcast,OpenStream: peerMgr.P2P().OpenStream,- OnlinePeers: func() []string {+ PairedPeers: func() []string {_, list := peerMgr.Devices()- var online []string+ ids := make([]string, 0, len(list))for _, d := range list {- if d.GetOnline() {- online = append(online, d.GetId())- }+ ids = append(ids, d.GetId())}- return online+ return ids},OnRecord: func(r *pb.ClipRecord) {hub.Publish(rpc.EventClipAdded(r))diff --git a/client-core/cmd/natlab/main.go b/client-core/cmd/natlab/main.goindex 9f2f9e7..e3b9ddc 100644--- a/client-core/cmd/natlab/main.go+++ b/client-core/cmd/natlab/main.go@@ -177,9 +177,10 @@ func runPeer(args []string) error {legacy := fs.Bool("legacy", false, "用旧版本的候选收集方式(对照实验)")timeout := fs.Duration("timeout", 40*time.Second, "等待连接的最长时间")linger := fs.Duration("linger", 4*time.Second, "报完结果后保持连接的时间")+ settle := fs.Duration("settle", 0, "连上中转后再等多久,看能否换成直连")_ = fs.Parse(args)- ctx, cancel := context.WithTimeout(context.Background(), *timeout+10*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), *timeout+*settle+10*time.Second)defer cancel()start := time.Now()@@ -230,7 +231,7 @@ func runPeer(args []string) error {return err}- final := waitFinal(states, m, *peerID, *timeout)+ final := waitFinal(states, m, *peerID, *timeout, *settle)var egress []stringfor _, e := range m.Egress().Egresses {egress = append(egress, e.Addr.String())@@ -245,15 +246,21 @@ func runPeer(args []string) error {}// waitFinal 等连接建立,再多等一会儿让两端交换 LinkInfo,取稳定后的状态。-func waitFinal(states <-chan p2p.ConnState, m *p2p.Manager, peerID string, timeout time.Duration) p2p.ConnState {+// settle 大于零时,若稳定后是中转,再最多等这么久,看能否换成直连。+func waitFinal(states <-chan p2p.ConnState, m *p2p.Manager, peerID string, timeout, settle time.Duration) p2p.ConnState {deadline := time.After(timeout)for {select {case s := <-states:- if s == p2p.StateDirect || s == p2p.StateRelay {- time.Sleep(1500 * time.Millisecond)- return m.State(peerID)+ if s != p2p.StateDirect && s != p2p.StateRelay {+ continue+ }+ time.Sleep(1500 * time.Millisecond)+ until := time.Now().Add(settle)+ for m.State(peerID) == p2p.StateRelay && time.Now().Before(until) {+ time.Sleep(100 * time.Millisecond)}+ return m.State(peerID)case <-deadline:return m.State(peerID)}diff --git a/client-core/internal/peers/manager.go b/client-core/internal/peers/manager.goindex 35c5773..9c6d92a 100644--- a/client-core/internal/peers/manager.go+++ b/client-core/internal/peers/manager.go@@ -48,6 +48,8 @@ type Manager struct {onStatusChanged func()// 收到对端信令(SDP/candidate),M2 的 WebRTC 层在此接管onSignal func(from string, msg *pb.SignalMessage)+ // onPeerReady 见 Options.OnPeerReady+ onPeerReady func(deviceID string)client *signaling.Clientp2p *p2p.Manager@@ -79,6 +81,8 @@ type Options struct {// OnPeerMessage / OnPeerStream 是 P2P 数据面的入口,M4 的同步逻辑挂在这里OnPeerMessage func(deviceID string, msg *pb.PeerMessage)OnPeerStream func(deviceID, label string, stream *p2p.Stream)+ // OnPeerReady 在与某台设备的 P2P 连接建立或恢复时调用(同步引擎据此补发)+ OnPeerReady func(deviceID string)// StatePath 保存网络出口历史的文件,见 p2p/egress_history.goStatePath string}@@ -97,6 +101,7 @@ func NewManager(opts Options) (*Manager, error) {onDeviceChanged: opts.OnDeviceChanged,onStatusChanged: opts.OnStatusChanged,onSignal: opts.OnSignal,+ onPeerReady: opts.OnPeerReady,known: make(map[string]store.Device),online: make(map[string]bool),conn: make(map[string]p2p.ConnState),@@ -368,6 +373,7 @@ func (m *Manager) replaySignals(from string) {// handleP2PState 在直连/中转状态变化时刷新界面。func (m *Manager) handleP2PState(deviceID string, state p2p.ConnState) {m.mu.Lock()+ prev := m.conn[deviceID]m.conn[deviceID] = statem.mu.Unlock()@@ -375,6 +381,14 @@ func (m *Manager) handleP2PState(deviceID string, state p2p.ConnState) {if d, ok := m.device(deviceID); ok {m.notify(d)}+ // 直连与中转之间切换不算重新连上+ if connected(state) && !connected(prev) && m.onPeerReady != nil {+ m.onPeerReady(deviceID)+ }+}++func connected(s p2p.ConnState) bool {+ return s == p2p.StateDirect || s == p2p.StateRelay}func (m *Manager) sendSignal(ctx context.Context, to string, msg *pb.SignalMessage) error {diff --git a/client-core/internal/sync/backlog.go b/client-core/internal/sync/backlog.gonew file mode 100644index 0000000..5c9bb9f--- /dev/null+++ b/client-core/internal/sync/backlog.go@@ -0,0 +1,124 @@+package sync++import (+ "context"+ "slices"+ "sync"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/store"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// 补发:复制时对端连不上(断线、睡眠、连接已失效但还没被发现),+// 这条内容就记下来,连接恢复后再发过去。只记在内存里,后台服务重启后清空。+const (+ backlogMax = 20 // 每台设备最多补发的条数,只留最新的+ backlogMaxAge = 24 * time.Hour // 再旧的不补+)++type backlog struct {+ mu sync.Mutex+ pending map[string][]string // 设备 ID → 待补发的记录 ID,按复制先后排列+}++func (b *backlog) add(peer, clipID string) {+ b.mu.Lock()+ defer b.mu.Unlock()+ if b.pending == nil {+ b.pending = make(map[string][]string)+ }+ list := slices.DeleteFunc(b.pending[peer], func(id string) bool { return id == clipID })+ list = append(list, clipID)+ if len(list) > backlogMax {+ list = slices.Clone(list[len(list)-backlogMax:])+ }+ b.pending[peer] = list+}++// take 取走某台设备的全部待补发记录。+func (b *backlog) take(peer string) []string {+ b.mu.Lock()+ defer b.mu.Unlock()+ list := b.pending[peer]+ delete(b.pending, peer)+ return list+}++// offerToPeers 把一条本机复制发给每台已配对设备。没送达的记进待补发,+// 连接恢复后再发(见 PeerReady)。+func (e *Engine) offerToPeers(ctx context.Context, clip store.Clip, cfg config.Config) {+ peers := e.pairedPeers()+ if len(peers) == 0 {+ return+ }+ offer := e.buildOffer(clip, cfg)+ msg := &pb.PeerMessage{Payload: &pb.PeerMessage_Offer{Offer: offer}}+ var reached []string+ for _, peer := range peers {+ if err := e.send(peer, msg); err != nil {+ e.backlog.add(peer, clip.ID)+ continue+ }+ reached = append(reached, peer)+ }+ e.log.Info("已广播剪贴板内容", "clip", clip.ID, "kind", clip.Kind, "size", clip.TotalSize,+ "对端数", len(reached), "待补发", len(peers)-len(reached))++ // 小内容随即推送,对端无需等待即可粘贴+ if pushes(offer, clip) {+ for _, peer := range reached {+ go e.pushOrRequeue(context.WithoutCancel(ctx), peer, clip)+ }+ }+}++// PeerReady 在与某台设备的连接建立或恢复时调用,补发连不上期间没送达的内容。+//+// 补发的 offer 带 backlog 标记,对端只记进复制记录、不写进剪贴板:+// 它此刻剪贴板里的内容比这些旧内容更新。+func (e *Engine) PeerReady(ctx context.Context, peer string) {+ ids := e.backlog.take(peer)+ if len(ids) == 0 {+ return+ }+ cfg := e.loadConfig()+ var sent int+ for i, id := range ids {+ clip, err := e.store.GetClip(id)+ if err != nil || time.Since(clip.CreatedAt) > backlogMaxAge {+ continue // 已删除或太旧+ }+ offer := e.buildOffer(clip, cfg)+ offer.Backlog = true+ if err := e.send(peer, &pb.PeerMessage{Payload: &pb.PeerMessage_Offer{Offer: offer}}); err != nil {+ // 刚连上又断了:剩下的放回去,等下次+ for _, rest := range ids[i:] {+ e.backlog.add(peer, rest)+ }+ break+ }+ sent+++ if pushes(offer, clip) {+ // 逐条推、不并发:补发可能有一串,同时开流会互相抢带宽+ e.pushOrRequeue(ctx, peer, clip)+ }+ }+ if sent > 0 {+ e.log.Info("已补发连接中断期间的内容", "to", peer, "条数", sent)+ }+}++// pushOrRequeue 推送内容;中途断了就记进待补发,重连后连同 offer 一起重来,+// 不让对端的记录一直停在「接收中」。+func (e *Engine) pushOrRequeue(ctx context.Context, peer string, clip store.Clip) {+ if err := e.pushTo(ctx, peer, clip); err != nil {+ e.log.Warn("推送内容失败,连接恢复后补发", "clip", clip.ID, "to", peer, "err", err)+ e.backlog.add(peer, clip.ID)+ }+}++func pushes(offer *pb.ClipOffer, clip store.Clip) bool {+ return offer.GetWillPush() && (clip.Kind == store.KindFile || clip.Kind == store.KindImage)+}diff --git a/client-core/internal/sync/backlog_test.go b/client-core/internal/sync/backlog_test.gonew file mode 100644index 0000000..dfb349b--- /dev/null+++ b/client-core/internal/sync/backlog_test.go@@ -0,0 +1,191 @@+package sync++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "path/filepath"+ gosync "sync"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/store"+ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++func TestBacklogKeepsNewest(t *testing.T) {+ var b backlog+ for i := range backlogMax + 5 {+ b.add("p", fmt.Sprint(i))+ }+ b.add("p", "10") // 再次加入的挪到最后,不重复++ got := b.take("p")+ if len(got) != backlogMax {+ t.Fatalf("留下 %d 条,应为 %d", len(got), backlogMax)+ }+ if got[0] != "5" || got[len(got)-1] != "10" {+ t.Errorf("首尾 = %s…%s,应为 5…10", got[0], got[len(got)-1])+ }+ if again := b.take("p"); len(again) != 0 {+ t.Errorf("取走后还剩 %v", again)+ }+}++type fakePeers struct {+ mu gosync.Mutex+ up map[string]bool+ offers map[string][]*pb.ClipOffer+}++func (f *fakePeers) send(peer string, msg *pb.PeerMessage) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ if !f.up[peer] {+ return p2p.ErrNotConnected+ }+ if o := msg.GetOffer(); o != nil {+ f.offers[peer] = append(f.offers[peer], o)+ }+ return nil+}++func (f *fakePeers) received(peer string) []*pb.ClipOffer {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.offers[peer]+}++func newBacklogEngine(t *testing.T, peers *fakePeers) *Engine {+ t.Helper()+ db, err := store.Open(filepath.Join(t.TempDir(), "copysync.db"))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { db.Close() })+ cfg := config.Default()+ return &Engine{+ log: slog.New(slog.NewTextHandler(io.Discard, nil)),+ store: db,+ loadConfig: func() config.Config { return cfg },+ send: peers.send,+ pairedPeers: func() []string { return []string{"office", "home"} },+ quiet: map[string]bool{},+ lastProgress: map[string]time.Time{},+ }+}++func putText(t *testing.T, e *Engine, id, text string, at time.Time) store.Clip {+ t.Helper()+ clip := store.Clip{+ ID: id, Kind: store.KindText, Status: store.StatusReady, Outgoing: true,+ TextContent: text, TextPreview: text, TotalSize: int64(len(text)),+ CreatedAt: at, ExpiresAt: at.Add(72 * time.Hour),+ }+ if err := e.store.PutClip(clip); err != nil {+ t.Fatal(err)+ }+ return clip+}++// 复制时对端连不上的内容,连接恢复后补发,并标为 backlog;已送达的不重复发。+func TestMissedOfferIsReplayedOnReconnect(t *testing.T) {+ peers := &fakePeers{up: map[string]bool{"office": true}, offers: map[string][]*pb.ClipOffer{}}+ e := newBacklogEngine(t, peers)+ ctx := context.Background()++ now := time.Now()+ for i, text := range []string{"一", "二", "三"} {+ clip := putText(t, e, fmt.Sprintf("clip-%d", i), text, now.Add(time.Duration(i)*time.Second))+ e.offerToPeers(ctx, clip, e.loadConfig())+ }+ if n := len(peers.received("office")); n != 3 {+ t.Fatalf("在线的设备收到 %d 条,应为 3", n)+ }+ if n := len(peers.received("home")); n != 0 {+ t.Fatalf("连不上的设备收到 %d 条,应为 0", n)+ }++ peers.mu.Lock()+ peers.up["home"] = true+ peers.mu.Unlock()+ e.PeerReady(ctx, "home")++ got := peers.received("home")+ if len(got) != 3 {+ t.Fatalf("补发了 %d 条,应为 3", len(got))+ }+ for i, o := range got {+ if !o.GetBacklog() {+ t.Errorf("第 %d 条没有标为补发", i)+ }+ if want := fmt.Sprintf("clip-%d", i); o.GetClipId() != want {+ t.Errorf("第 %d 条是 %s,应按复制先后补发 %s", i, o.GetClipId(), want)+ }+ }++ e.PeerReady(ctx, "office")+ e.PeerReady(ctx, "home")+ if n := len(peers.received("office")); n != 3 {+ t.Errorf("已送达的设备又收到补发,共 %d 条", n)+ }+ if n := len(peers.received("home")); n != 3 {+ t.Errorf("补发过的又发了一次,共 %d 条", n)+ }+}++// 太旧的、已删除的不补发;补发途中又断开,剩下的留到下次。+func TestReplaySkipsStaleAndRequeuesOnFailure(t *testing.T) {+ peers := &fakePeers{up: map[string]bool{}, offers: map[string][]*pb.ClipOffer{}}+ e := newBacklogEngine(t, peers)+ ctx := context.Background()++ old := putText(t, e, "old", "旧", time.Now().Add(-2*backlogMaxAge))+ e.offerToPeers(ctx, old, e.loadConfig())+ e.backlog.add("home", "deleted")+ fresh := putText(t, e, "fresh", "新", time.Now())+ e.offerToPeers(ctx, fresh, e.loadConfig())++ // 还没连上就调用:太旧的、已删除的丢掉,发不出去的留到下次+ e.PeerReady(ctx, "home")+ left := e.backlog.take("home")+ if len(left) != 1 || left[0] != "fresh" {+ t.Fatalf("留下 %v,应只留下 fresh", left)+ }+ e.backlog.add("home", "fresh")++ peers.mu.Lock()+ peers.up["home"] = true+ peers.mu.Unlock()+ e.PeerReady(ctx, "home")+ got := peers.received("home")+ if len(got) != 1 || got[0].GetClipId() != "fresh" {+ t.Fatalf("补发了 %v,应只补发 fresh", got)+ }+}++// 补发来的文件收完后不写进剪贴板:对端此刻剪贴板里的内容更新。+func TestBacklogOfferIsMarkedQuiet(t *testing.T) {+ peers := &fakePeers{up: map[string]bool{}, offers: map[string][]*pb.ClipOffer{}}+ e := newBacklogEngine(t, peers)+ e.onRecord = func(*pb.ClipRecord) {}++ for _, tc := range []struct {+ id string+ backlog bool+ }{{"live", false}, {"late", true}} {+ e.handleOffer(context.Background(), "office", &pb.ClipOffer{+ ClipId: tc.id, Kind: pb.ClipKind(store.KindFile), TotalSize: 10, WillPush: true,+ Items: []*pb.ClipItem{{Name: "a.txt", Size: 10}}, Backlog: tc.backlog,+ CreatedAtUnix: time.Now().Unix(),+ })+ }+ e.mu.Lock()+ defer e.mu.Unlock()+ if e.quiet["live"] || !e.quiet["late"] {+ t.Errorf("quiet = %v,应只有补发的 late", e.quiet)+ }+}diff --git a/client-core/internal/sync/chunkwriter.go b/client-core/internal/sync/chunkwriter.goindex 9ab3698..6f019ab 100644--- a/client-core/internal/sync/chunkwriter.go+++ b/client-core/internal/sync/chunkwriter.go@@ -117,18 +117,22 @@ func (w *chunkWriter) waitForBuffer() error {// WaitDrained 等待发送缓冲彻底排空。//// 数据通道一关,尚未发出的数据就丢了;关闭前必须确认本地缓冲已清空。-func (w *chunkWriter) WaitDrained(ctx context.Context, timeout time.Duration) {+// 排不空说明对端没在接收(连接多半已经断了),返回错误,不能当作发送成功。+func (w *chunkWriter) WaitDrained(ctx context.Context, timeout time.Duration) error {deadline := time.Now().Add(timeout)- for time.Now().Before(deadline) {+ for {if w.dc.BufferedAmount() == 0 {- return+ return nil}if w.dc.ReadyState() != webrtc.DataChannelStateOpen {- return+ return nil // 对端收完后可能先关通道,此时缓冲计数未必已归零+ }+ if time.Now().After(deadline) {+ return errors.New("对端迟迟没有收完,连接可能已经中断")}select {case <-ctx.Done():- return+ return ctx.Err()case <-time.After(5 * time.Millisecond):}}diff --git a/client-core/internal/sync/engine.go b/client-core/internal/sync/engine.goindex f707121..e460142 100644--- a/client-core/internal/sync/engine.go+++ b/client-core/internal/sync/engine.go@@ -63,9 +63,8 @@ type Engine struct {// 传输层send func(deviceID string, msg *pb.PeerMessage) error- broadcast func(msg *pb.PeerMessage) intopenStream func(deviceID, label string) (*webrtc.DataChannel, error)- onlinePeers func() []string+ pairedPeers func() []string// 事件回传给界面onRecord func(*pb.ClipRecord)@@ -74,6 +73,11 @@ type Engine struct {mu sync.Mutex// 正在接收中的流:stream_id -> 接收器incoming map[string]*receiver+ // 对端补发来的内容,收完后不写进剪贴板:clip_id 集合,见 PeerReady+ quiet map[string]bool++ // 没送达对端、等连接恢复后补发的内容,见 backlog.go+ backlog backlog// 每次传输上一次上报进度的时间,用于节流,见 emitProgressprogressMu sync.Mutex@@ -81,17 +85,17 @@ type Engine struct {}type Options struct {- Logger *slog.Logger- Store *store.Store- Cache *cache.Cache- Watcher *clipboard.Watcher- DeviceID string- DeviceName func() string- LoadConfig func() config.Config- Send func(deviceID string, msg *pb.PeerMessage) error- Broadcast func(msg *pb.PeerMessage) int- OpenStream func(deviceID, label string) (*webrtc.DataChannel, error)- OnlinePeers func() []string+ Logger *slog.Logger+ Store *store.Store+ Cache *cache.Cache+ Watcher *clipboard.Watcher+ DeviceID string+ DeviceName func() string+ LoadConfig func() config.Config+ Send func(deviceID string, msg *pb.PeerMessage) error+ OpenStream func(deviceID, label string) (*webrtc.DataChannel, error)+ // PairedPeers 返回所有已配对设备,不论在线与否:连不上的记进待补发+ PairedPeers func() []stringOnRecord func(*pb.ClipRecord)OnProgress func(*pb.TransferProgress)}@@ -110,12 +114,12 @@ func New(opts Options) *Engine {deviceName: opts.DeviceName,loadConfig: opts.LoadConfig,send: opts.Send,- broadcast: opts.Broadcast,openStream: opts.OpenStream,- onlinePeers: opts.OnlinePeers,+ pairedPeers: opts.PairedPeers,onRecord: opts.OnRecord,onProgress: opts.OnProgress,incoming: make(map[string]*receiver),+ quiet: make(map[string]bool),lastProgress: make(map[string]time.Time),}}@@ -155,25 +159,7 @@ func (e *Engine) HandleClipboardChange(ctx context.Context, snap clipboard.Snaps}e.emitRecord(clip)-- // 没有在线对端时只留本地记录,不必尝试发送- if len(e.onlinePeers()) == 0 {- return- }-- offer := e.buildOffer(clip, cfg)- sent := e.broadcast(&pb.PeerMessage{- Payload: &pb.PeerMessage_Offer{Offer: offer},- })- e.log.Info("已广播剪贴板内容",- "clip", clip.ID, "kind", clip.Kind, "size", clip.TotalSize, "对端数", sent)-- // 小内容随即推送,对端无需等待即可粘贴- if offer.GetWillPush() && clip.Kind == store.KindFile || offer.GetWillPush() && clip.Kind == store.KindImage {- for _, peer := range e.onlinePeers() {- go e.pushTo(context.WithoutCancel(ctx), peer, clip)- }- }+ e.offerToPeers(ctx, clip, cfg)}// recordOutgoing 把本机复制的内容落库。@@ -355,12 +341,18 @@ func (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffe.log.Warn("保存对端记录失败", "err", err)return}+ backlog := offer.GetBacklog()+ if backlog && clip.Status == store.StatusFetching {+ e.mu.Lock()+ e.quiet[clip.ID] = true+ e.mu.Unlock()+ }e.emitRecord(clip)e.log.Info("收到对端剪贴板内容",- "clip", clip.ID, "kind", clip.Kind, "status", clip.Status, "from", from)+ "clip", clip.ID, "kind", clip.Kind, "status", clip.Status, "from", from, "补发", backlog)- // 文本类内容可以马上写进剪贴板- if clip.Status == store.StatusReady && cfg.AutoApplyToClipboard {+ // 文本类内容可以马上写进剪贴板;补发来的是旧内容,不覆盖本机剪贴板+ if clip.Status == store.StatusReady && cfg.AutoApplyToClipboard && !backlog {if err := e.applyToClipboard(ctx, clip); err != nil {e.log.Warn("写入剪贴板失败", "err", err)}@@ -459,7 +451,9 @@ func (e *Engine) pushTo(ctx context.Context, peer string, clip store.Clip) error}// 等发送缓冲排空再关闭,否则尾部数据会被丢弃- w.WaitDrained(ctx, 60*time.Second)+ if drainErr := w.WaitDrained(ctx, 60*time.Second); packErr == nil {+ packErr = drainErr+ }dc.Close()e.forgetProgress(clip.ID)@@ -626,6 +620,8 @@ func (e *Engine) bindStream(r *receiver, stream *p2p.Stream) {func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) {e.mu.Lock()delete(e.incoming, r.streamID)+ quiet := e.quiet[r.clipID]+ delete(e.quiet, r.clipID)e.mu.Unlock()e.forgetProgress(r.clipID)@@ -648,7 +644,7 @@ func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) {"clip", r.clipID, "from", r.from, "收到字节", r.received,"条目", len(tops), "耗时", time.Since(r.start).Round(time.Millisecond))- if e.loadConfig().AutoApplyToClipboard {+ if e.loadConfig().AutoApplyToClipboard && !quiet {ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()if err := e.applyToClipboard(ctx, clip); err != nil {diff --git a/client-core/internal/transport/p2p/egress.go b/client-core/internal/transport/p2p/egress.goindex c10836b..26da8f6 100644--- a/client-core/internal/transport/p2p/egress.go+++ b/client-core/internal/transport/p2p/egress.go@@ -140,31 +140,49 @@ type probeTarget struct {//// 按 IP 去重是因为出口只按目标 IP 选择:同一 IP 的不同端口、同一 IP 的多个域名// (Google 的 stun1–4 就是同一个 IP)只会落在同一个出口上,多探无益。+//+// 各域名并发解析:逐个解析时一台 DNS 慢就拖住整轮探测,而刚开机、刚换网络时+// 正是 DNS 最慢、最需要尽快探完的时候(探完才能把出口地址发给对端)。func resolveProbeTargets(ctx context.Context, servers []string, opts probeOptions) []probeTarget {resolver := opts.Resolverif resolver == nil {resolver = net.DefaultResolver}- seen := map[netip.Addr]bool{}- var out []probeTarget- for _, s := range servers {+ type resolved struct {+ host string+ port uint16+ ips []netip.Addr+ }+ results := make([]resolved, len(servers))+ var wg sync.WaitGroup+ for i, s := range servers {host, port, err := parseProbeServer(s)if err != nil {continue}- var ips []netip.Addr+ results[i] = resolved{host: host, port: port}if ip, err := netip.ParseAddr(host); err == nil {- ips = []netip.Addr{ip}- } else {+ results[i].ips = []netip.Addr{ip}+ continue+ }+ wg.Add(1)+ go func() {+ defer wg.Done()lctx, cancel := context.WithTimeout(ctx, 2*time.Second)- resolved, err := resolver.LookupNetIP(lctx, "ip4", host)- cancel()- if err != nil {- continue+ defer cancel()+ if ips, err := resolver.LookupNetIP(lctx, "ip4", host); err == nil {+ results[i].ips = ips}- ips = resolved- }- for _, ip := range ips {+ }()+ }+ wg.Wait()++ // 按服务器原本的顺序去重,结果与解析快慢无关+ seen := map[netip.Addr]bool{}+ var out []probeTarget+ for _, r := range results {+ host, port := r.host, r.port+ for _, ip := range r.ips {ip = ip.Unmap()if !ip.Is4() || seen[ip] || !usableProbeIP(ip, opts.AllowPrivate) {continuediff --git a/client-core/internal/transport/p2p/egress_test.go b/client-core/internal/transport/p2p/egress_test.goindex de2429a..19d0146 100644--- a/client-core/internal/transport/p2p/egress_test.go+++ b/client-core/internal/transport/p2p/egress_test.go@@ -32,7 +32,7 @@ func TestParseProbeServer(t *testing.T) {port uint16}{{"stun:stun.l.google.com:19302", "stun.l.google.com", 19302},- {"stun:106.12.83.160:3478", "106.12.83.160", 3478},+ {"stun:101.6.6.6:3478", "101.6.6.6", 3478},{"stun.cloudflare.com:3478", "stun.cloudflare.com", 3478},{"stun:example.com", "example.com", 3478},{"stun:example.com:3478?transport=udp", "example.com", 3478},@@ -51,7 +51,7 @@ func TestUsableProbeIP(t *testing.T) {allowPrivate boolwant bool}{- {"106.12.83.160", false, true},+ {"101.6.6.6", false, true},{"162.159.207.0", false, true},{"192.0.2.42", false, false}, // 实测 stun.syncthing.net 被 DNS 污染到这里{"198.18.3.7", false, false}, // 代理软件 fake-ip 的默认网段diff --git a/client-core/internal/transport/p2p/manager.go b/client-core/internal/transport/p2p/manager.goindex 64b6c50..92761c8 100644--- a/client-core/internal/transport/p2p/manager.go+++ b/client-core/internal/transport/p2p/manager.go@@ -261,8 +261,27 @@ func (m *Manager) runProbe(done chan struct{}) {}}+// refreshEgress 立即重新探测一轮出口并等它结束(最多 5 秒)。+// 尝试从中转换成直连之前调用:公司网络里每条线路分到哪些目标会随时间变化,+// 上一轮没探测到的线路这一轮可能就有了。+func (m *Manager) refreshEgress() {+ m.triggerProbe()+ m.egressMu.Lock()+ wait := m.probing+ m.egressMu.Unlock()+ if wait != nil {+ select {+ case <-wait:+ case <-time.After(5 * time.Second):+ }+ }+}+// advertisedCandidates 返回要额外发给对端的出口地址。-// 正在探测时最多等 3 秒,免得刚连上信令就用一份空的结果去握手。+//+// 正在探测时最多等 4 秒,免得刚连上信令就用一份空的结果去握手。这是在发出 offer/answer+// 之后的后台里等,不耽误握手;但要短于中转的等待时限(relayAcceptanceWait),+// 出口地址到了对端还来得及打洞。func (m *Manager) advertisedCandidates() []string {if m.mux == nil {return nil@@ -273,7 +292,7 @@ func (m *Manager) advertisedCandidates() []string {if wait != nil {select {case <-wait:- case <-time.After(3 * time.Second):+ case <-time.After(4 * time.Second):}}return srflxCandidates(m.Egress())@@ -404,6 +423,7 @@ func (m *Manager) peer(deviceID string) (*Peer, error) {ForceRelay: forceRelay,UDPMux: mux,ExtraCandidates: m.advertisedCandidates,+ RefreshEgress: m.refreshEgress,SendSignal: func(ctx context.Context, msg *pb.SignalMessage) error {return m.sendSignal(ctx, deviceID, msg)},diff --git a/client-core/internal/transport/p2p/peer.go b/client-core/internal/transport/p2p/peer.goindex d1706f3..b5aaa0b 100644--- a/client-core/internal/transport/p2p/peer.go+++ b/client-core/internal/transport/p2p/peer.go@@ -61,10 +61,22 @@ func (s ConnState) Proto() pb.ConnectionKind {const (controlChannelLabel = "control"connectTimeout = 30 * time.Second- // relayAcceptanceWait 是中转路径最早可以被选中的时间,给直连留出打通的机会- relayAcceptanceWait = 3 * time.Second+ // relayAcceptanceWait 是中转路径最早可以被选中的时间,给直连留出打通的机会。+ // 要长于对端探测出口、把出口地址发过来所需的时间(见 Manager.advertisedCandidates)+ relayAcceptanceWait = 5 * time.Second+ // restartTimeout 是 ICE 重启后等待恢复的最长时间,超时就重置连接+ restartTimeout = 30 * time.Second)+var (+ // upgradeDelays 是走中转时,每次尝试换成直连之前等待的时间;用完后按最后一项重复+ upgradeDelays = []time.Duration{10 * time.Second, 30 * time.Second, 2 * time.Minute, 5 * time.Minute, 15 * time.Minute}+ // upgradeIdle:这么久之内有过同步就先不换,ICE 重启会让传输停顿几秒+ upgradeIdle = 10 * time.Second+)++var errNegotiating = errors.New("正在协商中")+// Peer 管理与单个对端的 WebRTC 连接。type Peer struct {deviceID string@@ -78,6 +90,8 @@ type Peer struct {onStream func(label string, stream *Stream)// extraCands 返回出口探测得到的公网地址,见 sendExtraCandidatesextraCands func() []string+ // refreshEgress 重新探测一轮出口,见 tryUpgrade+ refreshEgress func()api *webrtc.APIconfig webrtc.Configuration@@ -105,6 +119,18 @@ type Peer struct {connectTimer *time.Timer// dialing 表示 Connect 正在进行中,防止并发重入建出两个 PeerConnectiondialing bool++ forceRelay bool+ // 生成并发出 offer/answer 期间,新收集到的 candidate 先攒着,见 holdCandidates+ holdCands bool+ heldCands []*pb.IceCandidate+ // 走中转时定期尝试换成直连,见 tryUpgrade+ upgradeTimer *time.Timer+ upgradeAttempt int+ restarts int // ICE 重启的次数,watchRestart 用它识别过期的计时+ // lastActivity 与 streams 用来判断连接是否空闲,见 busy+ lastActivity time.Time+ streams []*webrtc.DataChannel}type PeerOptions struct {@@ -119,10 +145,12 @@ type PeerOptions struct {UDPMux ice.UDPMux// ExtraCandidates 返回出口探测得到的公网地址(srflx candidate),握手时一并发给对端ExtraCandidates func() []string- SendSignal func(ctx context.Context, msg *pb.SignalMessage) error- OnState func(ConnState)- OnMessage func(*pb.PeerMessage)- OnStream func(label string, stream *Stream)+ // RefreshEgress 立即重新探测出口并等它结束,尝试换成直连之前调用+ RefreshEgress func()+ SendSignal func(ctx context.Context, msg *pb.SignalMessage) error+ OnState func(ConnState)+ OnMessage func(*pb.PeerMessage)+ OnStream func(label string, stream *Stream)}func NewPeer(opts PeerOptions) (*Peer, error) {@@ -150,15 +178,17 @@ func NewPeer(opts PeerOptions) (*Peer, error) {}return &Peer{- deviceID: opts.DeviceID,- log: log.With("peer", opts.DeviceID),- sendSignal: opts.SendSignal,- onState: opts.OnState,- onMessage: opts.OnMessage,- onStream: opts.OnStream,- extraCands: opts.ExtraCandidates,- api: webrtc.NewAPI(webrtc.WithSettingEngine(settings)),- config: config,+ deviceID: opts.DeviceID,+ log: log.With("peer", opts.DeviceID),+ sendSignal: opts.SendSignal,+ onState: opts.OnState,+ onMessage: opts.OnMessage,+ onStream: opts.OnStream,+ extraCands: opts.ExtraCandidates,+ refreshEgress: opts.RefreshEgress,+ api: webrtc.NewAPI(webrtc.WithSettingEngine(settings)),+ config: config,+ forceRelay: opts.ForceRelay,// 用 device_id 字典序决定礼让方:双方规则一致且无需协商,// 天然避免两端同时发 offer 时的死锁。polite: opts.SelfID > opts.DeviceID,@@ -231,6 +261,9 @@ func (p *Peer) Connect(ctx context.Context) error {p.mu.Unlock()}()+ p.holdCandidates()+ defer p.releaseCandidates()+offer, err := pc.CreateOffer(nil)if err != nil {return fmt.Errorf("创建 offer: %w", err)@@ -242,18 +275,107 @@ func (p *Peer) Connect(ctx context.Context) error {p.setState(StateConnecting)p.armConnectTimeout()- if err := p.sendSignal(ctx, &pb.SignalMessage{- Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{- Sdp: offer.SDP,- DtlsFingerprint: fingerprintFromSDP(offer.SDP),- }},- }); err != nil {+ if err := p.sendSignal(ctx, offerMessage(offer)); err != nil {return err}go p.sendExtraCandidates()return nil}+// restartICE 在已连通的连接上做一次 ICE 重启:两端重新收集地址、重新做连通性检查,+// DTLS 与数据通道保持不变。重启期间发出的数据会暂时丢失,由 SCTP 重传补上,+// 所以只停顿、不断开。+func (p *Peer) restartICE(ctx context.Context) error {+ p.mu.Lock()+ pc := p.pc+ if pc == nil || p.makingOffer || pc.SignalingState() != webrtc.SignalingStateStable {+ p.mu.Unlock()+ return errNegotiating+ }+ p.makingOffer = true+ p.mu.Unlock()+ defer func() {+ p.mu.Lock()+ p.makingOffer = false+ p.mu.Unlock()+ }()++ p.holdCandidates()+ defer p.releaseCandidates()++ // 先盯住:从 CreateOffer 起本端的 ICE 就已重启,之后任何一步失败都要能恢复+ p.watchRestart(pc)+ offer, err := pc.CreateOffer(&webrtc.OfferOptions{ICERestart: true})+ if err != nil {+ return fmt.Errorf("创建 offer: %w", err)+ }+ if err := pc.SetLocalDescription(offer); err != nil {+ return fmt.Errorf("设置本地描述: %w", err)+ }+ if err := p.sendSignal(ctx, offerMessage(offer)); err != nil {+ return err+ }+ go p.sendExtraCandidates()+ return nil+}++// watchRestart 在 ICE 重启后迟迟恢复不了时重置连接,交给上层重连。+// 重启用的 offer 或 answer 若在信令里丢了,ICE 会一直停在检查中,自己不会失败。+func (p *Peer) watchRestart(pc *webrtc.PeerConnection) {+ p.mu.Lock()+ p.restarts+++ gen := p.restarts+ p.mu.Unlock()+ time.AfterFunc(restartTimeout, func() {+ p.mu.Lock()+ stale := p.pc != pc || p.restarts != gen+ p.mu.Unlock()+ if !stale && pc.ConnectionState() != webrtc.PeerConnectionStateConnected {+ p.log.Warn("ICE 重启后迟迟没有恢复,重置连接")+ p.Close()+ }+ })+}++func offerMessage(offer webrtc.SessionDescription) *pb.SignalMessage {+ return &pb.SignalMessage{Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{+ Sdp: offer.SDP,+ DtlsFingerprint: fingerprintFromSDP(offer.SDP),+ }}}+}++// holdCandidates 让新收集到的 candidate 先攒着,releaseCandidates 时再发。+//+// 生成 offer/answer 时 pion 就开始收集地址,candidate 可能抢在描述之前发出。+// 初次握手时无妨,对端会先缓存;ICE 重启时对端手里还是旧的远端描述,新一代+// candidate 的 ufrag 对不上,会被直接丢弃。+func (p *Peer) holdCandidates() {+ p.mu.Lock()+ p.holdCands = true+ p.mu.Unlock()+}++func (p *Peer) releaseCandidates() {+ p.mu.Lock()+ held := p.heldCands+ p.heldCands = nil+ p.holdCands = false+ p.mu.Unlock()+ for _, c := range held {+ p.sendCandidate(c)+ }+}++func (p *Peer) sendCandidate(c *pb.IceCandidate) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := p.sendSignal(ctx, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Candidate{Candidate: c},+ }); err != nil {+ p.log.Debug("发送 candidate 失败", "err", err)+ }+}+// sendExtraCandidates 把出口探测得到的各个公网地址作为 srflx candidate 发给对端。//// pion 自己只会探测出一个公网地址;在多出口网络里,发往对端的包很可能从另一个出口@@ -312,8 +434,26 @@ func (p *Peer) handleOffer(ctx context.Context, offer *pb.SdpOffer) error {pc := p.pcpolite := p.politemaking := p.makingOffer+ // 已连通时收到同一证书的 offer,是对端在做 ICE 重启(见 tryUpgrade):+ // 连接还在,不能当成新握手把状态打回「连接中」+ restart := pc != nil && p.pcConnected &&+ strings.EqualFold(offer.GetDtlsFingerprint(), p.expectFingerprint)+ // 证书变了,说明对端已经重建了 PeerConnection(重启、或它那边判定连接失效)。+ // 本端的旧连接与它再也接不上,在旧连接上协商只会卡到超时,直接换新的+ if pc != nil && p.expectFingerprint != "" &&+ !strings.EqualFold(offer.GetDtlsFingerprint(), p.expectFingerprint) {+ p.log.Info("对端已重建连接,丢弃本端的旧连接")+ pending := p.pendingCandidates // 对端新连接的 candidate 可能先到,留着+ p.closeLocked()+ p.pendingCandidates = pending+ pc = nil+ making = false+ }p.mu.Unlock()+ p.holdCandidates()+ defer p.releaseCandidates()+// Perfect Negotiation:双方同时发 offer 时(glare),// 不礼让方忽略对方的 offer,礼让方回滚自己的 local description。//@@ -344,6 +484,10 @@ func (p *Peer) handleOffer(ctx context.Context, offer *pb.SdpOffer) error {p.expectFingerprint = offer.GetDtlsFingerprint()p.mu.Unlock()+ if restart {+ // 设置远端描述时本端的 ICE 随之重启,从这里起就要盯住+ p.watchRestart(pc)+ }if err := pc.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer,SDP: offer.GetSdp(),@@ -360,8 +504,10 @@ func (p *Peer) handleOffer(ctx context.Context, offer *pb.SdpOffer) error {return fmt.Errorf("设置本地描述: %w", err)}- p.setState(StateConnecting)- p.armConnectTimeout()+ if !restart {+ p.setState(StateConnecting)+ p.armConnectTimeout()+ }if err := p.sendSignal(ctx, &pb.SignalMessage{Payload: &pb.SignalMessage_Answer{Answer: &pb.SdpAnswer{@@ -409,8 +555,13 @@ func (p *Peer) handleCandidate(c *pb.IceCandidate) error {p.mu.Lock()pc := p.pc- // remote description 尚未设置时 AddICECandidate 会失败,先缓存- if pc == nil || pc.RemoteDescription() == nil {+ // 先缓存、等设好远端描述再加的两种情况:+ // - 远端描述尚未设置,AddICECandidate 会失败;+ // - ICE 重启时对端新一代的 candidate 抢在它的 offer/answer 之前到达,+ // ufrag 与手里的远端描述对不上,pion 会直接丢弃。+ // 缓存里若混进旧一代的 candidate,补加时由 pion 按 ufrag 丢弃。+ if pc == nil || pc.RemoteDescription() == nil ||+ !sdpHasUfrag(pc.RemoteDescription().SDP, candidateUfrag(init.Candidate)) {p.pendingCandidates = append(p.pendingCandidates, init)p.mu.Unlock()return nil@@ -420,6 +571,31 @@ func (p *Peer) handleCandidate(c *pb.IceCandidate) error {return pc.AddICECandidate(init)}+// candidateUfrag 取出 candidate 里的 ufrag 扩展。pion 生成的 candidate 都带,+// 出口探测得到的那几条不带(返回空)。+func candidateUfrag(candidate string) string {+ f := strings.Fields(candidate)+ for i := 6; i+1 < len(f); i++ { // 前 6 项是 foundation、component、协议、优先级、地址、端口+ if f[i] == "ufrag" {+ return f[i+1]+ }+ }+ return ""+}++// sdpHasUfrag 判断 SDP 里是否有这个 ufrag;ufrag 为空视为匹配。+func sdpHasUfrag(sdp, ufrag string) bool {+ if ufrag == "" {+ return true+ }+ for _, line := range strings.Split(sdp, "\n") {+ if strings.TrimSpace(line) == "a=ice-ufrag:"+ufrag {+ return true+ }+ }+ return false+}+func (p *Peer) flushPendingCandidates() {p.mu.Lock()pc := p.pc@@ -448,25 +624,21 @@ func (p *Peer) newPeerConnection() (*webrtc.PeerConnection, error) {return // candidate 收集完毕}init := c.ToJSON()- var mid string+ cand := &pb.IceCandidate{Candidate: init.Candidate}if init.SDPMid != nil {- mid = *init.SDPMid+ cand.SdpMid = *init.SDPMid}- var idx uint32if init.SDPMLineIndex != nil {- idx = uint32(*init.SDPMLineIndex)+ cand.SdpMlineIndex = uint32(*init.SDPMLineIndex)}- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- if err := p.sendSignal(ctx, &pb.SignalMessage{- Payload: &pb.SignalMessage_Candidate{Candidate: &pb.IceCandidate{- Candidate: init.Candidate,- SdpMid: mid,- SdpMlineIndex: idx,- }},- }); err != nil {- p.log.Debug("发送 candidate 失败", "err", err)+ p.mu.Lock()+ if p.holdCands {+ p.heldCands = append(p.heldCands, cand)+ p.mu.Unlock()+ return}+ p.mu.Unlock()+ p.sendCandidate(cand)})pc.OnDataChannel(func(dc *webrtc.DataChannel) {@@ -474,6 +646,7 @@ func (p *Peer) newPeerConnection() (*webrtc.PeerConnection, error) {p.bindControl(dc)return}+ p.trackStream(dc)// 数据流必须在回调里**立即**挂上接收器。//// pion 的 OnMessage 只是存一个 handler;在它被设置之前到达的消息@@ -488,12 +661,24 @@ func (p *Peer) newPeerConnection() (*webrtc.PeerConnection, error) {pc.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {p.log.Debug("PeerConnection 状态", "state", s)+ p.mu.Lock()+ current := p.pc == pc+ p.mu.Unlock()+ if !current {+ // 已被替换或关闭的连接:它迟到的「已关闭」不能把新连接的状态改成离线+ return+ }switch s {case webrtc.PeerConnectionStateConnected:p.onConnected(pc)- case webrtc.PeerConnectionStateFailed,- webrtc.PeerConnectionStateClosed,- webrtc.PeerConnectionStateDisconnected:+ case webrtc.PeerConnectionStateFailed, webrtc.PeerConnectionStateClosed:+ // 失败与关闭都是终态(本端主动关闭的在上面已被过滤),必须清理掉。+ // 留着的话 Connect 以为连接还在、不会重建;控制通道看上去仍是打开的,+ // 发出的消息石沉大海+ p.log.Warn("连接已失效,关闭以便重连", "state", s)+ p.Close()+ case webrtc.PeerConnectionStateDisconnected:+ // 断开可能是暂时的(网络抖动),pion 会继续检测,恢复不了时转为失败p.setState(StateOffline)}})@@ -540,10 +725,7 @@ func (p *Peer) maybeReady() {ready := p.pcConnected && p.control != nil &&p.control.ReadyState() == webrtc.DataChannelStateOpenownView := p.pendingKind- kind := ownView- if p.remoteRelayed {- kind = StateRelay- }+ kind := p.combinedKindLocked()p.mu.Unlock()if ready {@@ -553,7 +735,7 @@ func (p *Peer) maybeReady() {p.connectTimer = nil}p.mu.Unlock()- p.setState(kind)+ p.settle(kind)// 只有本端能确定自己发出的数据走没走 TURN,告诉对端,让两边显示一致_ = p.Send(&pb.PeerMessage{Payload: &pb.PeerMessage_Link{Link: &pb.LinkInfo{Relayed: ownView == StateRelay},@@ -561,17 +743,132 @@ func (p *Peer) maybeReady() {}}-// handleLinkInfo 记下对端的视角;对端经中转时,本端也改报中转。+// handleLinkInfo 记下对端的视角,与本端的合起来重新决定显示直连还是中转。+// ICE 重启换成直连后,也是靠对端发来的这条消息从「中转」改回「直连」。func (p *Peer) handleLinkInfo(l *pb.LinkInfo) {p.mu.Lock()p.remoteRelayed = l.GetRelayed()- upgrade := l.GetRelayed() && p.state == StateDirect+ settled := p.state == StateDirect || p.state == StateRelay+ kind := p.combinedKindLocked()p.mu.Unlock()- if upgrade {- p.setState(StateRelay)+ if settled {+ p.settle(kind)}}+// combinedKindLocked:两端任一端经中转,数据就经过服务器,算中转。+func (p *Peer) combinedKindLocked() ConnState {+ if p.remoteRelayed {+ return StateRelay+ }+ return p.pendingKind+}++// settle 报告连接就绪后的状态。走中转时安排稍后尝试换成直连,走直连时取消。+func (p *Peer) settle(kind ConnState) {+ p.setState(kind)+ p.mu.Lock()+ defer p.mu.Unlock()+ if kind == StateDirect {+ p.upgradeAttempt = 0+ p.stopUpgradeLocked()+ return+ }+ p.scheduleUpgradeLocked(upgradeDelays[min(p.upgradeAttempt, len(upgradeDelays)-1)])+}++// scheduleUpgradeLocked 安排一次换直连的尝试。只由不礼让的一方(也就是发起连接的+// 一方)来做,两端不会同时发起 ICE 重启。+func (p *Peer) scheduleUpgradeLocked(delay time.Duration) {+ if p.polite || p.forceRelay || p.upgradeTimer != nil {+ return+ }+ p.upgradeTimer = time.AfterFunc(delay, p.tryUpgrade)+}++func (p *Peer) stopUpgradeLocked() {+ if p.upgradeTimer != nil {+ p.upgradeTimer.Stop()+ p.upgradeTimer = nil+ }+}++// tryUpgrade 在走中转时用 ICE 重启再打一次洞。+//+// pion 一旦选定 candidate 对就不会再换。走中转常常只是输了一场赛跑:对端刚启动,+// 出口还没探测完,中转的等待时限就到了;之后直连其实打得通,却再没有机会。+// ICE 重启让两端重新收集地址、同时再打一次洞。仍打不通就照旧落回中转,+// 下一次隔得更久再试(upgradeDelays)。+func (p *Peer) tryUpgrade() {+ p.mu.Lock()+ p.upgradeTimer = nil+ relay := p.pc != nil && p.state == StateRelay+ p.mu.Unlock()+ if !relay {+ return+ }+ if p.busy() {+ // 有数据在传,重启会让它停顿几秒,等空闲了再试+ p.mu.Lock()+ p.scheduleUpgradeLocked(upgradeIdle)+ p.mu.Unlock()+ return+ }++ p.mu.Lock()+ p.upgradeAttempt+++ attempt := p.upgradeAttempt+ p.mu.Unlock()+ p.log.Info("当前经中转,尝试换成直连", "attempt", attempt)++ // 先重新探测出口,新发现的线路地址随重启一起发给对端+ if p.refreshEgress != nil {+ p.refreshEgress()+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := p.restartICE(ctx); err != nil {+ p.log.Debug("ICE 重启没有发起", "err", err)+ p.mu.Lock()+ p.scheduleUpgradeLocked(upgradeDelays[min(p.upgradeAttempt, len(upgradeDelays)-1)])+ p.mu.Unlock()+ }+ // 发起成功时,重启完成后 onConnected → maybeReady → settle 会报告新状态;+ // 仍是中转的话,settle 会按下一档间隔再安排+}++// busy 判断连接上是否有数据在传:有文件流未关闭,或者刚有过控制消息。+func (p *Peer) busy() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ if time.Since(p.lastActivity) < upgradeIdle {+ return true+ }+ live := p.streams[:0]+ for _, dc := range p.streams {+ if dc.ReadyState() != webrtc.DataChannelStateClosed {+ live = append(live, dc)+ }+ }+ clear(p.streams[len(live):])+ p.streams = live+ return len(live) > 0+}++func (p *Peer) trackStream(dc *webrtc.DataChannel) {+ p.mu.Lock()+ p.streams = append(p.streams, dc)+ p.lastActivity = time.Now()+ p.mu.Unlock()+}++func (p *Peer) touch() {+ p.mu.Lock()+ p.lastActivity = time.Now()+ p.mu.Unlock()+}+// detectConnectionKind 判断当前选中的 candidate 对是直连还是经 TURN 中转。//// 两端的 candidate 都要看:只要有一端是 relay,数据就经过 TURN。@@ -637,6 +934,7 @@ func (p *Peer) bindControl(dc *webrtc.DataChannel) {p.handleLinkInfo(l) // 连接层自己的消息,不交给同步引擎return}+ p.touch()if p.onMessage != nil {p.onMessage(&m)}@@ -649,15 +947,21 @@ var ErrNotConnected = errors.New("与对端的连接尚未建立")func (p *Peer) Send(m *pb.PeerMessage) error {p.mu.Lock()dc := p.control+ // 连接断开(或已失效)时,控制通道可能还显示「打开」,往里写只会石沉大海。+ // 报告未连接,让上层记下来等连接恢复后补发+ up := p.state == StateDirect || p.state == StateRelayp.mu.Unlock()- if dc == nil || dc.ReadyState() != webrtc.DataChannelStateOpen {+ if !up || dc == nil || dc.ReadyState() != webrtc.DataChannelStateOpen {return ErrNotConnected}data, err := proto.Marshal(m)if err != nil {return err}+ if m.GetLink() == nil {+ p.touch()+ }return dc.Send(data)}@@ -673,7 +977,11 @@ func (p *Peer) OpenStream(label string) (*webrtc.DataChannel, error) {return nil, ErrNotConnected}ordered := true- return pc.CreateDataChannel(label, &webrtc.DataChannelInit{Ordered: &ordered})+ dc, err := pc.CreateDataChannel(label, &webrtc.DataChannelInit{Ordered: &ordered})+ if err == nil {+ p.trackStream(dc)+ }+ return dc, err}func (p *Peer) Close() {@@ -702,6 +1010,11 @@ func (p *Peer) closeLocked() {p.connectTimer.Stop()p.connectTimer = nil}+ p.holdCands = false+ p.heldCands = nil+ p.streams = nil+ // upgradeAttempt 保留:连接反复重建时,换直连的尝试不必每次都从最密的间隔开始+ p.stopUpgradeLocked()}// fingerprintFromSDP 从 SDP 中提取 DTLS 证书指纹(a=fingerprint 行)。diff --git a/client-core/internal/transport/p2p/upgrade_test.go b/client-core/internal/transport/p2p/upgrade_test.gonew file mode 100644index 0000000..28101ed--- /dev/null+++ b/client-core/internal/transport/p2p/upgrade_test.go@@ -0,0 +1,346 @@+package p2p++import (+ "context"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/pion/webrtc/v4"++ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// signalBus 把几个 Manager 直接对接起来。异步、不保序地投递,+// 比真实的信令服务器更苛刻:ICE 重启时新一代 candidate 常常抢在 offer/answer 之前到达。+type signalBus struct {+ mu sync.Mutex+ targets map[string]*Manager+}++func (b *signalBus) send(from string) func(context.Context, string, *pb.SignalMessage) error {+ return func(_ context.Context, to string, msg *pb.SignalMessage) error {+ b.mu.Lock()+ target := b.targets[to]+ b.mu.Unlock()+ if target != nil {+ go func() {+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ _ = target.HandleSignal(ctx, from, msg)+ }()+ }+ return nil+ }+}++type testNode struct {+ m *Manager+ mu sync.Mutex+ states []ConnState+ messages chan *pb.PeerMessage+}++func (n *testNode) history() []ConnState {+ n.mu.Lock()+ defer n.mu.Unlock()+ return append([]ConnState(nil), n.states...)+}++func (n *testNode) peer(id string) *Peer {+ n.m.mu.RLock()+ defer n.m.mu.RUnlock()+ return n.m.peers[id]+}++func newTestNode(t *testing.T, bus *signalBus, id string) *testNode {+ t.Helper()+ n := &testNode{messages: make(chan *pb.PeerMessage, 16)}+ n.m = NewManager(ManagerOptions{+ SelfID: id,+ SendSignal: bus.send(id),+ OnState: func(_ string, s ConnState) {+ n.mu.Lock()+ n.states = append(n.states, s)+ n.mu.Unlock()+ },+ OnMessage: func(_ string, m *pb.PeerMessage) {+ select {+ case n.messages <- m:+ default:+ }+ },+ })+ n.m.SetICEServers(nil) // 回环环境下 host candidate 足以直连+ bus.mu.Lock()+ bus.targets[id] = n.m+ bus.mu.Unlock()+ t.Cleanup(n.m.Close)+ return n+}++// connectPair 让 alice(不礼让、负责发起)与 bob 直连,返回两端。+func connectPair(t *testing.T) (alice, bob *testNode) {+ t.Helper()+ bus := &signalBus{targets: map[string]*Manager{}}+ alice = newTestNode(t, bus, "alice")+ bob = newTestNode(t, bus, "bob")+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ if err := alice.m.Connect(ctx, "bob"); err != nil {+ t.Fatalf("发起连接: %v", err)+ }+ waitState(t, alice, "bob", StateDirect, 20*time.Second)+ waitState(t, bob, "alice", StateDirect, 20*time.Second)+ return alice, bob+}++func waitState(t *testing.T, n *testNode, peerID string, want ConnState, timeout time.Duration) {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if n.m.State(peerID) == want {+ return+ }+ time.Sleep(20 * time.Millisecond)+ }+ t.Fatalf("%s 看 %s:等待 %v 超时,当前 %v,经历 %v", n.m.selfID, peerID, want, n.m.State(peerID), n.history())+}++func localUfrag(pc *webrtc.PeerConnection) string {+ for _, line := range strings.Split(pc.LocalDescription().SDP, "\n") {+ if u, ok := strings.CutPrefix(strings.TrimSpace(line), "a=ice-ufrag:"); ok {+ return u+ }+ }+ return ""+}++func expectMessage(t *testing.T, n *testNode, clipID string) {+ t.Helper()+ timeout := time.After(15 * time.Second)+ for {+ select {+ case m := <-n.messages:+ if m.GetFetch().GetClipId() == clipID {+ return+ }+ case <-timeout:+ t.Fatalf("%s 没有收到 %s", n.m.selfID, clipID)+ }+ }+}++// TestICERestartKeepsConnection 验证 ICE 重启只是让传输停顿,不会断开:+// 两端状态不经过「连接中」「离线」,重启期间发出的消息也能送达。+func TestICERestartKeepsConnection(t *testing.T) {+ alice, bob := connectPair(t)+ ap, bp := alice.peer("bob"), bob.peer("alice")+ before := localUfrag(ap.pc)+ aliceSeen, bobSeen := len(alice.history()), len(bob.history())++ // 记下两端 ICE 的状态变化:先回到「检查中」再「已连通」,才说明重启真的走完了+ restarted := func(pc *webrtc.PeerConnection) <-chan struct{} {+ done := make(chan struct{})+ var once sync.Once+ checking := false+ pc.OnICEConnectionStateChange(func(s webrtc.ICEConnectionState) {+ switch s {+ case webrtc.ICEConnectionStateChecking:+ checking = true+ case webrtc.ICEConnectionStateConnected:+ if checking {+ once.Do(func() { close(done) })+ }+ }+ })+ return done+ }+ aliceDone, bobDone := restarted(ap.pc), restarted(bp.pc)++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := ap.restartICE(ctx); err != nil {+ t.Fatalf("ICE 重启: %v", err)+ }+ // 重启进行中就发:数据暂时丢失,由 SCTP 重传补上+ fetch := func(id string) *pb.PeerMessage {+ return &pb.PeerMessage{Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: id}}}+ }+ if err := alice.m.Send("bob", fetch("during-restart")); err != nil {+ t.Fatalf("重启期间发送: %v", err)+ }++ for name, done := range map[string]<-chan struct{}{"alice": aliceDone, "bob": bobDone} {+ select {+ case <-done:+ case <-time.After(15 * time.Second):+ t.Fatalf("%s 的 ICE 没有完成重启(当前 %v)", name, ap.pc.ICEConnectionState())+ }+ }+ if localUfrag(ap.pc) == before {+ t.Fatal("本地 ufrag 没有变化,ICE 没有重启")+ }+ expectMessage(t, bob, "during-restart")++ if err := bob.m.Send("alice", fetch("after-restart")); err != nil {+ t.Fatalf("重启后发送: %v", err)+ }+ expectMessage(t, alice, "after-restart")++ for _, s := range alice.history()[aliceSeen:] {+ if s != StateDirect {+ t.Errorf("alice 在重启期间报告了 %v,应一直是直连", s)+ }+ }+ for _, s := range bob.history()[bobSeen:] {+ if s != StateDirect {+ t.Errorf("bob 在重启期间报告了 %v,应一直是直连", s)+ }+ }+}++// TestUpgradeFromRelay 验证走中转时,发起方会自己做 ICE 重启,打通后两端都改回直连。+//+// 回环环境里造不出真正打不通的网络,这里让 bob 谎报「我这边走中转」,+// 两端随之显示中转;重启后 bob 如实报告,两端回到直连。+// 真实的「先中转、后直连」由 NAT 实验室的「出口地址晚到」场景验证。+func TestUpgradeFromRelay(t *testing.T) {+ saveDelays, saveIdle := upgradeDelays, upgradeIdle+ upgradeDelays, upgradeIdle = []time.Duration{300 * time.Millisecond}, 100*time.Millisecond+ t.Cleanup(func() { upgradeDelays, upgradeIdle = saveDelays, saveIdle })++ alice, bob := connectPair(t)+ ap := alice.peer("bob")++ if err := bob.peer("alice").Send(&pb.PeerMessage{Payload: &pb.PeerMessage_Link{+ Link: &pb.LinkInfo{Relayed: true},+ }}); err != nil {+ t.Fatalf("发送 LinkInfo: %v", err)+ }++ waitState(t, alice, "bob", StateRelay, 5*time.Second)+ waitState(t, alice, "bob", StateDirect, 20*time.Second)++ ap.mu.Lock()+ restarts := ap.restarts+ ap.mu.Unlock()+ if restarts == 0 {+ t.Fatal("alice 没有做 ICE 重启就回到了直连")+ }+ if s := bob.m.State("alice"); s != StateDirect {+ t.Errorf("bob 的状态 = %v,应为直连", s)+ }+}++// TestPoliteSideWaitsForPeer 验证礼让的一方不主动重启,免得两端同时发起。+func TestPoliteSideWaitsForPeer(t *testing.T) {+ saveDelays := upgradeDelays+ upgradeDelays = []time.Duration{100 * time.Millisecond}+ t.Cleanup(func() { upgradeDelays = saveDelays })++ alice, bob := connectPair(t)+ if err := alice.peer("bob").Send(&pb.PeerMessage{Payload: &pb.PeerMessage_Link{+ Link: &pb.LinkInfo{Relayed: true},+ }}); err != nil {+ t.Fatalf("发送 LinkInfo: %v", err)+ }+ waitState(t, bob, "alice", StateRelay, 5*time.Second)+ time.Sleep(time.Second)++ bp := bob.peer("alice")+ bp.mu.Lock()+ restarts := bp.restarts+ bp.mu.Unlock()+ if restarts != 0 {+ t.Errorf("礼让方做了 %d 次 ICE 重启,应该等对方发起", restarts)+ }+}++func TestBusy(t *testing.T) {+ p := &Peer{}+ if p.busy() {+ t.Fatal("新连接不应算忙")+ }+ p.touch()+ if !p.busy() {+ t.Fatal("刚有过消息往来,应算忙")+ }+ p.lastActivity = time.Now().Add(-2 * upgradeIdle)+ if p.busy() {+ t.Fatal("空闲够久,不应算忙")+ }+}++func TestCandidateUfrag(t *testing.T) {+ cases := map[string]string{+ "candidate:1 1 udp 2130706431 192.168.1.2 50000 typ host ufrag AbCd network-cost 999": "AbCd",+ "candidate:2 1 udp 1694498815 1.2.3.4 50000 typ srflx raddr 0.0.0.0 rport 50000": "",+ // 地址、端口等位置上即使碰巧是 "ufrag" 也不算+ "candidate:ufrag 1 udp 1 ufrag 50000 typ host": "",+ }+ for c, want := range cases {+ if got := candidateUfrag(c); got != want {+ t.Errorf("candidateUfrag(%q) = %q,应为 %q", c, got, want)+ }+ }++ sdp := "v=0\r\na=ice-ufrag:AbCd\r\na=ice-pwd:x\r\n"+ if !sdpHasUfrag(sdp, "AbCd") || !sdpHasUfrag(sdp, "") {+ t.Error("应匹配")+ }+ if sdpHasUfrag(sdp, "Ab") || sdpHasUfrag(sdp, "Other") {+ t.Error("不应匹配")+ }+}++// TestRebuildWhenPeerRestarts 验证对端重建了连接(例如重启了后台服务)时,+// 本端丢弃旧连接、跟着建新的,而不是在旧连接上协商到超时。+func TestRebuildWhenPeerRestarts(t *testing.T) {+ alice, bob := connectPair(t)+ bp := bob.peer("alice")+ bp.mu.Lock()+ oldBob := bp.pc+ bp.mu.Unlock()++ // alice 悄悄丢下旧连接、建一个新的:模拟它重启,bob 对此一无所知+ ap := alice.peer("bob")+ ap.mu.Lock()+ oldAlice := ap.pc+ ap.pc, ap.control, ap.pcConnected = nil, nil, false+ ap.mu.Unlock()+ t.Cleanup(func() { _ = oldAlice.Close() })+ ap.setState(StateOffline)++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ if err := alice.m.Connect(ctx, "bob"); err != nil {+ t.Fatalf("重新发起: %v", err)+ }+ waitState(t, alice, "bob", StateDirect, 20*time.Second)+ waitState(t, bob, "alice", StateDirect, 20*time.Second)++ bp.mu.Lock()+ rebuilt := bp.pc != oldBob+ bp.mu.Unlock()+ if !rebuilt {+ t.Error("bob 还在用旧连接")+ }+ if err := alice.m.Send("bob", &pb.PeerMessage{Payload: &pb.PeerMessage_Fetch{+ Fetch: &pb.PeerFetch{ClipId: "after-rebuild"}}}); err != nil {+ t.Fatalf("发送: %v", err)+ }+ expectMessage(t, bob, "after-rebuild")+}++// TestSendRefusedWhileDown 验证连接断开期间发送会报错,而不是写进一个收不到的通道。+func TestSendRefusedWhileDown(t *testing.T) {+ alice, _ := connectPair(t)+ ap := alice.peer("bob")+ ap.setState(StateOffline) // 模拟 ICE 断开:控制通道此时仍显示「打开」+ err := alice.m.Send("bob", &pb.PeerMessage{Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{}}})+ if err != ErrNotConnected {+ t.Errorf("断开时发送返回 %v,应为 ErrNotConnected", err)+ }+}diff --git a/design/nat-traversal.md b/design/nat-traversal.mdnew file mode 100644index 0000000..bc49fcf--- /dev/null+++ b/design/nat-traversal.md@@ -0,0 +1,237 @@+# 多出口网络的 NAT 打洞++> 状态:已实现。多出口探测随 1.1.0 发布(2026-10-08);中转后换直连、连接失效检测与补发随 1.1.1 发布(2026-10-09)+> 代码:`client-core/internal/transport/p2p/egress*.go`、`manager.go`、`peer.go`;补发在 `client-core/internal/sync/backlog.go`+> 验证:`tools/natlab/`(NAT 打洞实验室,CI 中运行)++## 一、问题++两台 Mac 配对成功,同步也正常,但设备列表里一直显示「中转」:数据全部经服务器转发,速度被服务器带宽卡在约 0.6 MB/s。++两台设备分别在公司和家里。逐一排查后确认,打不通的根源是公司网络有多个出口。++## 二、测量++### 公司这台++从同一个本地 UDP 端口,向分布在不同网络的多台 STUN 服务器发 Binding 请求,记录每台服务器看到的本机公网地址。实测有 4 个不同的出口 IP,下文以出口 A–D 代称(公网地址不公开):++| 出口 | 落在这个出口上的服务器 | 公网端口 |+|---|---|---|+| 出口 A | 自己的服务器(百度云北京)、Twilio | 与本地端口相同 |+| 出口 B | B 站、Google、Nextcloud | 与本地端口相同 |+| 出口 C | Cloudflare、FreeSWITCH | 改写,但对不同目标相同 |+| 出口 D | 阿里云上的服务、有时是 Google(经 Wi-Fi 时) | 改写 |++另外两组对照实验:++- **出口只按目标 IP 选择**。向同一台服务器的 8 个不同端口探测,全部从同一个出口出去、得到同一个公网端口。+- **同一线路上映射固定**。同一本地端口发往 Cloudflare 与 Twilio,看到的都是出口 C 上的同一个端口。++结论:公司网络等于 4 个并列的、各自「端点无关映射」的 NAT,按目标 IP 选择走哪一个。单看每一条都很好打洞,难点只在于「发往对端的包走哪一条」事先不知道。++公司路由器不支持 UPnP 与 NAT-PMP,也没有 IPv6。++### 家里这台++| 项目 | 结果 |+|---|---|+| 国内目标 | 同一本地端口发往不同服务器,公网地址与端口都相同:端点无关映射,好打洞 |+| 国外目标 | 经本机的代理出去,与 CopySync 无关 |+| 路由器 | 支持 UPnP,但它自己的外网地址与服务器看到的地址不同:运营商还有一层 NAT,在路由器上映射端口没用 |+| IPv6 | 只有内网地址 |++### 旧版本为什么打不通++1. **只问了一台服务器**。客户端只从自己的服务器得知本机公网地址,即出口 A,也只把它告诉对端。发往对端的包按目标 IP 很可能从另外三个出口之一出去,对端收到的源地址与告诉它的不一致,被它的路由器当作陌生来源丢弃。+2. **多配几台 STUN 也没用**。pion 每问一台 STUN 服务器都单独开一个本地端口,问到的地址只对那个端口成立,互相用不上。++## 三、方案++### 1. 所有连接共用一个本地端口++`p2p.Manager` 启动时打开一个 UDP 端口,用 pion 的 `UniversalUDPMux` 包装,交给所有 `PeerConnection`(`SettingEngine.SetICEUDPMux`)。之后本机的所有连通性检查都从这个端口收发,于是「这个端口在每条线路上的公网地址」是一组固定、可知的值。++信令服务器下发的 STUN 地址不再交给 pion,改由本端在共享端口上探测;TURN 照常交给 pion 用于中转。打不开端口时退回 pion 的默认做法。++### 2. 探测每个出口++在共享端口上并发探测一组 IP 分散的服务器:信令服务器下发的 STUN,加上内置的公共服务器(B 站、Cloudflare、Twilio、Nextcloud、Google、FreeSWITCH)。实测 7 台服务器覆盖了公司全部出口。++- **按 IP 去重**:出口只按目标 IP 选择,同一 IP 的多个域名或端口探多少次都落在同一个出口。+- **过滤不可能是公网 STUN 的地址**:实测有域名被 DNS 污染到 `192.0.2.42`;代理软件的 fake-ip 常用 `198.18.0.0/15`。这些地址直接丢弃,不当成出口。+- **域名并发解析,每台 1.5 秒超时**。1.1.0 逐个解析域名,一台 DNS 慢就拖住整轮,实测整轮约 1.6 秒;1.1.1 改为并发后在 0.2 秒以内。启动时、服务器配置变化时、每 5 分钟、本机网络变化时、尝试换直连之前各探测一轮;探测进行中又被触发,结束后补一轮,不并发。++### 3. 把所有出口地址告诉对端++每个出口的公网地址作为一条 srflx candidate,在 offer 或 answer 之后经信令发给对端,最多 8 条。对端为每条建立 candidate pair 做连通性检查,与实际出口吻合的那一条能打通。++- 优先级按 RFC 8445 计算,实测地址排在推算地址之前。+- 会改写端口的线路,探测拿到的就是这个端口在该线路上的真实映射,不需要猜。+- 首轮探测还没结束时最多等 4 秒,免得刚上线就发一份空结果。这是在发出 offer/answer 之后的后台里等,不耽误握手,但要短于中转的等待时限。++### 4. 记住见过的出口++某一轮的探测服务器可能恰好都没落到某条线路上(实测出口 D 就时有时无)。本端按「本机各网卡的 IPv4 地址」区分网络,记下每个网络见过的出口 IP 及其是否改写端口,保存 7 天(`~/Library/Application Support/CopySync/egress.json`)。++不改写端口的线路,地址就是「出口 IP + 本地端口」,这一轮没探测到也可以推算出来补发给对端;会改写端口的线路无法推算,不补。++### 5. 优先直连++中转路径经服务器,握手往往比直连快。若不加约束,常常在直连打通之前就选中了中转,之后不再更换。中转路径要等一段时间才允许被选中(`SetRelayAcceptanceMinWait`):1.1.0 是 3 秒,1.1.1 放宽到 5 秒,见第 8 节。++### 6. 两端显示一致++只有发送方能确定自己的数据是否走 TURN:对端经中转发来的包,在本端看来可能只是一个普通的 peer-reflexive 地址。连接就绪后两端经控制通道交换 `LinkInfo{relayed}`,任一端经中转,两端都显示「中转」(1.0.2 引入)。++### 7. 隐私开关与诊断++- 设置「用公共服务器探测网络出口」,默认开启。公共 STUN 服务器能看到本机公网 IP,与任何 WebRTC 应用相同,看不到内容。关闭后只用自己的服务器探测。配置字段 `only_own_stun` 刻意设计为「关闭」语义:旧版界面不发这个字段时,默认值 false 不会把功能误关。+- `copysync-cli nat`(后台接口 `GetNetwork`)显示打洞端口、每个出口的地址与来源,以及各设备当前走直连还是中转。++### 8. 落到中转后,再试直连(1.1.1)++**问题。**1.1.0 实机验收直连之后约 10 分钟,家里那台重启了后台服务,重连后变成了中转,之后一直是中转:++```+23:19:42 P2P 连接状态 direct+23:29:01 P2P 连接状态 offline 家里那台断开+23:29:06 P2P 连接状态 connecting 它重新上线,本端发起握手+23:29:10 P2P 连接状态 relay+```++这是一场赛跑。家里那台刚启动,要先探测完出口才能把出口地址发过来,而它访问部分公共 STUN 要经过代理,探测慢。出口地址到达之前,3 秒的中转等待时限已到,中转被选中。pion 选定 candidate 对之后不会再换,于是整个连接期间都走中转,哪怕直连其实打得通。++**做法。**++1. **缩短探测、放宽等待**:域名并发解析,整轮探测从约 1.6 秒降到 0.2 秒以内;中转等待从 3 秒放宽到 5 秒,比等待出口地址的上限(4 秒)长。+2. **中转时用 ICE 重启再打一次洞**:连接以中转就绪后,由发起连接的一方(不礼让方,两端规则一致,不会同时发起)安排一次尝试:先重新探测出口,再发一个 `ICERestart` 的 offer。两端重新收集地址、同时再打一次洞。打通就换成直连;仍打不通,还是落回中转,下次隔得更久再试:10 秒、30 秒、2 分钟、5 分钟、15 分钟,之后每 15 分钟一次。+3. **只在空闲时重启**:有数据流未关闭,或 10 秒内有过消息往来,就推迟。重启期间 pion 会清掉选中的 candidate 对,发出的数据暂时丢弃,由 SCTP 重传补上:连接不断、DTLS 与数据通道不变,只停顿几秒,但仍不该在传文件时做。++**ICE 重启要处理的细节:**++- **对端不能把它当成新握手**。应答方收到 offer 时,若连接已就绪且 DTLS 证书指纹没变,就是对端在重启 ICE:状态保持直连/中转,不打回「连接中」,也不启动 30 秒的握手超时,改由一个「重启 30 秒内没恢复就重置连接」的计时兜底(重启用的 offer 或 answer 若在信令里丢了,ICE 会一直停在检查中,自己不会失败)。+- **新一代 candidate 不能早于描述发出**。生成 offer/answer 时 pion 就开始收集地址,candidate 可能抢在描述之前发出;初次握手时对端会先缓存,重启时对端手里还是旧的远端描述,新 candidate 的 ufrag 对不上,pion 会直接丢弃。现在生成描述期间收集到的 candidate 先攒着,描述发出后再发。+- **信令不保序,接收端也要兜底**。candidate 的 ufrag 与当前远端描述对不上时,先缓存起来,设好新的远端描述后再加;缓存里混进的旧一代 candidate,补加时由 pion 按 ufrag 丢弃。+- **显示要能从「中转」改回「直连」**。1.0.2 的 `LinkInfo` 只会把状态改成中转。现在两端的视角合起来决定显示:重启后两端各自重新判断,再互发一次 `LinkInfo`,都不经中转就改回直连。++pion 4.4 也带有自动续提名(renomination),能不重启就换线路,但要求两端都开启,对端是旧版本时不起作用。ICE 重启是标准做法;对端是 1.1.0 时,按代码逻辑也能配合:它会把重启的 offer 当成新握手,状态短暂显示「连接中」,随后照常恢复。这一点没有单独测试,两台都升级最稳妥。++### 9. 发现失效的连接,补发没送达的内容(1.1.1)++**问题。**1.1.1 开发期间又遇到一次:家里那台断线后,本端一直以为连接还在,此后复制的 6 个文件全部「发」进了一条死连接,对方一个也没收到,日志却记着「内容已发送」。三处缺陷叠在一起:++1. pion 报告连接「失败」或「已关闭」后,本端只把状态改成离线,没有关闭连接。`Connect` 看到连接对象还在就直接返回,重连巡检因此永远重连不上。+2. 控制通道在连接失败后仍显示「打开」,消息照样写进去,发送不报错。+3. 推送文件时,等发送缓冲排空的 60 秒超时到了也按成功处理。++**做法。**++- 连接进入「失败」或「已关闭」就关闭清理,交给重连巡检重建。本端主动关闭、或已被新连接替换的旧连接发来的迟到状态一律忽略,不影响新连接。+- 对端重建了连接(例如重启了后台服务)时,它发来的 offer 带着新的 DTLS 证书。本端发现指纹变了就丢弃旧连接、新建一个应答,不在旧连接上协商到超时。+- 连接不在直连/中转状态时,发送一律返回「未连接」。缓冲排不空按失败处理。+- **补发**:同步引擎不再「广播一次了事」,而是逐台设备发送。没送达的(连不上、推送中途断开)记进该设备的待补发队列,连接建立或恢复时补发。队列在内存里,每台设备最多 20 条、24 小时内的;已删除的记录跳过。补发的 offer 带 `backlog` 标记,对端只记进复制记录,不写进剪贴板:对方此刻剪贴板里的内容比这些旧内容更新。++### 代码位置++| 文件 | 内容 |+|---|---|+| `p2p/egress.go` | 探测、地址过滤、srflx candidate 生成 |+| `p2p/egress_history.go` | 出口历史与推算 |+| `p2p/manager.go` | 共享端口、探测时机、把地址交给每个连接 |+| `p2p/peer.go` | 发送出口地址、中转等待、`LinkInfo`、ICE 重启换直连、失效连接的清理 |+| `sync/backlog.go` | 逐台发送、待补发队列、连接恢复后补发 |+| `server/relay/turn.go` | TURN 可绑定指定 IP(`ListenIP`),实验室需要 |++## 四、能覆盖哪些场景++| 本端 | 对端 | 结果 |+|---|---|---|+| 单出口 | 单出口 | 直连 |+| 多出口(按目标 IP 选) | 单出口 | 直连 |+| 多出口 | 多出口 | 直连(实验室验证;能否成立取决于两边线路组合,属于尽力而为) |+| 任意 | 端口随机分配的 NAT | 中转 |+| 任意 | UDP 被拦截 | 中转 |+| 同一局域网 | — | 直连 |++只要多出口的一侧升级,就能与旧版本的对端直连:新增的只是标准的 srflx candidate,旧版本照常处理。++## 五、验证++### 单元测试与集成测试++`p2p/egress_test.go`:解析服务器地址;过滤污染地址;同一出口被多台服务器看到时归并;区分改写端口与不改写端口;按历史补出口、换网络不串用、过期失效;生成的 candidate 能被 pion 解析,且实测地址优先级高于推算地址。++`p2p/egress_integration_test.go`:起一台本机 STUN 服务,验证管理器在共享端口上完成探测,把出口地址作为 srflx candidate 发给对端,连接照常建立。++`p2p/upgrade_test.go`(1.1.1):ICE 重启期间两端状态一直是直连、重启中发出的消息照样送达;中转时发起方自己重启并改回直连,礼让方不主动重启;对端换了证书时本端重建连接(去掉这个处理,测试会卡在「连接中」);连接断开时发送报错。信令桩异步、不保序地投递,比真实服务器更苛刻。++`sync/backlog_test.go`(1.1.1):连不上的设备在连接恢复后按复制先后收到补发、带补发标记,已送达的不重复;太旧的、已删除的不补发,补发途中又断开的留到下次;收到补发的文件不写进剪贴板。++### NAT 打洞实验室++`tools/natlab/run.sh` 用 Linux 网络命名空间与 iptables 搭出真实拓扑,`client-core/cmd/natlab` 用 CopySync 真实的 P2P 代码扮演两台设备:++```+[a] 192.168.10.2 ── [rA] 出口 10.255.0.11–14 ──┐+ [inet] 信令 TURN STUN×4+[b] 192.168.20.2 ── [rB] 出口 10.254.0.21–22 ──┘+```++rA 用 SNAT 规则按目标地址选出口,还原公司网络;rB 还原家用路由器或端口随机分配的 NAT。两台路由器都丢弃外网主动发起的新连接,与真实路由器一致(原因见「踩过的坑」)。++| 场景 | 预期 | 结果 |+|---|---|---|+| 单出口 ↔ 家用路由器 | 直连 | 通过 |+| 两个出口,旧版本(对照) | 中转 | 通过:复现了原问题 |+| 两个出口 ↔ 家用路由器 | 直连 | 通过 |+| 四个出口 ↔ 家用路由器 | 直连 | 通过 |+| 两个出口,第二条没探测到,无历史 | 中转 | 通过 |+| 两个出口,第二条没探测到,有历史 | 直连 | 通过 |+| 两个出口 ↔ 两个出口 | 直连 | 通过 |+| 两个出口 ↔ 端口随机分配的 NAT | 中转 | 通过 |+| 一开始打不通,8 秒后网络恢复(1.1.1) | 先中转,随后换成直连 | 通过 |++最后一个场景让家用路由器开头 8 秒不放行发往公司出口的 UDP,第一次握手只能落到中转;放开后,脚本还要求日志里确实出现了「中转 → 尝试换成直连」,排除一开始就碰巧直连的情况。++本地运行:`./tools/natlab/docker.sh`(macOS 上在特权容器里跑;国内网络加 `APK_MIRROR=mirrors.aliyun.com`)。CI 的 `natlab` 任务在每次提交时运行。++### 实机验收++公司这台(4 个出口)升级到 1.1.0,家里那台仍是 1.0.2:++```+23:19:40.083 信令已连接+23:19:41.718 出口探测完成 B:64778 C:17820 A:64778+23:19:42.884 P2P 连接状态 direct+```++连上信令后约 3 秒建立直连。改造前同一对设备只能中转。++公司这台升级到 1.1.1 之后:++```+00:12:14.666 信令已连接+00:12:14.837 出口探测完成 C:19735 B:49454 D:60103 A:49454+00:12:18.127 P2P 连接状态 direct+```++探测在连上信令后 0.17 秒完成(1.1.0 约 1.6 秒),4 条线路全部探到。++## 六、踩过的坑++- **pion 为每台 STUN 服务器单独开端口。**这是多配 STUN 服务器也打不通的原因,也是改用共享端口的出发点。+- **单靠本端判断「是否中转」会出错。**一端经 TURN 发送时,另一端看到的源地址可能是 peer-reflexive 地址,并不标为 relay。这曾导致两台设备一台显示直连、一台显示中转,靠两端交换 `LinkInfo` 解决。+- **实验室路由器必须丢弃外网主动发起的新连接。**两端同时打洞时,对方的包可能先到达本端路由器。若放行到路由器本机,Linux conntrack 会为它建一条「未应答」记录;随后本端往外发时源端口与之冲突,SNAT 只好换一个端口,事先告诉对端的地址就失效了。真实路由器的防火墙直接丢弃这类包,被丢弃的包不会留下连接记录。没加这条规则时,连最简单的单出口场景都会误判为打不通。+- **公共 STUN 域名可能被污染。**`stun.syncthing.net` 在测试网络里被解析到 `192.0.2.42`。不过滤的话,要么白等超时,要么被当成一个出口。+- **实验室场景要互相隔离。**出口历史文件跨场景残留,曾让「无历史」场景意外直连。这反过来也说明历史推算确实生效。+- **pion 选定 candidate 对后不再更换。**一次握手输给中转,整个连接期间都是中转。等待时限只能降低输的概率,要补救得靠 ICE 重启(第 8 节)。+- **pion 报告失败后不会自己关闭连接**,控制通道也仍显示打开。只把状态改成离线是不够的,必须关闭清理,否则上层永远不会重连(第 9 节)。++## 七、局限与后续++- **对端是端口随机分配的 NAT 时仍会中转。**理论上可以做端口预测或大规模并发打洞,但成功率低、流量大,暂不做。+- **UDP 被拦截时只能中转。**后续可以增加 TURN over TCP/TLS(443 端口)。+- **探测覆盖取决于服务器 IP 的分散程度。**线路越多,越需要更多 IP。服务器可以用 `-stun` 参数下发更多 STUN 地址,客户端会一并探测。+- **待补发队列只在内存里。**本机后台服务重启后清空;对方离线超过 24 小时的内容也不补发。+- **两边都有公网 IPv6 时最省事。**pion 会直接收集 IPv6 地址,无需穿越 NAT。这次的两台设备都没有。diff --git a/docs/assets/screenshots/settings.png b/docs/assets/screenshots/settings.pngindex 475ab92..2bff6ae 100644Binary files a/docs/assets/screenshots/settings.png and b/docs/assets/screenshots/settings.png differdiff --git a/docs/assets/site.css b/docs/assets/site.cssindex 848afa0..9993153 100644--- a/docs/assets/site.css+++ b/docs/assets/site.css@@ -980,3 +980,23 @@ tbody th {stroke-width: 1.5;stroke-dasharray: 6 6;}++/* 多出口网络:实测出口与实验室结果 */+.measure {+ margin-top: 1rem;+}++.measure td:first-child {+ font-family: var(--mono);+ font-size: 0.9rem;+ white-space: nowrap;+}++.measure td:last-child,+.lab td:last-child {+ color: var(--dim);+}++.lab td:last-child {+ white-space: nowrap;+}diff --git a/docs/en/index.html b/docs/en/index.htmlindex 790d246..87c9d86 100644--- a/docs/en/index.html+++ b/docs/en/index.html@@ -40,8 +40,8 @@"description": "Open-source tool that syncs the clipboard and files between Macs. Copy text, images, files or folders on one Mac and paste them on another. Devices connect directly over WebRTC with DTLS encryption, falling back to a TURN relay on a server the user hosts.","applicationCategory": "UtilitiesApplication","operatingSystem": "macOS 13 or later (Intel and Apple silicon)",- "softwareVersion": "1.1.0",- "datePublished": "2026-10-08",+ "softwareVersion": "1.1.1",+ "datePublished": "2026-10-09","inLanguage": "en","license": "https://opensource.org/licenses/MIT","isAccessibleForFree": true,@@ -139,7 +139,7 @@<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3v10m0 0-4-4m4 4 4-4M4 16h12"/></svg>Download for macOS</a>- <span class="note">Version 1.1.0, free and open source. macOS 13 or later, Intel and Apple silicon.</span>+ <span class="note">Version 1.1.1, free and open source. macOS 13 or later, Intel and Apple silicon.</span></div><div class="demo" role="img" aria-label="Demo: a file is selected on a MacBook Pro and copied with Command C, travels over a direct connection to a MacBook Air, and is pasted there with Command V">@@ -274,7 +274,59 @@</div></section>- <section class="section" aria-labelledby="security-title">+ <section class="section" id="multi-uplink" aria-labelledby="multi-title">+ <div class="wrap">+ <h2 id="multi-title">Direct on office networks too</h2>+ <p class="intro">Office networks with two ISPs, or carriers with a pool of NAT addresses, have several uplinks and pick one per destination. CopySync 1.0 knew only one of its addresses there and had to relay through the server. 1.1 probes every uplink and tells the peer about all of them.</p>+ <div class="two-col">+ <div class="prose">+ <h3>What changed</h3>+ <ul>+ <li><strong>One shared port.</strong> All connections send and receive on one local UDP port. Previously each STUN server got its own port, so the answers didn't apply to each other.</li>+ <li><strong>Every uplink probed.</strong> Seven IP-diverse servers are queried from that port at once, yielding one address per uplink. Addresses poisoned by DNS are dropped first.</li>+ <li><strong>All of them sent to the peer.</strong> The peer tries each address; the one matching the real uplink gets through.</li>+ <li><strong>Uplinks remembered.</strong> If a round misses an uplink that keeps ports unchanged, its address is filled in as uplink IP plus local port.</li>+ <li><strong>Relay first, direct later.</strong> When the peer has just started, its addresses can arrive a moment late and the first handshake lands on the relay. CopySync punches again while the link is idle and switches to direct when that works.</li>+ </ul>+ </div>+ <div>+ <h3>A real office network</h3>+ <table class="measure">+ <thead><tr><th scope="col">Uplink</th><th scope="col">Public port</th></tr></thead>+ <tbody>+ <tr><td>Uplink A</td><td>Unchanged</td></tr>+ <tr><td>Uplink B</td><td>Unchanged</td></tr>+ <tr><td>Uplink C</td><td>Rewritten, same for every destination</td></tr>+ <tr><td>Uplink D</td><td>Rewritten</td></tr>+ </tbody>+ </table>+ <p class="aside-p">Before, this Mac and one at home could only relay, capped at 0.6 MB/s by the server's bandwidth. Now they connect directly, about 3 seconds after reaching the server.</p>+ </div>+ </div>++ <h3 class="subhead">Checked against real network topologies</h3>+ <p class="aside-p">The NAT lab builds the nine topologies below with Linux network namespaces and iptables and runs CopySync's actual connection code through each. It runs on every commit.</p>+ <div class="table-scroll">+ <table class="lab">+ <thead><tr><th scope="col">Scenario</th><th scope="col">Result</th></tr></thead>+ <tbody>+ <tr><td>Single uplink ↔ home router</td><td>Direct</td></tr>+ <tr><td>Two uplinks, previous version (control)</td><td>Relay</td></tr>+ <tr><td>Two uplinks ↔ home router</td><td>Direct</td></tr>+ <tr><td>Four uplinks ↔ home router</td><td>Direct</td></tr>+ <tr><td>Two uplinks, second not probed, no history</td><td>Relay</td></tr>+ <tr><td>Two uplinks, second not probed, with history</td><td>Direct</td></tr>+ <tr><td>Two uplinks ↔ two uplinks</td><td>Direct</td></tr>+ <tr><td>Two uplinks ↔ NAT that randomizes ports</td><td>Relay</td></tr>+ <tr><td>Blocked at first, network recovers later</td><td>Relay, then direct</td></tr>+ </tbody>+ </table>+ </div>+ <p class="aside-p">Measurements, design trade-offs and lessons learned are in the <a href="https://github.com/baiyuze/copysync/blob/main/design/nat-traversal.md">design document</a> (Chinese).</p>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="security-title"><div class="wrap two-col"><div class="prose"><h2 id="security-title">Your server can't see what you copy</h2>@@ -294,7 +346,7 @@</div></section>- <section class="section section-band" aria-labelledby="fallback-title">+ <section class="section" aria-labelledby="fallback-title"><div class="wrap"><h2 id="fallback-title">When things go wrong</h2><p class="intro">Every network is different. Each of these cases was considered, and each has a test.</p>@@ -305,6 +357,10 @@<dd>Public STUN is unreliable in some regions, including mainland China. Your server runs its own STUN, and clients prefer it.</dd><dt>An office network with several uplinks</dt><dd>These networks pick an uplink per destination, so a single probe only reveals one of your addresses. CopySync probes several servers from one port and sends the peer its address on every uplink to try in turn.</dd>+ <dt>Connected through the relay first</dt>+ <dd>The relay handshake is fast and sometimes beats the direct path. Once connected, the side that started the connection punches again while idle and switches to direct when that works, never in the middle of a transfer.</dd>+ <dt>The other Mac sleeps, drops off or restarts</dt>+ <dd>A connection that dies silently is noticed, closed and reconnected. Anything you copy meanwhile is kept and added to the other Mac's history once it's back, without overwriting what's on its clipboard now.</dd><dt>Server connection drops</dt><dd>Reconnects automatically: the delay starts at 1 second and doubles up to 30, with jitter so devices don't all reconnect at once. The app shows the status live.</dd><dt>File too large</dt>@@ -321,7 +377,7 @@</div></section>- <section class="section" id="install" aria-labelledby="install-title">+ <section class="section section-band" id="install" aria-labelledby="install-title"><div class="wrap"><h2 id="install-title">Install</h2><p class="intro">Install the app on each Mac, and set up a server both of them can reach. If both Macs share a LAN, the server can run on one of them.</p>@@ -363,13 +419,13 @@ sudo ./install.sh YOUR_PUBLIC_IP</code></pre></div></section>- <section class="section section-band" aria-labelledby="specs-title">+ <section class="section" aria-labelledby="specs-title"><div class="wrap"><h2 id="specs-title">Specifications</h2><div class="table-scroll"><table class="specs"><tbody>- <tr><th scope="row">Version</th><td>1.1.0, released <time datetime="2026-10-08">October 8, 2026</time></td></tr>+ <tr><th scope="row">Version</th><td>1.1.1, released <time datetime="2026-10-09">October 9, 2026</time></td></tr><tr><th scope="row">Mac app</th><td>macOS 13 Ventura or later; universal binary for Intel and Apple silicon, no Rosetta; 45 MB download</td></tr><tr><th scope="row">Server</th><td>Linux on x86_64 or ARM64 (systemd or Docker), or macOS; about 15 MB of RAM</td></tr><tr><th scope="row">Content</th><td>Plain text, rich text, images and screenshots, files, folders; each type can be turned off</td></tr>@@ -387,7 +443,7 @@ sudo ./install.sh YOUR_PUBLIC_IP</code></pre></div></section>- <section class="section" id="faq" aria-labelledby="faq-title">+ <section class="section section-band" id="faq" aria-labelledby="faq-title"><div class="wrap"><h2 id="faq-title">Questions</h2><div class="faq">@@ -444,7 +500,7 @@ sudo ./install.sh YOUR_PUBLIC_IP</code></pre></div></section>- <section class="closing section-band" aria-labelledby="closing-title">+ <section class="closing" aria-labelledby="closing-title"><div class="wrap"><h2 id="closing-title">Two Macs, one clipboard.</h2><div class="cta">diff --git a/docs/index.html b/docs/index.htmlindex ea2acc1..6207a7e 100644--- a/docs/index.html+++ b/docs/index.html@@ -40,8 +40,8 @@"description": "在两台 Mac 之间同步剪贴板与文件的开源工具。复制文本、图片、文件或文件夹后,另一台 Mac 可直接粘贴。设备间 WebRTC 直连、DTLS 端到端加密,打不通时经用户自建服务器的 TURN 中转。","applicationCategory": "UtilitiesApplication","operatingSystem": "macOS 13 及以上(Intel 与 Apple 芯片)",- "softwareVersion": "1.1.0",- "datePublished": "2026-10-08",+ "softwareVersion": "1.1.1",+ "datePublished": "2026-10-09","inLanguage": "zh-CN","license": "https://opensource.org/licenses/MIT","isAccessibleForFree": true,@@ -139,7 +139,7 @@<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3v10m0 0-4-4m4 4 4-4M4 16h12"/></svg>下载 macOS 版</a>- <span class="note">版本 1.1.0,免费开源。macOS 13 及以上,Intel 与 Apple 芯片通用。</span>+ <span class="note">版本 1.1.1,免费开源。macOS 13 及以上,Intel 与 Apple 芯片通用。</span></div><div class="demo" role="img" aria-label="演示:在 MacBook Pro 上选中文件并按下 Command C,文件经直连传到 MacBook Air,在那里按下 Command V 粘贴出来">@@ -274,7 +274,59 @@</div></section>- <section class="section" aria-labelledby="security-title">+ <section class="section" id="multi-uplink" aria-labelledby="multi-title">+ <div class="wrap">+ <h2 id="multi-title">公司网络也能直连</h2>+ <p class="intro">公司双线、运营商地址池这类网络有多个出口,按目标地址选走哪一个。CopySync 1.0 只知道其中一个出口的地址,在这类网络里只能经服务器中转。1.1 会探测每个出口,把地址都告诉对端。</p>+ <div class="two-col">+ <div class="prose">+ <h3>做了什么</h3>+ <ul>+ <li><strong>共用一个端口。</strong>所有连接从同一个本地 UDP 端口收发。之前每问一台 STUN 服务器就开一个新端口,问到的地址互相用不上。</li>+ <li><strong>探测每个出口。</strong>在这个端口上同时询问 7 台 IP 分散的服务器,网络有几个出口就拿到几个地址。被 DNS 污染的地址先过滤掉。</li>+ <li><strong>全部告诉对端。</strong>每个出口的地址都发给对端,由它逐个尝试,与实际出口吻合的那一个能打通。</li>+ <li><strong>记住见过的出口。</strong>某次漏掉的出口如果不改端口,就用「出口 IP + 本地端口」推算补上。</li>+ <li><strong>先中转,再换直连。</strong>对端刚启动时,出口地址可能晚到一步,第一次握手落到了中转。之后会在空闲时再打一次洞,打通就换成直连。</li>+ </ul>+ </div>+ <div>+ <h3>一个真实的公司网络</h3>+ <table class="measure">+ <thead><tr><th scope="col">出口</th><th scope="col">公网端口</th></tr></thead>+ <tbody>+ <tr><td>出口 A</td><td>不变</td></tr>+ <tr><td>出口 B</td><td>不变</td></tr>+ <tr><td>出口 C</td><td>改写,但对不同目标相同</td></tr>+ <tr><td>出口 D</td><td>改写</td></tr>+ </tbody>+ </table>+ <p class="aside-p">改造前,这台 Mac 与家里的 Mac 只能中转,速度被服务器带宽限制在 0.6 MB/s。改造后直连,连上服务器后约 3 秒建立。</p>+ </div>+ </div>++ <h3 class="subhead">用真实的网络拓扑验证</h3>+ <p class="aside-p">NAT 打洞实验室用 Linux 网络命名空间与 iptables 搭出下面 9 种拓扑,用 CopySync 真实的连接代码各跑一遍。每次提交代码都会自动运行。</p>+ <div class="table-scroll">+ <table class="lab">+ <thead><tr><th scope="col">场景</th><th scope="col">结果</th></tr></thead>+ <tbody>+ <tr><td>单出口 ↔ 家用路由器</td><td>直连</td></tr>+ <tr><td>两个出口,旧版本(对照)</td><td>中转</td></tr>+ <tr><td>两个出口 ↔ 家用路由器</td><td>直连</td></tr>+ <tr><td>四个出口 ↔ 家用路由器</td><td>直连</td></tr>+ <tr><td>两个出口,第二条没探测到,没有历史</td><td>中转</td></tr>+ <tr><td>两个出口,第二条没探测到,有历史</td><td>直连</td></tr>+ <tr><td>两个出口 ↔ 两个出口</td><td>直连</td></tr>+ <tr><td>两个出口 ↔ 端口随机分配的 NAT</td><td>中转</td></tr>+ <tr><td>一开始打不通,之后网络恢复</td><td>先中转,随后直连</td></tr>+ </tbody>+ </table>+ </div>+ <p class="aside-p">测量过程、设计取舍与踩过的坑见<a href="https://github.com/baiyuze/copysync/blob/main/design/nat-traversal.md">技术方案</a>。</p>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="security-title"><div class="wrap two-col"><div class="prose"><h2 id="security-title">服务器看不到你复制了什么</h2>@@ -294,7 +346,7 @@</div></section>- <section class="section section-band" aria-labelledby="fallback-title">+ <section class="section" aria-labelledby="fallback-title"><div class="wrap"><h2 id="fallback-title">出问题的时候会发生什么</h2><p class="intro">每个人的网络环境都不一样。下面这些情况都考虑过,也都有对应的测试。</p>@@ -305,6 +357,10 @@<dd>国内访问公共 STUN 时通时断。服务器自带 STUN,客户端优先用它。</dd><dt>公司网络有多个出口</dt><dd>双线、运营商地址池这类网络按目标地址选出口,只探测一次只会知道其中一个出口的地址。CopySync 在同一个端口上向多台服务器探测,把每个出口的地址都发给对端,由它逐个尝试。</dd>+ <dt>先连上了中转</dt>+ <dd>中转握手快,有时会抢在直连之前。连上之后,发起连接的一方会在空闲时再打一次洞,打通就换成直连;正在传文件时不打扰。</dd>+ <dt>对方睡眠、断网或重启</dt>+ <dd>连接悄悄断了也能发现,立即关闭重连。这期间复制的内容会记下来,连上后补发到对方的复制记录里,但不会覆盖对方此刻剪贴板里的内容。</dd><dt>服务器断开</dt><dd>自动重连,间隔从 1 秒开始翻倍、最长 30 秒,并带随机抖动,避免一群设备同时重连。界面实时显示连接状态。</dd><dt>文件太大</dt>@@ -321,7 +377,7 @@</div></section>- <section class="section" id="install" aria-labelledby="install-title">+ <section class="section section-band" id="install" aria-labelledby="install-title"><div class="wrap"><h2 id="install-title">安装</h2><p class="intro">每台 Mac 装一个 App,再准备一台两边都能访问到的服务器。两台 Mac 在同一个局域网的话,服务器直接跑在其中一台上就行。</p>@@ -363,13 +419,13 @@ sudo ./install.sh 你的公网IP</code></pre></div></section>- <section class="section section-band" aria-labelledby="specs-title">+ <section class="section" aria-labelledby="specs-title"><div class="wrap"><h2 id="specs-title">技术规格</h2><div class="table-scroll"><table class="specs"><tbody>- <tr><th scope="row">版本</th><td>1.1.0,<time datetime="2026-10-08">2026 年 10 月 8 日</time>发布</td></tr>+ <tr><th scope="row">版本</th><td>1.1.1,<time datetime="2026-10-09">2026 年 10 月 9 日</time>发布</td></tr><tr><th scope="row">Mac 客户端</th><td>macOS 13 Ventura 及以上;Intel 与 Apple 芯片通用,不需要 Rosetta;安装包 45 MB</td></tr><tr><th scope="row">服务器</th><td>Linux x86_64 或 ARM64(systemd 或 Docker),也可以运行在 macOS 上;约 15 MB 内存</td></tr><tr><th scope="row">同步的内容</th><td>纯文本、带格式的文本、图片与截图、文件、文件夹,可以按类型关闭</td></tr>@@ -387,7 +443,7 @@ sudo ./install.sh 你的公网IP</code></pre></div></section>- <section class="section" id="faq" aria-labelledby="faq-title">+ <section class="section section-band" id="faq" aria-labelledby="faq-title"><div class="wrap"><h2 id="faq-title">常见问题</h2><div class="faq">@@ -444,7 +500,7 @@ sudo ./install.sh 你的公网IP</code></pre></div></section>- <section class="closing section-band" aria-labelledby="closing-title">+ <section class="closing" aria-labelledby="closing-title"><div class="wrap"><h2 id="closing-title">两台 Mac,一个剪贴板。</h2><div class="cta">diff --git a/docs/llms.txt b/docs/llms.txtindex 3fd7da8..afb09a7 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -6,15 +6,15 @@Key facts:-- Current version: 1.1.0, released 2026-10-08.+- Current version: 1.1.1, released 2026-10-09.- Client: macOS 13 Ventura or later, universal binary for Intel and Apple silicon. Distributed as a DMG; not notarized by Apple, so the first launch needs "Open Anyway" in System Settings → Privacy & Security.- Server: a single static Go binary for Linux (x86_64, ARM64) or macOS, installed via systemd script or Docker Compose. Ports: 8787/tcp (signaling), 3478/udp (STUN/TURN), 32768–60999/udp (relay).- Content synced: plain text, rich text (HTML plus a plain-text copy), images, files, folders.-- Works on multi-uplink networks (e.g. offices with two ISPs) that pick an uplink per destination: the client probes several STUN servers from one shared port to learn its address on every uplink and sends all of them to the peer. Diagnose with `copysync-cli nat`.+- Works on multi-uplink networks (e.g. offices with two ISPs) that pick an uplink per destination: the client probes several STUN servers from one shared port to learn its address on every uplink and sends all of them to the peer. Diagnose with `copysync-cli nat`. If a connection lands on the relay first, the client retries the direct path with an ICE restart while idle.- Items under 50 MB (adjustable 1 MB–1 GB) are pushed on copy; larger files sync as a record and are pulled on demand.- History keeps 3 days by default (adjustable 1 hour–30 days).- Pairing: 6-character code valid for 5 minutes, plus a human check that both Macs show the same two fingerprints (one per device's Ed25519 public key), which prevents man-in-the-middle attacks by the server.-- Not supported: Windows (planned), iPhone/iPad (iOS forbids background clipboard monitoring). Both Macs must be online at the same time; there is no store-and-forward.+- Not supported: Windows (planned), iPhone/iPad (iOS forbids background clipboard monitoring). The server stores nothing: while the other Mac is unreachable, the latest 20 items are kept in memory and sent when it reconnects (added to its history, not its clipboard).- Compared with Apple's Universal Clipboard: no same-Apple-ID or proximity requirement, keeps a history, handles large files and folders.## Docs@@ -22,6 +22,7 @@ Key facts:- [README (中文)](https://github.com/baiyuze/copysync/blob/main/README.md): features, installation, architecture, security model, fallbacks- [README (English)](https://github.com/baiyuze/copysync/blob/main/README.en.md): the same in English- [Server deployment](https://github.com/baiyuze/copysync/blob/main/server/deploy/README.md): systemd, Docker and manual setup+- [NAT traversal design (中文)](https://github.com/baiyuze/copysync/blob/main/design/nat-traversal.md): multi-uplink probing, relay-to-direct upgrade, measurements and the NAT lab- [Changelog](https://github.com/baiyuze/copysync/blob/main/CHANGELOG.md)## Downloaddiff --git a/proto/copysync/v1/wire.proto b/proto/copysync/v1/wire.protoindex b4e8593..21e21c2 100644--- a/proto/copysync/v1/wire.proto+++ b/proto/copysync/v1/wire.proto@@ -192,6 +192,9 @@ message ClipOffer {// HTML 的纯文本形式(此时 text_content 是 HTML 标记)。旧版本不发这个字段,// 收到空值时由接收方从 HTML 中提取。string plain_text = 8;+ // 补发:复制时对端连不上,连接恢复后才发过去的旧内容。+ // 只进复制记录,不写进对端的剪贴板,免得覆盖对方此刻正在用的内容。+ bool backlog = 9;}// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peerdiff --git a/proto/gen/copysync/v1/wire.pb.go b/proto/gen/copysync/v1/wire.pb.goindex 0b11947..aa9a3f6 100644--- a/proto/gen/copysync/v1/wire.pb.go+++ b/proto/gen/copysync/v1/wire.pb.go@@ -1707,7 +1707,10 @@ type ClipOffer struct {WillPush bool `protobuf:"varint,7,opt,name=will_push,json=willPush,proto3" json:"will_push,omitempty"` // true=发送方会主动推,false=需 fetch// HTML 的纯文本形式(此时 text_content 是 HTML 标记)。旧版本不发这个字段,// 收到空值时由接收方从 HTML 中提取。- PlainText string `protobuf:"bytes,8,opt,name=plain_text,json=plainText,proto3" json:"plain_text,omitempty"`+ PlainText string `protobuf:"bytes,8,opt,name=plain_text,json=plainText,proto3" json:"plain_text,omitempty"`+ // 补发:复制时对端连不上,连接恢复后才发过去的旧内容。+ // 只进复制记录,不写进对端的剪贴板,免得覆盖对方此刻正在用的内容。+ Backlog bool `protobuf:"varint,9,opt,name=backlog,proto3" json:"backlog,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -1798,6 +1801,13 @@ func (x *ClipOffer) GetPlainText() string {return ""}+func (x *ClipOffer) GetBacklog() bool {+ if x != nil {+ return x.Backlog+ }+ return false+}+// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peertype PeerFetch struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -2162,7 +2172,7 @@ const file_copysync_v1_wire_proto_rawDesc = "" +"\x04link\x18\x06 \x01(\v2\x15.copysync.v1.LinkInfoH\x00R\x04linkB\t\n" +"\apayload\"$\n" +"\bLinkInfo\x12\x18\n" +- "\arelayed\x18\x01 \x01(\bR\arelayed\"\xa2\x02\n" ++ "\arelayed\x18\x01 \x01(\bR\arelayed\"\xbc\x02\n" +"\tClipOffer\x12\x17\n" +"\aclip_id\x18\x01 \x01(\tR\x06clipId\x12)\n" +"\x04kind\x18\x02 \x01(\x0e2\x15.copysync.v1.ClipKindR\x04kind\x12+\n" +@@ -2173,7 +2183,8 @@ const file_copysync_v1_wire_proto_rawDesc = "" +"\x0fcreated_at_unix\x18\x06 \x01(\x03R\rcreatedAtUnix\x12\x1b\n" +"\twill_push\x18\a \x01(\bR\bwillPush\x12\x1d\n" +"\n" +- "plain_text\x18\b \x01(\tR\tplainText\"$\n" ++ "plain_text\x18\b \x01(\tR\tplainText\x12\x18\n" ++ "\abacklog\x18\t \x01(\bR\abacklog\"$\n" +"\tPeerFetch\x12\x17\n" +"\aclip_id\x18\x01 \x01(\tR\x06clipId\">\n" +"\vFetchReject\x12\x17\n" +diff --git a/scripts/build.sh b/scripts/build.shindex f5c3a1c..146fb46 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -14,7 +14,7 @@ set -euo pipefailcd "$(dirname "$0")/.."DIST=dist-VERSION=${VERSION:-1.1.0}+VERSION=${VERSION:-1.1.1}rm -rf "$DIST" && mkdir -p "$DIST"# 构建 x86_64 + arm64 通用二进制:两台 Mac 的芯片未必相同,单架构的diff --git a/scripts/package.sh b/scripts/package.shindex 454b30b..174b406 100755--- a/scripts/package.sh+++ b/scripts/package.sh@@ -15,7 +15,7 @@set -euo pipefailcd "$(dirname "$0")/.."-export VERSION=${VERSION:-1.1.0}+export VERSION=${VERSION:-1.1.1}OUT=release./scripts/build.shdiff --git a/tools/natlab/docker.sh b/tools/natlab/docker.shindex 8efd656..f97c220 100755--- a/tools/natlab/docker.sh+++ b/tools/natlab/docker.sh@@ -4,6 +4,7 @@# ./tools/natlab/docker.sh## 国内网络拉取 Alpine 软件包慢的话:APK_MIRROR=mirrors.aliyun.com ./tools/natlab/docker.sh+# 只跑部分场景:NATLAB_ONLY=晚到 ./tools/natlab/docker.shset -euo pipefailcd "$(dirname "$0")/../.."@@ -18,5 +19,5 @@ echo "▶ 编译 natlab(linux/$ARCH)"echo "▶ 准备实验室镜像"docker build -q -t copysync-natlab --build-arg APK_MIRROR="${APK_MIRROR:-}" tools/natlab >/dev/null-docker run --rm --privileged -v "$OUT:/lab:ro" -v "$PWD/tools/natlab:/scripts:ro" \+docker run --rm --privileged -e NATLAB_ONLY -v "$OUT:/lab:ro" -v "$PWD/tools/natlab:/scripts:ro" \copysync-natlab bash /scripts/run.sh /lab/natlabdiff --git a/tools/natlab/run.sh b/tools/natlab/run.shindex f5dc285..1114e18 100755--- a/tools/natlab/run.sh+++ b/tools/natlab/run.sh@@ -135,11 +135,11 @@ setup() {PASS=0FAIL=0-# check <场景名> <A 侧> <B 侧> <direct|relay> [legacy|history]+# check <场景名> <A 侧> <B 侧> <direct|relay> [legacy|history|late]check() {# NATLAB_ONLY 只跑名字里含这段文字的场景,排查问题时用[[ -n ${NATLAB_ONLY:-} && $1 != *"$NATLAB_ONLY"* ]] && return- local name=$1 expect=$4 flag=${5:-} aflags=() state="$WORK/a-state.json"+ local name=$1 expect=$4 flag=${5:-} aflags=() bflags=() state="$WORK/a-state.json"rm -f "$state" # 每个场景从空白开始:上一个场景的出口历史会让这一个「意外」直连setup "$2" "$3"case $flag in@@ -149,9 +149,19 @@ check() {printf '{"networks":{"192.168.10.2":[{"ip":"10.255.0.12","port_preserved":true,"last_seen":"%s"}]}}' \"$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$state";;+ late)+ # 开头 8 秒 rB 不放行发往 a 那边的 UDP,第一次握手只能落到中转;+ # 之后放开,a 应当用 ICE 重启换成直连。对应现实里「对端刚启动,+ # 出口地址晚到」「网络刚恢复」等一次没打通、之后其实打得通的情形+ local block=(FORWARD -i lan -d 10.255.0.0/24 -p udp -j DROP)+ ns rB iptables -I "${block[@]}"+ (sleep 8 && ns rB iptables -D "${block[@]}") &+ aflags=(-settle 40s)+ bflags=(-settle 40s)+ ;;esaclocal common=(-infra http://10.200.0.2:9000 -stun 10.200.1.1:3478 -timeout 30s)- ns b "$BIN" peer -id b -peer a "${common[@]}" -probe "$PROBE" >"$WORK/b.json" 2>"$WORK/b.log" &+ ns b "$BIN" peer -id b -peer a "${common[@]}" -probe "$PROBE" "${bflags[@]}" >"$WORK/b.json" 2>"$WORK/b.log" &local bpid=$!ns a "$BIN" peer -id a -peer b "${common[@]}" -probe "$PROBE" -state "$state" "${aflags[@]}" \>"$WORK/a.json" 2>"$WORK/a.log" || true@@ -160,7 +170,14 @@ check() {local a ba=$(sed -n 's/.*"state":"\([a-z]*\)".*/\1/p' "$WORK/a.json")b=$(sed -n 's/.*"state":"\([a-z]*\)".*/\1/p' "$WORK/b.json")- if [[ $a == "$expect" && $b == "$expect" ]]; then+ local ok=0+ [[ $a == "$expect" && $b == "$expect" ]] && ok=1+ # 「晚到」场景必须真的先落到中转、再靠 ICE 重启换成直连,否则没测到要测的东西+ if [[ $flag == late ]] && ! grep -q '尝试换成直连' "$WORK/a.log"; then+ ok=0+ echo " a 没有经过「中转 → 尝试换成直连」"+ fi+ if [[ $ok == 1 ]]; thenPASS=$((PASS + 1))printf ' ✓ %-34s %s\n' "$name" "$a"else@@ -168,7 +185,7 @@ check() {printf ' ✗ %-34s 期望 %s,实际 a=%s b=%s\n' "$name" "$expect" "${a:-无结果}" "${b:-无结果}"echo " a: $(cat "$WORK/a.json")"echo " b: $(cat "$WORK/b.json")"- grep -h -E '出口探测完成|P2P|失败|error' "$WORK/a.log" "$WORK/b.log" | head -8 | sed 's/^/ /'+ grep -h -E '出口探测完成|P2P|换成直连|ICE 重启|失败|error' "$WORK/a.log" "$WORK/b.log" | head -8 | sed 's/^/ /'# NATLAB_KEEP 指定目录时把完整日志留下来[[ -n ${NATLAB_KEEP:-} ]] && cp "$WORK"/*.log "$NATLAB_KEEP/" 2>/dev/null || truefi@@ -183,6 +200,7 @@ check "两个出口,第二条没探测到,无历史" hidden cone relaycheck "两个出口,第二条没探测到,有历史" hidden cone direct historycheck "两个出口 ↔ 两个出口" dual dual directcheck "两个出口 ↔ 端口随机分配的 NAT" dual symmetric relay+check "一开始打不通,先中转后换直连" dual cone direct lateechoecho "通过 $PASS,失败 $FAIL"diff --git a/ui/lib/gen/copysync/v1/wire.pb.dart b/ui/lib/gen/copysync/v1/wire.pb.dartindex 839c8cc..f14bb64 100644--- a/ui/lib/gen/copysync/v1/wire.pb.dart+++ b/ui/lib/gen/copysync/v1/wire.pb.dart@@ -2020,6 +2020,7 @@ class ClipOffer extends $pb.GeneratedMessage {$fixnum.Int64? createdAtUnix,$core.bool? willPush,$core.String? plainText,+ $core.bool? backlog,}) {final result = ClipOffer._();if (clipId != null) result.clipId = clipId;@@ -2030,6 +2031,7 @@ class ClipOffer extends $pb.GeneratedMessage {if (createdAtUnix != null) result.createdAtUnix = createdAtUnix;if (willPush != null) result.willPush = willPush;if (plainText != null) result.plainText = plainText;+ if (backlog != null) result.backlog = backlog;return result;}@@ -2056,6 +2058,7 @@ class ClipOffer extends $pb.GeneratedMessage {..aInt64(6, _omitFieldNames ? '' : 'createdAtUnix')..aOB(7, _omitFieldNames ? '' : 'willPush')..aOS(8, _omitFieldNames ? '' : 'plainText')+ ..aOB(9, _omitFieldNames ? '' : 'backlog')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -2145,6 +2148,17 @@ class ClipOffer extends $pb.GeneratedMessage {$core.bool hasPlainText() => $_has(7);@$pb.TagNumber(8)void clearPlainText() => $_clearField(8);++ /// 补发:复制时对端连不上,连接恢复后才发过去的旧内容。+ /// 只进复制记录,不写进对端的剪贴板,免得覆盖对方此刻正在用的内容。+ @$pb.TagNumber(9)+ $core.bool get backlog => $_getBF(8);+ @$pb.TagNumber(9)+ set backlog($core.bool value) => $_setBool(8, value);+ @$pb.TagNumber(9)+ $core.bool hasBacklog() => $_has(8);+ @$pb.TagNumber(9)+ void clearBacklog() => $_clearField(9);}/// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peerdiff --git a/ui/lib/gen/copysync/v1/wire.pbjson.dart b/ui/lib/gen/copysync/v1/wire.pbjson.dartindex 2f8f059..4068d20 100644--- a/ui/lib/gen/copysync/v1/wire.pbjson.dart+++ b/ui/lib/gen/copysync/v1/wire.pbjson.dart@@ -623,6 +623,7 @@ const ClipOffer$json = {{'1': 'created_at_unix', '3': 6, '4': 1, '5': 3, '10': 'createdAtUnix'},{'1': 'will_push', '3': 7, '4': 1, '5': 8, '10': 'willPush'},{'1': 'plain_text', '3': 8, '4': 1, '5': 9, '10': 'plainText'},+ {'1': 'backlog', '3': 9, '4': 1, '5': 8, '10': 'backlog'},],};@@ -633,7 +634,7 @@ final $typed_data.Uint8List clipOfferDescriptor = $convert.base64Decode('aXBJdGVtUgVpdGVtcxIdCgp0b3RhbF9zaXplGAQgASgDUgl0b3RhbFNpemUSIQoMdGV4dF9jb2''50ZW50GAUgASgJUgt0ZXh0Q29udGVudBImCg9jcmVhdGVkX2F0X3VuaXgYBiABKANSDWNyZWF0''ZWRBdFVuaXgSGwoJd2lsbF9wdXNoGAcgASgIUgh3aWxsUHVzaBIdCgpwbGFpbl90ZXh0GAggAS'- 'gJUglwbGFpblRleHQ=');+ 'gJUglwbGFpblRleHQSGAoHYmFja2xvZxgJIAEoCFIHYmFja2xvZw==');@$core.Deprecated('Use peerFetchDescriptor instead')const PeerFetch$json = {diff --git a/ui/pubspec.yaml b/ui/pubspec.yamlindex d4becef..4e1688b 100644--- a/ui/pubspec.yaml+++ b/ui/pubspec.yaml@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html# In Windows, build-name is used as the major, minor, and patch parts# of the product and file versions while build-number is used as the build suffix.-version: 1.1.0+4+version: 1.1.1+5environment:sdk: ^3.12.2