This commit is contained in:
RPRX 2020-11-25 19:01:53 +08:00
parent 47d23e9972
commit c7f7c08ead
711 changed files with 82154 additions and 2 deletions

View file

@ -0,0 +1,11 @@
package protocol
// Account is a user identity used for authentication.
type Account interface {
Equals(Account) bool
}
// AsAccount is an object can be converted into account.
type AsAccount interface {
AsAccount() (Account, error)
}

258
common/protocol/address.go Normal file
View file

@ -0,0 +1,258 @@
package protocol
import (
"io"
"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/serial"
)
type AddressOption func(*option)
func PortThenAddress() AddressOption {
return func(p *option) {
p.portFirst = true
}
}
func AddressFamilyByte(b byte, f net.AddressFamily) AddressOption {
if b >= 16 {
panic("address family byte too big")
}
return func(p *option) {
p.addrTypeMap[b] = f
p.addrByteMap[f] = b
}
}
type AddressTypeParser func(byte) byte
func WithAddressTypeParser(atp AddressTypeParser) AddressOption {
return func(p *option) {
p.typeParser = atp
}
}
type AddressSerializer interface {
ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error)
WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error
}
const afInvalid = 255
type option struct {
addrTypeMap [16]net.AddressFamily
addrByteMap [16]byte
portFirst bool
typeParser AddressTypeParser
}
// NewAddressParser creates a new AddressParser
func NewAddressParser(options ...AddressOption) AddressSerializer {
var o option
for i := range o.addrByteMap {
o.addrByteMap[i] = afInvalid
}
for i := range o.addrTypeMap {
o.addrTypeMap[i] = net.AddressFamily(afInvalid)
}
for _, opt := range options {
opt(&o)
}
ap := &addressParser{
addrByteMap: o.addrByteMap,
addrTypeMap: o.addrTypeMap,
}
if o.typeParser != nil {
ap.typeParser = o.typeParser
}
if o.portFirst {
return portFirstAddressParser{ap: ap}
}
return portLastAddressParser{ap: ap}
}
type portFirstAddressParser struct {
ap *addressParser
}
func (p portFirstAddressParser) ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error) {
if buffer == nil {
buffer = buf.New()
defer buffer.Release()
}
port, err := readPort(buffer, input)
if err != nil {
return nil, 0, err
}
addr, err := p.ap.readAddress(buffer, input)
if err != nil {
return nil, 0, err
}
return addr, port, nil
}
func (p portFirstAddressParser) WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error {
if err := writePort(writer, port); err != nil {
return err
}
return p.ap.writeAddress(writer, addr)
}
type portLastAddressParser struct {
ap *addressParser
}
func (p portLastAddressParser) ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error) {
if buffer == nil {
buffer = buf.New()
defer buffer.Release()
}
addr, err := p.ap.readAddress(buffer, input)
if err != nil {
return nil, 0, err
}
port, err := readPort(buffer, input)
if err != nil {
return nil, 0, err
}
return addr, port, nil
}
func (p portLastAddressParser) WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error {
if err := p.ap.writeAddress(writer, addr); err != nil {
return err
}
return writePort(writer, port)
}
func readPort(b *buf.Buffer, reader io.Reader) (net.Port, error) {
if _, err := b.ReadFullFrom(reader, 2); err != nil {
return 0, err
}
return net.PortFromBytes(b.BytesFrom(-2)), nil
}
func writePort(writer io.Writer, port net.Port) error {
return common.Error2(serial.WriteUint16(writer, port.Value()))
}
func maybeIPPrefix(b byte) bool {
return b == '[' || (b >= '0' && b <= '9')
}
func isValidDomain(d string) bool {
for _, c := range d {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '.' || c == '_') {
return false
}
}
return true
}
type addressParser struct {
addrTypeMap [16]net.AddressFamily
addrByteMap [16]byte
typeParser AddressTypeParser
}
func (p *addressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Address, error) {
if _, err := b.ReadFullFrom(reader, 1); err != nil {
return nil, err
}
addrType := b.Byte(b.Len() - 1)
if p.typeParser != nil {
addrType = p.typeParser(addrType)
}
if addrType >= 16 {
return nil, newError("unknown address type: ", addrType)
}
addrFamily := p.addrTypeMap[addrType]
if addrFamily == net.AddressFamily(afInvalid) {
return nil, newError("unknown address type: ", addrType)
}
switch addrFamily {
case net.AddressFamilyIPv4:
if _, err := b.ReadFullFrom(reader, 4); err != nil {
return nil, err
}
return net.IPAddress(b.BytesFrom(-4)), nil
case net.AddressFamilyIPv6:
if _, err := b.ReadFullFrom(reader, 16); err != nil {
return nil, err
}
return net.IPAddress(b.BytesFrom(-16)), nil
case net.AddressFamilyDomain:
if _, err := b.ReadFullFrom(reader, 1); err != nil {
return nil, err
}
domainLength := int32(b.Byte(b.Len() - 1))
if _, err := b.ReadFullFrom(reader, domainLength); err != nil {
return nil, err
}
domain := string(b.BytesFrom(-domainLength))
if maybeIPPrefix(domain[0]) {
addr := net.ParseAddress(domain)
if addr.Family().IsIP() {
return addr, nil
}
}
if !isValidDomain(domain) {
return nil, newError("invalid domain name: ", domain)
}
return net.DomainAddress(domain), nil
default:
panic("impossible case")
}
}
func (p *addressParser) writeAddress(writer io.Writer, address net.Address) error {
tb := p.addrByteMap[address.Family()]
if tb == afInvalid {
return newError("unknown address family", address.Family())
}
switch address.Family() {
case net.AddressFamilyIPv4, net.AddressFamilyIPv6:
if _, err := writer.Write([]byte{tb}); err != nil {
return err
}
if _, err := writer.Write(address.IP()); err != nil {
return err
}
case net.AddressFamilyDomain:
domain := address.Domain()
if isDomainTooLong(domain) {
return newError("Super long domain is not supported: ", domain)
}
if _, err := writer.Write([]byte{tb, byte(len(domain))}); err != nil {
return err
}
if _, err := writer.Write([]byte(domain)); err != nil {
return err
}
default:
panic("Unknown family type.")
}
return nil
}

View file

@ -0,0 +1,242 @@
package protocol_test
import (
"bytes"
"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"
)
func TestAddressReading(t *testing.T) {
data := []struct {
Options []AddressOption
Input []byte
Address net.Address
Port net.Port
Error bool
}{
{
Options: []AddressOption{},
Input: []byte{},
Error: true,
},
{
Options: []AddressOption{},
Input: []byte{0, 0, 0, 0, 0},
Error: true,
},
{
Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)},
Input: []byte{1, 0, 0, 0, 0, 0, 53},
Address: net.IPAddress([]byte{0, 0, 0, 0}),
Port: net.Port(53),
},
{
Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4), PortThenAddress()},
Input: []byte{0, 53, 1, 0, 0, 0, 0},
Address: net.IPAddress([]byte{0, 0, 0, 0}),
Port: net.Port(53),
},
{
Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)},
Input: []byte{1, 0, 0, 0, 0},
Error: true,
},
{
Options: []AddressOption{AddressFamilyByte(0x04, net.AddressFamilyIPv6)},
Input: []byte{4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 80},
Address: net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}),
Port: net.Port(80),
},
{
Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)},
Input: []byte{3, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0, 80},
Address: net.DomainAddress("example.com"),
Port: net.Port(80),
},
{
Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)},
Input: []byte{3, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0},
Error: true,
},
{
Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)},
Input: []byte{3, 7, 56, 46, 56, 46, 56, 46, 56, 0, 80},
Address: net.ParseAddress("8.8.8.8"),
Port: net.Port(80),
},
{
Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)},
Input: []byte{3, 7, 10, 46, 56, 46, 56, 46, 56, 0, 80},
Error: true,
},
{
Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)},
Input: append(append([]byte{3, 24}, []byte("2a00:1450:4007:816::200e")...), 0, 80),
Address: net.ParseAddress("2a00:1450:4007:816::200e"),
Port: net.Port(80),
},
}
for _, tc := range data {
b := buf.New()
parser := NewAddressParser(tc.Options...)
addr, port, err := parser.ReadAddressPort(b, bytes.NewReader(tc.Input))
b.Release()
if tc.Error {
if err == nil {
t.Errorf("Expect error but not: %v", tc)
}
} else {
if err != nil {
t.Errorf("Expect no error but: %s %v", err.Error(), tc)
}
if addr != tc.Address {
t.Error("Got address ", addr.String(), " want ", tc.Address.String())
}
if tc.Port != port {
t.Error("Got port ", port, " want ", tc.Port)
}
}
}
}
func TestAddressWriting(t *testing.T) {
data := []struct {
Options []AddressOption
Address net.Address
Port net.Port
Bytes []byte
Error bool
}{
{
Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)},
Address: net.LocalHostIP,
Port: net.Port(80),
Bytes: []byte{1, 127, 0, 0, 1, 0, 80},
},
}
for _, tc := range data {
parser := NewAddressParser(tc.Options...)
b := buf.New()
err := parser.WriteAddressPort(b, tc.Address, tc.Port)
if tc.Error {
if err == nil {
t.Error("Expect error but nil")
}
} else {
common.Must(err)
if diff := cmp.Diff(tc.Bytes, b.Bytes()); diff != "" {
t.Error(err)
}
}
}
}
func BenchmarkAddressReadingIPv4(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x01, net.AddressFamilyIPv4))
cache := buf.New()
defer cache.Release()
payload := buf.New()
defer payload.Release()
raw := []byte{1, 0, 0, 0, 0, 0, 53}
payload.Write(raw)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, err := parser.ReadAddressPort(cache, payload)
common.Must(err)
cache.Clear()
payload.Clear()
payload.Extend(int32(len(raw)))
}
}
func BenchmarkAddressReadingIPv6(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x04, net.AddressFamilyIPv6))
cache := buf.New()
defer cache.Release()
payload := buf.New()
defer payload.Release()
raw := []byte{4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 80}
payload.Write(raw)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, err := parser.ReadAddressPort(cache, payload)
common.Must(err)
cache.Clear()
payload.Clear()
payload.Extend(int32(len(raw)))
}
}
func BenchmarkAddressReadingDomain(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x03, net.AddressFamilyDomain))
cache := buf.New()
defer cache.Release()
payload := buf.New()
defer payload.Release()
raw := []byte{3, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0, 80}
payload.Write(raw)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, err := parser.ReadAddressPort(cache, payload)
common.Must(err)
cache.Clear()
payload.Clear()
payload.Extend(int32(len(raw)))
}
}
func BenchmarkAddressWritingIPv4(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x01, net.AddressFamilyIPv4))
writer := buf.New()
defer writer.Release()
b.ResetTimer()
for i := 0; i < b.N; i++ {
common.Must(parser.WriteAddressPort(writer, net.LocalHostIP, net.Port(80)))
writer.Clear()
}
}
func BenchmarkAddressWritingIPv6(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x04, net.AddressFamilyIPv6))
writer := buf.New()
defer writer.Release()
b.ResetTimer()
for i := 0; i < b.N; i++ {
common.Must(parser.WriteAddressPort(writer, net.LocalHostIPv6, net.Port(80)))
writer.Clear()
}
}
func BenchmarkAddressWritingDomain(b *testing.B) {
parser := NewAddressParser(AddressFamilyByte(0x02, net.AddressFamilyDomain))
writer := buf.New()
defer writer.Release()
b.ResetTimer()
for i := 0; i < b.N; i++ {
common.Must(parser.WriteAddressPort(writer, net.DomainAddress("www.example.com"), net.Port(80)))
writer.Clear()
}
}

View file

@ -0,0 +1,32 @@
package bittorrent
import (
"errors"
"github.com/xtls/xray-core/v1/common"
)
type SniffHeader struct {
}
func (h *SniffHeader) Protocol() string {
return "bittorrent"
}
func (h *SniffHeader) Domain() string {
return ""
}
var errNotBittorrent = errors.New("not bittorrent header")
func SniffBittorrent(b []byte) (*SniffHeader, error) {
if len(b) < 20 {
return nil, common.ErrNoClue
}
if b[0] == 19 && string(b[1:20]) == "BitTorrent protocol" {
return &SniffHeader{}, nil
}
return nil, errNotBittorrent
}

View file

@ -0,0 +1,23 @@
package protocol
import (
"context"
)
type key int
const (
requestKey key = iota
)
func ContextWithRequestHeader(ctx context.Context, request *RequestHeader) context.Context {
return context.WithValue(ctx, requestKey, request)
}
func RequestHeaderFromContext(ctx context.Context) *RequestHeader {
request := ctx.Value(requestKey)
if request == nil {
return nil
}
return request.(*RequestHeader)
}

View file

@ -0,0 +1,9 @@
package dns
import "github.com/xtls/xray-core/v1/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

143
common/protocol/dns/io.go Normal file
View file

@ -0,0 +1,143 @@
package dns
import (
"encoding/binary"
"sync"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/buf"
"github.com/xtls/xray-core/v1/common/serial"
"golang.org/x/net/dns/dnsmessage"
)
func PackMessage(msg *dnsmessage.Message) (*buf.Buffer, error) {
buffer := buf.New()
rawBytes := buffer.Extend(buf.Size)
packed, err := msg.AppendPack(rawBytes[:0])
if err != nil {
buffer.Release()
return nil, err
}
buffer.Resize(0, int32(len(packed)))
return buffer, nil
}
type MessageReader interface {
ReadMessage() (*buf.Buffer, error)
}
type UDPReader struct {
buf.Reader
access sync.Mutex
cache buf.MultiBuffer
}
func (r *UDPReader) readCache() *buf.Buffer {
r.access.Lock()
defer r.access.Unlock()
mb, b := buf.SplitFirst(r.cache)
r.cache = mb
return b
}
func (r *UDPReader) refill() error {
mb, err := r.Reader.ReadMultiBuffer()
if err != nil {
return err
}
r.access.Lock()
r.cache = mb
r.access.Unlock()
return nil
}
// ReadMessage implements MessageReader.
func (r *UDPReader) ReadMessage() (*buf.Buffer, error) {
for {
b := r.readCache()
if b != nil {
return b, nil
}
if err := r.refill(); err != nil {
return nil, err
}
}
}
// Close implements common.Closable.
func (r *UDPReader) Close() error {
defer func() {
r.access.Lock()
buf.ReleaseMulti(r.cache)
r.cache = nil
r.access.Unlock()
}()
return common.Close(r.Reader)
}
type TCPReader struct {
reader *buf.BufferedReader
}
func NewTCPReader(reader buf.Reader) *TCPReader {
return &TCPReader{
reader: &buf.BufferedReader{
Reader: reader,
},
}
}
func (r *TCPReader) ReadMessage() (*buf.Buffer, error) {
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
if size > buf.Size {
return nil, newError("message size too large: ", size)
}
b := buf.New()
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
return nil, err
}
return b, nil
}
func (r *TCPReader) Interrupt() {
common.Interrupt(r.reader)
}
func (r *TCPReader) Close() error {
return common.Close(r.reader)
}
type MessageWriter interface {
WriteMessage(msg *buf.Buffer) error
}
type UDPWriter struct {
buf.Writer
}
func (w *UDPWriter) WriteMessage(b *buf.Buffer) error {
return w.WriteMultiBuffer(buf.MultiBuffer{b})
}
type TCPWriter struct {
buf.Writer
}
func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
if b.IsEmpty() {
return nil
}
mb := make(buf.MultiBuffer, 0, 2)
size := buf.New()
binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len()))
mb = append(mb, size, b)
return w.WriteMultiBuffer(mb)
}

View file

@ -0,0 +1,9 @@
package protocol
import "github.com/xtls/xray-core/v1/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

View file

@ -0,0 +1,92 @@
package protocol
import (
"runtime"
"github.com/xtls/xray-core/v1/common/bitmask"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/common/uuid"
)
// RequestCommand is a custom command in a proxy request.
type RequestCommand byte
const (
RequestCommandTCP = RequestCommand(0x01)
RequestCommandUDP = RequestCommand(0x02)
RequestCommandMux = RequestCommand(0x03)
)
func (c RequestCommand) TransferType() TransferType {
switch c {
case RequestCommandTCP, RequestCommandMux:
return TransferTypeStream
case RequestCommandUDP:
return TransferTypePacket
default:
return TransferTypeStream
}
}
const (
// RequestOptionChunkStream indicates request payload is chunked. Each chunk consists of length, authentication and payload.
RequestOptionChunkStream bitmask.Byte = 0x01
// RequestOptionConnectionReuse indicates client side expects to reuse the connection.
RequestOptionConnectionReuse bitmask.Byte = 0x02
RequestOptionChunkMasking bitmask.Byte = 0x04
RequestOptionGlobalPadding bitmask.Byte = 0x08
)
type RequestHeader struct {
Version byte
Command RequestCommand
Option bitmask.Byte
Security SecurityType
Port net.Port
Address net.Address
User *MemoryUser
}
func (h *RequestHeader) Destination() net.Destination {
if h.Command == RequestCommandUDP {
return net.UDPDestination(h.Address, h.Port)
}
return net.TCPDestination(h.Address, h.Port)
}
const (
ResponseOptionConnectionReuse bitmask.Byte = 0x01
)
type ResponseCommand interface{}
type ResponseHeader struct {
Option bitmask.Byte
Command ResponseCommand
}
type CommandSwitchAccount struct {
Host net.Address
Port net.Port
ID uuid.UUID
Level uint32
AlterIds uint16
ValidMin byte
}
func (sc *SecurityConfig) GetSecurityType() SecurityType {
if sc == nil || sc.Type == SecurityType_AUTO {
if runtime.GOARCH == "amd64" || runtime.GOARCH == "s390x" || runtime.GOARCH == "arm64" {
return SecurityType_AES128_GCM
}
return SecurityType_CHACHA20_POLY1305
}
return sc.Type
}
func isDomainTooLong(domain string) bool {
return len(domain) > 256
}

View file

@ -0,0 +1,224 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: common/protocol/headers.proto
package protocol
import (
proto "github.com/golang/protobuf/proto"
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 SecurityType int32
const (
SecurityType_UNKNOWN SecurityType = 0
SecurityType_LEGACY SecurityType = 1
SecurityType_AUTO SecurityType = 2
SecurityType_AES128_GCM SecurityType = 3
SecurityType_CHACHA20_POLY1305 SecurityType = 4
SecurityType_NONE SecurityType = 5
)
// Enum value maps for SecurityType.
var (
SecurityType_name = map[int32]string{
0: "UNKNOWN",
1: "LEGACY",
2: "AUTO",
3: "AES128_GCM",
4: "CHACHA20_POLY1305",
5: "NONE",
}
SecurityType_value = map[string]int32{
"UNKNOWN": 0,
"LEGACY": 1,
"AUTO": 2,
"AES128_GCM": 3,
"CHACHA20_POLY1305": 4,
"NONE": 5,
}
)
func (x SecurityType) Enum() *SecurityType {
p := new(SecurityType)
*p = x
return p
}
func (x SecurityType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (SecurityType) Descriptor() protoreflect.EnumDescriptor {
return file_common_protocol_headers_proto_enumTypes[0].Descriptor()
}
func (SecurityType) Type() protoreflect.EnumType {
return &file_common_protocol_headers_proto_enumTypes[0]
}
func (x SecurityType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use SecurityType.Descriptor instead.
func (SecurityType) EnumDescriptor() ([]byte, []int) {
return file_common_protocol_headers_proto_rawDescGZIP(), []int{0}
}
type SecurityConfig struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Type SecurityType `protobuf:"varint,1,opt,name=type,proto3,enum=xray.common.protocol.SecurityType" json:"type,omitempty"`
}
func (x *SecurityConfig) Reset() {
*x = SecurityConfig{}
if protoimpl.UnsafeEnabled {
mi := &file_common_protocol_headers_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SecurityConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SecurityConfig) ProtoMessage() {}
func (x *SecurityConfig) ProtoReflect() protoreflect.Message {
mi := &file_common_protocol_headers_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 SecurityConfig.ProtoReflect.Descriptor instead.
func (*SecurityConfig) Descriptor() ([]byte, []int) {
return file_common_protocol_headers_proto_rawDescGZIP(), []int{0}
}
func (x *SecurityConfig) GetType() SecurityType {
if x != nil {
return x.Type
}
return SecurityType_UNKNOWN
}
var File_common_protocol_headers_proto protoreflect.FileDescriptor
var file_common_protocol_headers_proto_rawDesc = []byte{
0x0a, 0x1d, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f,
0x6c, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x14, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x48, 0x0a, 0x0e, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74,
0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x36, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18,
0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x22, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d,
0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x65, 0x63,
0x75, 0x72, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x2a,
0x62, 0x0a, 0x0c, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12,
0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06,
0x4c, 0x45, 0x47, 0x41, 0x43, 0x59, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x41, 0x55, 0x54, 0x4f,
0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x41, 0x45, 0x53, 0x31, 0x32, 0x38, 0x5f, 0x47, 0x43, 0x4d,
0x10, 0x03, 0x12, 0x15, 0x0a, 0x11, 0x43, 0x48, 0x41, 0x43, 0x48, 0x41, 0x32, 0x30, 0x5f, 0x50,
0x4f, 0x4c, 0x59, 0x31, 0x33, 0x30, 0x35, 0x10, 0x04, 0x12, 0x08, 0x0a, 0x04, 0x4e, 0x4f, 0x4e,
0x45, 0x10, 0x05, 0x42, 0x61, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e,
0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x50,
0x01, 0x5a, 0x2c, 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,
0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0xaa,
0x02, 0x14, 0x58, 0x72, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x50, 0x72,
0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_common_protocol_headers_proto_rawDescOnce sync.Once
file_common_protocol_headers_proto_rawDescData = file_common_protocol_headers_proto_rawDesc
)
func file_common_protocol_headers_proto_rawDescGZIP() []byte {
file_common_protocol_headers_proto_rawDescOnce.Do(func() {
file_common_protocol_headers_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_protocol_headers_proto_rawDescData)
})
return file_common_protocol_headers_proto_rawDescData
}
var file_common_protocol_headers_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_common_protocol_headers_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_common_protocol_headers_proto_goTypes = []interface{}{
(SecurityType)(0), // 0: xray.common.protocol.SecurityType
(*SecurityConfig)(nil), // 1: xray.common.protocol.SecurityConfig
}
var file_common_protocol_headers_proto_depIdxs = []int32{
0, // 0: xray.common.protocol.SecurityConfig.type:type_name -> xray.common.protocol.SecurityType
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_common_protocol_headers_proto_init() }
func file_common_protocol_headers_proto_init() {
if File_common_protocol_headers_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_common_protocol_headers_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SecurityConfig); 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_common_protocol_headers_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_common_protocol_headers_proto_goTypes,
DependencyIndexes: file_common_protocol_headers_proto_depIdxs,
EnumInfos: file_common_protocol_headers_proto_enumTypes,
MessageInfos: file_common_protocol_headers_proto_msgTypes,
}.Build()
File_common_protocol_headers_proto = out.File
file_common_protocol_headers_proto_rawDesc = nil
file_common_protocol_headers_proto_goTypes = nil
file_common_protocol_headers_proto_depIdxs = nil
}

View file

@ -0,0 +1,20 @@
syntax = "proto3";
package xray.common.protocol;
option csharp_namespace = "Xray.Common.Protocol";
option go_package = "github.com/xtls/xray-core/v1/common/protocol";
option java_package = "com.xray.common.protocol";
option java_multiple_files = true;
enum SecurityType {
UNKNOWN = 0;
LEGACY = 1;
AUTO = 2;
AES128_GCM = 3;
CHACHA20_POLY1305 = 4;
NONE = 5;
}
message SecurityConfig {
SecurityType type = 1;
}

View file

@ -0,0 +1,68 @@
package http
import (
"net/http"
"strconv"
"strings"
"github.com/xtls/xray-core/v1/common/net"
)
// ParseXForwardedFor parses X-Forwarded-For header in http headers, and return the IP list in it.
func ParseXForwardedFor(header http.Header) []net.Address {
xff := header.Get("X-Forwarded-For")
if xff == "" {
return nil
}
list := strings.Split(xff, ",")
addrs := make([]net.Address, 0, len(list))
for _, proxy := range list {
addrs = append(addrs, net.ParseAddress(proxy))
}
return addrs
}
// RemoveHopByHopHeaders remove hop by hop headers in http header list.
func RemoveHopByHopHeaders(header http.Header) {
// Strip hop-by-hop header based on RFC:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
header.Del("Proxy-Connection")
header.Del("Proxy-Authenticate")
header.Del("Proxy-Authorization")
header.Del("TE")
header.Del("Trailers")
header.Del("Transfer-Encoding")
header.Del("Upgrade")
connections := header.Get("Connection")
header.Del("Connection")
if connections == "" {
return
}
for _, h := range strings.Split(connections, ",") {
header.Del(strings.TrimSpace(h))
}
}
// ParseHost splits host and port from a raw string. Default port is used when raw string doesn't contain port.
func ParseHost(rawHost string, defaultPort net.Port) (net.Destination, error) {
port := defaultPort
host, rawPort, err := net.SplitHostPort(rawHost)
if err != nil {
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
host = rawHost
} else {
return net.Destination{}, err
}
} else if len(rawPort) > 0 {
intPort, err := strconv.Atoi(rawPort)
if err != nil {
return net.Destination{}, err
}
port = net.Port(intPort)
}
return net.TCPDestination(net.ParseAddress(host), port), nil
}

View file

@ -0,0 +1,118 @@
package http_test
import (
"bufio"
"net/http"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/net"
. "github.com/xtls/xray-core/v1/common/protocol/http"
)
func TestParseXForwardedFor(t *testing.T) {
header := http.Header{}
header.Add("X-Forwarded-For", "129.78.138.66, 129.78.64.103")
addrs := ParseXForwardedFor(header)
if r := cmp.Diff(addrs, []net.Address{net.ParseAddress("129.78.138.66"), net.ParseAddress("129.78.64.103")}); r != "" {
t.Error(r)
}
}
func TestHopByHopHeadersRemoving(t *testing.T) {
rawRequest := `GET /pkg/net/http/ HTTP/1.1
Host: golang.org
Connection: keep-alive,Foo, Bar
Foo: foo
Bar: bar
Proxy-Connection: keep-alive
Proxy-Authenticate: abc
Accept-Encoding: gzip
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
Cache-Control: no-cache
Accept-Language: de,en;q=0.7,en-us;q=0.3
`
b := bufio.NewReader(strings.NewReader(rawRequest))
req, err := http.ReadRequest(b)
common.Must(err)
headers := []struct {
Key string
Value string
}{
{
Key: "Foo",
Value: "foo",
},
{
Key: "Bar",
Value: "bar",
},
{
Key: "Connection",
Value: "keep-alive,Foo, Bar",
},
{
Key: "Proxy-Connection",
Value: "keep-alive",
},
{
Key: "Proxy-Authenticate",
Value: "abc",
},
}
for _, header := range headers {
if v := req.Header.Get(header.Key); v != header.Value {
t.Error("header ", header.Key, " = ", v, " want ", header.Value)
}
}
RemoveHopByHopHeaders(req.Header)
for _, header := range []string{"Connection", "Foo", "Bar", "Proxy-Connection", "Proxy-Authenticate"} {
if v := req.Header.Get(header); v != "" {
t.Error("header ", header, " = ", v)
}
}
}
func TestParseHost(t *testing.T) {
testCases := []struct {
RawHost string
DefaultPort net.Port
Destination net.Destination
Error bool
}{
{
RawHost: "example.com:80",
DefaultPort: 443,
Destination: net.TCPDestination(net.DomainAddress("example.com"), 80),
},
{
RawHost: "tls.example.com",
DefaultPort: 443,
Destination: net.TCPDestination(net.DomainAddress("tls.example.com"), 443),
},
{
RawHost: "[2401:1bc0:51f0:ec08::1]:80",
DefaultPort: 443,
Destination: net.TCPDestination(net.ParseAddress("[2401:1bc0:51f0:ec08::1]"), 80),
},
}
for _, testCase := range testCases {
dest, err := ParseHost(testCase.RawHost, testCase.DefaultPort)
if testCase.Error {
if err == nil {
t.Error("for test case: ", testCase.RawHost, " expected error, but actually nil")
}
} else {
if dest != testCase.Destination {
t.Error("for test case: ", testCase.RawHost, " expected host: ", testCase.Destination.String(), " but got ", dest.String())
}
}
}
}

View file

@ -0,0 +1,94 @@
package http
import (
"bytes"
"errors"
"strings"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/net"
)
type version byte
const (
HTTP1 version = iota
HTTP2
)
type SniffHeader struct {
version version
host string
}
func (h *SniffHeader) Protocol() string {
switch h.version {
case HTTP1:
return "http1"
case HTTP2:
return "http2"
default:
return "unknown"
}
}
func (h *SniffHeader) Domain() string {
return h.host
}
var (
methods = [...]string{"get", "post", "head", "put", "delete", "options", "connect"}
errNotHTTPMethod = errors.New("not an HTTP method")
)
func beginWithHTTPMethod(b []byte) error {
for _, m := range &methods {
if len(b) >= len(m) && strings.EqualFold(string(b[:len(m)]), m) {
return nil
}
if len(b) < len(m) {
return common.ErrNoClue
}
}
return errNotHTTPMethod
}
func SniffHTTP(b []byte) (*SniffHeader, error) {
if err := beginWithHTTPMethod(b); err != nil {
return nil, err
}
sh := &SniffHeader{
version: HTTP1,
}
headers := bytes.Split(b, []byte{'\n'})
for i := 1; i < len(headers); i++ {
header := headers[i]
if len(header) == 0 {
break
}
parts := bytes.SplitN(header, []byte{':'}, 2)
if len(parts) != 2 {
continue
}
key := strings.ToLower(string(parts[0]))
if key == "host" {
rawHost := strings.ToLower(string(bytes.TrimSpace(parts[1])))
dest, err := ParseHost(rawHost, net.Port(80))
if err != nil {
return nil, err
}
sh.host = dest.Address.String()
}
}
if len(sh.host) > 0 {
return sh, nil
}
return nil, common.ErrNoClue
}

View file

@ -0,0 +1,105 @@
package http_test
import (
"testing"
. "github.com/xtls/xray-core/v1/common/protocol/http"
)
func TestHTTPHeaders(t *testing.T) {
cases := []struct {
input string
domain string
err bool
}{
{
input: `GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1
Host: net.tutsplus.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120
Pragma: no-cache
Cache-Control: no-cache`,
domain: "net.tutsplus.com",
},
{
input: `POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
first_name=John&last_name=Doe&action=Submit`,
domain: "localhost",
},
{
input: `X /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
first_name=John&last_name=Doe&action=Submit`,
domain: "",
err: true,
},
{
input: `GET /foo.php HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
Host: localhost
first_name=John&last_name=Doe&action=Submit`,
domain: "",
err: true,
},
{
input: `GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1`,
domain: "",
err: true,
},
}
for _, test := range cases {
header, err := SniffHTTP([]byte(test.input))
if test.err {
if err == nil {
t.Errorf("Expect error but nil, in test: %v", test)
}
} else {
if err != nil {
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
}
if header.Domain() != test.domain {
t.Error("expected domain ", test.domain, " but got ", header.Domain())
}
}
}
}

82
common/protocol/id.go Normal file
View file

@ -0,0 +1,82 @@
package protocol
import (
"crypto/hmac"
"crypto/md5"
"hash"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/uuid"
)
const (
IDBytesLen = 16
)
type IDHash func(key []byte) hash.Hash
func DefaultIDHash(key []byte) hash.Hash {
return hmac.New(md5.New, key)
}
// The ID of en entity, in the form of a UUID.
type ID struct {
uuid uuid.UUID
cmdKey [IDBytesLen]byte
}
// Equals returns true if this ID equals to the other one.
func (id *ID) Equals(another *ID) bool {
return id.uuid.Equals(&(another.uuid))
}
func (id *ID) Bytes() []byte {
return id.uuid.Bytes()
}
func (id *ID) String() string {
return id.uuid.String()
}
func (id *ID) UUID() uuid.UUID {
return id.uuid
}
func (id ID) CmdKey() []byte {
return id.cmdKey[:]
}
// NewID returns an ID with given UUID.
func NewID(uuid uuid.UUID) *ID {
id := &ID{uuid: uuid}
md5hash := md5.New()
common.Must2(md5hash.Write(uuid.Bytes()))
common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
md5hash.Sum(id.cmdKey[:0])
return id
}
func nextID(u *uuid.UUID) uuid.UUID {
md5hash := md5.New()
common.Must2(md5hash.Write(u.Bytes()))
common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")))
var newid uuid.UUID
for {
md5hash.Sum(newid[:0])
if !newid.Equals(u) {
return newid
}
common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")))
}
}
func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
alterIDs := make([]*ID, alterIDCount)
prevID := primary.UUID()
for idx := range alterIDs {
newid := nextID(&prevID)
alterIDs[idx] = NewID(newid)
prevID = newid
}
return alterIDs
}

View file

@ -0,0 +1,21 @@
package protocol_test
import (
"testing"
. "github.com/xtls/xray-core/v1/common/protocol"
"github.com/xtls/xray-core/v1/common/uuid"
)
func TestIdEquals(t *testing.T) {
id1 := NewID(uuid.New())
id2 := NewID(id1.UUID())
if !id1.Equals(id2) {
t.Error("expected id1 to equal id2, but actually not")
}
if id1.String() != id2.String() {
t.Error(id1.String(), " != ", id2.String())
}
}

View file

@ -0,0 +1,16 @@
package protocol
type TransferType byte
const (
TransferTypeStream TransferType = 0
TransferTypePacket TransferType = 1
)
type AddressType byte
const (
AddressTypeIPv4 AddressType = 1
AddressTypeDomain AddressType = 2
AddressTypeIPv6 AddressType = 3
)

View file

@ -0,0 +1,3 @@
package protocol // import "github.com/xtls/xray-core/v1/common/protocol"
//go:generate go run github.com/xtls/xray-core/v1/common/errors/errorgen

View file

@ -0,0 +1,89 @@
package protocol
import (
"sync"
)
type ServerList struct {
sync.RWMutex
servers []*ServerSpec
}
func NewServerList() *ServerList {
return &ServerList{}
}
func (sl *ServerList) AddServer(server *ServerSpec) {
sl.Lock()
defer sl.Unlock()
sl.servers = append(sl.servers, server)
}
func (sl *ServerList) Size() uint32 {
sl.RLock()
defer sl.RUnlock()
return uint32(len(sl.servers))
}
func (sl *ServerList) GetServer(idx uint32) *ServerSpec {
sl.Lock()
defer sl.Unlock()
for {
if idx >= uint32(len(sl.servers)) {
return nil
}
server := sl.servers[idx]
if !server.IsValid() {
sl.removeServer(idx)
continue
}
return server
}
}
func (sl *ServerList) removeServer(idx uint32) {
n := len(sl.servers)
sl.servers[idx] = sl.servers[n-1]
sl.servers = sl.servers[:n-1]
}
type ServerPicker interface {
PickServer() *ServerSpec
}
type RoundRobinServerPicker struct {
sync.Mutex
serverlist *ServerList
nextIndex uint32
}
func NewRoundRobinServerPicker(serverlist *ServerList) *RoundRobinServerPicker {
return &RoundRobinServerPicker{
serverlist: serverlist,
nextIndex: 0,
}
}
func (p *RoundRobinServerPicker) PickServer() *ServerSpec {
p.Lock()
defer p.Unlock()
next := p.nextIndex
server := p.serverlist.GetServer(next)
if server == nil {
next = 0
server = p.serverlist.GetServer(0)
}
next++
if next >= p.serverlist.Size() {
next = 0
}
p.nextIndex = next
return server
}

View file

@ -0,0 +1,71 @@
package protocol_test
import (
"testing"
"time"
"github.com/xtls/xray-core/v1/common/net"
. "github.com/xtls/xray-core/v1/common/protocol"
)
func TestServerList(t *testing.T) {
list := NewServerList()
list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid()))
if list.Size() != 1 {
t.Error("list size: ", list.Size())
}
list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
if list.Size() != 2 {
t.Error("list.size: ", list.Size())
}
server := list.GetServer(1)
if server.Destination().Port != 2 {
t.Error("server: ", server.Destination())
}
time.Sleep(2 * time.Second)
server = list.GetServer(1)
if server != nil {
t.Error("server: ", server)
}
server = list.GetServer(0)
if server.Destination().Port != 1 {
t.Error("server: ", server.Destination())
}
}
func TestServerPicker(t *testing.T) {
list := NewServerList()
list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid()))
list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(3)), BeforeTime(time.Now().Add(time.Second))))
picker := NewRoundRobinServerPicker(list)
server := picker.PickServer()
if server.Destination().Port != 1 {
t.Error("server: ", server.Destination())
}
server = picker.PickServer()
if server.Destination().Port != 2 {
t.Error("server: ", server.Destination())
}
server = picker.PickServer()
if server.Destination().Port != 3 {
t.Error("server: ", server.Destination())
}
server = picker.PickServer()
if server.Destination().Port != 1 {
t.Error("server: ", server.Destination())
}
time.Sleep(2 * time.Second)
server = picker.PickServer()
if server.Destination().Port != 1 {
t.Error("server: ", server.Destination())
}
server = picker.PickServer()
if server.Destination().Port != 1 {
t.Error("server: ", server.Destination())
}
}

View file

@ -0,0 +1,122 @@
package protocol
import (
"sync"
"time"
"github.com/xtls/xray-core/v1/common/dice"
"github.com/xtls/xray-core/v1/common/net"
)
type ValidationStrategy interface {
IsValid() bool
Invalidate()
}
type alwaysValidStrategy struct{}
func AlwaysValid() ValidationStrategy {
return alwaysValidStrategy{}
}
func (alwaysValidStrategy) IsValid() bool {
return true
}
func (alwaysValidStrategy) Invalidate() {}
type timeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
return &timeoutValidStrategy{
until: t,
}
}
func (s *timeoutValidStrategy) IsValid() bool {
return s.until.After(time.Now())
}
func (s *timeoutValidStrategy) Invalidate() {
s.until = time.Time{}
}
type ServerSpec struct {
sync.RWMutex
dest net.Destination
users []*MemoryUser
valid ValidationStrategy
}
func NewServerSpec(dest net.Destination, valid ValidationStrategy, users ...*MemoryUser) *ServerSpec {
return &ServerSpec{
dest: dest,
users: users,
valid: valid,
}
}
func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) {
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
mUsers := make([]*MemoryUser, len(spec.User))
for idx, u := range spec.User {
mUser, err := u.ToMemoryUser()
if err != nil {
return nil, err
}
mUsers[idx] = mUser
}
return NewServerSpec(dest, AlwaysValid(), mUsers...), nil
}
func (s *ServerSpec) Destination() net.Destination {
return s.dest
}
func (s *ServerSpec) HasUser(user *MemoryUser) bool {
s.RLock()
defer s.RUnlock()
for _, u := range s.users {
if u.Account.Equals(user.Account) {
return true
}
}
return false
}
func (s *ServerSpec) AddUser(user *MemoryUser) {
if s.HasUser(user) {
return
}
s.Lock()
defer s.Unlock()
s.users = append(s.users, user)
}
func (s *ServerSpec) PickUser() *MemoryUser {
s.RLock()
defer s.RUnlock()
userCount := len(s.users)
switch userCount {
case 0:
return nil
case 1:
return s.users[0]
default:
return s.users[dice.Roll(userCount)]
}
}
func (s *ServerSpec) IsValid() bool {
return s.valid.IsValid()
}
func (s *ServerSpec) Invalidate() {
s.valid.Invalidate()
}

View file

@ -0,0 +1,186 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: common/protocol/server_spec.proto
package protocol
import (
proto "github.com/golang/protobuf/proto"
net "github.com/xtls/xray-core/v1/common/net"
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 ServerEndpoint struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
User []*User `protobuf:"bytes,3,rep,name=user,proto3" json:"user,omitempty"`
}
func (x *ServerEndpoint) Reset() {
*x = ServerEndpoint{}
if protoimpl.UnsafeEnabled {
mi := &file_common_protocol_server_spec_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ServerEndpoint) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerEndpoint) ProtoMessage() {}
func (x *ServerEndpoint) ProtoReflect() protoreflect.Message {
mi := &file_common_protocol_server_spec_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 ServerEndpoint.ProtoReflect.Descriptor instead.
func (*ServerEndpoint) Descriptor() ([]byte, []int) {
return file_common_protocol_server_spec_proto_rawDescGZIP(), []int{0}
}
func (x *ServerEndpoint) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ServerEndpoint) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *ServerEndpoint) GetUser() []*User {
if x != nil {
return x.User
}
return nil
}
var File_common_protocol_server_spec_proto protoreflect.FileDescriptor
var file_common_protocol_server_spec_proto_rawDesc = []byte{
0x0a, 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, 0x12, 0x14, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f,
0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 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, 0x22,
0x8b, 0x01, 0x0a, 0x0e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69,
0x6e, 0x74, 0x12, 0x35, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20,
0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f,
0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x49, 0x50, 0x4f, 0x72, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e,
0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, 0x72,
0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x2e, 0x0a,
0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x03, 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, 0x04, 0x75, 0x73, 0x65, 0x72, 0x42, 0x61, 0x0a,
0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x50, 0x01, 0x5a, 0x2c, 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, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0xaa, 0x02, 0x14, 0x58, 0x72, 0x61, 0x79,
0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c,
0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_common_protocol_server_spec_proto_rawDescOnce sync.Once
file_common_protocol_server_spec_proto_rawDescData = file_common_protocol_server_spec_proto_rawDesc
)
func file_common_protocol_server_spec_proto_rawDescGZIP() []byte {
file_common_protocol_server_spec_proto_rawDescOnce.Do(func() {
file_common_protocol_server_spec_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_protocol_server_spec_proto_rawDescData)
})
return file_common_protocol_server_spec_proto_rawDescData
}
var file_common_protocol_server_spec_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_common_protocol_server_spec_proto_goTypes = []interface{}{
(*ServerEndpoint)(nil), // 0: xray.common.protocol.ServerEndpoint
(*net.IPOrDomain)(nil), // 1: xray.common.net.IPOrDomain
(*User)(nil), // 2: xray.common.protocol.User
}
var file_common_protocol_server_spec_proto_depIdxs = []int32{
1, // 0: xray.common.protocol.ServerEndpoint.address:type_name -> xray.common.net.IPOrDomain
2, // 1: xray.common.protocol.ServerEndpoint.user:type_name -> xray.common.protocol.User
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_common_protocol_server_spec_proto_init() }
func file_common_protocol_server_spec_proto_init() {
if File_common_protocol_server_spec_proto != nil {
return
}
file_common_protocol_user_proto_init()
if !protoimpl.UnsafeEnabled {
file_common_protocol_server_spec_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ServerEndpoint); 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_common_protocol_server_spec_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_common_protocol_server_spec_proto_goTypes,
DependencyIndexes: file_common_protocol_server_spec_proto_depIdxs,
MessageInfos: file_common_protocol_server_spec_proto_msgTypes,
}.Build()
File_common_protocol_server_spec_proto = out.File
file_common_protocol_server_spec_proto_rawDesc = nil
file_common_protocol_server_spec_proto_goTypes = nil
file_common_protocol_server_spec_proto_depIdxs = nil
}

View file

@ -0,0 +1,16 @@
syntax = "proto3";
package xray.common.protocol;
option csharp_namespace = "Xray.Common.Protocol";
option go_package = "github.com/xtls/xray-core/v1/common/protocol";
option java_package = "com.xray.common.protocol";
option java_multiple_files = true;
import "common/net/address.proto";
import "common/protocol/user.proto";
message ServerEndpoint {
xray.common.net.IPOrDomain address = 1;
uint32 port = 2;
repeated xray.common.protocol.User user = 3;
}

View file

@ -0,0 +1,79 @@
package protocol_test
import (
"strings"
"testing"
"time"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/net"
. "github.com/xtls/xray-core/v1/common/protocol"
"github.com/xtls/xray-core/v1/common/uuid"
"github.com/xtls/xray-core/v1/proxy/vmess"
)
func TestAlwaysValidStrategy(t *testing.T) {
strategy := AlwaysValid()
if !strategy.IsValid() {
t.Error("strategy not valid")
}
strategy.Invalidate()
if !strategy.IsValid() {
t.Error("strategy not valid")
}
}
func TestTimeoutValidStrategy(t *testing.T) {
strategy := BeforeTime(time.Now().Add(2 * time.Second))
if !strategy.IsValid() {
t.Error("strategy not valid")
}
time.Sleep(3 * time.Second)
if strategy.IsValid() {
t.Error("strategy is valid")
}
strategy = BeforeTime(time.Now().Add(2 * time.Second))
strategy.Invalidate()
if strategy.IsValid() {
t.Error("strategy is valid")
}
}
func TestUserInServerSpec(t *testing.T) {
uuid1 := uuid.New()
uuid2 := uuid.New()
toAccount := func(a *vmess.Account) Account {
account, err := a.AsAccount()
common.Must(err)
return account
}
spec := NewServerSpec(net.Destination{}, AlwaysValid(), &MemoryUser{
Email: "test1@example.com",
Account: toAccount(&vmess.Account{Id: uuid1.String()}),
})
if spec.HasUser(&MemoryUser{
Email: "test1@example.com",
Account: toAccount(&vmess.Account{Id: uuid2.String()}),
}) {
t.Error("has user: ", uuid2)
}
spec.AddUser(&MemoryUser{Email: "test2@example.com"})
if !spec.HasUser(&MemoryUser{
Email: "test1@example.com",
Account: toAccount(&vmess.Account{Id: uuid1.String()}),
}) {
t.Error("not having user: ", uuid1)
}
}
func TestPickUser(t *testing.T) {
spec := NewServerSpec(net.Destination{}, AlwaysValid(), &MemoryUser{Email: "test1@example.com"}, &MemoryUser{Email: "test2@example.com"}, &MemoryUser{Email: "test3@example.com"})
user := spec.PickUser()
if !strings.HasSuffix(user.Email, "@example.com") {
t.Error("user: ", user.Email)
}
}

22
common/protocol/time.go Normal file
View file

@ -0,0 +1,22 @@
package protocol
import (
"time"
"github.com/xtls/xray-core/v1/common/dice"
)
type Timestamp int64
type TimestampGenerator func() Timestamp
func NowTime() Timestamp {
return Timestamp(time.Now().Unix())
}
func NewTimestampGenerator(base Timestamp, delta int) TimestampGenerator {
return func() Timestamp {
rangeInDelta := dice.Roll(delta*2) - delta
return base + Timestamp(rangeInDelta)
}
}

View file

@ -0,0 +1,21 @@
package protocol_test
import (
"testing"
"time"
. "github.com/xtls/xray-core/v1/common/protocol"
)
func TestGenerateRandomInt64InRange(t *testing.T) {
base := time.Now().Unix()
delta := 100
generator := NewTimestampGenerator(Timestamp(base), delta)
for i := 0; i < 100; i++ {
val := int64(generator())
if val > base+int64(delta) || val < base-int64(delta) {
t.Error(val, " not between ", base-int64(delta), " and ", base+int64(delta))
}
}
}

1
common/protocol/tls/cert/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.pem

View file

@ -0,0 +1,178 @@
package cert
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"math/big"
"time"
"github.com/xtls/xray-core/v1/common"
)
//go:generate go run github.com/xtls/xray-core/v1/common/errors/errorgen
type Certificate struct {
// Cerificate in ASN.1 DER format
Certificate []byte
// Private key in ASN.1 DER format
PrivateKey []byte
}
func ParseCertificate(certPEM []byte, keyPEM []byte) (*Certificate, error) {
certBlock, _ := pem.Decode(certPEM)
if certBlock == nil {
return nil, newError("failed to decode certificate")
}
keyBlock, _ := pem.Decode(keyPEM)
if keyBlock == nil {
return nil, newError("failed to decode key")
}
return &Certificate{
Certificate: certBlock.Bytes,
PrivateKey: keyBlock.Bytes,
}, nil
}
func (c *Certificate) ToPEM() ([]byte, []byte) {
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate}),
pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: c.PrivateKey})
}
type Option func(*x509.Certificate)
func Authority(isCA bool) Option {
return func(cert *x509.Certificate) {
cert.IsCA = isCA
}
}
func NotBefore(t time.Time) Option {
return func(c *x509.Certificate) {
c.NotBefore = t
}
}
func NotAfter(t time.Time) Option {
return func(c *x509.Certificate) {
c.NotAfter = t
}
}
func DNSNames(names ...string) Option {
return func(c *x509.Certificate) {
c.DNSNames = names
}
}
func CommonName(name string) Option {
return func(c *x509.Certificate) {
c.Subject.CommonName = name
}
}
func KeyUsage(usage x509.KeyUsage) Option {
return func(c *x509.Certificate) {
c.KeyUsage = usage
}
}
func Organization(org string) Option {
return func(c *x509.Certificate) {
c.Subject.Organization = []string{org}
}
}
func MustGenerate(parent *Certificate, opts ...Option) *Certificate {
cert, err := Generate(parent, opts...)
common.Must(err)
return cert
}
func publicKey(priv interface{}) interface{} {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
case ed25519.PrivateKey:
return k.Public().(ed25519.PublicKey)
default:
return nil
}
}
func Generate(parent *Certificate, opts ...Option) (*Certificate, error) {
var (
pKey interface{}
parentKey interface{}
err error
)
// higher signing performance than RSA2048
selfKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, newError("failed to generate self private key").Base(err)
}
parentKey = selfKey
if parent != nil {
if _, e := asn1.Unmarshal(parent.PrivateKey, &ecPrivateKey{}); e == nil {
pKey, err = x509.ParseECPrivateKey(parent.PrivateKey)
} else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs8{}); e == nil {
pKey, err = x509.ParsePKCS8PrivateKey(parent.PrivateKey)
} else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs1PrivateKey{}); e == nil {
pKey, err = x509.ParsePKCS1PrivateKey(parent.PrivateKey)
}
if err != nil {
return nil, newError("failed to parse parent private key").Base(err)
}
parentKey = pKey
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, newError("failed to generate serial number").Base(err)
}
template := &x509.Certificate{
SerialNumber: serialNumber,
NotBefore: time.Now().Add(time.Hour * -1),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
for _, opt := range opts {
opt(template)
}
parentCert := template
if parent != nil {
pCert, err := x509.ParseCertificate(parent.Certificate)
if err != nil {
return nil, newError("failed to parse parent certificate").Base(err)
}
parentCert = pCert
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, publicKey(selfKey), parentKey)
if err != nil {
return nil, newError("failed to create certificate").Base(err)
}
privateKey, err := x509.MarshalPKCS8PrivateKey(selfKey)
if err != nil {
return nil, newError("Unable to marshal private key").Base(err)
}
return &Certificate{
Certificate: derBytes,
PrivateKey: privateKey,
}, nil
}

View file

@ -0,0 +1,92 @@
package cert
import (
"context"
"crypto/x509"
"encoding/json"
"os"
"strings"
"testing"
"time"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/task"
)
func TestGenerate(t *testing.T) {
err := generate(nil, true, true, "ca")
if err != nil {
t.Fatal(err)
}
}
func generate(domainNames []string, isCA bool, jsonOutput bool, fileOutput string) error {
commonName := "Xray Root CA"
organization := "Xray Inc"
expire := time.Hour * 3
var opts []Option
if isCA {
opts = append(opts, Authority(isCA))
opts = append(opts, KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature))
}
opts = append(opts, NotAfter(time.Now().Add(expire)))
opts = append(opts, CommonName(commonName))
if len(domainNames) > 0 {
opts = append(opts, DNSNames(domainNames...))
}
opts = append(opts, Organization(organization))
cert, err := Generate(nil, opts...)
if err != nil {
return newError("failed to generate TLS certificate").Base(err)
}
if jsonOutput {
printJSON(cert)
}
if len(fileOutput) > 0 {
if err := printFile(cert, fileOutput); err != nil {
return err
}
}
return nil
}
type jsonCert struct {
Certificate []string `json:"certificate"`
Key []string `json:"key"`
}
func printJSON(certificate *Certificate) {
certPEM, keyPEM := certificate.ToPEM()
jCert := &jsonCert{
Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"),
Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"),
}
content, err := json.MarshalIndent(jCert, "", " ")
common.Must(err)
os.Stdout.Write(content)
os.Stdout.WriteString("\n")
}
func printFile(certificate *Certificate, name string) error {
certPEM, keyPEM := certificate.ToPEM()
return task.Run(context.Background(), func() error {
return writeFile(certPEM, name+"_cert.pem")
}, func() error {
return writeFile(keyPEM, name+"_key.pem")
})
}
func writeFile(content []byte, name string) error {
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
return common.Error2(f.Write(content))
}

View file

@ -0,0 +1,9 @@
package cert
import "github.com/xtls/xray-core/v1/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

View file

@ -0,0 +1,44 @@
package cert
import (
"crypto/x509/pkix"
"encoding/asn1"
"math/big"
)
type ecPrivateKey struct {
Version int
PrivateKey []byte
NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
}
type pkcs8 struct {
Version int
Algo pkix.AlgorithmIdentifier
PrivateKey []byte
// optional attributes omitted.
}
type pkcs1AdditionalRSAPrime struct {
Prime *big.Int
// We ignore these values because rsa will calculate them.
Exp *big.Int
Coeff *big.Int
}
type pkcs1PrivateKey struct {
Version int
N *big.Int
E int
D *big.Int
P *big.Int
Q *big.Int
// We ignore these values, if present, because rsa will calculate them.
Dp *big.Int `asn1:"optional"`
Dq *big.Int `asn1:"optional"`
Qinv *big.Int `asn1:"optional"`
AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
}

View file

@ -0,0 +1,146 @@
package tls
import (
"encoding/binary"
"errors"
"strings"
"github.com/xtls/xray-core/v1/common"
)
type SniffHeader struct {
domain string
}
func (h *SniffHeader) Protocol() string {
return "tls"
}
func (h *SniffHeader) Domain() string {
return h.domain
}
var errNotTLS = errors.New("not TLS header")
var errNotClientHello = errors.New("not client hello")
func IsValidTLSVersion(major, minor byte) bool {
return major == 3
}
// ReadClientHello returns server name (if any) from TLS client hello message.
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
func ReadClientHello(data []byte, h *SniffHeader) error {
if len(data) < 42 {
return common.ErrNoClue
}
sessionIDLen := int(data[38])
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
return common.ErrNoClue
}
data = data[39+sessionIDLen:]
if len(data) < 2 {
return common.ErrNoClue
}
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
// they are uint16s, the number must be even.
cipherSuiteLen := int(data[0])<<8 | int(data[1])
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
return errNotClientHello
}
data = data[2+cipherSuiteLen:]
if len(data) < 1 {
return common.ErrNoClue
}
compressionMethodsLen := int(data[0])
if len(data) < 1+compressionMethodsLen {
return common.ErrNoClue
}
data = data[1+compressionMethodsLen:]
if len(data) == 0 {
return errNotClientHello
}
if len(data) < 2 {
return errNotClientHello
}
extensionsLength := int(data[0])<<8 | int(data[1])
data = data[2:]
if extensionsLength != len(data) {
return errNotClientHello
}
for len(data) != 0 {
if len(data) < 4 {
return errNotClientHello
}
extension := uint16(data[0])<<8 | uint16(data[1])
length := int(data[2])<<8 | int(data[3])
data = data[4:]
if len(data) < length {
return errNotClientHello
}
if extension == 0x00 { /* extensionServerName */
d := data[:length]
if len(d) < 2 {
return errNotClientHello
}
namesLen := int(d[0])<<8 | int(d[1])
d = d[2:]
if len(d) != namesLen {
return errNotClientHello
}
for len(d) > 0 {
if len(d) < 3 {
return errNotClientHello
}
nameType := d[0]
nameLen := int(d[1])<<8 | int(d[2])
d = d[3:]
if len(d) < nameLen {
return errNotClientHello
}
if nameType == 0 {
serverName := string(d[:nameLen])
// An SNI value may not include a
// trailing dot. See
// https://tools.ietf.org/html/rfc6066#section-3.
if strings.HasSuffix(serverName, ".") {
return errNotClientHello
}
h.domain = serverName
return nil
}
d = d[nameLen:]
}
}
data = data[length:]
}
return errNotTLS
}
func SniffTLS(b []byte) (*SniffHeader, error) {
if len(b) < 5 {
return nil, common.ErrNoClue
}
if b[0] != 0x16 /* TLS Handshake */ {
return nil, errNotTLS
}
if !IsValidTLSVersion(b[1], b[2]) {
return nil, errNotTLS
}
headerLen := int(binary.BigEndian.Uint16(b[3:5]))
if 5+headerLen > len(b) {
return nil, common.ErrNoClue
}
h := &SniffHeader{}
err := ReadClientHello(b[5:5+headerLen], h)
if err == nil {
return h, nil
}
return nil, err
}

View file

@ -0,0 +1,161 @@
package tls_test
import (
"testing"
. "github.com/xtls/xray-core/v1/common/protocol/tls"
)
func TestTLSHeaders(t *testing.T) {
cases := []struct {
input []byte
domain string
err bool
}{
{
input: []byte{
0x16, 0x03, 0x01, 0x00, 0xc8, 0x01, 0x00, 0x00,
0xc4, 0x03, 0x03, 0x1a, 0xac, 0xb2, 0xa8, 0xfe,
0xb4, 0x96, 0x04, 0x5b, 0xca, 0xf7, 0xc1, 0xf4,
0x2e, 0x53, 0x24, 0x6e, 0x34, 0x0c, 0x58, 0x36,
0x71, 0x97, 0x59, 0xe9, 0x41, 0x66, 0xe2, 0x43,
0xa0, 0x13, 0xb6, 0x00, 0x00, 0x20, 0x1a, 0x1a,
0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13,
0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d,
0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
0x00, 0x7b, 0xba, 0xba, 0x00, 0x00, 0xff, 0x01,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00,
0x14, 0x00, 0x00, 0x11, 0x63, 0x2e, 0x73, 0x2d,
0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66,
0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x17, 0x00,
0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00,
0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04,
0x01, 0x05, 0x03, 0x08, 0x05, 0x05, 0x01, 0x08,
0x06, 0x06, 0x01, 0x02, 0x01, 0x00, 0x05, 0x00,
0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x0c,
0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70,
0x2f, 0x31, 0x2e, 0x31, 0x00, 0x0b, 0x00, 0x02,
0x01, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08,
0xaa, 0xaa, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18,
0xaa, 0xaa, 0x00, 0x01, 0x00,
},
domain: "c.s-microsoft.com",
err: false,
},
{
input: []byte{
0x16, 0x03, 0x01, 0x00, 0xee, 0x01, 0x00, 0x00,
0xea, 0x03, 0x03, 0xe7, 0x91, 0x9e, 0x93, 0xca,
0x78, 0x1b, 0x3c, 0xe0, 0x65, 0x25, 0x58, 0xb5,
0x93, 0xe1, 0x0f, 0x85, 0xec, 0x9a, 0x66, 0x8e,
0x61, 0x82, 0x88, 0xc8, 0xfc, 0xae, 0x1e, 0xca,
0xd7, 0xa5, 0x63, 0x20, 0xbd, 0x1c, 0x00, 0x00,
0x8b, 0xee, 0x09, 0xe3, 0x47, 0x6a, 0x0e, 0x74,
0xb0, 0xbc, 0xa3, 0x02, 0xa7, 0x35, 0xe8, 0x85,
0x70, 0x7c, 0x7a, 0xf0, 0x00, 0xdf, 0x4a, 0xea,
0x87, 0x01, 0x14, 0x91, 0x00, 0x20, 0xea, 0xea,
0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13,
0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d,
0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
0x00, 0x81, 0x9a, 0x9a, 0x00, 0x00, 0xff, 0x01,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00,
0x16, 0x00, 0x00, 0x13, 0x77, 0x77, 0x77, 0x30,
0x37, 0x2e, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x74,
0x61, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x00,
0x17, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x0d, 0x00, 0x14, 0x00, 0x12, 0x04, 0x03, 0x08,
0x04, 0x04, 0x01, 0x05, 0x03, 0x08, 0x05, 0x05,
0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x00,
0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e,
0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74,
0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x75, 0x50,
0x00, 0x00, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00,
0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x9a, 0x9a,
0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x8a, 0x8a,
0x00, 0x01, 0x00,
},
domain: "www07.clicktale.net",
err: false,
},
{
input: []byte{
0x16, 0x03, 0x01, 0x00, 0xe6, 0x01, 0x00, 0x00, 0xe2, 0x03, 0x03, 0x81, 0x47, 0xc1,
0x66, 0xd5, 0x1b, 0xfa, 0x4b, 0xb5, 0xe0, 0x2a, 0xe1, 0xa7, 0x87, 0x13, 0x1d, 0x11, 0xaa, 0xc6,
0xce, 0xfc, 0x7f, 0xab, 0x94, 0xc8, 0x62, 0xad, 0xc8, 0xab, 0x0c, 0xdd, 0xcb, 0x20, 0x6f, 0x9d,
0x07, 0xf1, 0x95, 0x3e, 0x99, 0xd8, 0xf3, 0x6d, 0x97, 0xee, 0x19, 0x0b, 0x06, 0x1b, 0xf4, 0x84,
0x0b, 0xb6, 0x8f, 0xcc, 0xde, 0xe2, 0xd0, 0x2d, 0x6b, 0x0c, 0x1f, 0x52, 0x53, 0x13, 0x00, 0x08,
0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0x00, 0xff, 0x01, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00, 0x0c,
0x00, 0x0a, 0x00, 0x00, 0x07, 0x64, 0x6f, 0x67, 0x66, 0x69, 0x73, 0x68, 0x00, 0x0b, 0x00, 0x04,
0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x1e,
0x00, 0x19, 0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00,
0x00, 0x0d, 0x00, 0x1e, 0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x07, 0x08, 0x08,
0x08, 0x09, 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01,
0x06, 0x01, 0x00, 0x2b, 0x00, 0x07, 0x06, 0x7f, 0x1c, 0x7f, 0x1b, 0x7f, 0x1a, 0x00, 0x2d, 0x00,
0x02, 0x01, 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x2f, 0x35, 0x0c,
0xb6, 0x90, 0x0a, 0xb7, 0xd5, 0xc4, 0x1b, 0x2f, 0x60, 0xaa, 0x56, 0x7b, 0x3f, 0x71, 0xc8, 0x01,
0x7e, 0x86, 0xd3, 0xb7, 0x0c, 0x29, 0x1a, 0x9e, 0x5b, 0x38, 0x3f, 0x01, 0x72,
},
domain: "dogfish",
err: false,
},
{
input: []byte{
0x16, 0x03, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00,
0xff, 0x03, 0x03, 0x3d, 0x89, 0x52, 0x9e, 0xee,
0xbe, 0x17, 0x63, 0x75, 0xef, 0x29, 0xbd, 0x14,
0x6a, 0x49, 0xe0, 0x2c, 0x37, 0x57, 0x71, 0x62,
0x82, 0x44, 0x94, 0x8f, 0x6e, 0x94, 0x08, 0x45,
0x7f, 0xdb, 0xc1, 0x00, 0x00, 0x3e, 0xc0, 0x2c,
0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8,
0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e,
0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23,
0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14,
0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33,
0x00, 0x9d, 0x00, 0x9c, 0x13, 0x02, 0x13, 0x03,
0x13, 0x01, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35,
0x00, 0x2f, 0x00, 0xff, 0x01, 0x00, 0x00, 0x98,
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00,
0x0b, 0x31, 0x30, 0x2e, 0x34, 0x32, 0x2e, 0x30,
0x2e, 0x32, 0x34, 0x33, 0x00, 0x0b, 0x00, 0x04,
0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0a,
0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19,
0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d,
0x00, 0x20, 0x00, 0x1e, 0x04, 0x03, 0x05, 0x03,
0x06, 0x03, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06,
0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x03,
0x02, 0x01, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02,
0x06, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17,
0x00, 0x00, 0x00, 0x2b, 0x00, 0x09, 0x08, 0x7f,
0x14, 0x03, 0x03, 0x03, 0x02, 0x03, 0x01, 0x00,
0x2d, 0x00, 0x03, 0x02, 0x01, 0x00, 0x00, 0x28,
0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
0x13, 0x7c, 0x6e, 0x97, 0xc4, 0xfd, 0x09, 0x2e,
0x70, 0x2f, 0x73, 0x5a, 0x9b, 0x57, 0x4d, 0x5f,
0x2b, 0x73, 0x2c, 0xa5, 0x4a, 0x98, 0x40, 0x3d,
0x75, 0x6e, 0xb4, 0x76, 0xf9, 0x48, 0x8f, 0x36,
},
domain: "10.42.0.243",
err: false,
},
}
for _, test := range cases {
header, err := SniffTLS(test.input)
if test.err {
if err == nil {
t.Errorf("Exepct error but nil in test %v", test)
}
} else {
if err != nil {
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
}
if header.Domain() != test.domain {
t.Error("expect domain ", test.domain, " but got ", header.Domain())
}
}
}
}

View file

@ -0,0 +1,13 @@
package udp
import (
"github.com/xtls/xray-core/v1/common/buf"
"github.com/xtls/xray-core/v1/common/net"
)
// Packet is a UDP packet together with its source and destination address.
type Packet struct {
Payload *buf.Buffer
Source net.Destination
Target net.Destination
}

View file

@ -0,0 +1 @@
package udp

39
common/protocol/user.go Normal file
View file

@ -0,0 +1,39 @@
package protocol
func (u *User) GetTypedAccount() (Account, error) {
if u.GetAccount() == nil {
return nil, newError("Account missing").AtWarning()
}
rawAccount, err := u.Account.GetInstance()
if err != nil {
return nil, err
}
if asAccount, ok := rawAccount.(AsAccount); ok {
return asAccount.AsAccount()
}
if account, ok := rawAccount.(Account); ok {
return account, nil
}
return nil, newError("Unknown account type: ", u.Account.Type)
}
func (u *User) ToMemoryUser() (*MemoryUser, error) {
account, err := u.GetTypedAccount()
if err != nil {
return nil, err
}
return &MemoryUser{
Account: account,
Email: u.Email,
Level: u.Level,
}, nil
}
// MemoryUser is a parsed form of User, to reduce number of parsing of Account proto.
type MemoryUser struct {
// Account is the parsed account of the protocol.
Account Account
Email string
Level uint32
}

182
common/protocol/user.pb.go Normal file
View file

@ -0,0 +1,182 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: common/protocol/user.proto
package protocol
import (
proto "github.com/golang/protobuf/proto"
serial "github.com/xtls/xray-core/v1/common/serial"
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
// User is a generic user for all procotols.
type User struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Level uint32 `protobuf:"varint,1,opt,name=level,proto3" json:"level,omitempty"`
Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"`
// Protocol specific account information. Must be the account proto in one of
// the proxies.
Account *serial.TypedMessage `protobuf:"bytes,3,opt,name=account,proto3" json:"account,omitempty"`
}
func (x *User) Reset() {
*x = User{}
if protoimpl.UnsafeEnabled {
mi := &file_common_protocol_user_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *User) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*User) ProtoMessage() {}
func (x *User) ProtoReflect() protoreflect.Message {
mi := &file_common_protocol_user_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 User.ProtoReflect.Descriptor instead.
func (*User) Descriptor() ([]byte, []int) {
return file_common_protocol_user_proto_rawDescGZIP(), []int{0}
}
func (x *User) GetLevel() uint32 {
if x != nil {
return x.Level
}
return 0
}
func (x *User) GetEmail() string {
if x != nil {
return x.Email
}
return ""
}
func (x *User) GetAccount() *serial.TypedMessage {
if x != nil {
return x.Account
}
return nil
}
var File_common_protocol_user_proto protoreflect.FileDescriptor
var file_common_protocol_user_proto_rawDesc = []byte{
0x0a, 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, 0x12, 0x14, 0x78, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63,
0x6f, 0x6c, 0x1a, 0x21, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x73, 0x65, 0x72, 0x69, 0x61,
0x6c, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x64, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6e, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x14, 0x0a,
0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6c, 0x65,
0x76, 0x65, 0x6c, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x02, 0x20, 0x01,
0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x3a, 0x0a, 0x07, 0x61, 0x63, 0x63,
0x6f, 0x75, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x78, 0x72, 0x61,
0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x2e,
0x54, 0x79, 0x70, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x61, 0x63,
0x63, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x61, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61,
0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f,
0x6c, 0x50, 0x01, 0x5a, 0x2c, 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, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f,
0x6c, 0xaa, 0x02, 0x14, 0x58, 0x72, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_common_protocol_user_proto_rawDescOnce sync.Once
file_common_protocol_user_proto_rawDescData = file_common_protocol_user_proto_rawDesc
)
func file_common_protocol_user_proto_rawDescGZIP() []byte {
file_common_protocol_user_proto_rawDescOnce.Do(func() {
file_common_protocol_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_protocol_user_proto_rawDescData)
})
return file_common_protocol_user_proto_rawDescData
}
var file_common_protocol_user_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_common_protocol_user_proto_goTypes = []interface{}{
(*User)(nil), // 0: xray.common.protocol.User
(*serial.TypedMessage)(nil), // 1: xray.common.serial.TypedMessage
}
var file_common_protocol_user_proto_depIdxs = []int32{
1, // 0: xray.common.protocol.User.account:type_name -> xray.common.serial.TypedMessage
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_common_protocol_user_proto_init() }
func file_common_protocol_user_proto_init() {
if File_common_protocol_user_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_common_protocol_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*User); 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_common_protocol_user_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_common_protocol_user_proto_goTypes,
DependencyIndexes: file_common_protocol_user_proto_depIdxs,
MessageInfos: file_common_protocol_user_proto_msgTypes,
}.Build()
File_common_protocol_user_proto = out.File
file_common_protocol_user_proto_rawDesc = nil
file_common_protocol_user_proto_goTypes = nil
file_common_protocol_user_proto_depIdxs = nil
}

View file

@ -0,0 +1,19 @@
syntax = "proto3";
package xray.common.protocol;
option csharp_namespace = "Xray.Common.Protocol";
option go_package = "github.com/xtls/xray-core/v1/common/protocol";
option java_package = "com.xray.common.protocol";
option java_multiple_files = true;
import "common/serial/typed_message.proto";
// User is a generic user for all procotols.
message User {
uint32 level = 1;
string email = 2;
// Protocol specific account information. Must be the account proto in one of
// the proxies.
xray.common.serial.TypedMessage account = 3;
}