github.com/xraypb/xray-core@v1.6.6/proxy/vmess/outbound/outbound.go (about)

     1  package outbound
     2  
     3  //go:generate go run github.com/xraypb/xray-core/common/errors/errorgen
     4  
     5  import (
     6  	"context"
     7  	"crypto/hmac"
     8  	"crypto/sha256"
     9  	"hash/crc64"
    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/net"
    15  	"github.com/xraypb/xray-core/common/platform"
    16  	"github.com/xraypb/xray-core/common/protocol"
    17  	"github.com/xraypb/xray-core/common/retry"
    18  	"github.com/xraypb/xray-core/common/session"
    19  	"github.com/xraypb/xray-core/common/signal"
    20  	"github.com/xraypb/xray-core/common/task"
    21  	"github.com/xraypb/xray-core/common/xudp"
    22  	core "github.com/xraypb/xray-core/core"
    23  	"github.com/xraypb/xray-core/features/policy"
    24  	"github.com/xraypb/xray-core/proxy/vmess"
    25  	"github.com/xraypb/xray-core/proxy/vmess/encoding"
    26  	"github.com/xraypb/xray-core/transport"
    27  	"github.com/xraypb/xray-core/transport/internet"
    28  	"github.com/xraypb/xray-core/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  	var rec *protocol.ServerSpec
    64  	var conn stat.Connection
    65  
    66  	err := retry.ExponentialBackoff(5, 200).On(func() error {
    67  		rec = h.serverPicker.PickServer()
    68  		rawConn, err := dialer.Dial(ctx, rec.Destination())
    69  		if err != nil {
    70  			return err
    71  		}
    72  		conn = rawConn
    73  
    74  		return nil
    75  	})
    76  	if err != nil {
    77  		return newError("failed to find an available destination").Base(err).AtWarning()
    78  	}
    79  	defer conn.Close()
    80  
    81  	outbound := session.OutboundFromContext(ctx)
    82  	if outbound == nil || !outbound.Target.IsValid() {
    83  		return newError("target not specified").AtError()
    84  	}
    85  
    86  	target := outbound.Target
    87  	newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    88  
    89  	command := protocol.RequestCommandTCP
    90  	if target.Network == net.Network_UDP {
    91  		command = protocol.RequestCommandUDP
    92  	}
    93  	if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
    94  		command = protocol.RequestCommandMux
    95  	}
    96  
    97  	user := rec.PickUser()
    98  	request := &protocol.RequestHeader{
    99  		Version: encoding.Version,
   100  		User:    user,
   101  		Command: command,
   102  		Address: target.Address,
   103  		Port:    target.Port,
   104  		Option:  protocol.RequestOptionChunkStream,
   105  	}
   106  
   107  	account := request.User.Account.(*vmess.MemoryAccount)
   108  	request.Security = account.Security
   109  
   110  	if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_NONE || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
   111  		request.Option.Set(protocol.RequestOptionChunkMasking)
   112  	}
   113  
   114  	if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
   115  		request.Option.Set(protocol.RequestOptionGlobalPadding)
   116  	}
   117  
   118  	if request.Security == protocol.SecurityType_ZERO {
   119  		request.Security = protocol.SecurityType_NONE
   120  		request.Option.Clear(protocol.RequestOptionChunkStream)
   121  		request.Option.Clear(protocol.RequestOptionChunkMasking)
   122  	}
   123  
   124  	if account.AuthenticatedLengthExperiment {
   125  		request.Option.Set(protocol.RequestOptionAuthenticatedLength)
   126  	}
   127  
   128  	input := link.Reader
   129  	output := link.Writer
   130  
   131  	isAEAD := false
   132  	if !aeadDisabled && len(account.AlterIDs) == 0 {
   133  		isAEAD = true
   134  	}
   135  
   136  	hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
   137  	hashkdf.Write(account.ID.Bytes())
   138  
   139  	behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
   140  
   141  	session := encoding.NewClientSession(ctx, isAEAD, protocol.DefaultIDHash, int64(behaviorSeed))
   142  	sessionPolicy := h.policyManager.ForLevel(request.User.Level)
   143  
   144  	ctx, cancel := context.WithCancel(ctx)
   145  	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
   146  
   147  	if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
   148  		request.Command = protocol.RequestCommandMux
   149  		request.Address = net.DomainAddress("v1.mux.cool")
   150  		request.Port = net.Port(666)
   151  	}
   152  
   153  	requestDone := func() error {
   154  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   155  
   156  		writer := buf.NewBufferedWriter(buf.NewWriter(conn))
   157  		if err := session.EncodeRequestHeader(request, writer); err != nil {
   158  			return newError("failed to encode request").Base(err).AtWarning()
   159  		}
   160  
   161  		bodyWriter, err := session.EncodeRequestBody(request, writer)
   162  		if err != nil {
   163  			return newError("failed to start encoding").Base(err)
   164  		}
   165  		bodyWriter2 := bodyWriter
   166  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   167  			bodyWriter = xudp.NewPacketWriter(bodyWriter, target)
   168  		}
   169  		if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   170  			return newError("failed to write first payload").Base(err)
   171  		}
   172  
   173  		if err := writer.SetBuffered(false); err != nil {
   174  			return err
   175  		}
   176  
   177  		if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   178  			return err
   179  		}
   180  
   181  		if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
   182  			if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
   183  				return err
   184  			}
   185  		}
   186  
   187  		return nil
   188  	}
   189  
   190  	responseDone := func() error {
   191  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   192  
   193  		reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
   194  		header, err := session.DecodeResponseHeader(reader)
   195  		if err != nil {
   196  			return newError("failed to read header").Base(err)
   197  		}
   198  		h.handleCommand(rec.Destination(), header.Command)
   199  
   200  		bodyReader, err := session.DecodeResponseBody(request, reader)
   201  		if err != nil {
   202  			return newError("failed to start encoding response").Base(err)
   203  		}
   204  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   205  			bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
   206  		}
   207  
   208  		return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
   209  	}
   210  
   211  	responseDonePost := task.OnSuccess(responseDone, task.Close(output))
   212  	if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
   213  		return newError("connection ends").Base(err)
   214  	}
   215  
   216  	return nil
   217  }
   218  
   219  var (
   220  	enablePadding = false
   221  	aeadDisabled  = false
   222  )
   223  
   224  func shouldEnablePadding(s protocol.SecurityType) bool {
   225  	return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO
   226  }
   227  
   228  func init() {
   229  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   230  		return New(ctx, config.(*Config))
   231  	}))
   232  
   233  	const defaultFlagValue = "NOT_DEFINED_AT_ALL"
   234  
   235  	paddingValue := platform.NewEnvFlag("xray.vmess.padding").GetValue(func() string { return defaultFlagValue })
   236  	if paddingValue != defaultFlagValue {
   237  		enablePadding = true
   238  	}
   239  
   240  	isAeadDisabled := platform.NewEnvFlag("xray.vmess.aead.disabled").GetValue(func() string { return defaultFlagValue })
   241  	if isAeadDisabled == "true" {
   242  		aeadDisabled = true
   243  	}
   244  }