github.com/moqsien/xraycore@v1.8.5/proxy/vmess/outbound/outbound.go (about)

     1  package outbound
     2  
     3  //go:generate go run github.com/moqsien/xraycore/common/errors/errorgen
     4  
     5  import (
     6  	"context"
     7  	"crypto/hmac"
     8  	"crypto/sha256"
     9  	"hash/crc64"
    10  	"time"
    11  
    12  	"github.com/moqsien/xraycore/common"
    13  	"github.com/moqsien/xraycore/common/buf"
    14  	"github.com/moqsien/xraycore/common/net"
    15  	"github.com/moqsien/xraycore/common/platform"
    16  	"github.com/moqsien/xraycore/common/protocol"
    17  	"github.com/moqsien/xraycore/common/retry"
    18  	"github.com/moqsien/xraycore/common/session"
    19  	"github.com/moqsien/xraycore/common/signal"
    20  	"github.com/moqsien/xraycore/common/task"
    21  	"github.com/moqsien/xraycore/common/xudp"
    22  	core "github.com/moqsien/xraycore/core"
    23  	"github.com/moqsien/xraycore/features/policy"
    24  	"github.com/moqsien/xraycore/proxy/vmess"
    25  	"github.com/moqsien/xraycore/proxy/vmess/encoding"
    26  	"github.com/moqsien/xraycore/transport"
    27  	"github.com/moqsien/xraycore/transport/internet"
    28  	"github.com/moqsien/xraycore/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  	hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
   132  	hashkdf.Write(account.ID.Bytes())
   133  
   134  	behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
   135  
   136  	var newCtx context.Context
   137  	var newCancel context.CancelFunc
   138  	if session.TimeoutOnlyFromContext(ctx) {
   139  		newCtx, newCancel = context.WithCancel(context.Background())
   140  	}
   141  
   142  	session := encoding.NewClientSession(ctx, int64(behaviorSeed))
   143  	sessionPolicy := h.policyManager.ForLevel(request.User.Level)
   144  
   145  	ctx, cancel := context.WithCancel(ctx)
   146  	timer := signal.CancelAfterInactivity(ctx, func() {
   147  		cancel()
   148  		if newCancel != nil {
   149  			newCancel()
   150  		}
   151  	}, sessionPolicy.Timeouts.ConnectionIdle)
   152  
   153  	if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
   154  		request.Command = protocol.RequestCommandMux
   155  		request.Address = net.DomainAddress("v1.mux.cool")
   156  		request.Port = net.Port(666)
   157  	}
   158  
   159  	requestDone := func() error {
   160  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   161  
   162  		writer := buf.NewBufferedWriter(buf.NewWriter(conn))
   163  		if err := session.EncodeRequestHeader(request, writer); err != nil {
   164  			return newError("failed to encode request").Base(err).AtWarning()
   165  		}
   166  
   167  		bodyWriter, err := session.EncodeRequestBody(request, writer)
   168  		if err != nil {
   169  			return newError("failed to start encoding").Base(err)
   170  		}
   171  		bodyWriter2 := bodyWriter
   172  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   173  			bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
   174  		}
   175  		if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   176  			return newError("failed to write first payload").Base(err)
   177  		}
   178  
   179  		if err := writer.SetBuffered(false); err != nil {
   180  			return err
   181  		}
   182  
   183  		if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   184  			return err
   185  		}
   186  
   187  		if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
   188  			if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
   189  				return err
   190  			}
   191  		}
   192  
   193  		return nil
   194  	}
   195  
   196  	responseDone := func() error {
   197  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   198  
   199  		reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
   200  		header, err := session.DecodeResponseHeader(reader)
   201  		if err != nil {
   202  			return newError("failed to read header").Base(err)
   203  		}
   204  		h.handleCommand(rec.Destination(), header.Command)
   205  
   206  		bodyReader, err := session.DecodeResponseBody(request, reader)
   207  		if err != nil {
   208  			return newError("failed to start encoding response").Base(err)
   209  		}
   210  		if request.Command == protocol.RequestCommandMux && request.Port == 666 {
   211  			bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
   212  		}
   213  
   214  		return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
   215  	}
   216  
   217  	if newCtx != nil {
   218  		ctx = newCtx
   219  	}
   220  
   221  	responseDonePost := task.OnSuccess(responseDone, task.Close(output))
   222  	if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
   223  		return newError("connection ends").Base(err)
   224  	}
   225  
   226  	return nil
   227  }
   228  
   229  var (
   230  	enablePadding = false
   231  )
   232  
   233  func shouldEnablePadding(s protocol.SecurityType) bool {
   234  	return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO
   235  }
   236  
   237  func init() {
   238  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   239  		return New(ctx, config.(*Config))
   240  	}))
   241  
   242  	const defaultFlagValue = "NOT_DEFINED_AT_ALL"
   243  
   244  	paddingValue := platform.NewEnvFlag("xray.vmess.padding").GetValue(func() string { return defaultFlagValue })
   245  	if paddingValue != defaultFlagValue {
   246  		enablePadding = true
   247  	}
   248  }