github.com/xraypb/Xray-core@v1.8.1/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.Name = "vmess"
   291  	inbound.User = request.User
   292  
   293  	sessionPolicy = h.policyManager.ForLevel(request.User.Level)
   294  
   295  	ctx, cancel := context.WithCancel(ctx)
   296  	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
   297  
   298  	ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
   299  	link, err := dispatcher.Dispatch(ctx, request.Destination())
   300  	if err != nil {
   301  		return newError("failed to dispatch request to ", request.Destination()).Base(err)
   302  	}
   303  
   304  	requestDone := func() error {
   305  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   306  
   307  		bodyReader, err := svrSession.DecodeRequestBody(request, reader)
   308  		if err != nil {
   309  			return newError("failed to start decoding").Base(err)
   310  		}
   311  		if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
   312  			return newError("failed to transfer request").Base(err)
   313  		}
   314  		return nil
   315  	}
   316  
   317  	responseDone := func() error {
   318  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   319  
   320  		writer := buf.NewBufferedWriter(buf.NewWriter(connection))
   321  		defer writer.Flush()
   322  
   323  		response := &protocol.ResponseHeader{
   324  			Command: h.generateCommand(ctx, request),
   325  		}
   326  		return transferResponse(timer, svrSession, request, response, link.Reader, writer)
   327  	}
   328  
   329  	requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
   330  	if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
   331  		common.Interrupt(link.Reader)
   332  		common.Interrupt(link.Writer)
   333  		return newError("connection ends").Base(err)
   334  	}
   335  
   336  	return nil
   337  }
   338  
   339  func (h *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
   340  	if h.detours != nil {
   341  		tag := h.detours.To
   342  		if h.inboundHandlerManager != nil {
   343  			handler, err := h.inboundHandlerManager.GetHandler(ctx, tag)
   344  			if err != nil {
   345  				newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
   346  				return nil
   347  			}
   348  			proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
   349  			inboundHandler, ok := proxyHandler.(*Handler)
   350  			if ok && inboundHandler != nil {
   351  				if availableMin > 255 {
   352  					availableMin = 255
   353  				}
   354  
   355  				newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog(session.ExportIDToError(ctx))
   356  				user := inboundHandler.GetUser(request.User.Email)
   357  				if user == nil {
   358  					return nil
   359  				}
   360  				account := user.Account.(*vmess.MemoryAccount)
   361  				return &protocol.CommandSwitchAccount{
   362  					Port:     port,
   363  					ID:       account.ID.UUID(),
   364  					AlterIds: uint16(len(account.AlterIDs)),
   365  					Level:    user.Level,
   366  					ValidMin: byte(availableMin),
   367  				}
   368  			}
   369  		}
   370  	}
   371  
   372  	return nil
   373  }
   374  
   375  func init() {
   376  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   377  		return New(ctx, config.(*Config))
   378  	}))
   379  
   380  	defaultFlagValue := "NOT_DEFINED_AT_ALL"
   381  
   382  	if time.Now().Year() >= 2022 {
   383  		defaultFlagValue = "true_by_default_2022"
   384  	}
   385  
   386  	isAeadForced := platform.NewEnvFlag("xray.vmess.aead.forced").GetValue(func() string { return defaultFlagValue })
   387  	aeadForced = (isAeadForced == "true")
   388  
   389  	if isAeadForced == "true_by_default_2022" {
   390  		aeadForced = true
   391  		aeadForced2022 = true
   392  	}
   393  }