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
fix(core): reconnect at once when a LAN peer restarts
baiyuze4133190c58a1
diff --git a/client-core/internal/peers/manager.go b/client-core/internal/peers/manager.goindex 5206715..366222a 100644--- a/client-core/internal/peers/manager.go+++ b/client-core/internal/peers/manager.go@@ -185,6 +185,7 @@ func NewManager(opts Options) (*Manager, error) {},OnSignal: m.handleSignal,OnReachable: m.handleLANReachable,+ OnRestarted: m.handlePeerRestarted,AcceptPair: m.acceptLANPair,OnChange: m.notifyStatus,})@@ -373,6 +374,16 @@ func (m *Manager) handleLANReachable(deviceID string, reachable bool) {m.notifyStatus()}+// handlePeerRestarted:局域网里的某台设备重启过,本端的 P2P 连接已经失效,只是还没察觉。+// 立即丢掉重建;否则要等握手超时,对方又可能是应答方,只能干等本端来连。+func (m *Manager) handlePeerRestarted(deviceID string) {+ m.p2p.Disconnect(deviceID)+ m.mu.Lock()+ delete(m.conn, deviceID)+ m.mu.Unlock()+ m.connectIfOffline(deviceID)+}+// connectIfOffline 在对端上线时建立 P2P 通道,这样真正要传数据时已经就绪。// 谁发起由 p2p.Manager 内部按 device_id 字典序决定,这里无脑调用即可。func (m *Manager) connectIfOffline(deviceID string) {diff --git a/client-core/internal/transport/lan/lan.go b/client-core/internal/transport/lan/lan.goindex b5cab20..4f0e85e 100644--- a/client-core/internal/transport/lan/lan.go+++ b/client-core/internal/transport/lan/lan.go@@ -12,6 +12,7 @@package lanimport (+ "bytes""context"cryptorand "crypto/rand""encoding/hex"@@ -89,6 +90,8 @@ type Options struct {OnSignal func(from string, msg *pb.SignalMessage)// OnReachable 某台设备在局域网里变得可达或不可达OnReachable func(deviceID string, reachable bool)+ // OnRestarted 发现某台已配对设备重启过(hello 里的启动标识变了)时调用:旧连接已经失效+ OnRestarted func(deviceID string)// AcceptPair 在有人用正确的配对码发来请求时调用。返回 false 表示这个码已经在别处// (服务器那边)用掉了,请求会被拒绝。AcceptPair func(peer PeerInfo) bool@@ -103,6 +106,7 @@ type peerState struct {reachable boolreported []netip.AddrPort // 对方 hello 里自报的地址+ boot []byte // 对方 hello 里的启动标识discovered map[netip.AddrPort]time.Time // mDNS 发现的地址book []netip.AddrPort // 地址簿里存的地址bookLoaded bool@@ -124,6 +128,7 @@ type Transport struct {id *identity.Identitydiscovery Discoveryinstance string+ boot []byte // 本次启动的标识,随 hello 发给对方mu sync.Mutexrunning bool@@ -161,6 +166,8 @@ func New(opts Options) *Transport {}suffix := make([]byte, 6)_, _ = cryptorand.Read(suffix)+ boot := make([]byte, 8)+ _, _ = cryptorand.Read(boot)return &Transport{opts: opts,log: log.With("模块", "局域网"),@@ -168,6 +175,7 @@ func New(opts Options) *Transport {discovery: d,// 实例名每次启动随机,不带设备名:同一网络里的其他人看不出这是谁的电脑instance: "copysync-" + hex.EncodeToString(suffix),+ boot: boot,peers: make(map[string]*peerState),instances: make(map[string]seenInstance),tokens: make(map[string]string),@@ -516,9 +524,14 @@ func (t *Transport) sawPeer(id string, src netip.AddrPort, hello *pb.LanHello) {}st := t.peerLocked(id)st.addr, st.lastSeen = src, now+ restarted := falseif hello != nil {st.ttl = ttlFor(hello.GetIntervalSeconds())st.reported = parseAddrs(hello.GetAddresses())+ if b := hello.GetBoot(); len(b) > 0 {+ restarted = len(st.boot) > 0 && !bytes.Equal(st.boot, b)+ st.boot = append(st.boot[:0], b...)+ }} else if st.ttl == 0 {st.ttl = ttlFor(0)}@@ -538,6 +551,12 @@ func (t *Transport) sawPeer(id string, src netip.AddrPort, hello *pb.LanHello) {t.log.Info("局域网里找到了设备", "device", id, "地址", src)t.reachable(id, true)}+ if restarted {+ t.log.Info("局域网里的设备重启过", "device", id)+ if t.opts.OnRestarted != nil {+ t.opts.OnRestarted(id)+ }+ }}func (t *Transport) answerHello(from string, src netip.AddrPort, hello *pb.LanHello) {@@ -716,6 +735,7 @@ func (t *Transport) sendHello(to string, targets []netip.AddrPort, replyWanted bAddresses: addrs,ReplyWanted: replyWanted,IntervalSeconds: uint32(interval / time.Second),+ Boot: t.boot,}}})if err != nil {return@@ -790,7 +810,10 @@ func (t *Transport) found(inst Instance) {st.discovered = make(map[netip.AddrPort]time.Time)}st.discovered[inst.Addr] = now- if fresh && !st.reachable {+ // 实例名或地址变了,说明对方重启过或换了网络:即使还当它可达,也马上打招呼。+ // 对方若是没放行防火墙的 Windows,它收不到本机主动发去的包,得靠本机先回应它+ restarted := !had || prev.inst.Addr != inst.Addr+ if fresh && (!st.reachable || restarted) {hello = id}}diff --git a/client-core/internal/transport/lan/lan_test.go b/client-core/internal/transport/lan/lan_test.goindex 408bc00..6ebe39b 100644--- a/client-core/internal/transport/lan/lan_test.go+++ b/client-core/internal/transport/lan/lan_test.go@@ -20,12 +20,13 @@ type node struct {id *identity.Identityt *Transport- mu sync.Mutex- known map[string]ed25519.PublicKey- book map[string][]string- accepted []PeerInfo- signals chan *pb.SignalMessage- reach chan string+ mu sync.Mutex+ known map[string]ed25519.PublicKey+ book map[string][]string+ accepted []PeerInfo+ signals chan *pb.SignalMessage+ reach chan string+ restarted chan string}func newNode(t *testing.T, net *MemoryNetwork) *node {@@ -35,11 +36,12 @@ func newNode(t *testing.T, net *MemoryNetwork) *node {t.Fatal(err)}n := &node{- id: id,- known: map[string]ed25519.PublicKey{},- book: map[string][]string{},- signals: make(chan *pb.SignalMessage, 16),- reach: make(chan string, 16),+ id: id,+ known: map[string]ed25519.PublicKey{},+ book: map[string][]string{},+ signals: make(chan *pb.SignalMessage, 16),+ reach: make(chan string, 16),+ restarted: make(chan string, 16),}var d Discoveryif net != nil {@@ -61,6 +63,7 @@ func newNode(t *testing.T, net *MemoryNetwork) *node {n.reach <- id}},+ OnRestarted: func(id string) { n.restarted <- id },AcceptPair: func(p PeerInfo) bool {n.mu.Lock()defer n.mu.Unlock()@@ -328,3 +331,36 @@ func TestPresenceTokenRotatesDaily(t *testing.T) {t.Error("不同设备的令牌应当不同")}}++// 对方重启后带着新的启动标识打招呼:本端要知道旧连接已经失效。+func TestPeerRestartIsNoticed(t *testing.T) {+ net := NewMemoryNetwork()+ a, b := newNode(t, net), newNode(t, net)+ pair(a, b)+ waitReachable(t, a, b.id.DeviceID)++ // b 用同一个身份重新启动:新的 Transport 有新的启动标识+ b.t.Stop()+ b.t = New(Options{+ Identity: b.id,+ Port: -1,+ Discovery: net.Discovery(),+ Verifier: signed.NewVerifier(b.id.DeviceID, b.keyOf),+ Book: b,+ Peers: b.peers,+ DeviceInfo: func() (string, string) { return "b", "test" },+ })+ if err := b.t.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(b.t.Stop)++ select {+ case id := <-a.restarted:+ if id != b.id.DeviceID {+ t.Fatalf("报告重启的设备不对: %s", id)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("对方重启后没有察觉")+ }+}diff --git a/proto/copysync/v1/wire.proto b/proto/copysync/v1/wire.protoindex 10ebd81..50f36d4 100644--- a/proto/copysync/v1/wire.proto+++ b/proto/copysync/v1/wire.proto@@ -187,6 +187,9 @@ message LanHello {repeated string addresses = 1; // 发送方本机的局域网地址,ip:portbool reply_wanted = 2; // 收到后回一条,让发送方也知道本端可达uint32 interval_seconds = 3; // 发送方多久发一次;超过三倍没收到即视为不可达+ // 发送方每次启动时随机生成。变了说明对方重启过,旧的 P2P 连接已经失效,+ // 要立即重建,而不是等连接超时(用服务器时,这件事由上下线通知完成)+ bytes boot = 4;}// payload 是序列化后的 LanPairInfo,signature 用 LanPairInfo.public_key 签名。diff --git a/proto/gen/copysync/v1/wire.pb.go b/proto/gen/copysync/v1/wire.pb.goindex 70f93ec..41753d5 100644--- a/proto/gen/copysync/v1/wire.pb.go+++ b/proto/gen/copysync/v1/wire.pb.go@@ -1650,8 +1650,11 @@ type LanHello struct {Addresses []string `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses,omitempty"` // 发送方本机的局域网地址,ip:portReplyWanted bool `protobuf:"varint,2,opt,name=reply_wanted,json=replyWanted,proto3" json:"reply_wanted,omitempty"` // 收到后回一条,让发送方也知道本端可达IntervalSeconds uint32 `protobuf:"varint,3,opt,name=interval_seconds,json=intervalSeconds,proto3" json:"interval_seconds,omitempty"` // 发送方多久发一次;超过三倍没收到即视为不可达- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // 发送方每次启动时随机生成。变了说明对方重启过,旧的 P2P 连接已经失效,+ // 要立即重建,而不是等连接超时(用服务器时,这件事由上下线通知完成)+ Boot []byte `protobuf:"bytes,4,opt,name=boot,proto3" json:"boot,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *LanHello) Reset() {@@ -1705,6 +1708,13 @@ func (x *LanHello) GetIntervalSeconds() uint32 {return 0}+func (x *LanHello) GetBoot() []byte {+ if x != nil {+ return x.Boot+ }+ return nil+}+// payload 是序列化后的 LanPairInfo,signature 用 LanPairInfo.public_key 签名。type LanPairSigned struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -2589,11 +2599,12 @@ const file_copysync_v1_wire_proto_rawDesc = "" +"\rpair_response\x18\x03 \x01(\v2\x1a.copysync.v1.LanPairSignedH\x00R\fpairResponse\x12=\n" +"\vpair_reject\x18\x04 \x01(\v2\x1a.copysync.v1.LanPairRejectH\x00R\n" +"pairRejectB\t\n" +- "\apayload\"v\n" ++ "\apayload\"\x8a\x01\n" +"\bLanHello\x12\x1c\n" +"\taddresses\x18\x01 \x03(\tR\taddresses\x12!\n" +"\freply_wanted\x18\x02 \x01(\bR\vreplyWanted\x12)\n" +- "\x10interval_seconds\x18\x03 \x01(\rR\x0fintervalSeconds\"G\n" ++ "\x10interval_seconds\x18\x03 \x01(\rR\x0fintervalSeconds\x12\x12\n" ++ "\x04boot\x18\x04 \x01(\fR\x04boot\"G\n" +"\rLanPairSigned\x12\x18\n" +"\apayload\x18\x01 \x01(\fR\apayload\x12\x1c\n" +"\tsignature\x18\x02 \x01(\fR\tsignature\"\x9a\x02\n" +diff --git a/ui/lib/gen/copysync/v1/wire.pb.dart b/ui/lib/gen/copysync/v1/wire.pb.dartindex 527031d..6a0667f 100644--- a/ui/lib/gen/copysync/v1/wire.pb.dart+++ b/ui/lib/gen/copysync/v1/wire.pb.dart@@ -1951,11 +1951,13 @@ class LanHello extends $pb.GeneratedMessage {$core.Iterable<$core.String>? addresses,$core.bool? replyWanted,$core.int? intervalSeconds,+ $core.List<$core.int>? boot,}) {final result = LanHello._();if (addresses != null) result.addresses.addAll(addresses);if (replyWanted != null) result.replyWanted = replyWanted;if (intervalSeconds != null) result.intervalSeconds = intervalSeconds;+ if (boot != null) result.boot = boot;return result;}@@ -1976,6 +1978,8 @@ class LanHello extends $pb.GeneratedMessage {..aOB(2, _omitFieldNames ? '' : 'replyWanted')..aI(3, _omitFieldNames ? '' : 'intervalSeconds',fieldType: $pb.PbFieldType.OU3)+ ..a<$core.List<$core.int>>(+ 4, _omitFieldNames ? '' : 'boot', $pb.PbFieldType.OY)..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -2018,6 +2022,17 @@ class LanHello extends $pb.GeneratedMessage {$core.bool hasIntervalSeconds() => $_has(2);@$pb.TagNumber(3)void clearIntervalSeconds() => $_clearField(3);++ /// 发送方每次启动时随机生成。变了说明对方重启过,旧的 P2P 连接已经失效,+ /// 要立即重建,而不是等连接超时(用服务器时,这件事由上下线通知完成)+ @$pb.TagNumber(4)+ $core.List<$core.int> get boot => $_getN(3);+ @$pb.TagNumber(4)+ set boot($core.List<$core.int> value) => $_setBytes(3, value);+ @$pb.TagNumber(4)+ $core.bool hasBoot() => $_has(3);+ @$pb.TagNumber(4)+ void clearBoot() => $_clearField(4);}/// payload 是序列化后的 LanPairInfo,signature 用 LanPairInfo.public_key 签名。diff --git a/ui/lib/gen/copysync/v1/wire.pbjson.dart b/ui/lib/gen/copysync/v1/wire.pbjson.dartindex a8175a6..eb97ca8 100644--- a/ui/lib/gen/copysync/v1/wire.pbjson.dart+++ b/ui/lib/gen/copysync/v1/wire.pbjson.dart@@ -584,6 +584,7 @@ const LanHello$json = {{'1': 'addresses', '3': 1, '4': 3, '5': 9, '10': 'addresses'},{'1': 'reply_wanted', '3': 2, '4': 1, '5': 8, '10': 'replyWanted'},{'1': 'interval_seconds', '3': 3, '4': 1, '5': 13, '10': 'intervalSeconds'},+ {'1': 'boot', '3': 4, '4': 1, '5': 12, '10': 'boot'},],};@@ -591,7 +592,7 @@ const LanHello$json = {final $typed_data.Uint8List lanHelloDescriptor = $convert.base64Decode('CghMYW5IZWxsbxIcCglhZGRyZXNzZXMYASADKAlSCWFkZHJlc3NlcxIhCgxyZXBseV93YW50ZW''QYAiABKAhSC3JlcGx5V2FudGVkEikKEGludGVydmFsX3NlY29uZHMYAyABKA1SD2ludGVydmFs'- 'U2Vjb25kcw==');+ 'U2Vjb25kcxISCgRib290GAQgASgMUgRib290');@$core.Deprecated('Use lanPairSignedDescriptor instead')const LanPairSigned$json = {