net.go 11.2 KB
Newer Older
1 2 3 4 5
// Package manet provides Multiaddr
// (https://github.com/multiformats/go-multiaddr) specific versions of common
// functions in Go's standard `net` package. This means wrappers of standard
// net symbols like `net.Dial` and `net.Listen`, as well as conversion to
// and from `net.Addr`.
6
package manet
7 8

import (
9
	"context"
10 11 12
	"fmt"
	"net"

13
	ma "github.com/multiformats/go-multiaddr"
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
)

// Conn is the equivalent of a net.Conn object. It is the
// result of calling the Dial or Listen functions in this
// package, with associated local and remote Multiaddrs.
type Conn interface {
	net.Conn

	// LocalMultiaddr returns the local Multiaddr associated
	// with this connection
	LocalMultiaddr() ma.Multiaddr

	// RemoteMultiaddr returns the remote Multiaddr associated
	// with this connection
	RemoteMultiaddr() ma.Multiaddr
}

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
type halfOpen interface {
	net.Conn
	CloseRead() error
	CloseWrite() error
}

func wrap(nconn net.Conn, laddr, raddr ma.Multiaddr) Conn {
	endpts := maEndpoints{
		laddr: laddr,
		raddr: raddr,
	}
	// This sucks. However, it's the only way to reliably expose the
	// underlying methods. This way, users that need access to, e.g.,
	// CloseRead and CloseWrite, can do so via type assertions.
	switch nconn := nconn.(type) {
	case *net.TCPConn:
		return &struct {
			*net.TCPConn
			maEndpoints
		}{nconn, endpts}
	case *net.UDPConn:
		return &struct {
			*net.UDPConn
			maEndpoints
		}{nconn, endpts}
	case *net.IPConn:
		return &struct {
			*net.IPConn
			maEndpoints
		}{nconn, endpts}
	case *net.UnixConn:
		return &struct {
			*net.UnixConn
			maEndpoints
		}{nconn, endpts}
	case halfOpen:
		return &struct {
			halfOpen
			maEndpoints
		}{nconn, endpts}
	default:
		return &struct {
			net.Conn
			maEndpoints
		}{nconn, endpts}
	}
}

// WrapNetConn wraps a net.Conn object with a Multiaddr friendly Conn.
//
// This function does it's best to avoid "hiding" methods exposed by the wrapped
// type. Guarantees:
//
web3-bot's avatar
web3-bot committed
84 85 86 87 88
//   - If the wrapped connection exposes the "half-open" closer methods
//     (CloseWrite, CloseRead), these will be available on the wrapped connection
//     via type assertions.
//   - If the wrapped connection is a UnixConn, IPConn, TCPConn, or UDPConn, all
//     methods on these wrapped connections will be available via type assertions.
89
func WrapNetConn(nconn net.Conn) (Conn, error) {
90 91 92
	if nconn == nil {
		return nil, fmt.Errorf("failed to convert nconn.LocalAddr: nil")
	}
93 94 95 96 97 98 99 100 101 102 103

	laddr, err := FromNetAddr(nconn.LocalAddr())
	if err != nil {
		return nil, fmt.Errorf("failed to convert nconn.LocalAddr: %s", err)
	}

	raddr, err := FromNetAddr(nconn.RemoteAddr())
	if err != nil {
		return nil, fmt.Errorf("failed to convert nconn.RemoteAddr: %s", err)
	}

104
	return wrap(nconn, laddr, raddr), nil
105 106
}

107
type maEndpoints struct {
108 109 110 111 112 113
	laddr ma.Multiaddr
	raddr ma.Multiaddr
}

// LocalMultiaddr returns the local address associated with
// this connection
114
func (c *maEndpoints) LocalMultiaddr() ma.Multiaddr {
115 116 117 118 119
	return c.laddr
}

// RemoteMultiaddr returns the remote address associated with
// this connection
120
func (c *maEndpoints) RemoteMultiaddr() ma.Multiaddr {
121 122 123 124 125 126 127 128
	return c.raddr
}

// Dialer contains options for connecting to an address. It
// is effectively the same as net.Dialer, but its LocalAddr
// and RemoteAddr options are Multiaddrs, instead of net.Addrs.
type Dialer struct {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	// Dialer is just an embedded net.Dialer, with all its options.
130 131 132 133 134 135 136 137 138 139 140 141 142 143
	net.Dialer

	// LocalAddr is the local address to use when dialing an
	// address. The address must be of a compatible type for the
	// network being dialed.
	// If nil, a local address is automatically chosen.
	LocalAddr ma.Multiaddr
}

// Dial connects to a remote address, using the options of the
// Dialer. Dialer uses an underlying net.Dialer to Dial a
// net.Conn, then wraps that in a Conn object (with local and
// remote Multiaddrs).
func (d *Dialer) Dial(remote ma.Multiaddr) (Conn, error) {
144 145
	return d.DialContext(context.Background(), remote)
}
146

147
// DialContext allows to provide a custom context to Dial().
148
func (d *Dialer) DialContext(ctx context.Context, remote ma.Multiaddr) (Conn, error) {
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	// if a LocalAddr is specified, use it on the embedded dialer.
	if d.LocalAddr != nil {
		// convert our multiaddr to net.Addr friendly
		naddr, err := ToNetAddr(d.LocalAddr)
		if err != nil {
			return nil, err
		}

		// set the dialer's LocalAddr as naddr
		d.Dialer.LocalAddr = naddr
	}

	// get the net.Dial friendly arguments from the remote addr
	rnet, rnaddr, err := DialArgs(remote)
	if err != nil {
		return nil, err
	}

	// ok, Dial!
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
	var nconn net.Conn
	switch rnet {
Cole Brown's avatar
Cole Brown committed
170
	case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "unix":
171
		nconn, err = d.Dialer.DialContext(ctx, rnet, rnaddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172 173 174
		if err != nil {
			return nil, err
		}
Jeromy's avatar
Jeromy committed
175 176
	default:
		return nil, fmt.Errorf("unrecognized network: %s", rnet)
177 178 179 180
	}

	// get local address (pre-specified or assigned within net.Conn)
	local := d.LocalAddr
Cole Brown's avatar
Cole Brown committed
181 182 183
	// This block helps us avoid parsing addresses in transports (such as unix
	// sockets) that don't have local addresses when dialing out.
	if local == nil && nconn.LocalAddr().String() != "" {
184 185 186 187 188
		local, err = FromNetAddr(nconn.LocalAddr())
		if err != nil {
			return nil, err
		}
	}
189
	return wrap(nconn, local, remote), nil
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
}

// Dial connects to a remote address. It uses an underlying net.Conn,
// then wraps it in a Conn object (with local and remote Multiaddrs).
func Dial(remote ma.Multiaddr) (Conn, error) {
	return (&Dialer{}).Dial(remote)
}

// A Listener is a generic network listener for stream-oriented protocols.
// it uses an embedded net.Listener, overriding net.Listener.Accept to
// return a Conn and providing Multiaddr.
type Listener interface {
	// Accept waits for and returns the next connection to the listener.
	// Returns a Multiaddr friendly Conn
	Accept() (Conn, error)

	// Close closes the listener.
	// Any blocked Accept operations will be unblocked and return errors.
	Close() error

	// Multiaddr returns the listener's (local) Multiaddr.
	Multiaddr() ma.Multiaddr

	// Addr returns the net.Listener's network address.
	Addr() net.Addr
}

217 218 219 220 221 222 223 224 225 226
type netListenerAdapter struct {
	Listener
}

func (nla *netListenerAdapter) Accept() (net.Conn, error) {
	return nla.Listener.Accept()
}

// NetListener turns this Listener into a net.Listener.
//
web3-bot's avatar
web3-bot committed
227 228 229
//   - Connections returned from Accept implement multiaddr/net Conn.
//   - Calling WrapNetListener on the net.Listener returned by this function will
//     return the original (underlying) multiaddr/net Listener.
230 231 232 233
func NetListener(l Listener) net.Listener {
	return &netListenerAdapter{l}
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247
// maListener implements Listener
type maListener struct {
	net.Listener
	laddr ma.Multiaddr
}

// Accept waits for and returns the next connection to the listener.
// Returns a Multiaddr friendly Conn
func (l *maListener) Accept() (Conn, error) {
	nconn, err := l.Listener.Accept()
	if err != nil {
		return nil, err
	}

Cole Brown's avatar
Cole Brown committed
248 249 250
	var raddr ma.Multiaddr
	// This block protects us in transports (i.e. unix sockets) that don't have
	// remote addresses for inbound connections.
251 252
	if addr := nconn.RemoteAddr(); addr != nil && addr.String() != "" {
		raddr, err = FromNetAddr(addr)
Cole Brown's avatar
Cole Brown committed
253 254 255
		if err != nil {
			return nil, fmt.Errorf("failed to convert conn.RemoteAddr: %s", err)
		}
256 257
	}

aarshkshah1992's avatar
aarshkshah1992 committed
258
	var laddr ma.Multiaddr
259 260
	if addr := nconn.LocalAddr(); addr != nil && addr.String() != "" {
		laddr, err = FromNetAddr(addr)
aarshkshah1992's avatar
aarshkshah1992 committed
261 262 263 264 265 266
		if err != nil {
			return nil, fmt.Errorf("failed to convert conn.LocalAddr: %s", err)
		}
	}

	return wrap(nconn, laddr, raddr), nil
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
}

// Multiaddr returns the listener's (local) Multiaddr.
func (l *maListener) Multiaddr() ma.Multiaddr {
	return l.laddr
}

// Addr returns the listener's network address.
func (l *maListener) Addr() net.Addr {
	return l.Listener.Addr()
}

// Listen announces on the local network address laddr.
// The Multiaddr must be a "ThinWaist" stream-oriented network:
// ip4/tcp, ip6/tcp, (TODO: unix, unixpacket)
// See Dial for the syntax of laddr.
func Listen(laddr ma.Multiaddr) (Listener, error) {

	// get the net.Listen friendly arguments from the remote addr
	lnet, lnaddr, err := DialArgs(laddr)
	if err != nil {
		return nil, err
	}

291
	nl, err := net.Listen(lnet, lnaddr)
292 293
	if err != nil {
		return nil, err
294 295
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296 297 298 299 300 301 302
	// we want to fetch the new multiaddr from the listener, as it may
	// have resolved to some other value. WrapNetListener does it for us.
	return WrapNetListener(nl)
}

// WrapNetListener wraps a net.Listener with a manet.Listener.
func WrapNetListener(nl net.Listener) (Listener, error) {
303 304 305 306
	if nla, ok := nl.(*netListenerAdapter); ok {
		return nla.Listener, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307
	laddr, err := FromNetAddr(nl.Addr())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
308 309 310 311
	if err != nil {
		return nil, err
	}

312 313 314 315 316
	return &maListener{
		Listener: nl,
		laddr:    laddr,
	}, nil
}
317

318 319 320
// A PacketConn is a generic packet oriented network connection which uses an
// underlying net.PacketConn, wrapped with the locally bound Multiaddr.
type PacketConn interface {
321
	net.PacketConn
322

323
	LocalMultiaddr() ma.Multiaddr
324

325 326
	ReadFromMultiaddr(b []byte) (int, ma.Multiaddr, error)
	WriteToMultiaddr(b []byte, maddr ma.Multiaddr) (int, error)
327 328 329 330 331 332 333 334
}

// maPacketConn implements PacketConn
type maPacketConn struct {
	net.PacketConn
	laddr ma.Multiaddr
}

335
var _ PacketConn = (*maPacketConn)(nil)
336

337 338
// LocalMultiaddr returns the bound local Multiaddr.
func (l *maPacketConn) LocalMultiaddr() ma.Multiaddr {
339 340 341
	return l.laddr
}

342 343
func (l *maPacketConn) ReadFromMultiaddr(b []byte) (int, ma.Multiaddr, error) {
	n, addr, err := l.ReadFrom(b)
344 345 346 347
	maddr, _ := FromNetAddr(addr)
	return n, maddr, err
}

348
func (l *maPacketConn) WriteToMultiaddr(b []byte, maddr ma.Multiaddr) (int, error) {
349 350 351 352
	addr, err := ToNetAddr(maddr)
	if err != nil {
		return 0, err
	}
353
	return l.WriteTo(b, addr)
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
}

// ListenPacket announces on the local network address laddr.
// The Multiaddr must be a packet driven network, like udp4 or udp6.
// See Dial for the syntax of laddr.
func ListenPacket(laddr ma.Multiaddr) (PacketConn, error) {
	lnet, lnaddr, err := DialArgs(laddr)
	if err != nil {
		return nil, err
	}

	pc, err := net.ListenPacket(lnet, lnaddr)
	if err != nil {
		return nil, err
	}

	// We want to fetch the new multiaddr from the listener, as it may
	// have resolved to some other value. WrapPacketConn does this.
	return WrapPacketConn(pc)
}

// WrapPacketConn wraps a net.PacketConn with a manet.PacketConn.
func WrapPacketConn(pc net.PacketConn) (PacketConn, error) {
	laddr, err := FromNetAddr(pc.LocalAddr())
	if err != nil {
		return nil, err
	}

	return &maPacketConn{
		PacketConn: pc,
		laddr:      laddr,
	}, nil
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
// InterfaceMultiaddrs will return the addresses matching net.InterfaceAddrs
func InterfaceMultiaddrs() ([]ma.Multiaddr, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, err
	}

	maddrs := make([]ma.Multiaddr, len(addrs))
	for i, a := range addrs {
		maddrs[i], err = FromNetAddr(a)
		if err != nil {
			return nil, err
		}
	}
	return maddrs, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

// AddrMatch returns the Multiaddrs that match the protocol stack on addr
func AddrMatch(match ma.Multiaddr, addrs []ma.Multiaddr) []ma.Multiaddr {

	// we should match transports entirely.
	p1s := match.Protocols()

	out := make([]ma.Multiaddr, 0, len(addrs))
	for _, a := range addrs {
		p2s := a.Protocols()
		if len(p1s) != len(p2s) {
			continue
		}

		match := true
		for i, p2 := range p2s {
			if p1s[i].Code != p2.Code {
				match = false
				break
			}
		}
		if match {
			out = append(out, a)
		}
	}
	return out
}