listener.go 1.23 KB
Newer Older
Marten Seemann's avatar
Marten Seemann committed
1
2
3
4
5
6
package libp2pquic

import (
	"net"

	tpt "github.com/libp2p/go-libp2p-transport"
7
	quic "github.com/lucas-clemente/quic-go"
8
	testdata "github.com/lucas-clemente/quic-go/testdata"
Marten Seemann's avatar
Marten Seemann committed
9
	ma "github.com/multiformats/go-multiaddr"
Marten Seemann's avatar
Marten Seemann committed
10
	manet "github.com/multiformats/go-multiaddr-net"
Marten Seemann's avatar
Marten Seemann committed
11
12
)

Marten Seemann's avatar
Marten Seemann committed
13
14
type listener struct {
	laddr        ma.Multiaddr
15
	quicListener quic.Listener
Marten Seemann's avatar
Marten Seemann committed
16
17
18
19

	transport tpt.Transport
}

20
21
22
23
24
25
26
27
28
29
var _ tpt.Listener = &listener{}

func newListener(laddr ma.Multiaddr, t tpt.Transport) (*listener, error) {
	qconf := &quic.Config{
		// we need to provide a certificate here
		// use the demo certificate from quic-go
		TLSConfig: testdata.GetTLSConfig(),
	}

	_, host, err := manet.DialArgs(laddr)
Marten Seemann's avatar
Marten Seemann committed
30
31
32
	if err != nil {
		return nil, err
	}
33
	qln, err := quic.ListenAddr(host, qconf)
Marten Seemann's avatar
Marten Seemann committed
34
35
36
	if err != nil {
		return nil, err
	}
37

Marten Seemann's avatar
Marten Seemann committed
38
39
40
	return &listener{
		laddr:        laddr,
		quicListener: qln,
41
		transport:    t,
Marten Seemann's avatar
Marten Seemann committed
42
43
	}, nil
}
Marten Seemann's avatar
Marten Seemann committed
44
45

func (l *listener) Accept() (tpt.Conn, error) {
46
	sess, err := l.quicListener.Accept()
Marten Seemann's avatar
Marten Seemann committed
47
48
49
	if err != nil {
		return nil, err
	}
50
	return newQuicConn(sess, l.transport)
Marten Seemann's avatar
Marten Seemann committed
51
52
53
}

func (l *listener) Close() error {
Marten Seemann's avatar
Marten Seemann committed
54
	return l.quicListener.Close()
Marten Seemann's avatar
Marten Seemann committed
55
56
57
}

func (l *listener) Addr() net.Addr {
Marten Seemann's avatar
Marten Seemann committed
58
	return l.quicListener.Addr()
Marten Seemann's avatar
Marten Seemann committed
59
60
61
}

func (l *listener) Multiaddr() ma.Multiaddr {
Marten Seemann's avatar
Marten Seemann committed
62
	return l.laddr
Marten Seemann's avatar
Marten Seemann committed
63
}