listener.go 1.33 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
	testdata "github.com/lucas-clemente/quic-go/testdata"
Marten Seemann's avatar
Marten Seemann committed
8
	quicconn "github.com/marten-seemann/quic-conn"
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
15
16
17
18
19
type listener struct {
	laddr        ma.Multiaddr
	quicListener net.Listener

	transport tpt.Transport
}

20
func newListener(laddr ma.Multiaddr, transport tpt.Transport) (*listener, error) {
21
22
23
	// we need to provide a certificate here
	// use the demo certificate from quic-go
	tlsConf := testdata.GetTLSConfig()
Marten Seemann's avatar
Marten Seemann committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	network, host, err := manet.DialArgs(laddr)
	if err != nil {
		return nil, err
	}
	qln, err := quicconn.Listen(network, host, tlsConf)
	if err != nil {
		return nil, err
	}
	return &listener{
		laddr:        laddr,
		quicListener: qln,
		transport:    transport,
	}, nil
}
Marten Seemann's avatar
Marten Seemann committed
38
39

func (l *listener) Accept() (tpt.Conn, error) {
Marten Seemann's avatar
Marten Seemann committed
40
41
42
43
	c, err := l.quicListener.Accept()
	if err != nil {
		return nil, err
	}
44
45
46
47
48
49
50
51
52

	mnc, err := manet.WrapNetConn(c)
	if err != nil {
		return nil, err
	}

	return &tpt.ConnWrap{
		Conn: mnc,
		Tpt:  l.transport,
Marten Seemann's avatar
Marten Seemann committed
53
	}, nil
Marten Seemann's avatar
Marten Seemann committed
54
55
56
}

func (l *listener) Close() error {
Marten Seemann's avatar
Marten Seemann committed
57
	return l.quicListener.Close()
Marten Seemann's avatar
Marten Seemann committed
58
59
60
}

func (l *listener) Addr() net.Addr {
Marten Seemann's avatar
Marten Seemann committed
61
	return l.quicListener.Addr()
Marten Seemann's avatar
Marten Seemann committed
62
63
64
}

func (l *listener) Multiaddr() ma.Multiaddr {
Marten Seemann's avatar
Marten Seemann committed
65
	return l.laddr
Marten Seemann's avatar
Marten Seemann committed
66
67
68
}

var _ tpt.Listener = &listener{}