-
Notifications
You must be signed in to change notification settings - Fork 62
/
remote.go
92 lines (69 loc) · 1.86 KB
/
remote.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package p2p
import (
"context"
ma "gx/ipfs/QmT4U94DnD8FRfqr21obWY32HLM5VExccPKMjQHofeYqr9/go-multiaddr"
net "gx/ipfs/QmXuRkCR7BNQa9uqfpTiFWsTQLzmTWYg91Ja1w95gnqb6u/go-libp2p-net"
protocol "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol"
manet "gx/ipfs/Qmaabb1tJZ2CX5cp6MuuiGgns71NYoxdgQP6Xdid1dVceC/go-multiaddr-net"
)
var maPrefix = "/" + ma.ProtocolWithCode(ma.P_IPFS).Name + "/"
// remoteListener accepts libp2p streams and proxies them to a manet host
type remoteListener struct {
p2p *P2P
// Application proto identifier.
proto protocol.ID
// Address to proxy the incoming connections to
addr ma.Multiaddr
}
// ForwardRemote creates new p2p listener
func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Multiaddr) (Listener, error) {
listener := &remoteListener{
p2p: p2p,
proto: proto,
addr: addr,
}
if err := p2p.ListenersP2P.Register(listener); err != nil {
return nil, err
}
return listener, nil
}
func (l *remoteListener) handleStream(remote net.Stream) {
local, err := manet.Dial(l.addr)
if err != nil {
remote.Reset()
return
}
peer := remote.Conn().RemotePeer()
peerMa, err := ma.NewMultiaddr(maPrefix + peer.Pretty())
if err != nil {
remote.Reset()
return
}
stream := &Stream{
Protocol: l.proto,
OriginAddr: peerMa,
TargetAddr: l.addr,
peer: peer,
Local: local,
Remote: remote,
Registry: l.p2p.Streams,
}
l.p2p.Streams.Register(stream)
}
func (l *remoteListener) Protocol() protocol.ID {
return l.proto
}
func (l *remoteListener) ListenAddress() ma.Multiaddr {
addr, err := ma.NewMultiaddr(maPrefix + l.p2p.identity.Pretty())
if err != nil {
panic(err)
}
return addr
}
func (l *remoteListener) TargetAddress() ma.Multiaddr {
return l.addr
}
func (l *remoteListener) close() {}
func (l *remoteListener) key() string {
return string(l.proto)
}