mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-29 16:58:34 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
212
proxy/trojan/client.go
Normal file
212
proxy/trojan/client.go
Normal file
|
@ -0,0 +1,212 @@
|
|||
// +build !confonly
|
||||
|
||||
package trojan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/buf"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/platform"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
"github.com/xtls/xray-core/v1/common/retry"
|
||||
"github.com/xtls/xray-core/v1/common/session"
|
||||
"github.com/xtls/xray-core/v1/common/signal"
|
||||
"github.com/xtls/xray-core/v1/common/task"
|
||||
core "github.com/xtls/xray-core/v1/core"
|
||||
"github.com/xtls/xray-core/v1/features/policy"
|
||||
"github.com/xtls/xray-core/v1/features/stats"
|
||||
"github.com/xtls/xray-core/v1/transport"
|
||||
"github.com/xtls/xray-core/v1/transport/internet"
|
||||
"github.com/xtls/xray-core/v1/transport/internet/xtls"
|
||||
)
|
||||
|
||||
// Client is a inbound handler for trojan protocol
|
||||
type Client struct {
|
||||
serverPicker protocol.ServerPicker
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
// NewClient create a new trojan client.
|
||||
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
|
||||
serverList := protocol.NewServerList()
|
||||
for _, rec := range config.Server {
|
||||
s, err := protocol.NewServerSpecFromPB(rec)
|
||||
if err != nil {
|
||||
return nil, newError("failed to parse server spec").Base(err)
|
||||
}
|
||||
serverList.AddServer(s)
|
||||
}
|
||||
if serverList.Size() == 0 {
|
||||
return nil, newError("0 server")
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
client := &Client{
|
||||
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Process implements OutboundHandler.Process().
|
||||
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
outbound := session.OutboundFromContext(ctx)
|
||||
if outbound == nil || !outbound.Target.IsValid() {
|
||||
return newError("target not specified")
|
||||
}
|
||||
destination := outbound.Target
|
||||
network := destination.Network
|
||||
|
||||
var server *protocol.ServerSpec
|
||||
var conn internet.Connection
|
||||
|
||||
err := retry.ExponentialBackoff(5, 100).On(func() error {
|
||||
server = c.serverPicker.PickServer()
|
||||
rawConn, err := dialer.Dial(ctx, server.Destination())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
conn = rawConn
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return newError("failed to find an available destination").AtWarning().Base(err)
|
||||
}
|
||||
newError("tunneling request to ", destination, " via ", server.Destination()).WriteToLog(session.ExportIDToError(ctx))
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
user := server.PickUser()
|
||||
account, ok := user.Account.(*MemoryAccount)
|
||||
if !ok {
|
||||
return newError("user account is not valid")
|
||||
}
|
||||
|
||||
iConn := conn
|
||||
statConn, ok := iConn.(*internet.StatCouterConnection)
|
||||
if ok {
|
||||
iConn = statConn.Connection
|
||||
}
|
||||
|
||||
var rawConn syscall.RawConn
|
||||
|
||||
connWriter := &ConnWriter{}
|
||||
allowUDP443 := false
|
||||
switch account.Flow {
|
||||
case XRO + "-udp443", XRD + "-udp443":
|
||||
allowUDP443 = true
|
||||
account.Flow = account.Flow[:16]
|
||||
fallthrough
|
||||
case XRO, XRD:
|
||||
if destination.Address.Family().IsDomain() && destination.Address.Domain() == muxCoolAddress {
|
||||
return newError(account.Flow + " doesn't support Mux").AtWarning()
|
||||
}
|
||||
if destination.Network == net.Network_UDP {
|
||||
if !allowUDP443 && destination.Port == 443 {
|
||||
return newError(account.Flow + " stopped UDP/443").AtInfo()
|
||||
}
|
||||
} else { // enable XTLS only if making TCP request
|
||||
if xtlsConn, ok := iConn.(*xtls.Conn); ok {
|
||||
xtlsConn.RPRX = true
|
||||
xtlsConn.SHOW = trojanXTLSShow
|
||||
connWriter.Flow = account.Flow
|
||||
if account.Flow == XRD {
|
||||
xtlsConn.DirectMode = true
|
||||
}
|
||||
if sc, ok := xtlsConn.Connection.(syscall.Conn); ok {
|
||||
rawConn, _ = sc.SyscallConn()
|
||||
}
|
||||
} else {
|
||||
return newError(`failed to use ` + account.Flow + `, maybe "security" is not "xtls"`).AtWarning()
|
||||
}
|
||||
}
|
||||
case "":
|
||||
if _, ok := iConn.(*xtls.Conn); ok {
|
||||
panic(`To avoid misunderstanding, you must fill in Trojan "flow" when using XTLS.`)
|
||||
}
|
||||
default:
|
||||
return newError("unsupported flow " + account.Flow).AtWarning()
|
||||
}
|
||||
|
||||
sessionPolicy := c.policyManager.ForLevel(user.Level)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
|
||||
postRequest := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
var bodyWriter buf.Writer
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
connWriter.Writer = bufferWriter
|
||||
connWriter.Target = destination
|
||||
connWriter.Account = account
|
||||
|
||||
if destination.Network == net.Network_UDP {
|
||||
bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
|
||||
} else {
|
||||
bodyWriter = connWriter
|
||||
}
|
||||
|
||||
// write some request payload to buffer
|
||||
if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
|
||||
return newError("failed to write A request payload").Base(err).AtWarning()
|
||||
}
|
||||
|
||||
// Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
|
||||
if err = bufferWriter.SetBuffered(false); err != nil {
|
||||
return newError("failed to flush payload").Base(err).AtWarning()
|
||||
}
|
||||
|
||||
if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
|
||||
return newError("failed to transfer request payload").Base(err).AtInfo()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
getResponse := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
var reader buf.Reader
|
||||
if network == net.Network_UDP {
|
||||
reader = &PacketReader{
|
||||
Reader: conn,
|
||||
}
|
||||
} else {
|
||||
reader = buf.NewReader(conn)
|
||||
}
|
||||
if rawConn != nil {
|
||||
var counter stats.Counter
|
||||
if statConn != nil {
|
||||
counter = statConn.ReadCounter
|
||||
}
|
||||
return ReadV(reader, link.Writer, timer, iConn.(*xtls.Conn), rawConn, counter)
|
||||
}
|
||||
return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
|
||||
var responseDoneAndCloseWriter = task.OnSuccess(getResponse, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
|
||||
return newError("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return NewClient(ctx, config.(*ClientConfig))
|
||||
}))
|
||||
|
||||
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
|
||||
|
||||
xtlsShow := platform.NewEnvFlag("xray.trojan.xtls.show").GetValue(func() string { return defaultFlagValue })
|
||||
if xtlsShow == "true" {
|
||||
trojanXTLSShow = true
|
||||
}
|
||||
}
|
52
proxy/trojan/config.go
Normal file
52
proxy/trojan/config.go
Normal file
|
@ -0,0 +1,52 @@
|
|||
package trojan
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
fmt "fmt"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
)
|
||||
|
||||
// MemoryAccount is an account type converted from Account.
|
||||
type MemoryAccount struct {
|
||||
Password string
|
||||
Key []byte
|
||||
Flow string
|
||||
}
|
||||
|
||||
// AsAccount implements protocol.AsAccount.
|
||||
func (a *Account) AsAccount() (protocol.Account, error) {
|
||||
password := a.GetPassword()
|
||||
key := hexSha224(password)
|
||||
return &MemoryAccount{
|
||||
Password: password,
|
||||
Key: key,
|
||||
Flow: a.Flow,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Equals implements protocol.Account.Equals().
|
||||
func (a *MemoryAccount) Equals(another protocol.Account) bool {
|
||||
if account, ok := another.(*MemoryAccount); ok {
|
||||
return a.Password == account.Password
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hexSha224(password string) []byte {
|
||||
buf := make([]byte, 56)
|
||||
hash := sha256.New224()
|
||||
common.Must2(hash.Write([]byte(password)))
|
||||
hex.Encode(buf, hash.Sum(nil))
|
||||
return buf
|
||||
}
|
||||
|
||||
func hexString(data []byte) string {
|
||||
str := ""
|
||||
for _, v := range data {
|
||||
str += fmt.Sprintf("%02x", v)
|
||||
}
|
||||
return str
|
||||
}
|
412
proxy/trojan/config.pb.go
Normal file
412
proxy/trojan/config.pb.go
Normal file
|
@ -0,0 +1,412 @@
|
|||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.25.0
|
||||
// protoc v3.14.0
|
||||
// source: proxy/trojan/config.proto
|
||||
|
||||
package trojan
|
||||
|
||||
import (
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
protocol "github.com/xtls/xray-core/v1/common/protocol"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||
// of the legacy proto package is being used.
|
||||
const _ = proto.ProtoPackageIsVersion4
|
||||
|
||||
type Account struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
|
||||
Flow string `protobuf:"bytes,2,opt,name=flow,proto3" json:"flow,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Account) Reset() {
|
||||
*x = Account{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Account) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Account) ProtoMessage() {}
|
||||
|
||||
func (x *Account) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
|
||||
func (*Account) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_trojan_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Account) GetPassword() string {
|
||||
if x != nil {
|
||||
return x.Password
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Account) GetFlow() string {
|
||||
if x != nil {
|
||||
return x.Flow
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Fallback struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Alpn string `protobuf:"bytes,1,opt,name=alpn,proto3" json:"alpn,omitempty"`
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
|
||||
Dest string `protobuf:"bytes,4,opt,name=dest,proto3" json:"dest,omitempty"`
|
||||
Xver uint64 `protobuf:"varint,5,opt,name=xver,proto3" json:"xver,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Fallback) Reset() {
|
||||
*x = Fallback{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Fallback) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Fallback) ProtoMessage() {}
|
||||
|
||||
func (x *Fallback) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Fallback.ProtoReflect.Descriptor instead.
|
||||
func (*Fallback) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_trojan_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Fallback) GetAlpn() string {
|
||||
if x != nil {
|
||||
return x.Alpn
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Fallback) GetPath() string {
|
||||
if x != nil {
|
||||
return x.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Fallback) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Fallback) GetDest() string {
|
||||
if x != nil {
|
||||
return x.Dest
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Fallback) GetXver() uint64 {
|
||||
if x != nil {
|
||||
return x.Xver
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type ClientConfig struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ClientConfig) Reset() {
|
||||
*x = ClientConfig{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ClientConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ClientConfig) ProtoMessage() {}
|
||||
|
||||
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
|
||||
func (*ClientConfig) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_trojan_config_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint {
|
||||
if x != nil {
|
||||
return x.Server
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Users []*protocol.User `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"`
|
||||
Fallbacks []*Fallback `protobuf:"bytes,3,rep,name=fallbacks,proto3" json:"fallbacks,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ServerConfig) Reset() {
|
||||
*x = ServerConfig{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ServerConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ServerConfig) ProtoMessage() {}
|
||||
|
||||
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_trojan_config_proto_msgTypes[3]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
|
||||
func (*ServerConfig) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_trojan_config_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *ServerConfig) GetUsers() []*protocol.User {
|
||||
if x != nil {
|
||||
return x.Users
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ServerConfig) GetFallbacks() []*Fallback {
|
||||
if x != nil {
|
||||
return x.Fallbacks
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_trojan_config_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_proxy_trojan_config_proto_rawDesc = []byte{
|
||||
0x0a, 0x19, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x74, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0x2f, 0x63,
|
||||
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x11, 0x78, 0x72, 0x61,
|
||||
0x79, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x74, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0x1a, 0x1a,
|
||||
0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2f,
|
||||
0x75, 0x73, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x63, 0x6f, 0x6d, 0x6d,
|
||||
0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76,
|
||||
0x65, 0x72, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x39, 0x0a,
|
||||
0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73,
|
||||
0x77, 0x6f, 0x72, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73,
|
||||
0x77, 0x6f, 0x72, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x66, 0x6c, 0x6f, 0x77, 0x18, 0x02, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x04, 0x66, 0x6c, 0x6f, 0x77, 0x22, 0x6e, 0x0a, 0x08, 0x46, 0x61, 0x6c, 0x6c,
|
||||
0x62, 0x61, 0x63, 0x6b, 0x12, 0x12, 0x0a, 0x04, 0x61, 0x6c, 0x70, 0x6e, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x04, 0x61, 0x6c, 0x70, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x12, 0x0a, 0x04,
|
||||
0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65,
|
||||
0x12, 0x12, 0x0a, 0x04, 0x64, 0x65, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04,
|
||||
0x64, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x78, 0x76, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01,
|
||||
0x28, 0x04, 0x52, 0x04, 0x78, 0x76, 0x65, 0x72, 0x22, 0x4c, 0x0a, 0x0c, 0x43, 0x6c, 0x69, 0x65,
|
||||
0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76,
|
||||
0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e,
|
||||
0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e,
|
||||
0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x06,
|
||||
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x22, 0x7b, 0x0a, 0x0c, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72,
|
||||
0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x30, 0x0a, 0x05, 0x75, 0x73, 0x65, 0x72, 0x73, 0x18,
|
||||
0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d,
|
||||
0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x55, 0x73, 0x65,
|
||||
0x72, 0x52, 0x05, 0x75, 0x73, 0x65, 0x72, 0x73, 0x12, 0x39, 0x0a, 0x09, 0x66, 0x61, 0x6c, 0x6c,
|
||||
0x62, 0x61, 0x63, 0x6b, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x78, 0x72,
|
||||
0x61, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x74, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0x2e,
|
||||
0x46, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x09, 0x66, 0x61, 0x6c, 0x6c, 0x62, 0x61,
|
||||
0x63, 0x6b, 0x73, 0x42, 0x58, 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x74, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0x50, 0x01, 0x5a, 0x29,
|
||||
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x74, 0x6c, 0x73, 0x2f,
|
||||
0x78, 0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x70, 0x72, 0x6f,
|
||||
0x78, 0x79, 0x2f, 0x74, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0xaa, 0x02, 0x11, 0x58, 0x72, 0x61, 0x79,
|
||||
0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x54, 0x72, 0x6f, 0x6a, 0x61, 0x6e, 0x62, 0x06, 0x70,
|
||||
0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_proxy_trojan_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_trojan_config_proto_rawDescData = file_proxy_trojan_config_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_proxy_trojan_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_trojan_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_trojan_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_trojan_config_proto_rawDescData)
|
||||
})
|
||||
return file_proxy_trojan_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_trojan_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
|
||||
var file_proxy_trojan_config_proto_goTypes = []interface{}{
|
||||
(*Account)(nil), // 0: xray.proxy.trojan.Account
|
||||
(*Fallback)(nil), // 1: xray.proxy.trojan.Fallback
|
||||
(*ClientConfig)(nil), // 2: xray.proxy.trojan.ClientConfig
|
||||
(*ServerConfig)(nil), // 3: xray.proxy.trojan.ServerConfig
|
||||
(*protocol.ServerEndpoint)(nil), // 4: xray.common.protocol.ServerEndpoint
|
||||
(*protocol.User)(nil), // 5: xray.common.protocol.User
|
||||
}
|
||||
var file_proxy_trojan_config_proto_depIdxs = []int32{
|
||||
4, // 0: xray.proxy.trojan.ClientConfig.server:type_name -> xray.common.protocol.ServerEndpoint
|
||||
5, // 1: xray.proxy.trojan.ServerConfig.users:type_name -> xray.common.protocol.User
|
||||
1, // 2: xray.proxy.trojan.ServerConfig.fallbacks:type_name -> xray.proxy.trojan.Fallback
|
||||
3, // [3:3] is the sub-list for method output_type
|
||||
3, // [3:3] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_trojan_config_proto_init() }
|
||||
func file_proxy_trojan_config_proto_init() {
|
||||
if File_proxy_trojan_config_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_proxy_trojan_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Account); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_proxy_trojan_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Fallback); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_proxy_trojan_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*ClientConfig); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_proxy_trojan_config_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*ServerConfig); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_proxy_trojan_config_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 4,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_trojan_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_trojan_config_proto_depIdxs,
|
||||
MessageInfos: file_proxy_trojan_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_trojan_config_proto = out.File
|
||||
file_proxy_trojan_config_proto_rawDesc = nil
|
||||
file_proxy_trojan_config_proto_goTypes = nil
|
||||
file_proxy_trojan_config_proto_depIdxs = nil
|
||||
}
|
32
proxy/trojan/config.proto
Normal file
32
proxy/trojan/config.proto
Normal file
|
@ -0,0 +1,32 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package xray.proxy.trojan;
|
||||
option csharp_namespace = "Xray.Proxy.Trojan";
|
||||
option go_package = "github.com/xtls/xray-core/v1/proxy/trojan";
|
||||
option java_package = "com.xray.proxy.trojan";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/protocol/user.proto";
|
||||
import "common/protocol/server_spec.proto";
|
||||
|
||||
message Account {
|
||||
string password = 1;
|
||||
string flow = 2;
|
||||
}
|
||||
|
||||
message Fallback {
|
||||
string alpn = 1;
|
||||
string path = 2;
|
||||
string type = 3;
|
||||
string dest = 4;
|
||||
uint64 xver = 5;
|
||||
}
|
||||
|
||||
message ClientConfig {
|
||||
repeated xray.common.protocol.ServerEndpoint server = 1;
|
||||
}
|
||||
|
||||
message ServerConfig {
|
||||
repeated xray.common.protocol.User users = 1;
|
||||
repeated Fallback fallbacks = 3;
|
||||
}
|
9
proxy/trojan/errors.generated.go
Normal file
9
proxy/trojan/errors.generated.go
Normal file
|
@ -0,0 +1,9 @@
|
|||
package trojan
|
||||
|
||||
import "github.com/xtls/xray-core/v1/common/errors"
|
||||
|
||||
type errPathObjHolder struct{}
|
||||
|
||||
func newError(values ...interface{}) *errors.Error {
|
||||
return errors.New(values...).WithPathObj(errPathObjHolder{})
|
||||
}
|
341
proxy/trojan/protocol.go
Normal file
341
proxy/trojan/protocol.go
Normal file
|
@ -0,0 +1,341 @@
|
|||
package trojan
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
fmt "fmt"
|
||||
"io"
|
||||
"syscall"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/buf"
|
||||
"github.com/xtls/xray-core/v1/common/errors"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
"github.com/xtls/xray-core/v1/common/signal"
|
||||
"github.com/xtls/xray-core/v1/features/stats"
|
||||
"github.com/xtls/xray-core/v1/transport/internet/xtls"
|
||||
)
|
||||
|
||||
var (
|
||||
crlf = []byte{'\r', '\n'}
|
||||
|
||||
addrParser = protocol.NewAddressParser(
|
||||
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
|
||||
protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
|
||||
protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
|
||||
)
|
||||
|
||||
trojanXTLSShow = false
|
||||
)
|
||||
|
||||
const (
|
||||
maxLength = 8192
|
||||
// XRD is constant for XTLS direct mode
|
||||
XRD = "xtls-rprx-direct"
|
||||
// XRO is constant for XTLS origin mode
|
||||
XRO = "xtls-rprx-origin"
|
||||
|
||||
commandTCP byte = 1
|
||||
commandUDP byte = 3
|
||||
|
||||
// for XTLS
|
||||
commandXRD byte = 0xf0 // XTLS direct mode
|
||||
commandXRO byte = 0xf1 // XTLS origin mode
|
||||
)
|
||||
|
||||
// ConnWriter is TCP Connection Writer Wrapper for trojan protocol
|
||||
type ConnWriter struct {
|
||||
io.Writer
|
||||
Target net.Destination
|
||||
Account *MemoryAccount
|
||||
Flow string
|
||||
headerSent bool
|
||||
}
|
||||
|
||||
// Write implements io.Writer
|
||||
func (c *ConnWriter) Write(p []byte) (n int, err error) {
|
||||
if !c.headerSent {
|
||||
if err := c.writeHeader(); err != nil {
|
||||
return 0, newError("failed to write request header").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
return c.Writer.Write(p)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer
|
||||
func (c *ConnWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
defer buf.ReleaseMulti(mb)
|
||||
|
||||
for _, b := range mb {
|
||||
if !b.IsEmpty() {
|
||||
if _, err := c.Write(b.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConnWriter) writeHeader() error {
|
||||
buffer := buf.StackNew()
|
||||
defer buffer.Release()
|
||||
|
||||
command := commandTCP
|
||||
if c.Target.Network == net.Network_UDP {
|
||||
command = commandUDP
|
||||
} else if c.Flow == XRO {
|
||||
command = commandXRO
|
||||
} else if c.Flow == XRD {
|
||||
command = commandXRD
|
||||
}
|
||||
|
||||
if _, err := buffer.Write(c.Account.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := buffer.Write(crlf); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := buffer.WriteByte(command); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := addrParser.WriteAddressPort(&buffer, c.Target.Address, c.Target.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := buffer.Write(crlf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := c.Writer.Write(buffer.Bytes())
|
||||
if err == nil {
|
||||
c.headerSent = true
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// PacketWriter UDP Connection Writer Wrapper for trojan protocol
|
||||
type PacketWriter struct {
|
||||
io.Writer
|
||||
Target net.Destination
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer
|
||||
func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
b := make([]byte, maxLength)
|
||||
for !mb.IsEmpty() {
|
||||
var length int
|
||||
mb, length = buf.SplitBytes(mb, b)
|
||||
if _, err := w.writePacket(b[:length], w.Target); err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteMultiBufferWithMetadata writes udp packet with destination specified
|
||||
func (w *PacketWriter) WriteMultiBufferWithMetadata(mb buf.MultiBuffer, dest net.Destination) error {
|
||||
b := make([]byte, maxLength)
|
||||
for !mb.IsEmpty() {
|
||||
var length int
|
||||
mb, length = buf.SplitBytes(mb, b)
|
||||
if _, err := w.writePacket(b[:length], dest); err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *PacketWriter) writePacket(payload []byte, dest net.Destination) (int, error) {
|
||||
buffer := buf.StackNew()
|
||||
defer buffer.Release()
|
||||
|
||||
length := len(payload)
|
||||
lengthBuf := [2]byte{}
|
||||
binary.BigEndian.PutUint16(lengthBuf[:], uint16(length))
|
||||
if err := addrParser.WriteAddressPort(&buffer, dest.Address, dest.Port); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := buffer.Write(lengthBuf[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := buffer.Write(crlf); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := buffer.Write(payload); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
_, err := w.Write(buffer.Bytes())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return length, nil
|
||||
}
|
||||
|
||||
// ConnReader is TCP Connection Reader Wrapper for trojan protocol
|
||||
type ConnReader struct {
|
||||
io.Reader
|
||||
Target net.Destination
|
||||
Flow string
|
||||
headerParsed bool
|
||||
}
|
||||
|
||||
// ParseHeader parses the trojan protocol header
|
||||
func (c *ConnReader) ParseHeader() error {
|
||||
var crlf [2]byte
|
||||
var command [1]byte
|
||||
var hash [56]byte
|
||||
if _, err := io.ReadFull(c.Reader, hash[:]); err != nil {
|
||||
return newError("failed to read user hash").Base(err)
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil {
|
||||
return newError("failed to read crlf").Base(err)
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(c.Reader, command[:]); err != nil {
|
||||
return newError("failed to read command").Base(err)
|
||||
}
|
||||
|
||||
network := net.Network_TCP
|
||||
if command[0] == commandUDP {
|
||||
network = net.Network_UDP
|
||||
} else if command[0] == commandXRO {
|
||||
c.Flow = XRO
|
||||
} else if command[0] == commandXRD {
|
||||
c.Flow = XRD
|
||||
}
|
||||
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, c.Reader)
|
||||
if err != nil {
|
||||
return newError("failed to read address and port").Base(err)
|
||||
}
|
||||
c.Target = net.Destination{Network: network, Address: addr, Port: port}
|
||||
|
||||
if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil {
|
||||
return newError("failed to read crlf").Base(err)
|
||||
}
|
||||
|
||||
c.headerParsed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read implements io.Reader
|
||||
func (c *ConnReader) Read(p []byte) (int, error) {
|
||||
if !c.headerParsed {
|
||||
if err := c.ParseHeader(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return c.Reader.Read(p)
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader
|
||||
func (c *ConnReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
b := buf.New()
|
||||
_, err := b.ReadFrom(c)
|
||||
return buf.MultiBuffer{b}, err
|
||||
}
|
||||
|
||||
// PacketPayload combines udp payload and destination
|
||||
type PacketPayload struct {
|
||||
Target net.Destination
|
||||
Buffer buf.MultiBuffer
|
||||
}
|
||||
|
||||
// PacketReader is UDP Connection Reader Wrapper for trojan protocol
|
||||
type PacketReader struct {
|
||||
io.Reader
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader
|
||||
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
p, err := r.ReadMultiBufferWithMetadata()
|
||||
if p != nil {
|
||||
return p.Buffer, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// ReadMultiBufferWithMetadata reads udp packet with destination
|
||||
func (r *PacketReader) ReadMultiBufferWithMetadata() (*PacketPayload, error) {
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, r)
|
||||
if err != nil {
|
||||
return nil, newError("failed to read address and port").Base(err)
|
||||
}
|
||||
|
||||
var lengthBuf [2]byte
|
||||
if _, err := io.ReadFull(r, lengthBuf[:]); err != nil {
|
||||
return nil, newError("failed to read payload length").Base(err)
|
||||
}
|
||||
|
||||
remain := int(binary.BigEndian.Uint16(lengthBuf[:]))
|
||||
if remain > maxLength {
|
||||
return nil, newError("oversize payload")
|
||||
}
|
||||
|
||||
var crlf [2]byte
|
||||
if _, err := io.ReadFull(r, crlf[:]); err != nil {
|
||||
return nil, newError("failed to read crlf").Base(err)
|
||||
}
|
||||
|
||||
dest := net.UDPDestination(addr, port)
|
||||
var mb buf.MultiBuffer
|
||||
for remain > 0 {
|
||||
length := buf.Size
|
||||
if remain < length {
|
||||
length = remain
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
mb = append(mb, b)
|
||||
n, err := b.ReadFullFrom(r, int32(length))
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
return nil, newError("failed to read payload").Base(err)
|
||||
}
|
||||
|
||||
remain -= int(n)
|
||||
}
|
||||
|
||||
return &PacketPayload{Target: dest, Buffer: mb}, nil
|
||||
}
|
||||
|
||||
func ReadV(reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, conn *xtls.Conn, rawConn syscall.RawConn, counter stats.Counter) error {
|
||||
err := func() error {
|
||||
var ct stats.Counter
|
||||
for {
|
||||
if conn.DirectIn {
|
||||
conn.DirectIn = false
|
||||
reader = buf.NewReadVReader(conn.Connection, rawConn)
|
||||
ct = counter
|
||||
if conn.SHOW {
|
||||
fmt.Println(conn.MARK, "ReadV")
|
||||
}
|
||||
}
|
||||
buffer, err := reader.ReadMultiBuffer()
|
||||
if !buffer.IsEmpty() {
|
||||
if ct != nil {
|
||||
ct.Add(int64(buffer.Len()))
|
||||
}
|
||||
timer.Update()
|
||||
if werr := writer.WriteMultiBuffer(buffer); werr != nil {
|
||||
return werr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}()
|
||||
if err != nil && errors.Cause(err) != io.EOF {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
91
proxy/trojan/protocol_test.go
Normal file
91
proxy/trojan/protocol_test.go
Normal file
|
@ -0,0 +1,91 @@
|
|||
package trojan_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/buf"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
. "github.com/xtls/xray-core/v1/proxy/trojan"
|
||||
)
|
||||
|
||||
func toAccount(a *Account) protocol.Account {
|
||||
account, err := a.AsAccount()
|
||||
common.Must(err)
|
||||
return account
|
||||
}
|
||||
|
||||
func TestTCPRequest(t *testing.T) {
|
||||
user := &protocol.MemoryUser{
|
||||
Email: "love@example.com",
|
||||
Account: toAccount(&Account{
|
||||
Password: "password",
|
||||
}),
|
||||
}
|
||||
payload := []byte("test string")
|
||||
data := buf.New()
|
||||
common.Must2(data.Write(payload))
|
||||
|
||||
buffer := buf.New()
|
||||
defer buffer.Release()
|
||||
|
||||
destination := net.Destination{Network: net.Network_TCP, Address: net.LocalHostIP, Port: 1234}
|
||||
writer := &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)}
|
||||
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data}))
|
||||
|
||||
reader := &ConnReader{Reader: buffer}
|
||||
common.Must(reader.ParseHeader())
|
||||
|
||||
if r := cmp.Diff(reader.Target, destination); r != "" {
|
||||
t.Error("destination: ", r)
|
||||
}
|
||||
|
||||
decodedData, err := reader.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
if r := cmp.Diff(decodedData[0].Bytes(), payload); r != "" {
|
||||
t.Error("data: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPRequest(t *testing.T) {
|
||||
user := &protocol.MemoryUser{
|
||||
Email: "love@example.com",
|
||||
Account: toAccount(&Account{
|
||||
Password: "password",
|
||||
}),
|
||||
}
|
||||
payload := []byte("test string")
|
||||
data := buf.New()
|
||||
common.Must2(data.Write(payload))
|
||||
|
||||
buffer := buf.New()
|
||||
defer buffer.Release()
|
||||
|
||||
destination := net.Destination{Network: net.Network_UDP, Address: net.LocalHostIP, Port: 1234}
|
||||
writer := &PacketWriter{Writer: &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)}, Target: destination}
|
||||
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data}))
|
||||
|
||||
connReader := &ConnReader{Reader: buffer}
|
||||
common.Must(connReader.ParseHeader())
|
||||
|
||||
packetReader := &PacketReader{Reader: connReader}
|
||||
p, err := packetReader.ReadMultiBufferWithMetadata()
|
||||
common.Must(err)
|
||||
|
||||
if p.Buffer.IsEmpty() {
|
||||
t.Error("no request data")
|
||||
}
|
||||
|
||||
if r := cmp.Diff(p.Target, destination); r != "" {
|
||||
t.Error("destination: ", r)
|
||||
}
|
||||
|
||||
mb, decoded := buf.SplitFirst(p.Buffer)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
if r := cmp.Diff(decoded.Bytes(), payload); r != "" {
|
||||
t.Error("data: ", r)
|
||||
}
|
||||
}
|
489
proxy/trojan/server.go
Normal file
489
proxy/trojan/server.go
Normal file
|
@ -0,0 +1,489 @@
|
|||
// +build !confonly
|
||||
|
||||
package trojan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common"
|
||||
"github.com/xtls/xray-core/v1/common/buf"
|
||||
"github.com/xtls/xray-core/v1/common/errors"
|
||||
"github.com/xtls/xray-core/v1/common/log"
|
||||
"github.com/xtls/xray-core/v1/common/net"
|
||||
"github.com/xtls/xray-core/v1/common/platform"
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
udp_proto "github.com/xtls/xray-core/v1/common/protocol/udp"
|
||||
"github.com/xtls/xray-core/v1/common/retry"
|
||||
"github.com/xtls/xray-core/v1/common/session"
|
||||
"github.com/xtls/xray-core/v1/common/signal"
|
||||
"github.com/xtls/xray-core/v1/common/task"
|
||||
core "github.com/xtls/xray-core/v1/core"
|
||||
"github.com/xtls/xray-core/v1/features/policy"
|
||||
"github.com/xtls/xray-core/v1/features/routing"
|
||||
"github.com/xtls/xray-core/v1/features/stats"
|
||||
"github.com/xtls/xray-core/v1/transport/internet"
|
||||
"github.com/xtls/xray-core/v1/transport/internet/udp"
|
||||
"github.com/xtls/xray-core/v1/transport/internet/xtls"
|
||||
)
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return NewServer(ctx, config.(*ServerConfig))
|
||||
}))
|
||||
|
||||
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
|
||||
|
||||
xtlsShow := platform.NewEnvFlag("xray.trojan.xtls.show").GetValue(func() string { return defaultFlagValue })
|
||||
if xtlsShow == "true" {
|
||||
trojanXTLSShow = true
|
||||
}
|
||||
}
|
||||
|
||||
// Server is an inbound connection handler that handles messages in trojan protocol.
|
||||
type Server struct {
|
||||
policyManager policy.Manager
|
||||
validator *Validator
|
||||
fallbacks map[string]map[string]*Fallback // or nil
|
||||
}
|
||||
|
||||
// NewServer creates a new trojan inbound handler.
|
||||
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
validator := new(Validator)
|
||||
for _, user := range config.Users {
|
||||
u, err := user.ToMemoryUser()
|
||||
if err != nil {
|
||||
return nil, newError("failed to get trojan user").Base(err).AtError()
|
||||
}
|
||||
|
||||
if err := validator.Add(u); err != nil {
|
||||
return nil, newError("failed to add user").Base(err).AtError()
|
||||
}
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
server := &Server{
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
validator: validator,
|
||||
}
|
||||
|
||||
if config.Fallbacks != nil {
|
||||
server.fallbacks = make(map[string]map[string]*Fallback)
|
||||
for _, fb := range config.Fallbacks {
|
||||
if server.fallbacks[fb.Alpn] == nil {
|
||||
server.fallbacks[fb.Alpn] = make(map[string]*Fallback)
|
||||
}
|
||||
server.fallbacks[fb.Alpn][fb.Path] = fb
|
||||
}
|
||||
if server.fallbacks[""] != nil {
|
||||
for alpn, pfb := range server.fallbacks {
|
||||
if alpn != "" { // && alpn != "h2" {
|
||||
for path, fb := range server.fallbacks[""] {
|
||||
if pfb[path] == nil {
|
||||
pfb[path] = fb
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// AddUser implements proxy.UserManager.AddUser().
|
||||
func (s *Server) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
|
||||
return s.validator.Add(u)
|
||||
}
|
||||
|
||||
// RemoveUser implements proxy.UserManager.RemoveUser().
|
||||
func (s *Server) RemoveUser(ctx context.Context, e string) error {
|
||||
return s.validator.Del(e)
|
||||
}
|
||||
|
||||
// Network implements proxy.Inbound.Network().
|
||||
func (s *Server) Network() []net.Network {
|
||||
return []net.Network{net.Network_TCP, net.Network_UNIX}
|
||||
}
|
||||
|
||||
// Process implements proxy.Inbound.Process().
|
||||
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
|
||||
sid := session.ExportIDToError(ctx)
|
||||
|
||||
iConn := conn
|
||||
statConn, ok := iConn.(*internet.StatCouterConnection)
|
||||
if ok {
|
||||
iConn = statConn.Connection
|
||||
}
|
||||
|
||||
sessionPolicy := s.policyManager.ForLevel(0)
|
||||
if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
|
||||
return newError("unable to set read deadline").Base(err).AtWarning()
|
||||
}
|
||||
|
||||
first := buf.New()
|
||||
defer first.Release()
|
||||
|
||||
firstLen, err := first.ReadFrom(conn)
|
||||
if err != nil {
|
||||
return newError("failed to read first request").Base(err)
|
||||
}
|
||||
newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
|
||||
|
||||
bufferedReader := &buf.BufferedReader{
|
||||
Reader: buf.NewReader(conn),
|
||||
Buffer: buf.MultiBuffer{first},
|
||||
}
|
||||
|
||||
var user *protocol.MemoryUser
|
||||
|
||||
apfb := s.fallbacks
|
||||
isfb := apfb != nil
|
||||
|
||||
shouldFallback := false
|
||||
if firstLen < 58 || first.Byte(56) != '\r' {
|
||||
// invalid protocol
|
||||
err = newError("not trojan protocol")
|
||||
log.Record(&log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
To: "",
|
||||
Status: log.AccessRejected,
|
||||
Reason: err,
|
||||
})
|
||||
|
||||
shouldFallback = true
|
||||
} else {
|
||||
user = s.validator.Get(hexString(first.BytesTo(56)))
|
||||
if user == nil {
|
||||
// invalid user, let's fallback
|
||||
err = newError("not a valid user")
|
||||
log.Record(&log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
To: "",
|
||||
Status: log.AccessRejected,
|
||||
Reason: err,
|
||||
})
|
||||
|
||||
shouldFallback = true
|
||||
}
|
||||
}
|
||||
|
||||
if isfb && shouldFallback {
|
||||
return s.fallback(ctx, sid, err, sessionPolicy, conn, iConn, apfb, first, firstLen, bufferedReader)
|
||||
} else if shouldFallback {
|
||||
return newError("invalid protocol or invalid user")
|
||||
}
|
||||
|
||||
clientReader := &ConnReader{Reader: bufferedReader}
|
||||
if err := clientReader.ParseHeader(); err != nil {
|
||||
log.Record(&log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
To: "",
|
||||
Status: log.AccessRejected,
|
||||
Reason: err,
|
||||
})
|
||||
return newError("failed to create request from: ", conn.RemoteAddr()).Base(err)
|
||||
}
|
||||
|
||||
destination := clientReader.Target
|
||||
if err := conn.SetReadDeadline(time.Time{}); err != nil {
|
||||
return newError("unable to set read deadline").Base(err).AtWarning()
|
||||
}
|
||||
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
if inbound == nil {
|
||||
panic("no inbound metadata")
|
||||
}
|
||||
inbound.User = user
|
||||
sessionPolicy = s.policyManager.ForLevel(user.Level)
|
||||
|
||||
if destination.Network == net.Network_UDP { // handle udp request
|
||||
return s.handleUDPPayload(ctx, &PacketReader{Reader: clientReader}, &PacketWriter{Writer: conn}, dispatcher)
|
||||
}
|
||||
|
||||
// handle tcp request
|
||||
account, ok := user.Account.(*MemoryAccount)
|
||||
if !ok {
|
||||
return newError("user account is not valid")
|
||||
}
|
||||
|
||||
var rawConn syscall.RawConn
|
||||
|
||||
switch clientReader.Flow {
|
||||
case XRO, XRD:
|
||||
if account.Flow == clientReader.Flow {
|
||||
if destination.Address.Family().IsDomain() && destination.Address.Domain() == muxCoolAddress {
|
||||
return newError(clientReader.Flow + " doesn't support Mux").AtWarning()
|
||||
}
|
||||
if xtlsConn, ok := iConn.(*xtls.Conn); ok {
|
||||
xtlsConn.RPRX = true
|
||||
xtlsConn.SHOW = trojanXTLSShow
|
||||
if clientReader.Flow == XRD {
|
||||
xtlsConn.DirectMode = true
|
||||
if sc, ok := xtlsConn.Connection.(syscall.Conn); ok {
|
||||
rawConn, _ = sc.SyscallConn()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return newError(`failed to use ` + clientReader.Flow + `, maybe "security" is not "xtls"`).AtWarning()
|
||||
}
|
||||
} else {
|
||||
return newError("unable to use ", clientReader.Flow).AtWarning()
|
||||
}
|
||||
case "":
|
||||
default:
|
||||
return newError("unsupported flow " + account.Flow).AtWarning()
|
||||
}
|
||||
|
||||
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
To: destination,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
Email: user.Email,
|
||||
})
|
||||
|
||||
newError("received request for ", destination).WriteToLog(sid)
|
||||
return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher, iConn, rawConn, statConn)
|
||||
}
|
||||
|
||||
func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReader, clientWriter *PacketWriter, dispatcher routing.Dispatcher) error {
|
||||
udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
|
||||
common.Must(clientWriter.WriteMultiBufferWithMetadata(buf.MultiBuffer{packet.Payload}, packet.Source))
|
||||
})
|
||||
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
user := inbound.User
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
default:
|
||||
p, err := clientReader.ReadMultiBufferWithMetadata()
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
return newError("unexpected EOF").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
||||
From: inbound.Source,
|
||||
To: p.Target,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
Email: user.Email,
|
||||
})
|
||||
newError("tunnelling request to ", p.Target).WriteToLog(session.ExportIDToError(ctx))
|
||||
|
||||
for _, b := range p.Buffer {
|
||||
udpServer.Dispatch(ctx, p.Target, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Session,
|
||||
destination net.Destination,
|
||||
clientReader buf.Reader,
|
||||
clientWriter buf.Writer, dispatcher routing.Dispatcher, iConn internet.Connection, rawConn syscall.RawConn, statConn *internet.StatCouterConnection) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
|
||||
|
||||
link, err := dispatcher.Dispatch(ctx, destination)
|
||||
if err != nil {
|
||||
return newError("failed to dispatch request to ", destination).Base(err)
|
||||
}
|
||||
|
||||
requestDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
var err error
|
||||
if rawConn != nil {
|
||||
var counter stats.Counter
|
||||
if statConn != nil {
|
||||
counter = statConn.ReadCounter
|
||||
}
|
||||
err = ReadV(clientReader, link.Writer, timer, iConn.(*xtls.Conn), rawConn, counter)
|
||||
} else {
|
||||
err = buf.Copy(clientReader, link.Writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
if err != nil {
|
||||
return newError("failed to transfer request").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
responseDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil {
|
||||
return newError("failed to write response").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
|
||||
common.Must(common.Interrupt(link.Reader))
|
||||
common.Must(common.Interrupt(link.Writer))
|
||||
return newError("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err error, sessionPolicy policy.Session, connection internet.Connection, iConn internet.Connection, apfb map[string]map[string]*Fallback, first *buf.Buffer, firstLen int64, reader buf.Reader) error {
|
||||
if err := connection.SetReadDeadline(time.Time{}); err != nil {
|
||||
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
|
||||
}
|
||||
newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
|
||||
|
||||
alpn := ""
|
||||
if len(apfb) > 1 || apfb[""] == nil {
|
||||
if tlsConn, ok := iConn.(*tls.Conn); ok {
|
||||
alpn = tlsConn.ConnectionState().NegotiatedProtocol
|
||||
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
|
||||
} else if xtlsConn, ok := iConn.(*xtls.Conn); ok {
|
||||
alpn = xtlsConn.ConnectionState().NegotiatedProtocol
|
||||
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
|
||||
}
|
||||
if apfb[alpn] == nil {
|
||||
alpn = ""
|
||||
}
|
||||
}
|
||||
pfb := apfb[alpn]
|
||||
if pfb == nil {
|
||||
return newError(`failed to find the default "alpn" config`).AtWarning()
|
||||
}
|
||||
|
||||
path := ""
|
||||
if len(pfb) > 1 || pfb[""] == nil {
|
||||
if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
|
||||
firstBytes := first.Bytes()
|
||||
for i := 4; i <= 8; i++ { // 5 -> 9
|
||||
if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
|
||||
search := len(firstBytes)
|
||||
if search > 64 {
|
||||
search = 64 // up to about 60
|
||||
}
|
||||
for j := i + 1; j < search; j++ {
|
||||
k := firstBytes[j]
|
||||
if k == '\r' || k == '\n' { // avoid logging \r or \n
|
||||
break
|
||||
}
|
||||
if k == ' ' {
|
||||
path = string(firstBytes[i:j])
|
||||
newError("realPath = " + path).AtInfo().WriteToLog(sid)
|
||||
if pfb[path] == nil {
|
||||
path = ""
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fb := pfb[path]
|
||||
if fb == nil {
|
||||
return newError(`failed to find the default "path" config`).AtWarning()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
|
||||
|
||||
var conn net.Conn
|
||||
if err := retry.ExponentialBackoff(5, 100).On(func() error {
|
||||
var dialer net.Dialer
|
||||
conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
serverReader := buf.NewReader(conn)
|
||||
serverWriter := buf.NewWriter(conn)
|
||||
|
||||
postRequest := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
if fb.Xver != 0 {
|
||||
remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ipv4 := true
|
||||
for i := 0; i < len(remoteAddr); i++ {
|
||||
if remoteAddr[i] == ':' {
|
||||
ipv4 = false
|
||||
break
|
||||
}
|
||||
}
|
||||
pro := buf.New()
|
||||
defer pro.Release()
|
||||
switch fb.Xver {
|
||||
case 1:
|
||||
if ipv4 {
|
||||
common.Must2(pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")))
|
||||
} else {
|
||||
common.Must2(pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")))
|
||||
}
|
||||
case 2:
|
||||
common.Must2(pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A\x21"))) // signature + v2 + PROXY
|
||||
if ipv4 {
|
||||
common.Must2(pro.Write([]byte("\x11\x00\x0C"))) // AF_INET + STREAM + 12 bytes
|
||||
common.Must2(pro.Write(net.ParseIP(remoteAddr).To4()))
|
||||
common.Must2(pro.Write(net.ParseIP(localAddr).To4()))
|
||||
} else {
|
||||
common.Must2(pro.Write([]byte("\x21\x00\x24"))) // AF_INET6 + STREAM + 36 bytes
|
||||
common.Must2(pro.Write(net.ParseIP(remoteAddr).To16()))
|
||||
common.Must2(pro.Write(net.ParseIP(localAddr).To16()))
|
||||
}
|
||||
p1, _ := strconv.ParseUint(remotePort, 10, 16)
|
||||
p2, _ := strconv.ParseUint(localPort, 10, 16)
|
||||
common.Must2(pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)}))
|
||||
}
|
||||
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
|
||||
return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
|
||||
}
|
||||
}
|
||||
if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
|
||||
return newError("failed to fallback request payload").Base(err).AtInfo()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
writer := buf.NewWriter(connection)
|
||||
|
||||
getResponse := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
|
||||
return newError("failed to deliver response payload").Base(err).AtInfo()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
|
||||
common.Must(common.Interrupt(serverReader))
|
||||
common.Must(common.Interrupt(serverWriter))
|
||||
return newError("fallback ends").Base(err).AtInfo()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
5
proxy/trojan/trojan.go
Normal file
5
proxy/trojan/trojan.go
Normal file
|
@ -0,0 +1,5 @@
|
|||
package trojan
|
||||
|
||||
const (
|
||||
muxCoolAddress = "v1.mux.cool"
|
||||
)
|
53
proxy/trojan/validator.go
Normal file
53
proxy/trojan/validator.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
// +build !confonly
|
||||
|
||||
package trojan
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/protocol"
|
||||
)
|
||||
|
||||
// Validator stores valid trojan users.
|
||||
type Validator struct {
|
||||
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
|
||||
email sync.Map
|
||||
users sync.Map
|
||||
}
|
||||
|
||||
// Add a trojan user, Email must be empty or unique.
|
||||
func (v *Validator) Add(u *protocol.MemoryUser) error {
|
||||
if u.Email != "" {
|
||||
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
|
||||
if loaded {
|
||||
return newError("User ", u.Email, " already exists.")
|
||||
}
|
||||
}
|
||||
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Del a trojan user with a non-empty Email.
|
||||
func (v *Validator) Del(e string) error {
|
||||
if e == "" {
|
||||
return newError("Email must not be empty.")
|
||||
}
|
||||
le := strings.ToLower(e)
|
||||
u, _ := v.email.Load(le)
|
||||
if u == nil {
|
||||
return newError("User ", e, " not found.")
|
||||
}
|
||||
v.email.Delete(le)
|
||||
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get a trojan user with hashed key, nil if user doesn't exist.
|
||||
func (v *Validator) Get(hash string) *protocol.MemoryUser {
|
||||
u, _ := v.users.Load(hash)
|
||||
if u != nil {
|
||||
return u.(*protocol.MemoryUser)
|
||||
}
|
||||
return nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue