dial.go 4.89 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
4
package conn

import (
	"fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"math/rand"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
7
	"strings"

Jeromy's avatar
Jeromy committed
8
	manet "QmRCPT5WRph8aWXmaT2Rfn6ac98YRUUJnNURpD3hNAWp4f/go-multiaddr-net"
Jeromy's avatar
Jeromy committed
9
	context "QmacZi9WygGK7Me8mH53pypyscHzU386aUZXpr28GZgUct/context"
Jeromy's avatar
Jeromy committed
10
	ma "QmbWxL1aXQhBjc1XGjGF1f2KGBMCBYSuT2ThA8YXnXJK83/go-multiaddr"
Jeromy's avatar
Jeromy committed
11
	lgbl "util/eventlog/loggables"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12

Jeromy's avatar
Jeromy committed
13
	ci "github.com/ipfs/go-libp2p/p2p/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14
	addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr"
Jeromy's avatar
Jeromy committed
15
	transport "github.com/ipfs/go-libp2p/p2p/net/transport"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
	peer "github.com/ipfs/go-libp2p/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
18
)

Jeromy's avatar
Jeromy committed
19
20
21
22
23
24
25
26
27
28
type WrapFunc func(transport.Conn) transport.Conn

func NewDialer(p peer.ID, pk ci.PrivKey, wrap WrapFunc) *Dialer {
	return &Dialer{
		LocalPeer:  p,
		PrivateKey: pk,
		Wrapper:    wrap,
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
30
// String returns the string rep of d.
func (d *Dialer) String() string {
Jeromy's avatar
Jeromy committed
31
	return fmt.Sprintf("<Dialer %s ...>", d.LocalPeer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
33
34
35
36
37
}

// Dial connects to a peer over a particular address
// Ensures raddr is part of peer.Addresses()
// Example: d.DialAddr(ctx, peer.Addresses()[0], peer)
func (d *Dialer) Dial(ctx context.Context, raddr ma.Multiaddr, remote peer.ID) (Conn, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	logdial := lgbl.Dial("conn", d.LocalPeer, remote, nil, raddr)
39
	logdial["encrypted"] = (d.PrivateKey != nil) // log wether this will be an encrypted dial or not.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
	defer log.EventBegin(ctx, "connDial", logdial).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
42
43
44
45
46
47

	var connOut Conn
	var errOut error
	done := make(chan struct{})

	// do it async to ensure we respect don contexteone
	go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
49
50
51
52
53
		defer func() {
			select {
			case done <- struct{}{}:
			case <-ctx.Done():
			}
		}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54

55
56
57
58
59
60
		maconn, err := d.rawConnDial(ctx, raddr, remote)
		if err != nil {
			errOut = err
			return
		}

Jeromy's avatar
Jeromy committed
61
62
63
64
		if d.Wrapper != nil {
			maconn = d.Wrapper(maconn)
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
66
		c, err := newSingleConn(ctx, d.LocalPeer, remote, maconn)
		if err != nil {
67
			maconn.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
69
70
71
			errOut = err
			return
		}

72
		if d.PrivateKey == nil || EncryptConnections == false {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
74
75
76
			log.Warning("dialer %s dialing INSECURELY %s at %s!", d, remote, raddr)
			connOut = c
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
79
80
81
82
83
84
85
86
87
88
89
		c2, err := newSecureConn(ctx, d.PrivateKey, c)
		if err != nil {
			errOut = err
			c.Close()
			return
		}

		connOut = c2
	}()

	select {
	case <-ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
		logdial["error"] = ctx.Err()
91
		logdial["dial"] = "failure"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
93
94
95
96
		return nil, ctx.Err()
	case <-done:
		// whew, finished.
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
98
99
100
101
102
103
104
	if errOut != nil {
		logdial["error"] = errOut
		logdial["dial"] = "failure"
		return nil, errOut
	}

	logdial["dial"] = "success"
	return connOut, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105
106
}

Jeromy's avatar
Jeromy committed
107
108
func (d *Dialer) AddDialer(pd transport.Dialer) {
	d.Dialers = append(d.Dialers, pd)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
110
}

Jeromy's avatar
Jeromy committed
111
112
113
114
115
116
// returns dialer that can dial the given address
func (d *Dialer) subDialerForAddr(raddr ma.Multiaddr) transport.Dialer {
	for _, pd := range d.Dialers {
		if pd.Matches(raddr) {
			return pd
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
118
	}

Jeromy's avatar
Jeromy committed
119
	return nil
120
121
}

Jeromy's avatar
Jeromy committed
122
123
124
125
126
// rawConnDial dials the underlying net.Conn + manet.Conns
func (d *Dialer) rawConnDial(ctx context.Context, raddr ma.Multiaddr, remote peer.ID) (transport.Conn, error) {
	if strings.HasPrefix(raddr.String(), "/ip4/0.0.0.0") {
		log.Event(ctx, "connDialZeroAddr", lgbl.Dial("conn", d.LocalPeer, remote, nil, raddr))
		return nil, fmt.Errorf("Attempted to connect to zero address: %s", raddr)
127
128
	}

Jeromy's avatar
Jeromy committed
129
130
131
	sd := d.subDialerForAddr(raddr)
	if sd == nil {
		return nil, fmt.Errorf("no dialer for %s", raddr)
132
133
	}

Jeromy's avatar
Jeromy committed
134
	return sd.Dial(raddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135
136
137
138
139
140
141
}

func pickLocalAddr(laddrs []ma.Multiaddr, raddr ma.Multiaddr) (laddr ma.Multiaddr) {
	if len(laddrs) < 1 {
		return nil
	}

142
	// make sure that we ONLY use local addrs that match the remote addr.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
144
145
146
147
	laddrs = manet.AddrMatch(raddr, laddrs)
	if len(laddrs) < 1 {
		return nil
	}

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	// make sure that we ONLY use local addrs that CAN dial the remote addr.
	// filter out all the local addrs that aren't capable
	raddrIPLayer := ma.Split(raddr)[0]
	raddrIsLoopback := manet.IsIPLoopback(raddrIPLayer)
	raddrIsLinkLocal := manet.IsIP6LinkLocal(raddrIPLayer)
	laddrs = addrutil.FilterAddrs(laddrs, func(a ma.Multiaddr) bool {
		laddrIPLayer := ma.Split(a)[0]
		laddrIsLoopback := manet.IsIPLoopback(laddrIPLayer)
		laddrIsLinkLocal := manet.IsIP6LinkLocal(laddrIPLayer)
		if laddrIsLoopback { // our loopback addrs can only dial loopbacks.
			return raddrIsLoopback
		}
		if laddrIsLinkLocal {
			return raddrIsLinkLocal // out linklocal addrs can only dial link locals.
		}
		return true
	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166
167
168
169
170
171
	// TODO pick with a good heuristic
	// we use a random one for now to prevent bad addresses from making nodes unreachable
	// with a random selection, multiple tries may work.
	return laddrs[rand.Intn(len(laddrs))]
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
173
174
175
176
177
178
179
180
181
// MultiaddrProtocolsMatch returns whether two multiaddrs match in protocol stacks.
func MultiaddrProtocolsMatch(a, b ma.Multiaddr) bool {
	ap := a.Protocols()
	bp := b.Protocols()

	if len(ap) != len(bp) {
		return false
	}

	for i, api := range ap {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
		if api.Code != bp[i].Code {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
			return false
		}
	}

	return true
}

// MultiaddrNetMatch returns the first Multiaddr found to match  network.
func MultiaddrNetMatch(tgt ma.Multiaddr, srcs []ma.Multiaddr) ma.Multiaddr {
	for _, a := range srcs {
		if MultiaddrProtocolsMatch(tgt, a) {
			return a
		}
	}
	return nil
}