-
Notifications
You must be signed in to change notification settings - Fork 10
/
session.go
115 lines (99 loc) · 2.32 KB
/
session.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package mux
import (
"io"
"net"
"reflect"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/smux"
"github.com/hashicorp/yamux"
)
type abstractSession interface {
Open() (net.Conn, error)
Accept() (net.Conn, error)
NumStreams() int
Close() error
IsClosed() bool
CanTakeNewRequest() bool
}
func newClientSession(conn net.Conn, protocol byte) (abstractSession, error) {
switch protocol {
case ProtocolH2Mux:
session, err := newH2MuxClient(conn)
if err != nil {
return nil, err
}
return session, nil
case ProtocolSmux:
client, err := smux.Client(conn, smuxConfig())
if err != nil {
return nil, err
}
return &smuxSession{client}, nil
case ProtocolYAMux:
checkYAMuxConn(conn)
client, err := yamux.Client(conn, yaMuxConfig())
if err != nil {
return nil, err
}
return &yamuxSession{client}, nil
default:
return nil, E.New("unexpected protocol ", protocol)
}
}
func newServerSession(conn net.Conn, protocol byte) (abstractSession, error) {
switch protocol {
case ProtocolH2Mux:
return newH2MuxServer(conn), nil
case ProtocolSmux:
client, err := smux.Server(conn, smuxConfig())
if err != nil {
return nil, err
}
return &smuxSession{client}, nil
case ProtocolYAMux:
checkYAMuxConn(conn)
client, err := yamux.Server(conn, yaMuxConfig())
if err != nil {
return nil, err
}
return &yamuxSession{client}, nil
default:
return nil, E.New("unexpected protocol ", protocol)
}
}
func checkYAMuxConn(conn net.Conn) {
if conn.LocalAddr() == nil || conn.RemoteAddr() == nil {
panic("found net.Conn with nil addr: " + reflect.TypeOf(conn).String())
}
}
var _ abstractSession = (*smuxSession)(nil)
type smuxSession struct {
*smux.Session
}
func (s *smuxSession) Open() (net.Conn, error) {
return s.OpenStream()
}
func (s *smuxSession) Accept() (net.Conn, error) {
return s.AcceptStream()
}
func (s *smuxSession) CanTakeNewRequest() bool {
return true
}
type yamuxSession struct {
*yamux.Session
}
func (y *yamuxSession) CanTakeNewRequest() bool {
return true
}
func smuxConfig() *smux.Config {
config := smux.DefaultConfig()
config.KeepAliveDisabled = true
return config
}
func yaMuxConfig() *yamux.Config {
config := yamux.DefaultConfig()
config.LogOutput = io.Discard
config.StreamCloseTimeout = TCPTimeout
config.StreamOpenTimeout = TCPTimeout
return config
}