1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-14 00:07:09 -05:00
v2fly/proxy/vmess/outbound/outbound.go

244 lines
7.5 KiB
Go
Raw Normal View History

2015-12-04 06:07:32 -05:00
package outbound
2015-09-10 18:24:18 -04:00
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
2017-04-08 19:43:25 -04:00
2015-09-10 18:24:18 -04:00
import (
"context"
"crypto/hmac"
"crypto/sha256"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/platform"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/proxy"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/encoding"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"hash/crc64"
2015-09-10 18:24:18 -04:00
)
2017-02-13 07:16:37 -05:00
// Handler is an outbound connection handler for VMess protocol.
type Handler struct {
2018-10-21 04:27:13 -04:00
serverList *protocol.ServerList
serverPicker protocol.ServerPicker
policyManager policy.Manager
2015-09-10 18:24:18 -04:00
}
2018-05-25 17:20:24 -04:00
// New creates a new VMess outbound handler.
2017-02-13 07:16:37 -05:00
func New(ctx context.Context, config *Config) (*Handler, error) {
serverList := protocol.NewServerList()
for _, rec := range config.Receiver {
2020-08-26 07:35:33 -04:00
s, err := protocol.NewServerSpecFromPB(rec)
2018-08-26 18:11:32 -04:00
if err != nil {
return nil, newError("failed to parse server spec").Base(err)
}
serverList.AddServer(s)
}
2018-10-21 04:27:13 -04:00
v := core.MustFromContext(ctx)
2017-02-13 07:16:37 -05:00
handler := &Handler{
2018-10-21 04:27:13 -04:00
serverList: serverList,
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
2017-11-27 16:09:30 -05:00
return handler, nil
}
2017-02-13 07:16:37 -05:00
// Process implements proxy.Outbound.Process().
2020-09-20 21:10:56 -04:00
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
2016-07-25 10:48:09 -04:00
var rec *protocol.ServerSpec
2016-06-14 16:54:08 -04:00
var conn internet.Connection
2016-06-05 18:10:51 -04:00
2017-02-10 05:41:50 -05:00
err := retry.ExponentialBackoff(5, 200).On(func() error {
2020-09-20 21:10:56 -04:00
rec = h.serverPicker.PickServer()
rawConn, err := dialer.Dial(ctx, rec.Destination())
2016-06-05 18:10:51 -04:00
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
2017-04-08 19:43:25 -04:00
return newError("failed to find an available destination").Base(err).AtWarning()
2016-06-05 18:10:51 -04:00
}
defer conn.Close()
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
2017-04-08 19:43:25 -04:00
return newError("target not specified").AtError()
2017-02-09 16:49:38 -05:00
}
target := outbound.Target
newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
2015-09-10 18:24:18 -04:00
2016-05-07 14:26:29 -04:00
command := protocol.RequestCommandTCP
2017-01-13 17:42:39 -05:00
if target.Network == net.Network_UDP {
2016-05-07 14:26:29 -04:00
command = protocol.RequestCommandUDP
2015-09-20 12:22:29 -04:00
}
2018-02-11 18:06:51 -05:00
if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
command = protocol.RequestCommandMux
}
user := rec.PickUser()
2016-05-07 14:26:29 -04:00
request := &protocol.RequestHeader{
2016-07-23 07:17:51 -04:00
Version: encoding.Version,
User: user,
2015-09-20 12:22:29 -04:00
Command: command,
2016-09-20 05:53:05 -04:00
Address: target.Address,
Port: target.Port,
2016-05-07 14:26:29 -04:00
Option: protocol.RequestOptionChunkStream,
2016-02-01 06:22:29 -05:00
}
2018-10-18 03:25:58 -04:00
account := request.User.Account.(*vmess.MemoryAccount)
2016-12-07 15:43:41 -05:00
request.Security = account.Security
if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_NONE || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
2017-02-14 08:16:43 -05:00
request.Option.Set(protocol.RequestOptionChunkMasking)
}
if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
request.Option.Set(protocol.RequestOptionGlobalPadding)
}
if request.Security == protocol.SecurityType_ZERO {
request.Security = protocol.SecurityType_NONE
request.Option.Clear(protocol.RequestOptionChunkStream)
request.Option.Clear(protocol.RequestOptionChunkMasking)
}
2021-04-28 18:29:42 -04:00
if account.AuthenticatedLengthExperiment {
request.Option.Set(protocol.RequestOptionAuthenticatedLength)
}
2018-04-16 18:31:10 -04:00
input := link.Reader
output := link.Writer
2016-01-05 06:08:16 -05:00
2020-09-20 21:10:56 -04:00
isAEAD := false
if !aeadDisabled && len(account.AlterIDs) == 0 {
2020-09-20 21:10:56 -04:00
isAEAD = true
}
hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
hashkdf.Write(account.ID.Bytes())
behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
session := encoding.NewClientSession(ctx, isAEAD, protocol.DefaultIDHash, int64(behaviorSeed))
2020-09-20 21:10:56 -04:00
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
2016-02-27 10:41:21 -05:00
2017-11-14 18:36:14 -05:00
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
2017-01-31 06:42:05 -05:00
2018-04-11 10:45:09 -04:00
requestDone := func() error {
2018-02-19 11:50:21 -05:00
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
2017-11-09 16:33:15 -05:00
writer := buf.NewBufferedWriter(buf.NewWriter(conn))
if err := session.EncodeRequestHeader(request, writer); err != nil {
return newError("failed to encode request").Base(err).AtWarning()
}
2015-09-15 18:06:22 -04:00
bodyWriter, err := session.EncodeRequestBody(request, writer)
if err != nil {
return newError("failed to start encoding").Base(err)
}
if err := buf.CopyOnceTimeout(input, bodyWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
return newError("failed to write first payload").Base(err)
2016-12-29 18:32:20 -05:00
}
2017-01-04 06:34:01 -05:00
2017-03-27 05:26:44 -04:00
if err := writer.SetBuffered(false); err != nil {
return err
}
2017-04-27 16:30:48 -04:00
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
2016-12-29 18:32:20 -05:00
return err
}
2016-05-12 20:20:07 -04:00
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
2017-11-09 16:33:15 -05:00
if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
2016-12-29 18:32:20 -05:00
return err
}
}
2018-02-19 11:50:21 -05:00
2016-12-29 18:32:20 -05:00
return nil
2018-04-11 10:45:09 -04:00
}
2016-12-29 18:32:20 -05:00
2018-04-11 10:45:09 -04:00
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
2016-12-29 18:32:20 -05:00
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
2016-12-29 18:32:20 -05:00
header, err := session.DecodeResponseHeader(reader)
2016-06-02 15:34:25 -04:00
if err != nil {
2018-02-19 11:50:21 -05:00
return newError("failed to read header").Base(err)
2016-06-02 15:34:25 -04:00
}
2020-09-20 21:10:56 -04:00
h.handleCommand(rec.Destination(), header.Command)
2015-09-10 18:24:18 -04:00
bodyReader, err := session.DecodeResponseBody(request, reader)
if err != nil {
return newError("failed to start encoding response").Base(err)
}
2017-11-23 17:46:46 -05:00
return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
2018-04-11 10:45:09 -04:00
}
2015-10-03 05:34:01 -04:00
2021-05-19 17:28:52 -04:00
responseDonePost := task.OnSuccess(responseDone, task.Close(output))
2018-12-06 05:35:02 -05:00
if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
2017-04-08 19:43:25 -04:00
return newError("connection ends").Base(err)
2016-06-01 16:09:34 -04:00
}
return nil
2015-09-10 18:24:18 -04:00
}
2016-06-14 16:54:08 -04:00
2018-07-18 04:40:28 -04:00
var (
enablePadding = false
aeadDisabled = false
2018-07-18 04:40:28 -04:00
)
func shouldEnablePadding(s protocol.SecurityType) bool {
return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO
}
2016-06-14 16:54:08 -04:00
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
2018-07-18 04:40:28 -04:00
2021-09-04 16:16:13 -04:00
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedClient := config.(*SimplifiedConfig)
fullClient := &Config{Receiver: []*protocol.ServerEndpoint{
{
Address: simplifiedClient.Address,
Port: simplifiedClient.Port,
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{Id: simplifiedClient.Uuid}),
},
},
},
}}
return common.CreateObject(ctx, fullClient)
2021-09-04 16:16:13 -04:00
}))
2018-07-18 04:40:28 -04:00
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
2020-09-20 23:20:04 -04:00
2018-07-18 04:40:28 -04:00
paddingValue := platform.NewEnvFlag("v2ray.vmess.padding").GetValue(func() string { return defaultFlagValue })
if paddingValue != defaultFlagValue {
enablePadding = true
}
2020-09-20 23:20:04 -04:00
isAeadDisabled := platform.NewEnvFlag("v2ray.vmess.aead.disabled").GetValue(func() string { return defaultFlagValue })
if isAeadDisabled == "true" {
aeadDisabled = true
2020-09-20 23:20:04 -04:00
}
2015-09-10 18:24:18 -04:00
}