github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/proxy/vmess/outbound/outbound.go (about)

     1  package outbound
     2  
     3  //go:generate go run github.com/xmplusdev/xmcore/common/errors/errorgen
     4  
     5  import (
     6  	"context"
     7  	"crypto/hmac"
     8  	"crypto/sha256"
     9  	"hash/crc64"
    10  	"time"
    11  
    12  	"github.com/xmplusdev/xmcore/common"
    13  	"github.com/xmplusdev/xmcore/common/buf"
    14  	"github.com/xmplusdev/xmcore/common/net"
    15  	"github.com/xmplusdev/xmcore/common/platform"
    16  	"github.com/xmplusdev/xmcore/common/protocol"
    17  	"github.com/xmplusdev/xmcore/common/retry"
    18  	"github.com/xmplusdev/xmcore/common/session"
    19  	"github.com/xmplusdev/xmcore/common/signal"
    20  	"github.com/xmplusdev/xmcore/common/task"
    21  	"github.com/xmplusdev/xmcore/common/xudp"
    22  	core "github.com/xmplusdev/xmcore/core"
    23  	"github.com/xmplusdev/xmcore/features/policy"
    24  	"github.com/xmplusdev/xmcore/proxy/vmess"
    25  	"github.com/xmplusdev/xmcore/proxy/vmess/encoding"
    26  	"github.com/xmplusdev/xmcore/transport"
    27  	"github.com/xmplusdev/xmcore/transport/internet"
    28  	"github.com/xmplusdev/xmcore/transport/internet/stat"
    29  )
    30  
    31  // Handler is an outbound connection handler for VMess protocol.
    32  type Handler struct {
    33  	serverList    *protocol.ServerList
    34  	serverPicker  protocol.ServerPicker
    35  	policyManager policy.Manager
    36  	cone          bool
    37  }
    38  
    39  // New creates a new VMess outbound handler.
    40  func New(ctx context.Context, config *Config) (*Handler, error) {
    41  	serverList := protocol.NewServerList()
    42  	for _, rec := range config.Receiver {
    43  		s, err := protocol.NewServerSpecFromPB(rec)
    44  		if err != nil {
    45  			return nil, newError("failed to parse server spec").Base(err)
    46  		}
    47  		serverList.AddServer(s)
    48  	}
    49  
    50  	v := core.MustFromContext(ctx)
    51  	handler := &Handler{
    52  		serverList:    serverList,
    53  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    54  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    55  		cone:          ctx.Value("cone").(bool),
    56  	}
    57  
    58  	return handler, nil
    59  }
    60  
    61  // Process implements proxy.Outbound.Process().
    62  func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    63  	outbound := session.OutboundFromContext(ctx)
    64  	if outbound == nil || !outbound.Target.IsValid() {
    65  		return newError("target not specified").AtError()
    66  	}
    67  	outbound.Name = "vmess"
    68  	inbound := session.InboundFromContext(ctx)
    69  	if inbound != nil {
    70  		inbound.SetCanSpliceCopy(3)
    71  	}
    72  
    73  	var rec *protocol.ServerSpec
    74  	var conn stat.Connection
    75  	err := retry.ExponentialBackoff(5, 200).On(func() error {
    76  		rec = h.serverPicker.PickServer()
    77  		rawConn, err := dialer.Dial(ctx, rec.Destination())
    78  		if err != nil {
    79  			return err
    80  		}
    81  		conn = rawConn
    82  
    83  		return nil
    84  	})
    85  	if err != nil {
    86  		return newError("failed to find an available destination").Base(err).AtWarning()
    87  	}
    88  	defer conn.Close()
    89  
    90  	target := outbound.Target
    91  	newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    92  
    93  	command := protocol.RequestCommandTCP
    94  	if target.Network == net.Network_UDP {
    95  		command = protocol.RequestCommandUDP
    96  	}
    97  	if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
    98  		command = protocol.RequestCommandMux
    99  	}
   100  
   101  	user := rec.PickUser()
   102  	request := &protocol.RequestHeader{
   103  		Version: encoding.Version,
   104  		User:    user,
   105  		Command: command,
   106  		Address: target.Address,
   107  		Port:    target.Port,
   108  		Option:  protocol.RequestOptionChunkStream,
   109  	}
   110  
   111  	account := request.User.Account.(*vmess.MemoryAccount)
   112  	request.Security = account.Security
   113  
   114  	if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_NONE || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
   115  		request.Option.Set(protocol.RequestOptionChunkMasking)
   116  	}
   117  
   118  	if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
   119  		request.Option.Set(protocol.RequestOptionGlobalPadding)
   120  	}
   121  
   122  	if request.Security == protocol.SecurityType_ZERO {
   123  		request.Security = protocol.SecurityType_NONE
   124  		request.Option.Clear(protocol.RequestOptionChunkStream)
   125  		request.Option.Clear(protocol.RequestOptionChunkMasking)
   126  	}
   127  
   128  	if account.AuthenticatedLengthExperiment {
   129  		request.Option.Set(protocol.RequestOptionAuthenticatedLength)
   130  	}
   131  
   132  	input := link.Reader
   133  	output := link.Writer
   134  
   135  	hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
   136  	hashkdf.Write(account.ID.Bytes())
   137  
   138  	behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
   139  
   140  	var newCtx context.Context
   141  	var newCancel context.CancelFunc
   142  	if session.TimeoutOnlyFromContext(ctx) {
   143  		newCtx, newCancel = context.WithCancel(context.Background())
   144  	}
   145  
   146  	session := encoding.NewClientSession(ctx, int64(behaviorSeed))
   147  	sessionPolicy := h.policyManager.ForLevel(request.User.Level)
   148  
   149  	ctx, cancel := context.WithCancel(ctx)
   150  	timer := signal.CancelAfterInactivity(ctx, func() {
   151  		cancel()
   152  		if newCancel != nil {
   153  			newCancel()
   154  		}
   155  	}, sessionPolicy.Timeouts.ConnectionIdle)
   156  
   157  	if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
   158  		request.Command = protocol.RequestCommandMux
   159  		request.Address = net.DomainAddress("v1.mux.cool")
   160  		request.Port = net.Port(666)
   161  	}
   162  
   163  	requestDone := func() error {
   164  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   165  
   166  		writer := buf.NewBufferedWriter(buf.NewWriter(conn))
   167  		if err := session.EncodeRequestHeader(request, writer); err != nil {
   168  			return newError("failed to encode request").Base(err).AtWarning()
   169  		}
   170  
   171  		bodyWriter, err := session.EncodeRequestBody(request, writer)
   172  		if err != nil {
   173  			return newError("failed to start encoding").Base(err)
   174  		}
   175  		bodyWriter2 := bodyWriter
   176  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   177  			bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
   178  		}
   179  		if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   180  			return newError("failed to write first payload").Base(err)
   181  		}
   182  
   183  		if err := writer.SetBuffered(false); err != nil {
   184  			return err
   185  		}
   186  
   187  		if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   188  			return err
   189  		}
   190  
   191  		if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
   192  			if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
   193  				return err
   194  			}
   195  		}
   196  
   197  		return nil
   198  	}
   199  
   200  	responseDone := func() error {
   201  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   202  
   203  		reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
   204  		header, err := session.DecodeResponseHeader(reader)
   205  		if err != nil {
   206  			return newError("failed to read header").Base(err)
   207  		}
   208  		h.handleCommand(rec.Destination(), header.Command)
   209  
   210  		bodyReader, err := session.DecodeResponseBody(request, reader)
   211  		if err != nil {
   212  			return newError("failed to start encoding response").Base(err)
   213  		}
   214  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   215  			bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
   216  		}
   217  
   218  		return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
   219  	}
   220  
   221  	if newCtx != nil {
   222  		ctx = newCtx
   223  	}
   224  
   225  	responseDonePost := task.OnSuccess(responseDone, task.Close(output))
   226  	if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
   227  		return newError("connection ends").Base(err)
   228  	}
   229  
   230  	return nil
   231  }
   232  
   233  var (
   234  	enablePadding = false
   235  )
   236  
   237  func shouldEnablePadding(s protocol.SecurityType) bool {
   238  	return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO
   239  }
   240  
   241  func init() {
   242  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   243  		return New(ctx, config.(*Config))
   244  	}))
   245  
   246  	const defaultFlagValue = "NOT_DEFINED_AT_ALL"
   247  
   248  	paddingValue := platform.NewEnvFlag(platform.UseVmessPadding).GetValue(func() string { return defaultFlagValue })
   249  	if paddingValue != defaultFlagValue {
   250  		enablePadding = true
   251  	}
   252  }