-
Notifications
You must be signed in to change notification settings - Fork 0
/
inbound.go
280 lines (236 loc) · 7.57 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
277
278
279
280
package inbound
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg inbound -path Proxy,VMess,Inbound
import (
"context"
"io"
"runtime"
"sync"
"time"
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/common/signal"
"v2ray.com/core/common/uuid"
"v2ray.com/core/proxy/vmess"
"v2ray.com/core/proxy/vmess/encoding"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/ray"
)
type userByEmail struct {
sync.RWMutex
cache map[string]*protocol.User
defaultLevel uint32
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: uint16(config.AlterId),
}
}
func (v *userByEmail) Get(email string) (*protocol.User, bool) {
var user *protocol.User
var found bool
v.RLock()
user, found = v.cache[email]
v.RUnlock()
if !found {
v.Lock()
user, found = v.cache[email]
if !found {
account := &vmess.Account{
Id: uuid.New().String(),
AlterId: uint32(v.defaultAlterIDs),
}
user = &protocol.User{
Level: v.defaultLevel,
Email: email,
Account: serial.ToTypedMessage(account),
}
v.cache[email] = user
}
v.Unlock()
}
return user, found
}
// Handler is an inbound connection handler that handles messages in VMess protocol.
type Handler struct {
inboundHandlerManager proxyman.InboundHandlerManager
clients protocol.UserValidator
usersByEmail *userByEmail
detours *DetourConfig
sessionHistory *encoding.SessionHistory
}
func New(ctx context.Context, config *Config) (*Handler, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, newError("no space in context")
}
allowedClients := vmess.NewTimedUserValidator(ctx, protocol.DefaultIDHash)
for _, user := range config.User {
allowedClients.Add(user)
}
handler := &Handler{
clients: allowedClients,
detours: config.Detour,
usersByEmail: NewUserByEmail(config.User, config.GetDefaultValue()),
sessionHistory: encoding.NewSessionHistory(ctx),
}
space.OnInitialize(func() error {
handler.inboundHandlerManager = proxyman.InboundHandlerManagerFromSpace(space)
if handler.inboundHandlerManager == nil {
return newError("InboundHandlerManager is not found is space")
}
return nil
})
return handler, nil
}
// Network implements proxy.Inbound.Network().
func (*Handler) Network() net.NetworkList {
return net.NetworkList{
Network: []net.Network{net.Network_TCP},
}
}
func (v *Handler) GetUser(email string) *protocol.User {
user, existing := v.usersByEmail.Get(email)
if !existing {
v.clients.Add(user)
}
return user
}
func transferRequest(timer signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, input io.Reader, output ray.OutputStream) error {
defer output.Close()
bodyReader := session.DecodeRequestBody(request, input)
if err := buf.PipeUntilEOF(timer, bodyReader, output); err != nil {
return err
}
return nil
}
func transferResponse(timer signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output io.Writer) error {
session.EncodeResponseHeader(response, output)
bodyWriter := session.EncodeResponseBody(request, output)
var reader buf.Reader = input
if request.Command == protocol.RequestCommandTCP {
reader = buf.NewMergingReader(input)
}
// Optimize for small response packet
data, err := reader.Read()
if err != nil {
return err
}
if err := bodyWriter.Write(data); err != nil {
return err
}
data.Release()
if bufferedWriter, ok := output.(*buf.BufferedWriter); ok {
if err := bufferedWriter.SetBuffered(false); err != nil {
return err
}
}
if err := buf.PipeUntilEOF(timer, reader, bodyWriter); err != nil {
return err
}
if request.Option.Has(protocol.RequestOptionChunkStream) {
if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
return err
}
}
return nil
}
// Process implements proxy.Inbound.Process().
func (v *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher dispatcher.Interface) error {
connection.SetReadDeadline(time.Now().Add(time.Second * 8))
reader := buf.NewBufferedReader(connection)
session := encoding.NewServerSession(v.clients, v.sessionHistory)
request, err := session.DecodeRequestHeader(reader)
if err != nil {
if errors.Cause(err) != io.EOF {
log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
log.Trace(newError("invalid request from ", connection.RemoteAddr(), ": ", err))
}
return err
}
log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
log.Trace(newError("received request for ", request.Destination()))
connection.SetReadDeadline(time.Time{})
userSettings := request.User.GetSettings()
ctx = protocol.ContextWithUser(ctx, request.User)
ctx, timer := signal.CancelAfterInactivity(ctx, userSettings.PayloadTimeout)
ray, err := dispatcher.Dispatch(ctx, request.Destination())
if err != nil {
return newError("failed to dispatch request to ", request.Destination()).Base(err)
}
input := ray.InboundInput()
output := ray.InboundOutput()
reader.SetBuffered(false)
requestDone := signal.ExecuteAsync(func() error {
return transferRequest(timer, session, request, reader, input)
})
writer := buf.NewBufferedWriter(connection)
response := &protocol.ResponseHeader{
Command: v.generateCommand(ctx, request),
}
responseDone := signal.ExecuteAsync(func() error {
return transferResponse(timer, session, request, response, output, writer)
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
input.CloseError()
output.CloseError()
return newError("connection ends").Base(err)
}
if err := writer.Flush(); err != nil {
return newError("error during flushing remaining data").Base(err)
}
runtime.KeepAlive(timer)
return nil
}
func (v *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
if v.detours != nil {
tag := v.detours.To
if v.inboundHandlerManager != nil {
handler, err := v.inboundHandlerManager.GetHandler(ctx, tag)
if err != nil {
log.Trace(newError("failed to get detour handler: ", tag, err).AtWarning())
return nil
}
proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
inboundHandler, ok := proxyHandler.(*Handler)
if ok && inboundHandler != nil {
if availableMin > 255 {
availableMin = 255
}
log.Trace(newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug())
user := inboundHandler.GetUser(request.User.Email)
if user == nil {
return nil
}
account, _ := user.GetTypedAccount()
return &protocol.CommandSwitchAccount{
Port: port,
ID: account.(*vmess.InternalAccount).ID.UUID(),
AlterIds: uint16(len(account.(*vmess.InternalAccount).AlterIDs)),
Level: user.Level,
ValidMin: byte(availableMin),
}
}
}
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}