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.0
baiyuze6f7a178ff0ce
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0216422..a1ca5b9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -42,3 +42,17 @@ jobs:cache: true- run: flutter pub get && flutter analyze && flutter testworking-directory: ui++ natlab:+ name: NAT 打洞实验室+ # 用网络命名空间与 iptables 搭出多出口、对称 NAT 等拓扑,验证直连与中转兜底+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: client-core/go.mod+ cache-dependency-path: client-core/go.sum+ - run: CGO_ENABLED=0 go build -o /tmp/natlab ./cmd/natlab+ working-directory: client-core+ - run: sudo bash tools/natlab/run.sh /tmp/natlabdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9738d85..6498e62 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,20 @@# 更新记录 / Changelog+## 1.1.0 — 2026-10-08++- **多出口网络也能直连**:公司双线、运营商 NAT 地址池这类网络有多个出口,并按目标地址选出口。+ 以前只向自己的服务器探测一次,只知道其中一个出口的地址,发往对端的包从别的出口出去就对不上,+ 只能走中转。现在所有连接共用一个本地端口,在这个端口上向多台服务器探测,拿到每个出口的地址+ 一并发给对端;会改端口的出口也能拿到真实映射,探测漏掉的不改端口出口按历史推算。+ **Direct connections on multi-uplink networks.** Office networks with several uplinks pick an uplink per+ destination; CopySync now probes every uplink from one shared port and sends all of them to the peer.+- 中转路径要等 3 秒才允许被选中,给直连留出打通的时间。 Relay paths wait 3 s before they can be selected.+- 设置里新增「用公共服务器探测网络出口」开关,关闭后只用自己的服务器。 New setting to probe with your own server only.+- 新增 `copysync-cli nat`:查看本机有几个出口、各设备走直连还是中转。 New `copysync-cli nat` diagnostics.+- 新增 NAT 打洞实验室(`tools/natlab`),在 CI 里用真实的网络拓扑验证 8 种场景。+ New NAT lab that checks 8 network topologies in CI.+- 服务器:TURN 可以绑定指定 IP(`relay.Options.ListenIP`)。 Server: TURN can bind to a specific IP.+## 1.0.2 — 2026-10-08- 修复:一端经中转时,另一端误显示为「直连」,两台设备显示不一致。只有发送方能确定自己的数据diff --git a/README.en.md b/README.en.mdindex c8a1b0a..87d7cb1 100644--- a/README.en.md+++ b/README.en.md@@ -166,6 +166,7 @@ flowchart LR- **Fingerprints are compared by a person when pairing.** Both Macs show the same two lines: the fingerprint of each side's public key (the first 60 bits of its SHA-256, like `R8NF-2WTC-QL5J`), in a fixed order. The server could swap keys in transit, but then the two screens would no longer match — this step is what stops a man in the middle. The fingerprints are shown separately rather than combined into one short code: an attacker controlling both forged keys could find a matching combined code with a birthday attack, while separate fingerprints need a preimage attack per key, roughly a billion times harder.- **Every signaling message after that is signed**, so the server cannot forge a device. The DTLS certificate fingerprint of the direct channel is also sent signed and checked against the actual certificate after the handshake; a mismatch drops the connection.- **The relay can't read anything either.** TURN only forwards encrypted UDP packets. Relay credentials are issued per device and expire after 12 hours.+- **Public STUN servers see only your public IP.** To find every uplink on multi-uplink networks, CopySync probes a few public STUN servers by default. They see your public IP, as with any WebRTC app, never content. Turn off 用公共服务器探测网络出口 (Probe with public servers) in Settings to use only your own server.- **No App Sandbox**, because CopySync needs to read files at whatever path you copy them from.### Fallbacks@@ -174,6 +175,7 @@ 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` || 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 |@@ -213,6 +215,7 @@ During development:```bashcd client-core && go test ./... # service tests+./tools/natlab/docker.sh # NAT lab: direct vs relay across 8 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@@ -242,7 +245,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 symmetric NAT or strict firewalls. Everything still works; speed is limited by the server's bandwidth.+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 c4afc4f..be930f9 100644--- a/README.md+++ b/README.md@@ -164,6 +164,7 @@ flowchart LR- **配对时人工核对指纹**。两台设备显示同样的两行:双方各自公钥的指纹(SHA-256 的前 60 位,形如 `R8NF-2WTC-QL5J`),按固定顺序排列。服务器可以在配对时替换转发中的公钥,但替换后两块屏幕上的内容就对不上了,这一步就是防中间人的闸门。两个指纹分开显示而不是合成一串短码,是因为攻击者同时控制两把伪造公钥时,凑出一串相同的短码只需生日攻击;分开显示则要为每把公钥各做一次原像攻击,难度高出约十亿倍。- **之后的每条信令都带签名**,服务器无法伪造设备。直连通道的 DTLS 证书指纹也经签名传递,握手后比对实际证书,不一致立即断开。- **中转也看不到内容**。TURN 只转发加密后的 UDP 包。中转凭证按设备单独签发,12 小时过期。+- **公共 STUN 服务器只看到公网 IP**。为了在多出口网络里找到每个出口,默认会向几台公共 STUN 服务器探测,它们能看到你的公网 IP(与任何 WebRTC 应用一样),看不到内容。介意的话在设置里关掉「用公共服务器探测网络出口」,只用自己的服务器。- **不启用 App 沙盒**:需要访问你复制的任意路径下的文件。### 兜底:出问题时会发生什么@@ -172,6 +173,7 @@ flowchart LR|---|---|| 两端打不通直连(对称 NAT、公司防火墙) | 自动改走服务器的 TURN 中转,内容依然加密;界面上显示「中转」 || 公共 STUN 在国内时通时断 | 服务器自带 STUN,客户端优先用它 |+| 公司双线等多出口网络(按目标地址选出口) | 所有连接共用一个本地端口,在这个端口上向多台服务器探测每个出口的地址,全部发给对端由它逐个尝试;探测漏掉的出口按历史推算。`copysync-cli nat` 可以看到探测结果 || 信令服务器断开 | 指数退避自动重连(1 秒起,最长 30 秒,带随机抖动),界面实时显示连接状态 || 配对时两端确认有先后 | 先确认一方发来的握手消息会被暂存,另一方确认后重放,配对完成几十毫秒内即可直连 || 大文件 | 超过阈值只同步记录,按需拉取;拉取时源文件已被删除会明确提示,而不是失败得不明不白 |@@ -211,6 +213,7 @@ flowchart LR```bashcd client-core && go test ./... # 后台服务的测试+./tools/natlab/docker.sh # NAT 打洞实验室:8 种网络拓扑下的直连与中转cd ui && flutter test # 界面的测试./scripts/install-macos.sh # 把 dist/ 里的后台服务装成登录项./dist/copysync-cli status # 查看后台服务状态@@ -240,7 +243,7 @@ spikes/ 开工前的技术验证检查两台 Mac 的 **设置 → 连接状态** 是否都是「已连接」。不是的话,确认服务器地址正确、8787 端口可以访问。**一直显示「中转」而不是「直连」**-NAT 打洞没成功,常见于对称 NAT 或严格的防火墙。功能不受影响,只是速度受服务器带宽限制。+NAT 打洞没成功,常见于端口随机分配的 NAT 或严格的防火墙。功能不受影响,只是速度受服务器带宽限制。运行 `copysync-cli nat` 看本机探测到了几个出口:出口为 0 说明 UDP 被拦截了。**查看日志**后台服务的日志在 `~/Library/Logs/CopySync/daemon.log`,服务器的日志用 `journalctl -u copysync-server -f` 查看。diff --git a/client-core/cmd/copysync-cli/main.go b/client-core/cmd/copysync-cli/main.goindex 0bd1f61..4f9731e 100644--- a/client-core/cmd/copysync-cli/main.go+++ b/client-core/cmd/copysync-cli/main.go@@ -18,6 +18,7 @@ import ("os""path/filepath""sort"+ "strings""time""google.golang.org/grpc"@@ -36,7 +37,7 @@ func main() {cmd := flag.Arg(0)if cmd == "" {fmt.Fprintln(os.Stderr,- "用法: copysync-cli [-data-dir DIR] <status|watch|history|config|devices|pair|join CODE>")+ "用法: copysync-cli [-data-dir DIR] <status|watch|history|config|devices|nat|pair|join CODE>")os.Exit(2)}@@ -82,6 +83,8 @@ func run(cmd, dataDir string) error {return showConfig(ctx, client)case "devices":return showDevices(ctx, client)+ case "nat":+ return showNetwork(ctx, client)case "pair":return createPairing(ctx, client)case "join":@@ -211,6 +214,62 @@ func printFingerprints(ctx context.Context, c pb.DaemonServiceClient, peer *pb.Dreturn nil}+// showNetwork 打印后台服务最近一轮的网络出口探测结果,以及各设备当前走直连还是中转。+// 看的是后台服务实际在用的数据,而不是另起炉灶再测一遍。+func showNetwork(ctx context.Context, c pb.DaemonServiceClient) error {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ info, err := c.GetNetwork(ctx, &pb.Empty{})+ if err != nil {+ return err+ }+ when := "尚未探测"+ if info.GetProbedAtUnix() > 0 {+ when = time.Unix(info.GetProbedAtUnix(), 0).Format("15:04:05")+ }+ fmt.Printf("打洞端口 %d(UDP)\n", info.GetLocalPort())+ fmt.Printf("最近探测 %s,%d 个服务器中 %d 个响应\n\n", when, info.GetProbed(), info.GetAnswered())++ measured := 0+ for _, e := range info.GetEgresses() {+ mode := "改端口 "+ if e.GetPortPreserved() {+ mode = "不改端口"+ }+ source := strings.Join(e.GetVia(), ", ")+ if e.GetGuessed() {+ source = "按历史推算"+ } else {+ measured+++ }+ fmt.Printf(" %-22s %s %s\n", e.GetAddress(), mode, source)+ }+ switch n := len(info.GetEgresses()); {+ case n == 0:+ fmt.Println(" 没有探测到出口:UDP 可能被拦截,设备之间只能走中转。")+ case n == 1:+ fmt.Println("\n单一出口。")+ default:+ fmt.Printf("\n%d 个出口:这是多出口网络。每个出口的地址都会发给对端,由对端逐个尝试。\n", n)+ }+ if measured > 0 && measured < len(info.GetEgresses()) {+ fmt.Println("按历史推算的出口这一轮没探测到,但它不改端口,地址可以推算出来。")+ }++ devs, err := c.ListDevices(ctx, &pb.Empty{})+ if err != nil {+ return nil+ }+ if peers := devs.GetPeers(); len(peers) > 0 {+ fmt.Println("\n设备连接:")+ for _, p := range peers {+ fmt.Printf(" %-18s %s\n", p.GetName(), connectionLabel(p))+ }+ }+ return nil+}+func joinPairing(ctx context.Context, c pb.DaemonServiceClient, code string) error {if code == "" {return errors.New("用法: copysync-cli join <配对码>")diff --git a/client-core/cmd/copysyncd/main.go b/client-core/cmd/copysyncd/main.goindex 3193866..7810c27 100644--- a/client-core/cmd/copysyncd/main.go+++ b/client-core/cmd/copysyncd/main.go@@ -184,6 +184,7 @@ func run(dataDir string) error {Identity: id,Store: db,LoadConfig: loadCfg,+ StatePath: filepath.Join(paths.Root, "egress.json"),OnDeviceChanged: func(d *pb.Device) {hub.Publish(rpc.EventDeviceChanged(d))},@@ -298,6 +299,20 @@ func run(dataDir string) error {defer cancel()return watcher.Permission(ctx)},+ Network: func() *pb.NetworkInfo {+ r := peerMgr.P2P().Egress()+ info := &pb.NetworkInfo{+ LocalPort: int32(r.LocalPort), Probed: int32(r.Probed),+ Answered: int32(r.Answered), ProbedAtUnix: r.At.Unix(),+ }+ for _, e := range r.Egresses {+ info.Egresses = append(info.Egresses, &pb.NetworkEgress{+ Address: e.Addr.String(), PortPreserved: e.PortPreserved,+ Guessed: e.Guessed(), Via: e.Via,+ })+ }+ return info+ },OpenPermissionSettings: func() error {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()diff --git a/client-core/cmd/natlab/main.go b/client-core/cmd/natlab/main.gonew file mode 100644index 0000000..9f2f9e7--- /dev/null+++ b/client-core/cmd/natlab/main.go@@ -0,0 +1,320 @@+// natlab 是 NAT 打洞实验室的驱动程序,配合 tools/natlab/run.sh 在 Linux 网络命名空间里+// 复现真实网络拓扑(多出口、对称 NAT 等),验证两台设备最终走直连还是中转。+//+// natlab infra -http 10.200.0.2:9000 -stun 10.200.1.1,10.200.1.2 -turn 10.200.0.3+// natlab peer -id a -peer b -infra http://10.200.0.2:9000 -stun ... -probe ... -turn ...+//+// infra 扮演「互联网」上的服务:信令转发、若干台 STUN 服务器、一台 TURN 中转。+// peer 用的就是 CopySync 真实的 P2P 连接代码,只把信令换成了这里的 HTTP 转发。+package main++import (+ "context"+ "encoding/json"+ "errors"+ "flag"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "net/url"+ "os"+ "strings"+ "sync"+ "time"++ "github.com/pion/stun/v4"+ "google.golang.org/protobuf/proto"++ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ turnrelay "github.com/baiyuze/copysync/server/relay"+)++const turnSecret = "natlab"++func main() {+ if len(os.Args) < 2 {+ fmt.Fprintln(os.Stderr, "用法: natlab <infra|peer> [参数]")+ os.Exit(2)+ }+ var err error+ switch os.Args[1] {+ case "infra":+ err = runInfra(os.Args[2:])+ case "peer":+ err = runPeer(os.Args[2:])+ default:+ err = fmt.Errorf("未知的子命令 %q", os.Args[1])+ }+ if err != nil {+ fmt.Fprintln(os.Stderr, "natlab:", err)+ os.Exit(1)+ }+}++// ─────────────────────────── infra ───────────────────────────++func runInfra(args []string) error {+ fs := flag.NewFlagSet("infra", flag.ExitOnError)+ httpAddr := fs.String("http", "", "信令转发的 HTTP 监听地址")+ stunIPs := fs.String("stun", "", "STUN 服务器的 IP,逗号分隔,每个 IP 各起一台")+ turnIP := fs.String("turn", "", "TURN 中转的 IP")+ _ = fs.Parse(args)++ for _, ip := range splitList(*stunIPs) {+ if err := serveSTUN(ip); err != nil {+ return err+ }+ }+ turn, err := turnrelay.New(turnrelay.Options{+ PublicIP: *turnIP, ListenIP: *turnIP, Port: 3478, Secret: turnSecret,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ if err != nil {+ return fmt.Errorf("启动 TURN: %w", err)+ }++ relay := &signalRelay{queues: map[string]chan envelope{}}+ mux := http.NewServeMux()+ mux.HandleFunc("/send", relay.send)+ mux.HandleFunc("/recv", relay.recv)+ mux.HandleFunc("/turn", func(w http.ResponseWriter, r *http.Request) {+ c := turn.Issue(r.URL.Query().Get("id"))+ _ = json.NewEncoder(w).Encode(map[string]any{+ "urls": c.URLs, "username": c.Username, "credential": c.Password,+ })+ })+ return http.ListenAndServe(*httpAddr, mux)+}++// serveSTUN 在指定 IP 上起一台最简的 STUN 服务器:只回答 Binding 请求。+// 绑定具体 IP 而不是 0.0.0.0:回包的源地址必须与客户端发往的地址一致。+func serveSTUN(ip string) error {+ conn, err := net.ListenPacket("udp4", net.JoinHostPort(ip, "3478"))+ if err != nil {+ return fmt.Errorf("STUN %s: %w", ip, err)+ }+ go func() {+ buf := make([]byte, 1500)+ for {+ n, addr, err := conn.ReadFrom(buf)+ if err != nil {+ return+ }+ req := &stun.Message{Raw: append([]byte(nil), buf[:n]...)}+ if req.Decode() != nil || req.Type != stun.BindingRequest {+ continue+ }+ ua := addr.(*net.UDPAddr)+ resp, err := stun.Build(stun.NewTransactionIDSetter(req.TransactionID), stun.BindingSuccess,+ &stun.XORMappedAddress{IP: ua.IP, Port: ua.Port}, stun.Fingerprint)+ if err == nil {+ _, _ = conn.WriteTo(resp.Raw, addr)+ }+ }+ }()+ return nil+}++type envelope struct {+ from string+ body []byte+}++// signalRelay 是最简的信令转发:按收件人排队,收件人长轮询取走。+type signalRelay struct {+ mu sync.Mutex+ queues map[string]chan envelope+}++func (r *signalRelay) queue(id string) chan envelope {+ r.mu.Lock()+ defer r.mu.Unlock()+ q, ok := r.queues[id]+ if !ok {+ q = make(chan envelope, 256)+ r.queues[id] = q+ }+ return q+}++func (r *signalRelay) send(w http.ResponseWriter, req *http.Request) {+ body, _ := io.ReadAll(req.Body)+ q := req.URL.Query()+ r.queue(q.Get("to")) <- envelope{from: q.Get("from"), body: body}+}++func (r *signalRelay) recv(w http.ResponseWriter, req *http.Request) {+ select {+ case e := <-r.queue(req.URL.Query().Get("id")):+ w.Header().Set("X-From", e.from)+ _, _ = w.Write(e.body)+ case <-time.After(20 * time.Second):+ w.WriteHeader(http.StatusNoContent)+ case <-req.Context().Done():+ }+}++// ─────────────────────────── peer ───────────────────────────++type result struct {+ ID string `json:"id"`+ State string `json:"state"`+ Egress []string `json:"egress"`+ Elapsed string `json:"elapsed"`+}++func runPeer(args []string) error {+ fs := flag.NewFlagSet("peer", flag.ExitOnError)+ id := fs.String("id", "", "本端设备 ID")+ peerID := fs.String("peer", "", "对端设备 ID")+ infra := fs.String("infra", "", "infra 的 HTTP 地址")+ stunList := fs.String("stun", "", "信令服务器下发的 STUN(ip:port,逗号分隔)")+ probeList := fs.String("probe", "", "额外的探测服务器,对应真实环境里的公共 STUN")+ statePath := fs.String("state", "", "出口历史文件")+ legacy := fs.Bool("legacy", false, "用旧版本的候选收集方式(对照实验)")+ timeout := fs.Duration("timeout", 40*time.Second, "等待连接的最长时间")+ linger := fs.Duration("linger", 4*time.Second, "报完结果后保持连接的时间")+ _ = fs.Parse(args)++ ctx, cancel := context.WithTimeout(context.Background(), *timeout+10*time.Second)+ defer cancel()+ start := time.Now()++ states := make(chan p2p.ConnState, 16)+ m := p2p.NewManager(p2p.ManagerOptions{+ SelfID: *id,+ Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),+ ProbeAllowPrivate: true, // 实验室用内网地址扮演公网+ DisableEgressProbe: *legacy,+ StatePath: *statePath,+ ProbeServers: func() []string { return splitList(*probeList) },+ SendSignal: func(ctx context.Context, to string, msg *pb.SignalMessage) error {+ raw, err := proto.Marshal(msg)+ if err != nil {+ return err+ }+ u := fmt.Sprintf("%s/send?from=%s&to=%s", *infra, url.QueryEscape(*id), url.QueryEscape(to))+ resp, err := http.Post(u, "application/octet-stream", strings.NewReader(string(raw)))+ if err == nil {+ resp.Body.Close()+ }+ return err+ },+ OnState: func(_ string, s p2p.ConnState) {+ select {+ case states <- s:+ default:+ }+ },+ })+ defer m.Close()++ servers, err := iceServers(*infra, *id, splitList(*stunList))+ if err != nil {+ return err+ }+ m.SetICEServers(servers)+ go receiveSignals(ctx, m, *infra, *id)++ // 等首轮出口探测结束,免得用一份空结果去握手+ if !*legacy {+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) && m.Egress().At.IsZero() {+ time.Sleep(50 * time.Millisecond)+ }+ }+ if err := m.Connect(ctx, *peerID); err != nil {+ return err+ }++ final := waitFinal(states, m, *peerID, *timeout)+ var egress []string+ for _, e := range m.Egress().Egresses {+ egress = append(egress, e.Addr.String())+ }+ err = json.NewEncoder(os.Stdout).Encode(result{+ ID: *id, State: final.String(), Egress: egress, Elapsed: time.Since(start).Round(time.Millisecond).String(),+ })+ // 报完结果再留一会儿:先报完的一端立即退出会关掉连接,另一端还在等稳定状态,+ // 读到的就成了「已断开」+ time.Sleep(*linger)+ return err+}++// waitFinal 等连接建立,再多等一会儿让两端交换 LinkInfo,取稳定后的状态。+func waitFinal(states <-chan p2p.ConnState, m *p2p.Manager, peerID string, timeout 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)+ }+ case <-deadline:+ return m.State(peerID)+ }+ }+}++func iceServers(infra, id string, stunAddrs []string) ([]*pb.IceServer, error) {+ resp, err := http.Get(infra + "/turn?id=" + url.QueryEscape(id))+ if err != nil {+ return nil, fmt.Errorf("获取 TURN 凭证: %w", err)+ }+ defer resp.Body.Close()+ var cred struct {+ URLs []string `json:"urls"`+ Username string `json:"username"`+ Credential string `json:"credential"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&cred); err != nil {+ return nil, err+ }+ servers := []*pb.IceServer{{Urls: cred.URLs, Username: cred.Username, Credential: cred.Credential}}+ if len(stunAddrs) > 0 {+ var urls []string+ for _, a := range stunAddrs {+ urls = append(urls, "stun:"+a)+ }+ servers = append(servers, &pb.IceServer{Urls: urls})+ }+ return servers, nil+}++func receiveSignals(ctx context.Context, m *p2p.Manager, infra, id string) {+ client := &http.Client{Timeout: 30 * time.Second}+ for ctx.Err() == nil {+ resp, err := client.Get(infra + "/recv?id=" + url.QueryEscape(id))+ if err != nil {+ time.Sleep(200 * time.Millisecond)+ continue+ }+ body, _ := io.ReadAll(resp.Body)+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ continue+ }+ var msg pb.SignalMessage+ if err := proto.Unmarshal(body, &msg); err != nil {+ continue+ }+ if err := m.HandleSignal(ctx, resp.Header.Get("X-From"), &msg); err != nil &&+ !errors.Is(err, context.Canceled) {+ fmt.Fprintln(os.Stderr, "处理信令:", err)+ }+ }+}++func splitList(s string) []string {+ var out []string+ for _, v := range strings.Split(s, ",") {+ if v = strings.TrimSpace(v); v != "" {+ out = append(out, v)+ }+ }+ return out+}diff --git a/client-core/go.mod b/client-core/go.modindex 959514f..078e714 100644--- a/client-core/go.mod+++ b/client-core/go.mod@@ -11,7 +11,6 @@ require (github.com/ncruces/go-strftime v1.0.0 // indirectgithub.com/pion/datachannel v1.6.2 // indirectgithub.com/pion/dtls/v3 v3.1.8 // indirect- github.com/pion/ice/v4 v4.4.2 // indirectgithub.com/pion/interceptor v0.1.48 // indirectgithub.com/pion/logging v0.2.4 // indirectgithub.com/pion/mdns/v2 v2.2.0 // indirect@@ -22,7 +21,6 @@ require (github.com/pion/sdp/v3 v3.0.19 // indirectgithub.com/pion/srtp/v3 v3.0.13 // indirectgithub.com/pion/stun/v3 v3.0.1 // indirect- github.com/pion/stun/v4 v4.0.0 // indirectgithub.com/pion/transport/v3 v3.0.8 // indirectgithub.com/pion/transport/v4 v4.1.0 // indirectgithub.com/pion/turn/v4 v4.1.4 // indirect@@ -51,6 +49,8 @@ replace github.com/baiyuze/copysync/proto => ../protorequire (github.com/baiyuze/copysync/server v0.0.0github.com/klauspost/compress v1.20.0+ github.com/pion/ice/v4 v4.4.2+ github.com/pion/stun/v4 v4.0.0github.com/pion/webrtc/v4 v4.2.20golang.org/x/net v0.57.0)diff --git a/client-core/internal/config/config.go b/client-core/internal/config/config.goindex 6553bf6..fcb3fa5 100644--- a/client-core/internal/config/config.go+++ b/client-core/internal/config/config.go@@ -30,6 +30,11 @@ type Config struct {AutoApplyToClipboard bool `json:"auto_apply_to_clipboard"`LaunchAtLogin bool `json:"launch_at_login"`++ // OnlyOwnSTUN 只用自己的服务器探测网络出口。公共 STUN 服务器能看到本机的公网 IP+ // (与任何 WebRTC 应用一样,看不到内容),介意的用户可以关掉;代价是多出口网络里+ // 可能探测不全,直连机会变小。+ OnlyOwnSTUN bool `json:"only_own_stun"`}func Default() Config {diff --git a/client-core/internal/peers/manager.go b/client-core/internal/peers/manager.goindex eecf93b..35c5773 100644--- a/client-core/internal/peers/manager.go+++ b/client-core/internal/peers/manager.go@@ -79,6 +79,8 @@ type Options struct {// OnPeerMessage / OnPeerStream 是 P2P 数据面的入口,M4 的同步逻辑挂在这里OnPeerMessage func(deviceID string, msg *pb.PeerMessage)OnPeerStream func(deviceID, label string, stream *p2p.Stream)+ // StatePath 保存网络出口历史的文件,见 p2p/egress_history.go+ StatePath string}func NewManager(opts Options) (*Manager, error) {@@ -117,6 +119,14 @@ func NewManager(opts Options) (*Manager, error) {OnState: m.handleP2PState,OnMessage: opts.OnPeerMessage,OnStream: opts.OnPeerStream,+ StatePath: opts.StatePath,+ // 公共 STUN 服务器 IP 分散,能探测到更多出口;用户可以在设置里关掉+ ProbeServers: func() []string {+ if opts.LoadConfig().OnlyOwnSTUN {+ return nil+ }+ return p2p.DefaultProbeServers+ },})m.client = signaling.New(signaling.Options{diff --git a/client-core/internal/rpc/convert.go b/client-core/internal/rpc/convert.goindex 36f9268..243f661 100644--- a/client-core/internal/rpc/convert.go+++ b/client-core/internal/rpc/convert.go@@ -51,6 +51,7 @@ func configToProto(c config.Config) *pb.Config {LaunchAtLogin: c.LaunchAtLogin,DeviceName: c.DeviceName,SignalingUrl: c.SignalingURL,+ OnlyOwnStun: c.OnlyOwnSTUN,}}@@ -83,6 +84,7 @@ func configFromProto(in *pb.Config, base config.Config) config.Config {c.SyncFile = in.GetSyncFile()c.AutoApplyToClipboard = in.GetAutoApplyToClipboard()c.LaunchAtLogin = in.GetLaunchAtLogin()+ c.OnlyOwnSTUN = in.GetOnlyOwnStun()return c}diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.goindex 3a83ff6..f5e747a 100644--- a/client-core/internal/rpc/server.go+++ b/client-core/internal/rpc/server.go@@ -38,13 +38,15 @@ type Deps struct {ApplyToClipboard func(ctx context.Context, clipID string) errorPermission func() clipboard.PermissionOpenPermissionSettings func() error- Devices func() (self *pb.Device, peers []*pb.Device)- CreatePairingCode func(ctx context.Context) (code string, expiresAt time.Time, err error)- RedeemPairingCode func(ctx context.Context, code string) (*pb.Device, string, error)- ConfirmPairing func(ctx context.Context, session string, accept bool) error- Unpair func(ctx context.Context, deviceID string) error- SignalingConnected func() bool- CacheBytesUsed func() int64+ // Network 返回最近一轮网络出口探测的结果+ Network func() *pb.NetworkInfo+ Devices func() (self *pb.Device, peers []*pb.Device)+ CreatePairingCode func(ctx context.Context) (code string, expiresAt time.Time, err error)+ RedeemPairingCode func(ctx context.Context, code string) (*pb.Device, string, error)+ ConfirmPairing func(ctx context.Context, session string, accept bool) error+ Unpair func(ctx context.Context, deviceID string) error+ SignalingConnected func() bool+ CacheBytesUsed func() int64}type Server struct {@@ -265,6 +267,13 @@ func (s *Server) GetStatus(context.Context, *pb.Empty) (*pb.Status, error) {return st, nil}+func (s *Server) GetNetwork(context.Context, *pb.Empty) (*pb.NetworkInfo, error) {+ if s.deps.Network == nil {+ return nil, status.Error(codes.Unimplemented, "当前版本不支持网络诊断")+ }+ return s.deps.Network(), nil+}+func (s *Server) RequestClipboardPermission(context.Context, *pb.Empty) (*pb.Empty, error) {if s.deps.OpenPermissionSettings == nil {return nil, status.Error(codes.Unimplemented, "当前平台无需授权")diff --git a/client-core/internal/transport/p2p/egress.go b/client-core/internal/transport/p2p/egress.gonew file mode 100644index 0000000..c10836b--- /dev/null+++ b/client-core/internal/transport/p2p/egress.go@@ -0,0 +1,275 @@+package p2p++import (+ "context"+ "fmt"+ "hash/fnv"+ "net"+ "net/netip"+ "sort"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/pion/ice/v4"+ "github.com/pion/stun/v4"+)++// 出口探测:在打洞用的那一个本地端口上,向多台 STUN 服务器询问本机的公网地址。+//+// 有的网络不止一个出口——公司双线、运营商的 NAT 地址池——并且按目标地址选出口。+// 只问一台服务器,得到的只是「去往那台服务器」的出口地址;发往对端的包可能从另一个+// 出口出去,对端收到的源地址与告诉它的对不上,就会被它的路由器丢弃,打洞随之失败。+//+// 实测(见仓库提交记录):这类网络里出口只按目标 IP 选择,与目标端口无关;同一条+// 线路上同一个本地端口的公网映射是固定的。所以向 IP 足够分散的一组服务器探测,+// 就能拿到本机在每条线路上的地址,把它们都告诉对端,对端挨个打过来总有一个对得上。++// DefaultProbeServers 是内置的公共 STUN 服务器,按「IP 分散、国内可达」挑选。+// 信令服务器下发的 STUN 地址总会被一并探测;这一组只在用户允许时使用。+var DefaultProbeServers = []string{+ "stun.chat.bilibili.com:3478",+ "stun.cloudflare.com:3478",+ "global.stun.twilio.com:3478",+ "stun.nextcloud.com:3478",+ "stun.l.google.com:19302",+ "stun.freeswitch.org:3478",+}++const (+ probeTimeout = 1500 * time.Millisecond+ maxSrflxAdvertise = 8 // 发给对端的出口地址上限,太多只会拖慢连通性检查+ historyTTL = 7 * 24 * time.Hour+)++// Egress 是本机在某个出口上的公网地址。+type Egress struct {+ Addr netip.AddrPort+ // PortPreserved 表示这个出口不改端口(公网端口等于本地端口)。+ // 这样的出口即使某一轮没探测到,也能用「出口 IP + 本地端口」推算出来。+ PortPreserved bool+ // Via 是经由哪些探测服务器发现的;为空表示来自历史记录的推算。+ Via []string+}++// Guessed 表示这个地址是按历史记录推算的,而非本轮实测。+func (e Egress) Guessed() bool { return len(e.Via) == 0 }++// EgressReport 是一轮探测的结果。+type EgressReport struct {+ LocalPort int+ Egresses []Egress+ Probed int // 发出探测的服务器数(按 IP 去重后)+ Answered int // 有响应的服务器数+ At time.Time+}++// stunProber 由 ice.UniversalUDPMux 实现:在共享的那个端口上做一次 STUN 探测。+type stunProber interface {+ GetXORMappedAddr(stunAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error)+}++var _ stunProber = (*ice.UniversalUDPMuxDefault)(nil)++type probeOptions struct {+ // AllowPrivate 允许内网与回环地址的探测服务器,仅供测试与实验环境使用+ AllowPrivate bool+ Resolver *net.Resolver+}++// probeEgress 并发探测所有服务器,按公网地址归并结果。+func probeEgress(ctx context.Context, prober stunProber, localPort int, servers []string,+ opts probeOptions) EgressReport {+ targets := resolveProbeTargets(ctx, servers, opts)+ report := EgressReport{LocalPort: localPort, Probed: len(targets), At: time.Now()}++ type answer struct {+ name string+ addr netip.AddrPort+ }+ answers := make(chan answer, len(targets))+ var wg sync.WaitGroup+ for _, t := range targets {+ wg.Add(1)+ go func(t probeTarget) {+ defer wg.Done()+ mapped, err := prober.GetXORMappedAddr(net.UDPAddrFromAddrPort(t.addr), probeTimeout)+ if err != nil || mapped == nil {+ return+ }+ ip, ok := netip.AddrFromSlice(mapped.IP)+ if !ok {+ return+ }+ answers <- answer{name: t.name, addr: netip.AddrPortFrom(ip.Unmap(), uint16(mapped.Port))}+ }(t)+ }+ wg.Wait()+ close(answers)++ byAddr := map[netip.AddrPort]*Egress{}+ var order []netip.AddrPort+ for a := range answers {+ report.Answered+++ e, ok := byAddr[a.addr]+ if !ok {+ e = &Egress{Addr: a.addr, PortPreserved: int(a.addr.Port()) == localPort}+ byAddr[a.addr] = e+ order = append(order, a.addr)+ }+ e.Via = append(e.Via, a.name)+ }+ // 被越多服务器看到的出口越可能是常用出口,排在前面+ sort.SliceStable(order, func(i, j int) bool {+ return len(byAddr[order[i]].Via) > len(byAddr[order[j]].Via)+ })+ for _, a := range order {+ sort.Strings(byAddr[a].Via)+ report.Egresses = append(report.Egresses, *byAddr[a])+ }+ return report+}++type probeTarget struct {+ name string+ addr netip.AddrPort+}++// resolveProbeTargets 解析服务器地址,过滤掉不可能是公网 STUN 的地址,并按 IP 去重。+//+// 按 IP 去重是因为出口只按目标 IP 选择:同一 IP 的不同端口、同一 IP 的多个域名+// (Google 的 stun1–4 就是同一个 IP)只会落在同一个出口上,多探无益。+func resolveProbeTargets(ctx context.Context, servers []string, opts probeOptions) []probeTarget {+ resolver := opts.Resolver+ if resolver == nil {+ resolver = net.DefaultResolver+ }+ seen := map[netip.Addr]bool{}+ var out []probeTarget+ for _, s := range servers {+ host, port, err := parseProbeServer(s)+ if err != nil {+ continue+ }+ var ips []netip.Addr+ if ip, err := netip.ParseAddr(host); err == nil {+ ips = []netip.Addr{ip}+ } else {+ lctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ resolved, err := resolver.LookupNetIP(lctx, "ip4", host)+ cancel()+ if err != nil {+ continue+ }+ ips = resolved+ }+ for _, ip := range ips {+ ip = ip.Unmap()+ if !ip.Is4() || seen[ip] || !usableProbeIP(ip, opts.AllowPrivate) {+ continue+ }+ seen[ip] = true+ out = append(out, probeTarget{name: host, addr: netip.AddrPortFrom(ip, port)})+ break // 一个域名取一个可用 IP 就够了+ }+ }+ return out+}++// parseProbeServer 接受 "stun:host:port"、"stun:host"、"host:port" 等写法。+func parseProbeServer(s string) (string, uint16, error) {+ s = strings.TrimSpace(s)+ s = strings.TrimPrefix(strings.TrimPrefix(s, "stuns:"), "stun:")+ if i := strings.IndexByte(s, '?'); i >= 0 {+ s = s[:i]+ }+ if s == "" {+ return "", 0, fmt.Errorf("空地址")+ }+ host, portStr, err := net.SplitHostPort(s)+ if err != nil {+ return s, 3478, nil // 没写端口,用 STUN 默认端口+ }+ port, err := strconv.ParseUint(portStr, 10, 16)+ if err != nil || port == 0 {+ return "", 0, fmt.Errorf("端口无效: %q", portStr)+ }+ return host, uint16(port), nil+}++// 不可能是公网 STUN 服务器的地址段。DNS 污染与代理软件的 fake-ip 会把域名解析到这些地方,+// 向它们发探测只会超时,或者更糟——被当成一个出口。+var bogusPrefixes = mustPrefixes(+ "0.0.0.0/8", // 本网络+ "100.64.0.0/10", // 运营商 NAT 内部地址+ "192.0.0.0/24", // IETF 协议分配+ "192.0.2.0/24", // 文档示例(实测某些域名被污染到这里)+ "198.18.0.0/15", // 基准测试段,Clash 等代理的 fake-ip 默认用它+ "198.51.100.0/24", // 文档示例+ "203.0.113.0/24", // 文档示例+ "240.0.0.0/4", // 保留+)++func usableProbeIP(ip netip.Addr, allowPrivate bool) bool {+ if !ip.IsValid() || ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() {+ return false+ }+ if ip.IsLoopback() || ip.IsPrivate() {+ return allowPrivate+ }+ for _, p := range bogusPrefixes {+ if p.Contains(ip) {+ return false+ }+ }+ return true+}++func mustPrefixes(ss ...string) []netip.Prefix {+ out := make([]netip.Prefix, len(ss))+ for i, s := range ss {+ out[i] = netip.MustParsePrefix(s)+ }+ return out+}++// srflxCandidates 把探测结果转成发给对端的 srflx candidate 字符串。+//+// 实测到的地址排在前面、优先级更高;推算的地址垫底。数量有上限:每多一个地址,+// 对端就要多做一轮连通性检查。+func srflxCandidates(r EgressReport) []string {+ var out []string+ seen := map[netip.AddrPort]bool{}+ add := func(e Egress, localPref int) {+ if len(out) >= maxSrflxAdvertise || seen[e.Addr] {+ return+ }+ seen[e.Addr] = true+ // RFC 8445 5.1.2.1:priority = 2^24*type + 2^8*local + (256 - component)+ priority := (1<<24)*100 + (1<<8)*localPref + 255+ out = append(out, fmt.Sprintf("candidate:%d 1 udp %d %s %d typ srflx raddr 0.0.0.0 rport %d",+ candidateFoundation(e.Addr), priority, e.Addr.Addr(), e.Addr.Port(), r.LocalPort))+ }+ var measured, guessed []Egress+ for _, e := range r.Egresses {+ if e.Guessed() {+ guessed = append(guessed, e)+ } else {+ measured = append(measured, e)+ }+ }+ for i, e := range measured {+ add(e, 65535-i)+ }+ for i, e := range guessed {+ add(e, 32767-i)+ }+ return out+}++func candidateFoundation(a netip.AddrPort) uint32 {+ h := fnv.New32a()+ h.Write([]byte(a.String()))+ return h.Sum32()+}diff --git a/client-core/internal/transport/p2p/egress_history.go b/client-core/internal/transport/p2p/egress_history.gonew file mode 100644index 0000000..3a74b47--- /dev/null+++ b/client-core/internal/transport/p2p/egress_history.go@@ -0,0 +1,149 @@+package p2p++import (+ "encoding/json"+ "net"+ "net/netip"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"+)++// egressHistory 记住每个网络里见过的出口 IP,补上某一轮探测漏掉的线路。+//+// 探测服务器的 IP 恰好都没落到某条线路上时,这一轮就看不到它。若这条线路不改端口,+// 它在本端口上的公网地址就是「出口 IP + 本地端口」,可以直接推算出来发给对端。+// 会改端口的线路无法推算,不记。+type egressHistory struct {+ path string+ now func() time.Time++ mu sync.Mutex+ data historyFile+}++type historyFile struct {+ // 键是网络标识(见 localNetworkKey):换了网络,出口自然也不一样了+ Networks map[string][]historyEntry `json:"networks"`+}++type historyEntry struct {+ IP string `json:"ip"`+ PortPreserved bool `json:"port_preserved"`+ LastSeen time.Time `json:"last_seen"`+}++// loadEgressHistory 读取历史;path 为空时只保存在内存里。文件损坏就当没有历史。+func loadEgressHistory(path string) *egressHistory {+ h := &egressHistory{path: path, now: time.Now, data: historyFile{Networks: map[string][]historyEntry{}}}+ if path == "" {+ return h+ }+ if raw, err := os.ReadFile(path); err == nil {+ var f historyFile+ if json.Unmarshal(raw, &f) == nil && f.Networks != nil {+ h.data = f+ }+ }+ return h+}++// record 把一轮实测结果并入历史,并清掉过期的条目。+func (h *egressHistory) record(network string, r EgressReport) {+ h.mu.Lock()+ defer h.mu.Unlock()++ now := h.now()+ byIP := map[string]historyEntry{}+ for _, e := range h.data.Networks[network] {+ if now.Sub(e.LastSeen) < historyTTL {+ byIP[e.IP] = e+ }+ }+ for _, e := range r.Egresses {+ if e.Guessed() {+ continue // 推算出来的不能反过来当作见过的证据+ }+ ip := e.Addr.Addr().String()+ byIP[ip] = historyEntry{IP: ip, PortPreserved: e.PortPreserved, LastSeen: now}+ }++ entries := make([]historyEntry, 0, len(byIP))+ for _, e := range byIP {+ entries = append(entries, e)+ }+ sort.Slice(entries, func(i, j int) bool { return entries[i].IP < entries[j].IP })+ h.data.Networks[network] = entries+ h.saveLocked()+}++// augment 给本轮结果补上历史里见过、这一轮没探测到、并且不改端口的出口。+func (h *egressHistory) augment(network string, r EgressReport) EgressReport {+ h.mu.Lock()+ defer h.mu.Unlock()++ present := map[netip.Addr]bool{}+ for _, e := range r.Egresses {+ present[e.Addr.Addr()] = true+ }+ now := h.now()+ for _, e := range h.data.Networks[network] {+ ip, err := netip.ParseAddr(e.IP)+ if err != nil || !e.PortPreserved || present[ip] || now.Sub(e.LastSeen) >= historyTTL {+ continue+ }+ r.Egresses = append(r.Egresses, Egress{+ Addr: netip.AddrPortFrom(ip, uint16(r.LocalPort)),+ PortPreserved: true,+ })+ }+ return r+}++func (h *egressHistory) saveLocked() {+ if h.path == "" {+ return+ }+ raw, err := json.MarshalIndent(h.data, "", " ")+ if err != nil {+ return+ }+ // 先写临时文件再改名,避免进程中途退出留下半个文件+ tmp := h.path + ".tmp"+ if err := os.MkdirAll(filepath.Dir(h.path), 0o700); err != nil {+ return+ }+ if err := os.WriteFile(tmp, raw, 0o600); err != nil {+ return+ }+ _ = os.Rename(tmp, h.path)+}++// localNetworkKey 用本机各网卡的 IPv4 地址标识「当前所在的网络」。+// 换了 Wi-Fi、插拔网线,地址随之变化,历史与探测结果也就跟着换一套。+func localNetworkKey() string {+ ifaces, err := net.Interfaces()+ if err != nil {+ return ""+ }+ var addrs []string+ for _, ifc := range ifaces {+ if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {+ continue+ }+ list, err := ifc.Addrs()+ if err != nil {+ continue+ }+ for _, a := range list {+ if ipn, ok := a.(*net.IPNet); ok && ipn.IP.To4() != nil {+ addrs = append(addrs, ipn.IP.String())+ }+ }+ }+ sort.Strings(addrs)+ return strings.Join(addrs, ",")+}diff --git a/client-core/internal/transport/p2p/egress_integration_test.go b/client-core/internal/transport/p2p/egress_integration_test.gonew file mode 100644index 0000000..022f636--- /dev/null+++ b/client-core/internal/transport/p2p/egress_integration_test.go@@ -0,0 +1,98 @@+package p2p_test++import (+ "context"+ "fmt"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ turnrelay "github.com/baiyuze/copysync/server/relay"+)++// TestManagerAdvertisesProbedEgress 验证:管理器在共享端口上做出口探测,+// 把探测到的公网地址作为 srflx candidate 发给对端,连接在共享端口上照常建立。+//+// 本机回环没有 NAT,探测到的「公网地址」就是 127.0.0.1 加上共享端口,+// 这正好能核对两件事:探测确实发生在共享端口上,结果确实发给了对端。+func TestManagerAdvertisesProbedEgress(t *testing.T) {+ stunSrv, err := turnrelay.New(turnrelay.Options{+ PublicIP: "127.0.0.1", Port: 34782, Secret: "test-secret", CredentialTTL: time.Hour,+ })+ if err != nil {+ t.Skipf("无法启动 STUN 服务(端口可能被占用): %v", err)+ }+ defer stunSrv.Close()++ r := newRelay()+ var mu sync.Mutex+ var sentByAlice []string+ spy := func(from string) func(context.Context, string, *pb.SignalMessage) error {+ forward := r.send(from)+ return func(ctx context.Context, to string, msg *pb.SignalMessage) error {+ if c := msg.GetCandidate(); c != nil && from == "alice" {+ mu.Lock()+ sentByAlice = append(sentByAlice, c.GetCandidate())+ mu.Unlock()+ }+ return forward(ctx, to, msg)+ }+ }++ newProbingHarness := func(id string) *harness {+ h := &harness{id: id, states: make(chan p2p.ConnState, 16), messages: make(chan *pb.PeerMessage, 16)}+ h.manager = p2p.NewManager(p2p.ManagerOptions{+ SelfID: id,+ SendSignal: spy(id),+ ProbeAllowPrivate: true, // 探测服务器在回环地址上+ OnState: func(_ string, s p2p.ConnState) {+ select {+ case h.states <- s:+ default:+ }+ },+ })+ h.manager.SetICEServers([]*pb.IceServer{{Urls: []string{"stun:127.0.0.1:34782"}}})+ r.register(id, h.manager)+ t.Cleanup(h.manager.Close)+ return h+ }+ alice := newProbingHarness("alice")+ bob := newProbingHarness("bob")++ // 等首轮探测结束,核对结果+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) && len(alice.manager.Egress().Egresses) == 0 {+ time.Sleep(50 * time.Millisecond)+ }+ egress := alice.manager.Egress()+ if len(egress.Egresses) != 1 {+ t.Fatalf("探测结果 = %+v,期望恰好一个出口", egress)+ }+ e := egress.Egresses[0]+ if e.Addr.String() != fmt.Sprintf("127.0.0.1:%d", egress.LocalPort) || !e.PortPreserved {+ t.Fatalf("出口 = %v,期望 127.0.0.1:%d 且不改端口(回环没有 NAT)", e.Addr, egress.LocalPort)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("发起连接: %v", err)+ }+ waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ // 出口地址必须作为 srflx candidate 发给了对端+ want := fmt.Sprintf("127.0.0.1 %d typ srflx", egress.LocalPort)+ mu.Lock()+ defer mu.Unlock()+ for _, c := range sentByAlice {+ if strings.Contains(c, want) {+ return+ }+ }+ t.Errorf("alice 没有把出口地址发给对端;发出的 candidate:\n%s", strings.Join(sentByAlice, "\n"))+}diff --git a/client-core/internal/transport/p2p/egress_test.go b/client-core/internal/transport/p2p/egress_test.gonew file mode 100644index 0000000..de2429a--- /dev/null+++ b/client-core/internal/transport/p2p/egress_test.go@@ -0,0 +1,170 @@+package p2p++import (+ "context"+ "errors"+ "net"+ "net/netip"+ "path/filepath"+ "testing"+ "time"++ "github.com/pion/ice/v4"+ "github.com/pion/stun/v4"+)++// fakeProber 按服务器地址返回预设的公网映射,模拟「按目标 IP 选出口」的网络。+type fakeProber map[string]string // 服务器 ip:port -> 本机公网 ip:port++func (f fakeProber) GetXORMappedAddr(addr net.Addr, _ time.Duration) (*stun.XORMappedAddress, error) {+ mapped, ok := f[addr.String()]+ if !ok {+ return nil, errors.New("超时")+ }+ ap := netip.MustParseAddrPort(mapped)+ return &stun.XORMappedAddress{IP: ap.Addr().AsSlice(), Port: int(ap.Port())}, nil+}++func TestParseProbeServer(t *testing.T) {+ cases := []struct {+ in string+ host string+ 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.cloudflare.com:3478", "stun.cloudflare.com", 3478},+ {"stun:example.com", "example.com", 3478},+ {"stun:example.com:3478?transport=udp", "example.com", 3478},+ }+ for _, c := range cases {+ host, port, err := parseProbeServer(c.in)+ if err != nil || host != c.host || port != c.port {+ t.Errorf("parseProbeServer(%q) = %q, %d, %v;期望 %q, %d", c.in, host, port, err, c.host, c.port)+ }+ }+}++func TestUsableProbeIP(t *testing.T) {+ cases := []struct {+ ip string+ allowPrivate bool+ want bool+ }{+ {"106.12.83.160", 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 的默认网段+ {"100.64.1.1", false, false}, // 运营商 NAT 内部地址+ {"0.0.0.0", false, false},+ {"10.1.2.3", false, false},+ {"10.1.2.3", true, true}, // 实验环境允许内网+ {"127.0.0.1", false, false},+ {"127.0.0.1", true, true},+ }+ for _, c := range cases {+ if got := usableProbeIP(netip.MustParseAddr(c.ip), c.allowPrivate); got != c.want {+ t.Errorf("usableProbeIP(%s, allowPrivate=%v) = %v,期望 %v", c.ip, c.allowPrivate, got, c.want)+ }+ }+}++// 公司网络的情形:不同的服务器落在不同出口上,同一出口被多台服务器看到。+func TestProbeEgressMergesByMappedAddress(t *testing.T) {+ prober := fakeProber{+ "1.1.1.1:3478": "9.9.9.1:5000", // 出口 1,不改端口+ "2.2.2.2:3478": "9.9.9.2:6000", // 出口 2,改端口+ "3.3.3.3:3478": "9.9.9.2:6000", // 也走出口 2:同一线路上映射固定+ // 4.4.4.4 不响应+ }+ servers := []string{+ "stun:1.1.1.1:3478", "2.2.2.2:3478", "3.3.3.3:3478", "4.4.4.4:3478",+ "1.1.1.1:19302", // 与第一个同 IP:出口只按 IP 选,不该重复探测+ "192.0.2.42:3478", // 被污染的地址:直接丢弃+ }+ r := probeEgress(context.Background(), prober, 5000, servers, probeOptions{})++ if r.Probed != 4 || r.Answered != 3 {+ t.Fatalf("探测 %d 个、响应 %d 个,期望 4 与 3", r.Probed, r.Answered)+ }+ if len(r.Egresses) != 2 {+ t.Fatalf("出口数 = %d,期望 2:%+v", len(r.Egresses), r.Egresses)+ }+ // 被更多服务器看到的出口排在前面+ if e := r.Egresses[0]; e.Addr.String() != "9.9.9.2:6000" || len(e.Via) != 2 || e.PortPreserved {+ t.Errorf("第一个出口 = %+v,期望 9.9.9.2:6000、2 个来源、改端口", e)+ }+ if e := r.Egresses[1]; e.Addr.String() != "9.9.9.1:5000" || !e.PortPreserved {+ t.Errorf("第二个出口 = %+v,期望 9.9.9.1:5000、不改端口", e)+ }+}++func TestSrflxCandidatesAreValidAndOrdered(t *testing.T) {+ r := EgressReport{LocalPort: 5000}+ for i := 0; i < 10; i++ {+ r.Egresses = append(r.Egresses, Egress{+ Addr: netip.AddrPortFrom(netip.AddrFrom4([4]byte{9, 9, 9, byte(i + 1)}), 5000),+ Via: []string{"stun"},+ })+ }+ // 推算的地址排在实测之后;与实测重复的不再发+ r.Egresses = append([]Egress{{Addr: netip.MustParseAddrPort("8.8.8.8:5000"), PortPreserved: true}}, r.Egresses...)++ cands := srflxCandidates(r)+ if len(cands) != maxSrflxAdvertise {+ t.Fatalf("候选数 = %d,应截断到 %d", len(cands), maxSrflxAdvertise)+ }+ var last uint32 = 1<<32 - 1+ for i, s := range cands {+ c, err := ice.UnmarshalCandidate(s)+ if err != nil {+ t.Fatalf("pion 解析不了第 %d 个候选 %q: %v", i, s, err)+ }+ if c.Type() != ice.CandidateTypeServerReflexive {+ t.Errorf("第 %d 个候选类型 = %v,应为 srflx", i, c.Type())+ }+ if c.Priority() > last {+ t.Errorf("候选 %d 的优先级高于前一个:实测地址应排在前面", i)+ }+ last = c.Priority()+ if c.Address() == "8.8.8.8" {+ t.Errorf("推算的地址挤掉了实测地址:%q", s)+ }+ }+}++func TestHistoryFillsInMissedPreservedEgress(t *testing.T) {+ path := filepath.Join(t.TempDir(), "egress.json")+ now := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)++ h := loadEgressHistory(path)+ h.now = func() time.Time { return now }+ h.record("office", EgressReport{LocalPort: 5000, Egresses: []Egress{+ {Addr: netip.MustParseAddrPort("9.9.9.1:5000"), PortPreserved: true, Via: []string{"a"}},+ {Addr: netip.MustParseAddrPort("9.9.9.2:6000"), Via: []string{"b"}},+ }})++ // 重新加载:历史要能持久化+ h = loadEgressHistory(path)+ h.now = func() time.Time { return now.Add(time.Hour) }++ // 新一轮换了本地端口,且只探测到出口 2+ got := h.augment("office", EgressReport{LocalPort: 7000, Egresses: []Egress{+ {Addr: netip.MustParseAddrPort("9.9.9.2:6100"), Via: []string{"b"}},+ }})+ if len(got.Egresses) != 2 {+ t.Fatalf("出口数 = %d,期望补上不改端口的出口 1:%+v", len(got.Egresses), got.Egresses)+ }+ if g := got.Egresses[1]; g.Addr.String() != "9.9.9.1:7000" || !g.Guessed() {+ t.Errorf("补上的出口 = %+v,期望 9.9.9.1:7000(出口 IP + 新的本地端口)", g)+ }++ // 别的网络不受影响;过期的历史不再使用+ if other := h.augment("home", EgressReport{LocalPort: 7000}); len(other.Egresses) != 0 {+ t.Errorf("其他网络不该用这份历史:%+v", other.Egresses)+ }+ h.now = func() time.Time { return now.Add(historyTTL + time.Hour) }+ if stale := h.augment("office", EgressReport{LocalPort: 7000}); len(stale.Egresses) != 0 {+ t.Errorf("过期的历史不该再用:%+v", stale.Egresses)+ }+}diff --git a/client-core/internal/transport/p2p/manager.go b/client-core/internal/transport/p2p/manager.goindex 06ee9e3..64b6c50 100644--- a/client-core/internal/transport/p2p/manager.go+++ b/client-core/internal/transport/p2p/manager.go@@ -3,8 +3,13 @@ package p2pimport ("context""log/slog"+ "net"+ "slices"+ "strings""sync"+ "time"+ "github.com/pion/ice/v4""github.com/pion/webrtc/v4"pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"@@ -24,6 +29,22 @@ type Manager struct {peers map[string]*PeericeServers []webrtc.ICEServerforceRelay bool++ // 打洞共用的那一个本地 UDP 端口,所有连接都从它收发。+ // 只有共用一个端口,各台探测服务器问到的公网地址才对同一个端口成立(见 egress.go)。+ mux *ice.UniversalUDPMuxDefault+ localPort int+ probeOpts probeOptions+ probeServers func() []string+ history *egressHistory+ stop chan struct{}+ closeOnce sync.Once++ egressMu sync.Mutex+ egress EgressReport+ serverSTUN []string // 信令服务器下发的 STUN 地址,只用于出口探测+ probing chan struct{} // 非空表示正在探测,探测结束时关闭+ probeAgain bool // 探测期间又有新的触发,结束后再探一轮}type ManagerOptions struct {@@ -35,6 +56,16 @@ type ManagerOptions struct {OnStream func(deviceID, label string, stream *Stream)// ForceRelay 强制走 TURN 中转,用于验证中转链路ForceRelay bool++ // StatePath 保存出口历史的文件;为空则只记在内存里+ StatePath string+ // ProbeServers 返回额外用于出口探测的公共 STUN 服务器;用户关闭时返回空+ ProbeServers func() []string+ // ProbeAllowPrivate 允许内网与回环地址的探测服务器,仅供测试与 NAT 实验室使用+ ProbeAllowPrivate bool+ // DisableEgressProbe 退回 pion 默认的候选收集方式:每个 STUN 服务器各开一个端口,+ // 不做多出口探测。NAT 实验室用它复现旧版本的行为作对照+ DisableEgressProbe bool}func NewManager(opts ManagerOptions) *Manager {@@ -42,25 +73,64 @@ func NewManager(opts ManagerOptions) *Manager {if log == nil {log = slog.Default()}- return &Manager{- selfID: opts.SelfID,- log: log,- sendSignal: opts.SendSignal,- onState: opts.OnState,- onMessage: opts.OnMessage,- onStream: opts.OnStream,- peers: make(map[string]*Peer),- forceRelay: opts.ForceRelay,+ m := &Manager{+ selfID: opts.SelfID,+ log: log,+ sendSignal: opts.SendSignal,+ onState: opts.OnState,+ onMessage: opts.OnMessage,+ onStream: opts.OnStream,+ peers: make(map[string]*Peer),+ forceRelay: opts.ForceRelay,+ probeOpts: probeOptions{AllowPrivate: opts.ProbeAllowPrivate},+ probeServers: opts.ProbeServers,+ history: loadEgressHistory(opts.StatePath),+ stop: make(chan struct{}),+ }++ if opts.DisableEgressProbe {+ return m+ }+ conn, err := net.ListenUDP("udp4", &net.UDPAddr{})+ if err != nil {+ // 开不出共享端口就退回 pion 的默认做法:功能不受影响,只是多出口网络里难以直连+ log.Warn("无法打开打洞端口,退回默认的候选收集方式", "err", err)+ return m}+ m.mux = ice.NewUniversalUDPMuxDefault(ice.UniversalUDPMuxParams{UDPConn: conn})+ m.localPort = conn.LocalAddr().(*net.UDPAddr).Port++ go m.egressLoop()+ m.triggerProbe()+ return m}// SetICEServers 更新 STUN/TURN 配置。信令服务器在握手时下发,// TURN 凭证是短期的,需要定期刷新。+//+// STUN 地址不交给 pion:pion 每问一个 STUN 服务器都单独开一个端口,问到的地址+// 只对那个端口成立。改由本端在共享端口上探测(见 egress.go),TURN 照常交给 pion。func (m *Manager) SetICEServers(servers []*pb.IceServer) {converted := make([]webrtc.ICEServer, 0, len(servers))+ var stunURLs []stringfor _, s := range servers {+ urls := s.GetUrls()+ if m.mux != nil {+ var turnURLs []string+ for _, u := range urls {+ if strings.HasPrefix(u, "stun:") || strings.HasPrefix(u, "stuns:") {+ stunURLs = append(stunURLs, u)+ } else {+ turnURLs = append(turnURLs, u)+ }+ }+ if len(turnURLs) == 0 {+ continue+ }+ urls = turnURLs+ }converted = append(converted, webrtc.ICEServer{- URLs: s.GetUrls(),+ URLs: urls,Username: s.GetUsername(),Credential: s.GetCredential(),})@@ -70,7 +140,143 @@ func (m *Manager) SetICEServers(servers []*pb.IceServer) {m.iceServers = convertedm.mu.Unlock()- m.log.Debug("ICE 配置已更新", "servers", len(converted))+ m.egressMu.Lock()+ changed := !slices.Equal(m.serverSTUN, stunURLs)+ m.serverSTUN = stunURLs+ m.egressMu.Unlock()+ if changed {+ m.triggerProbe()+ }++ m.log.Debug("ICE 配置已更新", "servers", len(converted), "stun", len(stunURLs))+}++// Close 断开所有连接并释放打洞端口。+func (m *Manager) Close() {+ m.CloseAll()+ m.closeOnce.Do(func() {+ close(m.stop)+ if m.mux != nil {+ _ = m.mux.Close()+ }+ })+}++// Egress 返回最近一轮出口探测的结果(含按历史推算的出口),供诊断展示。+func (m *Manager) Egress() EgressReport {+ m.egressMu.Lock()+ defer m.egressMu.Unlock()+ return m.egress+}++// egressLoop 定期重新探测;本机所在网络变化时立即探测。+func (m *Manager) egressLoop() {+ periodic := time.NewTicker(5 * time.Minute)+ netCheck := time.NewTicker(15 * time.Second)+ defer periodic.Stop()+ defer netCheck.Stop()++ lastNet := localNetworkKey()+ for {+ select {+ case <-m.stop:+ return+ case <-periodic.C:+ m.triggerProbe()+ case <-netCheck.C:+ if k := localNetworkKey(); k != lastNet {+ lastNet = k+ m.log.Info("网络已变化,重新探测出口")+ m.triggerProbe()+ }+ }+ }+}++// triggerProbe 发起一轮出口探测。正在探测时只做标记,结束后再补一轮,+// 不会并发探测。+func (m *Manager) triggerProbe() {+ if m.mux == nil {+ return+ }+ m.egressMu.Lock()+ if m.probing != nil {+ m.probeAgain = true+ m.egressMu.Unlock()+ return+ }+ done := make(chan struct{})+ m.probing = done+ m.egressMu.Unlock()++ go m.runProbe(done)+}++func (m *Manager) runProbe(done chan struct{}) {+ for {+ m.egressMu.Lock()+ servers := slices.Clone(m.serverSTUN)+ m.egressMu.Unlock()+ if m.probeServers != nil {+ servers = append(servers, m.probeServers()...)+ }++ report := EgressReport{LocalPort: m.localPort, At: time.Now()}+ if len(servers) > 0 {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ report = probeEgress(ctx, m.mux, m.localPort, servers, m.probeOpts)+ cancel()+ }+ network := localNetworkKey()+ m.history.record(network, report)+ report = m.history.augment(network, report)++ var summary []string+ for _, e := range report.Egresses {+ s := e.Addr.String()+ switch {+ case e.Guessed():+ s += "(按历史推算)"+ case e.PortPreserved:+ s += "(不改端口)"+ }+ summary = append(summary, s)+ }+ if len(servers) > 0 {+ m.log.Info("出口探测完成", "本地端口", m.localPort, "出口", summary,+ "响应", report.Answered, "探测", report.Probed)+ }++ m.egressMu.Lock()+ m.egress = report+ if m.probeAgain {+ m.probeAgain = false+ m.egressMu.Unlock()+ continue+ }+ m.probing = nil+ m.egressMu.Unlock()+ close(done)+ return+ }+}++// advertisedCandidates 返回要额外发给对端的出口地址。+// 正在探测时最多等 3 秒,免得刚连上信令就用一份空的结果去握手。+func (m *Manager) advertisedCandidates() []string {+ if m.mux == nil {+ return nil+ }+ m.egressMu.Lock()+ wait := m.probing+ m.egressMu.Unlock()+ if wait != nil {+ select {+ case <-wait:+ case <-time.After(3 * time.Second):+ }+ }+ return srflxCandidates(m.Egress())}// Connect 与对端建立连接。双方都可以调用,不会因此产生 glare。@@ -182,16 +388,22 @@ func (m *Manager) peer(deviceID string) (*Peer, error) {m.mu.Unlock()return p, nil}- ice := m.iceServers+ iceServers := m.iceServersforceRelay := m.forceRelaym.mu.Unlock()+ var mux ice.UDPMux+ if m.mux != nil {+ mux = m.mux+ }p, err := NewPeer(PeerOptions{- DeviceID: deviceID,- SelfID: m.selfID,- Logger: m.log,- ICEServers: ice,- ForceRelay: forceRelay,+ DeviceID: deviceID,+ SelfID: m.selfID,+ Logger: m.log,+ ICEServers: iceServers,+ ForceRelay: forceRelay,+ UDPMux: mux,+ ExtraCandidates: m.advertisedCandidates,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 6e47fa4..d1706f3 100644--- a/client-core/internal/transport/p2p/peer.go+++ b/client-core/internal/transport/p2p/peer.go@@ -15,6 +15,7 @@ import ("sync""time"+ "github.com/pion/ice/v4""github.com/pion/webrtc/v4""google.golang.org/protobuf/proto"@@ -60,6 +61,8 @@ func (s ConnState) Proto() pb.ConnectionKind {const (controlChannelLabel = "control"connectTimeout = 30 * time.Second+ // relayAcceptanceWait 是中转路径最早可以被选中的时间,给直连留出打通的机会+ relayAcceptanceWait = 3 * time.Second)// Peer 管理与单个对端的 WebRTC 连接。@@ -73,6 +76,8 @@ type Peer struct {onMessage func(*pb.PeerMessage)// onStream 处理对端新开的数据流(大文件传输用)onStream func(label string, stream *Stream)+ // extraCands 返回出口探测得到的公网地址,见 sendExtraCandidates+ extraCands func() []stringapi *webrtc.APIconfig webrtc.Configuration@@ -110,10 +115,14 @@ type PeerOptions struct {// ForceRelay 强制只用 TURN 中转,不尝试直连。// 用于验证中转链路是否可用——正常运行时应保持关闭。ForceRelay bool- SendSignal func(ctx context.Context, msg *pb.SignalMessage) error- OnState func(ConnState)- OnMessage func(*pb.PeerMessage)- OnStream func(label string, stream *Stream)+ // UDPMux 是所有连接共用的打洞端口;为空则由 pion 为每个连接各开端口+ 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)}func NewPeer(opts PeerOptions) (*Peer, error) {@@ -128,10 +137,16 @@ func NewPeer(opts PeerOptions) (*Peer, error) {// 分片与背压(BufferedAmount / OnBufferedAmountLow)本来就要自己处理,// 统一走消息接口反而让两类通道的代码保持一致。settings := webrtc.SettingEngine{}+ if opts.UDPMux != nil {+ settings.SetICEUDPMux(opts.UDPMux)+ }config := webrtc.Configuration{ICEServers: opts.ICEServers}if opts.ForceRelay {config.ICETransportPolicy = webrtc.ICETransportPolicyRelay+ } else {+ // 中转路径握手快,若不加等待,往往在直连打通之前就被选中,之后再也不会换成直连+ settings.SetRelayAcceptanceMinWait(relayAcceptanceWait)}return &Peer{@@ -141,6 +156,7 @@ func NewPeer(opts PeerOptions) (*Peer, error) {onState: opts.OnState,onMessage: opts.OnMessage,onStream: opts.OnStream,+ extraCands: opts.ExtraCandidates,api: webrtc.NewAPI(webrtc.WithSettingEngine(settings)),config: config,// 用 device_id 字典序决定礼让方:双方规则一致且无需协商,@@ -226,12 +242,38 @@ func (p *Peer) Connect(ctx context.Context) error {p.setState(StateConnecting)p.armConnectTimeout()- return p.sendSignal(ctx, &pb.SignalMessage{+ if err := p.sendSignal(ctx, &pb.SignalMessage{Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{Sdp: offer.SDP,DtlsFingerprint: fingerprintFromSDP(offer.SDP),}},- })+ }); err != nil {+ return err+ }+ go p.sendExtraCandidates()+ return nil+}++// sendExtraCandidates 把出口探测得到的各个公网地址作为 srflx candidate 发给对端。+//+// pion 自己只会探测出一个公网地址;在多出口网络里,发往对端的包很可能从另一个出口+// 出去,那个地址对不上,打洞就失败了。把每个出口的地址都告诉对端,对端逐个检查连通性,+// 总有一个与实际出口吻合。必须在 offer/answer 之后发:对端设好远端描述前收到的+// candidate 会先缓存起来。+func (p *Peer) sendExtraCandidates() {+ if p.extraCands == nil {+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ for _, c := range p.extraCands() {+ if err := p.sendSignal(ctx, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Candidate{Candidate: &pb.IceCandidate{Candidate: c, SdpMid: "0"}},+ }); err != nil {+ p.log.Debug("发送出口地址失败", "err", err)+ return+ }+ }}// armConnectTimeout 在握手迟迟不完成时重置连接,让上层得以重试。@@ -321,12 +363,16 @@ func (p *Peer) handleOffer(ctx context.Context, offer *pb.SdpOffer) error {p.setState(StateConnecting)p.armConnectTimeout()- return p.sendSignal(ctx, &pb.SignalMessage{+ if err := p.sendSignal(ctx, &pb.SignalMessage{Payload: &pb.SignalMessage_Answer{Answer: &pb.SdpAnswer{Sdp: answer.SDP,DtlsFingerprint: fingerprintFromSDP(answer.SDP),}},- })+ }); err != nil {+ return err+ }+ go p.sendExtraCandidates()+ return nil}func (p *Peer) handleAnswer(answer *pb.SdpAnswer) error {diff --git a/client-core/internal/transport/p2p/peer_test.go b/client-core/internal/transport/p2p/peer_test.goindex e3d8cae..abc5209 100644--- a/client-core/internal/transport/p2p/peer_test.go+++ b/client-core/internal/transport/p2p/peer_test.go@@ -89,7 +89,7 @@ func newHarness(t *testing.T, id string, r *relay) *harness {// 本地回环测试不需要 STUN/TURN:host candidate 足以直连h.manager.SetICEServers(nil)r.register(id, h.manager)- t.Cleanup(h.manager.CloseAll)+ t.Cleanup(h.manager.Close)return h}diff --git a/client-core/internal/transport/p2p/relay_test.go b/client-core/internal/transport/p2p/relay_test.goindex ce12a6e..01812d3 100644--- a/client-core/internal/transport/p2p/relay_test.go+++ b/client-core/internal/transport/p2p/relay_test.go@@ -146,6 +146,6 @@ func newRelayHarness(t *testing.T, id string, r *relay, turnSrv *turnrelay.Serve}})r.register(id, h.manager)- t.Cleanup(h.manager.CloseAll)+ t.Cleanup(h.manager.Close)return h}diff --git a/docs/en/index.html b/docs/en/index.htmlindex 3dc6d2f..790d246 100644--- a/docs/en/index.html+++ b/docs/en/index.html@@ -40,7 +40,7 @@"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.0.2",+ "softwareVersion": "1.1.0","datePublished": "2026-10-08","inLanguage": "en","license": "https://opensource.org/licenses/MIT",@@ -74,6 +74,11 @@"name": "Can the CopySync server see what I copy?","acceptedAnswer": { "@type": "Answer", "text": "No. With a direct connection the data never touches the server. When relaying, the server only forwards DTLS-encrypted UDP packets. It keeps no accounts and stores no clipboard content." }},+ {+ "@type": "Question",+ "name": "Can CopySync connect directly on office networks with several uplinks?",+ "acceptedAnswer": { "@type": "Answer", "text": "Yes. CopySync probes several servers from one port to learn its address on every uplink and sends them all to the peer, which tries each one. Peers behind NATs that randomize ports still fall back to the relay." }+ },{"@type": "Question","name": "Do I need my own server to use CopySync?",@@ -134,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.0.2, free and open source. macOS 13 or later, Intel and Apple silicon.</span>+ <span class="note">Version 1.1.0, 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">@@ -298,6 +303,8 @@<dd>Common behind symmetric NAT and corporate firewalls. Traffic switches to the TURN relay on your server, still encrypted, and the device list shows "relay".</dd><dt>Public STUN servers unreachable</dt><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>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>@@ -362,11 +369,11 @@ sudo ./install.sh YOUR_PUBLIC_IP</code></pre><div class="table-scroll"><table class="specs"><tbody>- <tr><th scope="row">Version</th><td>1.0.2, released <time datetime="2026-10-08">October 8, 2026</time></td></tr>+ <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">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>- <tr><th scope="row">Transport</th><td>WebRTC data channels, direct first with TURN relay fallback; files streamed as tar + zstd</td></tr>+ <tr><th scope="row">Transport</th><td>WebRTC data channels, direct first with TURN relay fallback; every uplink probed on multi-uplink networks; files streamed as tar + zstd</td></tr><tr><th scope="row">Encryption and identity</th><td>End-to-end DTLS; Ed25519 device keys; every signaling message signed</td></tr><tr><th scope="row">Pairing</th><td>6-character code valid for 5 minutes, using an alphabet without look-alikes such as 0/O and 1/I; fingerprints compared by you</td></tr><tr><th scope="row">Auto-sync limit</th><td>50 MB by default, adjustable from 1 MB to 1 GB</td></tr>@@ -397,6 +404,12 @@ sudo ./install.sh YOUR_PUBLIC_IP</code></pre><p>No. With a direct connection the data never touches the server. When it relays, it forwards DTLS-encrypted packets. It keeps no accounts and stores no clipboard content. The code is open, so you can check.</p></div></details>+ <details>+ <summary>Does it connect directly on office networks with several uplinks?</summary>+ <div class="answer">+ <p>Yes. These networks pick an uplink per destination. CopySync probes several servers from one port to learn its address on every uplink and sends them all to the peer, which tries each one. A Mac behind a 4-uplink office network connects directly to a home connection in our tests. Peers behind NATs that randomize ports still fall back to the relay.</p>+ </div>+ </details><details><summary>Do I need my own server?</summary><div class="answer">diff --git a/docs/index.html b/docs/index.htmlindex 009f94a..ea2acc1 100644--- a/docs/index.html+++ b/docs/index.html@@ -40,7 +40,7 @@"description": "在两台 Mac 之间同步剪贴板与文件的开源工具。复制文本、图片、文件或文件夹后,另一台 Mac 可直接粘贴。设备间 WebRTC 直连、DTLS 端到端加密,打不通时经用户自建服务器的 TURN 中转。","applicationCategory": "UtilitiesApplication","operatingSystem": "macOS 13 及以上(Intel 与 Apple 芯片)",- "softwareVersion": "1.0.2",+ "softwareVersion": "1.1.0","datePublished": "2026-10-08","inLanguage": "zh-CN","license": "https://opensource.org/licenses/MIT",@@ -74,6 +74,11 @@"name": "CopySync 的服务器会看到我复制的内容吗?","acceptedAnswer": { "@type": "Answer", "text": "不会。直连时数据不经过服务器;需要中转时,服务器只转发 DTLS 加密后的 UDP 包。服务器不存账号,也不存任何复制内容。" }},+ {+ "@type": "Question",+ "name": "公司网络(双线、多出口)能用 CopySync 直连吗?",+ "acceptedAnswer": { "@type": "Answer", "text": "能。这类网络按目标地址选出口,CopySync 在同一个端口上向多台服务器探测,拿到每个出口的地址一并发给对端,对端逐个尝试。对端是端口随机分配的 NAT 时仍会经服务器中转。" }+ },{"@type": "Question","name": "使用 CopySync 必须自己准备服务器吗?",@@ -134,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.0.2,免费开源。macOS 13 及以上,Intel 与 Apple 芯片通用。</span>+ <span class="note">版本 1.1.0,免费开源。macOS 13 及以上,Intel 与 Apple 芯片通用。</span></div><div class="demo" role="img" aria-label="演示:在 MacBook Pro 上选中文件并按下 Command C,文件经直连传到 MacBook Air,在那里按下 Command V 粘贴出来">@@ -298,6 +303,8 @@<dd>常见于对称 NAT 和公司防火墙。自动改走你服务器上的 TURN 中转,内容依然加密,设备列表里显示「中转」。</dd><dt>公共 STUN 服务器连不上</dt><dd>国内访问公共 STUN 时通时断。服务器自带 STUN,客户端优先用它。</dd>+ <dt>公司网络有多个出口</dt>+ <dd>双线、运营商地址池这类网络按目标地址选出口,只探测一次只会知道其中一个出口的地址。CopySync 在同一个端口上向多台服务器探测,把每个出口的地址都发给对端,由它逐个尝试。</dd><dt>服务器断开</dt><dd>自动重连,间隔从 1 秒开始翻倍、最长 30 秒,并带随机抖动,避免一群设备同时重连。界面实时显示连接状态。</dd><dt>文件太大</dt>@@ -362,11 +369,11 @@ sudo ./install.sh 你的公网IP</code></pre><div class="table-scroll"><table class="specs"><tbody>- <tr><th scope="row">版本</th><td>1.0.2,<time datetime="2026-10-08">2026 年 10 月 8 日</time>发布</td></tr>+ <tr><th scope="row">版本</th><td>1.1.0,<time datetime="2026-10-08">2026 年 10 月 8 日</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>- <tr><th scope="row">传输</th><td>WebRTC 数据通道,直连优先,打不通时经 TURN 中转;文件以 tar + zstd 流式打包</td></tr>+ <tr><th scope="row">传输</th><td>WebRTC 数据通道,直连优先,打不通时经 TURN 中转;多出口网络逐个探测每个出口;文件以 tar + zstd 流式打包</td></tr><tr><th scope="row">加密与身份</th><td>DTLS 端到端加密;设备身份为 Ed25519 密钥;信令消息逐条签名</td></tr><tr><th scope="row">配对</th><td>6 位配对码,5 分钟内有效,字符集去掉了 0/O、1/I 等易混字符;配对时人工核对安全指纹</td></tr><tr><th scope="row">自动同步上限</th><td>默认 50 MB,可在 1 MB 到 1 GB 之间调整</td></tr>@@ -397,6 +404,12 @@ sudo ./install.sh 你的公网IP</code></pre><p>不会。直连时数据根本不经过服务器;需要中转时,服务器转发的是 DTLS 加密后的数据包。服务器不存账号,也不存任何复制内容。代码是开源的,可以自己核对。</p></div></details>+ <details>+ <summary>公司网络(双线、多出口)能直连吗?</summary>+ <div class="answer">+ <p>能。这类网络按目标地址选出口,CopySync 会在同一个端口上向多台服务器探测,拿到每个出口的地址一并发给对端,对端逐个尝试,总有一个对得上。实测公司 4 个出口与家用宽带之间可以直连。对端是端口随机分配的 NAT 时仍会走中转。</p>+ </div>+ </details><details><summary>必须自己准备服务器吗?</summary><div class="answer">diff --git a/docs/llms.txt b/docs/llms.txtindex c6286bc..3fd7da8 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -6,10 +6,11 @@Key facts:-- Current version: 1.0.2, released 2026-10-08.+- Current version: 1.1.0, released 2026-10-08.- 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`.- 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.diff --git a/proto/copysync/v1/daemon.proto b/proto/copysync/v1/daemon.protoindex c14d6ea..b5d15a4 100644--- a/proto/copysync/v1/daemon.proto+++ b/proto/copysync/v1/daemon.proto@@ -34,6 +34,9 @@ service DaemonService {rpc GetStatus(Empty) returns (Status);// 引导用户授予剪贴板权限(打开系统设置面板)rpc RequestClipboardPermission(Empty) returns (Empty);++ // 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 copysync-cli nat+ rpc GetNetwork(Empty) returns (NetworkInfo);}message Empty {}@@ -216,6 +219,26 @@ message Config {string device_name = 10;string signaling_url = 11;++ // 只用自己的服务器探测网络出口,不用公共 STUN 服务器。+ // 默认 false(即允许公共服务器):旧版界面不发这个字段时,不会被误关掉。+ bool only_own_stun = 12;+}++// 最近一轮网络出口探测的结果。+message NetworkInfo {+ int32 local_port = 1; // 打洞共用的本地 UDP 端口+ repeated NetworkEgress egresses = 2;+ int32 probed = 3; // 探测的服务器数(按 IP 去重后)+ int32 answered = 4; // 有响应的服务器数+ int64 probed_at_unix = 5;+}++message NetworkEgress {+ string address = 1; // 本机在这个出口上的公网 ip:port+ bool port_preserved = 2; // 这个出口不改端口+ bool guessed = 3; // 按历史推算,而非本轮实测+ repeated string via = 4; // 经由哪些探测服务器发现}message Status {diff --git a/proto/gen/copysync/v1/daemon.pb.go b/proto/gen/copysync/v1/daemon.pb.goindex 02f3703..57d8d7e 100644--- a/proto/gen/copysync/v1/daemon.pb.go+++ b/proto/gen/copysync/v1/daemon.pb.go@@ -1421,8 +1421,11 @@ type Config struct {LaunchAtLogin bool `protobuf:"varint,9,opt,name=launch_at_login,json=launchAtLogin,proto3" json:"launch_at_login,omitempty"`DeviceName string `protobuf:"bytes,10,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`SignalingUrl string `protobuf:"bytes,11,opt,name=signaling_url,json=signalingUrl,proto3" json:"signaling_url,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // 只用自己的服务器探测网络出口,不用公共 STUN 服务器。+ // 默认 false(即允许公共服务器):旧版界面不发这个字段时,不会被误关掉。+ OnlyOwnStun bool `protobuf:"varint,12,opt,name=only_own_stun,json=onlyOwnStun,proto3" json:"only_own_stun,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *Config) Reset() {@@ -1532,6 +1535,158 @@ func (x *Config) GetSignalingUrl() string {return ""}+func (x *Config) GetOnlyOwnStun() bool {+ if x != nil {+ return x.OnlyOwnStun+ }+ return false+}++// 最近一轮网络出口探测的结果。+type NetworkInfo struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ LocalPort int32 `protobuf:"varint,1,opt,name=local_port,json=localPort,proto3" json:"local_port,omitempty"` // 打洞共用的本地 UDP 端口+ Egresses []*NetworkEgress `protobuf:"bytes,2,rep,name=egresses,proto3" json:"egresses,omitempty"`+ Probed int32 `protobuf:"varint,3,opt,name=probed,proto3" json:"probed,omitempty"` // 探测的服务器数(按 IP 去重后)+ Answered int32 `protobuf:"varint,4,opt,name=answered,proto3" json:"answered,omitempty"` // 有响应的服务器数+ ProbedAtUnix int64 `protobuf:"varint,5,opt,name=probed_at_unix,json=probedAtUnix,proto3" json:"probed_at_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *NetworkInfo) Reset() {+ *x = NetworkInfo{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *NetworkInfo) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*NetworkInfo) ProtoMessage() {}++func (x *NetworkInfo) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use NetworkInfo.ProtoReflect.Descriptor instead.+func (*NetworkInfo) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{19}+}++func (x *NetworkInfo) GetLocalPort() int32 {+ if x != nil {+ return x.LocalPort+ }+ return 0+}++func (x *NetworkInfo) GetEgresses() []*NetworkEgress {+ if x != nil {+ return x.Egresses+ }+ return nil+}++func (x *NetworkInfo) GetProbed() int32 {+ if x != nil {+ return x.Probed+ }+ return 0+}++func (x *NetworkInfo) GetAnswered() int32 {+ if x != nil {+ return x.Answered+ }+ return 0+}++func (x *NetworkInfo) GetProbedAtUnix() int64 {+ if x != nil {+ return x.ProbedAtUnix+ }+ return 0+}++type NetworkEgress struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` // 本机在这个出口上的公网 ip:port+ PortPreserved bool `protobuf:"varint,2,opt,name=port_preserved,json=portPreserved,proto3" json:"port_preserved,omitempty"` // 这个出口不改端口+ Guessed bool `protobuf:"varint,3,opt,name=guessed,proto3" json:"guessed,omitempty"` // 按历史推算,而非本轮实测+ Via []string `protobuf:"bytes,4,rep,name=via,proto3" json:"via,omitempty"` // 经由哪些探测服务器发现+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *NetworkEgress) Reset() {+ *x = NetworkEgress{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[20]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *NetworkEgress) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*NetworkEgress) ProtoMessage() {}++func (x *NetworkEgress) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[20]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use NetworkEgress.ProtoReflect.Descriptor instead.+func (*NetworkEgress) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{20}+}++func (x *NetworkEgress) GetAddress() string {+ if x != nil {+ return x.Address+ }+ return ""+}++func (x *NetworkEgress) GetPortPreserved() bool {+ if x != nil {+ return x.PortPreserved+ }+ return false+}++func (x *NetworkEgress) GetGuessed() bool {+ if x != nil {+ return x.Guessed+ }+ return false+}++func (x *NetworkEgress) GetVia() []string {+ if x != nil {+ return x.Via+ }+ return nil+}+type Status struct {state protoimpl.MessageState `protogen:"open.v1"`DeviceId string `protobuf:"bytes,1,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`@@ -1547,7 +1702,7 @@ type Status struct {func (x *Status) Reset() {*x = Status{}- mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ mi := &file_copysync_v1_daemon_proto_msgTypes[21]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1559,7 +1714,7 @@ func (x *Status) String() string {func (*Status) ProtoMessage() {}func (x *Status) ProtoReflect() protoreflect.Message {- mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ mi := &file_copysync_v1_daemon_proto_msgTypes[21]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1572,7 +1727,7 @@ func (x *Status) ProtoReflect() protoreflect.Message {// Deprecated: Use Status.ProtoReflect.Descriptor instead.func (*Status) Descriptor() ([]byte, []int) {- return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{19}+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{21}}func (x *Status) GetDeviceId() string {@@ -1710,7 +1865,7 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +"\x0fpairing_session\x18\x01 \x01(\tR\x0epairingSession\x12\x16\n" +"\x06accept\x18\x02 \x01(\bR\x06accept\",\n" +"\rUnpairRequest\x12\x1b\n" +- "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\"\xba\x03\n" ++ "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\"\xde\x03\n" +"\x06Config\x129\n" +"\x19auto_sync_threshold_bytes\x18\x01 \x01(\x03R\x16autoSyncThresholdBytes\x12.\n" +"\x13history_ttl_seconds\x18\x02 \x01(\x03R\x11historyTtlSeconds\x12*\n" +@@ -1725,7 +1880,20 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +"\vdevice_name\x18\n" +" \x01(\tR\n" +"deviceName\x12#\n" +- "\rsignaling_url\x18\v \x01(\tR\fsignalingUrl\"\xb3\x02\n" ++ "\rsignaling_url\x18\v \x01(\tR\fsignalingUrl\x12\"\n" ++ "\ronly_own_stun\x18\f \x01(\bR\vonlyOwnStun\"\xbe\x01\n" ++ "\vNetworkInfo\x12\x1d\n" ++ "\n" ++ "local_port\x18\x01 \x01(\x05R\tlocalPort\x126\n" ++ "\begresses\x18\x02 \x03(\v2\x1a.copysync.v1.NetworkEgressR\begresses\x12\x16\n" ++ "\x06probed\x18\x03 \x01(\x05R\x06probed\x12\x1a\n" ++ "\banswered\x18\x04 \x01(\x05R\banswered\x12$\n" ++ "\x0eprobed_at_unix\x18\x05 \x01(\x03R\fprobedAtUnix\"|\n" ++ "\rNetworkEgress\x12\x18\n" ++ "\aaddress\x18\x01 \x01(\tR\aaddress\x12%\n" ++ "\x0eport_preserved\x18\x02 \x01(\bR\rportPreserved\x12\x18\n" ++ "\aguessed\x18\x03 \x01(\bR\aguessed\x12\x10\n" ++ "\x03via\x18\x04 \x03(\tR\x03via\"\xb3\x02\n" +"\x06Status\x12\x1b\n" +"\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x1f\n" +"\vdevice_name\x18\x02 \x01(\tR\n" +@@ -1760,7 +1928,7 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +"\x1cCLIPBOARD_PERMISSION_DEFAULT\x10\x02\x12\x1c\n" +"\x18CLIPBOARD_PERMISSION_ASK\x10\x03\x12%\n" +"!CLIPBOARD_PERMISSION_ALWAYS_ALLOW\x10\x04\x12$\n" +- " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x052\xdb\a\n" ++ " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x052\x97\b\n" +"\rDaemonService\x12@\n" +"\tSubscribe\x12\x1d.copysync.v1.SubscribeRequest\x1a\x12.copysync.v1.Event0\x01\x12P\n" +"\vListHistory\x12\x1f.copysync.v1.ListHistoryRequest\x1a .copysync.v1.ListHistoryResponse\x12F\n" +@@ -1775,7 +1943,9 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +"\tGetConfig\x12\x12.copysync.v1.Empty\x1a\x13.copysync.v1.Config\x128\n" +"\fUpdateConfig\x12\x13.copysync.v1.Config\x1a\x13.copysync.v1.Config\x124\n" +"\tGetStatus\x12\x12.copysync.v1.Empty\x1a\x13.copysync.v1.Status\x12D\n" +- "\x1aRequestClipboardPermission\x12\x12.copysync.v1.Empty\x1a\x12.copysync.v1.EmptyB>Z<github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1b\x06proto3"+ "\x1aRequestClipboardPermission\x12\x12.copysync.v1.Empty\x1a\x12.copysync.v1.Empty\x12:\n" ++ "\n" ++ "GetNetwork\x12\x12.copysync.v1.Empty\x1a\x18.copysync.v1.NetworkInfoB>Z<github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1b\x06proto3"var (file_copysync_v1_daemon_proto_rawDescOnce sync.Once@@ -1790,7 +1960,7 @@ func file_copysync_v1_daemon_proto_rawDescGZIP() []byte {}var file_copysync_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 4)-var file_copysync_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 20)+var file_copysync_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 22)var file_copysync_v1_daemon_proto_goTypes = []any{(ClipKind)(0), // 0: copysync.v1.ClipKind(ClipStatus)(0), // 1: copysync.v1.ClipStatus@@ -1815,7 +1985,9 @@ var file_copysync_v1_daemon_proto_goTypes = []any{(*ConfirmPairingRequest)(nil), // 20: copysync.v1.ConfirmPairingRequest(*UnpairRequest)(nil), // 21: copysync.v1.UnpairRequest(*Config)(nil), // 22: copysync.v1.Config- (*Status)(nil), // 23: copysync.v1.Status+ (*NetworkInfo)(nil), // 23: copysync.v1.NetworkInfo+ (*NetworkEgress)(nil), // 24: copysync.v1.NetworkEgress+ (*Status)(nil), // 25: copysync.v1.Status}var file_copysync_v1_daemon_proto_depIdxs = []int32{0, // 0: copysync.v1.ClipRecord.kind:type_name -> copysync.v1.ClipKind@@ -1827,46 +1999,49 @@ var file_copysync_v1_daemon_proto_depIdxs = []int32{8, // 6: copysync.v1.Event.progress:type_name -> copysync.v1.TransferProgress9, // 7: copysync.v1.Event.device_changed:type_name -> copysync.v1.Device3, // 8: copysync.v1.Event.permission_changed:type_name -> copysync.v1.ClipboardPermission- 23, // 9: copysync.v1.Event.status_changed:type_name -> copysync.v1.Status+ 25, // 9: copysync.v1.Event.status_changed:type_name -> copysync.v1.Status0, // 10: copysync.v1.ListHistoryRequest.kind_filter:type_name -> copysync.v1.ClipKind6, // 11: copysync.v1.ListHistoryResponse.records:type_name -> copysync.v1.ClipRecord9, // 12: copysync.v1.ListDevicesResponse.self:type_name -> copysync.v1.Device9, // 13: copysync.v1.ListDevicesResponse.peers:type_name -> copysync.v1.Device9, // 14: copysync.v1.RedeemPairingCodeResponse.peer:type_name -> copysync.v1.Device- 3, // 15: copysync.v1.Status.clipboard_permission:type_name -> copysync.v1.ClipboardPermission- 7, // 16: copysync.v1.DaemonService.Subscribe:input_type -> copysync.v1.SubscribeRequest- 11, // 17: copysync.v1.DaemonService.ListHistory:input_type -> copysync.v1.ListHistoryRequest- 13, // 18: copysync.v1.DaemonService.DeleteHistory:input_type -> copysync.v1.DeleteHistoryRequest- 14, // 19: copysync.v1.DaemonService.Fetch:input_type -> copysync.v1.FetchRequest- 15, // 20: copysync.v1.DaemonService.ApplyToClipboard:input_type -> copysync.v1.ApplyToClipboardRequest- 4, // 21: copysync.v1.DaemonService.ListDevices:input_type -> copysync.v1.Empty- 4, // 22: copysync.v1.DaemonService.CreatePairingCode:input_type -> copysync.v1.Empty- 18, // 23: copysync.v1.DaemonService.RedeemPairingCode:input_type -> copysync.v1.RedeemPairingCodeRequest- 20, // 24: copysync.v1.DaemonService.ConfirmPairing:input_type -> copysync.v1.ConfirmPairingRequest- 21, // 25: copysync.v1.DaemonService.Unpair:input_type -> copysync.v1.UnpairRequest- 4, // 26: copysync.v1.DaemonService.GetConfig:input_type -> copysync.v1.Empty- 22, // 27: copysync.v1.DaemonService.UpdateConfig:input_type -> copysync.v1.Config- 4, // 28: copysync.v1.DaemonService.GetStatus:input_type -> copysync.v1.Empty- 4, // 29: copysync.v1.DaemonService.RequestClipboardPermission:input_type -> copysync.v1.Empty- 10, // 30: copysync.v1.DaemonService.Subscribe:output_type -> copysync.v1.Event- 12, // 31: copysync.v1.DaemonService.ListHistory:output_type -> copysync.v1.ListHistoryResponse- 4, // 32: copysync.v1.DaemonService.DeleteHistory:output_type -> copysync.v1.Empty- 4, // 33: copysync.v1.DaemonService.Fetch:output_type -> copysync.v1.Empty- 4, // 34: copysync.v1.DaemonService.ApplyToClipboard:output_type -> copysync.v1.Empty- 16, // 35: copysync.v1.DaemonService.ListDevices:output_type -> copysync.v1.ListDevicesResponse- 17, // 36: copysync.v1.DaemonService.CreatePairingCode:output_type -> copysync.v1.CreatePairingCodeResponse- 19, // 37: copysync.v1.DaemonService.RedeemPairingCode:output_type -> copysync.v1.RedeemPairingCodeResponse- 4, // 38: copysync.v1.DaemonService.ConfirmPairing:output_type -> copysync.v1.Empty- 4, // 39: copysync.v1.DaemonService.Unpair:output_type -> copysync.v1.Empty- 22, // 40: copysync.v1.DaemonService.GetConfig:output_type -> copysync.v1.Config- 22, // 41: copysync.v1.DaemonService.UpdateConfig:output_type -> copysync.v1.Config- 23, // 42: copysync.v1.DaemonService.GetStatus:output_type -> copysync.v1.Status- 4, // 43: copysync.v1.DaemonService.RequestClipboardPermission:output_type -> copysync.v1.Empty- 30, // [30:44] is the sub-list for method output_type- 16, // [16:30] is the sub-list for method input_type- 16, // [16:16] is the sub-list for extension type_name- 16, // [16:16] is the sub-list for extension extendee- 0, // [0:16] is the sub-list for field type_name+ 24, // 15: copysync.v1.NetworkInfo.egresses:type_name -> copysync.v1.NetworkEgress+ 3, // 16: copysync.v1.Status.clipboard_permission:type_name -> copysync.v1.ClipboardPermission+ 7, // 17: copysync.v1.DaemonService.Subscribe:input_type -> copysync.v1.SubscribeRequest+ 11, // 18: copysync.v1.DaemonService.ListHistory:input_type -> copysync.v1.ListHistoryRequest+ 13, // 19: copysync.v1.DaemonService.DeleteHistory:input_type -> copysync.v1.DeleteHistoryRequest+ 14, // 20: copysync.v1.DaemonService.Fetch:input_type -> copysync.v1.FetchRequest+ 15, // 21: copysync.v1.DaemonService.ApplyToClipboard:input_type -> copysync.v1.ApplyToClipboardRequest+ 4, // 22: copysync.v1.DaemonService.ListDevices:input_type -> copysync.v1.Empty+ 4, // 23: copysync.v1.DaemonService.CreatePairingCode:input_type -> copysync.v1.Empty+ 18, // 24: copysync.v1.DaemonService.RedeemPairingCode:input_type -> copysync.v1.RedeemPairingCodeRequest+ 20, // 25: copysync.v1.DaemonService.ConfirmPairing:input_type -> copysync.v1.ConfirmPairingRequest+ 21, // 26: copysync.v1.DaemonService.Unpair:input_type -> copysync.v1.UnpairRequest+ 4, // 27: copysync.v1.DaemonService.GetConfig:input_type -> copysync.v1.Empty+ 22, // 28: copysync.v1.DaemonService.UpdateConfig:input_type -> copysync.v1.Config+ 4, // 29: copysync.v1.DaemonService.GetStatus:input_type -> copysync.v1.Empty+ 4, // 30: copysync.v1.DaemonService.RequestClipboardPermission:input_type -> copysync.v1.Empty+ 4, // 31: copysync.v1.DaemonService.GetNetwork:input_type -> copysync.v1.Empty+ 10, // 32: copysync.v1.DaemonService.Subscribe:output_type -> copysync.v1.Event+ 12, // 33: copysync.v1.DaemonService.ListHistory:output_type -> copysync.v1.ListHistoryResponse+ 4, // 34: copysync.v1.DaemonService.DeleteHistory:output_type -> copysync.v1.Empty+ 4, // 35: copysync.v1.DaemonService.Fetch:output_type -> copysync.v1.Empty+ 4, // 36: copysync.v1.DaemonService.ApplyToClipboard:output_type -> copysync.v1.Empty+ 16, // 37: copysync.v1.DaemonService.ListDevices:output_type -> copysync.v1.ListDevicesResponse+ 17, // 38: copysync.v1.DaemonService.CreatePairingCode:output_type -> copysync.v1.CreatePairingCodeResponse+ 19, // 39: copysync.v1.DaemonService.RedeemPairingCode:output_type -> copysync.v1.RedeemPairingCodeResponse+ 4, // 40: copysync.v1.DaemonService.ConfirmPairing:output_type -> copysync.v1.Empty+ 4, // 41: copysync.v1.DaemonService.Unpair:output_type -> copysync.v1.Empty+ 22, // 42: copysync.v1.DaemonService.GetConfig:output_type -> copysync.v1.Config+ 22, // 43: copysync.v1.DaemonService.UpdateConfig:output_type -> copysync.v1.Config+ 25, // 44: copysync.v1.DaemonService.GetStatus:output_type -> copysync.v1.Status+ 4, // 45: copysync.v1.DaemonService.RequestClipboardPermission:output_type -> copysync.v1.Empty+ 23, // 46: copysync.v1.DaemonService.GetNetwork:output_type -> copysync.v1.NetworkInfo+ 32, // [32:47] is the sub-list for method output_type+ 17, // [17:32] is the sub-list for method input_type+ 17, // [17:17] is the sub-list for extension type_name+ 17, // [17:17] is the sub-list for extension extendee+ 0, // [0:17] is the sub-list for field type_name}func init() { file_copysync_v1_daemon_proto_init() }@@ -1889,7 +2064,7 @@ func file_copysync_v1_daemon_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_copysync_v1_daemon_proto_rawDesc), len(file_copysync_v1_daemon_proto_rawDesc)),NumEnums: 4,- NumMessages: 20,+ NumMessages: 22,NumExtensions: 0,NumServices: 1,},diff --git a/proto/gen/copysync/v1/daemon_grpc.pb.go b/proto/gen/copysync/v1/daemon_grpc.pb.goindex 5bf8abe..d67521e 100644--- a/proto/gen/copysync/v1/daemon_grpc.pb.go+++ b/proto/gen/copysync/v1/daemon_grpc.pb.go@@ -38,6 +38,7 @@ const (DaemonService_UpdateConfig_FullMethodName = "/copysync.v1.DaemonService/UpdateConfig"DaemonService_GetStatus_FullMethodName = "/copysync.v1.DaemonService/GetStatus"DaemonService_RequestClipboardPermission_FullMethodName = "/copysync.v1.DaemonService/RequestClipboardPermission"+ DaemonService_GetNetwork_FullMethodName = "/copysync.v1.DaemonService/GetNetwork")// DaemonServiceClient is the client API for DaemonService service.@@ -63,6 +64,8 @@ type DaemonServiceClient interface {GetStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Status, error)// 引导用户授予剪贴板权限(打开系统设置面板)RequestClipboardPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error)+ // 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 copysync-cli nat+ GetNetwork(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NetworkInfo, error)}type daemonServiceClient struct {@@ -222,6 +225,16 @@ func (c *daemonServiceClient) RequestClipboardPermission(ctx context.Context, inreturn out, nil}+func (c *daemonServiceClient) GetNetwork(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NetworkInfo, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(NetworkInfo)+ err := c.cc.Invoke(ctx, DaemonService_GetNetwork_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// DaemonServiceServer is the server API for DaemonService service.// All implementations must embed UnimplementedDaemonServiceServer// for forward compatibility.@@ -245,6 +258,8 @@ type DaemonServiceServer interface {GetStatus(context.Context, *Empty) (*Status, error)// 引导用户授予剪贴板权限(打开系统设置面板)RequestClipboardPermission(context.Context, *Empty) (*Empty, error)+ // 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 copysync-cli nat+ GetNetwork(context.Context, *Empty) (*NetworkInfo, error)mustEmbedUnimplementedDaemonServiceServer()}@@ -297,6 +312,9 @@ func (UnimplementedDaemonServiceServer) GetStatus(context.Context, *Empty) (*Stafunc (UnimplementedDaemonServiceServer) RequestClipboardPermission(context.Context, *Empty) (*Empty, error) {return nil, status.Error(codes.Unimplemented, "method RequestClipboardPermission not implemented")}+func (UnimplementedDaemonServiceServer) GetNetwork(context.Context, *Empty) (*NetworkInfo, error) {+ return nil, status.Error(codes.Unimplemented, "method GetNetwork not implemented")+}func (UnimplementedDaemonServiceServer) mustEmbedUnimplementedDaemonServiceServer() {}func (UnimplementedDaemonServiceServer) testEmbeddedByValue() {}@@ -563,6 +581,24 @@ func _DaemonService_RequestClipboardPermission_Handler(srv interface{}, ctx contreturn interceptor(ctx, in, info, handler)}+func _DaemonService_GetNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).GetNetwork(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_GetNetwork_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).GetNetwork(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}+// DaemonService_ServiceDesc is the grpc.ServiceDesc for DaemonService service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -622,6 +658,10 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{MethodName: "RequestClipboardPermission",Handler: _DaemonService_RequestClipboardPermission_Handler,},+ {+ MethodName: "GetNetwork",+ Handler: _DaemonService_GetNetwork_Handler,+ },},Streams: []grpc.StreamDesc{{diff --git a/scripts/build.sh b/scripts/build.shindex 1492183..f5c3a1c 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -14,7 +14,7 @@ set -euo pipefailcd "$(dirname "$0")/.."DIST=dist-VERSION=${VERSION:-1.0.2}+VERSION=${VERSION:-1.1.0}rm -rf "$DIST" && mkdir -p "$DIST"# 构建 x86_64 + arm64 通用二进制:两台 Mac 的芯片未必相同,单架构的diff --git a/scripts/package.sh b/scripts/package.shindex b678161..454b30b 100755--- a/scripts/package.sh+++ b/scripts/package.sh@@ -15,7 +15,7 @@set -euo pipefailcd "$(dirname "$0")/.."-export VERSION=${VERSION:-1.0.2}+export VERSION=${VERSION:-1.1.0}OUT=release./scripts/build.shdiff --git a/server/relay/turn.go b/server/relay/turn.goindex c0d595a..94690e5 100644--- a/server/relay/turn.go+++ b/server/relay/turn.go@@ -20,18 +20,21 @@ import (// Server 封装 pion/turn,并按标准的 TURN REST API 方式签发短期凭证。type Server struct {- turn *turn.Server- secret []byte- publicIP string- port int- ttl time.Duration- log *slog.Logger+ turn *turn.Server+ secret []byte+ publicIP string+ port int+ ttl time.Duration+ log *slog.Logger}type Options struct {// PublicIP 是客户端能访问到的地址。NAT 后部署时必须显式指定,// 否则 TURN 会把内网地址写进 relay candidate,外部设备连不上。PublicIP string+ // ListenIP 是本机监听的地址,默认 0.0.0.0。服务器有多个 IP 时指定它,+ // 回包的源地址才会与客户端发往的地址一致——否则客户端的 NAT 会把回包当作陌生来源丢掉。+ ListenIP stringPort intRealm string// Secret 用于派生短期凭证。与签发方共享,不下发给客户端。@@ -48,6 +51,9 @@ func New(opts Options) (*Server, error) {if opts.Port == 0 {opts.Port = 3478}+ if opts.ListenIP == "" {+ opts.ListenIP = "0.0.0.0"+ }if opts.Realm == "" {opts.Realm = "copysync"}@@ -59,7 +65,7 @@ func New(opts Options) (*Server, error) {log = slog.Default()}- udpConn, err := net.ListenPacket("udp4", "0.0.0.0:"+strconv.Itoa(opts.Port))+ udpConn, err := net.ListenPacket("udp4", net.JoinHostPort(opts.ListenIP, strconv.Itoa(opts.Port)))if err != nil {return nil, fmt.Errorf("监听 TURN 端口 %d: %w", opts.Port, err)}@@ -88,7 +94,7 @@ func New(opts Options) (*Server, error) {PacketConn: udpConn,RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{RelayAddress: net.ParseIP(opts.PublicIP),- Address: "0.0.0.0",+ Address: opts.ListenIP,},}},})diff --git a/server/signal/server.go b/server/signal/server.goindex 4e26384..42faa64 100644--- a/server/signal/server.go+++ b/server/signal/server.go@@ -20,7 +20,7 @@ import (const (// 信令消息都很小(最大的是 SDP,通常几 KB)- maxMessageBytes = 256 << 10+ maxMessageBytes = 256 << 10handshakeTimeout = 15 * time.SecondwriteTimeout = 10 * time.Second// 心跳:及时发现半开连接,否则对端会一直显示"在线"diff --git a/tools/natlab/Dockerfile b/tools/natlab/Dockerfilenew file mode 100644index 0000000..19586b4--- /dev/null+++ b/tools/natlab/Dockerfile@@ -0,0 +1,7 @@+# NAT 打洞实验室的运行环境:只需要 bash、iproute2 与 iptables。+FROM alpine:3.20+ARG APK_MIRROR=""+RUN if [ -n "$APK_MIRROR" ]; then \+ sed -i "s#dl-cdn.alpinelinux.org#$APK_MIRROR#g" /etc/apk/repositories; \+ fi \+ && apk add --no-cache bash iproute2 iptablesdiff --git a/tools/natlab/docker.sh b/tools/natlab/docker.shnew file mode 100755index 0000000..8efd656--- /dev/null+++ b/tools/natlab/docker.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+# 在 macOS 上运行 NAT 打洞实验室:编译 Linux 版的 natlab,在特权容器里执行 run.sh。+#+# ./tools/natlab/docker.sh+#+# 国内网络拉取 Alpine 软件包慢的话:APK_MIRROR=mirrors.aliyun.com ./tools/natlab/docker.sh++set -euo pipefail+cd "$(dirname "$0")/../.."++OUT=$(mktemp -d)+trap 'rm -rf "$OUT"' EXIT+ARCH=$(docker version --format '{{.Server.Arch}}')++echo "▶ 编译 natlab(linux/$ARCH)"+(cd client-core && CGO_ENABLED=0 GOOS=linux GOARCH=$ARCH go build -o "$OUT/natlab" ./cmd/natlab)++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" \+ copysync-natlab bash /scripts/run.sh /lab/natlabdiff --git a/tools/natlab/run.sh b/tools/natlab/run.shnew file mode 100755index 0000000..f5dc285--- /dev/null+++ b/tools/natlab/run.sh@@ -0,0 +1,189 @@+#!/usr/bin/env bash+# NAT 打洞实验室:用 Linux 网络命名空间与 iptables 搭出真实的网络拓扑,+# 验证两台设备最终走直连还是中转。+#+# sudo ./tools/natlab/run.sh <natlab 可执行文件>+#+# 需要 root、iproute2、iptables。macOS 上用 tools/natlab/docker.sh,它会在容器里跑本脚本。+#+# 拓扑(全部用内网地址扮演公网,natlab 以 ProbeAllowPrivate 运行):+#+# [a] 192.168.10.2 ── [rA] 出口 10.255.0.11–14 ──┐+# [inet] 信令 10.200.0.2 TURN 10.200.0.3+# [b] 192.168.20.2 ── [rB] 出口 10.254.0.21–22 ──┘ STUN 10.200.1.1–4+#+# 10.200.1.1 扮演自己的服务器(信令服务器下发的 STUN),10.200.1.2–4 扮演公共 STUN。+# rA 按目标地址选出口,模拟公司双线、运营商地址池;入站只放行有连接记录的包,+# 与真实路由器一样「只认打过招呼的地址」。++set -euo pipefail++BIN=$(cd "$(dirname "${1:?用法: run.sh <natlab 可执行文件>}")" && pwd)/$(basename "$1")+WORK=$(mktemp -d)+PROBE="10.200.1.2:3478,10.200.1.3:3478,10.200.1.4:3478"++ns() { ip netns exec "$@"; }++INFRA_PID=""++# 按进程号结束 infra:用 pkill -f 按路径匹配会连本脚本自己一起杀掉(命令行里也有这个路径)+cleanup() {+ if [[ -n $INFRA_PID ]]; then+ kill "$INFRA_PID" 2>/dev/null || true+ wait "$INFRA_PID" 2>/dev/null || true+ INFRA_PID=""+ fi+ for n in inet rA a rB b; do ip netns del "$n" 2>/dev/null || true; done+}+trap 'cleanup; rm -rf "$WORK"' EXIT++veth() { # <命名空间1> <网卡1> <命名空间2> <网卡2>+ ip link add "$2" netns "$1" type veth peer name "$4" netns "$3"+}++# setup <A 侧出口模式> <B 侧模式>+# A:single 单出口 | dual 两个出口,去对端走出口 2、探测服务器有一台走出口 2+# hidden 两个出口,但没有任何探测服务器走出口 2 | quad 四个出口+# B:cone 家用路由器 | symmetric 端口随机分配 | dual 两个出口+setup() {+ cleanup+ for n in inet rA a rB b; do+ ip netns add "$n"+ ns "$n" ip link set lo up+ done+ veth inet i-a rA wan+ veth inet i-b rB wan+ veth rA lan a eth0+ veth rB lan b eth0++ ns inet ip addr add 10.255.0.1/24 dev i-a+ ns inet ip addr add 10.254.0.1/24 dev i-b+ for ip in 10.200.0.2 10.200.0.3 10.200.1.1 10.200.1.2 10.200.1.3 10.200.1.4; do+ ns inet ip addr add "$ip/32" dev lo+ done+ ns inet ip link set i-a up+ ns inet ip link set i-b up+ ns inet sysctl -qw net.ipv4.ip_forward=1++ for i in 1 2 3 4; do ns rA ip addr add "10.255.0.1$i/24" dev wan; done+ ns rA ip addr add 192.168.10.1/24 dev lan+ ns rA ip link set wan up+ ns rA ip link set lan up+ ns rA ip route add default via 10.255.0.1+ ns rA sysctl -qw net.ipv4.ip_forward=1+ ns a ip addr add 192.168.10.2/24 dev eth0+ ns a ip link set eth0 up+ ns a ip route add default via 192.168.10.1++ for i in 1 2; do ns rB ip addr add "10.254.0.2$i/24" dev wan; done+ ns rB ip addr add 192.168.20.1/24 dev lan+ ns rB ip link set wan up+ ns rB ip link set lan up+ ns rB ip route add default via 10.254.0.1+ ns rB sysctl -qw net.ipv4.ip_forward=1+ ns b ip addr add 192.168.20.2/24 dev eth0+ ns b ip link set eth0 up+ ns b ip route add default via 192.168.20.1++ # 路由器的防火墙:丢弃外网主动发来的新连接,与真实的家用、公司路由器一致。+ # 不能省:被丢弃的包不会留下连接记录。若放行到路由器本机,Linux 会为它建一条+ # 「未应答」的连接记录,随后本端往外发时源端口与之冲突,SNAT 只好换一个端口,+ # 事先告诉对端的地址就失效了——真实路由器不会这样。+ for r in rA rB; do+ ns "$r" iptables -A INPUT -i wan -m conntrack --ctstate NEW -j DROP+ ns "$r" iptables -A FORWARD -i wan -m conntrack --ctstate NEW -j DROP+ done++ local snat="iptables -t nat -A POSTROUTING -o wan"+ case $1 in+ single) ns rA $snat -j SNAT --to-source 10.255.0.11 ;;+ dual)+ ns rA $snat -d 10.254.0.0/24 -j SNAT --to-source 10.255.0.12+ ns rA $snat -d 10.200.1.2 -j SNAT --to-source 10.255.0.12+ ns rA $snat -j SNAT --to-source 10.255.0.11+ ;;+ hidden)+ ns rA $snat -d 10.254.0.0/24 -j SNAT --to-source 10.255.0.12+ ns rA $snat -j SNAT --to-source 10.255.0.11+ ;;+ quad)+ ns rA $snat -d 10.254.0.0/24 -j SNAT --to-source 10.255.0.14+ for i in 2 3 4; do ns rA $snat -d "10.200.1.$i" -j SNAT --to-source "10.255.0.1$i"; done+ ns rA $snat -j SNAT --to-source 10.255.0.11+ ;;+ esac+ case $2 in+ cone) ns rB $snat -j SNAT --to-source 10.254.0.21 ;;+ symmetric) ns rB $snat -j SNAT --to-source 10.254.0.21 --random-fully ;;+ dual)+ ns rB $snat -d 10.255.0.0/24 -j SNAT --to-source 10.254.0.22+ ns rB $snat -d 10.200.1.3 -j SNAT --to-source 10.254.0.22+ ns rB $snat -j SNAT --to-source 10.254.0.21+ ;;+ esac++ ns inet "$BIN" infra -http 10.200.0.2:9000 -turn 10.200.0.3 \+ -stun 10.200.1.1,10.200.1.2,10.200.1.3,10.200.1.4 >"$WORK/infra.log" 2>&1 &+ INFRA_PID=$!+ for _ in $(seq 50); do+ ns a bash -c 'exec 3<>/dev/tcp/10.200.0.2/9000' 2>/dev/null && return+ sleep 0.1+ done+ echo "infra 没有起来:" && cat "$WORK/infra.log" && exit 1+}++PASS=0+FAIL=0++# check <场景名> <A 侧> <B 侧> <direct|relay> [legacy|history]+check() {+ # NATLAB_ONLY 只跑名字里含这段文字的场景,排查问题时用+ [[ -n ${NATLAB_ONLY:-} && $1 != *"$NATLAB_ONLY"* ]] && return+ local name=$1 expect=$4 flag=${5:-} aflags=() state="$WORK/a-state.json"+ rm -f "$state" # 每个场景从空白开始:上一个场景的出口历史会让这一个「意外」直连+ setup "$2" "$3"+ case $flag in+ legacy) aflags=(-legacy) ;;+ history)+ # 预置一份历史:这个网络里见过不改端口的出口 2+ 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"+ ;;+ esac+ local 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" &+ local bpid=$!+ ns a "$BIN" peer -id a -peer b "${common[@]}" -probe "$PROBE" -state "$state" "${aflags[@]}" \+ >"$WORK/a.json" 2>"$WORK/a.log" || true+ wait "$bpid" || true++ local a b+ a=$(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+ PASS=$((PASS + 1))+ printf ' ✓ %-34s %s\n' "$name" "$a"+ else+ FAIL=$((FAIL + 1))+ 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/^/ /'+ # NATLAB_KEEP 指定目录时把完整日志留下来+ [[ -n ${NATLAB_KEEP:-} ]] && cp "$WORK"/*.log "$NATLAB_KEEP/" 2>/dev/null || true+ fi+}++echo "NAT 打洞实验室"+check "单出口 ↔ 家用路由器" single cone direct+check "两个出口(旧版本,对照)" dual cone relay legacy+check "两个出口 ↔ 家用路由器" dual cone direct+check "四个出口 ↔ 家用路由器" quad cone direct+check "两个出口,第二条没探测到,无历史" hidden cone relay+check "两个出口,第二条没探测到,有历史" hidden cone direct history+check "两个出口 ↔ 两个出口" dual dual direct+check "两个出口 ↔ 端口随机分配的 NAT" dual symmetric relay++echo+echo "通过 $PASS,失败 $FAIL"+[[ $FAIL -eq 0 ]]diff --git a/ui/lib/gen/copysync/v1/daemon.pb.dart b/ui/lib/gen/copysync/v1/daemon.pb.dartindex 0e0395e..e1328ae 100644--- a/ui/lib/gen/copysync/v1/daemon.pb.dart+++ b/ui/lib/gen/copysync/v1/daemon.pb.dart@@ -1546,6 +1546,7 @@ class Config extends $pb.GeneratedMessage {$core.bool? launchAtLogin,$core.String? deviceName,$core.String? signalingUrl,+ $core.bool? onlyOwnStun,}) {final result = Config._();if (autoSyncThresholdBytes != null)@@ -1561,6 +1562,7 @@ class Config extends $pb.GeneratedMessage {if (launchAtLogin != null) result.launchAtLogin = launchAtLogin;if (deviceName != null) result.deviceName = deviceName;if (signalingUrl != null) result.signalingUrl = signalingUrl;+ if (onlyOwnStun != null) result.onlyOwnStun = onlyOwnStun;return result;}@@ -1588,6 +1590,7 @@ class Config extends $pb.GeneratedMessage {..aOB(9, _omitFieldNames ? '' : 'launchAtLogin')..aOS(10, _omitFieldNames ? '' : 'deviceName')..aOS(11, _omitFieldNames ? '' : 'signalingUrl')+ ..aOB(12, _omitFieldNames ? '' : 'onlyOwnStun')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -1710,6 +1713,205 @@ class Config extends $pb.GeneratedMessage {$core.bool hasSignalingUrl() => $_has(10);@$pb.TagNumber(11)void clearSignalingUrl() => $_clearField(11);++ /// 只用自己的服务器探测网络出口,不用公共 STUN 服务器。+ /// 默认 false(即允许公共服务器):旧版界面不发这个字段时,不会被误关掉。+ @$pb.TagNumber(12)+ $core.bool get onlyOwnStun => $_getBF(11);+ @$pb.TagNumber(12)+ set onlyOwnStun($core.bool value) => $_setBool(11, value);+ @$pb.TagNumber(12)+ $core.bool hasOnlyOwnStun() => $_has(11);+ @$pb.TagNumber(12)+ void clearOnlyOwnStun() => $_clearField(12);+}++/// 最近一轮网络出口探测的结果。+class NetworkInfo extends $pb.GeneratedMessage {+ factory NetworkInfo({+ $core.int? localPort,+ $core.Iterable<NetworkEgress>? egresses,+ $core.int? probed,+ $core.int? answered,+ $fixnum.Int64? probedAtUnix,+ }) {+ final result = NetworkInfo._();+ if (localPort != null) result.localPort = localPort;+ if (egresses != null) result.egresses.addAll(egresses);+ if (probed != null) result.probed = probed;+ if (answered != null) result.answered = answered;+ if (probedAtUnix != null) result.probedAtUnix = probedAtUnix;+ return result;+ }++ NetworkInfo._();++ factory NetworkInfo.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NetworkInfo()..mergeFromBuffer(data, registry);+ factory NetworkInfo.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NetworkInfo()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'NetworkInfo',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: NetworkInfo.$_createMessage)+ ..aI(1, _omitFieldNames ? '' : 'localPort')+ ..pPM<NetworkEgress>(2, _omitFieldNames ? '' : 'egresses',+ subBuilder: NetworkEgress.$_createMessage)+ ..aI(3, _omitFieldNames ? '' : 'probed')+ ..aI(4, _omitFieldNames ? '' : 'answered')+ ..aInt64(5, _omitFieldNames ? '' : 'probedAtUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NetworkInfo clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NetworkInfo copyWith(void Function(NetworkInfo) updates) =>+ super.copyWith((message) => updates(message as NetworkInfo))+ as NetworkInfo;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use NetworkInfo() / NetworkInfo.new instead')+ static NetworkInfo create() => NetworkInfo._();+ static $pb.GeneratedMessage $_createMessage() => NetworkInfo._();+ @$core.override+ NetworkInfo createEmptyInstance() => NetworkInfo._();+ @$core.pragma('dart2js:noInline')+ static NetworkInfo getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<NetworkInfo>(+ NetworkInfo.$_createMessage);+ static NetworkInfo? _defaultInstance;++ @$pb.TagNumber(1)+ $core.int get localPort => $_getIZ(0);+ @$pb.TagNumber(1)+ set localPort($core.int value) => $_setSignedInt32(0, value);+ @$pb.TagNumber(1)+ $core.bool hasLocalPort() => $_has(0);+ @$pb.TagNumber(1)+ void clearLocalPort() => $_clearField(1);++ @$pb.TagNumber(2)+ $pb.PbList<NetworkEgress> get egresses => $_getList(1);++ @$pb.TagNumber(3)+ $core.int get probed => $_getIZ(2);+ @$pb.TagNumber(3)+ set probed($core.int value) => $_setSignedInt32(2, value);+ @$pb.TagNumber(3)+ $core.bool hasProbed() => $_has(2);+ @$pb.TagNumber(3)+ void clearProbed() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.int get answered => $_getIZ(3);+ @$pb.TagNumber(4)+ set answered($core.int value) => $_setSignedInt32(3, value);+ @$pb.TagNumber(4)+ $core.bool hasAnswered() => $_has(3);+ @$pb.TagNumber(4)+ void clearAnswered() => $_clearField(4);++ @$pb.TagNumber(5)+ $fixnum.Int64 get probedAtUnix => $_getI64(4);+ @$pb.TagNumber(5)+ set probedAtUnix($fixnum.Int64 value) => $_setInt64(4, value);+ @$pb.TagNumber(5)+ $core.bool hasProbedAtUnix() => $_has(4);+ @$pb.TagNumber(5)+ void clearProbedAtUnix() => $_clearField(5);+}++class NetworkEgress extends $pb.GeneratedMessage {+ factory NetworkEgress({+ $core.String? address,+ $core.bool? portPreserved,+ $core.bool? guessed,+ $core.Iterable<$core.String>? via,+ }) {+ final result = NetworkEgress._();+ if (address != null) result.address = address;+ if (portPreserved != null) result.portPreserved = portPreserved;+ if (guessed != null) result.guessed = guessed;+ if (via != null) result.via.addAll(via);+ return result;+ }++ NetworkEgress._();++ factory NetworkEgress.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NetworkEgress()..mergeFromBuffer(data, registry);+ factory NetworkEgress.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NetworkEgress()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'NetworkEgress',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: NetworkEgress.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'address')+ ..aOB(2, _omitFieldNames ? '' : 'portPreserved')+ ..aOB(3, _omitFieldNames ? '' : 'guessed')+ ..pPS(4, _omitFieldNames ? '' : 'via')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NetworkEgress clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NetworkEgress copyWith(void Function(NetworkEgress) updates) =>+ super.copyWith((message) => updates(message as NetworkEgress))+ as NetworkEgress;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use NetworkEgress() / NetworkEgress.new instead')+ static NetworkEgress create() => NetworkEgress._();+ static $pb.GeneratedMessage $_createMessage() => NetworkEgress._();+ @$core.override+ NetworkEgress createEmptyInstance() => NetworkEgress._();+ @$core.pragma('dart2js:noInline')+ static NetworkEgress getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<NetworkEgress>(+ NetworkEgress.$_createMessage);+ static NetworkEgress? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get address => $_getSZ(0);+ @$pb.TagNumber(1)+ set address($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasAddress() => $_has(0);+ @$pb.TagNumber(1)+ void clearAddress() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.bool get portPreserved => $_getBF(1);+ @$pb.TagNumber(2)+ set portPreserved($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasPortPreserved() => $_has(1);+ @$pb.TagNumber(2)+ void clearPortPreserved() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.bool get guessed => $_getBF(2);+ @$pb.TagNumber(3)+ set guessed($core.bool value) => $_setBool(2, value);+ @$pb.TagNumber(3)+ $core.bool hasGuessed() => $_has(2);+ @$pb.TagNumber(3)+ void clearGuessed() => $_clearField(3);++ @$pb.TagNumber(4)+ $pb.PbList<$core.String> get via => $_getList(3);}class Status extends $pb.GeneratedMessage {diff --git a/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dartindex 50cce05..b9ae589 100644--- a/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart+++ b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart@@ -138,6 +138,14 @@ class DaemonServiceClient extends $grpc.Client {options: options);}+ /// 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 copysync-cli nat+ $grpc.ResponseFuture<$0.NetworkInfo> getNetwork(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$getNetwork, request, options: options);+ }+// method descriptorsstatic final _$subscribe = $grpc.ClientMethod<$0.SubscribeRequest, $0.Event>(@@ -204,6 +212,10 @@ class DaemonServiceClient extends $grpc.Client {'/copysync.v1.DaemonService/RequestClipboardPermission',($0.Empty value) => value.writeToBuffer(),$0.Empty.fromBuffer);+ static final _$getNetwork = $grpc.ClientMethod<$0.Empty, $0.NetworkInfo>(+ '/copysync.v1.DaemonService/GetNetwork',+ ($0.Empty value) => value.writeToBuffer(),+ $0.NetworkInfo.fromBuffer);}@$pb.GrpcServiceName('copysync.v1.DaemonService')@@ -316,6 +328,13 @@ abstract class DaemonServiceBase extends $grpc.Service {false,($core.List<$core.int> value) => $0.Empty.fromBuffer(value),($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.NetworkInfo>(+ 'GetNetwork',+ getNetwork_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.NetworkInfo value) => value.writeToBuffer()));}$async.Stream<$0.Event> subscribe_Pre($grpc.ServiceCall $call,@@ -428,4 +447,12 @@ abstract class DaemonServiceBase extends $grpc.Service {$async.Future<$0.Empty> requestClipboardPermission($grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.NetworkInfo> getNetwork_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return getNetwork($call, await $request);+ }++ $async.Future<$0.NetworkInfo> getNetwork(+ $grpc.ServiceCall call, $0.Empty request);}diff --git a/ui/lib/gen/copysync/v1/daemon.pbjson.dart b/ui/lib/gen/copysync/v1/daemon.pbjson.dartindex f3dcb67..db6061c 100644--- a/ui/lib/gen/copysync/v1/daemon.pbjson.dart+++ b/ui/lib/gen/copysync/v1/daemon.pbjson.dart@@ -534,6 +534,7 @@ const Config$json = {{'1': 'launch_at_login', '3': 9, '4': 1, '5': 8, '10': 'launchAtLogin'},{'1': 'device_name', '3': 10, '4': 1, '5': 9, '10': 'deviceName'},{'1': 'signaling_url', '3': 11, '4': 1, '5': 9, '10': 'signalingUrl'},+ {'1': 'only_own_stun', '3': 12, '4': 1, '5': 8, '10': 'onlyOwnStun'},],};@@ -546,7 +547,51 @@ final $typed_data.Uint8List configDescriptor = $convert.base64Decode('eW5jX2ltYWdlGAYgASgIUglzeW5jSW1hZ2USGwoJc3luY19maWxlGAcgASgIUghzeW5jRmlsZR''I1ChdhdXRvX2FwcGx5X3RvX2NsaXBib2FyZBgIIAEoCFIUYXV0b0FwcGx5VG9DbGlwYm9hcmQS''JgoPbGF1bmNoX2F0X2xvZ2luGAkgASgIUg1sYXVuY2hBdExvZ2luEh8KC2RldmljZV9uYW1lGA'- 'ogASgJUgpkZXZpY2VOYW1lEiMKDXNpZ25hbGluZ191cmwYCyABKAlSDHNpZ25hbGluZ1VybA==');+ 'ogASgJUgpkZXZpY2VOYW1lEiMKDXNpZ25hbGluZ191cmwYCyABKAlSDHNpZ25hbGluZ1VybBIi'+ 'Cg1vbmx5X293bl9zdHVuGAwgASgIUgtvbmx5T3duU3R1bg==');++@$core.Deprecated('Use networkInfoDescriptor instead')+const NetworkInfo$json = {+ '1': 'NetworkInfo',+ '2': [+ {'1': 'local_port', '3': 1, '4': 1, '5': 5, '10': 'localPort'},+ {+ '1': 'egresses',+ '3': 2,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.NetworkEgress',+ '10': 'egresses'+ },+ {'1': 'probed', '3': 3, '4': 1, '5': 5, '10': 'probed'},+ {'1': 'answered', '3': 4, '4': 1, '5': 5, '10': 'answered'},+ {'1': 'probed_at_unix', '3': 5, '4': 1, '5': 3, '10': 'probedAtUnix'},+ ],+};++/// Descriptor for `NetworkInfo`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List networkInfoDescriptor = $convert.base64Decode(+ 'CgtOZXR3b3JrSW5mbxIdCgpsb2NhbF9wb3J0GAEgASgFUglsb2NhbFBvcnQSNgoIZWdyZXNzZX'+ 'MYAiADKAsyGi5jb3B5c3luYy52MS5OZXR3b3JrRWdyZXNzUghlZ3Jlc3NlcxIWCgZwcm9iZWQY'+ 'AyABKAVSBnByb2JlZBIaCghhbnN3ZXJlZBgEIAEoBVIIYW5zd2VyZWQSJAoOcHJvYmVkX2F0X3'+ 'VuaXgYBSABKANSDHByb2JlZEF0VW5peA==');++@$core.Deprecated('Use networkEgressDescriptor instead')+const NetworkEgress$json = {+ '1': 'NetworkEgress',+ '2': [+ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'},+ {'1': 'port_preserved', '3': 2, '4': 1, '5': 8, '10': 'portPreserved'},+ {'1': 'guessed', '3': 3, '4': 1, '5': 8, '10': 'guessed'},+ {'1': 'via', '3': 4, '4': 3, '5': 9, '10': 'via'},+ ],+};++/// Descriptor for `NetworkEgress`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List networkEgressDescriptor = $convert.base64Decode(+ 'Cg1OZXR3b3JrRWdyZXNzEhgKB2FkZHJlc3MYASABKAlSB2FkZHJlc3MSJQoOcG9ydF9wcmVzZX'+ 'J2ZWQYAiABKAhSDXBvcnRQcmVzZXJ2ZWQSGAoHZ3Vlc3NlZBgDIAEoCFIHZ3Vlc3NlZBIQCgN2'+ 'aWEYBCADKAlSA3ZpYQ==');@$core.Deprecated('Use statusDescriptor instead')const Status$json = {diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dartindex 3d57e35..9f30f6f 100644--- a/ui/lib/pages/settings_page.dart+++ b/ui/lib/pages/settings_page.dart@@ -93,6 +93,14 @@ class _SettingsPageState extends State<SettingsPage> {),),),+ SettingRow(+ title: '用公共服务器探测网络出口',+ description: '公司双线这类多出口网络里,能找到更多可以直连的路径。公共服务器只会看到你的公网 IP',+ child: SmallSwitch(+ value: !cfg.onlyOwnStun,+ onChanged: (v) => _update(state, cfg..onlyOwnStun = !v),+ ),+ ),SettingRow(title: '连接状态',description: connected ? '已连接到信令服务器' : '连不上服务器。检查地址是否正确、服务器是否在运行。',diff --git a/ui/pubspec.yaml b/ui/pubspec.yamlindex 44d0409..d4becef 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.0.2+3+version: 1.1.0+4environment:sdk: ^3.12.2