dial.go 4.93 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
	lgbl "github.com/ipfs/go-libp2p/loggables"
Jeromy's avatar
Jeromy committed
9
	ci "github.com/ipfs/go-libp2p/p2p/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr"
Jeromy's avatar
Jeromy committed
11
	transport "github.com/ipfs/go-libp2p/p2p/net/transport"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	peer "github.com/ipfs/go-libp2p/p2p/peer"
Jeromy's avatar
Jeromy committed
13
14
15
	manet "gx/ipfs/QmQB7mNP3QE7b4zP2MQmsyJDqG5hzYE2CL8k1VyLWky2Ed/go-multiaddr-net"
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
	ma "gx/ipfs/QmcobAGsCjYt5DXoq9et9L8yR8er7o7Cu3DTvpaq12jYSz/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
17
)

Jeromy's avatar
Jeromy committed
18
19
20
21
22
23
24
25
26
27
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
28
29
// String returns the string rep of d.
func (d *Dialer) String() string {
Jeromy's avatar
Jeromy committed
30
	return fmt.Sprintf("<Dialer %s ...>", d.LocalPeer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
32
33
34
35
36
}

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

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77
78
79
80
81
82
83
84
85
86
87
88
		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
89
		logdial["error"] = ctx.Err()
90
		logdial["dial"] = "failure"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
92
93
94
95
		return nil, ctx.Err()
	case <-done:
		// whew, finished.
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
97
98
99
100
101
102
103
	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
104
105
}

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

Jeromy's avatar
Jeromy committed
110
111
112
113
114
115
// 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
116
117
	}

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

Jeromy's avatar
Jeromy committed
121
122
123
124
125
// 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)
126
127
	}

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

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

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

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

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
	// 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
165
166
167
168
169
170
	// 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
171
172
173
174
175
176
177
178
179
180
// 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
181
		if api.Code != bp[i].Code {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
			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
}