-
Notifications
You must be signed in to change notification settings - Fork 0
/
inbound.go
276 lines (232 loc) · 7.1 KB
/
inbound.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package inbound
import (
"io"
"sync"
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/app/dispatcher"
"github.com/v2ray/v2ray-core/app/proxyman"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/uuid"
"github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/proxy/internal"
"github.com/v2ray/v2ray-core/proxy/vmess"
"github.com/v2ray/v2ray-core/proxy/vmess/encoding"
vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
"github.com/v2ray/v2ray-core/transport/internet"
)
type userByEmail struct {
sync.RWMutex
cache map[string]*protocol.User
defaultLevel protocol.UserLevel
defaultAlterIDs uint16
}
func NewUserByEmail(users []*protocol.User, config *DefaultConfig) *userByEmail {
cache := make(map[string]*protocol.User)
for _, user := range users {
cache[user.Email] = user
}
return &userByEmail{
cache: cache,
defaultLevel: config.Level,
defaultAlterIDs: config.AlterIDs,
}
}
func (this *userByEmail) Get(email string) (*protocol.User, bool) {
var user *protocol.User
var found bool
this.RLock()
user, found = this.cache[email]
this.RUnlock()
if !found {
this.Lock()
user, found = this.cache[email]
if !found {
id := protocol.NewID(uuid.New())
alterIDs := protocol.NewAlterIDs(id, this.defaultAlterIDs)
account := &vmess.Account{
ID: id,
AlterIDs: alterIDs,
}
user = protocol.NewUser(this.defaultLevel, email)
user.Account = account
this.cache[email] = user
}
this.Unlock()
}
return user, found
}
// Inbound connection handler that handles messages in VMess format.
type VMessInboundHandler struct {
sync.RWMutex
packetDispatcher dispatcher.PacketDispatcher
inboundHandlerManager proxyman.InboundHandlerManager
clients protocol.UserValidator
usersByEmail *userByEmail
accepting bool
listener *internet.TCPHub
detours *DetourConfig
meta *proxy.InboundHandlerMeta
}
func (this *VMessInboundHandler) Port() v2net.Port {
return this.meta.Port
}
func (this *VMessInboundHandler) Close() {
this.accepting = false
if this.listener != nil {
this.Lock()
this.listener.Close()
this.listener = nil
this.clients.Release()
this.clients = nil
this.Unlock()
}
}
func (this *VMessInboundHandler) GetUser(email string) *protocol.User {
this.RLock()
defer this.RUnlock()
if !this.accepting {
return nil
}
user, existing := this.usersByEmail.Get(email)
if !existing {
this.clients.Add(user)
}
return user
}
func (this *VMessInboundHandler) Start() error {
if this.accepting {
return nil
}
tcpListener, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.HandleConnection, this.meta.StreamSettings)
if err != nil {
log.Error("VMess|Inbound: Unable to listen tcp ", this.meta.Address, ":", this.meta.Port, ": ", err)
return err
}
this.accepting = true
this.Lock()
this.listener = tcpListener
this.Unlock()
return nil
}
func (this *VMessInboundHandler) HandleConnection(connection internet.Connection) {
defer connection.Close()
if !this.accepting {
return
}
connReader := v2net.NewTimeOutReader(8, connection)
defer connReader.Release()
reader := v2io.NewBufferedReader(connReader)
defer reader.Release()
this.RLock()
if !this.accepting {
this.RUnlock()
return
}
session := encoding.NewServerSession(this.clients)
defer session.Release()
request, err := session.DecodeRequestHeader(reader)
this.RUnlock()
if err != nil {
if err != io.EOF {
log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
}
connection.SetReusable(false)
return
}
log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
log.Info("VMessIn: Received request for ", request.Destination())
connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse))
ray := this.packetDispatcher.DispatchToOutbound(request.Destination())
input := ray.InboundInput()
output := ray.InboundOutput()
defer input.Close()
defer output.Release()
var readFinish sync.Mutex
readFinish.Lock()
userSettings := protocol.GetUserSettings(request.User.Level)
connReader.SetTimeOut(userSettings.PayloadReadTimeout)
reader.SetCached(false)
go func() {
bodyReader := session.DecodeRequestBody(reader)
var requestReader v2io.Reader
if request.Option.Has(protocol.RequestOptionChunkStream) {
requestReader = vmessio.NewAuthChunkReader(bodyReader)
} else {
requestReader = v2io.NewAdaptiveReader(bodyReader)
}
err := v2io.Pipe(requestReader, input)
if err != io.EOF {
connection.SetReusable(false)
}
requestReader.Release()
input.Close()
readFinish.Unlock()
}()
writer := v2io.NewBufferedWriter(connection)
defer writer.Release()
response := &protocol.ResponseHeader{
Command: this.generateCommand(request),
}
if connection.Reusable() {
response.Option.Set(protocol.ResponseOptionConnectionReuse)
}
session.EncodeResponseHeader(response, writer)
bodyWriter := session.EncodeResponseBody(writer)
var v2writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
if request.Option.Has(protocol.RequestOptionChunkStream) {
v2writer = vmessio.NewAuthChunkWriter(v2writer)
}
// Optimize for small response packet
if data, err := output.Read(); err == nil {
if err := v2writer.Write(data); err != nil {
connection.SetReusable(false)
}
writer.SetCached(false)
err = v2io.Pipe(output, v2writer)
if err != io.EOF {
connection.SetReusable(false)
}
}
output.Release()
if request.Option.Has(protocol.RequestOptionChunkStream) {
if err := v2writer.Write(alloc.NewLocalBuffer(32).Clear()); err != nil {
connection.SetReusable(false)
}
}
writer.Flush()
v2writer.Release()
readFinish.Lock()
}
type Factory struct{}
func (this *Factory) StreamCapability() internet.StreamConnectionType {
return internet.StreamConnectionTypeRawTCP | internet.StreamConnectionTypeTCP | internet.StreamConnectionTypeKCP
}
func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
if !space.HasApp(dispatcher.APP_ID) {
return nil, internal.ErrBadConfiguration
}
config := rawConfig.(*Config)
allowedClients := vmess.NewTimedUserValidator(protocol.DefaultIDHash)
for _, user := range config.AllowedUsers {
allowedClients.Add(user)
}
handler := &VMessInboundHandler{
packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
clients: allowedClients,
detours: config.DetourConfig,
usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
meta: meta,
}
if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
}
return handler, nil
}
func init() {
internal.MustRegisterInboundHandlerCreator("vmess", new(Factory))
}