listener.go 1.27 KB
Newer Older
Marten Seemann's avatar
Marten Seemann committed
1
2
3
package libp2pquic

import (
Marten Seemann's avatar
Marten Seemann committed
4
	"crypto/tls"
Marten Seemann's avatar
Marten Seemann committed
5
6
	"net"

Marten Seemann's avatar
Marten Seemann committed
7
	pstore "github.com/libp2p/go-libp2p-peerstore"
Marten Seemann's avatar
Marten Seemann committed
8
	tpt "github.com/libp2p/go-libp2p-transport"
Marten Seemann's avatar
Marten Seemann committed
9
	quicconn "github.com/marten-seemann/quic-conn"
Marten Seemann's avatar
Marten Seemann committed
10
	ma "github.com/multiformats/go-multiaddr"
Marten Seemann's avatar
Marten Seemann committed
11
	manet "github.com/multiformats/go-multiaddr-net"
Marten Seemann's avatar
Marten Seemann committed
12
13
)

Marten Seemann's avatar
Marten Seemann committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
type listener struct {
	laddr        ma.Multiaddr
	quicListener net.Listener

	transport tpt.Transport
}

func newListener(laddr ma.Multiaddr, peers pstore.Peerstore, transport tpt.Transport) (*listener, error) {
	tlsConf := &tls.Config{}
	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
37
38

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

	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
52
	}, nil
Marten Seemann's avatar
Marten Seemann committed
53
54
55
}

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

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

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

var _ tpt.Listener = &listener{}