github.com/v2fly/v2ray-core/v4@v4.45.2/proxy/vmess/outbound/outbound.go (about)

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