listener.go 1.2 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
43
44
45
46
	c, err := l.quicListener.Accept()
	if err != nil {
		return nil, err
	}
	return &conn{
		quicConn:  c,
		transport: l.transport,
	}, nil
Marten Seemann's avatar
Marten Seemann committed
47
48
49
}

func (l *listener) Close() error {
Marten Seemann's avatar
Marten Seemann committed
50
	return l.quicListener.Close()
Marten Seemann's avatar
Marten Seemann committed
51
52
53
}

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

func (l *listener) Multiaddr() ma.Multiaddr {
Marten Seemann's avatar
Marten Seemann committed
58
	return l.laddr
Marten Seemann's avatar
Marten Seemann committed
59
60
61
}

var _ tpt.Listener = &listener{}