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

import (
4
	"context"
Steven Allen's avatar
Steven Allen committed
5
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
Steven Allen's avatar
Steven Allen committed
7
	"sync"
8 9
	"sync/atomic"
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10

tavit ohanian's avatar
tavit ohanian committed
11 12 13 14 15
	ic "gitlab.dms3.io/p2p/go-p2p-core/crypto"
	"gitlab.dms3.io/p2p/go-p2p-core/mux"
	"gitlab.dms3.io/p2p/go-p2p-core/network"
	"gitlab.dms3.io/p2p/go-p2p-core/peer"
	"gitlab.dms3.io/p2p/go-p2p-core/transport"
16

17
	ma "gitlab.dms3.io/mf/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
)

Steven Allen's avatar
Steven Allen committed
20 21 22 23 24 25 26 27
// 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 {
Steven Allen's avatar
Steven Allen committed
28
	id    uint64
29
	conn  transport.CapableConn
Steven Allen's avatar
Steven Allen committed
30 31 32 33 34 35 36 37 38 39 40
	swarm *Swarm

	closeOnce sync.Once
	err       error

	notifyLk sync.Mutex

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

42
	stat network.Stat
Steven Allen's avatar
Steven Allen committed
43 44
}

45 46 47 48 49
func (c *Conn) ID() string {
	// format: <first 10 chars of peer id>-<global conn ordinal>
	return fmt.Sprintf("%s-%d", c.RemotePeer().Pretty()[0:10], c.id)
}

Steven Allen's avatar
Steven Allen committed
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
// 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()

84
		c.swarm.notifyAll(func(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
85 86 87 88
			f.Disconnected(c.swarm, c)
		})
		c.swarm.refs.Done() // taken in Swarm.addConn
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
}

91
func (c *Conn) removeStream(s *Stream) {
Steven Allen's avatar
Steven Allen committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
	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() {
113
				s, err := c.addStream(ts, network.DirInbound)
Steven Allen's avatar
Steven Allen committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

				// 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
130 131 132
}

func (c *Conn) String() string {
Steven Allen's avatar
Steven Allen committed
133
	return fmt.Sprintf(
134
		"<swarm.Conn[%T] %s (%s) <-> %s (%s)>",
Steven Allen's avatar
Steven Allen committed
135 136 137 138 139 140
		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
141 142 143 144
}

// LocalMultiaddr is the Multiaddr on this side
func (c *Conn) LocalMultiaddr() ma.Multiaddr {
Steven Allen's avatar
Steven Allen committed
145
	return c.conn.LocalMultiaddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148 149
}

// LocalPeer is the Peer on our side of the connection
func (c *Conn) LocalPeer() peer.ID {
Steven Allen's avatar
Steven Allen committed
150
	return c.conn.LocalPeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152 153 154
}

// RemoteMultiaddr is the Multiaddr on the remote side
func (c *Conn) RemoteMultiaddr() ma.Multiaddr {
Steven Allen's avatar
Steven Allen committed
155
	return c.conn.RemoteMultiaddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157 158 159
}

// RemotePeer is the Peer on the remote side
func (c *Conn) RemotePeer() peer.ID {
Steven Allen's avatar
Steven Allen committed
160
	return c.conn.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161 162 163 164
}

// LocalPrivateKey is the public key of the peer on this side
func (c *Conn) LocalPrivateKey() ic.PrivKey {
Steven Allen's avatar
Steven Allen committed
165
	return c.conn.LocalPrivateKey()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167 168 169
}

// 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
170
	return c.conn.RemotePublicKey()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171 172
}

173
// Stat returns metadata pertaining to this connection
174
func (c *Conn) Stat() network.Stat {
175 176 177
	return c.stat
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178
// NewStream returns a new Stream from this connection
179
func (c *Conn) NewStream(ctx context.Context) (network.Stream, error) {
Aarsh Shah's avatar
Aarsh Shah committed
180 181 182 183 184 185
	if c.Stat().Transient {
		if useTransient, _ := network.GetUseTransient(ctx); !useTransient {
			return nil, network.ErrTransientConn
		}
	}

186
	ts, err := c.conn.OpenStream(ctx)
187

Steven Allen's avatar
Steven Allen committed
188 189 190
	if err != nil {
		return nil, err
	}
191
	return c.addStream(ts, network.DirOutbound)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193
}

194
func (c *Conn) addStream(ts mux.MuxedStream, dir network.Direction) (*Stream, error) {
Steven Allen's avatar
Steven Allen committed
195 196 197 198 199 200
	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
201
	}
202

Steven Allen's avatar
Steven Allen committed
203
	// Wrap and register the stream.
204 205 206 207
	stat := network.Stat{
		Direction: dir,
		Opened:    time.Now(),
	}
Steven Allen's avatar
Steven Allen committed
208 209 210
	s := &Stream{
		stream: ts,
		conn:   c,
211
		stat:   stat,
Steven Allen's avatar
Steven Allen committed
212
		id:     atomic.AddUint64(&c.swarm.nextStreamID, 1),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
	}
Steven Allen's avatar
Steven Allen committed
214 215 216 217 218 219 220 221 222 223 224 225
	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()

226
	c.swarm.notifyAll(func(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
227 228 229 230 231
		f.OpenedStream(c.swarm, s)
	})
	s.notifyLk.Unlock()

	return s, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233
}

Steven Allen's avatar
Steven Allen committed
234
// GetStreams returns the streams associated with this connection.
235
func (c *Conn) GetStreams() []network.Stream {
Steven Allen's avatar
Steven Allen committed
236 237
	c.streams.Lock()
	defer c.streams.Unlock()
238
	streams := make([]network.Stream, 0, len(c.streams.m))
Steven Allen's avatar
Steven Allen committed
239 240
	for s := range c.streams.m {
		streams = append(streams, s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
	}
Steven Allen's avatar
Steven Allen committed
242
	return streams
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243
}