dial.go 5.29 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
	"strings"
7
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8

Jeromy's avatar
Jeromy committed
9
10
11
12
13
	ci "github.com/ipfs/go-libp2p-crypto"
	lgbl "github.com/ipfs/go-libp2p-loggables"
	peer "github.com/ipfs/go-libp2p-peer"
	ma "github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-multiaddr-net"
14
	transport "github.com/libp2p/go-libp2p-transport"
15
	addrutil "github.com/libp2p/go-libp2p/p2p/net/swarm/addr"
Jeromy's avatar
Jeromy committed
16
17
	msmux "github.com/whyrusleeping/go-multistream"
	context "golang.org/x/net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
19
)

Jeromy's avatar
Jeromy committed
20
21
22
23
24
25
26
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,
Jeromy's avatar
Jeromy committed
27
		fallback:   new(transport.FallbackDialer),
Jeromy's avatar
Jeromy committed
28
29
30
	}
}

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

// 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
40
	logdial := lgbl.Dial("conn", d.LocalPeer, remote, nil, raddr)
41
	logdial["encrypted"] = (d.PrivateKey != nil) // log wether this will be an encrypted dial or not.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	defer log.EventBegin(ctx, "connDial", logdial).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
44
45
46
47
48
49

	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
50
51
52
53
54
55
		defer func() {
			select {
			case done <- struct{}{}:
			case <-ctx.Done():
			}
		}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56

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

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

67
		cryptoProtoChoice := SecioTag
68
		if !EncryptConnections || d.PrivateKey == nil {
69
70
71
			cryptoProtoChoice = NoEncryptionTag
		}

72
73
		maconn.SetReadDeadline(time.Now().Add(NegotiateReadTimeout))

74
		err = msmux.SelectProtoOrFail(cryptoProtoChoice, maconn)
75
76
77
78
79
		if err != nil {
			errOut = err
			return
		}

80
81
		maconn.SetReadDeadline(time.Time{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82
83
		c, err := newSingleConn(ctx, d.LocalPeer, remote, maconn)
		if err != nil {
84
			maconn.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85
86
87
88
			errOut = err
			return
		}

John Steidley's avatar
John Steidley committed
89
		if d.PrivateKey == nil || !EncryptConnections {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
91
92
93
			log.Warning("dialer %s dialing INSECURELY %s at %s!", d, remote, raddr)
			connOut = c
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95
96
97
98
99
100
101
102
103
104
105
106
		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
107
		logdial["error"] = ctx.Err()
108
		logdial["dial"] = "failure"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
110
111
112
113
		return nil, ctx.Err()
	case <-done:
		// whew, finished.
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
115
116
117
118
119
120
121
	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
122
123
}

Jeromy's avatar
Jeromy committed
124
125
func (d *Dialer) AddDialer(pd transport.Dialer) {
	d.Dialers = append(d.Dialers, pd)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
127
}

Jeromy's avatar
Jeromy committed
128
129
130
131
132
133
// 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
134
135
	}

Jeromy's avatar
Jeromy committed
136
137
138
139
	if d.fallback.Matches(raddr) {
		return d.fallback
	}

Jeromy's avatar
Jeromy committed
140
	return nil
141
142
}

Jeromy's avatar
Jeromy committed
143
144
145
146
147
// 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)
148
149
	}

Jeromy's avatar
Jeromy committed
150
151
152
	sd := d.subDialerForAddr(raddr)
	if sd == nil {
		return nil, fmt.Errorf("no dialer for %s", raddr)
153
154
	}

155
	return sd.DialContext(ctx, raddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
157
158
159
160
161
162
}

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

163
	// make sure that we ONLY use local addrs that match the remote addr.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
165
166
167
168
	laddrs = manet.AddrMatch(raddr, laddrs)
	if len(laddrs) < 1 {
		return nil
	}

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
	// 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
187
188
189
190
191
192
	// 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
193
194
195
196
197
198
199
200
201
202
// 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
203
		if api.Code != bp[i].Code {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
			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
}