repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/errors.generated.go
proxy/blackhole/errors.generated.go
package blackhole import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/config.go
proxy/blackhole/config.go
package blackhole import ( "v2ray.com/core/common" "v2ray.com/core/common/buf" ) const ( http403response = `HTTP/1.1 403 Forbidden Connection: close Cache-Control: max-age=3600, public Content-Length: 0 ` ) // ResponseConfig is the configuration for blackhole responses. type ResponseConfig interface { // WriteTo writes predefined response to the give buffer. WriteTo(buf.Writer) int32 } // WriteTo implements ResponseConfig.WriteTo(). func (*NoneResponse) WriteTo(buf.Writer) int32 { return 0 } // WriteTo implements ResponseConfig.WriteTo(). func (*HTTPResponse) WriteTo(writer buf.Writer) int32 { b := buf.New() common.Must2(b.WriteString(http403response)) n := b.Len() writer.WriteMultiBuffer(buf.MultiBuffer{b}) return n } // GetInternalResponse converts response settings from proto to internal data structure. func (c *Config) GetInternalResponse() (ResponseConfig, error) { if c.GetResponse() == nil { return new(NoneResponse), nil } config, err := c.GetResponse().GetInstance() if err != nil { return nil, err } return config.(ResponseConfig), nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/config_test.go
proxy/blackhole/config_test.go
package blackhole_test import ( "bufio" "net/http" "testing" "v2ray.com/core/common" "v2ray.com/core/common/buf" . "v2ray.com/core/proxy/blackhole" ) func TestHTTPResponse(t *testing.T) { buffer := buf.New() httpResponse := new(HTTPResponse) httpResponse.WriteTo(buf.NewWriter(buffer)) reader := bufio.NewReader(buffer) response, err := http.ReadResponse(reader, nil) common.Must(err) if response.StatusCode != 403 { t.Error("expected status code 403, but got ", response.StatusCode) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/blackhole.go
proxy/blackhole/blackhole.go
// +build !confonly // Package blackhole is an outbound handler that blocks all connections. package blackhole //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "time" "v2ray.com/core/common" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) // Handler is an outbound connection that silently swallow the entire payload. type Handler struct { response ResponseConfig } // New creates a new blackhole handler. func New(ctx context.Context, config *Config) (*Handler, error) { response, err := config.GetInternalResponse() if err != nil { return nil, err } return &Handler{ response: response, }, nil } // Process implements OutboundHandler.Dispatch(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { nBytes := h.response.WriteTo(link.Writer) if nBytes > 0 { // Sleep a little here to make sure the response is sent to client. time.Sleep(time.Second) } common.Interrupt(link.Writer) return nil } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/config.pb.go
proxy/blackhole/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/blackhole/config.proto package blackhole 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" serial "v2ray.com/core/common/serial" ) 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 NoneResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *NoneResponse) Reset() { *x = NoneResponse{} if protoimpl.UnsafeEnabled { mi := &file_proxy_blackhole_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NoneResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*NoneResponse) ProtoMessage() {} func (x *NoneResponse) ProtoReflect() protoreflect.Message { mi := &file_proxy_blackhole_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 NoneResponse.ProtoReflect.Descriptor instead. func (*NoneResponse) Descriptor() ([]byte, []int) { return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0} } type HTTPResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *HTTPResponse) Reset() { *x = HTTPResponse{} if protoimpl.UnsafeEnabled { mi := &file_proxy_blackhole_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *HTTPResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*HTTPResponse) ProtoMessage() {} func (x *HTTPResponse) ProtoReflect() protoreflect.Message { mi := &file_proxy_blackhole_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 HTTPResponse.ProtoReflect.Descriptor instead. func (*HTTPResponse) Descriptor() ([]byte, []int) { return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1} } type Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Response *serial.TypedMessage `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_blackhole_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_blackhole_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{2} } func (x *Config) GetResponse() *serial.TypedMessage { if x != nil { return x.Response } return nil } var File_proxy_blackhole_config_proto protoreflect.FileDescriptor var file_proxy_blackhole_config_proto_rawDesc = []byte{ 0x0a, 0x1c, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x68, 0x6f, 0x6c, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1a, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x68, 0x6f, 0x6c, 0x65, 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, 0x0e, 0x0a, 0x0c, 0x4e, 0x6f, 0x6e, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x0e, 0x0a, 0x0c, 0x48, 0x54, 0x54, 0x50, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4c, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x42, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x5f, 0x0a, 0x1e, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x68, 0x6f, 0x6c, 0x65, 0x50, 0x01, 0x5a, 0x1e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x68, 0x6f, 0x6c, 0x65, 0xaa, 0x02, 0x1a, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x42, 0x6c, 0x61, 0x63, 0x6b, 0x68, 0x6f, 0x6c, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_blackhole_config_proto_rawDescOnce sync.Once file_proxy_blackhole_config_proto_rawDescData = file_proxy_blackhole_config_proto_rawDesc ) func file_proxy_blackhole_config_proto_rawDescGZIP() []byte { file_proxy_blackhole_config_proto_rawDescOnce.Do(func() { file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_blackhole_config_proto_rawDescData) }) return file_proxy_blackhole_config_proto_rawDescData } var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_proxy_blackhole_config_proto_goTypes = []interface{}{ (*NoneResponse)(nil), // 0: v2ray.core.proxy.blackhole.NoneResponse (*HTTPResponse)(nil), // 1: v2ray.core.proxy.blackhole.HTTPResponse (*Config)(nil), // 2: v2ray.core.proxy.blackhole.Config (*serial.TypedMessage)(nil), // 3: v2ray.core.common.serial.TypedMessage } var file_proxy_blackhole_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.proxy.blackhole.Config.response:type_name -> v2ray.core.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_proxy_blackhole_config_proto_init() } func file_proxy_blackhole_config_proto_init() { if File_proxy_blackhole_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_blackhole_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NoneResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proxy_blackhole_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HTTPResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proxy_blackhole_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_blackhole_config_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_blackhole_config_proto_goTypes, DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs, MessageInfos: file_proxy_blackhole_config_proto_msgTypes, }.Build() File_proxy_blackhole_config_proto = out.File file_proxy_blackhole_config_proto_rawDesc = nil file_proxy_blackhole_config_proto_goTypes = nil file_proxy_blackhole_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/blackhole/blackhole_test.go
proxy/blackhole/blackhole_test.go
package blackhole_test import ( "context" "testing" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/serial" "v2ray.com/core/proxy/blackhole" "v2ray.com/core/transport" "v2ray.com/core/transport/pipe" ) func TestBlackholeHTTPResponse(t *testing.T) { handler, err := blackhole.New(context.Background(), &blackhole.Config{ Response: serial.ToTypedMessage(&blackhole.HTTPResponse{}), }) common.Must(err) reader, writer := pipe.New(pipe.WithoutSizeLimit()) var mb buf.MultiBuffer var rerr error go func() { b, e := reader.ReadMultiBuffer() mb = b rerr = e }() link := transport.Link{ Reader: reader, Writer: writer, } common.Must(handler.Process(context.Background(), &link, nil)) common.Must(rerr) if mb.IsEmpty() { t.Error("expect http response, but nothing") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/freedom/errors.generated.go
proxy/freedom/errors.generated.go
package freedom import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/freedom/config.go
proxy/freedom/config.go
package freedom func (c *Config) useIP() bool { return c.DomainStrategy == Config_USE_IP || c.DomainStrategy == Config_USE_IP4 || c.DomainStrategy == Config_USE_IP6 }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/freedom/config.pb.go
proxy/freedom/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/freedom/config.proto package freedom 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" protocol "v2ray.com/core/common/protocol" ) 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 Config_DomainStrategy int32 const ( Config_AS_IS Config_DomainStrategy = 0 Config_USE_IP Config_DomainStrategy = 1 Config_USE_IP4 Config_DomainStrategy = 2 Config_USE_IP6 Config_DomainStrategy = 3 ) // Enum value maps for Config_DomainStrategy. var ( Config_DomainStrategy_name = map[int32]string{ 0: "AS_IS", 1: "USE_IP", 2: "USE_IP4", 3: "USE_IP6", } Config_DomainStrategy_value = map[string]int32{ "AS_IS": 0, "USE_IP": 1, "USE_IP4": 2, "USE_IP6": 3, } ) func (x Config_DomainStrategy) Enum() *Config_DomainStrategy { p := new(Config_DomainStrategy) *p = x return p } func (x Config_DomainStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Config_DomainStrategy) Descriptor() protoreflect.EnumDescriptor { return file_proxy_freedom_config_proto_enumTypes[0].Descriptor() } func (Config_DomainStrategy) Type() protoreflect.EnumType { return &file_proxy_freedom_config_proto_enumTypes[0] } func (x Config_DomainStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Config_DomainStrategy.Descriptor instead. func (Config_DomainStrategy) EnumDescriptor() ([]byte, []int) { return file_proxy_freedom_config_proto_rawDescGZIP(), []int{1, 0} } type DestinationOverride struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Server *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"` } func (x *DestinationOverride) Reset() { *x = DestinationOverride{} if protoimpl.UnsafeEnabled { mi := &file_proxy_freedom_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DestinationOverride) String() string { return protoimpl.X.MessageStringOf(x) } func (*DestinationOverride) ProtoMessage() {} func (x *DestinationOverride) ProtoReflect() protoreflect.Message { mi := &file_proxy_freedom_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 DestinationOverride.ProtoReflect.Descriptor instead. func (*DestinationOverride) Descriptor() ([]byte, []int) { return file_proxy_freedom_config_proto_rawDescGZIP(), []int{0} } func (x *DestinationOverride) GetServer() *protocol.ServerEndpoint { if x != nil { return x.Server } return nil } type Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields DomainStrategy Config_DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=v2ray.core.proxy.freedom.Config_DomainStrategy" json:"domain_strategy,omitempty"` // Deprecated: Do not use. Timeout uint32 `protobuf:"varint,2,opt,name=timeout,proto3" json:"timeout,omitempty"` DestinationOverride *DestinationOverride `protobuf:"bytes,3,opt,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"` UserLevel uint32 `protobuf:"varint,4,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_freedom_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_freedom_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_freedom_config_proto_rawDescGZIP(), []int{1} } func (x *Config) GetDomainStrategy() Config_DomainStrategy { if x != nil { return x.DomainStrategy } return Config_AS_IS } // Deprecated: Do not use. func (x *Config) GetTimeout() uint32 { if x != nil { return x.Timeout } return 0 } func (x *Config) GetDestinationOverride() *DestinationOverride { if x != nil { return x.DestinationOverride } return nil } func (x *Config) GetUserLevel() uint32 { if x != nil { return x.UserLevel } return 0 } var File_proxy_freedom_config_proto protoreflect.FileDescriptor var file_proxy_freedom_config_proto_rawDesc = []byte{ 0x0a, 0x1a, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 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, 0x59, 0x0a, 0x13, 0x44, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x12, 0x42, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0xc4, 0x02, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x58, 0x0a, 0x0f, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x73, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0e, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x1c, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x02, 0x18, 0x01, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x60, 0x0a, 0x14, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0x2e, 0x44, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x52, 0x13, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x22, 0x41, 0x0a, 0x0e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x53, 0x5f, 0x49, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x10, 0x03, 0x42, 0x59, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0x50, 0x01, 0x5a, 0x1c, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x66, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0xaa, 0x02, 0x18, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x46, 0x72, 0x65, 0x65, 0x64, 0x6f, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_freedom_config_proto_rawDescOnce sync.Once file_proxy_freedom_config_proto_rawDescData = file_proxy_freedom_config_proto_rawDesc ) func file_proxy_freedom_config_proto_rawDescGZIP() []byte { file_proxy_freedom_config_proto_rawDescOnce.Do(func() { file_proxy_freedom_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_freedom_config_proto_rawDescData) }) return file_proxy_freedom_config_proto_rawDescData } var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_freedom_config_proto_goTypes = []interface{}{ (Config_DomainStrategy)(0), // 0: v2ray.core.proxy.freedom.Config.DomainStrategy (*DestinationOverride)(nil), // 1: v2ray.core.proxy.freedom.DestinationOverride (*Config)(nil), // 2: v2ray.core.proxy.freedom.Config (*protocol.ServerEndpoint)(nil), // 3: v2ray.core.common.protocol.ServerEndpoint } var file_proxy_freedom_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.proxy.freedom.DestinationOverride.server:type_name -> v2ray.core.common.protocol.ServerEndpoint 0, // 1: v2ray.core.proxy.freedom.Config.domain_strategy:type_name -> v2ray.core.proxy.freedom.Config.DomainStrategy 1, // 2: v2ray.core.proxy.freedom.Config.destination_override:type_name -> v2ray.core.proxy.freedom.DestinationOverride 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_freedom_config_proto_init() } func file_proxy_freedom_config_proto_init() { if File_proxy_freedom_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_freedom_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DestinationOverride); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proxy_freedom_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_freedom_config_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_freedom_config_proto_goTypes, DependencyIndexes: file_proxy_freedom_config_proto_depIdxs, EnumInfos: file_proxy_freedom_config_proto_enumTypes, MessageInfos: file_proxy_freedom_config_proto_msgTypes, }.Build() File_proxy_freedom_config_proto = out.File file_proxy_freedom_config_proto_rawDesc = nil file_proxy_freedom_config_proto_goTypes = nil file_proxy_freedom_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/freedom/freedom.go
proxy/freedom/freedom.go
// +build !confonly package freedom //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/dice" "v2ray.com/core/common/net" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/dns" "v2ray.com/core/features/policy" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { h := new(Handler) if err := core.RequireFeatures(ctx, func(pm policy.Manager, d dns.Client) error { return h.Init(config.(*Config), pm, d) }); err != nil { return nil, err } return h, nil })) } // Handler handles Freedom connections. type Handler struct { policyManager policy.Manager dns dns.Client config *Config } // Init initializes the Handler with necessary parameters. func (h *Handler) Init(config *Config, pm policy.Manager, d dns.Client) error { h.config = config h.policyManager = pm h.dns = d return nil } func (h *Handler) policy() policy.Session { p := h.policyManager.ForLevel(h.config.UserLevel) if h.config.Timeout > 0 && h.config.UserLevel == 0 { p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second } return p } func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address { var lookupFunc func(string) ([]net.IP, error) = h.dns.LookupIP if h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()) { if lookupIPv4, ok := h.dns.(dns.IPv4Lookup); ok { lookupFunc = lookupIPv4.LookupIPv4 } } else if h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()) { if lookupIPv6, ok := h.dns.(dns.IPv6Lookup); ok { lookupFunc = lookupIPv6.LookupIPv6 } } ips, err := lookupFunc(domain) if err != nil { newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx)) } if len(ips) == 0 { return nil } return net.IPAddress(ips[dice.Roll(len(ips))]) } func isValidAddress(addr *net.IPOrDomain) bool { if addr == nil { return false } a := addr.AsAddress() return a != net.AnyIP } // Process implements proxy.Outbound. func (h *Handler) 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 if h.config.DestinationOverride != nil { server := h.config.DestinationOverride.Server if isValidAddress(server.Address) { destination.Address = server.Address.AsAddress() } if server.Port != 0 { destination.Port = net.Port(server.Port) } } newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx)) input := link.Reader output := link.Writer var conn internet.Connection err := retry.ExponentialBackoff(5, 100).On(func() error { dialDest := destination if h.config.useIP() && dialDest.Address.Family().IsDomain() { ip := h.resolveIP(ctx, dialDest.Address.Domain(), dialer.Address()) if ip != nil { dialDest = net.Destination{ Network: dialDest.Network, Address: ip, Port: dialDest.Port, } newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx)) } } rawConn, err := dialer.Dial(ctx, dialDest) if err != nil { return err } conn = rawConn return nil }) if err != nil { return newError("failed to open connection to ", destination).Base(err) } defer conn.Close() // nolint: errcheck plcy := h.policy() ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle) requestDone := func() error { defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) var writer buf.Writer if destination.Network == net.Network_TCP { writer = buf.NewWriter(conn) } else { writer = &buf.SequentialWriter{Writer: conn} } if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to process request").Base(err) } return nil } responseDone := func() error { defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) var reader buf.Reader if destination.Network == net.Network_TCP { reader = buf.NewReader(conn) } else { reader = buf.NewPacketReader(conn) } if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil { return newError("failed to process response").Base(err) } return nil } if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil { return newError("connection ends").Base(err) } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/errors.generated.go
proxy/vless/errors.generated.go
package vless import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/vless.go
proxy/vless/vless.go
// Package vless contains the implementation of VLess protocol and transportation. // // VLess contains both inbound and outbound connections. VLess inbound is usually used on servers // together with 'freedom' to talk to final destination, while VLess outbound is usually used on // clients with 'socks' for proxying. package vless //go:generate go run v2ray.com/core/common/errors/errorgen const ( XRO = "xtls-rprx-origin" XRD = "xtls-rprx-direct" )
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/validator.go
proxy/vless/validator.go
// +build !confonly package vless import ( "strings" "sync" "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" ) type Validator struct { // Considering email's usage here, map + sync.Mutex/RWMutex may have better performance. email sync.Map users sync.Map } 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(u.Account.(*MemoryAccount).ID.UUID(), u) return nil } 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(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID()) return nil } func (v *Validator) Get(id uuid.UUID) *protocol.MemoryUser { u, _ := v.users.Load(id) if u != nil { return u.(*protocol.MemoryUser) } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/account.pb.go
proxy/vless/account.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vless/account.proto package vless 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 Account struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // ID of the account, in the form of a UUID, e.g., "66ad4540-b58c-4ad2-9926-ea63445a9b57". Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Flow settings. May be "xtls-rprx-origin". Flow string `protobuf:"bytes,2,opt,name=flow,proto3" json:"flow,omitempty"` // Encryption settings. Only applies to client side, and only accepts "none" for now. Encryption string `protobuf:"bytes,3,opt,name=encryption,proto3" json:"encryption,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vless_account_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_vless_account_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_vless_account_proto_rawDescGZIP(), []int{0} } func (x *Account) GetId() string { if x != nil { return x.Id } return "" } func (x *Account) GetFlow() string { if x != nil { return x.Flow } return "" } func (x *Account) GetEncryption() string { if x != nil { return x.Encryption } return "" } var File_proxy_vless_account_proto protoreflect.FileDescriptor var file_proxy_vless_account_proto_rawDesc = []byte{ 0x0a, 0x19, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x16, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x22, 0x4d, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x66, 0x6c, 0x6f, 0x77, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x66, 0x6c, 0x6f, 0x77, 0x12, 0x1e, 0x0a, 0x0a, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x53, 0x0a, 0x1a, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x50, 0x01, 0x5a, 0x1a, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0xaa, 0x02, 0x16, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6c, 0x65, 0x73, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vless_account_proto_rawDescOnce sync.Once file_proxy_vless_account_proto_rawDescData = file_proxy_vless_account_proto_rawDesc ) func file_proxy_vless_account_proto_rawDescGZIP() []byte { file_proxy_vless_account_proto_rawDescOnce.Do(func() { file_proxy_vless_account_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vless_account_proto_rawDescData) }) return file_proxy_vless_account_proto_rawDescData } var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_vless_account_proto_goTypes = []interface{}{ (*Account)(nil), // 0: v2ray.core.proxy.vless.Account } var file_proxy_vless_account_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_proxy_vless_account_proto_init() } func file_proxy_vless_account_proto_init() { if File_proxy_vless_account_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vless_account_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 } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proxy_vless_account_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vless_account_proto_goTypes, DependencyIndexes: file_proxy_vless_account_proto_depIdxs, MessageInfos: file_proxy_vless_account_proto_msgTypes, }.Build() File_proxy_vless_account_proto = out.File file_proxy_vless_account_proto_rawDesc = nil file_proxy_vless_account_proto_goTypes = nil file_proxy_vless_account_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/account.go
proxy/vless/account.go
// +build !confonly package vless import ( "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" ) // AsAccount implements protocol.Account.AsAccount(). func (a *Account) AsAccount() (protocol.Account, error) { id, err := uuid.ParseString(a.Id) if err != nil { return nil, newError("failed to parse ID").Base(err).AtError() } return &MemoryAccount{ ID: protocol.NewID(id), Flow: a.Flow, // needs parser here? Encryption: a.Encryption, // needs parser here? }, nil } // MemoryAccount is an in-memory form of VLess account. type MemoryAccount struct { // ID of the account. ID *protocol.ID // Flow of the account. May be "xtls-rprx-origin". Flow string // Encryption of the account. Used for client connections, and only accepts "none" for now. Encryption string } // Equals implements protocol.Account.Equals(). func (a *MemoryAccount) Equals(account protocol.Account) bool { vlessAccount, ok := account.(*MemoryAccount) if !ok { return false } return a.ID.Equals(vlessAccount.ID) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/encoding/errors.generated.go
proxy/vless/encoding/errors.generated.go
package encoding import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/encoding/encoding_test.go
proxy/vless/encoding/encoding_test.go
package encoding_test import ( "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" "v2ray.com/core/proxy/vless" . "v2ray.com/core/proxy/vless/encoding" ) func toAccount(a *vless.Account) protocol.Account { account, err := a.AsAccount() common.Must(err) return account } func TestRequestSerialization(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2fly.org", } id := uuid.New() account := &vless.Account{ Id: id.String(), } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: Version, User: user, Command: protocol.RequestCommandTCP, Address: net.DomainAddress("www.v2fly.org"), Port: net.Port(443), } expectedAddons := &Addons{} buffer := buf.StackNew() common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons)) Validator := new(vless.Validator) Validator.Add(user) actualRequest, actualAddons, err, _ := DecodeRequestHeader(false, nil, &buffer, Validator) common.Must(err) if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" { t.Error(r) } if r := cmp.Diff(actualAddons, expectedAddons); r != "" { t.Error(r) } } func TestInvalidRequest(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2fly.org", } id := uuid.New() account := &vless.Account{ Id: id.String(), } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: Version, User: user, Command: protocol.RequestCommand(100), Address: net.DomainAddress("www.v2fly.org"), Port: net.Port(443), } expectedAddons := &Addons{} buffer := buf.StackNew() common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons)) Validator := new(vless.Validator) Validator.Add(user) _, _, err, _ := DecodeRequestHeader(false, nil, &buffer, Validator) if err == nil { t.Error("nil error") } } func TestMuxRequest(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2fly.org", } id := uuid.New() account := &vless.Account{ Id: id.String(), } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: Version, User: user, Command: protocol.RequestCommandMux, Address: net.DomainAddress("v1.mux.cool"), } expectedAddons := &Addons{} buffer := buf.StackNew() common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons)) Validator := new(vless.Validator) Validator.Add(user) actualRequest, actualAddons, err, _ := DecodeRequestHeader(false, nil, &buffer, Validator) common.Must(err) if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" { t.Error(r) } if r := cmp.Diff(actualAddons, expectedAddons); r != "" { t.Error(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/encoding/addons.go
proxy/vless/encoding/addons.go
// +build !confonly package encoding import ( "io" "github.com/golang/protobuf/proto" "v2ray.com/core/common/buf" "v2ray.com/core/common/protocol" "v2ray.com/core/proxy/vless" ) func EncodeHeaderAddons(buffer *buf.Buffer, addons *Addons) error { switch addons.Flow { case vless.XRO, vless.XRD: bytes, err := proto.Marshal(addons) if err != nil { return newError("failed to marshal addons protobuf value").Base(err) } if err := buffer.WriteByte(byte(len(bytes))); err != nil { return newError("failed to write addons protobuf length").Base(err) } if _, err := buffer.Write(bytes); err != nil { return newError("failed to write addons protobuf value").Base(err) } default: if err := buffer.WriteByte(0); err != nil { return newError("failed to write addons protobuf length").Base(err) } } return nil } func DecodeHeaderAddons(buffer *buf.Buffer, reader io.Reader) (*Addons, error) { addons := new(Addons) buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { return nil, newError("failed to read addons protobuf length").Base(err) } if length := int32(buffer.Byte(0)); length != 0 { buffer.Clear() if _, err := buffer.ReadFullFrom(reader, length); err != nil { return nil, newError("failed to read addons protobuf value").Base(err) } if err := proto.Unmarshal(buffer.Bytes(), addons); err != nil { return nil, newError("failed to unmarshal addons protobuf value").Base(err) } // Verification. switch addons.Flow { default: } } return addons, nil } // EncodeBodyAddons returns a Writer that auto-encrypt content written by caller. func EncodeBodyAddons(writer io.Writer, request *protocol.RequestHeader, addons *Addons) buf.Writer { switch addons.Flow { default: if request.Command == protocol.RequestCommandUDP { return NewMultiLengthPacketWriter(writer.(buf.Writer)) } } return buf.NewWriter(writer) } // DecodeBodyAddons returns a Reader from which caller can fetch decrypted body. func DecodeBodyAddons(reader io.Reader, request *protocol.RequestHeader, addons *Addons) buf.Reader { switch addons.Flow { default: if request.Command == protocol.RequestCommandUDP { return NewLengthPacketReader(reader) } } return buf.NewReader(reader) } func NewMultiLengthPacketWriter(writer buf.Writer) *MultiLengthPacketWriter { return &MultiLengthPacketWriter{ Writer: writer, } } type MultiLengthPacketWriter struct { buf.Writer } func (w *MultiLengthPacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { defer buf.ReleaseMulti(mb) mb2Write := make(buf.MultiBuffer, 0, len(mb)+1) for _, b := range mb { length := b.Len() if length == 0 || length+2 > buf.Size { continue } eb := buf.New() if err := eb.WriteByte(byte(length >> 8)); err != nil { eb.Release() continue } if err := eb.WriteByte(byte(length)); err != nil { eb.Release() continue } if _, err := eb.Write(b.Bytes()); err != nil { eb.Release() continue } mb2Write = append(mb2Write, eb) } if mb2Write.IsEmpty() { return nil } return w.Writer.WriteMultiBuffer(mb2Write) } func NewLengthPacketWriter(writer io.Writer) *LengthPacketWriter { return &LengthPacketWriter{ Writer: writer, cache: make([]byte, 0, 65536), } } type LengthPacketWriter struct { io.Writer cache []byte } func (w *LengthPacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { length := mb.Len() // none of mb is nil //fmt.Println("Write", length) if length == 0 { return nil } defer func() { w.cache = w.cache[:0] }() w.cache = append(w.cache, byte(length>>8), byte(length)) for i, b := range mb { w.cache = append(w.cache, b.Bytes()...) b.Release() mb[i] = nil } if _, err := w.Write(w.cache); err != nil { return newError("failed to write a packet").Base(err) } return nil } func NewLengthPacketReader(reader io.Reader) *LengthPacketReader { return &LengthPacketReader{ Reader: reader, cache: make([]byte, 2), } } type LengthPacketReader struct { io.Reader cache []byte } func (r *LengthPacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { if _, err := io.ReadFull(r.Reader, r.cache); err != nil { // maybe EOF return nil, newError("failed to read packet length").Base(err) } length := int32(r.cache[0])<<8 | int32(r.cache[1]) //fmt.Println("Read", length) mb := make(buf.MultiBuffer, 0, length/buf.Size+1) for length > 0 { size := length if size > buf.Size { size = buf.Size } length -= size b := buf.New() if _, err := b.ReadFullFrom(r.Reader, size); err != nil { return nil, newError("failed to read packet payload").Base(err) } mb = append(mb, b) } return mb, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/encoding/encoding.go
proxy/vless/encoding/encoding.go
// +build !confonly package encoding //go:generate go run v2ray.com/core/common/errors/errorgen import ( "io" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/proxy/vless" ) const ( Version = byte(0) ) var addrParser = protocol.NewAddressParser( protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4), protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain), protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6), protocol.PortThenAddress(), ) // EncodeRequestHeader writes encoded request header into the given writer. func EncodeRequestHeader(writer io.Writer, request *protocol.RequestHeader, requestAddons *Addons) error { buffer := buf.StackNew() defer buffer.Release() if err := buffer.WriteByte(request.Version); err != nil { return newError("failed to write request version").Base(err) } if _, err := buffer.Write(request.User.Account.(*vless.MemoryAccount).ID.Bytes()); err != nil { return newError("failed to write request user id").Base(err) } if err := EncodeHeaderAddons(&buffer, requestAddons); err != nil { return newError("failed to encode request header addons").Base(err) } if err := buffer.WriteByte(byte(request.Command)); err != nil { return newError("failed to write request command").Base(err) } if request.Command != protocol.RequestCommandMux { if err := addrParser.WriteAddressPort(&buffer, request.Address, request.Port); err != nil { return newError("failed to write request address and port").Base(err) } } if _, err := writer.Write(buffer.Bytes()); err != nil { return newError("failed to write request header").Base(err) } return nil } // DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream. func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validator *vless.Validator) (*protocol.RequestHeader, *Addons, error, bool) { buffer := buf.StackNew() defer buffer.Release() request := new(protocol.RequestHeader) if isfb { request.Version = first.Byte(0) } else { if _, err := buffer.ReadFullFrom(reader, 1); err != nil { return nil, nil, newError("failed to read request version").Base(err), false } request.Version = buffer.Byte(0) } switch request.Version { case 0: var id [16]byte if isfb { copy(id[:], first.BytesRange(1, 17)) } else { buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 16); err != nil { return nil, nil, newError("failed to read request user id").Base(err), false } copy(id[:], buffer.Bytes()) } if request.User = validator.Get(id); request.User == nil { return nil, nil, newError("invalid request user id"), isfb } if isfb { first.Advance(17) } requestAddons, err := DecodeHeaderAddons(&buffer, reader) if err != nil { return nil, nil, newError("failed to decode request header addons").Base(err), false } buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { return nil, nil, newError("failed to read request command").Base(err), false } request.Command = protocol.RequestCommand(buffer.Byte(0)) switch request.Command { case protocol.RequestCommandMux: request.Address = net.DomainAddress("v1.mux.cool") request.Port = 0 case protocol.RequestCommandTCP, protocol.RequestCommandUDP: if addr, port, err := addrParser.ReadAddressPort(&buffer, reader); err == nil { request.Address = addr request.Port = port } } if request.Address == nil { return nil, nil, newError("invalid request address"), false } return request, requestAddons, nil, false default: return nil, nil, newError("invalid request version"), isfb } } // EncodeResponseHeader writes encoded response header into the given writer. func EncodeResponseHeader(writer io.Writer, request *protocol.RequestHeader, responseAddons *Addons) error { buffer := buf.StackNew() defer buffer.Release() if err := buffer.WriteByte(request.Version); err != nil { return newError("failed to write response version").Base(err) } if err := EncodeHeaderAddons(&buffer, responseAddons); err != nil { return newError("failed to encode response header addons").Base(err) } if _, err := writer.Write(buffer.Bytes()); err != nil { return newError("failed to write response header").Base(err) } return nil } // DecodeResponseHeader decodes and returns (if successful) a ResponseHeader from an input stream. func DecodeResponseHeader(reader io.Reader, request *protocol.RequestHeader) (*Addons, error) { buffer := buf.StackNew() defer buffer.Release() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { return nil, newError("failed to read response version").Base(err) } if buffer.Byte(0) != request.Version { return nil, newError("unexpected response version. Expecting ", int(request.Version), " but actually ", int(buffer.Byte(0))) } responseAddons, err := DecodeHeaderAddons(&buffer, reader) if err != nil { return nil, newError("failed to decode response header addons").Base(err) } return responseAddons, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/encoding/addons.pb.go
proxy/vless/encoding/addons.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: proxy/vless/encoding/addons.proto package encoding import ( fmt "fmt" proto "github.com/golang/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type Addons struct { Flow string `protobuf:"bytes,1,opt,name=Flow,proto3" json:"Flow,omitempty"` Seed []byte `protobuf:"bytes,2,opt,name=Seed,proto3" json:"Seed,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Addons) Reset() { *m = Addons{} } func (m *Addons) String() string { return proto.CompactTextString(m) } func (*Addons) ProtoMessage() {} func (*Addons) Descriptor() ([]byte, []int) { return fileDescriptor_75ab671b0ca8b1cc, []int{0} } func (m *Addons) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Addons) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Addons.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Addons) XXX_Merge(src proto.Message) { xxx_messageInfo_Addons.Merge(m, src) } func (m *Addons) XXX_Size() int { return m.Size() } func (m *Addons) XXX_DiscardUnknown() { xxx_messageInfo_Addons.DiscardUnknown(m) } var xxx_messageInfo_Addons proto.InternalMessageInfo func (m *Addons) GetFlow() string { if m != nil { return m.Flow } return "" } func (m *Addons) GetSeed() []byte { if m != nil { return m.Seed } return nil } func init() { proto.RegisterType((*Addons)(nil), "v2ray.core.proxy.vless.encoding.Addons") } func init() { proto.RegisterFile("proxy/vless/encoding/addons.proto", fileDescriptor_75ab671b0ca8b1cc) } var fileDescriptor_75ab671b0ca8b1cc = []byte{ // 186 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2c, 0x28, 0xca, 0xaf, 0xa8, 0xd4, 0x2f, 0xcb, 0x49, 0x2d, 0x2e, 0xd6, 0x4f, 0xcd, 0x4b, 0xce, 0x4f, 0xc9, 0xcc, 0x4b, 0xd7, 0x4f, 0x4c, 0x49, 0xc9, 0xcf, 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x2f, 0x33, 0x2a, 0x4a, 0xac, 0xd4, 0x4b, 0xce, 0x2f, 0x4a, 0xd5, 0x03, 0xab, 0xd6, 0x03, 0xab, 0xd6, 0x83, 0xa9, 0x56, 0x32, 0xe0, 0x62, 0x73, 0x04, 0x6b, 0x10, 0x12, 0xe2, 0x62, 0x71, 0xcb, 0xc9, 0x2f, 0x97, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x41, 0x62, 0xc1, 0xa9, 0xa9, 0x29, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0x3c, 0x41, 0x60, 0xb6, 0x53, 0xdd, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe3, 0xb1, 0x1c, 0x03, 0x97, 0x72, 0x72, 0x7e, 0xae, 0x1e, 0x01, 0x8b, 0x02, 0x18, 0xa3, 0x94, 0x61, 0x4a, 0x72, 0xf5, 0x41, 0xca, 0xf4, 0xb1, 0xb9, 0x7e, 0x15, 0x93, 0x7c, 0x98, 0x51, 0x50, 0x62, 0xa5, 0x9e, 0x33, 0xc8, 0xa0, 0x00, 0xb0, 0x41, 0x61, 0x60, 0x83, 0x5c, 0xa1, 0x2a, 0x92, 0xd8, 0xc0, 0x3e, 0x33, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x36, 0x32, 0x14, 0x7c, 0xfe, 0x00, 0x00, 0x00, } func (m *Addons) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Addons) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Addons) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.XXX_unrecognized != nil { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) } if len(m.Seed) > 0 { i -= len(m.Seed) copy(dAtA[i:], m.Seed) i = encodeVarintAddons(dAtA, i, uint64(len(m.Seed))) i-- dAtA[i] = 0x12 } if len(m.Flow) > 0 { i -= len(m.Flow) copy(dAtA[i:], m.Flow) i = encodeVarintAddons(dAtA, i, uint64(len(m.Flow))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func encodeVarintAddons(dAtA []byte, offset int, v uint64) int { offset -= sovAddons(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *Addons) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Flow) if l > 0 { n += 1 + l + sovAddons(uint64(l)) } l = len(m.Seed) if l > 0 { n += 1 + l + sovAddons(uint64(l)) } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func sovAddons(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozAddons(x uint64) (n int) { return sovAddons(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *Addons) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAddons } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Addons: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Addons: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Flow", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAddons } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthAddons } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthAddons } if postIndex > l { return io.ErrUnexpectedEOF } m.Flow = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Seed", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAddons } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthAddons } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthAddons } if postIndex > l { return io.ErrUnexpectedEOF } m.Seed = append(m.Seed[:0], dAtA[iNdEx:postIndex]...) if m.Seed == nil { m.Seed = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipAddons(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthAddons } if (iNdEx + skippy) < 0 { return ErrInvalidLengthAddons } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipAddons(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowAddons } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowAddons } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowAddons } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthAddons } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupAddons } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthAddons } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthAddons = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowAddons = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupAddons = fmt.Errorf("proto: unexpected end of group") )
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/outbound/errors.generated.go
proxy/vless/outbound/errors.generated.go
package outbound import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/outbound/config.go
proxy/vless/outbound/config.go
// +build !confonly package outbound
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/outbound/outbound.go
proxy/vless/outbound/outbound.go
// +build !confonly package outbound //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/platform" "v2ray.com/core/common/protocol" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/proxy/vless" "v2ray.com/core/proxy/vless/encoding" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/xtls" ) var ( xtls_show = false ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) const defaultFlagValue = "NOT_DEFINED_AT_ALL" xtlsShow := platform.NewEnvFlag("v2ray.vless.xtls.show").GetValue(func() string { return defaultFlagValue }) if xtlsShow == "true" { xtls_show = true } } // Handler is an outbound connection handler for VLess protocol. type Handler struct { serverList *protocol.ServerList serverPicker protocol.ServerPicker policyManager policy.Manager } // New creates a new VLess outbound handler. func New(ctx context.Context, config *Config) (*Handler, error) { serverList := protocol.NewServerList() for _, rec := range config.Vnext { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { return nil, newError("failed to parse server spec").Base(err).AtError() } serverList.AddServer(s) } v := core.MustFromContext(ctx) handler := &Handler{ serverList: serverList, serverPicker: protocol.NewRoundRobinServerPicker(serverList), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), } return handler, nil } // Process implements proxy.Outbound.Process(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { var rec *protocol.ServerSpec var conn internet.Connection if err := retry.ExponentialBackoff(5, 200).On(func() error { rec = h.serverPicker.PickServer() var err error conn, err = dialer.Dial(ctx, rec.Destination()) if err != nil { return err } return nil }); err != nil { return newError("failed to find an available destination").Base(err).AtWarning() } defer conn.Close() // nolint: errcheck iConn := conn if statConn, ok := iConn.(*internet.StatCouterConnection); ok { iConn = statConn.Connection } outbound := session.OutboundFromContext(ctx) if outbound == nil || !outbound.Target.IsValid() { return newError("target not specified").AtError() } target := outbound.Target newError("tunneling request to ", target, " via ", rec.Destination()).AtInfo().WriteToLog(session.ExportIDToError(ctx)) command := protocol.RequestCommandTCP if target.Network == net.Network_UDP { command = protocol.RequestCommandUDP } if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" { command = protocol.RequestCommandMux } request := &protocol.RequestHeader{ Version: encoding.Version, User: rec.PickUser(), Command: command, Address: target.Address, Port: target.Port, } account := request.User.Account.(*vless.MemoryAccount) requestAddons := &encoding.Addons{ Flow: account.Flow, } allowUDP443 := false switch requestAddons.Flow { case vless.XRO + "-udp443", vless.XRD + "-udp443": allowUDP443 = true requestAddons.Flow = requestAddons.Flow[:16] fallthrough case vless.XRO, vless.XRD: switch request.Command { case protocol.RequestCommandMux: return newError(requestAddons.Flow + " doesn't support Mux").AtWarning() case protocol.RequestCommandUDP: if !allowUDP443 && request.Port == 443 { return newError(requestAddons.Flow + " stopped UDP/443").AtInfo() } requestAddons.Flow = "" case protocol.RequestCommandTCP: if xtlsConn, ok := iConn.(*xtls.Conn); ok { xtlsConn.RPRX = true xtlsConn.SHOW = xtls_show xtlsConn.MARK = "XTLS" if requestAddons.Flow == vless.XRD { xtlsConn.DirectMode = true } } else { return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning() } } default: if _, ok := iConn.(*xtls.Conn); ok { panic(`To avoid misunderstanding, you must fill in VLESS "flow" when using XTLS.`) } } sessionPolicy := h.policyManager.ForLevel(request.User.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) clientReader := link.Reader // .(*pipe.Reader) clientWriter := link.Writer // .(*pipe.Writer) postRequest := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil { return newError("failed to encode request header").Base(err).AtWarning() } // default: serverWriter := bufferWriter serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons) if err := buf.CopyOnceTimeout(clientReader, serverWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { return err // ... } // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer if err := bufferWriter.SetBuffered(false); err != nil { return newError("failed to write A request payload").Base(err).AtWarning() } // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer if err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer request payload").Base(err).AtInfo() } // Indicates the end of request payload. switch requestAddons.Flow { default: } return nil } getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) responseAddons, err := encoding.DecodeResponseHeader(conn, request) if err != nil { return newError("failed to decode response header").Base(err).AtWarning() } // default: serverReader := buf.NewReader(conn) serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons) // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer response payload").Base(err).AtInfo() } return nil } if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil { return newError("connection ends").Base(err).AtInfo() } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/outbound/config.pb.go
proxy/vless/outbound/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vless/outbound/config.proto package outbound 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" protocol "v2ray.com/core/common/protocol" ) 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 Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Vnext []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=vnext,proto3" json:"vnext,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vless_outbound_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_vless_outbound_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_vless_outbound_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetVnext() []*protocol.ServerEndpoint { if x != nil { return x.Vnext } return nil } var File_proxy_vless_outbound_config_proto protoreflect.FileDescriptor var file_proxy_vless_outbound_config_proto_rawDesc = []byte{ 0x0a, 0x21, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 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, 0x4a, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x40, 0x0a, 0x05, 0x76, 0x6e, 0x65, 0x78, 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x05, 0x76, 0x6e, 0x65, 0x78, 0x74, 0x42, 0x6e, 0x0a, 0x23, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x50, 0x01, 0x5a, 0x23, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0xaa, 0x02, 0x1f, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vless_outbound_config_proto_rawDescOnce sync.Once file_proxy_vless_outbound_config_proto_rawDescData = file_proxy_vless_outbound_config_proto_rawDesc ) func file_proxy_vless_outbound_config_proto_rawDescGZIP() []byte { file_proxy_vless_outbound_config_proto_rawDescOnce.Do(func() { file_proxy_vless_outbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vless_outbound_config_proto_rawDescData) }) return file_proxy_vless_outbound_config_proto_rawDescData } var file_proxy_vless_outbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_vless_outbound_config_proto_goTypes = []interface{}{ (*Config)(nil), // 0: v2ray.core.proxy.vless.outbound.Config (*protocol.ServerEndpoint)(nil), // 1: v2ray.core.common.protocol.ServerEndpoint } var file_proxy_vless_outbound_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.proxy.vless.outbound.Config.vnext:type_name -> v2ray.core.common.protocol.ServerEndpoint 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_proxy_vless_outbound_config_proto_init() } func file_proxy_vless_outbound_config_proto_init() { if File_proxy_vless_outbound_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vless_outbound_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_vless_outbound_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vless_outbound_config_proto_goTypes, DependencyIndexes: file_proxy_vless_outbound_config_proto_depIdxs, MessageInfos: file_proxy_vless_outbound_config_proto_msgTypes, }.Build() File_proxy_vless_outbound_config_proto = out.File file_proxy_vless_outbound_config_proto_rawDesc = nil file_proxy_vless_outbound_config_proto_goTypes = nil file_proxy_vless_outbound_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/inbound/inbound.go
proxy/vless/inbound/inbound.go
// +build !confonly package inbound //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "io" "strconv" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/platform" "v2ray.com/core/common/protocol" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/dns" feature_inbound "v2ray.com/core/features/inbound" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/proxy/vless" "v2ray.com/core/proxy/vless/encoding" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/tls" "v2ray.com/core/transport/internet/xtls" ) var ( xtls_show = false ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { var dc dns.Client if err := core.RequireFeatures(ctx, func(d dns.Client) error { dc = d return nil }); err != nil { return nil, err } return New(ctx, config.(*Config), dc) })) const defaultFlagValue = "NOT_DEFINED_AT_ALL" xtlsShow := platform.NewEnvFlag("v2ray.vless.xtls.show").GetValue(func() string { return defaultFlagValue }) if xtlsShow == "true" { xtls_show = true } } // Handler is an inbound connection handler that handles messages in VLess protocol. type Handler struct { inboundHandlerManager feature_inbound.Manager policyManager policy.Manager validator *vless.Validator dns dns.Client fallbacks map[string]map[string]*Fallback // or nil //regexps map[string]*regexp.Regexp // or nil } // New creates a new VLess inbound handler. func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) { v := core.MustFromContext(ctx) handler := &Handler{ inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), validator: new(vless.Validator), dns: dc, } for _, user := range config.Clients { u, err := user.ToMemoryUser() if err != nil { return nil, newError("failed to get VLESS user").Base(err).AtError() } if err := handler.AddUser(ctx, u); err != nil { return nil, newError("failed to initiate user").Base(err).AtError() } } if config.Fallbacks != nil { handler.fallbacks = make(map[string]map[string]*Fallback) //handler.regexps = make(map[string]*regexp.Regexp) for _, fb := range config.Fallbacks { if handler.fallbacks[fb.Alpn] == nil { handler.fallbacks[fb.Alpn] = make(map[string]*Fallback) } handler.fallbacks[fb.Alpn][fb.Path] = fb /* if fb.Path != "" { if r, err := regexp.Compile(fb.Path); err != nil { return nil, newError("invalid path regexp").Base(err).AtError() } else { handler.regexps[fb.Path] = r } } */ } if handler.fallbacks[""] != nil { for alpn, pfb := range handler.fallbacks { if alpn != "" { // && alpn != "h2" { for path, fb := range handler.fallbacks[""] { if pfb[path] == nil { pfb[path] = fb } } } } } } return handler, nil } // Close implements common.Closable.Close(). func (h *Handler) Close() error { return errors.Combine(common.Close(h.validator)) } // AddUser implements proxy.UserManager.AddUser(). func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error { return h.validator.Add(u) } // RemoveUser implements proxy.UserManager.RemoveUser(). func (h *Handler) RemoveUser(ctx context.Context, e string) error { return h.validator.Del(e) } // Network implements proxy.Inbound.Network(). func (*Handler) Network() []net.Network { return []net.Network{net.Network_TCP} } // Process implements proxy.Inbound.Process(). func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error { sid := session.ExportIDToError(ctx) iConn := connection if statConn, ok := iConn.(*internet.StatCouterConnection); ok { iConn = statConn.Connection } sessionPolicy := h.policyManager.ForLevel(0) if err := connection.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, _ := first.ReadFrom(connection) newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid) reader := &buf.BufferedReader{ Reader: buf.NewReader(connection), Buffer: buf.MultiBuffer{first}, } var request *protocol.RequestHeader var requestAddons *encoding.Addons var err error apfb := h.fallbacks isfb := apfb != nil if isfb && firstLen < 18 { err = newError("fallback directly") } else { request, requestAddons, err, isfb = encoding.DecodeRequestHeader(isfb, first, reader, h.validator) } if err != nil { if isfb { 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 lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 { if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 { if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 { newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid) for _, fb := range pfb { if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) { path = fb.Path break } } } } } */ 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() // nolint: errcheck 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 { pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")) } else { pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")) } case 2: pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A\x21")) // signature + v2 + PROXY if ipv4 { pro.Write([]byte("\x11\x00\x0C")) // AF_INET + STREAM + 12 bytes pro.Write(net.ParseIP(remoteAddr).To4()) pro.Write(net.ParseIP(localAddr).To4()) } else { pro.Write([]byte("\x21\x00\x24")) // AF_INET6 + STREAM + 36 bytes pro.Write(net.ParseIP(remoteAddr).To16()) pro.Write(net.ParseIP(localAddr).To16()) } p1, _ := strconv.ParseUint(remotePort, 10, 16) p2, _ := strconv.ParseUint(localPort, 10, 16) 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.Interrupt(serverReader) common.Interrupt(serverWriter) return newError("fallback ends").Base(err).AtInfo() } return nil } if errors.Cause(err) != io.EOF { log.Record(&log.AccessMessage{ From: connection.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: err, }) err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtWarning() } return err } if err := connection.SetReadDeadline(time.Time{}); err != nil { newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid) } newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid) inbound := session.InboundFromContext(ctx) if inbound == nil { panic("no inbound metadata") } inbound.User = request.User account := request.User.Account.(*vless.MemoryAccount) responseAddons := &encoding.Addons{ //Flow: requestAddons.Flow, } switch requestAddons.Flow { case vless.XRO, vless.XRD: if account.Flow == requestAddons.Flow { switch request.Command { case protocol.RequestCommandMux: return newError(requestAddons.Flow + " doesn't support Mux").AtWarning() case protocol.RequestCommandUDP: return newError(requestAddons.Flow + " doesn't support UDP").AtWarning() case protocol.RequestCommandTCP: if xtlsConn, ok := iConn.(*xtls.Conn); ok { xtlsConn.RPRX = true xtlsConn.SHOW = xtls_show xtlsConn.MARK = "XTLS" if requestAddons.Flow == vless.XRD { xtlsConn.DirectMode = true } } else { return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning() } } } else { return newError(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning() } case "": default: return newError("unknown request flow " + requestAddons.Flow).AtWarning() } if request.Command != protocol.RequestCommandMux { ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: connection.RemoteAddr(), To: request.Destination(), Status: log.AccessAccepted, Reason: "", Email: request.User.Email, }) } sessionPolicy = h.policyManager.ForLevel(request.User.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) link, err := dispatcher.Dispatch(ctx, request.Destination()) if err != nil { return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning() } serverReader := link.Reader // .(*pipe.Reader) serverWriter := link.Writer // .(*pipe.Writer) postRequest := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) // default: clientReader := reader clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons) // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer if err := buf.Copy(clientReader, serverWriter, 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) bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection)) if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil { return newError("failed to encode response header").Base(err).AtWarning() } // default: clientWriter := bufferWriter clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, responseAddons) { multiBuffer, err := serverReader.ReadMultiBuffer() if err != nil { return err // ... } if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil { return err // ... } } // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer if err := bufferWriter.SetBuffered(false); err != nil { return newError("failed to write A response payload").Base(err).AtWarning() } // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer response payload").Base(err).AtInfo() } // Indicates the end of response payload. switch responseAddons.Flow { default: } return nil } if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil { common.Interrupt(serverReader) common.Interrupt(serverWriter) return newError("connection ends").Base(err).AtInfo() } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/inbound/errors.generated.go
proxy/vless/inbound/errors.generated.go
package inbound import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/inbound/config.go
proxy/vless/inbound/config.go
// +build !confonly package inbound
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vless/inbound/config.pb.go
proxy/vless/inbound/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vless/inbound/config.proto package inbound 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" protocol "v2ray.com/core/common/protocol" ) 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 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_vless_inbound_config_proto_msgTypes[0] 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_vless_inbound_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 Fallback.ProtoReflect.Descriptor instead. func (*Fallback) Descriptor() ([]byte, []int) { return file_proxy_vless_inbound_config_proto_rawDescGZIP(), []int{0} } 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 Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Clients []*protocol.User `protobuf:"bytes,1,rep,name=clients,proto3" json:"clients,omitempty"` // Decryption settings. Only applies to server side, and only accepts "none" // for now. Decryption string `protobuf:"bytes,2,opt,name=decryption,proto3" json:"decryption,omitempty"` Fallbacks []*Fallback `protobuf:"bytes,3,rep,name=fallbacks,proto3" json:"fallbacks,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vless_inbound_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_vless_inbound_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_vless_inbound_config_proto_rawDescGZIP(), []int{1} } func (x *Config) GetClients() []*protocol.User { if x != nil { return x.Clients } return nil } func (x *Config) GetDecryption() string { if x != nil { return x.Decryption } return "" } func (x *Config) GetFallbacks() []*Fallback { if x != nil { return x.Fallbacks } return nil } var File_proxy_vless_inbound_config_proto protoreflect.FileDescriptor var file_proxy_vless_inbound_config_proto_rawDesc = []byte{ 0x0a, 0x20, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 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, 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, 0xac, 0x01, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3a, 0x0a, 0x07, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x07, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x64, 0x65, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x64, 0x65, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x46, 0x0a, 0x09, 0x66, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2e, 0x46, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x09, 0x66, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x73, 0x42, 0x6b, 0x0a, 0x22, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x50, 0x01, 0x5a, 0x22, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6c, 0x65, 0x73, 0x73, 0x2f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0xaa, 0x02, 0x1e, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6c, 0x65, 0x73, 0x73, 0x2e, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vless_inbound_config_proto_rawDescOnce sync.Once file_proxy_vless_inbound_config_proto_rawDescData = file_proxy_vless_inbound_config_proto_rawDesc ) func file_proxy_vless_inbound_config_proto_rawDescGZIP() []byte { file_proxy_vless_inbound_config_proto_rawDescOnce.Do(func() { file_proxy_vless_inbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vless_inbound_config_proto_rawDescData) }) return file_proxy_vless_inbound_config_proto_rawDescData } var file_proxy_vless_inbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_vless_inbound_config_proto_goTypes = []interface{}{ (*Fallback)(nil), // 0: v2ray.core.proxy.vless.inbound.Fallback (*Config)(nil), // 1: v2ray.core.proxy.vless.inbound.Config (*protocol.User)(nil), // 2: v2ray.core.common.protocol.User } var file_proxy_vless_inbound_config_proto_depIdxs = []int32{ 2, // 0: v2ray.core.proxy.vless.inbound.Config.clients:type_name -> v2ray.core.common.protocol.User 0, // 1: v2ray.core.proxy.vless.inbound.Config.fallbacks:type_name -> v2ray.core.proxy.vless.inbound.Fallback 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_proxy_vless_inbound_config_proto_init() } func file_proxy_vless_inbound_config_proto_init() { if File_proxy_vless_inbound_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vless_inbound_config_proto_msgTypes[0].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_vless_inbound_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_vless_inbound_config_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vless_inbound_config_proto_goTypes, DependencyIndexes: file_proxy_vless_inbound_config_proto_depIdxs, MessageInfos: file_proxy_vless_inbound_config_proto_msgTypes, }.Build() File_proxy_vless_inbound_config_proto = out.File file_proxy_vless_inbound_config_proto_rawDesc = nil file_proxy_vless_inbound_config_proto_goTypes = nil file_proxy_vless_inbound_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/errors.generated.go
proxy/shadowsocks/errors.generated.go
package shadowsocks import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/client.go
proxy/shadowsocks/client.go
// +build !confonly package shadowsocks import ( "context" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) // Client is a inbound handler for Shadowsocks protocol type Client struct { serverPicker protocol.ServerPicker policyManager policy.Manager } // NewClient create a new Shadowsocks 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() dest := server.Destination() dest.Network = network rawConn, err := dialer.Dial(ctx, dest) 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() request := &protocol.RequestHeader{ Version: Version, Address: destination.Address, Port: destination.Port, } if destination.Network == net.Network_TCP { request.Command = protocol.RequestCommandTCP } else { request.Command = protocol.RequestCommandUDP } user := server.PickUser() _, ok := user.Account.(*MemoryAccount) if !ok { return newError("user account is not valid") } request.User = user sessionPolicy := c.policyManager.ForLevel(user.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) if request.Command == protocol.RequestCommandTCP { bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) bodyWriter, err := WriteTCPRequest(request, bufferedWriter) if err != nil { return newError("failed to write request").Base(err) } if err := bufferedWriter.SetBuffered(false); err != nil { return err } requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)) } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) responseReader, err := ReadTCPResponse(user, conn) if err != nil { return err } return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer)) } var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { return newError("connection ends").Base(err) } return nil } if request.Command == protocol.RequestCommandUDP { writer := &buf.SequentialWriter{Writer: &UDPWriter{ Writer: conn, Request: request, }} requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport all UDP request").Base(err) } return nil } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) reader := &UDPReader{ Reader: conn, User: user, } if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport all UDP response").Base(err) } return nil } var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { return newError("connection ends").Base(err) } return nil } return nil } func init() { common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewClient(ctx, config.(*ClientConfig)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/shadowsocks.go
proxy/shadowsocks/shadowsocks.go
// Package shadowsocks provides compatible functionality to Shadowsocks. // // Shadowsocks client and server are implemented as outbound and inbound respectively in V2Ray's term. // // R.I.P Shadowsocks package shadowsocks //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/config.go
proxy/shadowsocks/config.go
package shadowsocks import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/sha1" "io" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/hkdf" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/protocol" ) // MemoryAccount is an account type converted from Account. type MemoryAccount struct { Cipher Cipher Key []byte } // Equals implements protocol.Account.Equals(). func (a *MemoryAccount) Equals(another protocol.Account) bool { if account, ok := another.(*MemoryAccount); ok { return bytes.Equal(a.Key, account.Key) } return false } func createAesGcm(key []byte) cipher.AEAD { block, err := aes.NewCipher(key) common.Must(err) gcm, err := cipher.NewGCM(block) common.Must(err) return gcm } func createChacha20Poly1305(key []byte) cipher.AEAD { chacha20, err := chacha20poly1305.New(key) common.Must(err) return chacha20 } func (a *Account) getCipher() (Cipher, error) { switch a.CipherType { case CipherType_AES_128_CFB: return &AesCfb{KeyBytes: 16}, nil case CipherType_AES_256_CFB: return &AesCfb{KeyBytes: 32}, nil case CipherType_CHACHA20: return &ChaCha20{IVBytes: 8}, nil case CipherType_CHACHA20_IETF: return &ChaCha20{IVBytes: 12}, nil case CipherType_AES_128_GCM: return &AEADCipher{ KeyBytes: 16, IVBytes: 16, AEADAuthCreator: createAesGcm, }, nil case CipherType_AES_256_GCM: return &AEADCipher{ KeyBytes: 32, IVBytes: 32, AEADAuthCreator: createAesGcm, }, nil case CipherType_CHACHA20_POLY1305: return &AEADCipher{ KeyBytes: 32, IVBytes: 32, AEADAuthCreator: createChacha20Poly1305, }, nil case CipherType_NONE: return NoneCipher{}, nil default: return nil, newError("Unsupported cipher.") } } // AsAccount implements protocol.AsAccount. func (a *Account) AsAccount() (protocol.Account, error) { cipher, err := a.getCipher() if err != nil { return nil, newError("failed to get cipher").Base(err) } return &MemoryAccount{ Cipher: cipher, Key: passwordToCipherKey([]byte(a.Password), cipher.KeySize()), }, nil } // Cipher is an interface for all Shadowsocks ciphers. type Cipher interface { KeySize() int32 IVSize() int32 NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) IsAEAD() bool EncodePacket(key []byte, b *buf.Buffer) error DecodePacket(key []byte, b *buf.Buffer) error } // AesCfb represents all AES-CFB ciphers. type AesCfb struct { KeyBytes int32 } func (*AesCfb) IsAEAD() bool { return false } func (v *AesCfb) KeySize() int32 { return v.KeyBytes } func (v *AesCfb) IVSize() int32 { return 16 } func (v *AesCfb) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) { stream := crypto.NewAesEncryptionStream(key, iv) return &buf.SequentialWriter{Writer: crypto.NewCryptionWriter(stream, writer)}, nil } func (v *AesCfb) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) { stream := crypto.NewAesDecryptionStream(key, iv) return &buf.SingleReader{ Reader: crypto.NewCryptionReader(stream, reader), }, nil } func (v *AesCfb) EncodePacket(key []byte, b *buf.Buffer) error { iv := b.BytesTo(v.IVSize()) stream := crypto.NewAesEncryptionStream(key, iv) stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize())) return nil } func (v *AesCfb) DecodePacket(key []byte, b *buf.Buffer) error { if b.Len() <= v.IVSize() { return newError("insufficient data: ", b.Len()) } iv := b.BytesTo(v.IVSize()) stream := crypto.NewAesDecryptionStream(key, iv) stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize())) b.Advance(v.IVSize()) return nil } type AEADCipher struct { KeyBytes int32 IVBytes int32 AEADAuthCreator func(key []byte) cipher.AEAD } func (*AEADCipher) IsAEAD() bool { return true } func (c *AEADCipher) KeySize() int32 { return c.KeyBytes } func (c *AEADCipher) IVSize() int32 { return c.IVBytes } func (c *AEADCipher) createAuthenticator(key []byte, iv []byte) *crypto.AEADAuthenticator { nonce := crypto.GenerateInitialAEADNonce() subkey := make([]byte, c.KeyBytes) hkdfSHA1(key, iv, subkey) return &crypto.AEADAuthenticator{ AEAD: c.AEADAuthCreator(subkey), NonceGenerator: nonce, } } func (c *AEADCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) { auth := c.createAuthenticator(key, iv) return crypto.NewAuthenticationWriter(auth, &crypto.AEADChunkSizeParser{ Auth: auth, }, writer, protocol.TransferTypeStream, nil), nil } func (c *AEADCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) { auth := c.createAuthenticator(key, iv) return crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{ Auth: auth, }, reader, protocol.TransferTypeStream, nil), nil } func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error { ivLen := c.IVSize() payloadLen := b.Len() auth := c.createAuthenticator(key, b.BytesTo(ivLen)) b.Extend(int32(auth.Overhead())) _, err := auth.Seal(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen)) return err } func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error { if b.Len() <= c.IVSize() { return newError("insufficient data: ", b.Len()) } ivLen := c.IVSize() payloadLen := b.Len() auth := c.createAuthenticator(key, b.BytesTo(ivLen)) bbb, err := auth.Open(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen)) if err != nil { return err } b.Resize(ivLen, int32(len(bbb))) return nil } type ChaCha20 struct { IVBytes int32 } func (*ChaCha20) IsAEAD() bool { return false } func (v *ChaCha20) KeySize() int32 { return 32 } func (v *ChaCha20) IVSize() int32 { return v.IVBytes } func (v *ChaCha20) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) { stream := crypto.NewChaCha20Stream(key, iv) return &buf.SequentialWriter{Writer: crypto.NewCryptionWriter(stream, writer)}, nil } func (v *ChaCha20) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) { stream := crypto.NewChaCha20Stream(key, iv) return &buf.SingleReader{Reader: crypto.NewCryptionReader(stream, reader)}, nil } func (v *ChaCha20) EncodePacket(key []byte, b *buf.Buffer) error { iv := b.BytesTo(v.IVSize()) stream := crypto.NewChaCha20Stream(key, iv) stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize())) return nil } func (v *ChaCha20) DecodePacket(key []byte, b *buf.Buffer) error { if b.Len() <= v.IVSize() { return newError("insufficient data: ", b.Len()) } iv := b.BytesTo(v.IVSize()) stream := crypto.NewChaCha20Stream(key, iv) stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize())) b.Advance(v.IVSize()) return nil } type NoneCipher struct{} func (NoneCipher) KeySize() int32 { return 0 } func (NoneCipher) IVSize() int32 { return 0 } func (NoneCipher) IsAEAD() bool { return true // to avoid OTA } func (NoneCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) { return buf.NewReader(reader), nil } func (NoneCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) { return buf.NewWriter(writer), nil } func (NoneCipher) EncodePacket(key []byte, b *buf.Buffer) error { return nil } func (NoneCipher) DecodePacket(key []byte, b *buf.Buffer) error { return nil } func passwordToCipherKey(password []byte, keySize int32) []byte { key := make([]byte, 0, keySize) md5Sum := md5.Sum(password) key = append(key, md5Sum[:]...) for int32(len(key)) < keySize { md5Hash := md5.New() common.Must2(md5Hash.Write(md5Sum[:])) common.Must2(md5Hash.Write(password)) md5Hash.Sum(md5Sum[:0]) key = append(key, md5Sum[:]...) } return key } func hkdfSHA1(secret, salt, outkey []byte) { r := hkdf.New(sha1.New, secret, salt, []byte("ss-subkey")) common.Must2(io.ReadFull(r, outkey)) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/protocol.go
proxy/shadowsocks/protocol.go
// +build !confonly package shadowsocks import ( "crypto/hmac" "crypto/rand" "crypto/sha256" "hash" "hash/crc32" "io" "io/ioutil" "v2ray.com/core/common/dice" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" ) const ( Version = 1 ) var addrParser = protocol.NewAddressParser( protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4), protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6), protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain), protocol.WithAddressTypeParser(func(b byte) byte { return b & 0x0F }), ) // ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts. func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) { account := user.Account.(*MemoryAccount) hashkdf := hmac.New(func() hash.Hash { return sha256.New() }, []byte("SSBSKDF")) hashkdf.Write(account.Key) behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil)) behaviorRand := dice.NewDeterministicDice(int64(behaviorSeed)) BaseDrainSize := behaviorRand.Roll(3266) RandDrainMax := behaviorRand.Roll(64) + 1 RandDrainRolled := dice.Roll(RandDrainMax) DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled readSizeRemain := DrainSize buffer := buf.New() defer buffer.Release() ivLen := account.Cipher.IVSize() var iv []byte if ivLen > 0 { if _, err := buffer.ReadFullFrom(reader, ivLen); err != nil { readSizeRemain -= int(buffer.Len()) DrainConnN(reader, readSizeRemain) return nil, nil, newError("failed to read IV").Base(err) } iv = append([]byte(nil), buffer.BytesTo(ivLen)...) } r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader) if err != nil { readSizeRemain -= int(buffer.Len()) DrainConnN(reader, readSizeRemain) return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError() } br := &buf.BufferedReader{Reader: r} request := &protocol.RequestHeader{ Version: Version, User: user, Command: protocol.RequestCommandTCP, } readSizeRemain -= int(buffer.Len()) buffer.Clear() addr, port, err := addrParser.ReadAddressPort(buffer, br) if err != nil { readSizeRemain -= int(buffer.Len()) DrainConnN(reader, readSizeRemain) return nil, nil, newError("failed to read address").Base(err) } request.Address = addr request.Port = port if request.Address == nil { readSizeRemain -= int(buffer.Len()) DrainConnN(reader, readSizeRemain) return nil, nil, newError("invalid remote address.") } return request, br, nil } func DrainConnN(reader io.Reader, n int) error { _, err := io.CopyN(ioutil.Discard, reader, int64(n)) return err } // WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body. func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) { user := request.User account := user.Account.(*MemoryAccount) var iv []byte if account.Cipher.IVSize() > 0 { iv = make([]byte, account.Cipher.IVSize()) common.Must2(rand.Read(iv)) if err := buf.WriteAllBytes(writer, iv); err != nil { return nil, newError("failed to write IV") } } w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer) if err != nil { return nil, newError("failed to create encoding stream").Base(err).AtError() } header := buf.New() if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil { return nil, newError("failed to write address").Base(err) } if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil { return nil, newError("failed to write header").Base(err) } return w, nil } func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) { account := user.Account.(*MemoryAccount) var iv []byte if account.Cipher.IVSize() > 0 { iv = make([]byte, account.Cipher.IVSize()) if _, err := io.ReadFull(reader, iv); err != nil { return nil, newError("failed to read IV").Base(err) } } return account.Cipher.NewDecryptionReader(account.Key, iv, reader) } func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) { user := request.User account := user.Account.(*MemoryAccount) var iv []byte if account.Cipher.IVSize() > 0 { iv = make([]byte, account.Cipher.IVSize()) common.Must2(rand.Read(iv)) if err := buf.WriteAllBytes(writer, iv); err != nil { return nil, newError("failed to write IV.").Base(err) } } return account.Cipher.NewEncryptionWriter(account.Key, iv, writer) } func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) { user := request.User account := user.Account.(*MemoryAccount) buffer := buf.New() ivLen := account.Cipher.IVSize() if ivLen > 0 { common.Must2(buffer.ReadFullFrom(rand.Reader, ivLen)) } if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil { return nil, newError("failed to write address").Base(err) } buffer.Write(payload) if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil { return nil, newError("failed to encrypt UDP payload").Base(err) } return buffer, nil } func DecodeUDPPacket(user *protocol.MemoryUser, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) { account := user.Account.(*MemoryAccount) var iv []byte if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 { // Keep track of IV as it gets removed from payload in DecodePacket. iv = make([]byte, account.Cipher.IVSize()) copy(iv, payload.BytesTo(account.Cipher.IVSize())) } if err := account.Cipher.DecodePacket(account.Key, payload); err != nil { return nil, nil, newError("failed to decrypt UDP payload").Base(err) } request := &protocol.RequestHeader{ Version: Version, User: user, Command: protocol.RequestCommandUDP, } payload.SetByte(0, payload.Byte(0)&0x0F) addr, port, err := addrParser.ReadAddressPort(nil, payload) if err != nil { return nil, nil, newError("failed to parse address").Base(err) } request.Address = addr request.Port = port return request, payload, nil } type UDPReader struct { Reader io.Reader User *protocol.MemoryUser } func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) { buffer := buf.New() _, err := buffer.ReadFrom(v.Reader) if err != nil { buffer.Release() return nil, err } _, payload, err := DecodeUDPPacket(v.User, buffer) if err != nil { buffer.Release() return nil, err } return buf.MultiBuffer{payload}, nil } type UDPWriter struct { Writer io.Writer Request *protocol.RequestHeader } // Write implements io.Writer. func (w *UDPWriter) Write(payload []byte) (int, error) { packet, err := EncodeUDPPacket(w.Request, payload) if err != nil { return 0, err } _, err = w.Writer.Write(packet.Bytes()) packet.Release() return len(payload), err }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/protocol_test.go
proxy/shadowsocks/protocol_test.go
package shadowsocks_test import ( "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" . "v2ray.com/core/proxy/shadowsocks" ) func toAccount(a *Account) protocol.Account { account, err := a.AsAccount() common.Must(err) return account } func TestUDPEncoding(t *testing.T) { request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandUDP, Address: net.LocalHostIP, Port: 1234, User: &protocol.MemoryUser{ Email: "love@v2ray.com", Account: toAccount(&Account{ Password: "shadowsocks-password", CipherType: CipherType_AES_128_CFB, }), }, } data := buf.New() common.Must2(data.WriteString("test string")) encodedData, err := EncodeUDPPacket(request, data.Bytes()) common.Must(err) decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData) common.Must(err) if r := cmp.Diff(decodedData.Bytes(), data.Bytes()); r != "" { t.Error("data: ", r) } if r := cmp.Diff(decodedRequest, request); r != "" { t.Error("request: ", r) } } func TestTCPRequest(t *testing.T) { cases := []struct { request *protocol.RequestHeader payload []byte }{ { request: &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandTCP, Address: net.LocalHostIP, Port: 1234, User: &protocol.MemoryUser{ Email: "love@v2ray.com", Account: toAccount(&Account{ Password: "tcp-password", CipherType: CipherType_CHACHA20, }), }, }, payload: []byte("test string"), }, { request: &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandTCP, Address: net.LocalHostIPv6, Port: 1234, User: &protocol.MemoryUser{ Email: "love@v2ray.com", Account: toAccount(&Account{ Password: "password", CipherType: CipherType_AES_256_CFB, }), }, }, payload: []byte("test string"), }, { request: &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandTCP, Address: net.DomainAddress("v2ray.com"), Port: 1234, User: &protocol.MemoryUser{ Email: "love@v2ray.com", Account: toAccount(&Account{ Password: "password", CipherType: CipherType_CHACHA20_IETF, }), }, }, payload: []byte("test string"), }, } runTest := func(request *protocol.RequestHeader, payload []byte) { data := buf.New() common.Must2(data.Write(payload)) cache := buf.New() defer cache.Release() writer, err := WriteTCPRequest(request, cache) common.Must(err) common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data})) decodedRequest, reader, err := ReadTCPSession(request.User, cache) common.Must(err) if r := cmp.Diff(decodedRequest, request); r != "" { t.Error("request: ", r) } decodedData, err := reader.ReadMultiBuffer() common.Must(err) if r := cmp.Diff(decodedData[0].Bytes(), payload); r != "" { t.Error("data: ", r) } } for _, test := range cases { runTest(test.request, test.payload) } } func TestUDPReaderWriter(t *testing.T) { user := &protocol.MemoryUser{ Account: toAccount(&Account{ Password: "test-password", CipherType: CipherType_CHACHA20_IETF, }), } cache := buf.New() defer cache.Release() writer := &buf.SequentialWriter{Writer: &UDPWriter{ Writer: cache, Request: &protocol.RequestHeader{ Version: Version, Address: net.DomainAddress("v2ray.com"), Port: 123, User: user, }, }} reader := &UDPReader{ Reader: cache, User: user, } { b := buf.New() common.Must2(b.WriteString("test payload")) common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b})) payload, err := reader.ReadMultiBuffer() common.Must(err) if payload[0].String() != "test payload" { t.Error("unexpected output: ", payload[0].String()) } } { b := buf.New() common.Must2(b.WriteString("test payload 2")) common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b})) payload, err := reader.ReadMultiBuffer() common.Must(err) if payload[0].String() != "test payload 2" { t.Error("unexpected output: ", payload[0].String()) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/config_test.go
proxy/shadowsocks/config_test.go
package shadowsocks_test import ( "crypto/rand" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/proxy/shadowsocks" ) func TestAEADCipherUDP(t *testing.T) { rawAccount := &shadowsocks.Account{ CipherType: shadowsocks.CipherType_AES_128_GCM, Password: "test", } account, err := rawAccount.AsAccount() common.Must(err) cipher := account.(*shadowsocks.MemoryAccount).Cipher key := make([]byte, cipher.KeySize()) common.Must2(rand.Read(key)) payload := make([]byte, 1024) common.Must2(rand.Read(payload)) b1 := buf.New() common.Must2(b1.ReadFullFrom(rand.Reader, cipher.IVSize())) common.Must2(b1.Write(payload)) common.Must(cipher.EncodePacket(key, b1)) common.Must(cipher.DecodePacket(key, b1)) if diff := cmp.Diff(b1.Bytes(), payload); diff != "" { t.Error(diff) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/server.go
proxy/shadowsocks/server.go
// +build !confonly package shadowsocks import ( "context" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" udp_proto "v2ray.com/core/common/protocol/udp" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/udp" ) type Server struct { config *ServerConfig user *protocol.MemoryUser policyManager policy.Manager } // NewServer create a new Shadowsocks server. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { if config.GetUser() == nil { return nil, newError("user is not specified") } mUser, err := config.User.ToMemoryUser() if err != nil { return nil, newError("failed to parse user account").Base(err) } v := core.MustFromContext(ctx) s := &Server{ config: config, user: mUser, policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), } return s, nil } func (s *Server) Network() []net.Network { list := s.config.Network if len(list) == 0 { list = append(list, net.Network_TCP) } if s.config.UdpEnabled { list = append(list, net.Network_UDP) } return list } func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { switch network { case net.Network_TCP: return s.handleConnection(ctx, conn, dispatcher) case net.Network_UDP: return s.handlerUDPPayload(ctx, conn, dispatcher) default: return newError("unknown network: ", network) } } func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error { udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) { request := protocol.RequestHeaderFromContext(ctx) if request == nil { return } payload := packet.Payload data, err := EncodeUDPPacket(request, payload.Bytes()) payload.Release() if err != nil { newError("failed to encode UDP packet").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) return } defer data.Release() conn.Write(data.Bytes()) }) inbound := session.InboundFromContext(ctx) if inbound == nil { panic("no inbound metadata") } inbound.User = s.user reader := buf.NewPacketReader(conn) for { mpayload, err := reader.ReadMultiBuffer() if err != nil { break } for _, payload := range mpayload { request, data, err := DecodeUDPPacket(s.user, payload) if err != nil { if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() { newError("dropping invalid UDP packet from: ", inbound.Source).Base(err).WriteToLog(session.ExportIDToError(ctx)) log.Record(&log.AccessMessage{ From: inbound.Source, To: "", Status: log.AccessRejected, Reason: err, }) } payload.Release() continue } currentPacketCtx := ctx dest := request.Destination() if inbound.Source.IsValid() { currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: inbound.Source, To: dest, Status: log.AccessAccepted, Reason: "", Email: request.User.Email, }) } newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(currentPacketCtx)) currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request) udpServer.Dispatch(currentPacketCtx, dest, data) } } return nil } func (s *Server) handleConnection(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error { sessionPolicy := s.policyManager.ForLevel(s.user.Level) conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)) bufferedReader := buf.BufferedReader{Reader: buf.NewReader(conn)} request, bodyReader, err := ReadTCPSession(s.user, &bufferedReader) if 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) } conn.SetReadDeadline(time.Time{}) inbound := session.InboundFromContext(ctx) if inbound == nil { panic("no inbound metadata") } inbound.User = s.user dest := request.Destination() ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: conn.RemoteAddr(), To: dest, Status: log.AccessAccepted, Reason: "", Email: request.User.Email, }) newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(ctx)) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { return err } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) responseWriter, err := WriteTCPResponse(request, bufferedWriter) if err != nil { return newError("failed to write response").Base(err) } { payload, err := link.Reader.ReadMultiBuffer() if err != nil { return err } if err := responseWriter.WriteMultiBuffer(payload); err != nil { return err } } if err := bufferedWriter.SetBuffered(false); err != nil { return err } if err := buf.Copy(link.Reader, responseWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport all TCP response").Base(err) } return nil } requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport all TCP request").Base(err) } return nil } var requestDoneAndCloseWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return nil } func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewServer(ctx, config.(*ServerConfig)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/shadowsocks/config.pb.go
proxy/shadowsocks/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/shadowsocks/config.proto package shadowsocks 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" net "v2ray.com/core/common/net" protocol "v2ray.com/core/common/protocol" ) 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 CipherType int32 const ( CipherType_UNKNOWN CipherType = 0 CipherType_AES_128_CFB CipherType = 1 CipherType_AES_256_CFB CipherType = 2 CipherType_CHACHA20 CipherType = 3 CipherType_CHACHA20_IETF CipherType = 4 CipherType_AES_128_GCM CipherType = 5 CipherType_AES_256_GCM CipherType = 6 CipherType_CHACHA20_POLY1305 CipherType = 7 CipherType_NONE CipherType = 8 ) // Enum value maps for CipherType. var ( CipherType_name = map[int32]string{ 0: "UNKNOWN", 1: "AES_128_CFB", 2: "AES_256_CFB", 3: "CHACHA20", 4: "CHACHA20_IETF", 5: "AES_128_GCM", 6: "AES_256_GCM", 7: "CHACHA20_POLY1305", 8: "NONE", } CipherType_value = map[string]int32{ "UNKNOWN": 0, "AES_128_CFB": 1, "AES_256_CFB": 2, "CHACHA20": 3, "CHACHA20_IETF": 4, "AES_128_GCM": 5, "AES_256_GCM": 6, "CHACHA20_POLY1305": 7, "NONE": 8, } ) func (x CipherType) Enum() *CipherType { p := new(CipherType) *p = x return p } func (x CipherType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (CipherType) Descriptor() protoreflect.EnumDescriptor { return file_proxy_shadowsocks_config_proto_enumTypes[0].Descriptor() } func (CipherType) Type() protoreflect.EnumType { return &file_proxy_shadowsocks_config_proto_enumTypes[0] } func (x CipherType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use CipherType.Descriptor instead. func (CipherType) EnumDescriptor() ([]byte, []int) { return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{0} } type Account struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"` CipherType CipherType `protobuf:"varint,2,opt,name=cipher_type,json=cipherType,proto3,enum=v2ray.core.proxy.shadowsocks.CipherType" json:"cipher_type,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_proxy_shadowsocks_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_shadowsocks_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_shadowsocks_config_proto_rawDescGZIP(), []int{0} } func (x *Account) GetPassword() string { if x != nil { return x.Password } return "" } func (x *Account) GetCipherType() CipherType { if x != nil { return x.CipherType } return CipherType_UNKNOWN } type ServerConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // UdpEnabled specified whether or not to enable UDP for Shadowsocks. // Deprecated. Use 'network' field. // // Deprecated: Do not use. UdpEnabled bool `protobuf:"varint,1,opt,name=udp_enabled,json=udpEnabled,proto3" json:"udp_enabled,omitempty"` User *protocol.User `protobuf:"bytes,2,opt,name=user,proto3" json:"user,omitempty"` Network []net.Network `protobuf:"varint,3,rep,packed,name=network,proto3,enum=v2ray.core.common.net.Network" json:"network,omitempty"` } func (x *ServerConfig) Reset() { *x = ServerConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_shadowsocks_config_proto_msgTypes[1] 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_shadowsocks_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 ServerConfig.ProtoReflect.Descriptor instead. func (*ServerConfig) Descriptor() ([]byte, []int) { return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{1} } // Deprecated: Do not use. func (x *ServerConfig) GetUdpEnabled() bool { if x != nil { return x.UdpEnabled } return false } func (x *ServerConfig) GetUser() *protocol.User { if x != nil { return x.User } return nil } func (x *ServerConfig) GetNetwork() []net.Network { if x != nil { return x.Network } return nil } 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_shadowsocks_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_shadowsocks_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_shadowsocks_config_proto_rawDescGZIP(), []int{2} } func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint { if x != nil { return x.Server } return nil } var File_proxy_shadowsocks_config_proto protoreflect.FileDescriptor var file_proxy_shadowsocks_config_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1c, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0x1a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 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, 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, 0x70, 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, 0x49, 0x0a, 0x0b, 0x63, 0x69, 0x70, 0x68, 0x65, 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x28, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0x2e, 0x43, 0x69, 0x70, 0x68, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x63, 0x69, 0x70, 0x68, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x22, 0xa3, 0x01, 0x0a, 0x0c, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x23, 0x0a, 0x0b, 0x75, 0x64, 0x70, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x42, 0x02, 0x18, 0x01, 0x52, 0x0a, 0x75, 0x64, 0x70, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x34, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x12, 0x38, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x52, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x22, 0x52, 0x0a, 0x0c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x42, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x2a, 0x9f, 0x01, 0x0a, 0x0a, 0x43, 0x69, 0x70, 0x68, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x0f, 0x0a, 0x0b, 0x41, 0x45, 0x53, 0x5f, 0x31, 0x32, 0x38, 0x5f, 0x43, 0x46, 0x42, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x41, 0x45, 0x53, 0x5f, 0x32, 0x35, 0x36, 0x5f, 0x43, 0x46, 0x42, 0x10, 0x02, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x48, 0x41, 0x43, 0x48, 0x41, 0x32, 0x30, 0x10, 0x03, 0x12, 0x11, 0x0a, 0x0d, 0x43, 0x48, 0x41, 0x43, 0x48, 0x41, 0x32, 0x30, 0x5f, 0x49, 0x45, 0x54, 0x46, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x41, 0x45, 0x53, 0x5f, 0x31, 0x32, 0x38, 0x5f, 0x47, 0x43, 0x4d, 0x10, 0x05, 0x12, 0x0f, 0x0a, 0x0b, 0x41, 0x45, 0x53, 0x5f, 0x32, 0x35, 0x36, 0x5f, 0x47, 0x43, 0x4d, 0x10, 0x06, 0x12, 0x15, 0x0a, 0x11, 0x43, 0x48, 0x41, 0x43, 0x48, 0x41, 0x32, 0x30, 0x5f, 0x50, 0x4f, 0x4c, 0x59, 0x31, 0x33, 0x30, 0x35, 0x10, 0x07, 0x12, 0x08, 0x0a, 0x04, 0x4e, 0x4f, 0x4e, 0x45, 0x10, 0x08, 0x42, 0x65, 0x0a, 0x20, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0x50, 0x01, 0x5a, 0x20, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0xaa, 0x02, 0x1c, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x53, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x73, 0x6f, 0x63, 0x6b, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_shadowsocks_config_proto_rawDescOnce sync.Once file_proxy_shadowsocks_config_proto_rawDescData = file_proxy_shadowsocks_config_proto_rawDesc ) func file_proxy_shadowsocks_config_proto_rawDescGZIP() []byte { file_proxy_shadowsocks_config_proto_rawDescOnce.Do(func() { file_proxy_shadowsocks_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_shadowsocks_config_proto_rawDescData) }) return file_proxy_shadowsocks_config_proto_rawDescData } var file_proxy_shadowsocks_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_proxy_shadowsocks_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_proxy_shadowsocks_config_proto_goTypes = []interface{}{ (CipherType)(0), // 0: v2ray.core.proxy.shadowsocks.CipherType (*Account)(nil), // 1: v2ray.core.proxy.shadowsocks.Account (*ServerConfig)(nil), // 2: v2ray.core.proxy.shadowsocks.ServerConfig (*ClientConfig)(nil), // 3: v2ray.core.proxy.shadowsocks.ClientConfig (*protocol.User)(nil), // 4: v2ray.core.common.protocol.User (net.Network)(0), // 5: v2ray.core.common.net.Network (*protocol.ServerEndpoint)(nil), // 6: v2ray.core.common.protocol.ServerEndpoint } var file_proxy_shadowsocks_config_proto_depIdxs = []int32{ 0, // 0: v2ray.core.proxy.shadowsocks.Account.cipher_type:type_name -> v2ray.core.proxy.shadowsocks.CipherType 4, // 1: v2ray.core.proxy.shadowsocks.ServerConfig.user:type_name -> v2ray.core.common.protocol.User 5, // 2: v2ray.core.proxy.shadowsocks.ServerConfig.network:type_name -> v2ray.core.common.net.Network 6, // 3: v2ray.core.proxy.shadowsocks.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_proxy_shadowsocks_config_proto_init() } func file_proxy_shadowsocks_config_proto_init() { if File_proxy_shadowsocks_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_shadowsocks_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_shadowsocks_config_proto_msgTypes[1].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 } } file_proxy_shadowsocks_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 } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proxy_shadowsocks_config_proto_rawDesc, NumEnums: 1, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_shadowsocks_config_proto_goTypes, DependencyIndexes: file_proxy_shadowsocks_config_proto_depIdxs, EnumInfos: file_proxy_shadowsocks_config_proto_enumTypes, MessageInfos: file_proxy_shadowsocks_config_proto_msgTypes, }.Build() File_proxy_shadowsocks_config_proto = out.File file_proxy_shadowsocks_config_proto_rawDesc = nil file_proxy_shadowsocks_config_proto_goTypes = nil file_proxy_shadowsocks_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dns/dns_test.go
proxy/dns/dns_test.go
package dns_test import ( "strconv" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/miekg/dns" "v2ray.com/core" "v2ray.com/core/app/dispatcher" dnsapp "v2ray.com/core/app/dns" "v2ray.com/core/app/policy" "v2ray.com/core/app/proxyman" _ "v2ray.com/core/app/proxyman/inbound" _ "v2ray.com/core/app/proxyman/outbound" "v2ray.com/core/common" "v2ray.com/core/common/net" "v2ray.com/core/common/serial" dns_proxy "v2ray.com/core/proxy/dns" "v2ray.com/core/proxy/dokodemo" "v2ray.com/core/testing/servers/tcp" "v2ray.com/core/testing/servers/udp" ) type staticHandler struct { } func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { ans := new(dns.Msg) ans.Id = r.Id var clientIP net.IP opt := r.IsEdns0() if opt != nil { for _, o := range opt.Option { if o.Option() == dns.EDNS0SUBNET { subnet := o.(*dns.EDNS0_SUBNET) clientIP = subnet.Address } } } for _, q := range r.Question { if q.Name == "google.com." && q.Qtype == dns.TypeA { if clientIP == nil { rr, _ := dns.NewRR("google.com. IN A 8.8.8.8") ans.Answer = append(ans.Answer, rr) } else { rr, _ := dns.NewRR("google.com. IN A 8.8.4.4") ans.Answer = append(ans.Answer, rr) } } else if q.Name == "facebook.com." && q.Qtype == dns.TypeA { rr, _ := dns.NewRR("facebook.com. IN A 9.9.9.9") ans.Answer = append(ans.Answer, rr) } else if q.Name == "ipv6.google.com." && q.Qtype == dns.TypeA { rr, err := dns.NewRR("ipv6.google.com. IN A 8.8.8.7") common.Must(err) ans.Answer = append(ans.Answer, rr) } else if q.Name == "ipv6.google.com." && q.Qtype == dns.TypeAAAA { rr, err := dns.NewRR("ipv6.google.com. IN AAAA 2001:4860:4860::8888") common.Must(err) ans.Answer = append(ans.Answer, rr) } else if q.Name == "notexist.google.com." && q.Qtype == dns.TypeAAAA { ans.MsgHdr.Rcode = dns.RcodeNameError } } w.WriteMsg(ans) } func TestUDPDNSTunnel(t *testing.T) { port := udp.PickPort() dnsServer := dns.Server{ Addr: "127.0.0.1:" + port.String(), Net: "udp", Handler: &staticHandler{}, UDPSize: 1200, } defer dnsServer.Shutdown() go dnsServer.ListenAndServe() time.Sleep(time.Second) serverPort := udp.PickPort() config := &core.Config{ App: []*serial.TypedMessage{ serial.ToTypedMessage(&dnsapp.Config{ NameServers: []*net.Endpoint{ { Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: uint32(port), }, }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&policy.Config{}), }, Inbound: []*core.InboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dokodemo.Config{ Address: net.NewIPOrDomain(net.LocalHostIP), Port: uint32(port), Networks: []net.Network{net.Network_UDP}, }), ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: net.SinglePortRange(serverPort), Listen: net.NewIPOrDomain(net.LocalHostIP), }), }, }, Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{}), }, }, } v, err := core.New(config) common.Must(err) common.Must(v.Start()) defer v.Close() { m1 := new(dns.Msg) m1.Id = dns.Id() m1.RecursionDesired = true m1.Question = make([]dns.Question, 1) m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET} c := new(dns.Client) in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort))) common.Must(err) if len(in.Answer) != 1 { t.Fatal("len(answer): ", len(in.Answer)) } rr, ok := in.Answer[0].(*dns.A) if !ok { t.Fatal("not A record") } if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" { t.Error(r) } } { m1 := new(dns.Msg) m1.Id = dns.Id() m1.RecursionDesired = true m1.Question = make([]dns.Question, 1) m1.Question[0] = dns.Question{Name: "ipv4only.google.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET} c := new(dns.Client) c.Timeout = 10 * time.Second in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort))) common.Must(err) if len(in.Answer) != 0 { t.Fatal("len(answer): ", len(in.Answer)) } } { m1 := new(dns.Msg) m1.Id = dns.Id() m1.RecursionDesired = true m1.Question = make([]dns.Question, 1) m1.Question[0] = dns.Question{Name: "notexist.google.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET} c := new(dns.Client) in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort))) common.Must(err) if in.Rcode != dns.RcodeNameError { t.Error("expected NameError, but got ", in.Rcode) } } } func TestTCPDNSTunnel(t *testing.T) { port := udp.PickPort() dnsServer := dns.Server{ Addr: "127.0.0.1:" + port.String(), Net: "udp", Handler: &staticHandler{}, } defer dnsServer.Shutdown() go dnsServer.ListenAndServe() time.Sleep(time.Second) serverPort := tcp.PickPort() config := &core.Config{ App: []*serial.TypedMessage{ serial.ToTypedMessage(&dnsapp.Config{ NameServer: []*dnsapp.NameServer{ { Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: uint32(port), }, }, }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&policy.Config{}), }, Inbound: []*core.InboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dokodemo.Config{ Address: net.NewIPOrDomain(net.LocalHostIP), Port: uint32(port), Networks: []net.Network{net.Network_TCP}, }), ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: net.SinglePortRange(serverPort), Listen: net.NewIPOrDomain(net.LocalHostIP), }), }, }, Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{}), }, }, } v, err := core.New(config) common.Must(err) common.Must(v.Start()) defer v.Close() m1 := new(dns.Msg) m1.Id = dns.Id() m1.RecursionDesired = true m1.Question = make([]dns.Question, 1) m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET} c := &dns.Client{ Net: "tcp", } in, _, err := c.Exchange(m1, "127.0.0.1:"+serverPort.String()) common.Must(err) if len(in.Answer) != 1 { t.Fatal("len(answer): ", len(in.Answer)) } rr, ok := in.Answer[0].(*dns.A) if !ok { t.Fatal("not A record") } if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" { t.Error(r) } } func TestUDP2TCPDNSTunnel(t *testing.T) { port := tcp.PickPort() dnsServer := dns.Server{ Addr: "127.0.0.1:" + port.String(), Net: "tcp", Handler: &staticHandler{}, } defer dnsServer.Shutdown() go dnsServer.ListenAndServe() time.Sleep(time.Second) serverPort := tcp.PickPort() config := &core.Config{ App: []*serial.TypedMessage{ serial.ToTypedMessage(&dnsapp.Config{ NameServer: []*dnsapp.NameServer{ { Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: uint32(port), }, }, }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&policy.Config{}), }, Inbound: []*core.InboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dokodemo.Config{ Address: net.NewIPOrDomain(net.LocalHostIP), Port: uint32(port), Networks: []net.Network{net.Network_TCP}, }), ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: net.SinglePortRange(serverPort), Listen: net.NewIPOrDomain(net.LocalHostIP), }), }, }, Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{ Server: &net.Endpoint{ Network: net.Network_TCP, }, }), }, }, } v, err := core.New(config) common.Must(err) common.Must(v.Start()) defer v.Close() m1 := new(dns.Msg) m1.Id = dns.Id() m1.RecursionDesired = true m1.Question = make([]dns.Question, 1) m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET} c := &dns.Client{ Net: "tcp", } in, _, err := c.Exchange(m1, "127.0.0.1:"+serverPort.String()) common.Must(err) if len(in.Answer) != 1 { t.Fatal("len(answer): ", len(in.Answer)) } rr, ok := in.Answer[0].(*dns.A) if !ok { t.Fatal("not A record") } if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" { t.Error(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dns/errors.generated.go
proxy/dns/errors.generated.go
package dns import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dns/dns.go
proxy/dns/dns.go
// +build !confonly package dns import ( "context" "io" "sync" "golang.org/x/net/dns/dnsmessage" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" dns_proto "v2ray.com/core/common/protocol/dns" "v2ray.com/core/common/session" "v2ray.com/core/common/task" "v2ray.com/core/features/dns" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { h := new(Handler) if err := core.RequireFeatures(ctx, func(dnsClient dns.Client) error { return h.Init(config.(*Config), dnsClient) }); err != nil { return nil, err } return h, nil })) } type ownLinkVerifier interface { IsOwnLink(ctx context.Context) bool } type Handler struct { ipv4Lookup dns.IPv4Lookup ipv6Lookup dns.IPv6Lookup ownLinkVerifier ownLinkVerifier server net.Destination } func (h *Handler) Init(config *Config, dnsClient dns.Client) error { ipv4lookup, ok := dnsClient.(dns.IPv4Lookup) if !ok { return newError("dns.Client doesn't implement IPv4Lookup") } h.ipv4Lookup = ipv4lookup ipv6lookup, ok := dnsClient.(dns.IPv6Lookup) if !ok { return newError("dns.Client doesn't implement IPv6Lookup") } h.ipv6Lookup = ipv6lookup if v, ok := dnsClient.(ownLinkVerifier); ok { h.ownLinkVerifier = v } if config.Server != nil { h.server = config.Server.AsDestination() } return nil } func (h *Handler) isOwnLink(ctx context.Context) bool { return h.ownLinkVerifier != nil && h.ownLinkVerifier.IsOwnLink(ctx) } func parseIPQuery(b []byte) (r bool, domain string, id uint16, qType dnsmessage.Type) { var parser dnsmessage.Parser header, err := parser.Start(b) if err != nil { newError("parser start").Base(err).WriteToLog() return } id = header.ID q, err := parser.Question() if err != nil { newError("question").Base(err).WriteToLog() return } qType = q.Type if qType != dnsmessage.TypeA && qType != dnsmessage.TypeAAAA { return } domain = q.Name.String() r = true return } // Process implements proxy.Outbound. func (h *Handler) Process(ctx context.Context, link *transport.Link, d internet.Dialer) error { outbound := session.OutboundFromContext(ctx) if outbound == nil || !outbound.Target.IsValid() { return newError("invalid outbound") } srcNetwork := outbound.Target.Network dest := outbound.Target if h.server.Network != net.Network_Unknown { dest.Network = h.server.Network } if h.server.Address != nil { dest.Address = h.server.Address } if h.server.Port != 0 { dest.Port = h.server.Port } newError("handling DNS traffic to ", dest).WriteToLog(session.ExportIDToError(ctx)) conn := &outboundConn{ dialer: func() (internet.Connection, error) { return d.Dial(ctx, dest) }, connReady: make(chan struct{}, 1), } var reader dns_proto.MessageReader var writer dns_proto.MessageWriter if srcNetwork == net.Network_TCP { reader = dns_proto.NewTCPReader(link.Reader) writer = &dns_proto.TCPWriter{ Writer: link.Writer, } } else { reader = &dns_proto.UDPReader{ Reader: link.Reader, } writer = &dns_proto.UDPWriter{ Writer: link.Writer, } } var connReader dns_proto.MessageReader var connWriter dns_proto.MessageWriter if dest.Network == net.Network_TCP { connReader = dns_proto.NewTCPReader(buf.NewReader(conn)) connWriter = &dns_proto.TCPWriter{ Writer: buf.NewWriter(conn), } } else { connReader = &dns_proto.UDPReader{ Reader: buf.NewPacketReader(conn), } connWriter = &dns_proto.UDPWriter{ Writer: buf.NewWriter(conn), } } request := func() error { defer conn.Close() for { b, err := reader.ReadMessage() if err == io.EOF { return nil } if err != nil { return err } if !h.isOwnLink(ctx) { isIPQuery, domain, id, qType := parseIPQuery(b.Bytes()) if isIPQuery { go h.handleIPQuery(id, qType, domain, writer) continue } } if err := connWriter.WriteMessage(b); err != nil { return err } } } response := func() error { for { b, err := connReader.ReadMessage() if err == io.EOF { return nil } if err != nil { return err } if err := writer.WriteMessage(b); err != nil { return err } } } if err := task.Run(ctx, request, response); err != nil { return newError("connection ends").Base(err) } return nil } func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string, writer dns_proto.MessageWriter) { var ips []net.IP var err error switch qType { case dnsmessage.TypeA: ips, err = h.ipv4Lookup.LookupIPv4(domain) case dnsmessage.TypeAAAA: ips, err = h.ipv6Lookup.LookupIPv6(domain) } rcode := dns.RCodeFromError(err) if rcode == 0 && len(ips) == 0 && err != dns.ErrEmptyResponse { newError("ip query").Base(err).WriteToLog() return } b := buf.New() rawBytes := b.Extend(buf.Size) builder := dnsmessage.NewBuilder(rawBytes[:0], dnsmessage.Header{ ID: id, RCode: dnsmessage.RCode(rcode), RecursionAvailable: true, RecursionDesired: true, Response: true, Authoritative: true, }) builder.EnableCompression() common.Must(builder.StartQuestions()) common.Must(builder.Question(dnsmessage.Question{ Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, Type: qType, })) common.Must(builder.StartAnswers()) rHeader := dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, TTL: 600} for _, ip := range ips { if len(ip) == net.IPv4len { var r dnsmessage.AResource copy(r.A[:], ip) common.Must(builder.AResource(rHeader, r)) } else { var r dnsmessage.AAAAResource copy(r.AAAA[:], ip) common.Must(builder.AAAAResource(rHeader, r)) } } msgBytes, err := builder.Finish() if err != nil { newError("pack message").Base(err).WriteToLog() b.Release() return } b.Resize(0, int32(len(msgBytes))) if err := writer.WriteMessage(b); err != nil { newError("write IP answer").Base(err).WriteToLog() } } type outboundConn struct { access sync.Mutex dialer func() (internet.Connection, error) conn net.Conn connReady chan struct{} } func (c *outboundConn) dial() error { conn, err := c.dialer() if err != nil { return err } c.conn = conn c.connReady <- struct{}{} return nil } func (c *outboundConn) Write(b []byte) (int, error) { c.access.Lock() if c.conn == nil { if err := c.dial(); err != nil { c.access.Unlock() newError("failed to dial outbound connection").Base(err).AtWarning().WriteToLog() return len(b), nil } } c.access.Unlock() return c.conn.Write(b) } func (c *outboundConn) Read(b []byte) (int, error) { var conn net.Conn c.access.Lock() conn = c.conn c.access.Unlock() if conn == nil { _, open := <-c.connReady if !open { return 0, io.EOF } conn = c.conn } return conn.Read(b) } func (c *outboundConn) Close() error { c.access.Lock() close(c.connReady) if c.conn != nil { c.conn.Close() } c.access.Unlock() return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dns/config.pb.go
proxy/dns/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/dns/config.proto package dns 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" net "v2ray.com/core/common/net" ) 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 Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Server is the DNS server address. If specified, this address overrides the // original one. Server *net.Endpoint `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_dns_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_dns_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_dns_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetServer() *net.Endpoint { if x != nil { return x.Server } return nil } var File_proxy_dns_config_proto protoreflect.FileDescriptor var file_proxy_dns_config_proto_rawDesc = []byte{ 0x0a, 0x16, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x64, 0x6e, 0x73, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x64, 0x6e, 0x73, 0x1a, 0x1c, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x41, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x42, 0x4d, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x64, 0x6e, 0x73, 0x50, 0x01, 0x5a, 0x18, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x64, 0x6e, 0x73, 0xaa, 0x02, 0x14, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x44, 0x6e, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_dns_config_proto_rawDescOnce sync.Once file_proxy_dns_config_proto_rawDescData = file_proxy_dns_config_proto_rawDesc ) func file_proxy_dns_config_proto_rawDescGZIP() []byte { file_proxy_dns_config_proto_rawDescOnce.Do(func() { file_proxy_dns_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_dns_config_proto_rawDescData) }) return file_proxy_dns_config_proto_rawDescData } var file_proxy_dns_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_dns_config_proto_goTypes = []interface{}{ (*Config)(nil), // 0: v2ray.core.proxy.dns.Config (*net.Endpoint)(nil), // 1: v2ray.core.common.net.Endpoint } var file_proxy_dns_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.proxy.dns.Config.server:type_name -> v2ray.core.common.net.Endpoint 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_proxy_dns_config_proto_init() } func file_proxy_dns_config_proto_init() { if File_proxy_dns_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_dns_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_dns_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_dns_config_proto_goTypes, DependencyIndexes: file_proxy_dns_config_proto_depIdxs, MessageInfos: file_proxy_dns_config_proto_msgTypes, }.Build() File_proxy_dns_config_proto = out.File file_proxy_dns_config_proto_rawDesc = nil file_proxy_dns_config_proto_goTypes = nil file_proxy_dns_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dokodemo/errors.generated.go
proxy/dokodemo/errors.generated.go
package dokodemo import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dokodemo/config.go
proxy/dokodemo/config.go
package dokodemo import ( "v2ray.com/core/common/net" ) // GetPredefinedAddress returns the defined address from proto config. Null if address is not valid. func (v *Config) GetPredefinedAddress() net.Address { addr := v.Address.AsAddress() if addr == nil { return nil } return addr }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dokodemo/config.pb.go
proxy/dokodemo/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/dokodemo/config.proto package dokodemo 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" net "v2ray.com/core/common/net" ) 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 Config 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"` // List of networks that the Dokodemo accepts. // Deprecated. Use networks. // // Deprecated: Do not use. NetworkList *net.NetworkList `protobuf:"bytes,3,opt,name=network_list,json=networkList,proto3" json:"network_list,omitempty"` // List of networks that the Dokodemo accepts. Networks []net.Network `protobuf:"varint,7,rep,packed,name=networks,proto3,enum=v2ray.core.common.net.Network" json:"networks,omitempty"` // Deprecated: Do not use. Timeout uint32 `protobuf:"varint,4,opt,name=timeout,proto3" json:"timeout,omitempty"` FollowRedirect bool `protobuf:"varint,5,opt,name=follow_redirect,json=followRedirect,proto3" json:"follow_redirect,omitempty"` UserLevel uint32 `protobuf:"varint,6,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_dokodemo_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_dokodemo_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_dokodemo_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetAddress() *net.IPOrDomain { if x != nil { return x.Address } return nil } func (x *Config) GetPort() uint32 { if x != nil { return x.Port } return 0 } // Deprecated: Do not use. func (x *Config) GetNetworkList() *net.NetworkList { if x != nil { return x.NetworkList } return nil } func (x *Config) GetNetworks() []net.Network { if x != nil { return x.Networks } return nil } // Deprecated: Do not use. func (x *Config) GetTimeout() uint32 { if x != nil { return x.Timeout } return 0 } func (x *Config) GetFollowRedirect() bool { if x != nil { return x.FollowRedirect } return false } func (x *Config) GetUserLevel() uint32 { if x != nil { return x.UserLevel } return 0 } var File_proxy_dokodemo_config_proto protoreflect.FileDescriptor var file_proxy_dokodemo_config_proto_rawDesc = []byte{ 0x0a, 0x1b, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x64, 0x6f, 0x6b, 0x6f, 0x64, 0x65, 0x6d, 0x6f, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x64, 0x6f, 0x6b, 0x6f, 0x64, 0x65, 0x6d, 0x6f, 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, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xc6, 0x02, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3b, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x49, 0x0a, 0x0c, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x42, 0x02, 0x18, 0x01, 0x52, 0x0b, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x3a, 0x0a, 0x08, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x52, 0x08, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x12, 0x1c, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x02, 0x18, 0x01, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x52, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x42, 0x5c, 0x0a, 0x1d, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x64, 0x6f, 0x6b, 0x6f, 0x64, 0x65, 0x6d, 0x6f, 0x50, 0x01, 0x5a, 0x1d, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x64, 0x6f, 0x6b, 0x6f, 0x64, 0x65, 0x6d, 0x6f, 0xaa, 0x02, 0x19, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x44, 0x6f, 0x6b, 0x6f, 0x64, 0x65, 0x6d, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_dokodemo_config_proto_rawDescOnce sync.Once file_proxy_dokodemo_config_proto_rawDescData = file_proxy_dokodemo_config_proto_rawDesc ) func file_proxy_dokodemo_config_proto_rawDescGZIP() []byte { file_proxy_dokodemo_config_proto_rawDescOnce.Do(func() { file_proxy_dokodemo_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_dokodemo_config_proto_rawDescData) }) return file_proxy_dokodemo_config_proto_rawDescData } var file_proxy_dokodemo_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_dokodemo_config_proto_goTypes = []interface{}{ (*Config)(nil), // 0: v2ray.core.proxy.dokodemo.Config (*net.IPOrDomain)(nil), // 1: v2ray.core.common.net.IPOrDomain (*net.NetworkList)(nil), // 2: v2ray.core.common.net.NetworkList (net.Network)(0), // 3: v2ray.core.common.net.Network } var file_proxy_dokodemo_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.proxy.dokodemo.Config.address:type_name -> v2ray.core.common.net.IPOrDomain 2, // 1: v2ray.core.proxy.dokodemo.Config.network_list:type_name -> v2ray.core.common.net.NetworkList 3, // 2: v2ray.core.proxy.dokodemo.Config.networks:type_name -> v2ray.core.common.net.Network 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_dokodemo_config_proto_init() } func file_proxy_dokodemo_config_proto_init() { if File_proxy_dokodemo_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_dokodemo_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_dokodemo_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_dokodemo_config_proto_goTypes, DependencyIndexes: file_proxy_dokodemo_config_proto_depIdxs, MessageInfos: file_proxy_dokodemo_config_proto_msgTypes, }.Build() File_proxy_dokodemo_config_proto = out.File file_proxy_dokodemo_config_proto_rawDesc = nil file_proxy_dokodemo_config_proto_goTypes = nil file_proxy_dokodemo_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/dokodemo/dokodemo.go
proxy/dokodemo/dokodemo.go
// +build !confonly package dokodemo //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "sync/atomic" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/transport/internet" ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { d := new(DokodemoDoor) err := core.RequireFeatures(ctx, func(pm policy.Manager) error { return d.Init(config.(*Config), pm, session.SockoptFromContext(ctx)) }) return d, err })) } type DokodemoDoor struct { policyManager policy.Manager config *Config address net.Address port net.Port sockopt *session.Sockopt } // Init initializes the DokodemoDoor instance with necessary parameters. func (d *DokodemoDoor) Init(config *Config, pm policy.Manager, sockopt *session.Sockopt) error { if (config.NetworkList == nil || len(config.NetworkList.Network) == 0) && len(config.Networks) == 0 { return newError("no network specified") } d.config = config d.address = config.GetPredefinedAddress() d.port = net.Port(config.Port) d.policyManager = pm d.sockopt = sockopt return nil } // Network implements proxy.Inbound. func (d *DokodemoDoor) Network() []net.Network { if len(d.config.Networks) > 0 { return d.config.Networks } return d.config.NetworkList.Network } func (d *DokodemoDoor) policy() policy.Session { config := d.config p := d.policyManager.ForLevel(config.UserLevel) if config.Timeout > 0 && config.UserLevel == 0 { p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second } return p } type hasHandshakeAddress interface { HandshakeAddress() net.Address } // Process implements proxy.Inbound. func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog(session.ExportIDToError(ctx)) dest := net.Destination{ Network: network, Address: d.address, Port: d.port, } destinationOverridden := false if d.config.FollowRedirect { if outbound := session.OutboundFromContext(ctx); outbound != nil && outbound.Target.IsValid() { dest = outbound.Target destinationOverridden = true } else if handshake, ok := conn.(hasHandshakeAddress); ok { addr := handshake.HandshakeAddress() if addr != nil { dest.Address = addr destinationOverridden = true } } } if !dest.IsValid() || dest.Address == nil { return newError("unable to get destination") } if inbound := session.InboundFromContext(ctx); inbound != nil { inbound.User = &protocol.MemoryUser{ Level: d.config.UserLevel, } } ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: conn.RemoteAddr(), To: dest, Status: log.AccessAccepted, Reason: "", }) newError("received request for ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx)) plcy := d.policy() ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { return newError("failed to dispatch request").Base(err) } requestCount := int32(1) requestDone := func() error { defer func() { if atomic.AddInt32(&requestCount, -1) == 0 { timer.SetTimeout(plcy.Timeouts.DownlinkOnly) } }() var reader buf.Reader if dest.Network == net.Network_UDP { reader = buf.NewPacketReader(conn) } else { reader = buf.NewReader(conn) } if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport request").Base(err) } return nil } tproxyRequest := func() error { return nil } var writer buf.Writer if network == net.Network_TCP { writer = buf.NewWriter(conn) } else { //if we are in TPROXY mode, use linux's udp forging functionality if !destinationOverridden { writer = &buf.SequentialWriter{Writer: conn} } else { sockopt := &internet.SocketConfig{ Tproxy: internet.SocketConfig_TProxy, } if dest.Address.Family().IsIP() { sockopt.BindAddress = dest.Address.IP() sockopt.BindPort = uint32(dest.Port) } if d.sockopt != nil { sockopt.Mark = d.sockopt.Mark } tConn, err := internet.DialSystem(ctx, net.DestinationFromAddr(conn.RemoteAddr()), sockopt) if err != nil { return err } defer tConn.Close() writer = &buf.SequentialWriter{Writer: tConn} tReader := buf.NewPacketReader(tConn) requestCount++ tproxyRequest = func() error { defer func() { if atomic.AddInt32(&requestCount, -1) == 0 { timer.SetTimeout(plcy.Timeouts.DownlinkOnly) } }() if err := buf.Copy(tReader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport request (TPROXY conn)").Base(err) } return nil } } } responseDone := func() error { defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transport response").Base(err) } return nil } if err := task.Run(ctx, task.OnSuccess(func() error { return task.Run(ctx, requestDone, tproxyRequest) }, task.Close(link.Writer)), responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/errors.generated.go
proxy/mtproto/errors.generated.go
package mtproto import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/client.go
proxy/mtproto/client.go
package mtproto import ( "context" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/net" "v2ray.com/core/common/session" "v2ray.com/core/common/task" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) type Client struct { } func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { return &Client{}, nil } 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("unknown destination.") } dest := outbound.Target if dest.Network != net.Network_TCP { return newError("not TCP traffic", dest) } conn, err := dialer.Dial(ctx, dest) if err != nil { return newError("failed to dial to ", dest).Base(err).AtWarning() } defer conn.Close() // nolint: errcheck sc := SessionContextFromContext(ctx) auth := NewAuthentication(sc) defer putAuthenticationObject(auth) request := func() error { encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:]) var header [HeaderSize]byte encryptor.XORKeyStream(header[:], auth.Header[:]) copy(header[:56], auth.Header[:]) if _, err := conn.Write(header[:]); err != nil { return newError("failed to write auth header").Base(err) } connWriter := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn)) return buf.Copy(link.Reader, connWriter) } response := func() error { decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:]) connReader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn)) return buf.Copy(connReader, link.Writer) } var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) if err := task.Run(ctx, request, 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)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/config.go
proxy/mtproto/config.go
package mtproto import ( "v2ray.com/core/common/protocol" ) func (a *Account) Equals(another protocol.Account) bool { aa, ok := another.(*Account) if !ok { return false } if len(a.Secret) != len(aa.Secret) { return false } for i, v := range a.Secret { if v != aa.Secret[i] { return false } } return true }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/mtproto.go
proxy/mtproto/mtproto.go
package mtproto //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/server.go
proxy/mtproto/server.go
// +build !confonly package mtproto import ( "bytes" "context" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/transport/internet" ) var ( dcList = []net.Address{ net.ParseAddress("149.154.175.50"), net.ParseAddress("149.154.167.51"), net.ParseAddress("149.154.175.100"), net.ParseAddress("149.154.167.91"), net.ParseAddress("149.154.171.5"), } ) type Server struct { user *protocol.User account *Account policy policy.Manager } func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { if len(config.User) == 0 { return nil, newError("no user configured.") } user := config.User[0] rawAccount, err := config.User[0].GetTypedAccount() if err != nil { return nil, newError("invalid account").Base(err) } account, ok := rawAccount.(*Account) if !ok { return nil, newError("not a MTProto account") } v := core.MustFromContext(ctx) return &Server{ user: user, account: account, policy: v.GetFeature(policy.ManagerType()).(policy.Manager), }, nil } func (s *Server) Network() []net.Network { return []net.Network{net.Network_TCP} } var ctype1 = []byte{0xef, 0xef, 0xef, 0xef} var ctype2 = []byte{0xee, 0xee, 0xee, 0xee} func isValidConnectionType(c [4]byte) bool { if bytes.Equal(c[:], ctype1) { return true } if bytes.Equal(c[:], ctype2) { return true } return false } func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { sPolicy := s.policy.ForLevel(s.user.Level) if err := conn.SetDeadline(time.Now().Add(sPolicy.Timeouts.Handshake)); err != nil { newError("failed to set deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) } auth, err := ReadAuthentication(conn) if err != nil { return newError("failed to read authentication header").Base(err) } defer putAuthenticationObject(auth) if err := conn.SetDeadline(time.Time{}); err != nil { newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) } auth.ApplySecret(s.account.Secret) decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:]) decryptor.XORKeyStream(auth.Header[:], auth.Header[:]) ct := auth.ConnectionType() if !isValidConnectionType(ct) { return newError("invalid connection type: ", ct) } dcID := auth.DataCenterID() if dcID >= uint16(len(dcList)) { return newError("invalid datacenter id: ", dcID) } dest := net.Destination{ Network: net.Network_TCP, Address: dcList[dcID], Port: net.Port(443), } ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sPolicy.Buffer) sc := SessionContext{ ConnectionType: ct, DataCenterID: dcID, } ctx = ContextWithSessionContext(ctx, sc) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { return newError("failed to dispatch request to: ", dest).Base(err) } request := func() error { defer timer.SetTimeout(sPolicy.Timeouts.DownlinkOnly) reader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn)) return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) } response := func() error { defer timer.SetTimeout(sPolicy.Timeouts.UplinkOnly) encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:]) writer := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn)) return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) } var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return nil } func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewServer(ctx, config.(*ServerConfig)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/auth.go
proxy/mtproto/auth.go
package mtproto import ( "context" "crypto/rand" "crypto/sha256" "io" "sync" "v2ray.com/core/common" ) const ( HeaderSize = 64 ) type SessionContext struct { ConnectionType [4]byte DataCenterID uint16 } func DefaultSessionContext() SessionContext { return SessionContext{ ConnectionType: [4]byte{0xef, 0xef, 0xef, 0xef}, DataCenterID: 0, } } type contextKey int32 const ( sessionContextKey contextKey = iota ) func ContextWithSessionContext(ctx context.Context, c SessionContext) context.Context { return context.WithValue(ctx, sessionContextKey, c) } func SessionContextFromContext(ctx context.Context) SessionContext { if c := ctx.Value(sessionContextKey); c != nil { return c.(SessionContext) } return DefaultSessionContext() } type Authentication struct { Header [HeaderSize]byte DecodingKey [32]byte EncodingKey [32]byte DecodingNonce [16]byte EncodingNonce [16]byte } func (a *Authentication) DataCenterID() uint16 { x := ((int16(a.Header[61]) << 8) | int16(a.Header[60])) if x < 0 { x = -x } return uint16(x) - 1 } func (a *Authentication) ConnectionType() [4]byte { var x [4]byte copy(x[:], a.Header[56:60]) return x } func (a *Authentication) ApplySecret(b []byte) { a.DecodingKey = sha256.Sum256(append(a.DecodingKey[:], b...)) a.EncodingKey = sha256.Sum256(append(a.EncodingKey[:], b...)) } func generateRandomBytes(random []byte, connType [4]byte) { for { common.Must2(rand.Read(random)) if random[0] == 0xef { continue } val := (uint32(random[3]) << 24) | (uint32(random[2]) << 16) | (uint32(random[1]) << 8) | uint32(random[0]) if val == 0x44414548 || val == 0x54534f50 || val == 0x20544547 || val == 0x4954504f || val == 0xeeeeeeee { continue } if (uint32(random[7])<<24)|(uint32(random[6])<<16)|(uint32(random[5])<<8)|uint32(random[4]) == 0x00000000 { continue } copy(random[56:60], connType[:]) return } } func NewAuthentication(sc SessionContext) *Authentication { auth := getAuthenticationObject() random := auth.Header[:] generateRandomBytes(random, sc.ConnectionType) copy(auth.EncodingKey[:], random[8:]) copy(auth.EncodingNonce[:], random[8+32:]) keyivInverse := Inverse(random[8 : 8+32+16]) copy(auth.DecodingKey[:], keyivInverse) copy(auth.DecodingNonce[:], keyivInverse[32:]) return auth } func ReadAuthentication(reader io.Reader) (*Authentication, error) { auth := getAuthenticationObject() if _, err := io.ReadFull(reader, auth.Header[:]); err != nil { putAuthenticationObject(auth) return nil, err } copy(auth.DecodingKey[:], auth.Header[8:]) copy(auth.DecodingNonce[:], auth.Header[8+32:]) keyivInverse := Inverse(auth.Header[8 : 8+32+16]) copy(auth.EncodingKey[:], keyivInverse) copy(auth.EncodingNonce[:], keyivInverse[32:]) return auth, nil } // Inverse returns a new byte array. It is a sequence of bytes when the input is read from end to beginning.Inverse // Visible for testing only. func Inverse(b []byte) []byte { lenb := len(b) b2 := make([]byte, lenb) for i, v := range b { b2[lenb-i-1] = v } return b2 } var ( authPool = sync.Pool{ New: func() interface{} { return new(Authentication) }, } ) func getAuthenticationObject() *Authentication { return authPool.Get().(*Authentication) } func putAuthenticationObject(auth *Authentication) { authPool.Put(auth) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/config.pb.go
proxy/mtproto/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/mtproto/config.proto package mtproto 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" protocol "v2ray.com/core/common/protocol" ) 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 Secret []byte `protobuf:"bytes,1,opt,name=secret,proto3" json:"secret,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_proxy_mtproto_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_mtproto_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_mtproto_config_proto_rawDescGZIP(), []int{0} } func (x *Account) GetSecret() []byte { if x != nil { return x.Secret } return nil } type ServerConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // User is a list of users that allowed to connect to this inbound. // Although this is a repeated field, only the first user is effective for // now. User []*protocol.User `protobuf:"bytes,1,rep,name=user,proto3" json:"user,omitempty"` } func (x *ServerConfig) Reset() { *x = ServerConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_mtproto_config_proto_msgTypes[1] 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_mtproto_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 ServerConfig.ProtoReflect.Descriptor instead. func (*ServerConfig) Descriptor() ([]byte, []int) { return file_proxy_mtproto_config_proto_rawDescGZIP(), []int{1} } func (x *ServerConfig) GetUser() []*protocol.User { if x != nil { return x.User } return nil } type ClientConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ClientConfig) Reset() { *x = ClientConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_mtproto_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_mtproto_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_mtproto_config_proto_rawDescGZIP(), []int{2} } var File_proxy_mtproto_config_proto protoreflect.FileDescriptor var file_proxy_mtproto_config_proto_rawDesc = []byte{ 0x0a, 0x1a, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x6d, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x6d, 0x74, 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, 0x21, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x22, 0x44, 0x0a, 0x0c, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x22, 0x0e, 0x0a, 0x0c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x59, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x6d, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x1c, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x6d, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0xaa, 0x02, 0x18, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x4d, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_mtproto_config_proto_rawDescOnce sync.Once file_proxy_mtproto_config_proto_rawDescData = file_proxy_mtproto_config_proto_rawDesc ) func file_proxy_mtproto_config_proto_rawDescGZIP() []byte { file_proxy_mtproto_config_proto_rawDescOnce.Do(func() { file_proxy_mtproto_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_mtproto_config_proto_rawDescData) }) return file_proxy_mtproto_config_proto_rawDescData } var file_proxy_mtproto_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_proxy_mtproto_config_proto_goTypes = []interface{}{ (*Account)(nil), // 0: v2ray.core.proxy.mtproto.Account (*ServerConfig)(nil), // 1: v2ray.core.proxy.mtproto.ServerConfig (*ClientConfig)(nil), // 2: v2ray.core.proxy.mtproto.ClientConfig (*protocol.User)(nil), // 3: v2ray.core.common.protocol.User } var file_proxy_mtproto_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.proxy.mtproto.ServerConfig.user:type_name -> v2ray.core.common.protocol.User 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_proxy_mtproto_config_proto_init() } func file_proxy_mtproto_config_proto_init() { if File_proxy_mtproto_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_mtproto_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_mtproto_config_proto_msgTypes[1].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 } } file_proxy_mtproto_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 } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proxy_mtproto_config_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_mtproto_config_proto_goTypes, DependencyIndexes: file_proxy_mtproto_config_proto_depIdxs, MessageInfos: file_proxy_mtproto_config_proto_msgTypes, }.Build() File_proxy_mtproto_config_proto = out.File file_proxy_mtproto_config_proto_rawDesc = nil file_proxy_mtproto_config_proto_goTypes = nil file_proxy_mtproto_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/mtproto/auth_test.go
proxy/mtproto/auth_test.go
package mtproto_test import ( "bytes" "crypto/rand" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" . "v2ray.com/core/proxy/mtproto" ) func TestInverse(t *testing.T) { const size = 64 b := make([]byte, 64) for b[0] == b[size-1] { common.Must2(rand.Read(b)) } bi := Inverse(b) if b[0] == bi[0] { t.Fatal("seems bytes are not inversed: ", b[0], "vs", bi[0]) } bii := Inverse(bi) if r := cmp.Diff(bii, b); r != "" { t.Fatal(r) } } func TestAuthenticationReadWrite(t *testing.T) { a := NewAuthentication(DefaultSessionContext()) b := bytes.NewReader(a.Header[:]) a2, err := ReadAuthentication(b) common.Must(err) if r := cmp.Diff(a.EncodingKey[:], a2.DecodingKey[:]); r != "" { t.Error("decoding key: ", r) } if r := cmp.Diff(a.EncodingNonce[:], a2.DecodingNonce[:]); r != "" { t.Error("decoding nonce: ", r) } if r := cmp.Diff(a.DecodingKey[:], a2.EncodingKey[:]); r != "" { t.Error("encoding key: ", r) } if r := cmp.Diff(a.DecodingNonce[:], a2.EncodingNonce[:]); r != "" { t.Error("encoding nonce: ", r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/vmess.go
proxy/vmess/vmess.go
// Package vmess contains the implementation of VMess protocol and transportation. // // VMess contains both inbound and outbound connections. VMess inbound is usually used on servers // together with 'freedom' to talk to final destination, while VMess outbound is usually used on // clients with 'socks' for proxying. package vmess //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/errors.generated.go
proxy/vmess/errors.generated.go
package vmess import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/validator_test.go
proxy/vmess/validator_test.go
package vmess_test import ( "testing" "time" "v2ray.com/core/common" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/common/uuid" . "v2ray.com/core/proxy/vmess" ) func toAccount(a *Account) protocol.Account { account, err := a.AsAccount() common.Must(err) return account } func TestUserValidator(t *testing.T) { hasher := protocol.DefaultIDHash v := NewTimedUserValidator(hasher) defer common.Close(v) id := uuid.New() user := &protocol.MemoryUser{ Email: "test", Account: toAccount(&Account{ Id: id.String(), AlterId: 8, }), } common.Must(v.Add(user)) { testSmallLag := func(lag time.Duration) { ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix()) idHash := hasher(id.Bytes()) common.Must2(serial.WriteUint64(idHash, uint64(ts))) userHash := idHash.Sum(nil) euser, ets, found, _ := v.Get(userHash) if !found { t.Fatal("user not found") } if euser.Email != user.Email { t.Error("unexpected user email: ", euser.Email, " want ", user.Email) } if ets != ts { t.Error("unexpected timestamp: ", ets, " want ", ts) } } testSmallLag(0) testSmallLag(40) testSmallLag(-40) testSmallLag(80) testSmallLag(-80) testSmallLag(120) testSmallLag(-120) } { testBigLag := func(lag time.Duration) { ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix()) idHash := hasher(id.Bytes()) common.Must2(serial.WriteUint64(idHash, uint64(ts))) userHash := idHash.Sum(nil) euser, _, found, _ := v.Get(userHash) if found || euser != nil { t.Error("unexpected user") } } testBigLag(121) testBigLag(-121) testBigLag(310) testBigLag(-310) testBigLag(500) testBigLag(-500) } if v := v.Remove(user.Email); !v { t.Error("unable to remove user") } if v := v.Remove(user.Email); v { t.Error("remove user twice") } } func BenchmarkUserValidator(b *testing.B) { for i := 0; i < b.N; i++ { hasher := protocol.DefaultIDHash v := NewTimedUserValidator(hasher) for j := 0; j < 1500; j++ { id := uuid.New() v.Add(&protocol.MemoryUser{ Email: "test", Account: toAccount(&Account{ Id: id.String(), AlterId: 16, }), }) } common.Close(v) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/validator.go
proxy/vmess/validator.go
// +build !confonly package vmess import ( "crypto/hmac" "crypto/sha256" "hash" "hash/crc64" "strings" "sync" "sync/atomic" "time" "v2ray.com/core/common" "v2ray.com/core/common/dice" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/common/task" "v2ray.com/core/proxy/vmess/aead" ) const ( updateInterval = 10 * time.Second cacheDurationSec = 120 ) type user struct { user protocol.MemoryUser lastSec protocol.Timestamp } // TimedUserValidator is a user Validator based on time. type TimedUserValidator struct { sync.RWMutex users []*user userHash map[[16]byte]indexTimePair hasher protocol.IDHash baseTime protocol.Timestamp task *task.Periodic behaviorSeed uint64 behaviorFused bool aeadDecoderHolder *aead.AuthIDDecoderHolder } type indexTimePair struct { user *user timeInc uint32 taintedFuse *uint32 } // NewTimedUserValidator creates a new TimedUserValidator. func NewTimedUserValidator(hasher protocol.IDHash) *TimedUserValidator { tuv := &TimedUserValidator{ users: make([]*user, 0, 16), userHash: make(map[[16]byte]indexTimePair, 1024), hasher: hasher, baseTime: protocol.Timestamp(time.Now().Unix() - cacheDurationSec*2), aeadDecoderHolder: aead.NewAuthIDDecoderHolder(), } tuv.task = &task.Periodic{ Interval: updateInterval, Execute: func() error { tuv.updateUserHash() return nil }, } common.Must(tuv.task.Start()) return tuv } func (v *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, user *user) { var hashValue [16]byte genEndSec := nowSec + cacheDurationSec genHashForID := func(id *protocol.ID) { idHash := v.hasher(id.Bytes()) genBeginSec := user.lastSec if genBeginSec < nowSec-cacheDurationSec { genBeginSec = nowSec - cacheDurationSec } for ts := genBeginSec; ts <= genEndSec; ts++ { common.Must2(serial.WriteUint64(idHash, uint64(ts))) idHash.Sum(hashValue[:0]) idHash.Reset() v.userHash[hashValue] = indexTimePair{ user: user, timeInc: uint32(ts - v.baseTime), taintedFuse: new(uint32), } } } account := user.user.Account.(*MemoryAccount) genHashForID(account.ID) for _, id := range account.AlterIDs { genHashForID(id) } user.lastSec = genEndSec } func (v *TimedUserValidator) removeExpiredHashes(expire uint32) { for key, pair := range v.userHash { if pair.timeInc < expire { delete(v.userHash, key) } } } func (v *TimedUserValidator) updateUserHash() { now := time.Now() nowSec := protocol.Timestamp(now.Unix()) v.Lock() defer v.Unlock() for _, user := range v.users { v.generateNewHashes(nowSec, user) } expire := protocol.Timestamp(now.Unix() - cacheDurationSec) if expire > v.baseTime { v.removeExpiredHashes(uint32(expire - v.baseTime)) } } func (v *TimedUserValidator) Add(u *protocol.MemoryUser) error { v.Lock() defer v.Unlock() nowSec := time.Now().Unix() uu := &user{ user: *u, lastSec: protocol.Timestamp(nowSec - cacheDurationSec), } v.users = append(v.users, uu) v.generateNewHashes(protocol.Timestamp(nowSec), uu) account := uu.user.Account.(*MemoryAccount) if !v.behaviorFused { hashkdf := hmac.New(func() hash.Hash { return sha256.New() }, []byte("VMESSBSKDF")) hashkdf.Write(account.ID.Bytes()) v.behaviorSeed = crc64.Update(v.behaviorSeed, crc64.MakeTable(crc64.ECMA), hashkdf.Sum(nil)) } var cmdkeyfl [16]byte copy(cmdkeyfl[:], account.ID.CmdKey()) v.aeadDecoderHolder.AddUser(cmdkeyfl, u) return nil } func (v *TimedUserValidator) Get(userHash []byte) (*protocol.MemoryUser, protocol.Timestamp, bool, error) { defer v.RUnlock() v.RLock() v.behaviorFused = true var fixedSizeHash [16]byte copy(fixedSizeHash[:], userHash) pair, found := v.userHash[fixedSizeHash] if found { user := pair.user.user if atomic.LoadUint32(pair.taintedFuse) == 0 { return &user, protocol.Timestamp(pair.timeInc) + v.baseTime, true, nil } return nil, 0, false, ErrTainted } return nil, 0, false, ErrNotFound } func (v *TimedUserValidator) GetAEAD(userHash []byte) (*protocol.MemoryUser, bool, error) { defer v.RUnlock() v.RLock() var userHashFL [16]byte copy(userHashFL[:], userHash) userd, err := v.aeadDecoderHolder.Match(userHashFL) if err != nil { return nil, false, err } return userd.(*protocol.MemoryUser), true, err } func (v *TimedUserValidator) Remove(email string) bool { v.Lock() defer v.Unlock() idx := -1 for i := range v.users { if strings.EqualFold(v.users[i].user.Email, email) { idx = i var cmdkeyfl [16]byte copy(cmdkeyfl[:], v.users[i].user.Account.(*MemoryAccount).ID.CmdKey()) v.aeadDecoderHolder.RemoveUser(cmdkeyfl) break } } if idx == -1 { return false } ulen := len(v.users) v.users[idx] = v.users[ulen-1] v.users[ulen-1] = nil v.users = v.users[:ulen-1] return true } // Close implements common.Closable. func (v *TimedUserValidator) Close() error { return v.task.Close() } func (v *TimedUserValidator) GetBehaviorSeed() uint64 { v.Lock() defer v.Unlock() v.behaviorFused = true if v.behaviorSeed == 0 { v.behaviorSeed = dice.RollUint64() } return v.behaviorSeed } func (v *TimedUserValidator) BurnTaintFuse(userHash []byte) error { v.RLock() defer v.RUnlock() var userHashFL [16]byte copy(userHashFL[:], userHash) pair, found := v.userHash[userHashFL] if found { if atomic.CompareAndSwapUint32(pair.taintedFuse, 0, 1) { return nil } return ErrTainted } return ErrNotFound } var ErrNotFound = newError("Not Found") var ErrTainted = newError("ErrTainted")
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/vmessCtxInterface.go
proxy/vmess/vmessCtxInterface.go
package vmess // example const AlterID = "VMessCtxInterface_AlterID"
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/account.pb.go
proxy/vmess/account.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vmess/account.proto package vmess 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" protocol "v2ray.com/core/common/protocol" ) 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 // ID of the account, in the form of a UUID, e.g., // "66ad4540-b58c-4ad2-9926-ea63445a9b57". Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Number of alternative IDs. Client and server must share the same number. AlterId uint32 `protobuf:"varint,2,opt,name=alter_id,json=alterId,proto3" json:"alter_id,omitempty"` // Security settings. Only applies to client side. SecuritySettings *protocol.SecurityConfig `protobuf:"bytes,3,opt,name=security_settings,json=securitySettings,proto3" json:"security_settings,omitempty"` // Define tests enabled for this account TestsEnabled string `protobuf:"bytes,4,opt,name=tests_enabled,json=testsEnabled,proto3" json:"tests_enabled,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vmess_account_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_vmess_account_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_vmess_account_proto_rawDescGZIP(), []int{0} } func (x *Account) GetId() string { if x != nil { return x.Id } return "" } func (x *Account) GetAlterId() uint32 { if x != nil { return x.AlterId } return 0 } func (x *Account) GetSecuritySettings() *protocol.SecurityConfig { if x != nil { return x.SecuritySettings } return nil } func (x *Account) GetTestsEnabled() string { if x != nil { return x.TestsEnabled } return "" } var File_proxy_vmess_account_proto protoreflect.FileDescriptor var file_proxy_vmess_account_proto_rawDesc = []byte{ 0x0a, 0x19, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x16, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x1a, 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, 0x22, 0xb2, 0x01, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x57, 0x0a, 0x11, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x10, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x73, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x74, 0x65, 0x73, 0x74, 0x73, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x42, 0x53, 0x0a, 0x1a, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x50, 0x01, 0x5a, 0x1a, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0xaa, 0x02, 0x16, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6d, 0x65, 0x73, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vmess_account_proto_rawDescOnce sync.Once file_proxy_vmess_account_proto_rawDescData = file_proxy_vmess_account_proto_rawDesc ) func file_proxy_vmess_account_proto_rawDescGZIP() []byte { file_proxy_vmess_account_proto_rawDescOnce.Do(func() { file_proxy_vmess_account_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vmess_account_proto_rawDescData) }) return file_proxy_vmess_account_proto_rawDescData } var file_proxy_vmess_account_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_vmess_account_proto_goTypes = []interface{}{ (*Account)(nil), // 0: v2ray.core.proxy.vmess.Account (*protocol.SecurityConfig)(nil), // 1: v2ray.core.common.protocol.SecurityConfig } var file_proxy_vmess_account_proto_depIdxs = []int32{ 1, // 0: v2ray.core.proxy.vmess.Account.security_settings:type_name -> v2ray.core.common.protocol.SecurityConfig 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_proxy_vmess_account_proto_init() } func file_proxy_vmess_account_proto_init() { if File_proxy_vmess_account_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vmess_account_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 } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proxy_vmess_account_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vmess_account_proto_goTypes, DependencyIndexes: file_proxy_vmess_account_proto_depIdxs, MessageInfos: file_proxy_vmess_account_proto_msgTypes, }.Build() File_proxy_vmess_account_proto = out.File file_proxy_vmess_account_proto_rawDesc = nil file_proxy_vmess_account_proto_goTypes = nil file_proxy_vmess_account_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/account.go
proxy/vmess/account.go
// +build !confonly package vmess import ( "v2ray.com/core/common/dice" "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" ) // MemoryAccount is an in-memory form of VMess account. type MemoryAccount struct { // ID is the main ID of the account. ID *protocol.ID // AlterIDs are the alternative IDs of the account. AlterIDs []*protocol.ID // Security type of the account. Used for client connections. Security protocol.SecurityType } // AnyValidID returns an ID that is either the main ID or one of the alternative IDs if any. func (a *MemoryAccount) AnyValidID() *protocol.ID { if len(a.AlterIDs) == 0 { return a.ID } return a.AlterIDs[dice.Roll(len(a.AlterIDs))] } // Equals implements protocol.Account. func (a *MemoryAccount) Equals(account protocol.Account) bool { vmessAccount, ok := account.(*MemoryAccount) if !ok { return false } // TODO: handle AlterIds difference return a.ID.Equals(vmessAccount.ID) } // AsAccount implements protocol.Account. func (a *Account) AsAccount() (protocol.Account, error) { id, err := uuid.ParseString(a.Id) if err != nil { return nil, newError("failed to parse ID").Base(err).AtError() } protoID := protocol.NewID(id) return &MemoryAccount{ ID: protoID, AlterIDs: protocol.NewAlterIDs(protoID, uint16(a.AlterId)), Security: a.SecuritySettings.GetSecurityType(), }, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/commands.go
proxy/vmess/encoding/commands.go
package encoding import ( "encoding/binary" "io" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/common/uuid" ) var ( ErrCommandTypeMismatch = newError("Command type mismatch.") ErrUnknownCommand = newError("Unknown command.") ErrCommandTooLarge = newError("Command too large.") ) func MarshalCommand(command interface{}, writer io.Writer) error { if command == nil { return ErrUnknownCommand } var cmdID byte var factory CommandFactory switch command.(type) { case *protocol.CommandSwitchAccount: factory = new(CommandSwitchAccountFactory) cmdID = 1 default: return ErrUnknownCommand } buffer := buf.New() defer buffer.Release() err := factory.Marshal(command, buffer) if err != nil { return err } auth := Authenticate(buffer.Bytes()) length := buffer.Len() + 4 if length > 255 { return ErrCommandTooLarge } common.Must2(writer.Write([]byte{cmdID, byte(length), byte(auth >> 24), byte(auth >> 16), byte(auth >> 8), byte(auth)})) common.Must2(writer.Write(buffer.Bytes())) return nil } func UnmarshalCommand(cmdID byte, data []byte) (protocol.ResponseCommand, error) { if len(data) <= 4 { return nil, newError("insufficient length") } expectedAuth := Authenticate(data[4:]) actualAuth := binary.BigEndian.Uint32(data[:4]) if expectedAuth != actualAuth { return nil, newError("invalid auth") } var factory CommandFactory switch cmdID { case 1: factory = new(CommandSwitchAccountFactory) default: return nil, ErrUnknownCommand } return factory.Unmarshal(data[4:]) } type CommandFactory interface { Marshal(command interface{}, writer io.Writer) error Unmarshal(data []byte) (interface{}, error) } type CommandSwitchAccountFactory struct { } func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { cmd, ok := command.(*protocol.CommandSwitchAccount) if !ok { return ErrCommandTypeMismatch } hostStr := "" if cmd.Host != nil { hostStr = cmd.Host.String() } common.Must2(writer.Write([]byte{byte(len(hostStr))})) if len(hostStr) > 0 { common.Must2(writer.Write([]byte(hostStr))) } common.Must2(serial.WriteUint16(writer, cmd.Port.Value())) idBytes := cmd.ID.Bytes() common.Must2(writer.Write(idBytes)) common.Must2(serial.WriteUint16(writer, cmd.AlterIds)) common.Must2(writer.Write([]byte{byte(cmd.Level)})) common.Must2(writer.Write([]byte{cmd.ValidMin})) return nil } func (f *CommandSwitchAccountFactory) Unmarshal(data []byte) (interface{}, error) { cmd := new(protocol.CommandSwitchAccount) if len(data) == 0 { return nil, newError("insufficient length.") } lenHost := int(data[0]) if len(data) < lenHost+1 { return nil, newError("insufficient length.") } if lenHost > 0 { cmd.Host = net.ParseAddress(string(data[1 : 1+lenHost])) } portStart := 1 + lenHost if len(data) < portStart+2 { return nil, newError("insufficient length.") } cmd.Port = net.PortFromBytes(data[portStart : portStart+2]) idStart := portStart + 2 if len(data) < idStart+16 { return nil, newError("insufficient length.") } cmd.ID, _ = uuid.ParseBytes(data[idStart : idStart+16]) alterIDStart := idStart + 16 if len(data) < alterIDStart+2 { return nil, newError("insufficient length.") } cmd.AlterIds = binary.BigEndian.Uint16(data[alterIDStart : alterIDStart+2]) levelStart := alterIDStart + 2 if len(data) < levelStart+1 { return nil, newError("insufficient length.") } cmd.Level = uint32(data[levelStart]) timeStart := levelStart + 1 if len(data) < timeStart { return nil, newError("insufficient length.") } cmd.ValidMin = data[timeStart] return cmd, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/errors.generated.go
proxy/vmess/encoding/errors.generated.go
package encoding import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/client.go
proxy/vmess/encoding/client.go
package encoding import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/rand" "crypto/sha256" "encoding/binary" "hash" "hash/fnv" "io" "golang.org/x/crypto/chacha20poly1305" "v2ray.com/core/common" "v2ray.com/core/common/bitmask" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/dice" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/proxy/vmess" vmessaead "v2ray.com/core/proxy/vmess/aead" ) func hashTimestamp(h hash.Hash, t protocol.Timestamp) []byte { common.Must2(serial.WriteUint64(h, uint64(t))) common.Must2(serial.WriteUint64(h, uint64(t))) common.Must2(serial.WriteUint64(h, uint64(t))) common.Must2(serial.WriteUint64(h, uint64(t))) return h.Sum(nil) } // ClientSession stores connection session info for VMess client. type ClientSession struct { isAEAD bool idHash protocol.IDHash requestBodyKey [16]byte requestBodyIV [16]byte responseBodyKey [16]byte responseBodyIV [16]byte responseReader io.Reader responseHeader byte } // NewClientSession creates a new ClientSession. func NewClientSession(isAEAD bool, idHash protocol.IDHash, ctx context.Context) *ClientSession { session := &ClientSession{ isAEAD: isAEAD, idHash: idHash, } randomBytes := make([]byte, 33) // 16 + 16 + 1 common.Must2(rand.Read(randomBytes)) copy(session.requestBodyKey[:], randomBytes[:16]) copy(session.requestBodyIV[:], randomBytes[16:32]) session.responseHeader = randomBytes[32] if !session.isAEAD { session.responseBodyKey = md5.Sum(session.requestBodyKey[:]) session.responseBodyIV = md5.Sum(session.requestBodyIV[:]) } else { BodyKey := sha256.Sum256(session.requestBodyKey[:]) copy(session.responseBodyKey[:], BodyKey[:16]) BodyIV := sha256.Sum256(session.requestBodyIV[:]) copy(session.responseBodyIV[:], BodyIV[:16]) } return session } func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) error { timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)() account := header.User.Account.(*vmess.MemoryAccount) if !c.isAEAD { idHash := c.idHash(account.AnyValidID().Bytes()) common.Must2(serial.WriteUint64(idHash, uint64(timestamp))) common.Must2(writer.Write(idHash.Sum(nil))) } buffer := buf.New() defer buffer.Release() common.Must(buffer.WriteByte(Version)) common.Must2(buffer.Write(c.requestBodyIV[:])) common.Must2(buffer.Write(c.requestBodyKey[:])) common.Must(buffer.WriteByte(c.responseHeader)) common.Must(buffer.WriteByte(byte(header.Option))) padingLen := dice.Roll(16) security := byte(padingLen<<4) | byte(header.Security) common.Must2(buffer.Write([]byte{security, byte(0), byte(header.Command)})) if header.Command != protocol.RequestCommandMux { if err := addrParser.WriteAddressPort(buffer, header.Address, header.Port); err != nil { return newError("failed to writer address and port").Base(err) } } if padingLen > 0 { common.Must2(buffer.ReadFullFrom(rand.Reader, int32(padingLen))) } { fnv1a := fnv.New32a() common.Must2(fnv1a.Write(buffer.Bytes())) hashBytes := buffer.Extend(int32(fnv1a.Size())) fnv1a.Sum(hashBytes[:0]) } if !c.isAEAD { iv := hashTimestamp(md5.New(), timestamp) aesStream := crypto.NewAesEncryptionStream(account.ID.CmdKey(), iv[:]) aesStream.XORKeyStream(buffer.Bytes(), buffer.Bytes()) common.Must2(writer.Write(buffer.Bytes())) } else { var fixedLengthCmdKey [16]byte copy(fixedLengthCmdKey[:], account.ID.CmdKey()) vmessout := vmessaead.SealVMessAEADHeader(fixedLengthCmdKey, buffer.Bytes()) common.Must2(io.Copy(writer, bytes.NewReader(vmessout))) } return nil } func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer { var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{} if request.Option.Has(protocol.RequestOptionChunkMasking) { sizeParser = NewShakeSizeParser(c.requestBodyIV[:]) } var padding crypto.PaddingLengthGenerator if request.Option.Has(protocol.RequestOptionGlobalPadding) { padding = sizeParser.(crypto.PaddingLengthGenerator) } switch request.Security { case protocol.SecurityType_NONE: if request.Option.Has(protocol.RequestOptionChunkStream) { if request.Command.TransferType() == protocol.TransferTypeStream { return crypto.NewChunkStreamWriter(sizeParser, writer) } auth := &crypto.AEADAuthenticator{ AEAD: new(NoOpAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding) } return buf.NewWriter(writer) case protocol.SecurityType_LEGACY: aesStream := crypto.NewAesEncryptionStream(c.requestBodyKey[:], c.requestBodyIV[:]) cryptionWriter := crypto.NewCryptionWriter(aesStream, writer) if request.Option.Has(protocol.RequestOptionChunkStream) { auth := &crypto.AEADAuthenticator{ AEAD: new(FnvAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, cryptionWriter, request.Command.TransferType(), padding) } return &buf.SequentialWriter{Writer: cryptionWriter} case protocol.SecurityType_AES128_GCM: aead := crypto.NewAesGcm(c.requestBodyKey[:]) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding) case protocol.SecurityType_CHACHA20_POLY1305: aead, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.requestBodyKey[:])) common.Must(err) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding) default: panic("Unknown security type.") } } func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) { if !c.isAEAD { aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:]) c.responseReader = crypto.NewCryptionReader(aesStream, reader) } else { aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderLenKey) aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderLenIV)[:12] aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block) aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD) var aeadEncryptedResponseHeaderLength [18]byte var decryptedResponseHeaderLength int var decryptedResponseHeaderLengthBinaryDeserializeBuffer uint16 if _, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil { return nil, newError("Unable to Read Header Len").Base(err) } if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil { return nil, newError("Failed To Decrypt Length").Base(err) } else { common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer)) decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer) } aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadKey) aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadIV)[:12] aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block) aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD) encryptedResponseHeaderBuffer := make([]byte, decryptedResponseHeaderLength+16) if _, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil { return nil, newError("Unable to Read Header Data").Base(err) } if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil { return nil, newError("Failed To Decrypt Payload").Base(err) } else { c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer) } } buffer := buf.StackNew() defer buffer.Release() if _, err := buffer.ReadFullFrom(c.responseReader, 4); err != nil { return nil, newError("failed to read response header").Base(err).AtWarning() } if buffer.Byte(0) != c.responseHeader { return nil, newError("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0))) } header := &protocol.ResponseHeader{ Option: bitmask.Byte(buffer.Byte(1)), } if buffer.Byte(2) != 0 { cmdID := buffer.Byte(2) dataLen := int32(buffer.Byte(3)) buffer.Clear() if _, err := buffer.ReadFullFrom(c.responseReader, dataLen); err != nil { return nil, newError("failed to read response command").Base(err) } command, err := UnmarshalCommand(cmdID, buffer.Bytes()) if err == nil { header.Command = command } } if c.isAEAD { aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:]) c.responseReader = crypto.NewCryptionReader(aesStream, reader) } return header, nil } func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader { var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{} if request.Option.Has(protocol.RequestOptionChunkMasking) { sizeParser = NewShakeSizeParser(c.responseBodyIV[:]) } var padding crypto.PaddingLengthGenerator if request.Option.Has(protocol.RequestOptionGlobalPadding) { padding = sizeParser.(crypto.PaddingLengthGenerator) } switch request.Security { case protocol.SecurityType_NONE: if request.Option.Has(protocol.RequestOptionChunkStream) { if request.Command.TransferType() == protocol.TransferTypeStream { return crypto.NewChunkStreamReader(sizeParser, reader) } auth := &crypto.AEADAuthenticator{ AEAD: new(NoOpAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding) } return buf.NewReader(reader) case protocol.SecurityType_LEGACY: if request.Option.Has(protocol.RequestOptionChunkStream) { auth := &crypto.AEADAuthenticator{ AEAD: new(FnvAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, c.responseReader, request.Command.TransferType(), padding) } return buf.NewReader(c.responseReader) case protocol.SecurityType_AES128_GCM: aead := crypto.NewAesGcm(c.responseBodyKey[:]) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding) case protocol.SecurityType_CHACHA20_POLY1305: aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.responseBodyKey[:])) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding) default: panic("Unknown security type.") } } func GenerateChunkNonce(nonce []byte, size uint32) crypto.BytesGenerator { c := append([]byte(nil), nonce...) count := uint16(0) return func() []byte { binary.BigEndian.PutUint16(c, count) count++ return c[:size] } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/commands_test.go
proxy/vmess/encoding/commands_test.go
package encoding_test import ( "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" . "v2ray.com/core/proxy/vmess/encoding" ) func TestSwitchAccount(t *testing.T) { sa := &protocol.CommandSwitchAccount{ Port: 1234, ID: uuid.New(), AlterIds: 1024, Level: 128, ValidMin: 16, } buffer := buf.New() common.Must(MarshalCommand(sa, buffer)) cmd, err := UnmarshalCommand(1, buffer.BytesFrom(2)) common.Must(err) sa2, ok := cmd.(*protocol.CommandSwitchAccount) if !ok { t.Fatal("failed to convert command to CommandSwitchAccount") } if r := cmp.Diff(sa2, sa); r != "" { t.Error(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/server.go
proxy/vmess/encoding/server.go
package encoding import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/sha256" "encoding/binary" "hash/fnv" "io" "io/ioutil" "sync" "time" "golang.org/x/crypto/chacha20poly1305" "v2ray.com/core/common" "v2ray.com/core/common/bitmask" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/dice" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/task" "v2ray.com/core/proxy/vmess" vmessaead "v2ray.com/core/proxy/vmess/aead" ) type sessionId struct { user [16]byte key [16]byte nonce [16]byte } // SessionHistory keeps track of historical session ids, to prevent replay attacks. type SessionHistory struct { sync.RWMutex cache map[sessionId]time.Time task *task.Periodic } // NewSessionHistory creates a new SessionHistory object. func NewSessionHistory() *SessionHistory { h := &SessionHistory{ cache: make(map[sessionId]time.Time, 128), } h.task = &task.Periodic{ Interval: time.Second * 30, Execute: h.removeExpiredEntries, } return h } // Close implements common.Closable. func (h *SessionHistory) Close() error { return h.task.Close() } func (h *SessionHistory) addIfNotExits(session sessionId) bool { h.Lock() if expire, found := h.cache[session]; found && expire.After(time.Now()) { h.Unlock() return false } h.cache[session] = time.Now().Add(time.Minute * 3) h.Unlock() common.Must(h.task.Start()) return true } func (h *SessionHistory) removeExpiredEntries() error { now := time.Now() h.Lock() defer h.Unlock() if len(h.cache) == 0 { return newError("nothing to do") } for session, expire := range h.cache { if expire.Before(now) { delete(h.cache, session) } } if len(h.cache) == 0 { h.cache = make(map[sessionId]time.Time, 128) } return nil } // ServerSession keeps information for a session in VMess server. type ServerSession struct { userValidator *vmess.TimedUserValidator sessionHistory *SessionHistory requestBodyKey [16]byte requestBodyIV [16]byte responseBodyKey [16]byte responseBodyIV [16]byte responseWriter io.Writer responseHeader byte isAEADRequest bool isAEADForced bool } // NewServerSession creates a new ServerSession, using the given UserValidator. // The ServerSession instance doesn't take ownership of the validator. func NewServerSession(validator *vmess.TimedUserValidator, sessionHistory *SessionHistory) *ServerSession { return &ServerSession{ userValidator: validator, sessionHistory: sessionHistory, } } func parseSecurityType(b byte) protocol.SecurityType { if _, f := protocol.SecurityType_name[int32(b)]; f { st := protocol.SecurityType(b) // For backward compatibility. if st == protocol.SecurityType_UNKNOWN { st = protocol.SecurityType_LEGACY } return st } return protocol.SecurityType_UNKNOWN } // DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream. func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) { buffer := buf.New() behaviorRand := dice.NewDeterministicDice(int64(s.userValidator.GetBehaviorSeed())) BaseDrainSize := behaviorRand.Roll(3266) RandDrainMax := behaviorRand.Roll(64) + 1 RandDrainRolled := dice.Roll(RandDrainMax) DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled readSizeRemain := DrainSize drainConnection := func(e error) error { //We read a deterministic generated length of data before closing the connection to offset padding read pattern readSizeRemain -= int(buffer.Len()) if readSizeRemain > 0 { err := s.DrainConnN(reader, readSizeRemain) if err != nil { return newError("failed to drain connection DrainSize = ", BaseDrainSize, " ", RandDrainMax, " ", RandDrainRolled).Base(err).Base(e) } return newError("connection drained DrainSize = ", BaseDrainSize, " ", RandDrainMax, " ", RandDrainRolled).Base(e) } return e } defer func() { buffer.Release() }() if _, err := buffer.ReadFullFrom(reader, protocol.IDBytesLen); err != nil { return nil, newError("failed to read request header").Base(err) } var decryptor io.Reader var vmessAccount *vmess.MemoryAccount user, foundAEAD, errorAEAD := s.userValidator.GetAEAD(buffer.Bytes()) var fixedSizeAuthID [16]byte copy(fixedSizeAuthID[:], buffer.Bytes()) if foundAEAD { vmessAccount = user.Account.(*vmess.MemoryAccount) var fixedSizeCmdKey [16]byte copy(fixedSizeCmdKey[:], vmessAccount.ID.CmdKey()) aeadData, shouldDrain, errorReason, bytesRead := vmessaead.OpenVMessAEADHeader(fixedSizeCmdKey, fixedSizeAuthID, reader) if errorReason != nil { if shouldDrain { readSizeRemain -= bytesRead return nil, drainConnection(newError("AEAD read failed").Base(errorReason)) } else { return nil, drainConnection(newError("AEAD read failed, drain skiped").Base(errorReason)) } } decryptor = bytes.NewReader(aeadData) s.isAEADRequest = true } else if !s.isAEADForced && errorAEAD == vmessaead.ErrNotFound { userLegacy, timestamp, valid, userValidationError := s.userValidator.Get(buffer.Bytes()) if !valid || userValidationError != nil { return nil, drainConnection(newError("invalid user").Base(userValidationError)) } user = userLegacy iv := hashTimestamp(md5.New(), timestamp) vmessAccount = userLegacy.Account.(*vmess.MemoryAccount) aesStream := crypto.NewAesDecryptionStream(vmessAccount.ID.CmdKey(), iv[:]) decryptor = crypto.NewCryptionReader(aesStream, reader) } else { return nil, drainConnection(newError("invalid user").Base(errorAEAD)) } readSizeRemain -= int(buffer.Len()) buffer.Clear() if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil { return nil, newError("failed to read request header").Base(err) } request := &protocol.RequestHeader{ User: user, Version: buffer.Byte(0), } copy(s.requestBodyIV[:], buffer.BytesRange(1, 17)) // 16 bytes copy(s.requestBodyKey[:], buffer.BytesRange(17, 33)) // 16 bytes var sid sessionId copy(sid.user[:], vmessAccount.ID.Bytes()) sid.key = s.requestBodyKey sid.nonce = s.requestBodyIV if !s.sessionHistory.addIfNotExits(sid) { if !s.isAEADRequest { drainErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:]) if drainErr != nil { return nil, drainConnection(newError("duplicated session id, possibly under replay attack, and failed to taint userHash").Base(drainErr)) } return nil, drainConnection(newError("duplicated session id, possibly under replay attack, userHash tainted")) } else { return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request") } } s.responseHeader = buffer.Byte(33) // 1 byte request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte padingLen := int(buffer.Byte(35) >> 4) request.Security = parseSecurityType(buffer.Byte(35) & 0x0F) // 1 bytes reserved request.Command = protocol.RequestCommand(buffer.Byte(37)) switch request.Command { case protocol.RequestCommandMux: request.Address = net.DomainAddress("v1.mux.cool") request.Port = 0 case protocol.RequestCommandTCP, protocol.RequestCommandUDP: if addr, port, err := addrParser.ReadAddressPort(buffer, decryptor); err == nil { request.Address = addr request.Port = port } } if padingLen > 0 { if _, err := buffer.ReadFullFrom(decryptor, int32(padingLen)); err != nil { if !s.isAEADRequest { burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:]) if burnErr != nil { return nil, newError("failed to read padding, failed to taint userHash").Base(burnErr).Base(err) } return nil, newError("failed to read padding, userHash tainted").Base(err) } return nil, newError("failed to read padding").Base(err) } } if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil { if !s.isAEADRequest { burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:]) if burnErr != nil { return nil, newError("failed to read checksum, failed to taint userHash").Base(burnErr).Base(err) } return nil, newError("failed to read checksum, userHash tainted").Base(err) } return nil, newError("failed to read checksum").Base(err) } fnv1a := fnv.New32a() common.Must2(fnv1a.Write(buffer.BytesTo(-4))) actualHash := fnv1a.Sum32() expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4)) if actualHash != expectedHash { if !s.isAEADRequest { Autherr := newError("invalid auth, legacy userHash tainted") burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:]) if burnErr != nil { Autherr = newError("invalid auth, can't taint legacy userHash").Base(burnErr) } //It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523 return nil, drainConnection(Autherr) } else { return nil, newError("invalid auth, but this is a AEAD request") } } if request.Address == nil { return nil, newError("invalid remote address") } if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO { return nil, newError("unknown security type: ", request.Security) } return request, nil } // DecodeRequestBody returns Reader from which caller can fetch decrypted body. func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader { var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{} if request.Option.Has(protocol.RequestOptionChunkMasking) { sizeParser = NewShakeSizeParser(s.requestBodyIV[:]) } var padding crypto.PaddingLengthGenerator if request.Option.Has(protocol.RequestOptionGlobalPadding) { padding = sizeParser.(crypto.PaddingLengthGenerator) } switch request.Security { case protocol.SecurityType_NONE: if request.Option.Has(protocol.RequestOptionChunkStream) { if request.Command.TransferType() == protocol.TransferTypeStream { return crypto.NewChunkStreamReader(sizeParser, reader) } auth := &crypto.AEADAuthenticator{ AEAD: new(NoOpAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding) } return buf.NewReader(reader) case protocol.SecurityType_LEGACY: aesStream := crypto.NewAesDecryptionStream(s.requestBodyKey[:], s.requestBodyIV[:]) cryptionReader := crypto.NewCryptionReader(aesStream, reader) if request.Option.Has(protocol.RequestOptionChunkStream) { auth := &crypto.AEADAuthenticator{ AEAD: new(FnvAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, cryptionReader, request.Command.TransferType(), padding) } return buf.NewReader(cryptionReader) case protocol.SecurityType_AES128_GCM: aead := crypto.NewAesGcm(s.requestBodyKey[:]) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding) case protocol.SecurityType_CHACHA20_POLY1305: aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey[:])) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding) default: panic("Unknown security type.") } } // EncodeResponseHeader writes encoded response header into the given writer. func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) { var encryptionWriter io.Writer if !s.isAEADRequest { s.responseBodyKey = md5.Sum(s.requestBodyKey[:]) s.responseBodyIV = md5.Sum(s.requestBodyIV[:]) } else { BodyKey := sha256.Sum256(s.requestBodyKey[:]) copy(s.responseBodyKey[:], BodyKey[:16]) BodyIV := sha256.Sum256(s.requestBodyIV[:]) copy(s.responseBodyIV[:], BodyIV[:16]) } aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey[:], s.responseBodyIV[:]) encryptionWriter = crypto.NewCryptionWriter(aesStream, writer) s.responseWriter = encryptionWriter aeadEncryptedHeaderBuffer := bytes.NewBuffer(nil) if s.isAEADRequest { encryptionWriter = aeadEncryptedHeaderBuffer } common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)})) err := MarshalCommand(header.Command, encryptionWriter) if err != nil { common.Must2(encryptionWriter.Write([]byte{0x00, 0x00})) } if s.isAEADRequest { aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderLenKey) aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderLenIV)[:12] aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block) aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD) aeadResponseHeaderLengthEncryptionBuffer := bytes.NewBuffer(nil) decryptedResponseHeaderLengthBinaryDeserializeBuffer := uint16(aeadEncryptedHeaderBuffer.Len()) common.Must(binary.Write(aeadResponseHeaderLengthEncryptionBuffer, binary.BigEndian, decryptedResponseHeaderLengthBinaryDeserializeBuffer)) AEADEncryptedLength := aeadResponseHeaderLengthEncryptionAEAD.Seal(nil, aeadResponseHeaderLengthEncryptionIV, aeadResponseHeaderLengthEncryptionBuffer.Bytes(), nil) common.Must2(io.Copy(writer, bytes.NewReader(AEADEncryptedLength))) aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadKey) aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadIV)[:12] aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block) aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD) aeadEncryptedHeaderPayload := aeadResponseHeaderPayloadEncryptionAEAD.Seal(nil, aeadResponseHeaderPayloadEncryptionIV, aeadEncryptedHeaderBuffer.Bytes(), nil) common.Must2(io.Copy(writer, bytes.NewReader(aeadEncryptedHeaderPayload))) } } // EncodeResponseBody returns a Writer that auto-encrypt content written by caller. func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer { var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{} if request.Option.Has(protocol.RequestOptionChunkMasking) { sizeParser = NewShakeSizeParser(s.responseBodyIV[:]) } var padding crypto.PaddingLengthGenerator if request.Option.Has(protocol.RequestOptionGlobalPadding) { padding = sizeParser.(crypto.PaddingLengthGenerator) } switch request.Security { case protocol.SecurityType_NONE: if request.Option.Has(protocol.RequestOptionChunkStream) { if request.Command.TransferType() == protocol.TransferTypeStream { return crypto.NewChunkStreamWriter(sizeParser, writer) } auth := &crypto.AEADAuthenticator{ AEAD: new(NoOpAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding) } return buf.NewWriter(writer) case protocol.SecurityType_LEGACY: if request.Option.Has(protocol.RequestOptionChunkStream) { auth := &crypto.AEADAuthenticator{ AEAD: new(FnvAuthenticator), NonceGenerator: crypto.GenerateEmptyBytes(), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, s.responseWriter, request.Command.TransferType(), padding) } return &buf.SequentialWriter{Writer: s.responseWriter} case protocol.SecurityType_AES128_GCM: aead := crypto.NewAesGcm(s.responseBodyKey[:]) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding) case protocol.SecurityType_CHACHA20_POLY1305: aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey[:])) auth := &crypto.AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())), AdditionalDataGenerator: crypto.GenerateEmptyBytes(), } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding) default: panic("Unknown security type.") } } func (s *ServerSession) DrainConnN(reader io.Reader, n int) error { _, err := io.CopyN(ioutil.Discard, reader, int64(n)) return err }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/encoding_test.go
proxy/vmess/encoding/encoding_test.go
package encoding_test import ( "context" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/uuid" "v2ray.com/core/proxy/vmess" . "v2ray.com/core/proxy/vmess/encoding" ) func toAccount(a *vmess.Account) protocol.Account { account, err := a.AsAccount() common.Must(err) return account } func TestRequestSerialization(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2ray.com", } id := uuid.New() account := &vmess.Account{ Id: id.String(), AlterId: 0, } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: 1, User: user, Command: protocol.RequestCommandTCP, Address: net.DomainAddress("www.v2ray.com"), Port: net.Port(443), Security: protocol.SecurityType_AES128_GCM, } buffer := buf.New() client := NewClientSession(true, protocol.DefaultIDHash, context.TODO()) common.Must(client.EncodeRequestHeader(expectedRequest, buffer)) buffer2 := buf.New() buffer2.Write(buffer.Bytes()) sessionHistory := NewSessionHistory() defer common.Close(sessionHistory) userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash) userValidator.Add(user) defer common.Close(userValidator) server := NewServerSession(userValidator, sessionHistory) actualRequest, err := server.DecodeRequestHeader(buffer) common.Must(err) if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" { t.Error(r) } _, err = server.DecodeRequestHeader(buffer2) // anti replay attack if err == nil { t.Error("nil error") } } func TestInvalidRequest(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2ray.com", } id := uuid.New() account := &vmess.Account{ Id: id.String(), AlterId: 0, } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: 1, User: user, Command: protocol.RequestCommand(100), Address: net.DomainAddress("www.v2ray.com"), Port: net.Port(443), Security: protocol.SecurityType_AES128_GCM, } buffer := buf.New() client := NewClientSession(true, protocol.DefaultIDHash, context.TODO()) common.Must(client.EncodeRequestHeader(expectedRequest, buffer)) buffer2 := buf.New() buffer2.Write(buffer.Bytes()) sessionHistory := NewSessionHistory() defer common.Close(sessionHistory) userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash) userValidator.Add(user) defer common.Close(userValidator) server := NewServerSession(userValidator, sessionHistory) _, err := server.DecodeRequestHeader(buffer) if err == nil { t.Error("nil error") } } func TestMuxRequest(t *testing.T) { user := &protocol.MemoryUser{ Level: 0, Email: "test@v2ray.com", } id := uuid.New() account := &vmess.Account{ Id: id.String(), AlterId: 0, } user.Account = toAccount(account) expectedRequest := &protocol.RequestHeader{ Version: 1, User: user, Command: protocol.RequestCommandMux, Security: protocol.SecurityType_AES128_GCM, Address: net.DomainAddress("v1.mux.cool"), } buffer := buf.New() client := NewClientSession(true, protocol.DefaultIDHash, context.TODO()) common.Must(client.EncodeRequestHeader(expectedRequest, buffer)) buffer2 := buf.New() buffer2.Write(buffer.Bytes()) sessionHistory := NewSessionHistory() defer common.Close(sessionHistory) userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash) userValidator.Add(user) defer common.Close(userValidator) server := NewServerSession(userValidator, sessionHistory) actualRequest, err := server.DecodeRequestHeader(buffer) common.Must(err) if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" { t.Error(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/auth.go
proxy/vmess/encoding/auth.go
package encoding import ( "crypto/md5" "encoding/binary" "hash/fnv" "v2ray.com/core/common" "golang.org/x/crypto/sha3" ) // Authenticate authenticates a byte array using Fnv hash. func Authenticate(b []byte) uint32 { fnv1hash := fnv.New32a() common.Must2(fnv1hash.Write(b)) return fnv1hash.Sum32() } type NoOpAuthenticator struct{} func (NoOpAuthenticator) NonceSize() int { return 0 } func (NoOpAuthenticator) Overhead() int { return 0 } // Seal implements AEAD.Seal(). func (NoOpAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte { return append(dst[:0], plaintext...) } // Open implements AEAD.Open(). func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { return append(dst[:0], ciphertext...), nil } // FnvAuthenticator is an AEAD based on Fnv hash. type FnvAuthenticator struct { } // NonceSize implements AEAD.NonceSize(). func (*FnvAuthenticator) NonceSize() int { return 0 } // Overhead impelements AEAD.Overhead(). func (*FnvAuthenticator) Overhead() int { return 4 } // Seal implements AEAD.Seal(). func (*FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte { dst = append(dst, 0, 0, 0, 0) binary.BigEndian.PutUint32(dst, Authenticate(plaintext)) return append(dst, plaintext...) } // Open implements AEAD.Open(). func (*FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { if binary.BigEndian.Uint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) { return dst, newError("invalid authentication") } return append(dst, ciphertext[4:]...), nil } // GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array. func GenerateChacha20Poly1305Key(b []byte) []byte { key := make([]byte, 32) t := md5.Sum(b) copy(key, t[:]) t = md5.Sum(key[:16]) copy(key[16:], t[:]) return key } type ShakeSizeParser struct { shake sha3.ShakeHash buffer [2]byte } func NewShakeSizeParser(nonce []byte) *ShakeSizeParser { shake := sha3.NewShake128() common.Must2(shake.Write(nonce)) return &ShakeSizeParser{ shake: shake, } } func (*ShakeSizeParser) SizeBytes() int32 { return 2 } func (s *ShakeSizeParser) next() uint16 { common.Must2(s.shake.Read(s.buffer[:])) return binary.BigEndian.Uint16(s.buffer[:]) } func (s *ShakeSizeParser) Decode(b []byte) (uint16, error) { mask := s.next() size := binary.BigEndian.Uint16(b) return mask ^ size, nil } func (s *ShakeSizeParser) Encode(size uint16, b []byte) []byte { mask := s.next() binary.BigEndian.PutUint16(b, mask^size) return b[:2] } func (s *ShakeSizeParser) NextPaddingLen() uint16 { return s.next() % 64 } func (s *ShakeSizeParser) MaxPaddingLen() uint16 { return 64 }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/encoding.go
proxy/vmess/encoding/encoding.go
package encoding import ( "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" ) //go:generate go run v2ray.com/core/common/errors/errorgen const ( Version = byte(1) ) var addrParser = protocol.NewAddressParser( protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4), protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain), protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6), protocol.PortThenAddress(), )
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/encoding/auth_test.go
proxy/vmess/encoding/auth_test.go
package encoding_test import ( "crypto/rand" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" . "v2ray.com/core/proxy/vmess/encoding" ) func TestFnvAuth(t *testing.T) { fnvAuth := new(FnvAuthenticator) expectedText := make([]byte, 256) _, err := rand.Read(expectedText) common.Must(err) buffer := make([]byte, 512) b := fnvAuth.Seal(buffer[:0], nil, expectedText, nil) b, err = fnvAuth.Open(buffer[:0], nil, b, nil) common.Must(err) if r := cmp.Diff(b, expectedText); r != "" { t.Error(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/outbound/errors.generated.go
proxy/vmess/outbound/errors.generated.go
package outbound import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/outbound/config.go
proxy/vmess/outbound/config.go
package outbound
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/outbound/outbound.go
proxy/vmess/outbound/outbound.go
// +build !confonly package outbound //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/platform" "v2ray.com/core/common/protocol" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/proxy/vmess" "v2ray.com/core/proxy/vmess/encoding" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" ) // Handler is an outbound connection handler for VMess protocol. type Handler struct { serverList *protocol.ServerList serverPicker protocol.ServerPicker policyManager policy.Manager } // New creates a new VMess outbound handler. func New(ctx context.Context, config *Config) (*Handler, error) { serverList := protocol.NewServerList() for _, rec := range config.Receiver { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { return nil, newError("failed to parse server spec").Base(err) } serverList.AddServer(s) } v := core.MustFromContext(ctx) handler := &Handler{ serverList: serverList, serverPicker: protocol.NewRoundRobinServerPicker(serverList), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), } return handler, nil } // Process implements proxy.Outbound.Process(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { var rec *protocol.ServerSpec var conn internet.Connection err := retry.ExponentialBackoff(5, 200).On(func() error { rec = h.serverPicker.PickServer() rawConn, err := dialer.Dial(ctx, rec.Destination()) if err != nil { return err } conn = rawConn return nil }) if err != nil { return newError("failed to find an available destination").Base(err).AtWarning() } defer conn.Close() //nolint: errcheck outbound := session.OutboundFromContext(ctx) if outbound == nil || !outbound.Target.IsValid() { return newError("target not specified").AtError() } target := outbound.Target newError("tunneling request to ", target, " via ", rec.Destination()).WriteToLog(session.ExportIDToError(ctx)) command := protocol.RequestCommandTCP if target.Network == net.Network_UDP { command = protocol.RequestCommandUDP } if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" { command = protocol.RequestCommandMux } user := rec.PickUser() request := &protocol.RequestHeader{ Version: encoding.Version, User: user, Command: command, Address: target.Address, Port: target.Port, Option: protocol.RequestOptionChunkStream, } account := request.User.Account.(*vmess.MemoryAccount) request.Security = account.Security if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_NONE || request.Security == protocol.SecurityType_CHACHA20_POLY1305 { request.Option.Set(protocol.RequestOptionChunkMasking) } if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) { request.Option.Set(protocol.RequestOptionGlobalPadding) } input := link.Reader output := link.Writer isAEAD := false if !aead_disabled && len(account.AlterIDs) == 0 { isAEAD = true } session := encoding.NewClientSession(isAEAD, protocol.DefaultIDHash, ctx) sessionPolicy := h.policyManager.ForLevel(request.User.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) writer := buf.NewBufferedWriter(buf.NewWriter(conn)) if err := session.EncodeRequestHeader(request, writer); err != nil { return newError("failed to encode request").Base(err).AtWarning() } bodyWriter := session.EncodeRequestBody(request, writer) if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { return newError("failed to write first payload").Base(err) } if err := writer.SetBuffered(false); err != nil { return err } if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil { return err } if request.Option.Has(protocol.RequestOptionChunkStream) { if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil { return err } } return nil } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) reader := &buf.BufferedReader{Reader: buf.NewReader(conn)} header, err := session.DecodeResponseHeader(reader) if err != nil { return newError("failed to read header").Base(err) } h.handleCommand(rec.Destination(), header.Command) bodyReader := session.DecodeResponseBody(request, reader) return buf.Copy(bodyReader, output, buf.UpdateActivity(timer)) } var responseDonePost = task.OnSuccess(responseDone, task.Close(output)) if err := task.Run(ctx, requestDone, responseDonePost); err != nil { return newError("connection ends").Base(err) } return nil } var ( enablePadding = false aead_disabled = false ) func shouldEnablePadding(s protocol.SecurityType) bool { return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) const defaultFlagValue = "NOT_DEFINED_AT_ALL" paddingValue := platform.NewEnvFlag("v2ray.vmess.padding").GetValue(func() string { return defaultFlagValue }) if paddingValue != defaultFlagValue { enablePadding = true } aeadDisabled := platform.NewEnvFlag("v2ray.vmess.aead.disabled").GetValue(func() string { return defaultFlagValue }) if aeadDisabled == "true" { aead_disabled = true } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/outbound/config.pb.go
proxy/vmess/outbound/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vmess/outbound/config.proto package outbound 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" protocol "v2ray.com/core/common/protocol" ) 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 Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Receiver []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=Receiver,proto3" json:"Receiver,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vmess_outbound_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_outbound_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_vmess_outbound_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetReceiver() []*protocol.ServerEndpoint { if x != nil { return x.Receiver } return nil } var File_proxy_vmess_outbound_config_proto protoreflect.FileDescriptor var file_proxy_vmess_outbound_config_proto_rawDesc = []byte{ 0x0a, 0x21, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 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, 0x50, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x46, 0x0a, 0x08, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x08, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x42, 0x6e, 0x0a, 0x23, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x50, 0x01, 0x5a, 0x23, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0xaa, 0x02, 0x1f, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vmess_outbound_config_proto_rawDescOnce sync.Once file_proxy_vmess_outbound_config_proto_rawDescData = file_proxy_vmess_outbound_config_proto_rawDesc ) func file_proxy_vmess_outbound_config_proto_rawDescGZIP() []byte { file_proxy_vmess_outbound_config_proto_rawDescOnce.Do(func() { file_proxy_vmess_outbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vmess_outbound_config_proto_rawDescData) }) return file_proxy_vmess_outbound_config_proto_rawDescData } var file_proxy_vmess_outbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_proxy_vmess_outbound_config_proto_goTypes = []interface{}{ (*Config)(nil), // 0: v2ray.core.proxy.vmess.outbound.Config (*protocol.ServerEndpoint)(nil), // 1: v2ray.core.common.protocol.ServerEndpoint } var file_proxy_vmess_outbound_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.proxy.vmess.outbound.Config.Receiver:type_name -> v2ray.core.common.protocol.ServerEndpoint 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_proxy_vmess_outbound_config_proto_init() } func file_proxy_vmess_outbound_config_proto_init() { if File_proxy_vmess_outbound_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vmess_outbound_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_vmess_outbound_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vmess_outbound_config_proto_goTypes, DependencyIndexes: file_proxy_vmess_outbound_config_proto_depIdxs, MessageInfos: file_proxy_vmess_outbound_config_proto_msgTypes, }.Build() File_proxy_vmess_outbound_config_proto = out.File file_proxy_vmess_outbound_config_proto_rawDesc = nil file_proxy_vmess_outbound_config_proto_goTypes = nil file_proxy_vmess_outbound_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/outbound/command.go
proxy/vmess/outbound/command.go
// +build !confonly package outbound import ( "time" "v2ray.com/core/common" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/proxy/vmess" ) func (h *Handler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) { rawAccount := &vmess.Account{ Id: cmd.ID.String(), AlterId: uint32(cmd.AlterIds), SecuritySettings: &protocol.SecurityConfig{ Type: protocol.SecurityType_LEGACY, }, } account, err := rawAccount.AsAccount() common.Must(err) user := &protocol.MemoryUser{ Email: "", Level: cmd.Level, Account: account, } dest := net.TCPDestination(cmd.Host, cmd.Port) until := time.Now().Add(time.Duration(cmd.ValidMin) * time.Minute) h.serverList.AddServer(protocol.NewServerSpec(dest, protocol.BeforeTime(until), user)) } func (h *Handler) handleCommand(dest net.Destination, cmd protocol.ResponseCommand) { switch typedCommand := cmd.(type) { case *protocol.CommandSwitchAccount: if typedCommand.Host == nil { typedCommand.Host = dest.Address } h.handleSwitchAccount(typedCommand) default: } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/inbound/inbound.go
proxy/vmess/inbound/inbound.go
// +build !confonly package inbound //go:generate go run v2ray.com/core/common/errors/errorgen import ( "context" "io" "strings" "sync" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/common/uuid" feature_inbound "v2ray.com/core/features/inbound" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/proxy/vmess" "v2ray.com/core/proxy/vmess/encoding" "v2ray.com/core/transport/internet" ) type userByEmail struct { sync.Mutex cache map[string]*protocol.MemoryUser defaultLevel uint32 defaultAlterIDs uint16 } func newUserByEmail(config *DefaultConfig) *userByEmail { return &userByEmail{ cache: make(map[string]*protocol.MemoryUser), defaultLevel: config.Level, defaultAlterIDs: uint16(config.AlterId), } } func (v *userByEmail) addNoLock(u *protocol.MemoryUser) bool { email := strings.ToLower(u.Email) _, found := v.cache[email] if found { return false } v.cache[email] = u return true } func (v *userByEmail) Add(u *protocol.MemoryUser) bool { v.Lock() defer v.Unlock() return v.addNoLock(u) } func (v *userByEmail) Get(email string) (*protocol.MemoryUser, bool) { email = strings.ToLower(email) v.Lock() defer v.Unlock() user, found := v.cache[email] if !found { id := uuid.New() rawAccount := &vmess.Account{ Id: id.String(), AlterId: uint32(v.defaultAlterIDs), } account, err := rawAccount.AsAccount() common.Must(err) user = &protocol.MemoryUser{ Level: v.defaultLevel, Email: email, Account: account, } v.cache[email] = user } return user, found } func (v *userByEmail) Remove(email string) bool { email = strings.ToLower(email) v.Lock() defer v.Unlock() if _, found := v.cache[email]; !found { return false } delete(v.cache, email) return true } // Handler is an inbound connection handler that handles messages in VMess protocol. type Handler struct { policyManager policy.Manager inboundHandlerManager feature_inbound.Manager clients *vmess.TimedUserValidator usersByEmail *userByEmail detours *DetourConfig sessionHistory *encoding.SessionHistory secure bool } // New creates a new VMess inbound handler. func New(ctx context.Context, config *Config) (*Handler, error) { v := core.MustFromContext(ctx) handler := &Handler{ policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager), clients: vmess.NewTimedUserValidator(protocol.DefaultIDHash), detours: config.Detour, usersByEmail: newUserByEmail(config.GetDefaultValue()), sessionHistory: encoding.NewSessionHistory(), secure: config.SecureEncryptionOnly, } for _, user := range config.User { mUser, err := user.ToMemoryUser() if err != nil { return nil, newError("failed to get VMess user").Base(err) } if err := handler.AddUser(ctx, mUser); err != nil { return nil, newError("failed to initiate user").Base(err) } } return handler, nil } // Close implements common.Closable. func (h *Handler) Close() error { return errors.Combine( h.clients.Close(), h.sessionHistory.Close(), common.Close(h.usersByEmail)) } // Network implements proxy.Inbound.Network(). func (*Handler) Network() []net.Network { return []net.Network{net.Network_TCP} } func (h *Handler) GetUser(email string) *protocol.MemoryUser { user, existing := h.usersByEmail.Get(email) if !existing { h.clients.Add(user) } return user } func (h *Handler) AddUser(ctx context.Context, user *protocol.MemoryUser) error { if len(user.Email) > 0 && !h.usersByEmail.Add(user) { return newError("User ", user.Email, " already exists.") } return h.clients.Add(user) } func (h *Handler) RemoveUser(ctx context.Context, email string) error { if email == "" { return newError("Email must not be empty.") } if !h.usersByEmail.Remove(email) { return newError("User ", email, " not found.") } h.clients.Remove(email) return nil } func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error { session.EncodeResponseHeader(response, output) bodyWriter := session.EncodeResponseBody(request, output) { // Optimize for small response packet data, err := input.ReadMultiBuffer() if err != nil { return err } if err := bodyWriter.WriteMultiBuffer(data); err != nil { return err } } if err := output.SetBuffered(false); err != nil { return err } if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil { return err } if request.Option.Has(protocol.RequestOptionChunkStream) { if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil { return err } } return nil } func isInsecureEncryption(s protocol.SecurityType) bool { return s == protocol.SecurityType_NONE || s == protocol.SecurityType_LEGACY || s == protocol.SecurityType_UNKNOWN } // Process implements proxy.Inbound.Process(). func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error { sessionPolicy := h.policyManager.ForLevel(0) if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { return newError("unable to set read deadline").Base(err).AtWarning() } reader := &buf.BufferedReader{Reader: buf.NewReader(connection)} svrSession := encoding.NewServerSession(h.clients, h.sessionHistory) request, err := svrSession.DecodeRequestHeader(reader) if err != nil { if errors.Cause(err) != io.EOF { log.Record(&log.AccessMessage{ From: connection.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: err, }) err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() } return err } if h.secure && isInsecureEncryption(request.Security) { log.Record(&log.AccessMessage{ From: connection.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: "Insecure encryption", Email: request.User.Email, }) return newError("client is using insecure encryption: ", request.Security) } if request.Command != protocol.RequestCommandMux { ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: connection.RemoteAddr(), To: request.Destination(), Status: log.AccessAccepted, Reason: "", Email: request.User.Email, }) } newError("received request for ", request.Destination()).WriteToLog(session.ExportIDToError(ctx)) if err := connection.SetReadDeadline(time.Time{}); err != nil { newError("unable to set back read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) } inbound := session.InboundFromContext(ctx) if inbound == nil { panic("no inbound metadata") } inbound.User = request.User sessionPolicy = h.policyManager.ForLevel(request.User.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) link, err := dispatcher.Dispatch(ctx, request.Destination()) if err != nil { return newError("failed to dispatch request to ", request.Destination()).Base(err) } requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) bodyReader := svrSession.DecodeRequestBody(request, reader) if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer request").Base(err) } return nil } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) writer := buf.NewBufferedWriter(buf.NewWriter(connection)) defer writer.Flush() response := &protocol.ResponseHeader{ Command: h.generateCommand(ctx, request), } return transferResponse(timer, svrSession, request, response, link.Reader, writer) } var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return nil } func (h *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand { if h.detours != nil { tag := h.detours.To if h.inboundHandlerManager != nil { handler, err := h.inboundHandlerManager.GetHandler(ctx, tag) if err != nil { newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) return nil } proxyHandler, port, availableMin := handler.GetRandomInboundProxy() inboundHandler, ok := proxyHandler.(*Handler) if ok && inboundHandler != nil { if availableMin > 255 { availableMin = 255 } newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog(session.ExportIDToError(ctx)) user := inboundHandler.GetUser(request.User.Email) if user == nil { return nil } account := user.Account.(*vmess.MemoryAccount) return &protocol.CommandSwitchAccount{ Port: port, ID: account.ID.UUID(), AlterIds: uint16(len(account.AlterIDs)), Level: user.Level, ValidMin: byte(availableMin), } } } } return nil } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/inbound/errors.generated.go
proxy/vmess/inbound/errors.generated.go
package inbound import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/inbound/config.go
proxy/vmess/inbound/config.go
// +build !confonly package inbound // GetDefaultValue returns default settings of DefaultConfig. func (c *Config) GetDefaultValue() *DefaultConfig { if c.GetDefault() == nil { return &DefaultConfig{ AlterId: 32, Level: 0, } } return c.Default }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/inbound/config.pb.go
proxy/vmess/inbound/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/vmess/inbound/config.proto package inbound 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" protocol "v2ray.com/core/common/protocol" ) 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 DetourConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields To string `protobuf:"bytes,1,opt,name=to,proto3" json:"to,omitempty"` } func (x *DetourConfig) Reset() { *x = DetourConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vmess_inbound_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DetourConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*DetourConfig) ProtoMessage() {} func (x *DetourConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_inbound_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 DetourConfig.ProtoReflect.Descriptor instead. func (*DetourConfig) Descriptor() ([]byte, []int) { return file_proxy_vmess_inbound_config_proto_rawDescGZIP(), []int{0} } func (x *DetourConfig) GetTo() string { if x != nil { return x.To } return "" } type DefaultConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AlterId uint32 `protobuf:"varint,1,opt,name=alter_id,json=alterId,proto3" json:"alter_id,omitempty"` Level uint32 `protobuf:"varint,2,opt,name=level,proto3" json:"level,omitempty"` } func (x *DefaultConfig) Reset() { *x = DefaultConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vmess_inbound_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DefaultConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*DefaultConfig) ProtoMessage() {} func (x *DefaultConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_inbound_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 DefaultConfig.ProtoReflect.Descriptor instead. func (*DefaultConfig) Descriptor() ([]byte, []int) { return file_proxy_vmess_inbound_config_proto_rawDescGZIP(), []int{1} } func (x *DefaultConfig) GetAlterId() uint32 { if x != nil { return x.AlterId } return 0 } func (x *DefaultConfig) GetLevel() uint32 { if x != nil { return x.Level } return 0 } type Config struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields User []*protocol.User `protobuf:"bytes,1,rep,name=user,proto3" json:"user,omitempty"` Default *DefaultConfig `protobuf:"bytes,2,opt,name=default,proto3" json:"default,omitempty"` Detour *DetourConfig `protobuf:"bytes,3,opt,name=detour,proto3" json:"detour,omitempty"` SecureEncryptionOnly bool `protobuf:"varint,4,opt,name=secure_encryption_only,json=secureEncryptionOnly,proto3" json:"secure_encryption_only,omitempty"` } func (x *Config) Reset() { *x = Config{} if protoimpl.UnsafeEnabled { mi := &file_proxy_vmess_inbound_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_inbound_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 Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_proxy_vmess_inbound_config_proto_rawDescGZIP(), []int{2} } func (x *Config) GetUser() []*protocol.User { if x != nil { return x.User } return nil } func (x *Config) GetDefault() *DefaultConfig { if x != nil { return x.Default } return nil } func (x *Config) GetDetour() *DetourConfig { if x != nil { return x.Detour } return nil } func (x *Config) GetSecureEncryptionOnly() bool { if x != nil { return x.SecureEncryptionOnly } return false } var File_proxy_vmess_inbound_config_proto protoreflect.FileDescriptor var file_proxy_vmess_inbound_config_proto_rawDesc = []byte{ 0x0a, 0x20, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 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, 0x1e, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x6f, 0x75, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x0e, 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x74, 0x6f, 0x22, 0x40, 0x0a, 0x0d, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x22, 0x83, 0x02, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x12, 0x47, 0x0a, 0x07, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2e, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x12, 0x44, 0x0a, 0x06, 0x64, 0x65, 0x74, 0x6f, 0x75, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x2e, 0x44, 0x65, 0x74, 0x6f, 0x75, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x06, 0x64, 0x65, 0x74, 0x6f, 0x75, 0x72, 0x12, 0x34, 0x0a, 0x16, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x5f, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x14, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x6e, 0x6c, 0x79, 0x42, 0x6b, 0x0a, 0x22, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x50, 0x01, 0x5a, 0x22, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x76, 0x6d, 0x65, 0x73, 0x73, 0x2f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0xaa, 0x02, 0x1e, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x56, 0x6d, 0x65, 0x73, 0x73, 0x2e, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_vmess_inbound_config_proto_rawDescOnce sync.Once file_proxy_vmess_inbound_config_proto_rawDescData = file_proxy_vmess_inbound_config_proto_rawDesc ) func file_proxy_vmess_inbound_config_proto_rawDescGZIP() []byte { file_proxy_vmess_inbound_config_proto_rawDescOnce.Do(func() { file_proxy_vmess_inbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_vmess_inbound_config_proto_rawDescData) }) return file_proxy_vmess_inbound_config_proto_rawDescData } var file_proxy_vmess_inbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_proxy_vmess_inbound_config_proto_goTypes = []interface{}{ (*DetourConfig)(nil), // 0: v2ray.core.proxy.vmess.inbound.DetourConfig (*DefaultConfig)(nil), // 1: v2ray.core.proxy.vmess.inbound.DefaultConfig (*Config)(nil), // 2: v2ray.core.proxy.vmess.inbound.Config (*protocol.User)(nil), // 3: v2ray.core.common.protocol.User } var file_proxy_vmess_inbound_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.proxy.vmess.inbound.Config.user:type_name -> v2ray.core.common.protocol.User 1, // 1: v2ray.core.proxy.vmess.inbound.Config.default:type_name -> v2ray.core.proxy.vmess.inbound.DefaultConfig 0, // 2: v2ray.core.proxy.vmess.inbound.Config.detour:type_name -> v2ray.core.proxy.vmess.inbound.DetourConfig 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_vmess_inbound_config_proto_init() } func file_proxy_vmess_inbound_config_proto_init() { if File_proxy_vmess_inbound_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_vmess_inbound_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DetourConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proxy_vmess_inbound_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DefaultConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proxy_vmess_inbound_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Config); 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_vmess_inbound_config_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_vmess_inbound_config_proto_goTypes, DependencyIndexes: file_proxy_vmess_inbound_config_proto_depIdxs, MessageInfos: file_proxy_vmess_inbound_config_proto_msgTypes, }.Build() File_proxy_vmess_inbound_config_proto = out.File file_proxy_vmess_inbound_config_proto_rawDesc = nil file_proxy_vmess_inbound_config_proto_goTypes = nil file_proxy_vmess_inbound_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/encrypt_test.go
proxy/vmess/aead/encrypt_test.go
package aead import ( "bytes" "fmt" "io" "testing" "github.com/stretchr/testify/assert" ) func TestOpenVMessAEADHeader(t *testing.T) { TestHeader := []byte("Test Header") key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") var keyw [16]byte copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) var AEADR = bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, _, err, _ := OpenVMessAEADHeader(keyw, authid, AEADR) fmt.Println(string(out)) fmt.Println(err) } func TestOpenVMessAEADHeader2(t *testing.T) { TestHeader := []byte("Test Header") key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") var keyw [16]byte copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) var AEADR = bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, _, err, readen := OpenVMessAEADHeader(keyw, authid, AEADR) assert.Equal(t, len(sealed)-16-AEADR.Len(), readen) assert.Equal(t, string(TestHeader), string(out)) assert.Nil(t, err) } func TestOpenVMessAEADHeader4(t *testing.T) { for i := 0; i <= 60; i++ { TestHeader := []byte("Test Header") key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") var keyw [16]byte copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) var sealedm [16]byte copy(sealedm[:], sealed) sealed[i] ^= 0xff var AEADR = bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, drain, err, readen := OpenVMessAEADHeader(keyw, authid, AEADR) assert.Equal(t, len(sealed)-16-AEADR.Len(), readen) assert.Equal(t, true, drain) assert.NotNil(t, err) if err == nil { fmt.Println(">") } assert.Nil(t, out) } } func TestOpenVMessAEADHeader4Massive(t *testing.T) { for j := 0; j < 1000; j++ { for i := 0; i <= 60; i++ { TestHeader := []byte("Test Header") key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") var keyw [16]byte copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) var sealedm [16]byte copy(sealedm[:], sealed) sealed[i] ^= 0xff var AEADR = bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, drain, err, readen := OpenVMessAEADHeader(keyw, authid, AEADR) assert.Equal(t, len(sealed)-16-AEADR.Len(), readen) assert.Equal(t, true, drain) assert.NotNil(t, err) if err == nil { fmt.Println(">") } assert.Nil(t, out) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/encrypt.go
proxy/vmess/aead/encrypt.go
package aead import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/binary" "io" "time" "v2ray.com/core/common" ) func SealVMessAEADHeader(key [16]byte, data []byte) []byte { generatedAuthID := CreateAuthID(key[:], time.Now().Unix()) connectionNonce := make([]byte, 8) if _, err := io.ReadFull(rand.Reader, connectionNonce); err != nil { panic(err.Error()) } aeadPayloadLengthSerializeBuffer := bytes.NewBuffer(nil) headerPayloadDataLen := uint16(len(data)) common.Must(binary.Write(aeadPayloadLengthSerializeBuffer, binary.BigEndian, headerPayloadDataLen)) aeadPayloadLengthSerializedByte := aeadPayloadLengthSerializeBuffer.Bytes() var payloadHeaderLengthAEADEncrypted []byte { payloadHeaderLengthAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADKey, string(generatedAuthID[:]), string(connectionNonce)) payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADIV, string(generatedAuthID[:]), string(connectionNonce))[:12] payloadHeaderLengthAEADAESBlock, err := aes.NewCipher(payloadHeaderLengthAEADKey) if err != nil { panic(err.Error()) } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock) if err != nil { panic(err.Error()) } payloadHeaderLengthAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderLengthAEADNonce, aeadPayloadLengthSerializedByte, generatedAuthID[:]) } var payloadHeaderAEADEncrypted []byte { payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(generatedAuthID[:]), string(connectionNonce)) payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(generatedAuthID[:]), string(connectionNonce))[:12] payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey) if err != nil { panic(err.Error()) } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) if err != nil { panic(err.Error()) } payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:]) } var outputBuffer = bytes.NewBuffer(nil) common.Must2(outputBuffer.Write(generatedAuthID[:])) //16 common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) //2+16 common.Must2(outputBuffer.Write(connectionNonce)) //8 common.Must2(outputBuffer.Write(payloadHeaderAEADEncrypted)) return outputBuffer.Bytes() } func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte, bool, error, int) { var payloadHeaderLengthAEADEncrypted [18]byte var nonce [8]byte var bytesRead int authidCheckValueReadBytesCounts, err := io.ReadFull(data, payloadHeaderLengthAEADEncrypted[:]) bytesRead += authidCheckValueReadBytesCounts if err != nil { return nil, false, err, bytesRead } nonceReadBytesCounts, err := io.ReadFull(data, nonce[:]) bytesRead += nonceReadBytesCounts if err != nil { return nil, false, err, bytesRead } //Decrypt Length var decryptedAEADHeaderLengthPayloadResult []byte { payloadHeaderLengthAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADKey, string(authid[:]), string(nonce[:])) payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADIV, string(authid[:]), string(nonce[:]))[:12] payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderLengthAEADKey) if err != nil { panic(err.Error()) } payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) if err != nil { panic(err.Error()) } decryptedAEADHeaderLengthPayload, erropenAEAD := payloadHeaderLengthAEAD.Open(nil, payloadHeaderLengthAEADNonce, payloadHeaderLengthAEADEncrypted[:], authid[:]) if erropenAEAD != nil { return nil, true, erropenAEAD, bytesRead } decryptedAEADHeaderLengthPayloadResult = decryptedAEADHeaderLengthPayload } var length uint16 common.Must(binary.Read(bytes.NewReader(decryptedAEADHeaderLengthPayloadResult[:]), binary.BigEndian, &length)) var decryptedAEADHeaderPayloadR []byte var payloadHeaderAEADEncryptedReadedBytesCounts int { payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(authid[:]), string(nonce[:])) payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(authid[:]), string(nonce[:]))[:12] //16 == AEAD Tag size payloadHeaderAEADEncrypted := make([]byte, length+16) payloadHeaderAEADEncryptedReadedBytesCounts, err = io.ReadFull(data, payloadHeaderAEADEncrypted) bytesRead += payloadHeaderAEADEncryptedReadedBytesCounts if err != nil { return nil, false, err, bytesRead } payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey) if err != nil { panic(err.Error()) } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) if err != nil { panic(err.Error()) } decryptedAEADHeaderPayload, erropenAEAD := payloadHeaderAEAD.Open(nil, payloadHeaderAEADNonce, payloadHeaderAEADEncrypted, authid[:]) if erropenAEAD != nil { return nil, true, erropenAEAD, bytesRead } decryptedAEADHeaderPayloadR = decryptedAEADHeaderPayload } return decryptedAEADHeaderPayloadR, false, nil, bytesRead }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/consts.go
proxy/vmess/aead/consts.go
package aead const KDFSaltConst_AuthIDEncryptionKey = "AES Auth ID Encryption" const KDFSaltConst_AEADRespHeaderLenKey = "AEAD Resp Header Len Key" const KDFSaltConst_AEADRespHeaderLenIV = "AEAD Resp Header Len IV" const KDFSaltConst_AEADRespHeaderPayloadKey = "AEAD Resp Header Key" const KDFSaltConst_AEADRespHeaderPayloadIV = "AEAD Resp Header IV" const KDFSaltConst_VMessAEADKDF = "VMess AEAD KDF" const KDFSaltConst_VMessHeaderPayloadAEADKey = "VMess Header AEAD Key" const KDFSaltConst_VMessHeaderPayloadAEADIV = "VMess Header AEAD Nonce" const KDFSaltConst_VMessHeaderPayloadLengthAEADKey = "VMess Header AEAD Key_Length" const KDFSaltConst_VMessHeaderPayloadLengthAEADIV = "VMess Header AEAD Nonce_Length"
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/authid_test.go
proxy/vmess/aead/authid_test.go
package aead import ( "fmt" "github.com/stretchr/testify/assert" "strconv" "testing" "time" ) func TestCreateAuthID(t *testing.T) { key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") authid := CreateAuthID(key, time.Now().Unix()) fmt.Println(key) fmt.Println(authid) } func TestCreateAuthIDAndDecode(t *testing.T) { key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") authid := CreateAuthID(key, time.Now().Unix()) fmt.Println(key) fmt.Println(authid) AuthDecoder := NewAuthIDDecoderHolder() var keyw [16]byte copy(keyw[:], key) AuthDecoder.AddUser(keyw, "Demo User") res, err := AuthDecoder.Match(authid) fmt.Println(res) fmt.Println(err) assert.Equal(t, "Demo User", res) assert.Nil(t, err) } func TestCreateAuthIDAndDecode2(t *testing.T) { key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") authid := CreateAuthID(key, time.Now().Unix()) fmt.Println(key) fmt.Println(authid) AuthDecoder := NewAuthIDDecoderHolder() var keyw [16]byte copy(keyw[:], key) AuthDecoder.AddUser(keyw, "Demo User") res, err := AuthDecoder.Match(authid) fmt.Println(res) fmt.Println(err) assert.Equal(t, "Demo User", res) assert.Nil(t, err) key2 := KDF16([]byte("Demo Key for Auth ID Test2"), "Demo Path for Auth ID Test") authid2 := CreateAuthID(key2, time.Now().Unix()) res2, err2 := AuthDecoder.Match(authid2) assert.EqualError(t, err2, "user do not exist") assert.Nil(t, res2) } func TestCreateAuthIDAndDecodeMassive(t *testing.T) { key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") authid := CreateAuthID(key, time.Now().Unix()) fmt.Println(key) fmt.Println(authid) AuthDecoder := NewAuthIDDecoderHolder() var keyw [16]byte copy(keyw[:], key) AuthDecoder.AddUser(keyw, "Demo User") res, err := AuthDecoder.Match(authid) fmt.Println(res) fmt.Println(err) assert.Equal(t, "Demo User", res) assert.Nil(t, err) for i := 0; i <= 10000; i++ { key2 := KDF16([]byte("Demo Key for Auth ID Test2"), "Demo Path for Auth ID Test", strconv.Itoa(i)) var keyw2 [16]byte copy(keyw2[:], key2) AuthDecoder.AddUser(keyw2, "Demo User"+strconv.Itoa(i)) } authid3 := CreateAuthID(key, time.Now().Unix()) res2, err2 := AuthDecoder.Match(authid3) assert.Equal(t, "Demo User", res2) assert.Nil(t, err2) } func TestCreateAuthIDAndDecodeSuperMassive(t *testing.T) { key := KDF16([]byte("Demo Key for Auth ID Test"), "Demo Path for Auth ID Test") authid := CreateAuthID(key, time.Now().Unix()) fmt.Println(key) fmt.Println(authid) AuthDecoder := NewAuthIDDecoderHolder() var keyw [16]byte copy(keyw[:], key) AuthDecoder.AddUser(keyw, "Demo User") res, err := AuthDecoder.Match(authid) fmt.Println(res) fmt.Println(err) assert.Equal(t, "Demo User", res) assert.Nil(t, err) for i := 0; i <= 1000000; i++ { key2 := KDF16([]byte("Demo Key for Auth ID Test2"), "Demo Path for Auth ID Test", strconv.Itoa(i)) var keyw2 [16]byte copy(keyw2[:], key2) AuthDecoder.AddUser(keyw2, "Demo User"+strconv.Itoa(i)) } authid3 := CreateAuthID(key, time.Now().Unix()) before := time.Now() res2, err2 := AuthDecoder.Match(authid3) after := time.Now() assert.Equal(t, "Demo User", res2) assert.Nil(t, err2) fmt.Println(after.Sub(before).Seconds()) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/authid.go
proxy/vmess/aead/authid.go
package aead import ( "bytes" "crypto/aes" "crypto/cipher" rand3 "crypto/rand" "encoding/binary" "errors" "hash/crc32" "io" "math" "time" "v2ray.com/core/common" antiReplayWindow "v2ray.com/core/common/antireplay" ) func CreateAuthID(cmdKey []byte, time int64) [16]byte { buf := bytes.NewBuffer(nil) common.Must(binary.Write(buf, binary.BigEndian, time)) var zero uint32 common.Must2(io.CopyN(buf, rand3.Reader, 4)) zero = crc32.ChecksumIEEE(buf.Bytes()) common.Must(binary.Write(buf, binary.BigEndian, zero)) aesBlock := NewCipherFromKey(cmdKey) if buf.Len() != 16 { panic("Size unexpected") } var result [16]byte aesBlock.Encrypt(result[:], buf.Bytes()) return result } func NewCipherFromKey(cmdKey []byte) cipher.Block { aesBlock, err := aes.NewCipher(KDF16(cmdKey, KDFSaltConst_AuthIDEncryptionKey)) if err != nil { panic(err) } return aesBlock } type AuthIDDecoder struct { s cipher.Block } func NewAuthIDDecoder(cmdKey []byte) *AuthIDDecoder { return &AuthIDDecoder{NewCipherFromKey(cmdKey)} } func (aidd *AuthIDDecoder) Decode(data [16]byte) (int64, uint32, int32, []byte) { aidd.s.Decrypt(data[:], data[:]) var t int64 var zero uint32 var rand int32 reader := bytes.NewReader(data[:]) common.Must(binary.Read(reader, binary.BigEndian, &t)) common.Must(binary.Read(reader, binary.BigEndian, &rand)) common.Must(binary.Read(reader, binary.BigEndian, &zero)) return t, zero, rand, data[:] } func NewAuthIDDecoderHolder() *AuthIDDecoderHolder { return &AuthIDDecoderHolder{make(map[string]*AuthIDDecoderItem), antiReplayWindow.NewAntiReplayWindow(120)} } type AuthIDDecoderHolder struct { aidhi map[string]*AuthIDDecoderItem apw *antiReplayWindow.AntiReplayWindow } type AuthIDDecoderItem struct { dec *AuthIDDecoder ticket interface{} } func NewAuthIDDecoderItem(key [16]byte, ticket interface{}) *AuthIDDecoderItem { return &AuthIDDecoderItem{ dec: NewAuthIDDecoder(key[:]), ticket: ticket, } } func (a *AuthIDDecoderHolder) AddUser(key [16]byte, ticket interface{}) { a.aidhi[string(key[:])] = NewAuthIDDecoderItem(key, ticket) } func (a *AuthIDDecoderHolder) RemoveUser(key [16]byte) { delete(a.aidhi, string(key[:])) } func (a *AuthIDDecoderHolder) Match(AuthID [16]byte) (interface{}, error) { for _, v := range a.aidhi { t, z, r, d := v.dec.Decode(AuthID) if z != crc32.ChecksumIEEE(d[:12]) { continue } if t < 0 { continue } if math.Abs(math.Abs(float64(t))-float64(time.Now().Unix())) > 120 { continue } if !a.apw.Check(AuthID[:]) { return nil, ErrReplay } _ = r return v.ticket, nil } return nil, ErrNotFound } var ErrNotFound = errors.New("user do not exist") var ErrReplay = errors.New("replayed request")
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/vmess/aead/kdf.go
proxy/vmess/aead/kdf.go
package aead import ( "crypto/hmac" "crypto/sha256" "hash" ) func KDF(key []byte, path ...string) []byte { hmacf := hmac.New(func() hash.Hash { return sha256.New() }, []byte(KDFSaltConst_VMessAEADKDF)) for _, v := range path { hmacf = hmac.New(func() hash.Hash { return hmacf }, []byte(v)) } hmacf.Write(key) return hmacf.Sum(nil) } func KDF16(key []byte, path ...string) []byte { r := KDF(key, path...) return r[:16] }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/errors.generated.go
proxy/http/errors.generated.go
package http import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/client.go
proxy/http/client.go
// +build !confonly package http import ( "bufio" "context" "encoding/base64" "io" "net/http" "net/url" "sync" "golang.org/x/net/http2" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/bytespool" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/retry" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet/tls" ) type Client struct { serverPicker protocol.ServerPicker policyManager policy.Manager } type h2Conn struct { rawConn net.Conn h2Conn *http2.ClientConn } var ( cachedH2Mutex sync.Mutex cachedH2Conns map[net.Destination]h2Conn ) // NewClient create a new http client based on the given config. 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 get server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { return nil, newError("0 target server") } v := core.MustFromContext(ctx) return &Client{ serverPicker: protocol.NewRoundRobinServerPicker(serverList), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), }, nil } // Process implements proxy.Outbound.Process. We first create a socket tunnel via HTTP CONNECT method, then redirect all inbound traffic to that tunnel. 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.") } target := outbound.Target targetAddr := target.NetAddr() if target.Network == net.Network_UDP { return newError("UDP is not supported by HTTP outbound") } var user *protocol.MemoryUser var conn internet.Connection mbuf, _ := link.Reader.ReadMultiBuffer() len := mbuf.Len() firstPayload := bytespool.Alloc(len) mbuf, _ = buf.SplitBytes(mbuf, firstPayload) firstPayload = firstPayload[:len] buf.ReleaseMulti(mbuf) defer bytespool.Free(firstPayload) if err := retry.ExponentialBackoff(5, 100).On(func() error { server := c.serverPicker.PickServer() dest := server.Destination() user = server.PickUser() netConn, err := setUpHTTPTunnel(ctx, dest, targetAddr, user, dialer, firstPayload) if netConn != nil { conn = internet.Connection(netConn) } return err }); err != nil { return newError("failed to find an available destination").Base(err) } defer func() { if err := conn.Close(); err != nil { newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) } }() p := c.policyManager.ForLevel(0) if user != nil { p = c.policyManager.ForLevel(user.Level) } ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle) requestFunc := func() error { defer timer.SetTimeout(p.Timeouts.DownlinkOnly) return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)) } responseFunc := func() error { defer timer.SetTimeout(p.Timeouts.UplinkOnly) return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) } var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer)) if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { return newError("connection ends").Base(err) } return nil } // setUpHTTPTunnel will create a socket tunnel via HTTP CONNECT method func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, user *protocol.MemoryUser, dialer internet.Dialer, firstPayload []byte) (net.Conn, error) { req := &http.Request{ Method: http.MethodConnect, URL: &url.URL{Host: target}, Header: make(http.Header), Host: target, } if user != nil && user.Account != nil { account := user.Account.(*Account) auth := account.GetUsername() + ":" + account.GetPassword() req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth))) } connectHTTP1 := func(rawConn net.Conn) (net.Conn, error) { req.Header.Set("Proxy-Connection", "Keep-Alive") err := req.Write(rawConn) if err != nil { rawConn.Close() return nil, err } if _, err := rawConn.Write(firstPayload); err != nil { rawConn.Close() return nil, err } resp, err := http.ReadResponse(bufio.NewReader(rawConn), req) if err != nil { rawConn.Close() return nil, err } if resp.StatusCode != http.StatusOK { rawConn.Close() return nil, newError("Proxy responded with non 200 code: " + resp.Status) } return rawConn, nil } connectHTTP2 := func(rawConn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) { pr, pw := io.Pipe() req.Body = pr var pErr error var wg sync.WaitGroup wg.Add(1) go func() { _, pErr = pw.Write(firstPayload) wg.Done() }() resp, err := h2clientConn.RoundTrip(req) if err != nil { rawConn.Close() return nil, err } wg.Wait() if pErr != nil { rawConn.Close() return nil, pErr } if resp.StatusCode != http.StatusOK { rawConn.Close() return nil, newError("Proxy responded with non 200 code: " + resp.Status) } return newHTTP2Conn(rawConn, pw, resp.Body), nil } cachedH2Mutex.Lock() cachedConn, cachedConnFound := cachedH2Conns[dest] cachedH2Mutex.Unlock() if cachedConnFound { rc, cc := cachedConn.rawConn, cachedConn.h2Conn if cc.CanTakeNewRequest() { proxyConn, err := connectHTTP2(rc, cc) if err != nil { return nil, err } return proxyConn, nil } } rawConn, err := dialer.Dial(ctx, dest) if err != nil { return nil, err } iConn := rawConn if statConn, ok := iConn.(*internet.StatCouterConnection); ok { iConn = statConn.Connection } nextProto := "" if tlsConn, ok := iConn.(*tls.Conn); ok { if err := tlsConn.Handshake(); err != nil { rawConn.Close() return nil, err } nextProto = tlsConn.ConnectionState().NegotiatedProtocol } switch nextProto { case "", "http/1.1": return connectHTTP1(rawConn) case "h2": t := http2.Transport{} h2clientConn, err := t.NewClientConn(rawConn) if err != nil { rawConn.Close() return nil, err } proxyConn, err := connectHTTP2(rawConn, h2clientConn) if err != nil { rawConn.Close() return nil, err } cachedH2Mutex.Lock() if cachedH2Conns == nil { cachedH2Conns = make(map[net.Destination]h2Conn) } cachedH2Conns[dest] = h2Conn{ rawConn: rawConn, h2Conn: h2clientConn, } cachedH2Mutex.Unlock() return proxyConn, err default: return nil, newError("negotiated unsupported application layer protocol: " + nextProto) } } func newHTTP2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn { return &http2Conn{Conn: c, in: pipedReqBody, out: respBody} } type http2Conn struct { net.Conn in *io.PipeWriter out io.ReadCloser } func (h *http2Conn) Read(p []byte) (n int, err error) { return h.out.Read(p) } func (h *http2Conn) Write(p []byte) (n int, err error) { return h.in.Write(p) } func (h *http2Conn) Close() error { h.in.Close() return h.out.Close() } func init() { common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewClient(ctx, config.(*ClientConfig)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/config.go
proxy/http/config.go
package http import ( "v2ray.com/core/common/protocol" ) func (a *Account) Equals(another protocol.Account) bool { if account, ok := another.(*Account); ok { return a.Username == account.Username } return false } func (a *Account) AsAccount() (protocol.Account, error) { return a, nil } func (sc *ServerConfig) HasAccount(username, password string) bool { if sc.Accounts == nil { return false } p, found := sc.Accounts[username] if !found { return false } return p == password }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/server.go
proxy/http/server.go
// +build !confonly package http import ( "bufio" "context" "encoding/base64" "io" "net/http" "strings" "time" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" http_proto "v2ray.com/core/common/protocol/http" "v2ray.com/core/common/session" "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" "v2ray.com/core/features/routing" "v2ray.com/core/transport/internet" ) // Server is an HTTP proxy server. type Server struct { config *ServerConfig policyManager policy.Manager } // NewServer creates a new HTTP inbound handler. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { v := core.MustFromContext(ctx) s := &Server{ config: config, policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), } return s, nil } func (s *Server) policy() policy.Session { config := s.config p := s.policyManager.ForLevel(config.UserLevel) if config.Timeout > 0 && config.UserLevel == 0 { p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second } return p } // Network implements proxy.Inbound. func (*Server) Network() []net.Network { return []net.Network{net.Network_TCP} } func isTimeout(err error) bool { nerr, ok := errors.Cause(err).(net.Error) return ok && nerr.Timeout() } func parseBasicAuth(auth string) (username, password string, ok bool) { const prefix = "Basic " if !strings.HasPrefix(auth, prefix) { return } c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) if err != nil { return } cs := string(c) s := strings.IndexByte(cs, ':') if s < 0 { return } return cs[:s], cs[s+1:], true } type readerOnly struct { io.Reader } func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { inbound := session.InboundFromContext(ctx) if inbound != nil { inbound.User = &protocol.MemoryUser{ Level: s.config.UserLevel, } } reader := bufio.NewReaderSize(readerOnly{conn}, buf.Size) Start: if err := conn.SetReadDeadline(time.Now().Add(s.policy().Timeouts.Handshake)); err != nil { newError("failed to set read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) } request, err := http.ReadRequest(reader) if err != nil { trace := newError("failed to read http request").Base(err) if errors.Cause(err) != io.EOF && !isTimeout(errors.Cause(err)) { trace.AtWarning() // nolint: errcheck } return trace } if len(s.config.Accounts) > 0 { user, pass, ok := parseBasicAuth(request.Header.Get("Proxy-Authorization")) if !ok || !s.config.HasAccount(user, pass) { return common.Error2(conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"proxy\"\r\nConnection: close\r\n\r\n"))) } if inbound != nil { inbound.User.Email = user } } newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WriteToLog(session.ExportIDToError(ctx)) if err := conn.SetReadDeadline(time.Time{}); err != nil { newError("failed to clear read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) } defaultPort := net.Port(80) if strings.EqualFold(request.URL.Scheme, "https") { defaultPort = net.Port(443) } host := request.Host if host == "" { host = request.URL.Host } dest, err := http_proto.ParseHost(host, defaultPort) if err != nil { return newError("malformed proxy host: ", host).AtWarning().Base(err) } ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: conn.RemoteAddr(), To: request.URL, Status: log.AccessAccepted, Reason: "", }) if strings.EqualFold(request.Method, "CONNECT") { return s.handleConnect(ctx, request, reader, conn, dest, dispatcher) } keepAlive := (strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive") err = s.handlePlainHTTP(ctx, request, conn, dest, dispatcher) if err == errWaitAnother { if keepAlive { goto Start } err = nil } return err } func (s *Server) handleConnect(ctx context.Context, request *http.Request, reader *bufio.Reader, conn internet.Connection, dest net.Destination, dispatcher routing.Dispatcher) error { _, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) if err != nil { return newError("failed to write back OK response").Base(err) } plcy := s.policy() ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { return err } if reader.Buffered() > 0 { payload, err := buf.ReadFrom(io.LimitReader(reader, int64(reader.Buffered()))) if err != nil { return err } if err := link.Writer.WriteMultiBuffer(payload); err != nil { return err } reader = nil } requestDone := func() error { defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) } responseDone := func() error { defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) v2writer := buf.NewWriter(conn) if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil { return err } return nil } var closeWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) if err := task.Run(ctx, closeWriter, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return nil } var errWaitAnother = newError("keep alive") func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error { if !s.config.AllowTransparent && request.URL.Host == "" { // RFC 2068 (HTTP/1.1) requires URL to be absolute URL in HTTP proxy. response := &http.Response{ Status: "Bad Request", StatusCode: 400, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: http.Header(make(map[string][]string)), Body: nil, ContentLength: 0, Close: true, } response.Header.Set("Proxy-Connection", "close") response.Header.Set("Connection", "close") return response.Write(writer) } if len(request.URL.Host) > 0 { request.Host = request.URL.Host } http_proto.RemoveHopByHopHeaders(request.Header) // Prevent UA from being set to golang's default ones if request.Header.Get("User-Agent") == "" { request.Header.Set("User-Agent", "") } content := &session.Content{ Protocol: "http/1.1", } content.SetAttribute(":method", strings.ToUpper(request.Method)) content.SetAttribute(":path", request.URL.Path) for key := range request.Header { value := request.Header.Get(key) content.SetAttribute(strings.ToLower(key), value) } ctx = session.ContextWithContent(ctx, content) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { return err } // Plain HTTP request is not a stream. The request always finishes before response. Hense request has to be closed later. defer common.Close(link.Writer) // nolint: errcheck var result error = errWaitAnother requestDone := func() error { request.Header.Set("Connection", "close") requestWriter := buf.NewBufferedWriter(link.Writer) common.Must(requestWriter.SetBuffered(false)) if err := request.Write(requestWriter); err != nil { return newError("failed to write whole request").Base(err).AtWarning() } return nil } responseDone := func() error { responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size) response, err := http.ReadResponse(responseReader, request) if err == nil { http_proto.RemoveHopByHopHeaders(response.Header) if response.ContentLength >= 0 { response.Header.Set("Proxy-Connection", "keep-alive") response.Header.Set("Connection", "keep-alive") response.Header.Set("Keep-Alive", "timeout=4") response.Close = false } else { response.Close = true result = nil } } else { newError("failed to read response from ", request.Host).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) response = &http.Response{ Status: "Service Unavailable", StatusCode: 503, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: http.Header(make(map[string][]string)), Body: nil, ContentLength: 0, Close: true, } response.Header.Set("Connection", "close") response.Header.Set("Proxy-Connection", "close") } if err := response.Write(writer); err != nil { return newError("failed to write response").Base(err).AtWarning() } return nil } if err := task.Run(ctx, requestDone, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) return newError("connection ends").Base(err) } return result } func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewServer(ctx, config.(*ServerConfig)) })) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/http.go
proxy/http/http.go
package http //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/proxy/http/config.pb.go
proxy/http/config.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: proxy/http/config.proto package http 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" protocol "v2ray.com/core/common/protocol" ) 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 Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_proxy_http_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_http_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_http_config_proto_rawDescGZIP(), []int{0} } func (x *Account) GetUsername() string { if x != nil { return x.Username } return "" } func (x *Account) GetPassword() string { if x != nil { return x.Password } return "" } // Config for HTTP proxy server. type ServerConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Deprecated: Do not use. Timeout uint32 `protobuf:"varint,1,opt,name=timeout,proto3" json:"timeout,omitempty"` Accounts map[string]string `protobuf:"bytes,2,rep,name=accounts,proto3" json:"accounts,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` AllowTransparent bool `protobuf:"varint,3,opt,name=allow_transparent,json=allowTransparent,proto3" json:"allow_transparent,omitempty"` UserLevel uint32 `protobuf:"varint,4,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"` } func (x *ServerConfig) Reset() { *x = ServerConfig{} if protoimpl.UnsafeEnabled { mi := &file_proxy_http_config_proto_msgTypes[1] 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_http_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 ServerConfig.ProtoReflect.Descriptor instead. func (*ServerConfig) Descriptor() ([]byte, []int) { return file_proxy_http_config_proto_rawDescGZIP(), []int{1} } // Deprecated: Do not use. func (x *ServerConfig) GetTimeout() uint32 { if x != nil { return x.Timeout } return 0 } func (x *ServerConfig) GetAccounts() map[string]string { if x != nil { return x.Accounts } return nil } func (x *ServerConfig) GetAllowTransparent() bool { if x != nil { return x.AllowTransparent } return false } func (x *ServerConfig) GetUserLevel() uint32 { if x != nil { return x.UserLevel } return 0 } // ClientConfig is the protobuf config for HTTP proxy client. type ClientConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Sever is a list of HTTP server addresses. 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_http_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_http_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_http_config_proto_rawDescGZIP(), []int{2} } func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint { if x != nil { return x.Server } return nil } var File_proxy_http_config_proto protoreflect.FileDescriptor var file_proxy_http_config_proto_rawDesc = []byte{ 0x0a, 0x17, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x68, 0x74, 0x74, 0x70, 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, 0x41, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x84, 0x02, 0x0a, 0x0c, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1c, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x02, 0x18, 0x01, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x4d, 0x0a, 0x08, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x12, 0x2b, 0x0a, 0x11, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x10, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x1a, 0x3b, 0x0a, 0x0d, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x52, 0x0a, 0x0c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x42, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 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, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x68, 0x74, 0x74, 0x70, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proxy_http_config_proto_rawDescOnce sync.Once file_proxy_http_config_proto_rawDescData = file_proxy_http_config_proto_rawDesc ) func file_proxy_http_config_proto_rawDescGZIP() []byte { file_proxy_http_config_proto_rawDescOnce.Do(func() { file_proxy_http_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_proxy_http_config_proto_rawDescData) }) return file_proxy_http_config_proto_rawDescData } var file_proxy_http_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_proxy_http_config_proto_goTypes = []interface{}{ (*Account)(nil), // 0: v2ray.core.proxy.http.Account (*ServerConfig)(nil), // 1: v2ray.core.proxy.http.ServerConfig (*ClientConfig)(nil), // 2: v2ray.core.proxy.http.ClientConfig nil, // 3: v2ray.core.proxy.http.ServerConfig.AccountsEntry (*protocol.ServerEndpoint)(nil), // 4: v2ray.core.common.protocol.ServerEndpoint } var file_proxy_http_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.proxy.http.ServerConfig.accounts:type_name -> v2ray.core.proxy.http.ServerConfig.AccountsEntry 4, // 1: v2ray.core.proxy.http.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint 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_proxy_http_config_proto_init() } func file_proxy_http_config_proto_init() { if File_proxy_http_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proxy_http_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_http_config_proto_msgTypes[1].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 } } file_proxy_http_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 } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proxy_http_config_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_http_config_proto_goTypes, DependencyIndexes: file_proxy_http_config_proto_depIdxs, MessageInfos: file_proxy_http_config_proto_msgTypes, }.Build() File_proxy_http_config_proto = out.File file_proxy_http_config_proto_rawDesc = nil file_proxy_http_config_proto_goTypes = nil file_proxy_http_config_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/vprotogen/main.go
infra/vprotogen/main.go
package main import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" "v2ray.com/core" "v2ray.com/core/common" ) func main() { pwd, wdErr := os.Getwd() if wdErr != nil { fmt.Println("Can not get current working directory.") os.Exit(1) } GOBIN := common.GetGOBIN() protoc := core.ProtocMap[runtime.GOOS] protoFilesMap := make(map[string][]string) walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return err } if info.IsDir() { return nil } dir := filepath.Dir(path) filename := filepath.Base(path) if strings.HasSuffix(filename, ".proto") { protoFilesMap[dir] = append(protoFilesMap[dir], path) } return nil }) if walkErr != nil { fmt.Println(walkErr) os.Exit(1) } for _, files := range protoFilesMap { for _, relProtoFile := range files { var args []string if core.ProtoFilesUsingProtocGenGoFast[relProtoFile] { args = []string{"--gofast_out", pwd, "--plugin", "protoc-gen-gofast=" + GOBIN + "/protoc-gen-gofast"} } else { args = []string{"--go_out", pwd, "--go-grpc_out", pwd, "--plugin", "protoc-gen-go=" + GOBIN + "/protoc-gen-go", "--plugin", "protoc-gen-go-grpc=" + GOBIN + "/protoc-gen-go-grpc"} } args = append(args, relProtoFile) cmd := exec.Command(protoc, args...) cmd.Env = append(cmd.Env, os.Environ()...) cmd.Env = append(cmd.Env, "GOBIN="+GOBIN) output, cmdErr := cmd.CombinedOutput() if len(output) > 0 { fmt.Println(string(output)) } if cmdErr != nil { fmt.Println(cmdErr) os.Exit(1) } } } moduleName, gmnErr := common.GetModuleName(pwd) if gmnErr != nil { fmt.Println(gmnErr) os.Exit(1) } modulePath := filepath.Join(strings.Split(moduleName, "/")...) pbGoFilesMap := make(map[string][]string) walkErr2 := filepath.Walk(modulePath, func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return err } if info.IsDir() { return nil } dir := filepath.Dir(path) filename := filepath.Base(path) if strings.HasSuffix(filename, ".pb.go") { pbGoFilesMap[dir] = append(pbGoFilesMap[dir], path) } return nil }) if walkErr2 != nil { fmt.Println(walkErr2) os.Exit(1) } var err error for _, srcPbGoFiles := range pbGoFilesMap { for _, srcPbGoFile := range srcPbGoFiles { var dstPbGoFile string dstPbGoFile, err = filepath.Rel(modulePath, srcPbGoFile) if err != nil { fmt.Println(err) continue } err = os.Link(srcPbGoFile, dstPbGoFile) if err != nil { if os.IsNotExist(err) { fmt.Printf("'%s' does not exist\n", srcPbGoFile) continue } if os.IsPermission(err) { fmt.Println(err) continue } if os.IsExist(err) { err = os.Remove(dstPbGoFile) if err != nil { fmt.Printf("Failed to delete file '%s'\n", dstPbGoFile) continue } err = os.Rename(srcPbGoFile, dstPbGoFile) if err != nil { fmt.Printf("Can not move '%s' to '%s'\n", srcPbGoFile, dstPbGoFile) } continue } } err = os.Rename(srcPbGoFile, dstPbGoFile) if err != nil { fmt.Printf("Can not move '%s' to '%s'\n", srcPbGoFile, dstPbGoFile) } continue } } if err == nil { err = os.RemoveAll(strings.Split(modulePath, "/")[0]) if err != nil { fmt.Println(err) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/loader.go
infra/conf/loader.go
package conf import ( "encoding/json" "strings" ) type ConfigCreator func() interface{} type ConfigCreatorCache map[string]ConfigCreator func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error { if _, found := v[id]; found { return newError(id, " already registered.").AtError() } v[id] = creator return nil } func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) { creator, found := v[id] if !found { return nil, newError("unknown config id: ", id) } return creator(), nil } type JSONConfigLoader struct { cache ConfigCreatorCache idKey string configKey string } func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey string) *JSONConfigLoader { return &JSONConfigLoader{ idKey: idKey, configKey: configKey, cache: cache, } } func (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) { id = strings.ToLower(id) config, err := v.cache.CreateConfig(id) if err != nil { return nil, err } if err := json.Unmarshal(raw, config); err != nil { return nil, err } return config, nil } func (v *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) { var obj map[string]json.RawMessage if err := json.Unmarshal(raw, &obj); err != nil { return nil, "", err } rawID, found := obj[v.idKey] if !found { return nil, "", newError(v.idKey, " not found in JSON context").AtError() } var id string if err := json.Unmarshal(rawID, &id); err != nil { return nil, "", err } rawConfig := json.RawMessage(raw) if len(v.configKey) > 0 { configValue, found := obj[v.configKey] if found { rawConfig = configValue } else { // Default to empty json object. rawConfig = json.RawMessage([]byte("{}")) } } config, err := v.LoadWithID([]byte(rawConfig), id) if err != nil { return nil, id, err } return config, id, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/reverse.go
infra/conf/reverse.go
package conf import ( "github.com/golang/protobuf/proto" "v2ray.com/core/app/reverse" ) type BridgeConfig struct { Tag string `json:"tag"` Domain string `json:"domain"` } func (c *BridgeConfig) Build() (*reverse.BridgeConfig, error) { return &reverse.BridgeConfig{ Tag: c.Tag, Domain: c.Domain, }, nil } type PortalConfig struct { Tag string `json:"tag"` Domain string `json:"domain"` } func (c *PortalConfig) Build() (*reverse.PortalConfig, error) { return &reverse.PortalConfig{ Tag: c.Tag, Domain: c.Domain, }, nil } type ReverseConfig struct { Bridges []BridgeConfig `json:"bridges"` Portals []PortalConfig `json:"portals"` } func (c *ReverseConfig) Build() (proto.Message, error) { config := &reverse.Config{} for _, bconfig := range c.Bridges { b, err := bconfig.Build() if err != nil { return nil, err } config.BridgeConfig = append(config.BridgeConfig, b) } for _, pconfig := range c.Portals { p, err := pconfig.Build() if err != nil { return nil, err } config.PortalConfig = append(config.PortalConfig, p) } return config, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/socks.go
infra/conf/socks.go
package conf import ( "encoding/json" "github.com/golang/protobuf/proto" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/proxy/socks" ) type SocksAccount struct { Username string `json:"user"` Password string `json:"pass"` } func (v *SocksAccount) Build() *socks.Account { return &socks.Account{ Username: v.Username, Password: v.Password, } } const ( AuthMethodNoAuth = "noauth" AuthMethodUserPass = "password" ) type SocksServerConfig struct { AuthMethod string `json:"auth"` Accounts []*SocksAccount `json:"accounts"` UDP bool `json:"udp"` Host *Address `json:"ip"` Timeout uint32 `json:"timeout"` UserLevel uint32 `json:"userLevel"` } func (v *SocksServerConfig) Build() (proto.Message, error) { config := new(socks.ServerConfig) switch v.AuthMethod { case AuthMethodNoAuth: config.AuthType = socks.AuthType_NO_AUTH case AuthMethodUserPass: config.AuthType = socks.AuthType_PASSWORD default: //newError("unknown socks auth method: ", v.AuthMethod, ". Default to noauth.").AtWarning().WriteToLog() config.AuthType = socks.AuthType_NO_AUTH } if len(v.Accounts) > 0 { config.Accounts = make(map[string]string, len(v.Accounts)) for _, account := range v.Accounts { config.Accounts[account.Username] = account.Password } } config.UdpEnabled = v.UDP if v.Host != nil { config.Address = v.Host.Build() } config.Timeout = v.Timeout config.UserLevel = v.UserLevel return config, nil } type SocksRemoteConfig struct { Address *Address `json:"address"` Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } type SocksClientConfig struct { Servers []*SocksRemoteConfig `json:"servers"` } func (v *SocksClientConfig) Build() (proto.Message, error) { config := new(socks.ClientConfig) config.Server = make([]*protocol.ServerEndpoint, len(v.Servers)) for idx, serverConfig := range v.Servers { server := &protocol.ServerEndpoint{ Address: serverConfig.Address.Build(), Port: uint32(serverConfig.Port), } for _, rawUser := range serverConfig.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, newError("failed to parse Socks user").Base(err).AtError() } account := new(SocksAccount) if err := json.Unmarshal(rawUser, account); err != nil { return nil, newError("failed to parse socks account").Base(err).AtError() } user.Account = serial.ToTypedMessage(account.Build()) server.User = append(server.User, user) } config.Server[idx] = server } return config, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/policy.go
infra/conf/policy.go
package conf import ( "v2ray.com/core/app/policy" ) type Policy struct { Handshake *uint32 `json:"handshake"` ConnectionIdle *uint32 `json:"connIdle"` UplinkOnly *uint32 `json:"uplinkOnly"` DownlinkOnly *uint32 `json:"downlinkOnly"` StatsUserUplink bool `json:"statsUserUplink"` StatsUserDownlink bool `json:"statsUserDownlink"` BufferSize *int32 `json:"bufferSize"` } func (t *Policy) Build() (*policy.Policy, error) { config := new(policy.Policy_Timeout) if t.Handshake != nil { config.Handshake = &policy.Second{Value: *t.Handshake} } if t.ConnectionIdle != nil { config.ConnectionIdle = &policy.Second{Value: *t.ConnectionIdle} } if t.UplinkOnly != nil { config.UplinkOnly = &policy.Second{Value: *t.UplinkOnly} } if t.DownlinkOnly != nil { config.DownlinkOnly = &policy.Second{Value: *t.DownlinkOnly} } p := &policy.Policy{ Timeout: config, Stats: &policy.Policy_Stats{ UserUplink: t.StatsUserUplink, UserDownlink: t.StatsUserDownlink, }, } if t.BufferSize != nil { bs := int32(-1) if *t.BufferSize >= 0 { bs = (*t.BufferSize) * 1024 } p.Buffer = &policy.Policy_Buffer{ Connection: bs, } } return p, nil } type SystemPolicy struct { StatsInboundUplink bool `json:"statsInboundUplink"` StatsInboundDownlink bool `json:"statsInboundDownlink"` StatsOutboundUplink bool `json:"statsOutboundUplink"` StatsOutboundDownlink bool `json:"statsOutboundDownlink"` } func (p *SystemPolicy) Build() (*policy.SystemPolicy, error) { return &policy.SystemPolicy{ Stats: &policy.SystemPolicy_Stats{ InboundUplink: p.StatsInboundUplink, InboundDownlink: p.StatsInboundDownlink, OutboundUplink: p.StatsOutboundUplink, OutboundDownlink: p.StatsOutboundDownlink, }, }, nil } type PolicyConfig struct { Levels map[uint32]*Policy `json:"levels"` System *SystemPolicy `json:"system"` } func (c *PolicyConfig) Build() (*policy.Config, error) { levels := make(map[uint32]*policy.Policy) for l, p := range c.Levels { if p != nil { pp, err := p.Build() if err != nil { return nil, err } levels[l] = pp } } config := &policy.Config{ Level: levels, } if c.System != nil { sc, err := c.System.Build() if err != nil { return nil, err } config.System = sc } return config, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dns_test.go
infra/conf/dns_test.go
package conf_test import ( "encoding/json" "os" "path/filepath" "testing" "github.com/golang/protobuf/proto" "v2ray.com/core/app/dns" "v2ray.com/core/app/router" "v2ray.com/core/common" "v2ray.com/core/common/net" "v2ray.com/core/common/platform" "v2ray.com/core/common/platform/filesystem" . "v2ray.com/core/infra/conf" ) func init() { wd, err := os.Getwd() common.Must(err) if _, err := os.Stat(platform.GetAssetLocation("geoip.dat")); err != nil && os.IsNotExist(err) { common.Must(filesystem.CopyFile(platform.GetAssetLocation("geoip.dat"), filepath.Join(wd, "..", "..", "release", "config", "geoip.dat"))) } geositeFilePath := filepath.Join(wd, "geosite.dat") os.Setenv("v2ray.location.asset", wd) geositeFile, err := os.OpenFile(geositeFilePath, os.O_CREATE|os.O_WRONLY, 0600) common.Must(err) defer geositeFile.Close() list := &router.GeoSiteList{ Entry: []*router.GeoSite{ { CountryCode: "TEST", Domain: []*router.Domain{ {Type: router.Domain_Full, Value: "example.com"}, }, }, }, } listBytes, err := proto.Marshal(list) common.Must(err) common.Must2(geositeFile.Write(listBytes)) } func TestDnsConfigParsing(t *testing.T) { geositePath := platform.GetAssetLocation("geosite.dat") defer func() { os.Remove(geositePath) os.Unsetenv("v2ray.location.asset") }() parserCreator := func() func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { config := new(DnsConfig) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } runMultiTestCase(t, []TestCase{ { Input: `{ "servers": [{ "address": "8.8.8.8", "port": 5353, "domains": ["domain:v2ray.com"] }], "hosts": { "v2ray.com": "127.0.0.1", "domain:example.com": "google.com", "geosite:test": "10.0.0.1", "keyword:google": "8.8.8.8", "regexp:.*\\.com": "8.8.4.4" }, "clientIp": "10.0.0.1" }`, Parser: parserCreator(), Output: &dns.Config{ NameServer: []*dns.NameServer{ { Address: &net.Endpoint{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{8, 8, 8, 8}, }, }, Network: net.Network_UDP, Port: 5353, }, PrioritizedDomain: []*dns.NameServer_PriorityDomain{ { Type: dns.DomainMatchingType_Subdomain, Domain: "v2ray.com", }, }, OriginalRules: []*dns.NameServer_OriginalRule{ { Rule: "domain:v2ray.com", Size: 1, }, }, }, }, StaticHosts: []*dns.Config_HostMapping{ { Type: dns.DomainMatchingType_Subdomain, Domain: "example.com", ProxiedDomain: "google.com", }, { Type: dns.DomainMatchingType_Full, Domain: "example.com", Ip: [][]byte{{10, 0, 0, 1}}, }, { Type: dns.DomainMatchingType_Keyword, Domain: "google", Ip: [][]byte{{8, 8, 8, 8}}, }, { Type: dns.DomainMatchingType_Regex, Domain: ".*\\.com", Ip: [][]byte{{8, 8, 4, 4}}, }, { Type: dns.DomainMatchingType_Full, Domain: "v2ray.com", Ip: [][]byte{{127, 0, 0, 1}}, }, }, ClientIp: []byte{10, 0, 0, 1}, }, }, }) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/common_test.go
infra/conf/common_test.go
package conf_test import ( "encoding/json" "github.com/google/go-cmp/cmp/cmpopts" "os" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common/protocol" "v2ray.com/core/common" "v2ray.com/core/common/net" . "v2ray.com/core/infra/conf" ) func TestStringListUnmarshalError(t *testing.T) { rawJson := `1234` list := new(StringList) err := json.Unmarshal([]byte(rawJson), list) if err == nil { t.Error("expected error, but got nil") } } func TestStringListLen(t *testing.T) { rawJson := `"a, b, c, d"` var list StringList err := json.Unmarshal([]byte(rawJson), &list) common.Must(err) if r := cmp.Diff([]string(list), []string{"a", " b", " c", " d"}); r != "" { t.Error(r) } } func TestIPParsing(t *testing.T) { rawJson := "\"8.8.8.8\"" var address Address err := json.Unmarshal([]byte(rawJson), &address) common.Must(err) if r := cmp.Diff(address.IP(), net.IP{8, 8, 8, 8}); r != "" { t.Error(r) } } func TestDomainParsing(t *testing.T) { rawJson := "\"v2ray.com\"" var address Address common.Must(json.Unmarshal([]byte(rawJson), &address)) if address.Domain() != "v2ray.com" { t.Error("domain: ", address.Domain()) } } func TestURLParsing(t *testing.T) { { rawJson := "\"https://dns.google/dns-query\"" var address Address common.Must(json.Unmarshal([]byte(rawJson), &address)) if address.Domain() != "https://dns.google/dns-query" { t.Error("URL: ", address.Domain()) } } { rawJson := "\"https+local://dns.google/dns-query\"" var address Address common.Must(json.Unmarshal([]byte(rawJson), &address)) if address.Domain() != "https+local://dns.google/dns-query" { t.Error("URL: ", address.Domain()) } } } func TestInvalidAddressJson(t *testing.T) { rawJson := "1234" var address Address err := json.Unmarshal([]byte(rawJson), &address) if err == nil { t.Error("nil error") } } func TestStringNetwork(t *testing.T) { var network Network common.Must(json.Unmarshal([]byte(`"tcp"`), &network)) if v := network.Build(); v != net.Network_TCP { t.Error("network: ", v) } } func TestArrayNetworkList(t *testing.T) { var list NetworkList common.Must(json.Unmarshal([]byte("[\"Tcp\"]"), &list)) nlist := list.Build() if !net.HasNetwork(nlist, net.Network_TCP) { t.Error("no tcp network") } if net.HasNetwork(nlist, net.Network_UDP) { t.Error("has udp network") } } func TestStringNetworkList(t *testing.T) { var list NetworkList common.Must(json.Unmarshal([]byte("\"TCP, ip\""), &list)) nlist := list.Build() if !net.HasNetwork(nlist, net.Network_TCP) { t.Error("no tcp network") } if net.HasNetwork(nlist, net.Network_UDP) { t.Error("has udp network") } } func TestInvalidNetworkJson(t *testing.T) { var list NetworkList err := json.Unmarshal([]byte("0"), &list) if err == nil { t.Error("nil error") } } func TestIntPort(t *testing.T) { var portRange PortRange common.Must(json.Unmarshal([]byte("1234"), &portRange)) if r := cmp.Diff(portRange, PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestOverRangeIntPort(t *testing.T) { var portRange PortRange err := json.Unmarshal([]byte("70000"), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("-1"), &portRange) if err == nil { t.Error("nil error") } } func TestEnvPort(t *testing.T) { common.Must(os.Setenv("PORT", "1234")) var portRange PortRange common.Must(json.Unmarshal([]byte("\"env:PORT\""), &portRange)) if r := cmp.Diff(portRange, PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestSingleStringPort(t *testing.T) { var portRange PortRange common.Must(json.Unmarshal([]byte("\"1234\""), &portRange)) if r := cmp.Diff(portRange, PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestStringPairPort(t *testing.T) { var portRange PortRange common.Must(json.Unmarshal([]byte("\"1234-5678\""), &portRange)) if r := cmp.Diff(portRange, PortRange{ From: 1234, To: 5678, }); r != "" { t.Error(r) } } func TestOverRangeStringPort(t *testing.T) { var portRange PortRange err := json.Unmarshal([]byte("\"65536\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"70000-80000\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"1-90000\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"700-600\""), &portRange) if err == nil { t.Error("nil error") } } func TestUserParsing(t *testing.T) { user := new(User) common.Must(json.Unmarshal([]byte(`{ "id": "96edb838-6d68-42ef-a933-25f7ac3a9d09", "email": "love@v2ray.com", "level": 1, "alterId": 100 }`), user)) nUser := user.Build() if r := cmp.Diff(nUser, &protocol.User{ Level: 1, Email: "love@v2ray.com", }, cmpopts.IgnoreUnexported(protocol.User{})); r != "" { t.Error(r) } } func TestInvalidUserJson(t *testing.T) { user := new(User) err := json.Unmarshal([]byte(`{"email": 1234}`), user) if err == nil { t.Error("nil error") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/vmess.go
infra/conf/vmess.go
package conf import ( "encoding/json" "strings" "github.com/golang/protobuf/proto" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" "v2ray.com/core/proxy/vmess" "v2ray.com/core/proxy/vmess/inbound" "v2ray.com/core/proxy/vmess/outbound" ) type VMessAccount struct { ID string `json:"id"` AlterIds uint16 `json:"alterId"` Security string `json:"security"` } // Build implements Buildable func (a *VMessAccount) Build() *vmess.Account { var st protocol.SecurityType switch strings.ToLower(a.Security) { case "aes-128-gcm": st = protocol.SecurityType_AES128_GCM case "chacha20-poly1305": st = protocol.SecurityType_CHACHA20_POLY1305 case "auto": st = protocol.SecurityType_AUTO case "none": st = protocol.SecurityType_NONE default: st = protocol.SecurityType_AUTO } return &vmess.Account{ Id: a.ID, AlterId: uint32(a.AlterIds), SecuritySettings: &protocol.SecurityConfig{ Type: st, }, } } type VMessDetourConfig struct { ToTag string `json:"to"` } // Build implements Buildable func (c *VMessDetourConfig) Build() *inbound.DetourConfig { return &inbound.DetourConfig{ To: c.ToTag, } } type FeaturesConfig struct { Detour *VMessDetourConfig `json:"detour"` } type VMessDefaultConfig struct { AlterIDs uint16 `json:"alterId"` Level byte `json:"level"` } // Build implements Buildable func (c *VMessDefaultConfig) Build() *inbound.DefaultConfig { config := new(inbound.DefaultConfig) config.AlterId = uint32(c.AlterIDs) if config.AlterId == 0 { config.AlterId = 32 } config.Level = uint32(c.Level) return config } type VMessInboundConfig struct { Users []json.RawMessage `json:"clients"` Features *FeaturesConfig `json:"features"` Defaults *VMessDefaultConfig `json:"default"` DetourConfig *VMessDetourConfig `json:"detour"` SecureOnly bool `json:"disableInsecureEncryption"` } // Build implements Buildable func (c *VMessInboundConfig) Build() (proto.Message, error) { config := &inbound.Config{ SecureEncryptionOnly: c.SecureOnly, } if c.Defaults != nil { config.Default = c.Defaults.Build() } if c.DetourConfig != nil { config.Detour = c.DetourConfig.Build() } else if c.Features != nil && c.Features.Detour != nil { config.Detour = c.Features.Detour.Build() } config.User = make([]*protocol.User, len(c.Users)) for idx, rawData := range c.Users { user := new(protocol.User) if err := json.Unmarshal(rawData, user); err != nil { return nil, newError("invalid VMess user").Base(err) } account := new(VMessAccount) if err := json.Unmarshal(rawData, account); err != nil { return nil, newError("invalid VMess user").Base(err) } user.Account = serial.ToTypedMessage(account.Build()) config.User[idx] = user } return config, nil } type VMessOutboundTarget struct { Address *Address `json:"address"` Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } type VMessOutboundConfig struct { Receivers []*VMessOutboundTarget `json:"vnext"` } // Build implements Buildable func (c *VMessOutboundConfig) Build() (proto.Message, error) { config := new(outbound.Config) if len(c.Receivers) == 0 { return nil, newError("0 VMess receiver configured") } serverSpecs := make([]*protocol.ServerEndpoint, len(c.Receivers)) for idx, rec := range c.Receivers { if len(rec.Users) == 0 { return nil, newError("0 user configured for VMess outbound") } if rec.Address == nil { return nil, newError("address is not set in VMess outbound config") } spec := &protocol.ServerEndpoint{ Address: rec.Address.Build(), Port: uint32(rec.Port), } for _, rawUser := range rec.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, newError("invalid VMess user").Base(err) } account := new(VMessAccount) if err := json.Unmarshal(rawUser, account); err != nil { return nil, newError("invalid VMess user").Base(err) } user.Account = serial.ToTypedMessage(account.Build()) spec.User = append(spec.User, user) } serverSpecs[idx] = spec } config.Receiver = serverSpecs return config, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/api.go
infra/conf/api.go
package conf import ( "strings" "v2ray.com/core/app/commander" loggerservice "v2ray.com/core/app/log/command" handlerservice "v2ray.com/core/app/proxyman/command" statsservice "v2ray.com/core/app/stats/command" "v2ray.com/core/common/serial" ) type ApiConfig struct { Tag string `json:"tag"` Services []string `json:"services"` } func (c *ApiConfig) Build() (*commander.Config, error) { if c.Tag == "" { return nil, newError("Api tag can't be empty.") } services := make([]*serial.TypedMessage, 0, 16) for _, s := range c.Services { switch strings.ToLower(s) { case "handlerservice": services = append(services, serial.ToTypedMessage(&handlerservice.Config{})) case "loggerservice": services = append(services, serial.ToTypedMessage(&loggerservice.Config{})) case "statsservice": services = append(services, serial.ToTypedMessage(&statsservice.Config{})) } } return &commander.Config{ Tag: c.Tag, Service: services, }, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/policy_test.go
infra/conf/policy_test.go
package conf_test import ( "testing" "v2ray.com/core/common" . "v2ray.com/core/infra/conf" ) func TestBufferSize(t *testing.T) { cases := []struct { Input int32 Output int32 }{ { Input: 0, Output: 0, }, { Input: -1, Output: -1, }, { Input: 1, Output: 1024, }, } for _, c := range cases { bs := int32(c.Input) pConf := Policy{ BufferSize: &bs, } p, err := pConf.Build() common.Must(err) if p.Buffer.Connection != c.Output { t.Error("expected buffer size ", c.Output, " but got ", p.Buffer.Connection) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false