github.com/xraypb/xray-core@v1.6.6/proxy/vmess/inbound/inbound.go (about) 1 package inbound 2 3 //go:generate go run github.com/xraypb/xray-core/common/errors/errorgen 4 5 import ( 6 "context" 7 "io" 8 "strings" 9 "sync" 10 "time" 11 12 "github.com/xraypb/xray-core/common" 13 "github.com/xraypb/xray-core/common/buf" 14 "github.com/xraypb/xray-core/common/errors" 15 "github.com/xraypb/xray-core/common/log" 16 "github.com/xraypb/xray-core/common/net" 17 "github.com/xraypb/xray-core/common/platform" 18 "github.com/xraypb/xray-core/common/protocol" 19 "github.com/xraypb/xray-core/common/session" 20 "github.com/xraypb/xray-core/common/signal" 21 "github.com/xraypb/xray-core/common/task" 22 "github.com/xraypb/xray-core/common/uuid" 23 "github.com/xraypb/xray-core/core" 24 feature_inbound "github.com/xraypb/xray-core/features/inbound" 25 "github.com/xraypb/xray-core/features/policy" 26 "github.com/xraypb/xray-core/features/routing" 27 "github.com/xraypb/xray-core/proxy/vmess" 28 "github.com/xraypb/xray-core/proxy/vmess/encoding" 29 "github.com/xraypb/xray-core/transport/internet/stat" 30 ) 31 32 var ( 33 aeadForced = false 34 aeadForced2022 = false 35 ) 36 37 type userByEmail struct { 38 sync.Mutex 39 cache map[string]*protocol.MemoryUser 40 defaultLevel uint32 41 defaultAlterIDs uint16 42 } 43 44 func newUserByEmail(config *DefaultConfig) *userByEmail { 45 return &userByEmail{ 46 cache: make(map[string]*protocol.MemoryUser), 47 defaultLevel: config.Level, 48 defaultAlterIDs: uint16(config.AlterId), 49 } 50 } 51 52 func (v *userByEmail) addNoLock(u *protocol.MemoryUser) bool { 53 email := strings.ToLower(u.Email) 54 _, found := v.cache[email] 55 if found { 56 return false 57 } 58 v.cache[email] = u 59 return true 60 } 61 62 func (v *userByEmail) Add(u *protocol.MemoryUser) bool { 63 v.Lock() 64 defer v.Unlock() 65 66 return v.addNoLock(u) 67 } 68 69 func (v *userByEmail) Get(email string) (*protocol.MemoryUser, bool) { 70 email = strings.ToLower(email) 71 72 v.Lock() 73 defer v.Unlock() 74 75 user, found := v.cache[email] 76 if !found { 77 id := uuid.New() 78 rawAccount := &vmess.Account{ 79 Id: id.String(), 80 AlterId: uint32(v.defaultAlterIDs), 81 } 82 account, err := rawAccount.AsAccount() 83 common.Must(err) 84 user = &protocol.MemoryUser{ 85 Level: v.defaultLevel, 86 Email: email, 87 Account: account, 88 } 89 v.cache[email] = user 90 } 91 return user, found 92 } 93 94 func (v *userByEmail) Remove(email string) bool { 95 email = strings.ToLower(email) 96 97 v.Lock() 98 defer v.Unlock() 99 100 if _, found := v.cache[email]; !found { 101 return false 102 } 103 delete(v.cache, email) 104 return true 105 } 106 107 // Handler is an inbound connection handler that handles messages in VMess protocol. 108 type Handler struct { 109 policyManager policy.Manager 110 inboundHandlerManager feature_inbound.Manager 111 clients *vmess.TimedUserValidator 112 usersByEmail *userByEmail 113 detours *DetourConfig 114 sessionHistory *encoding.SessionHistory 115 secure bool 116 } 117 118 // New creates a new VMess inbound handler. 119 func New(ctx context.Context, config *Config) (*Handler, error) { 120 v := core.MustFromContext(ctx) 121 handler := &Handler{ 122 policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), 123 inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager), 124 clients: vmess.NewTimedUserValidator(protocol.DefaultIDHash), 125 detours: config.Detour, 126 usersByEmail: newUserByEmail(config.GetDefaultValue()), 127 sessionHistory: encoding.NewSessionHistory(), 128 secure: config.SecureEncryptionOnly, 129 } 130 131 for _, user := range config.User { 132 mUser, err := user.ToMemoryUser() 133 if err != nil { 134 return nil, newError("failed to get VMess user").Base(err) 135 } 136 137 if err := handler.AddUser(ctx, mUser); err != nil { 138 return nil, newError("failed to initiate user").Base(err) 139 } 140 } 141 142 return handler, nil 143 } 144 145 // Close implements common.Closable. 146 func (h *Handler) Close() error { 147 return errors.Combine( 148 h.clients.Close(), 149 h.sessionHistory.Close(), 150 common.Close(h.usersByEmail)) 151 } 152 153 // Network implements proxy.Inbound.Network(). 154 func (*Handler) Network() []net.Network { 155 return []net.Network{net.Network_TCP, net.Network_UNIX} 156 } 157 158 func (h *Handler) GetUser(email string) *protocol.MemoryUser { 159 user, existing := h.usersByEmail.Get(email) 160 if !existing { 161 h.clients.Add(user) 162 } 163 return user 164 } 165 166 func (h *Handler) AddUser(ctx context.Context, user *protocol.MemoryUser) error { 167 if len(user.Email) > 0 && !h.usersByEmail.Add(user) { 168 return newError("User ", user.Email, " already exists.") 169 } 170 return h.clients.Add(user) 171 } 172 173 func (h *Handler) RemoveUser(ctx context.Context, email string) error { 174 if email == "" { 175 return newError("Email must not be empty.") 176 } 177 if !h.usersByEmail.Remove(email) { 178 return newError("User ", email, " not found.") 179 } 180 h.clients.Remove(email) 181 return nil 182 } 183 184 func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error { 185 session.EncodeResponseHeader(response, output) 186 187 bodyWriter, err := session.EncodeResponseBody(request, output) 188 if err != nil { 189 return newError("failed to start decoding response").Base(err) 190 } 191 { 192 // Optimize for small response packet 193 data, err := input.ReadMultiBuffer() 194 if err != nil { 195 return err 196 } 197 198 if err := bodyWriter.WriteMultiBuffer(data); err != nil { 199 return err 200 } 201 } 202 203 if err := output.SetBuffered(false); err != nil { 204 return err 205 } 206 207 if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil { 208 return err 209 } 210 211 account := request.User.Account.(*vmess.MemoryAccount) 212 213 if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal { 214 if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil { 215 return err 216 } 217 } 218 219 return nil 220 } 221 222 func isInsecureEncryption(s protocol.SecurityType) bool { 223 return s == protocol.SecurityType_NONE || s == protocol.SecurityType_LEGACY || s == protocol.SecurityType_UNKNOWN 224 } 225 226 // Process implements proxy.Inbound.Process(). 227 func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error { 228 sessionPolicy := h.policyManager.ForLevel(0) 229 if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { 230 return newError("unable to set read deadline").Base(err).AtWarning() 231 } 232 233 iConn := connection 234 if statConn, ok := iConn.(*stat.CounterConnection); ok { 235 iConn = statConn.Connection 236 } 237 _, isDrain := iConn.(*net.TCPConn) 238 if !isDrain { 239 _, isDrain = iConn.(*net.UnixConn) 240 } 241 242 reader := &buf.BufferedReader{Reader: buf.NewReader(connection)} 243 svrSession := encoding.NewServerSession(h.clients, h.sessionHistory) 244 svrSession.SetAEADForced(aeadForced) 245 request, err := svrSession.DecodeRequestHeader(reader, isDrain) 246 if err != nil { 247 if errors.Cause(err) != io.EOF { 248 log.Record(&log.AccessMessage{ 249 From: connection.RemoteAddr(), 250 To: "", 251 Status: log.AccessRejected, 252 Reason: err, 253 }) 254 err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() 255 } 256 return err 257 } 258 259 if h.secure && isInsecureEncryption(request.Security) { 260 log.Record(&log.AccessMessage{ 261 From: connection.RemoteAddr(), 262 To: "", 263 Status: log.AccessRejected, 264 Reason: "Insecure encryption", 265 Email: request.User.Email, 266 }) 267 return newError("client is using insecure encryption: ", request.Security) 268 } 269 270 if request.Command != protocol.RequestCommandMux { 271 ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ 272 From: connection.RemoteAddr(), 273 To: request.Destination(), 274 Status: log.AccessAccepted, 275 Reason: "", 276 Email: request.User.Email, 277 }) 278 } 279 280 newError("received request for ", request.Destination()).WriteToLog(session.ExportIDToError(ctx)) 281 282 if err := connection.SetReadDeadline(time.Time{}); err != nil { 283 newError("unable to set back read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) 284 } 285 286 inbound := session.InboundFromContext(ctx) 287 if inbound == nil { 288 panic("no inbound metadata") 289 } 290 inbound.User = request.User 291 292 sessionPolicy = h.policyManager.ForLevel(request.User.Level) 293 294 ctx, cancel := context.WithCancel(ctx) 295 timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) 296 297 ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) 298 link, err := dispatcher.Dispatch(ctx, request.Destination()) 299 if err != nil { 300 return newError("failed to dispatch request to ", request.Destination()).Base(err) 301 } 302 303 requestDone := func() error { 304 defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) 305 306 bodyReader, err := svrSession.DecodeRequestBody(request, reader) 307 if err != nil { 308 return newError("failed to start decoding").Base(err) 309 } 310 if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil { 311 return newError("failed to transfer request").Base(err) 312 } 313 return nil 314 } 315 316 responseDone := func() error { 317 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 318 319 writer := buf.NewBufferedWriter(buf.NewWriter(connection)) 320 defer writer.Flush() 321 322 response := &protocol.ResponseHeader{ 323 Command: h.generateCommand(ctx, request), 324 } 325 return transferResponse(timer, svrSession, request, response, link.Reader, writer) 326 } 327 328 requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer)) 329 if err := task.Run(ctx, requestDonePost, responseDone); err != nil { 330 common.Interrupt(link.Reader) 331 common.Interrupt(link.Writer) 332 return newError("connection ends").Base(err) 333 } 334 335 return nil 336 } 337 338 func (h *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand { 339 if h.detours != nil { 340 tag := h.detours.To 341 if h.inboundHandlerManager != nil { 342 handler, err := h.inboundHandlerManager.GetHandler(ctx, tag) 343 if err != nil { 344 newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) 345 return nil 346 } 347 proxyHandler, port, availableMin := handler.GetRandomInboundProxy() 348 inboundHandler, ok := proxyHandler.(*Handler) 349 if ok && inboundHandler != nil { 350 if availableMin > 255 { 351 availableMin = 255 352 } 353 354 newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog(session.ExportIDToError(ctx)) 355 user := inboundHandler.GetUser(request.User.Email) 356 if user == nil { 357 return nil 358 } 359 account := user.Account.(*vmess.MemoryAccount) 360 return &protocol.CommandSwitchAccount{ 361 Port: port, 362 ID: account.ID.UUID(), 363 AlterIds: uint16(len(account.AlterIDs)), 364 Level: user.Level, 365 ValidMin: byte(availableMin), 366 } 367 } 368 } 369 } 370 371 return nil 372 } 373 374 func init() { 375 common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 376 return New(ctx, config.(*Config)) 377 })) 378 379 defaultFlagValue := "NOT_DEFINED_AT_ALL" 380 381 if time.Now().Year() >= 2022 { 382 defaultFlagValue = "true_by_default_2022" 383 } 384 385 isAeadForced := platform.NewEnvFlag("xray.vmess.aead.forced").GetValue(func() string { return defaultFlagValue }) 386 aeadForced = (isAeadForced == "true") 387 388 if isAeadForced == "true_by_default_2022" { 389 aeadForced = true 390 aeadForced2022 = true 391 } 392 }