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