forked from libp2p/go-libp2p
/
conn.go
109 lines (87 loc) · 2.54 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
77
78
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
package libp2pquic
import (
"context"
"net"
ic "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
tpt "github.com/libp2p/go-libp2p/core/transport"
"github.com/lucas-clemente/quic-go"
ma "github.com/multiformats/go-multiaddr"
)
type pConn interface {
net.PacketConn
// count conn reference
DecreaseCount()
IncreaseCount()
}
type conn struct {
quicConn quic.Connection
pconn pConn
transport *transport
scope network.ConnManagementScope
localPeer peer.ID
privKey ic.PrivKey
localMultiaddr ma.Multiaddr
remotePeerID peer.ID
remotePubKey ic.PubKey
remoteMultiaddr ma.Multiaddr
}
var _ tpt.CapableConn = &conn{}
// Close closes the connection.
// It must be called even if the peer closed the connection in order for
// garbage collection to properly work in this package.
func (c *conn) Close() error {
c.transport.removeConn(c.quicConn)
err := c.quicConn.CloseWithError(0, "")
c.pconn.DecreaseCount()
c.scope.Done()
return err
}
// IsClosed returns whether a connection is fully closed.
func (c *conn) IsClosed() bool {
return c.quicConn.Context().Err() != nil
}
func (c *conn) allowWindowIncrease(size uint64) bool {
return c.scope.ReserveMemory(int(size), network.ReservationPriorityMedium) == nil
}
// OpenStream creates a new stream.
func (c *conn) OpenStream(ctx context.Context) (network.MuxedStream, error) {
qstr, err := c.quicConn.OpenStreamSync(ctx)
return &stream{Stream: qstr}, err
}
// AcceptStream accepts a stream opened by the other side.
func (c *conn) AcceptStream() (network.MuxedStream, error) {
qstr, err := c.quicConn.AcceptStream(context.Background())
return &stream{Stream: qstr}, err
}
// LocalPeer returns our peer ID
func (c *conn) LocalPeer() peer.ID {
return c.localPeer
}
// LocalPrivateKey returns our private key
func (c *conn) LocalPrivateKey() ic.PrivKey {
return c.privKey
}
// RemotePeer returns the peer ID of the remote peer.
func (c *conn) RemotePeer() peer.ID {
return c.remotePeerID
}
// RemotePublicKey returns the public key of the remote peer.
func (c *conn) RemotePublicKey() ic.PubKey {
return c.remotePubKey
}
// LocalMultiaddr returns the local Multiaddr associated
func (c *conn) LocalMultiaddr() ma.Multiaddr {
return c.localMultiaddr
}
// RemoteMultiaddr returns the remote Multiaddr associated
func (c *conn) RemoteMultiaddr() ma.Multiaddr {
return c.remoteMultiaddr
}
func (c *conn) Transport() tpt.Transport {
return c.transport
}
func (c *conn) Scope() network.ConnScope {
return c.scope
}