-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathquic.go
92 lines (81 loc) · 1.72 KB
/
quic.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
package main
import (
"crypto/tls"
"github.com/quic-go/quic-go"
"golang.org/x/net/context"
"net"
"runtime"
"sync/atomic"
)
type QuicDialer struct {
NextProtos []string
streams atomic.Uint32
c quic.Connection
}
func NewQuicDialer(nextProtos []string) *QuicDialer {
return &QuicDialer{
NextProtos: nextProtos,
}
}
const maxStreams = 32
func (d *QuicDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
now := d.streams.Add(1)
if now > maxStreams {
// wait for dialing
for {
if d.streams.Load() < maxStreams {
break
}
runtime.Gosched()
}
return d.DialContext(ctx, network, address)
}
if now == maxStreams || now == 1 {
c, err := quic.DialAddr(ctx, address, &tls.Config{
InsecureSkipVerify: true,
NextProtos: d.NextProtos,
}, nil)
if err != nil {
d.streams.Store(0)
return nil, err
}
d.c = c
d.streams.Store(1)
}
if d.c == nil {
// still in initial dialing
return d.DialContext(ctx, network, address)
}
s, err := d.c.OpenStreamSync(ctx)
if err != nil {
// dial a new connection in next time
d.streams.Store(0)
return nil, err
}
return NewStream(s, d.c.LocalAddr(), d.c.RemoteAddr()), nil
}
func (d *QuicDialer) Dial(network, address string) (net.Conn, error) {
return d.DialContext(context.Background(), network, address)
}
type Stream struct {
quic.Stream
lAddr net.Addr
rAddr net.Addr
}
func NewStream(s quic.Stream, lAddr, rAddr net.Addr) net.Conn {
return &Stream{
Stream: s,
lAddr: lAddr,
rAddr: rAddr,
}
}
func (s *Stream) LocalAddr() net.Addr {
return s.lAddr
}
func (s *Stream) RemoteAddr() net.Addr {
return s.rAddr
}
func (s *Stream) Close() error {
s.CancelRead(0)
return s.Stream.Close()
}