-
Notifications
You must be signed in to change notification settings - Fork 49
/
listener.go
91 lines (78 loc) · 1.56 KB
/
listener.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
package tls
import (
"context"
"net"
"sync"
)
type Listener struct {
net.Listener
config ServerConfig
}
func NewListener(inner net.Listener, config ServerConfig) net.Listener {
return &Listener{
Listener: inner,
config: config,
}
}
func (l *Listener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
return NewLazyConn(conn, l.config), nil
}
type LazyConn struct {
net.Conn
tlsConfig ServerConfig
access sync.Mutex
needHandshake bool
}
func NewLazyConn(conn net.Conn, config ServerConfig) *LazyConn {
return &LazyConn{
Conn: conn,
tlsConfig: config,
needHandshake: true,
}
}
func (c *LazyConn) HandshakeContext(ctx context.Context) error {
if !c.needHandshake {
return nil
}
c.access.Lock()
defer c.access.Unlock()
if c.needHandshake {
tlsConn, err := ServerHandshake(ctx, c.Conn, c.tlsConfig)
if err != nil {
return err
}
c.Conn = tlsConn
c.needHandshake = false
}
return nil
}
func (c *LazyConn) Read(p []byte) (n int, err error) {
err = c.HandshakeContext(context.Background())
if err != nil {
return
}
return c.Conn.Read(p)
}
func (c *LazyConn) Write(p []byte) (n int, err error) {
err = c.HandshakeContext(context.Background())
if err != nil {
return
}
return c.Conn.Write(p)
}
func (c *LazyConn) NeedHandshake() bool {
return c.needHandshake
}
func (c *LazyConn) ReaderReplaceable() bool {
return !c.needHandshake
}
func (c *LazyConn) WriterReplaceable() bool {
return !c.needHandshake
}
func (c *LazyConn) Upstream() any {
return c.Conn
}