remote.go 1.62 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
package p2p

import (
	"context"

	ma "gx/ipfs/QmWWQ2Txc2c6tqjsBpzg5Ar652cHPGNsQQp2SejkNmkUMb/go-multiaddr"
	net "gx/ipfs/QmYj8wdn5sZEHX2XMDWGBvcXJNdzVbaVpHmXvhHBVZepen/go-libp2p-net"
	protocol "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol"
	manet "gx/ipfs/QmcGXGdw9BWDysPJQHxJinjGHha3eEg4vzFETre4woNwcX/go-multiaddr-net"
)

Łukasz Magiera's avatar
Łukasz Magiera committed
12 13
// remoteListener accepts libp2p streams and proxies them to a manet host
type remoteListener struct {
14 15 16 17 18
	p2p *P2P

	// Application proto identifier.
	proto string

19
	// Address to proxy the incoming connections to
20 21 22
	addr ma.Multiaddr
}

Łukasz Magiera's avatar
Łukasz Magiera committed
23 24 25
// ForwardRemote creates new p2p listener
func (p2p *P2P) ForwardRemote(ctx context.Context, proto string, addr ma.Multiaddr) (Listener, error) {
	listenerInfo := &remoteListener{
26 27
		p2p: p2p,

28
		proto: proto,
29
		addr:  addr,
30 31
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
32 33
	p2p.Listeners.Register(listenerInfo)

34 35 36 37 38 39 40
	p2p.peerHost.SetStreamHandler(protocol.ID(proto), func(remote net.Stream) {
		local, err := manet.Dial(addr)
		if err != nil {
			remote.Reset()
			return
		}

41
		stream := Stream{
42 43
			Protocol: proto,

44 45
			OriginAddr: remote.Conn().RemoteMultiaddr(),
			TargetAddr: addr,
46 47 48 49

			Local:  local,
			Remote: remote,

50
			Registry: p2p.Streams,
51 52 53 54 55 56 57 58 59
		}

		p2p.Streams.Register(&stream)
		stream.startStreaming()
	})

	return listenerInfo, nil
}

Łukasz Magiera's avatar
Łukasz Magiera committed
60
func (l *remoteListener) Protocol() string {
61 62 63
	return l.proto
}

Łukasz Magiera's avatar
Łukasz Magiera committed
64 65 66 67 68
func (l *remoteListener) ListenAddress() string {
	return "/ipfs"
}

func (l *remoteListener) TargetAddress() string {
69 70 71
	return l.addr.String()
}

Łukasz Magiera's avatar
Łukasz Magiera committed
72
func (l *remoteListener) Close() error {
73
	l.p2p.peerHost.RemoveStreamHandler(protocol.ID(l.proto))
74
	l.p2p.Listeners.Deregister(getListenerKey(l))
75
	return nil
76
}