swarm_conn.go 4.78 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package swarm

import (
Steven Allen's avatar
Steven Allen committed
4
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"fmt"
Steven Allen's avatar
Steven Allen committed
6
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7

Jeromy's avatar
Jeromy committed
8 9 10
	ic "github.com/libp2p/go-libp2p-crypto"
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
Steven Allen's avatar
Steven Allen committed
11 12
	transport "github.com/libp2p/go-libp2p-transport"
	smux "github.com/libp2p/go-stream-muxer"
Jeromy's avatar
Jeromy committed
13
	ma "github.com/multiformats/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15
)

Steven Allen's avatar
Steven Allen committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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
// TODO: Put this elsewhere.

// ErrConnClosed is returned when operating on a closed connection.
var ErrConnClosed = errors.New("connection closed")

// Conn is the connection type used by swarm. In general, you won't use this
// type directly.
type Conn struct {
	conn  transport.Conn
	swarm *Swarm

	closeOnce sync.Once
	err       error

	notifyLk sync.Mutex

	streams struct {
		sync.Mutex
		m map[*Stream]struct{}
	}
}

// Close closes this connection.
//
// Note: This method won't wait for the close notifications to finish as that
// would create a deadlock when called from an open notification (because all
// open notifications must finish before we can fire off the close
// notifications).
func (c *Conn) Close() error {
	c.closeOnce.Do(c.doClose)
	return c.err
}

func (c *Conn) doClose() {
	c.swarm.removeConn(c)

	// Prevent new streams from opening.
	c.streams.Lock()
	streams := c.streams.m
	c.streams.m = nil
	c.streams.Unlock()

	c.err = c.conn.Close()

	// This is just for cleaning up state. The connection has already been closed.
	// We *could* optimize this but it really isn't worth it.
	for s := range streams {
		s.Reset()
	}

	// do this in a goroutine to avoid deadlocking if we call close in an open notification.
	go func() {
		// prevents us from issuing close notifications before finishing the open notifications
		c.notifyLk.Lock()
		defer c.notifyLk.Unlock()

		c.swarm.notifyAll(func(f inet.Notifiee) {
			f.Disconnected(c.swarm, c)
		})
		c.swarm.refs.Done() // taken in Swarm.addConn
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78
}

Steven Allen's avatar
Steven Allen committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
func (c *Conn) removeStream(s *Stream) {
	c.streams.Lock()
	delete(c.streams.m, s)
	c.streams.Unlock()
}

// listens for new streams.
//
// The caller must take a swarm ref before calling. This function decrements the
// swarm ref count.
func (c *Conn) start() {
	go func() {
		defer c.swarm.refs.Done()
		defer c.Close()

		for {
			ts, err := c.conn.AcceptStream()
			if err != nil {
				return
			}
			c.swarm.refs.Add(1)
			go func() {
				s, err := c.addStream(ts)

				// Don't defer this. We don't want to block
				// swarm shutdown on the connection handler.
				c.swarm.refs.Done()

				// We only get an error here when the swarm is closed or closing.
				if err != nil {
					return
				}

				if h := c.swarm.StreamHandler(); h != nil {
					h(s)
				}
			}()
		}
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119 120
}

func (c *Conn) String() string {
Steven Allen's avatar
Steven Allen committed
121 122 123 124 125 126 127 128
	return fmt.Sprintf(
		"<swarm.Conn[%s] %s (%s) <-> %s (%s)>",
		c.conn.Transport(),
		c.conn.LocalMultiaddr(),
		c.conn.LocalPeer().Pretty(),
		c.conn.RemoteMultiaddr(),
		c.conn.RemotePeer().Pretty(),
	)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130 131 132
}

// LocalMultiaddr is the Multiaddr on this side
func (c *Conn) LocalMultiaddr() ma.Multiaddr {
Steven Allen's avatar
Steven Allen committed
133
	return c.conn.LocalMultiaddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136 137
}

// LocalPeer is the Peer on our side of the connection
func (c *Conn) LocalPeer() peer.ID {
Steven Allen's avatar
Steven Allen committed
138
	return c.conn.LocalPeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140 141 142
}

// RemoteMultiaddr is the Multiaddr on the remote side
func (c *Conn) RemoteMultiaddr() ma.Multiaddr {
Steven Allen's avatar
Steven Allen committed
143
	return c.conn.RemoteMultiaddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145 146 147
}

// RemotePeer is the Peer on the remote side
func (c *Conn) RemotePeer() peer.ID {
Steven Allen's avatar
Steven Allen committed
148
	return c.conn.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150 151 152
}

// LocalPrivateKey is the public key of the peer on this side
func (c *Conn) LocalPrivateKey() ic.PrivKey {
Steven Allen's avatar
Steven Allen committed
153
	return c.conn.LocalPrivateKey()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155 156 157
}

// RemotePublicKey is the public key of the peer on the remote side
func (c *Conn) RemotePublicKey() ic.PubKey {
Steven Allen's avatar
Steven Allen committed
158
	return c.conn.RemotePublicKey()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160 161 162
}

// NewStream returns a new Stream from this connection
func (c *Conn) NewStream() (inet.Stream, error) {
Steven Allen's avatar
Steven Allen committed
163 164 165 166 167
	ts, err := c.conn.OpenStream()
	if err != nil {
		return nil, err
	}
	return c.addStream(ts)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
}

Steven Allen's avatar
Steven Allen committed
170 171 172 173 174 175 176
func (c *Conn) addStream(ts smux.Stream) (*Stream, error) {
	c.streams.Lock()
	// Are we still online?
	if c.streams.m == nil {
		c.streams.Unlock()
		ts.Reset()
		return nil, ErrConnClosed
Jeromy's avatar
Jeromy committed
177
	}
178

Steven Allen's avatar
Steven Allen committed
179 180 181 182
	// Wrap and register the stream.
	s := &Stream{
		stream: ts,
		conn:   c,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
	}
Steven Allen's avatar
Steven Allen committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	c.streams.m[s] = struct{}{}

	// Released once the stream disconnect notifications have finished
	// firing (in Swarm.remove).
	c.swarm.refs.Add(1)

	// Take the notification lock before releasing the streams lock to block
	// StreamClose notifications until after the StreamOpen notifications
	// done.
	s.notifyLk.Lock()
	c.streams.Unlock()

	c.swarm.notifyAll(func(f inet.Notifiee) {
		f.OpenedStream(c.swarm, s)
	})
	s.notifyLk.Unlock()

	return s, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203
}

Steven Allen's avatar
Steven Allen committed
204 205 206 207 208 209 210
// GetStreams returns the streams associated with this connection.
func (c *Conn) GetStreams() []inet.Stream {
	c.streams.Lock()
	defer c.streams.Unlock()
	streams := make([]inet.Stream, 0, len(c.streams.m))
	for s := range c.streams.m {
		streams = append(streams, s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211
	}
Steven Allen's avatar
Steven Allen committed
212
	return streams
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
}