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
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/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" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/outbound/errors.generated.go
proxy/vmess/outbound/errors.generated.go
package outbound import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/outbound/config.go
proxy/vmess/outbound/config.go
package outbound
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/outbound/outbound.go
proxy/vmess/outbound/outbound.go
package outbound //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "crypto/hmac" "crypto/sha256" "hash/crc64" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/retry" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "github.com/v2fly/v2ray-core/v5/proxy/vmess/encoding" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" ) // 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() 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().NetAddr()).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) } if request.Security == protocol.SecurityType_ZERO { request.Security = protocol.SecurityType_NONE request.Option.Clear(protocol.RequestOptionChunkStream) request.Option.Clear(protocol.RequestOptionChunkMasking) } if account.AuthenticatedLengthExperiment { request.Option.Set(protocol.RequestOptionAuthenticatedLength) } input := link.Reader output := link.Writer isAEAD := false if !aeadDisabled && len(account.AlterIDs) == 0 { isAEAD = true } hashkdf := hmac.New(sha256.New, []byte("VMessBF")) hashkdf.Write(account.ID.Bytes()) behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO)) session := encoding.NewClientSession(ctx, isAEAD, protocol.DefaultIDHash, int64(behaviorSeed)) 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, err := session.EncodeRequestBody(request, writer) if err != nil { return newError("failed to start encoding").Base(err) } if err := buf.CopyOnceTimeout(input, bodyWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { return newError("failed to write first payload").Base(err) } 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) && !account.NoTerminationSignal { 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, err := session.DecodeResponseBody(request, reader) if err != nil { return newError("failed to start encoding response").Base(err) } return buf.Copy(bodyReader, output, buf.UpdateActivity(timer)) } 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 aeadDisabled = 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)) })) common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedClient := config.(*SimplifiedConfig) fullClient := &Config{Receiver: []*protocol.ServerEndpoint{ { Address: simplifiedClient.Address, Port: simplifiedClient.Port, User: []*protocol.User{ { Account: serial.ToTypedMessage(&vmess.Account{Id: simplifiedClient.Uuid}), }, }, }, }} return common.CreateObject(ctx, fullClient) })) const defaultFlagValue = "NOT_DEFINED_AT_ALL" paddingValue := platform.NewEnvFlag("v2ray.vmess.padding").GetValue(func() string { return defaultFlagValue }) if paddingValue != defaultFlagValue { enablePadding = true } isAeadDisabled := platform.NewEnvFlag("v2ray.vmess.aead.disabled").GetValue(func() string { return defaultFlagValue }) if isAeadDisabled == "true" { aeadDisabled = true } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/outbound/config.pb.go
proxy/vmess/outbound/config.pb.go
package outbound import ( net "github.com/v2fly/v2ray-core/v5/common/net" protocol "github.com/v2fly/v2ray-core/v5/common/protocol" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) 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) ) type Config struct { state protoimpl.MessageState `protogen:"open.v1"` Receiver []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=Receiver,proto3" json:"Receiver,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} 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 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 } type SimplifiedConfig struct { state protoimpl.MessageState `protogen:"open.v1"` 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"` Uuid string `protobuf:"bytes,3,opt,name=uuid,proto3" json:"uuid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedConfig) Reset() { *x = SimplifiedConfig{} mi := &file_proxy_vmess_outbound_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedConfig) ProtoMessage() {} func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_outbound_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead. func (*SimplifiedConfig) Descriptor() ([]byte, []int) { return file_proxy_vmess_outbound_config_proto_rawDescGZIP(), []int{1} } func (x *SimplifiedConfig) GetAddress() *net.IPOrDomain { if x != nil { return x.Address } return nil } func (x *SimplifiedConfig) GetPort() uint32 { if x != nil { return x.Port } return 0 } func (x *SimplifiedConfig) GetUuid() string { if x != nil { return x.Uuid } return "" } var File_proxy_vmess_outbound_config_proto protoreflect.FileDescriptor const file_proxy_vmess_outbound_config_proto_rawDesc = "" + "\n" + "!proxy/vmess/outbound/config.proto\x12\x1fv2ray.core.proxy.vmess.outbound\x1a!common/protocol/server_spec.proto\x1a\x18common/net/address.proto\x1a common/protoext/extensions.proto\"P\n" + "\x06Config\x12F\n" + "\bReceiver\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\bReceiver\"\x92\x01\n" + "\x10SimplifiedConfig\x12;\n" + "\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" + "\x04port\x18\x02 \x01(\rR\x04port\x12\x12\n" + "\x04uuid\x18\x03 \x01(\tR\x04uuid:\x19\x82\xb5\x18\x15\n" + "\boutbound\x12\x05vmess\x90\xff)\x01B~\n" + "#com.v2ray.core.proxy.vmess.outboundP\x01Z3github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound\xaa\x02\x1fV2Ray.Core.Proxy.Vmess.Outboundb\x06proto3" var ( file_proxy_vmess_outbound_config_proto_rawDescOnce sync.Once file_proxy_vmess_outbound_config_proto_rawDescData []byte ) 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(unsafe.Slice(unsafe.StringData(file_proxy_vmess_outbound_config_proto_rawDesc), len(file_proxy_vmess_outbound_config_proto_rawDesc))) }) return file_proxy_vmess_outbound_config_proto_rawDescData } var file_proxy_vmess_outbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_vmess_outbound_config_proto_goTypes = []any{ (*Config)(nil), // 0: v2ray.core.proxy.vmess.outbound.Config (*SimplifiedConfig)(nil), // 1: v2ray.core.proxy.vmess.outbound.SimplifiedConfig (*protocol.ServerEndpoint)(nil), // 2: v2ray.core.common.protocol.ServerEndpoint (*net.IPOrDomain)(nil), // 3: v2ray.core.common.net.IPOrDomain } var file_proxy_vmess_outbound_config_proto_depIdxs = []int32{ 2, // 0: v2ray.core.proxy.vmess.outbound.Config.Receiver:type_name -> v2ray.core.common.protocol.ServerEndpoint 3, // 1: v2ray.core.proxy.vmess.outbound.SimplifiedConfig.address:type_name -> v2ray.core.common.net.IPOrDomain 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_vmess_outbound_config_proto_init() } func file_proxy_vmess_outbound_config_proto_init() { if File_proxy_vmess_outbound_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vmess_outbound_config_proto_rawDesc), len(file_proxy_vmess_outbound_config_proto_rawDesc)), NumEnums: 0, NumMessages: 2, 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_goTypes = nil file_proxy_vmess_outbound_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/outbound/command.go
proxy/vmess/outbound/command.go
package outbound import ( "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/inbound/inbound.go
proxy/vmess/inbound/inbound.go
package inbound //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "io" "strings" "sync" "time" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/common/uuid" feature_inbound "github.com/v2fly/v2ray-core/v5/features/inbound" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "github.com/v2fly/v2ray-core/v5/proxy/vmess/encoding" "github.com/v2fly/v2ray-core/v5/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, net.Network_UNIX} } 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, err := session.EncodeResponseBody(request, output) if err != nil { return newError("failed to start decoding response").Base(err) } { // 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 } account := request.User.Account.(*vmess.MemoryAccount) if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal { 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) svrSession.SetAEADForced(aeadForced) 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, err := svrSession.DecodeRequestBody(request, reader) if err != nil { return newError("failed to start decoding").Base(err) } 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) } 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 } var ( aeadForced = false aeadForced2022 = false ) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedServer := config.(*SimplifiedConfig) fullConfig := &Config{ User: func() (users []*protocol.User) { for _, v := range simplifiedServer.Users { account := &vmess.Account{Id: v} users = append(users, &protocol.User{ Account: serial.ToTypedMessage(account), }) } return }(), } return common.CreateObject(ctx, fullConfig) })) defaultFlagValue := "true_by_default_2022" isAeadForced := platform.NewEnvFlag("v2ray.vmess.aead.forced").GetValue(func() string { return defaultFlagValue }) if isAeadForced == "true" { aeadForced = true } if isAeadForced == "true_by_default_2022" { aeadForced = true aeadForced2022 = true } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/inbound/errors.generated.go
proxy/vmess/inbound/errors.generated.go
package inbound import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/inbound/config.go
proxy/vmess/inbound/config.go
package inbound // GetDefaultValue returns default settings of DefaultConfig. func (c *Config) GetDefaultValue() *DefaultConfig { if c.GetDefault() == nil { return &DefaultConfig{} } return c.Default }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/inbound/config.pb.go
proxy/vmess/inbound/config.pb.go
package inbound import ( protocol "github.com/v2fly/v2ray-core/v5/common/protocol" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) 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) ) type DetourConfig struct { state protoimpl.MessageState `protogen:"open.v1"` To string `protobuf:"bytes,1,opt,name=to,proto3" json:"to,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DetourConfig) Reset() { *x = DetourConfig{} 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 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 `protogen:"open.v1"` 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"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DefaultConfig) Reset() { *x = DefaultConfig{} 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 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 `protogen:"open.v1"` 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"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} 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 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 } type SimplifiedConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Users []string `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedConfig) Reset() { *x = SimplifiedConfig{} mi := &file_proxy_vmess_inbound_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedConfig) ProtoMessage() {} func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_vmess_inbound_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead. func (*SimplifiedConfig) Descriptor() ([]byte, []int) { return file_proxy_vmess_inbound_config_proto_rawDescGZIP(), []int{3} } func (x *SimplifiedConfig) GetUsers() []string { if x != nil { return x.Users } return nil } var File_proxy_vmess_inbound_config_proto protoreflect.FileDescriptor const file_proxy_vmess_inbound_config_proto_rawDesc = "" + "\n" + " proxy/vmess/inbound/config.proto\x12\x1ev2ray.core.proxy.vmess.inbound\x1a\x1acommon/protocol/user.proto\x1a common/protoext/extensions.proto\"\x1e\n" + "\fDetourConfig\x12\x0e\n" + "\x02to\x18\x01 \x01(\tR\x02to\"@\n" + "\rDefaultConfig\x12\x19\n" + "\balter_id\x18\x01 \x01(\rR\aalterId\x12\x14\n" + "\x05level\x18\x02 \x01(\rR\x05level\"\x83\x02\n" + "\x06Config\x124\n" + "\x04user\x18\x01 \x03(\v2 .v2ray.core.common.protocol.UserR\x04user\x12G\n" + "\adefault\x18\x02 \x01(\v2-.v2ray.core.proxy.vmess.inbound.DefaultConfigR\adefault\x12D\n" + "\x06detour\x18\x03 \x01(\v2,.v2ray.core.proxy.vmess.inbound.DetourConfigR\x06detour\x124\n" + "\x16secure_encryption_only\x18\x04 \x01(\bR\x14secureEncryptionOnly\">\n" + "\x10SimplifiedConfig\x12\x14\n" + "\x05users\x18\x01 \x03(\tR\x05users:\x14\x82\xb5\x18\x10\n" + "\ainbound\x12\x05vmessB{\n" + "\"com.v2ray.core.proxy.vmess.inboundP\x01Z2github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound\xaa\x02\x1eV2Ray.Core.Proxy.Vmess.Inboundb\x06proto3" var ( file_proxy_vmess_inbound_config_proto_rawDescOnce sync.Once file_proxy_vmess_inbound_config_proto_rawDescData []byte ) 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(unsafe.Slice(unsafe.StringData(file_proxy_vmess_inbound_config_proto_rawDesc), len(file_proxy_vmess_inbound_config_proto_rawDesc))) }) return file_proxy_vmess_inbound_config_proto_rawDescData } var file_proxy_vmess_inbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_proxy_vmess_inbound_config_proto_goTypes = []any{ (*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 (*SimplifiedConfig)(nil), // 3: v2ray.core.proxy.vmess.inbound.SimplifiedConfig (*protocol.User)(nil), // 4: v2ray.core.common.protocol.User } var file_proxy_vmess_inbound_config_proto_depIdxs = []int32{ 4, // 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 } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vmess_inbound_config_proto_rawDesc), len(file_proxy_vmess_inbound_config_proto_rawDesc)), NumEnums: 0, NumMessages: 4, 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_goTypes = nil file_proxy_vmess_inbound_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/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) 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) AEADR := bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, _, readen, err := 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 AEADR := bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, drain, readen, err := 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 AEADR := bytes.NewReader(sealed) var authid [16]byte io.ReadFull(AEADR, authid[:]) out, drain, readen, err := 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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/aead/encrypt.go
proxy/vmess/aead/encrypt.go
package aead import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/binary" "io" "time" "github.com/v2fly/v2ray-core/v5/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[:], KDFSaltConstVMessHeaderPayloadLengthAEADKey, string(generatedAuthID[:]), string(connectionNonce)) payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConstVMessHeaderPayloadLengthAEADIV, 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[:], KDFSaltConstVMessHeaderPayloadAEADKey, string(generatedAuthID[:]), string(connectionNonce)) payloadHeaderAEADNonce := KDF(key[:], KDFSaltConstVMessHeaderPayloadAEADIV, 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[:]) } 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, int, error) { 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, bytesRead, err } nonceReadBytesCounts, err := io.ReadFull(data, nonce[:]) bytesRead += nonceReadBytesCounts if err != nil { return nil, false, bytesRead, err } // Decrypt Length var decryptedAEADHeaderLengthPayloadResult []byte { payloadHeaderLengthAEADKey := KDF16(key[:], KDFSaltConstVMessHeaderPayloadLengthAEADKey, string(authid[:]), string(nonce[:])) payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConstVMessHeaderPayloadLengthAEADIV, 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, bytesRead, erropenAEAD } decryptedAEADHeaderLengthPayloadResult = decryptedAEADHeaderLengthPayload } var length uint16 common.Must(binary.Read(bytes.NewReader(decryptedAEADHeaderLengthPayloadResult), binary.BigEndian, &length)) var decryptedAEADHeaderPayloadR []byte var payloadHeaderAEADEncryptedReadedBytesCounts int { payloadHeaderAEADKey := KDF16(key[:], KDFSaltConstVMessHeaderPayloadAEADKey, string(authid[:]), string(nonce[:])) payloadHeaderAEADNonce := KDF(key[:], KDFSaltConstVMessHeaderPayloadAEADIV, 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, bytesRead, err } 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, bytesRead, erropenAEAD } decryptedAEADHeaderPayloadR = decryptedAEADHeaderPayload } return decryptedAEADHeaderPayloadR, false, bytesRead, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/aead/consts.go
proxy/vmess/aead/consts.go
package aead const ( KDFSaltConstAuthIDEncryptionKey = "AES Auth ID Encryption" KDFSaltConstAEADRespHeaderLenKey = "AEAD Resp Header Len Key" KDFSaltConstAEADRespHeaderLenIV = "AEAD Resp Header Len IV" KDFSaltConstAEADRespHeaderPayloadKey = "AEAD Resp Header Key" KDFSaltConstAEADRespHeaderPayloadIV = "AEAD Resp Header IV" KDFSaltConstVMessAEADKDF = "VMess AEAD KDF" KDFSaltConstVMessHeaderPayloadAEADKey = "VMess Header AEAD Key" KDFSaltConstVMessHeaderPayloadAEADIV = "VMess Header AEAD Nonce" KDFSaltConstVMessHeaderPayloadLengthAEADKey = "VMess Header AEAD Key_Length" KDFSaltConstVMessHeaderPayloadLengthAEADIV = "VMess Header AEAD Nonce_Length" )
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/aead/authid_test.go
proxy/vmess/aead/authid_test.go
package aead import ( "fmt" "strconv" "testing" "time" "github.com/stretchr/testify/assert" ) 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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/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" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/antireplay" ) var ( ErrNotFound = errors.New("user do not exist") ErrReplay = errors.New("replayed request") ) 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, KDFSaltConstAuthIDEncryptionKey)) 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), antireplay.NewReplayFilter(120)} } type AuthIDDecoderHolder struct { decoders map[string]*AuthIDDecoderItem filter *antireplay.ReplayFilter } 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.decoders[string(key[:])] = NewAuthIDDecoderItem(key, ticket) } func (a *AuthIDDecoderHolder) RemoveUser(key [16]byte) { delete(a.decoders, string(key[:])) } func (a *AuthIDDecoderHolder) Match(authID [16]byte) (interface{}, error) { for _, v := range a.decoders { t, z, _, 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.filter.Check(authID[:]) { return nil, ErrReplay } return v.ticket, nil } return nil, ErrNotFound }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/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 { hmacCreator := &hMacCreator{value: []byte(KDFSaltConstVMessAEADKDF)} for _, v := range path { hmacCreator = &hMacCreator{value: []byte(v), parent: hmacCreator} } hmacf := hmacCreator.Create() hmacf.Write(key) return hmacf.Sum(nil) } type hMacCreator struct { parent *hMacCreator value []byte } func (h *hMacCreator) Create() hash.Hash { if h.parent == nil { return hmac.New(sha256.New, h.value) } return hmac.New(h.parent.Create, h.value) } func KDF16(key []byte, path ...string) []byte { r := KDF(key, path...) return r[:16] }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/aead/kdf_test.go
proxy/vmess/aead/kdf_test.go
package aead import ( "encoding/hex" "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestKDFValue(t *testing.T) { GeneratedKey := KDF([]byte("Demo Key for KDF Value Test"), "Demo Path for KDF Value Test", "Demo Path for KDF Value Test2", "Demo Path for KDF Value Test3") fmt.Println(hex.EncodeToString(GeneratedKey)) assert.Equal(t, "53e9d7e1bd7bd25022b71ead07d8a596efc8a845c7888652fd684b4903dc8892", hex.EncodeToString(GeneratedKey), "Should generate expected KDF Value") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/errors.generated.go
proxy/http/errors.generated.go
package http import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/client.go
proxy/http/client.go
package http import ( "bufio" "bytes" "context" "encoding/base64" "io" "net/http" "net/url" "sync" "time" "golang.org/x/net/http2" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/bytespool" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/retry" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/security" ) type Client struct { serverPicker protocol.ServerPicker policyManager policy.Manager h1SkipWaitForReply bool } 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), h1SkipWaitForReply: config.H1SkipWaitForReply, }, 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 var firstPayload []byte if reader, ok := link.Reader.(buf.TimeoutReader); ok { // 0-RTT optimization for HTTP/2: If the payload comes very soon, it can be // transmitted together. Note we should not get stuck here, as the payload may // not exist (considering to access MySQL database via a HTTP proxy, where the // server sends hello to the client first). waitTime := proxy.FirstPayloadTimeout if c.h1SkipWaitForReply { // Some server require first write to be present in client hello. // Increase timeout to if the client have explicitly requested to skip waiting for reply. waitTime = time.Second } if mbuf, _ := reader.ReadMultiBufferTimeout(waitTime); mbuf != nil { mlen := mbuf.Len() firstPayload = bytespool.Alloc(mlen) mbuf, _ = buf.SplitBytes(mbuf, firstPayload) firstPayload = firstPayload[:mlen] 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, firstResp, err := setUpHTTPTunnel(ctx, dest, targetAddr, user, dialer, firstPayload, c.h1SkipWaitForReply) if netConn != nil { if _, ok := netConn.(*http2Conn); !ok && !c.h1SkipWaitForReply { if _, err := netConn.Write(firstPayload); err != nil { netConn.Close() return err } } if firstResp != nil { if err := link.Writer.WriteMultiBuffer(firstResp); err != nil { return err } } 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)) } 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, writeFirstPayloadInH1 bool, ) (net.Conn, buf.MultiBuffer, 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, buf.MultiBuffer, error) { req.Header.Set("Proxy-Connection", "Keep-Alive") if !writeFirstPayloadInH1 { err := req.Write(rawConn) if err != nil { rawConn.Close() return nil, nil, err } } else { buffer := bytes.NewBuffer(nil) err := req.Write(buffer) if err != nil { rawConn.Close() return nil, nil, err } _, err = io.Copy(buffer, bytes.NewReader(firstPayload)) if err != nil { rawConn.Close() return nil, nil, err } _, err = rawConn.Write(buffer.Bytes()) if err != nil { rawConn.Close() return nil, nil, err } } bufferedReader := bufio.NewReader(rawConn) resp, err := http.ReadResponse(bufferedReader, req) if err != nil { rawConn.Close() return nil, nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { rawConn.Close() return nil, nil, newError("Proxy responded with non 200 code: " + resp.Status) } if bufferedReader.Buffered() > 0 { payload, err := buf.ReadFrom(io.LimitReader(bufferedReader, int64(bufferedReader.Buffered()))) if err != nil { return nil, nil, newError("unable to drain buffer: ").Base(err) } return rawConn, payload, nil } return rawConn, nil, 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) // nolint: bodyclose 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, nil, err } return proxyConn, nil, nil } } rawConn, err := dialer.Dial(ctx, dest) if err != nil { return nil, nil, err } iConn := rawConn if statConn, ok := iConn.(*internet.StatCouterConnection); ok { iConn = statConn.Connection } nextProto := "" if connALPNGetter, ok := iConn.(security.ConnectionApplicationProtocol); ok { nextProto, err = connALPNGetter.GetConnectionApplicationProtocol() if err != nil { rawConn.Close() return nil, nil, err } } 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, nil, err } proxyConn, err := connectHTTP2(rawConn, h2clientConn) if err != nil { rawConn.Close() return nil, nil, err } cachedH2Mutex.Lock() if cachedH2Conns == nil { cachedH2Conns = make(map[net.Destination]h2Conn) } cachedH2Conns[dest] = h2Conn{ rawConn: rawConn, h2Conn: h2clientConn, } cachedH2Mutex.Unlock() return proxyConn, nil, err default: return nil, 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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/config.go
proxy/http/config.go
package http import ( "github.com/v2fly/v2ray-core/v5/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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/server.go
proxy/http/server.go
package http import ( "bufio" "bytes" "context" "encoding/base64" "io" "net/http" "strings" "time" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" http_proto "github.com/v2fly/v2ray-core/v5/common/protocol/http" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/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, net.Network_UNIX} } 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() } 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\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, _ *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 } 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{} 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. Hence, request has to be closed later. defer common.Close(link.Writer) 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 := readResponseAndHandle100Continue(responseReader, request, writer) 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 } defer response.Body.Close() } 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 } // Sometimes, server might send 1xx response to client // it should not be processed by http proxy handler, just forward it to client func readResponseAndHandle100Continue(r *bufio.Reader, req *http.Request, writer io.Writer) (*http.Response, error) { // have a little look of response peekBytes, err := r.Peek(56) if err == nil || err == bufio.ErrBufferFull { str := string(peekBytes) ResponseLine := strings.Split(str, "\r\n")[0] _, status, _ := strings.Cut(ResponseLine, " ") // only handle 1xx response if strings.HasPrefix(status, "1") { ResponseHeader1xx := []byte{} // read until \r\n\r\n (end of http response header) for { data, err := r.ReadSlice('\n') if err != nil { return nil, newError("failed to read http 1xx response").Base(err).AtError() } ResponseHeader1xx = append(ResponseHeader1xx, data...) if bytes.Equal(ResponseHeader1xx[len(ResponseHeader1xx)-4:], []byte{'\r', '\n', '\r', '\n'}) { break } if len(ResponseHeader1xx) > 1024 { return nil, newError("too big http 1xx response").AtError() } } writer.Write(ResponseHeader1xx) } } return http.ReadResponse(r, req) } func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewServer(ctx, config.(*ServerConfig)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/http.go
proxy/http/http.go
package http //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/config.pb.go
proxy/http/config.pb.go
package http import ( protocol "github.com/v2fly/v2ray-core/v5/common/protocol" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) 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) ) type Account struct { state protoimpl.MessageState `protogen:"open.v1"` Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Account) Reset() { *x = Account{} 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 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 `protogen:"open.v1"` // Deprecated: Marked as deprecated in proxy/http/config.proto. 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" protobuf_val:"bytes,2,opt,name=value"` 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"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ServerConfig) Reset() { *x = ServerConfig{} 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 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: Marked as deprecated in proxy/http/config.proto. 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 `protogen:"open.v1"` // Sever is a list of HTTP server addresses. Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"` H1SkipWaitForReply bool `protobuf:"varint,2,opt,name=h1_skip_wait_for_reply,json=h1SkipWaitForReply,proto3" json:"h1_skip_wait_for_reply,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ClientConfig) Reset() { *x = ClientConfig{} 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 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 } func (x *ClientConfig) GetH1SkipWaitForReply() bool { if x != nil { return x.H1SkipWaitForReply } return false } var File_proxy_http_config_proto protoreflect.FileDescriptor const file_proxy_http_config_proto_rawDesc = "" + "\n" + "\x17proxy/http/config.proto\x12\x15v2ray.core.proxy.http\x1a!common/protocol/server_spec.proto\"A\n" + "\aAccount\x12\x1a\n" + "\busername\x18\x01 \x01(\tR\busername\x12\x1a\n" + "\bpassword\x18\x02 \x01(\tR\bpassword\"\x84\x02\n" + "\fServerConfig\x12\x1c\n" + "\atimeout\x18\x01 \x01(\rB\x02\x18\x01R\atimeout\x12M\n" + "\baccounts\x18\x02 \x03(\v21.v2ray.core.proxy.http.ServerConfig.AccountsEntryR\baccounts\x12+\n" + "\x11allow_transparent\x18\x03 \x01(\bR\x10allowTransparent\x12\x1d\n" + "\n" + "user_level\x18\x04 \x01(\rR\tuserLevel\x1a;\n" + "\rAccountsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x86\x01\n" + "\fClientConfig\x12B\n" + "\x06server\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server\x122\n" + "\x16h1_skip_wait_for_reply\x18\x02 \x01(\bR\x12h1SkipWaitForReplyB`\n" + "\x19com.v2ray.core.proxy.httpP\x01Z)github.com/v2fly/v2ray-core/v5/proxy/http\xaa\x02\x15V2Ray.Core.Proxy.Httpb\x06proto3" var ( file_proxy_http_config_proto_rawDescOnce sync.Once file_proxy_http_config_proto_rawDescData []byte ) 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(unsafe.Slice(unsafe.StringData(file_proxy_http_config_proto_rawDesc), len(file_proxy_http_config_proto_rawDesc))) }) 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 = []any{ (*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 } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_http_config_proto_rawDesc), len(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_goTypes = nil file_proxy_http_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/simplified/config.go
proxy/http/simplified/config.go
package simplified import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/proxy/http" ) func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedServer := config.(*ServerConfig) _ = simplifiedServer fullServer := &http.ServerConfig{} return common.CreateObject(ctx, fullServer) })) common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedClient := config.(*ClientConfig) fullClient := &http.ClientConfig{ Server: []*protocol.ServerEndpoint{ { Address: simplifiedClient.Address, Port: simplifiedClient.Port, }, }, H1SkipWaitForReply: simplifiedClient.H1SkipWaitForReply, } return common.CreateObject(ctx, fullClient) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/http/simplified/config.pb.go
proxy/http/simplified/config.pb.go
package simplified import ( net "github.com/v2fly/v2ray-core/v5/common/net" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) 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) ) type ServerConfig struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ServerConfig) Reset() { *x = ServerConfig{} mi := &file_proxy_http_simplified_config_proto_msgTypes[0] 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_simplified_config_proto_msgTypes[0] if 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_simplified_config_proto_rawDescGZIP(), []int{0} } type ClientConfig struct { state protoimpl.MessageState `protogen:"open.v1"` 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"` H1SkipWaitForReply bool `protobuf:"varint,3,opt,name=h1_skip_wait_for_reply,json=h1SkipWaitForReply,proto3" json:"h1_skip_wait_for_reply,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ClientConfig) Reset() { *x = ClientConfig{} mi := &file_proxy_http_simplified_config_proto_msgTypes[1] 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_simplified_config_proto_msgTypes[1] if 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_simplified_config_proto_rawDescGZIP(), []int{1} } func (x *ClientConfig) GetAddress() *net.IPOrDomain { if x != nil { return x.Address } return nil } func (x *ClientConfig) GetPort() uint32 { if x != nil { return x.Port } return 0 } func (x *ClientConfig) GetH1SkipWaitForReply() bool { if x != nil { return x.H1SkipWaitForReply } return false } var File_proxy_http_simplified_config_proto protoreflect.FileDescriptor const file_proxy_http_simplified_config_proto_rawDesc = "" + "\n" + "\"proxy/http/simplified/config.proto\x12 v2ray.core.proxy.http.simplified\x1a common/protoext/extensions.proto\x1a\x18common/net/address.proto\"#\n" + "\fServerConfig:\x13\x82\xb5\x18\x0f\n" + "\ainbound\x12\x04http\"\xad\x01\n" + "\fClientConfig\x12;\n" + "\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" + "\x04port\x18\x02 \x01(\rR\x04port\x122\n" + "\x16h1_skip_wait_for_reply\x18\x03 \x01(\bR\x12h1SkipWaitForReply:\x18\x82\xb5\x18\x14\n" + "\boutbound\x12\x04http\x90\xff)\x01B\x81\x01\n" + "$com.v2ray.core.proxy.http.simplifiedP\x01Z4github.com/v2fly/v2ray-core/v5/proxy/http/simplified\xaa\x02 V2Ray.Core.Proxy.Http.Simplifiedb\x06proto3" var ( file_proxy_http_simplified_config_proto_rawDescOnce sync.Once file_proxy_http_simplified_config_proto_rawDescData []byte ) func file_proxy_http_simplified_config_proto_rawDescGZIP() []byte { file_proxy_http_simplified_config_proto_rawDescOnce.Do(func() { file_proxy_http_simplified_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_http_simplified_config_proto_rawDesc), len(file_proxy_http_simplified_config_proto_rawDesc))) }) return file_proxy_http_simplified_config_proto_rawDescData } var file_proxy_http_simplified_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_http_simplified_config_proto_goTypes = []any{ (*ServerConfig)(nil), // 0: v2ray.core.proxy.http.simplified.ServerConfig (*ClientConfig)(nil), // 1: v2ray.core.proxy.http.simplified.ClientConfig (*net.IPOrDomain)(nil), // 2: v2ray.core.common.net.IPOrDomain } var file_proxy_http_simplified_config_proto_depIdxs = []int32{ 2, // 0: v2ray.core.proxy.http.simplified.ClientConfig.address:type_name -> v2ray.core.common.net.IPOrDomain 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_http_simplified_config_proto_init() } func file_proxy_http_simplified_config_proto_init() { if File_proxy_http_simplified_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_http_simplified_config_proto_rawDesc), len(file_proxy_http_simplified_config_proto_rawDesc)), NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_http_simplified_config_proto_goTypes, DependencyIndexes: file_proxy_http_simplified_config_proto_depIdxs, MessageInfos: file_proxy_http_simplified_config_proto_msgTypes, }.Build() File_proxy_http_simplified_config_proto = out.File file_proxy_http_simplified_config_proto_goTypes = nil file_proxy_http_simplified_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/vformat/main.go
infra/vformat/main.go
package main import ( "fmt" "go/build" "os" "os/exec" "path/filepath" "runtime" "strings" ) // envFile returns the name of the Go environment configuration file. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166 func envFile() (string, error) { if file := os.Getenv("GOENV"); file != "" { if file == "off" { return "", fmt.Errorf("GOENV=off") } return file, nil } dir, err := os.UserConfigDir() if err != nil { return "", err } if dir == "" { return "", fmt.Errorf("missing user-config dir") } return filepath.Join(dir, "go", "env"), nil } // GetRuntimeEnv returns the value of runtime environment variable, // that is set by running following command: `go env -w key=value`. func GetRuntimeEnv(key string) (string, error) { file, err := envFile() if err != nil { return "", err } if file == "" { return "", fmt.Errorf("missing runtime env file") } var data []byte var runtimeEnv string data, readErr := os.ReadFile(file) if readErr != nil { return "", readErr } envStrings := strings.Split(string(data), "\n") for _, envItem := range envStrings { envItem = strings.TrimSuffix(envItem, "\r") envKeyValue := strings.Split(envItem, "=") if len(envKeyValue) == 2 && strings.TrimSpace(envKeyValue[0]) == key { runtimeEnv = strings.TrimSpace(envKeyValue[1]) } } return runtimeEnv, nil } // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty. func GetGOBIN() string { // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command` GOBIN := os.Getenv("GOBIN") if GOBIN == "" { var err error // The one set by user by running `go env -w GOBIN=/path` GOBIN, err = GetRuntimeEnv("GOBIN") if err != nil { // The default one that Golang uses return filepath.Join(build.Default.GOPATH, "bin") } if GOBIN == "" { return filepath.Join(build.Default.GOPATH, "bin") } return GOBIN } return GOBIN } func Run(binary string, args []string) ([]byte, error) { cmd := exec.Command(binary, args...) cmd.Env = append(cmd.Env, os.Environ()...) output, cmdErr := cmd.CombinedOutput() if cmdErr != nil { return nil, cmdErr } return output, nil } func RunMany(binary string, args, files []string) { fmt.Println("Processing...") maxTasks := make(chan struct{}, runtime.NumCPU()) for _, file := range files { maxTasks <- struct{}{} go func(file string) { output, err := Run(binary, append(args, file)) if err != nil { fmt.Println(err) } else if len(output) > 0 { fmt.Println(string(output)) } <-maxTasks }(file) } } func main() { pwd, err := os.Getwd() if err != nil { fmt.Println("Can not get current working directory.") os.Exit(1) } GOBIN := GetGOBIN() binPath := os.Getenv("PATH") pathSlice := []string{pwd, GOBIN, binPath} binPath = strings.Join(pathSlice, string(os.PathListSeparator)) os.Setenv("PATH", binPath) suffix := "" if runtime.GOOS == "windows" { suffix = ".exe" } gofmt := "gofmt" + suffix goimports := "gci" + suffix if gofmtPath, err := exec.LookPath(gofmt); err != nil { fmt.Println("Can not find", gofmt, "in system path or current working directory.") os.Exit(1) } else { gofmt = gofmtPath } if goimportsPath, err := exec.LookPath(goimports); err != nil { fmt.Println("Can not find", goimports, "in system path or current working directory.") os.Exit(1) } else { goimports = goimportsPath } rawFilesSlice := make([]string, 0, 1000) 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, ".go") && !strings.HasSuffix(filename, ".pb.go") && !strings.Contains(dir, filepath.Join("testing", "mocks")) && !strings.Contains(path, filepath.Join("main", "distro", "all", "all.go")) { rawFilesSlice = append(rawFilesSlice, path) } return nil }) if walkErr != nil { fmt.Println(walkErr) os.Exit(1) } gofmtArgs := []string{ "-s", "-l", "-e", "-w", } goimportsArgs := []string{ "write", "--NoInlineComments", "--NoPrefixComments", "--Section", "Standard", "--Section", "Default", "--Section", "pkgPrefix(github.com/v2fly/v2ray-core)", } RunMany(gofmt, gofmtArgs, rawFilesSlice) RunMany(goimports, goimportsArgs, rawFilesSlice) fmt.Println("Do NOT forget to commit file changes.") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/vprotogen/main.go
infra/vprotogen/main.go
package main import ( "bufio" "bytes" "errors" "fmt" "go/build" "io" "net/http" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" ) // envFile returns the name of the Go environment configuration file. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166 func envFile() (string, error) { if file := os.Getenv("GOENV"); file != "" { if file == "off" { return "", fmt.Errorf("GOENV=off") } return file, nil } dir, err := os.UserConfigDir() if err != nil { return "", err } if dir == "" { return "", fmt.Errorf("missing user-config dir") } return filepath.Join(dir, "go", "env"), nil } // GetRuntimeEnv returns the value of runtime environment variable, // that is set by running following command: `go env -w key=value`. func GetRuntimeEnv(key string) (string, error) { file, err := envFile() if err != nil { return "", err } if file == "" { return "", fmt.Errorf("missing runtime env file") } var data []byte var runtimeEnv string data, readErr := os.ReadFile(file) if readErr != nil { return "", readErr } envStrings := strings.Split(string(data), "\n") for _, envItem := range envStrings { envItem = strings.TrimSuffix(envItem, "\r") envKeyValue := strings.Split(envItem, "=") if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) { runtimeEnv = strings.TrimSpace(envKeyValue[1]) } } return runtimeEnv, nil } // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty. func GetGOBIN() string { // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command` GOBIN := os.Getenv("GOBIN") if GOBIN == "" { var err error // The one set by user by running `go env -w GOBIN=/path` GOBIN, err = GetRuntimeEnv("GOBIN") if err != nil { // The default one that Golang uses return filepath.Join(build.Default.GOPATH, "bin") } if GOBIN == "" { return filepath.Join(build.Default.GOPATH, "bin") } return GOBIN } return GOBIN } func whichProtoc(suffix, targetedVersion string) (string, error) { protoc := "protoc" + suffix path, err := exec.LookPath(protoc) if err != nil { errStr := fmt.Sprintf(` Command "%s" not found. Make sure that %s is in your system path or current path. Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases `, protoc, protoc, protoc, targetedVersion) return "", fmt.Errorf("%v", errStr) } return path, nil } func getProjectProtocVersion(url string) (string, error) { resp, err := http.Get(url) if err != nil { return "", fmt.Errorf("can not get the version of protobuf used in V2Ray project") } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("can not read from body") } versionRegexp := regexp.MustCompile(`\/\/\s*protoc\s*v(\d+\.(\d+\.\d+))`) matched := versionRegexp.FindStringSubmatch(string(body)) return matched[2], nil } func getInstalledProtocVersion(protocPath string) (string, error) { cmd := exec.Command(protocPath, "--version") cmd.Env = append(cmd.Env, os.Environ()...) output, cmdErr := cmd.CombinedOutput() if cmdErr != nil { return "", cmdErr } versionRegexp := regexp.MustCompile(`protoc\s*(\d+\.\d+(\.\d)*)`) matched := versionRegexp.FindStringSubmatch(string(output)) installedVersion := "" if len(matched) == 0 { return "", errors.New("can not parse protoc version") } installedVersion += matched[1] fmt.Println("Using protoc version: " + installedVersion) return installedVersion, nil } func parseVersion(s string, width int) int64 { strList := strings.Split(s, ".") format := fmt.Sprintf("%%s%%0%ds", width) v := "" for _, value := range strList { v = fmt.Sprintf(format, v, value) } var result int64 var err error if result, err = strconv.ParseInt(v, 10, 64); err != nil { return 0 } return result } func needToUpdate(targetedVersion, installedVersion string) bool { vt := parseVersion(targetedVersion, 4) vi := parseVersion(installedVersion, 4) return vt > vi } func main() { pwd, err := os.Getwd() if err != nil { fmt.Println("Can not get current working directory.") os.Exit(1) } GOBIN := GetGOBIN() binPath := os.Getenv("PATH") pathSlice := []string{pwd, GOBIN, binPath} binPath = strings.Join(pathSlice, string(os.PathListSeparator)) os.Setenv("PATH", binPath) suffix := "" if runtime.GOOS == "windows" { suffix = ".exe" } targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/v2fly/v2ray-core/HEAD/config.pb.go") if err != nil { fmt.Println(err) os.Exit(1) } protoc, err := whichProtoc(suffix, targetedVersion) if err != nil { fmt.Println(err) os.Exit(1) } installedVersion, err := getInstalledProtocVersion(protoc) if err != nil { fmt.Println(err) os.Exit(1) } if needToUpdate(targetedVersion, installedVersion) { fmt.Printf(` You are using an old protobuf version, please update to v%s or later. Download it from https://github.com/protocolbuffers/protobuf/releases * Protobuf version used in V2Ray project: v%s * Protobuf version you have installed: v%s `, targetedVersion, targetedVersion, installedVersion) os.Exit(1) } 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") && filename != "typed_message.proto" && filename != "descriptor.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 { args := []string{ "-I", fmt.Sprintf("%v/../include", filepath.Dir(protoc)), "-I", ".", "--go_out", pwd, "--go_opt", "paths=source_relative", "--go-grpc_out", pwd, "--go-grpc_opt", "paths=source_relative", "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix), "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix), } args = append(args, relProtoFile) cmd := exec.Command(protoc, args...) cmd.Env = append(cmd.Env, os.Environ()...) output, cmdErr := cmd.CombinedOutput() if len(output) > 0 { fmt.Println(string(output)) } if cmdErr != nil { fmt.Println(cmdErr) os.Exit(1) } } } normalizeWalkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return err } if info.IsDir() { return nil } filename := filepath.Base(path) if strings.HasSuffix(filename, ".pb.go") && path != "config.pb.go" { if err := NormalizeGeneratedProtoFile(path); err != nil { fmt.Println(err) os.Exit(1) } } return nil }) if normalizeWalkErr != nil { fmt.Println(normalizeWalkErr) os.Exit(1) } } func NormalizeGeneratedProtoFile(path string) error { fd, err := os.OpenFile(path, os.O_RDWR, 0o644) if err != nil { return err } _, err = fd.Seek(0, os.SEEK_SET) if err != nil { return err } out := bytes.NewBuffer(nil) scanner := bufio.NewScanner(fd) valid := false for scanner.Scan() { if !valid && !strings.HasPrefix(scanner.Text(), "package ") { continue } valid = true out.Write(scanner.Bytes()) out.Write([]byte("\n")) } _, err = fd.Seek(0, os.SEEK_SET) if err != nil { return err } err = fd.Truncate(0) if err != nil { return err } _, err = io.Copy(fd, bytes.NewReader(out.Bytes())) if err != nil { return err } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/reverse.go
infra/conf/v4/reverse.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/socks.go
infra/conf/v4/socks.go
package v4 import ( "encoding/json" "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/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 *cfgcommon.Address `json:"ip"` Timeout uint32 `json:"timeout"` UserLevel uint32 `json:"userLevel"` PacketEncoding string `json:"packetEncoding"` } 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 switch v.PacketEncoding { case "Packet": config.PacketEncoding = packetaddr.PacketAddrType_Packet case "", "None": config.PacketEncoding = packetaddr.PacketAddrType_None } return config, nil } type SocksRemoteConfig struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } type SocksClientConfig struct { Servers []*SocksRemoteConfig `json:"servers"` Version string `json:"version"` } func (v *SocksClientConfig) Build() (proto.Message, error) { config := new(socks.ClientConfig) config.Server = make([]*protocol.ServerEndpoint, len(v.Servers)) switch strings.ToLower(v.Version) { case "4": config.Version = socks.Version_SOCKS4 case "4a": config.Version = socks.Version_SOCKS4A case "", "5": config.Version = socks.Version_SOCKS5 default: return nil, newError("failed to parse socks server version: ", v.Version).AtError() } 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() } if config.Version != socks.Version_SOCKS5 && account.Password != "" { return nil, newError("password is only supported in socks5").AtError() } user.Account = serial.ToTypedMessage(account.Build()) server.User = append(server.User, user) } config.Server[idx] = server } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/policy.go
infra/conf/v4/policy.go
package v4 import ( "github.com/v2fly/v2ray-core/v5/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"` OverrideAccessLogDest bool `json:"overrideAccessLogDest"` } 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, }, OverrideAccessLogDest: p.OverrideAccessLogDest, }, 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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/gun.go
infra/conf/v4/gun.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/transport/internet/grpc" ) type GunConfig struct { ServiceName string `json:"serviceName"` } func (g GunConfig) Build() (proto.Message, error) { return &grpc.Config{ServiceName: g.ServiceName}, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/vmess.go
infra/conf/v4/vmess.go
package v4 import ( "encoding/json" "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound" "github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound" ) type VMessAccount struct { ID string `json:"id"` AlterIds uint16 `json:"alterId"` Security string `json:"security"` Experiments string `json:"experiments"` } // 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 case "zero": st = protocol.SecurityType_ZERO default: st = protocol.SecurityType_AUTO } return &vmess.Account{ Id: a.ID, AlterId: uint32(a.AlterIds), SecuritySettings: &protocol.SecurityConfig{ Type: st, }, TestsEnabled: a.Experiments, } } 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) 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 *cfgcommon.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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/api.go
infra/conf/v4/api.go
package v4 import ( "strings" "github.com/jhump/protoreflect/desc" "github.com/jhump/protoreflect/dynamic" "google.golang.org/protobuf/types/known/anypb" "github.com/v2fly/v2ray-core/v5/app/commander" loggerservice "github.com/v2fly/v2ray-core/v5/app/log/command" observatoryservice "github.com/v2fly/v2ray-core/v5/app/observatory/command" handlerservice "github.com/v2fly/v2ray-core/v5/app/proxyman/command" routerservice "github.com/v2fly/v2ray-core/v5/app/router/command" statsservice "github.com/v2fly/v2ray-core/v5/app/stats/command" "github.com/v2fly/v2ray-core/v5/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([]*anypb.Any, 0, 16) for _, s := range c.Services { switch strings.ToLower(s) { case "reflectionservice": services = append(services, serial.ToTypedMessage(&commander.ReflectionConfig{})) 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{})) case "observatoryservice": services = append(services, serial.ToTypedMessage(&observatoryservice.Config{})) case "routingservice": services = append(services, serial.ToTypedMessage(&routerservice.Config{})) default: if !strings.HasPrefix(s, "#") { continue } message, err := desc.LoadMessageDescriptor(s[1:]) if err != nil || message == nil { return nil, newError("Cannot find API", s, "").Base(err) } serviceConfig := dynamic.NewMessage(message) services = append(services, serial.ToTypedMessage(serviceConfig)) } } return &commander.Config{ Tag: c.Tag, Service: services, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/policy_test.go
infra/conf/v4/policy_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" ) 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 := c.Input pConf := v4.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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/errors.generated.go
infra/conf/v4/errors.generated.go
package v4 import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/vless_test.go
infra/conf/v4/vless_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/vless" "github.com/v2fly/v2ray-core/v5/proxy/vless/inbound" "github.com/v2fly/v2ray-core/v5/proxy/vless/outbound" ) func TestVLessOutbound(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.VLessOutboundConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "vnext": [{ "address": "example.com", "port": 443, "users": [ { "id": "27848739-7e62-4138-9fd3-098a63964b6b", "encryption": "none", "level": 0 } ] }] }`, Parser: testassist.LoadJSON(creator), Output: &outbound.Config{ Vnext: []*protocol.ServerEndpoint{ { Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Domain{ Domain: "example.com", }, }, Port: 443, User: []*protocol.User{ { Account: serial.ToTypedMessage(&vless.Account{ Id: "27848739-7e62-4138-9fd3-098a63964b6b", Encryption: "none", }), Level: 0, }, }, }, }, }, }, }) } func TestVLessInbound(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.VLessInboundConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "clients": [ { "id": "27848739-7e62-4138-9fd3-098a63964b6b", "level": 0, "email": "love@v2fly.org" } ], "decryption": "none", "fallbacks": [ { "dest": 80 }, { "alpn": "h2", "dest": "@/dev/shm/domain.socket", "xver": 2 }, { "path": "/innerws", "dest": "serve-ws-none" } ] }`, Parser: testassist.LoadJSON(creator), Output: &inbound.Config{ Clients: []*protocol.User{ { Account: serial.ToTypedMessage(&vless.Account{ Id: "27848739-7e62-4138-9fd3-098a63964b6b", }), Level: 0, Email: "love@v2fly.org", }, }, Decryption: "none", Fallbacks: []*inbound.Fallback{ { Alpn: "", Path: "", Type: "tcp", Dest: "127.0.0.1:80", Xver: 0, }, { Alpn: "h2", Path: "", Type: "unix", Dest: "@/dev/shm/domain.socket", Xver: 2, }, { Alpn: "", Path: "/innerws", Type: "serve", Dest: "serve-ws-none", Xver: 0, }, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/transport_test.go
infra/conf/v4/transport_test.go
package v4_test import ( "encoding/json" "testing" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/socketcfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/http" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/noop" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/tls" "github.com/v2fly/v2ray-core/v5/transport/internet/kcp" "github.com/v2fly/v2ray-core/v5/transport/internet/quic" "github.com/v2fly/v2ray-core/v5/transport/internet/tcp" "github.com/v2fly/v2ray-core/v5/transport/internet/websocket" ) func TestSocketConfig(t *testing.T) { createParser := func() func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { config := new(socketcfg.SocketConfig) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "mark": 1, "tcpFastOpen": true, "tcpFastOpenQueueLength": 1024, "mptcp": true }`, Parser: createParser(), Output: &internet.SocketConfig{ Mark: 1, Tfo: internet.SocketConfig_Enable, TfoQueueLength: 1024, Mptcp: internet.MPTCPState_Enable, }, }, }) } func TestTransportConfig(t *testing.T) { createParser := func() func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { config := new(v4.TransportConfig) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "tcpSettings": { "header": { "type": "http", "request": { "version": "1.1", "method": "GET", "path": "/b", "headers": { "a": "b", "c": "d" } }, "response": { "version": "1.0", "status": "404", "reason": "Not Found" } } }, "kcpSettings": { "mtu": 1200, "header": { "type": "none" } }, "wsSettings": { "path": "/t" }, "quicSettings": { "key": "abcd", "header": { "type": "dtls" } } }`, Parser: createParser(), Output: &transport.Config{ TransportSettings: []*internet.TransportConfig{ { ProtocolName: "tcp", Settings: serial.ToTypedMessage(&tcp.Config{ HeaderSettings: serial.ToTypedMessage(&http.Config{ Request: &http.RequestConfig{ Version: &http.Version{Value: "1.1"}, Method: &http.Method{Value: "GET"}, Uri: []string{"/b"}, Header: []*http.Header{ {Name: "a", Value: []string{"b"}}, {Name: "c", Value: []string{"d"}}, }, }, Response: &http.ResponseConfig{ Version: &http.Version{Value: "1.0"}, Status: &http.Status{Code: "404", Reason: "Not Found"}, Header: []*http.Header{ { Name: "Content-Type", Value: []string{"application/octet-stream", "video/mpeg"}, }, { Name: "Transfer-Encoding", Value: []string{"chunked"}, }, { Name: "Connection", Value: []string{"keep-alive"}, }, { Name: "Pragma", Value: []string{"no-cache"}, }, { Name: "Cache-Control", Value: []string{"private", "no-cache"}, }, }, }, }), }), }, { ProtocolName: "mkcp", Settings: serial.ToTypedMessage(&kcp.Config{ Mtu: &kcp.MTU{Value: 1200}, HeaderConfig: serial.ToTypedMessage(&noop.Config{}), }), }, { ProtocolName: "websocket", Settings: serial.ToTypedMessage(&websocket.Config{ Path: "/t", }), }, { ProtocolName: "quic", Settings: serial.ToTypedMessage(&quic.Config{ Key: "abcd", Security: &protocol.SecurityConfig{ Type: protocol.SecurityType_NONE, }, Header: serial.ToTypedMessage(&tls.PacketConfig{}), }), }, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/shadowsocks.go
infra/conf/v4/shadowsocks.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks" ) type ShadowsocksServerConfig struct { Cipher string `json:"method"` Password string `json:"password"` UDP bool `json:"udp"` Level byte `json:"level"` Email string `json:"email"` NetworkList *cfgcommon.NetworkList `json:"network"` IVCheck bool `json:"ivCheck"` PacketEncoding string `json:"packetEncoding"` } func (v *ShadowsocksServerConfig) Build() (proto.Message, error) { config := new(shadowsocks.ServerConfig) config.UdpEnabled = v.UDP config.Network = v.NetworkList.Build() if v.Password == "" { return nil, newError("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ Password: v.Password, IvCheck: v.IVCheck, } account.CipherType = shadowsocks.CipherFromString(v.Cipher) if account.CipherType == shadowsocks.CipherType_UNKNOWN { return nil, newError("unknown cipher method: ", v.Cipher) } config.User = &protocol.User{ Email: v.Email, Level: uint32(v.Level), Account: serial.ToTypedMessage(account), } switch v.PacketEncoding { case "Packet": config.PacketEncoding = packetaddr.PacketAddrType_Packet case "", "None": config.PacketEncoding = packetaddr.PacketAddrType_None } return config, nil } type ShadowsocksServerTarget struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Cipher string `json:"method"` Password string `json:"password"` Email string `json:"email"` Ota bool `json:"ota"` Level byte `json:"level"` IVCheck bool `json:"ivCheck"` } type ShadowsocksClientConfig struct { Servers []*ShadowsocksServerTarget `json:"servers"` } func (v *ShadowsocksClientConfig) Build() (proto.Message, error) { config := new(shadowsocks.ClientConfig) if len(v.Servers) == 0 { return nil, newError("0 Shadowsocks server configured.") } serverSpecs := make([]*protocol.ServerEndpoint, len(v.Servers)) for idx, server := range v.Servers { if server.Address == nil { return nil, newError("Shadowsocks server address is not set.") } if server.Port == 0 { return nil, newError("Invalid Shadowsocks port.") } if server.Password == "" { return nil, newError("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ Password: server.Password, } account.CipherType = shadowsocks.CipherFromString(server.Cipher) if account.CipherType == shadowsocks.CipherType_UNKNOWN { return nil, newError("unknown cipher method: ", server.Cipher) } account.IvCheck = server.IVCheck ss := &protocol.ServerEndpoint{ Address: server.Address.Build(), Port: uint32(server.Port), User: []*protocol.User{ { Level: uint32(server.Level), Email: server.Email, Account: serial.ToTypedMessage(account), }, }, } serverSpecs[idx] = ss } config.Server = serverSpecs return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/loopback.go
infra/conf/v4/loopback.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/proxy/loopback" ) type LoopbackConfig struct { InboundTag string `json:"inboundTag"` } func (l LoopbackConfig) Build() (proto.Message, error) { return &loopback.Config{InboundTag: l.InboundTag}, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/browser_forwarder.go
infra/conf/v4/browser_forwarder.go
package v4 import ( "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/browserforwarder" ) type BrowserForwarderConfig struct { ListenAddr string `json:"listenAddr"` ListenPort int32 `json:"listenPort"` } func (b *BrowserForwarderConfig) Build() (proto.Message, error) { b.ListenAddr = strings.TrimSpace(b.ListenAddr) if b.ListenAddr != "" && b.ListenPort == 0 { b.ListenPort = 54321 } return &browserforwarder.Config{ ListenAddr: b.ListenAddr, ListenPort: b.ListenPort, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/transport_internet.go
infra/conf/v4/transport_internet.go
package v4 import ( "encoding/json" "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/loader" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/socketcfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/tlscfg" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/domainsocket" httpheader "github.com/v2fly/v2ray-core/v5/transport/internet/headers/http" "github.com/v2fly/v2ray-core/v5/transport/internet/http" "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2" "github.com/v2fly/v2ray-core/v5/transport/internet/kcp" "github.com/v2fly/v2ray-core/v5/transport/internet/quic" "github.com/v2fly/v2ray-core/v5/transport/internet/tcp" "github.com/v2fly/v2ray-core/v5/transport/internet/websocket" ) var ( kcpHeaderLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{ "none": func() interface{} { return new(NoOpAuthenticator) }, "srtp": func() interface{} { return new(SRTPAuthenticator) }, "utp": func() interface{} { return new(UTPAuthenticator) }, "wechat-video": func() interface{} { return new(WechatVideoAuthenticator) }, "dtls": func() interface{} { return new(DTLSAuthenticator) }, "wireguard": func() interface{} { return new(WireguardAuthenticator) }, }, "type", "") tcpHeaderLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{ "none": func() interface{} { return new(NoOpConnectionAuthenticator) }, "http": func() interface{} { return new(Authenticator) }, }, "type", "") ) type KCPConfig struct { Mtu *uint32 `json:"mtu"` Tti *uint32 `json:"tti"` UpCap *uint32 `json:"uplinkCapacity"` DownCap *uint32 `json:"downlinkCapacity"` Congestion *bool `json:"congestion"` ReadBufferSize *uint32 `json:"readBufferSize"` WriteBufferSize *uint32 `json:"writeBufferSize"` HeaderConfig json.RawMessage `json:"header"` Seed *string `json:"seed"` } // Build implements Buildable. func (c *KCPConfig) Build() (proto.Message, error) { config := new(kcp.Config) if c.Mtu != nil { mtu := *c.Mtu if mtu < 576 || mtu > 1460 { return nil, newError("invalid mKCP MTU size: ", mtu).AtError() } config.Mtu = &kcp.MTU{Value: mtu} } if c.Tti != nil { tti := *c.Tti if tti < 10 || tti > 100 { return nil, newError("invalid mKCP TTI: ", tti).AtError() } config.Tti = &kcp.TTI{Value: tti} } if c.UpCap != nil { config.UplinkCapacity = &kcp.UplinkCapacity{Value: *c.UpCap} } if c.DownCap != nil { config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *c.DownCap} } if c.Congestion != nil { config.Congestion = *c.Congestion } if c.ReadBufferSize != nil { size := *c.ReadBufferSize if size > 0 { config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024} } else { config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024} } } if c.WriteBufferSize != nil { size := *c.WriteBufferSize if size > 0 { config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024} } else { config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024} } } if len(c.HeaderConfig) > 0 { headerConfig, _, err := kcpHeaderLoader.Load(c.HeaderConfig) if err != nil { return nil, newError("invalid mKCP header config.").Base(err).AtError() } ts, err := headerConfig.(cfgcommon.Buildable).Build() if err != nil { return nil, newError("invalid mKCP header config").Base(err).AtError() } config.HeaderConfig = serial.ToTypedMessage(ts) } if c.Seed != nil { config.Seed = &kcp.EncryptionSeed{Seed: *c.Seed} } return config, nil } type TCPConfig struct { HeaderConfig json.RawMessage `json:"header"` AcceptProxyProtocol bool `json:"acceptProxyProtocol"` } // Build implements Buildable. func (c *TCPConfig) Build() (proto.Message, error) { config := new(tcp.Config) if len(c.HeaderConfig) > 0 { headerConfig, _, err := tcpHeaderLoader.Load(c.HeaderConfig) if err != nil { return nil, newError("invalid TCP header config").Base(err).AtError() } ts, err := headerConfig.(cfgcommon.Buildable).Build() if err != nil { return nil, newError("invalid TCP header config").Base(err).AtError() } config.HeaderSettings = serial.ToTypedMessage(ts) } if c.AcceptProxyProtocol { config.AcceptProxyProtocol = c.AcceptProxyProtocol } return config, nil } type Hy2ConfigCongestion struct { Type string `json:"type"` UpMbps uint64 `json:"up_mbps"` DownMbps uint64 `json:"down_mbps"` } type Hy2Config struct { Password string `json:"password"` Congestion Hy2ConfigCongestion `json:"congestion"` UseUDPExtension bool `json:"use_udp_extension"` IgnoreClientBandwidth bool `json:"ignore_client_bandwidth"` } // Build implements Buildable. func (c *Hy2Config) Build() (proto.Message, error) { return &hysteria2.Config{ Password: c.Password, Congestion: &hysteria2.Congestion{ Type: c.Congestion.Type, DownMbps: c.Congestion.DownMbps, UpMbps: c.Congestion.UpMbps, }, UseUdpExtension: c.UseUDPExtension, IgnoreClientBandwidth: c.IgnoreClientBandwidth, }, nil } type WebSocketConfig struct { Path string `json:"path"` Headers map[string]string `json:"headers"` AcceptProxyProtocol bool `json:"acceptProxyProtocol"` MaxEarlyData int32 `json:"maxEarlyData"` UseBrowserForwarding bool `json:"useBrowserForwarding"` EarlyDataHeaderName string `json:"earlyDataHeaderName"` } // Build implements Buildable. func (c *WebSocketConfig) Build() (proto.Message, error) { path := c.Path header := make([]*websocket.Header, 0, 32) for key, value := range c.Headers { header = append(header, &websocket.Header{ Key: key, Value: value, }) } config := &websocket.Config{ Path: path, Header: header, MaxEarlyData: c.MaxEarlyData, UseBrowserForwarding: c.UseBrowserForwarding, EarlyDataHeaderName: c.EarlyDataHeaderName, } if c.AcceptProxyProtocol { config.AcceptProxyProtocol = c.AcceptProxyProtocol } return config, nil } type HTTPConfig struct { Host *cfgcommon.StringList `json:"host"` Path string `json:"path"` Method string `json:"method"` Headers map[string]*cfgcommon.StringList `json:"headers"` } // Build implements Buildable. func (c *HTTPConfig) Build() (proto.Message, error) { config := &http.Config{ Path: c.Path, } if c.Host != nil { config.Host = []string(*c.Host) } if c.Method != "" { config.Method = c.Method } if len(c.Headers) > 0 { config.Header = make([]*httpheader.Header, 0, len(c.Headers)) headerNames := sortMapKeys(c.Headers) for _, key := range headerNames { value := c.Headers[key] if value == nil { return nil, newError("empty HTTP header value: " + key).AtError() } config.Header = append(config.Header, &httpheader.Header{ Name: key, Value: append([]string(nil), (*value)...), }) } } return config, nil } type QUICConfig struct { Header json.RawMessage `json:"header"` Security string `json:"security"` Key string `json:"key"` } // Build implements Buildable. func (c *QUICConfig) Build() (proto.Message, error) { config := &quic.Config{ Key: c.Key, } if len(c.Header) > 0 { headerConfig, _, err := kcpHeaderLoader.Load(c.Header) if err != nil { return nil, newError("invalid QUIC header config.").Base(err).AtError() } ts, err := headerConfig.(cfgcommon.Buildable).Build() if err != nil { return nil, newError("invalid QUIC header config").Base(err).AtError() } config.Header = serial.ToTypedMessage(ts) } var st protocol.SecurityType switch strings.ToLower(c.Security) { case "aes-128-gcm": st = protocol.SecurityType_AES128_GCM case "chacha20-poly1305": st = protocol.SecurityType_CHACHA20_POLY1305 default: st = protocol.SecurityType_NONE } config.Security = &protocol.SecurityConfig{ Type: st, } return config, nil } type DomainSocketConfig struct { Path string `json:"path"` Abstract bool `json:"abstract"` Padding bool `json:"padding"` } // Build implements Buildable. func (c *DomainSocketConfig) Build() (proto.Message, error) { return &domainsocket.Config{ Path: c.Path, Abstract: c.Abstract, Padding: c.Padding, }, nil } type TransportProtocol string // Build implements Buildable. func (p TransportProtocol) Build() (string, error) { switch strings.ToLower(string(p)) { case "tcp": return "tcp", nil case "kcp", "mkcp": return "mkcp", nil case "ws", "websocket": return "websocket", nil case "h2", "http": return "http", nil case "ds", "domainsocket": return "domainsocket", nil case "quic": return "quic", nil case "gun", "grpc": return "gun", nil case "hy2", "hysteria2": return "hysteria2", nil default: return "", newError("Config: unknown transport protocol: ", p) } } type StreamConfig struct { Network *TransportProtocol `json:"network"` Security string `json:"security"` TLSSettings *tlscfg.TLSConfig `json:"tlsSettings"` TCPSettings *TCPConfig `json:"tcpSettings"` KCPSettings *KCPConfig `json:"kcpSettings"` WSSettings *WebSocketConfig `json:"wsSettings"` HTTPSettings *HTTPConfig `json:"httpSettings"` DSSettings *DomainSocketConfig `json:"dsSettings"` QUICSettings *QUICConfig `json:"quicSettings"` GunSettings *GunConfig `json:"gunSettings"` GRPCSettings *GunConfig `json:"grpcSettings"` Hy2Settings *Hy2Config `json:"hy2Settings"` SocketSettings *socketcfg.SocketConfig `json:"sockopt"` } // Build implements Buildable. func (c *StreamConfig) Build() (*internet.StreamConfig, error) { config := &internet.StreamConfig{ ProtocolName: "tcp", } if c.Network != nil { protocol, err := c.Network.Build() if err != nil { return nil, err } config.ProtocolName = protocol } if strings.EqualFold(c.Security, "tls") { tlsSettings := c.TLSSettings if tlsSettings == nil { tlsSettings = &tlscfg.TLSConfig{} } ts, err := tlsSettings.Build() if err != nil { return nil, newError("Failed to build TLS config.").Base(err) } tm := serial.ToTypedMessage(ts) config.SecuritySettings = append(config.SecuritySettings, tm) config.SecurityType = serial.V2Type(tm) } if c.TCPSettings != nil { ts, err := c.TCPSettings.Build() if err != nil { return nil, newError("Failed to build TCP config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "tcp", Settings: serial.ToTypedMessage(ts), }) } if c.KCPSettings != nil { ts, err := c.KCPSettings.Build() if err != nil { return nil, newError("Failed to build mKCP config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "mkcp", Settings: serial.ToTypedMessage(ts), }) } if c.WSSettings != nil { ts, err := c.WSSettings.Build() if err != nil { return nil, newError("Failed to build WebSocket config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "websocket", Settings: serial.ToTypedMessage(ts), }) } if c.HTTPSettings != nil { ts, err := c.HTTPSettings.Build() if err != nil { return nil, newError("Failed to build HTTP config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "http", Settings: serial.ToTypedMessage(ts), }) } if c.DSSettings != nil { ds, err := c.DSSettings.Build() if err != nil { return nil, newError("Failed to build DomainSocket config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "domainsocket", Settings: serial.ToTypedMessage(ds), }) } if c.QUICSettings != nil { qs, err := c.QUICSettings.Build() if err != nil { return nil, newError("Failed to build QUIC config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "quic", Settings: serial.ToTypedMessage(qs), }) } if c.GunSettings == nil { c.GunSettings = c.GRPCSettings } if c.GunSettings != nil { gs, err := c.GunSettings.Build() if err != nil { return nil, newError("Failed to build Gun config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "gun", Settings: serial.ToTypedMessage(gs), }) } if c.Hy2Settings != nil { hy2, err := c.Hy2Settings.Build() if err != nil { return nil, newError("Failed to build hy2 config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "hysteria2", Settings: serial.ToTypedMessage(hy2), }) } if c.SocketSettings != nil { ss, err := c.SocketSettings.Build() if err != nil { return nil, newError("Failed to build sockopt.").Base(err) } config.SocketSettings = ss } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/dns_proxy_test.go
infra/conf/v4/dns_proxy_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/dns" ) func TestDnsProxyConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.DNSOutboundConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "address": "8.8.8.8", "port": 53, "network": "tcp" }`, Parser: testassist.LoadJSON(creator), Output: &dns.Config{ Server: &net.Endpoint{ Network: net.Network_TCP, Address: net.NewIPOrDomain(net.IPAddress([]byte{8, 8, 8, 8})), Port: 53, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/vless.go
infra/conf/v4/vless.go
package v4 import ( "encoding/json" "path/filepath" "runtime" "strconv" "strings" "syscall" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/vless" "github.com/v2fly/v2ray-core/v5/proxy/vless/inbound" "github.com/v2fly/v2ray-core/v5/proxy/vless/outbound" ) type VLessInboundFallback struct { Alpn string `json:"alpn"` Path string `json:"path"` Type string `json:"type"` Dest json.RawMessage `json:"dest"` Xver uint64 `json:"xver"` } type VLessInboundConfig struct { Clients []json.RawMessage `json:"clients"` Decryption string `json:"decryption"` Fallback json.RawMessage `json:"fallback"` Fallbacks []*VLessInboundFallback `json:"fallbacks"` } // Build implements Buildable func (c *VLessInboundConfig) Build() (proto.Message, error) { config := new(inbound.Config) config.Clients = make([]*protocol.User, len(c.Clients)) for idx, rawUser := range c.Clients { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, newError(`VLESS clients: invalid user`).Base(err) } account := new(vless.Account) if err := json.Unmarshal(rawUser, account); err != nil { return nil, newError(`VLESS clients: invalid user`).Base(err) } if account.Encryption != "" { return nil, newError(`VLESS clients: "encryption" should not in inbound settings`) } user.Account = serial.ToTypedMessage(account) config.Clients[idx] = user } if c.Decryption != "none" { return nil, newError(`VLESS settings: please add/set "decryption":"none" to every settings`) } config.Decryption = c.Decryption if c.Fallback != nil { return nil, newError(`VLESS settings: please use "fallbacks":[{}] instead of "fallback":{}`) } for _, fb := range c.Fallbacks { var i uint16 var s string if err := json.Unmarshal(fb.Dest, &i); err == nil { s = strconv.Itoa(int(i)) } else { _ = json.Unmarshal(fb.Dest, &s) } config.Fallbacks = append(config.Fallbacks, &inbound.Fallback{ Alpn: fb.Alpn, Path: fb.Path, Type: fb.Type, Dest: s, Xver: fb.Xver, }) } for _, fb := range config.Fallbacks { /* if fb.Alpn == "h2" && fb.Path != "" { return nil, newError(`VLESS fallbacks: "alpn":"h2" doesn't support "path"`) } */ if fb.Path != "" && fb.Path[0] != '/' { return nil, newError(`VLESS fallbacks: "path" must be empty or start with "/"`) } if fb.Type == "" && fb.Dest != "" { if fb.Dest == "serve-ws-none" { // nolint:gocritic fb.Type = "serve" } else if filepath.IsAbs(fb.Dest) || fb.Dest[0] == '@' { fb.Type = "unix" if strings.HasPrefix(fb.Dest, "@@") && (runtime.GOOS == "linux" || runtime.GOOS == "android") { fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path)) // may need padding to work with haproxy copy(fullAddr, fb.Dest[1:]) fb.Dest = string(fullAddr) } } else { if _, err := strconv.Atoi(fb.Dest); err == nil { fb.Dest = "127.0.0.1:" + fb.Dest } if _, _, err := net.SplitHostPort(fb.Dest); err == nil { fb.Type = "tcp" } } } if fb.Type == "" { return nil, newError(`VLESS fallbacks: please fill in a valid value for every "dest"`) } if fb.Xver > 2 { return nil, newError(`VLESS fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`) } } return config, nil } type VLessOutboundVnext struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } type VLessOutboundConfig struct { Vnext []*VLessOutboundVnext `json:"vnext"` } // Build implements Buildable func (c *VLessOutboundConfig) Build() (proto.Message, error) { config := new(outbound.Config) if len(c.Vnext) == 0 { return nil, newError(`VLESS settings: "vnext" is empty`) } config.Vnext = make([]*protocol.ServerEndpoint, len(c.Vnext)) for idx, rec := range c.Vnext { if rec.Address == nil { return nil, newError(`VLESS vnext: "address" is not set`) } if len(rec.Users) == 0 { return nil, newError(`VLESS vnext: "users" is empty`) } spec := &protocol.ServerEndpoint{ Address: rec.Address.Build(), Port: uint32(rec.Port), User: make([]*protocol.User, len(rec.Users)), } for idx, rawUser := range rec.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, newError(`VLESS users: invalid user`).Base(err) } account := new(vless.Account) if err := json.Unmarshal(rawUser, account); err != nil { return nil, newError(`VLESS users: invalid user`).Base(err) } if account.Encryption != "none" { return nil, newError(`VLESS users: please add/set "encryption":"none" for every user`) } user.Account = serial.ToTypedMessage(account) spec.User[idx] = user } config.Vnext[idx] = spec } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/v2ray.go
infra/conf/v4/v2ray.go
package v4 import ( "context" "encoding/json" "fmt" "path/filepath" "strings" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/dispatcher" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/app/stats" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/loader" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/muxcfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/proxycfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/sniffer" "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/dns" "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/log" "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/router" "github.com/v2fly/v2ray-core/v5/infra/conf/v5cfg" ) var ( inboundConfigLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{ "dokodemo-door": func() interface{} { return new(DokodemoConfig) }, "http": func() interface{} { return new(HTTPServerConfig) }, "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) }, "socks": func() interface{} { return new(SocksServerConfig) }, "vless": func() interface{} { return new(VLessInboundConfig) }, "vmess": func() interface{} { return new(VMessInboundConfig) }, "trojan": func() interface{} { return new(TrojanServerConfig) }, "hysteria2": func() interface{} { return new(Hysteria2ServerConfig) }, }, "protocol", "settings") outboundConfigLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{ "blackhole": func() interface{} { return new(BlackholeConfig) }, "freedom": func() interface{} { return new(FreedomConfig) }, "http": func() interface{} { return new(HTTPClientConfig) }, "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) }, "socks": func() interface{} { return new(SocksClientConfig) }, "vless": func() interface{} { return new(VLessOutboundConfig) }, "vmess": func() interface{} { return new(VMessOutboundConfig) }, "trojan": func() interface{} { return new(TrojanClientConfig) }, "hysteria2": func() interface{} { return new(Hysteria2ClientConfig) }, "dns": func() interface{} { return new(DNSOutboundConfig) }, "loopback": func() interface{} { return new(LoopbackConfig) }, }, "protocol", "settings") ) func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) { kp := make([]proxyman.KnownProtocols, 0, 8) for _, p := range s { switch strings.ToLower(p) { case "http": kp = append(kp, proxyman.KnownProtocols_HTTP) case "https", "tls", "ssl": kp = append(kp, proxyman.KnownProtocols_TLS) default: return nil, newError("Unknown protocol: ", p) } } return kp, nil } type InboundDetourAllocationConfig struct { Strategy string `json:"strategy"` Concurrency *uint32 `json:"concurrency"` RefreshMin *uint32 `json:"refresh"` } // Build implements Buildable. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) { config := new(proxyman.AllocationStrategy) switch strings.ToLower(c.Strategy) { case "always": config.Type = proxyman.AllocationStrategy_Always case "random": config.Type = proxyman.AllocationStrategy_Random case "external": config.Type = proxyman.AllocationStrategy_External default: return nil, newError("unknown allocation strategy: ", c.Strategy) } if c.Concurrency != nil { config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{ Value: *c.Concurrency, } } if c.RefreshMin != nil { config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{ Value: *c.RefreshMin, } } return config, nil } type InboundDetourConfig struct { Protocol string `json:"protocol"` PortRange *cfgcommon.PortRange `json:"port"` ListenOn *cfgcommon.Address `json:"listen"` Settings *json.RawMessage `json:"settings"` Tag string `json:"tag"` Allocation *InboundDetourAllocationConfig `json:"allocate"` StreamSetting *StreamConfig `json:"streamSettings"` DomainOverride *cfgcommon.StringList `json:"domainOverride"` SniffingConfig *sniffer.SniffingConfig `json:"sniffing"` } // Build implements Buildable. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) { receiverSettings := &proxyman.ReceiverConfig{} if c.ListenOn == nil { // Listen on anyip, must set PortRange if c.PortRange == nil { return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.") } receiverSettings.PortRange = c.PortRange.Build() } else { // Listen on specific IP or Unix Domain Socket receiverSettings.Listen = c.ListenOn.Build() listenDS := c.ListenOn.Family().IsDomain() && (filepath.IsAbs(c.ListenOn.Domain()) || c.ListenOn.Domain()[0] == '@') listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost") switch { case listenIP: // Listen on specific IP, must set PortRange if c.PortRange == nil { return nil, newError("Listen on specific ip without port in InboundDetour.") } // Listen on IP:Port receiverSettings.PortRange = c.PortRange.Build() case listenDS: if c.PortRange != nil { // Listen on Unix Domain Socket, PortRange should be nil receiverSettings.PortRange = nil } default: return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain()) } } if c.Allocation != nil { concurrency := -1 if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" { concurrency = int(*c.Allocation.Concurrency) } portRange := int(c.PortRange.To - c.PortRange.From + 1) if concurrency >= 0 && concurrency >= portRange { return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To) } as, err := c.Allocation.Build() if err != nil { return nil, err } receiverSettings.AllocationStrategy = as } if c.StreamSetting != nil { ss, err := c.StreamSetting.Build() if err != nil { return nil, err } receiverSettings.StreamSettings = ss } if c.SniffingConfig != nil { s, err := c.SniffingConfig.Build() if err != nil { return nil, newError("failed to build sniffing config").Base(err) } receiverSettings.SniffingSettings = s } if c.DomainOverride != nil { kp, err := toProtocolList(*c.DomainOverride) if err != nil { return nil, newError("failed to parse inbound detour config").Base(err) } receiverSettings.DomainOverride = kp } settings := []byte("{}") if c.Settings != nil { settings = ([]byte)(*c.Settings) } rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol) if err != nil { return nil, newError("failed to load inbound detour config.").Base(err) } if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok { receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect } ts, err := rawConfig.(cfgcommon.Buildable).Build() if err != nil { return nil, err } return &core.InboundHandlerConfig{ Tag: c.Tag, ReceiverSettings: serial.ToTypedMessage(receiverSettings), ProxySettings: serial.ToTypedMessage(ts), }, nil } type OutboundDetourConfig struct { Protocol string `json:"protocol"` SendThrough *cfgcommon.Address `json:"sendThrough"` Tag string `json:"tag"` Settings *json.RawMessage `json:"settings"` StreamSetting *StreamConfig `json:"streamSettings"` ProxySettings *proxycfg.ProxyConfig `json:"proxySettings"` MuxSettings *muxcfg.MuxConfig `json:"mux"` DomainStrategy string `json:"domainStrategy"` } // Build implements Buildable. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) { senderSettings := &proxyman.SenderConfig{} if c.SendThrough != nil { address := c.SendThrough if address.Family().IsDomain() { return nil, newError("unable to send through: " + address.String()) } senderSettings.Via = address.Build() } if c.StreamSetting != nil { ss, err := c.StreamSetting.Build() if err != nil { return nil, err } senderSettings.StreamSettings = ss } if c.ProxySettings != nil { ps, err := c.ProxySettings.Build() if err != nil { return nil, newError("invalid outbound detour proxy settings.").Base(err) } senderSettings.ProxySettings = ps } if c.MuxSettings != nil { senderSettings.MultiplexSettings = c.MuxSettings.Build() } senderSettings.DomainStrategy = proxyman.SenderConfig_AS_IS switch strings.ToLower(c.DomainStrategy) { case "useip", "use_ip", "use-ip": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP4 case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP6 } settings := []byte("{}") if c.Settings != nil { settings = ([]byte)(*c.Settings) } rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol) if err != nil { return nil, newError("failed to parse to outbound detour config.").Base(err) } ts, err := rawConfig.(cfgcommon.Buildable).Build() if err != nil { return nil, err } return &core.OutboundHandlerConfig{ SenderSettings: serial.ToTypedMessage(senderSettings), Tag: c.Tag, ProxySettings: serial.ToTypedMessage(ts), }, nil } type StatsConfig struct{} // Build implements Buildable. func (c *StatsConfig) Build() (*stats.Config, error) { return &stats.Config{}, nil } type Config struct { // Port of this Point server. // Deprecated: Port exists for historical compatibility // and should not be used. Port uint16 `json:"port"` // Deprecated: InboundConfig exists for historical compatibility // and should not be used. InboundConfig *InboundDetourConfig `json:"inbound"` // Deprecated: OutboundConfig exists for historical compatibility // and should not be used. OutboundConfig *OutboundDetourConfig `json:"outbound"` // Deprecated: InboundDetours exists for historical compatibility // and should not be used. InboundDetours []InboundDetourConfig `json:"inboundDetour"` // Deprecated: OutboundDetours exists for historical compatibility // and should not be used. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"` LogConfig *log.LogConfig `json:"log"` RouterConfig *router.RouterConfig `json:"routing"` DNSConfig *dns.DNSConfig `json:"dns"` InboundConfigs []InboundDetourConfig `json:"inbounds"` OutboundConfigs []OutboundDetourConfig `json:"outbounds"` Transport *TransportConfig `json:"transport"` Policy *PolicyConfig `json:"policy"` API *APIConfig `json:"api"` Stats *StatsConfig `json:"stats"` Reverse *ReverseConfig `json:"reverse"` FakeDNS *dns.FakeDNSConfig `json:"fakeDns"` BrowserForwarder *BrowserForwarderConfig `json:"browserForwarder"` Observatory *ObservatoryConfig `json:"observatory"` BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"` MultiObservatory *MultiObservatoryConfig `json:"multiObservatory"` Services map[string]*json.RawMessage `json:"services"` } func (c *Config) findInboundTag(tag string) int { found := -1 for idx, ib := range c.InboundConfigs { if ib.Tag == tag { found = idx break } } return found } func (c *Config) findOutboundTag(tag string) int { found := -1 for idx, ob := range c.OutboundConfigs { if ob.Tag == tag { found = idx break } } return found } func applyTransportConfig(s *StreamConfig, t *TransportConfig) { if s.TCPSettings == nil { s.TCPSettings = t.TCPConfig } if s.KCPSettings == nil { s.KCPSettings = t.KCPConfig } if s.WSSettings == nil { s.WSSettings = t.WSConfig } if s.HTTPSettings == nil { s.HTTPSettings = t.HTTPConfig } if s.DSSettings == nil { s.DSSettings = t.DSConfig } } // Build implements Buildable. func (c *Config) Build() (*core.Config, error) { if err := PostProcessConfigureFile(c); err != nil { return nil, err } config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), }, } if c.API != nil { apiConf, err := c.API.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(apiConf)) } if c.Stats != nil { statsConf, err := c.Stats.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(statsConf)) } var logConfMsg *anypb.Any if c.LogConfig != nil { logConfMsg = serial.ToTypedMessage(c.LogConfig.Build()) } else { logConfMsg = serial.ToTypedMessage(log.DefaultLogConfig()) } // let logger module be the first App to start, // so that other modules could print log during initiating config.App = append([]*anypb.Any{logConfMsg}, config.App...) if c.RouterConfig != nil { routerConfig, err := c.RouterConfig.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(routerConfig)) } if c.FakeDNS != nil { features.PrintDeprecatedFeatureWarning("root fakedns settings") if c.DNSConfig != nil { c.DNSConfig.FakeDNS = c.FakeDNS } else { c.DNSConfig = &dns.DNSConfig{ FakeDNS: c.FakeDNS, } } } if c.DNSConfig != nil { dnsApp, err := c.DNSConfig.Build() if err != nil { return nil, newError("failed to parse DNS config").Base(err) } config.App = append(config.App, serial.ToTypedMessage(dnsApp)) } if c.Policy != nil { pc, err := c.Policy.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(pc)) } if c.Reverse != nil { r, err := c.Reverse.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(r)) } if c.BrowserForwarder != nil { r, err := c.BrowserForwarder.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(r)) } if c.Observatory != nil { r, err := c.Observatory.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(r)) } if c.BurstObservatory != nil { r, err := c.BurstObservatory.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(r)) } if c.MultiObservatory != nil { r, err := c.MultiObservatory.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(r)) } // Load Additional Services that do not have a json translator for serviceName, service := range c.Services { servicePackedConfig, err := v5cfg.LoadHeterogeneousConfigFromRawJSON(context.Background(), "service", serviceName, *service) if err != nil { return nil, newError(fmt.Sprintf("failed to parse %v config in Services", serviceName)).Base(err) } config.App = append(config.App, serial.ToTypedMessage(servicePackedConfig)) } var inbounds []InboundDetourConfig if c.InboundConfig != nil { inbounds = append(inbounds, *c.InboundConfig) } if len(c.InboundDetours) > 0 { inbounds = append(inbounds, c.InboundDetours...) } if len(c.InboundConfigs) > 0 { inbounds = append(inbounds, c.InboundConfigs...) } // Backward compatibility. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 { inbounds[0].PortRange = &cfgcommon.PortRange{ From: uint32(c.Port), To: uint32(c.Port), } } for _, rawInboundConfig := range inbounds { if c.Transport != nil { if rawInboundConfig.StreamSetting == nil { rawInboundConfig.StreamSetting = &StreamConfig{} } applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport) } ic, err := rawInboundConfig.Build() if err != nil { return nil, err } config.Inbound = append(config.Inbound, ic) } var outbounds []OutboundDetourConfig if c.OutboundConfig != nil { outbounds = append(outbounds, *c.OutboundConfig) } if len(c.OutboundDetours) > 0 { outbounds = append(outbounds, c.OutboundDetours...) } if len(c.OutboundConfigs) > 0 { outbounds = append(outbounds, c.OutboundConfigs...) } for _, rawOutboundConfig := range outbounds { if c.Transport != nil { if rawOutboundConfig.StreamSetting == nil { rawOutboundConfig.StreamSetting = &StreamConfig{} } applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport) } oc, err := rawOutboundConfig.Build() if err != nil { return nil, err } config.Outbound = append(config.Outbound, oc) } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/conf.go
infra/conf/v4/conf.go
package v4 //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/observatory.go
infra/conf/v4/observatory.go
package v4 import ( "encoding/json" "github.com/golang/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" "github.com/v2fly/v2ray-core/v5/app/observatory" "github.com/v2fly/v2ray-core/v5/app/observatory/burst" "github.com/v2fly/v2ray-core/v5/app/observatory/multiobservatory" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/taggedfeatures" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/duration" "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/router" ) type ObservatoryConfig struct { SubjectSelector []string `json:"subjectSelector"` ProbeURL string `json:"probeURL"` ProbeInterval duration.Duration `json:"probeInterval"` } func (o *ObservatoryConfig) Build() (proto.Message, error) { return &observatory.Config{SubjectSelector: o.SubjectSelector, ProbeUrl: o.ProbeURL, ProbeInterval: int64(o.ProbeInterval)}, nil } type BurstObservatoryConfig struct { SubjectSelector []string `json:"subjectSelector"` // health check settings HealthCheck *router.HealthCheckSettings `json:"pingConfig,omitempty"` } func (b BurstObservatoryConfig) Build() (proto.Message, error) { result, err := b.HealthCheck.Build() if err == nil { return &burst.Config{SubjectSelector: b.SubjectSelector, PingConfig: result.(*burst.HealthPingConfig)}, nil } return nil, err } type MultiObservatoryItem struct { MemberType string `json:"type"` Tag string `json:"tag"` Value json.RawMessage `json:"settings"` } type MultiObservatoryConfig struct { Observers []MultiObservatoryItem `json:"observers"` } func (o *MultiObservatoryConfig) Build() (proto.Message, error) { ret := &multiobservatory.Config{Holders: &taggedfeatures.Config{Features: make(map[string]*anypb.Any)}} for _, v := range o.Observers { switch v.MemberType { case "burst": var burstObservatoryConfig BurstObservatoryConfig err := json.Unmarshal(v.Value, &burstObservatoryConfig) if err != nil { return nil, err } burstObservatoryConfigPb, err := burstObservatoryConfig.Build() if err != nil { return nil, err } ret.Holders.Features[v.Tag] = serial.ToTypedMessage(burstObservatoryConfigPb) case "default": fallthrough default: var observatoryConfig ObservatoryConfig err := json.Unmarshal(v.Value, &observatoryConfig) if err != nil { return nil, err } observatoryConfigPb, err := observatoryConfig.Build() if err != nil { return nil, err } ret.Holders.Features[v.Tag] = serial.ToTypedMessage(observatoryConfigPb) } } return ret, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/vmess_test.go
infra/conf/v4/vmess_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound" "github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound" ) func TestVMessOutbound(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.VMessOutboundConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "vnext": [{ "address": "127.0.0.1", "port": 80, "users": [ { "id": "e641f5ad-9397-41e3-bf1a-e8740dfed019", "email": "love@v2fly.org", "level": 255 } ] }] }`, Parser: testassist.LoadJSON(creator), Output: &outbound.Config{ Receiver: []*protocol.ServerEndpoint{ { Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: 80, User: []*protocol.User{ { Email: "love@v2fly.org", Level: 255, Account: serial.ToTypedMessage(&vmess.Account{ Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019", AlterId: 0, SecuritySettings: &protocol.SecurityConfig{ Type: protocol.SecurityType_AUTO, }, }), }, }, }, }, }, }, }) } func TestVMessInbound(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.VMessInboundConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "clients": [ { "id": "27848739-7e62-4138-9fd3-098a63964b6b", "level": 0, "alterId": 16, "email": "love@v2fly.org", "security": "aes-128-gcm" } ], "default": { "level": 0, "alterId": 32 }, "detour": { "to": "tag_to_detour" }, "disableInsecureEncryption": true }`, Parser: testassist.LoadJSON(creator), Output: &inbound.Config{ User: []*protocol.User{ { Level: 0, Email: "love@v2fly.org", Account: serial.ToTypedMessage(&vmess.Account{ Id: "27848739-7e62-4138-9fd3-098a63964b6b", AlterId: 16, SecuritySettings: &protocol.SecurityConfig{ Type: protocol.SecurityType_AES128_GCM, }, }), }, }, Default: &inbound.DefaultConfig{ Level: 0, AlterId: 32, }, Detour: &inbound.DetourConfig{ To: "tag_to_detour", }, SecureEncryptionOnly: true, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/dokodemo_test.go
infra/conf/v4/dokodemo_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/dokodemo" ) func TestDokodemoConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.DokodemoConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "address": "8.8.8.8", "port": 53, "network": "tcp", "timeout": 10, "followRedirect": true, "userLevel": 1 }`, Parser: testassist.LoadJSON(creator), Output: &dokodemo.Config{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{8, 8, 8, 8}, }, }, Port: 53, Networks: []net.Network{net.Network_TCP}, Timeout: 10, FollowRedirect: true, UserLevel: 1, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/socks_test.go
infra/conf/v4/socks_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/socks" ) func TestSocksInboundConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.SocksServerConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "auth": "password", "accounts": [ { "user": "my-username", "pass": "my-password" } ], "udp": false, "ip": "127.0.0.1", "timeout": 5, "userLevel": 1, "packetEncoding": "Packet" }`, Parser: testassist.LoadJSON(creator), Output: &socks.ServerConfig{ AuthType: socks.AuthType_PASSWORD, Accounts: map[string]string{ "my-username": "my-password", }, UdpEnabled: false, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Timeout: 5, UserLevel: 1, PacketEncoding: packetaddr.PacketAddrType_Packet, }, }, }) } func TestSocksOutboundConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.SocksClientConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "servers": [{ "address": "127.0.0.1", "port": 1234, "users": [ {"user": "test user", "pass": "test pass", "email": "test@email.com"} ] }] }`, Parser: testassist.LoadJSON(creator), Output: &socks.ClientConfig{ Server: []*protocol.ServerEndpoint{ { Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: 1234, User: []*protocol.User{ { Email: "test@email.com", Account: serial.ToTypedMessage(&socks.Account{ Username: "test user", Password: "test pass", }), }, }, }, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/v2ray_test.go
infra/conf/v4/v2ray_test.go
package v4_test import ( "encoding/json" "reflect" "testing" "github.com/golang/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/dispatcher" "github.com/v2fly/v2ray-core/v5/app/log" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common" clog "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/muxcfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/memconservative" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/standard" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/blackhole" dns_proxy "github.com/v2fly/v2ray-core/v5/proxy/dns" "github.com/v2fly/v2ray-core/v5/proxy/freedom" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/http" "github.com/v2fly/v2ray-core/v5/transport/internet/tls" "github.com/v2fly/v2ray-core/v5/transport/internet/websocket" ) func TestV2RayConfig(t *testing.T) { createParser := func() func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { config := new(v4.Config) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "outbound": { "protocol": "freedom", "settings": {} }, "log": { "access": "/var/log/v2ray/access.log", "loglevel": "error", "error": "/var/log/v2ray/error.log" }, "inbound": { "streamSettings": { "network": "ws", "wsSettings": { "headers": { "host": "example.domain" }, "path": "" }, "tlsSettings": { "alpn": "h2" }, "security": "tls" }, "protocol": "vmess", "port": 443, "settings": { "clients": [ { "alterId": 100, "security": "aes-128-gcm", "id": "0cdf8a45-303d-4fed-9780-29aa7f54175e" } ] } }, "inbounds": [{ "streamSettings": { "network": "ws", "wsSettings": { "headers": { "host": "example.domain" }, "path": "" }, "tlsSettings": { "alpn": "h2" }, "security": "tls" }, "protocol": "vmess", "port": "443-500", "allocate": { "strategy": "random", "concurrency": 3 }, "settings": { "clients": [ { "alterId": 100, "security": "aes-128-gcm", "id": "0cdf8a45-303d-4fed-9780-29aa7f54175e" } ] } }], "outboundDetour": [ { "tag": "blocked", "protocol": "blackhole" }, { "protocol": "dns" } ], "routing": { "strategy": "rules", "settings": { "rules": [ { "ip": [ "10.0.0.0/8" ], "type": "field", "outboundTag": "blocked" } ] } }, "transport": { "httpSettings": { "path": "/test" } } }`, Parser: createParser(), Output: &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&log.Config{ Error: &log.LogSpecification{ Type: log.LogType_File, Level: clog.Severity_Error, Path: "/var/log/v2ray/error.log", }, Access: &log.LogSpecification{ Type: log.LogType_File, Path: "/var/log/v2ray/access.log", }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&router.Config{ DomainStrategy: router.DomainStrategy_AsIs, Rule: []*router.RoutingRule{ { Geoip: []*routercommon.GeoIP{ { Cidr: []*routercommon.CIDR{ { Ip: []byte{10, 0, 0, 0}, Prefix: 8, }, }, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "blocked", }, }, }, }), }, Outbound: []*core.OutboundHandlerConfig{ { SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{ StreamSettings: &internet.StreamConfig{ ProtocolName: "tcp", TransportSettings: []*internet.TransportConfig{ { ProtocolName: "http", Settings: serial.ToTypedMessage(&http.Config{ Path: "/test", }), }, }, }, }), ProxySettings: serial.ToTypedMessage(&freedom.Config{ DomainStrategy: freedom.Config_AS_IS, UserLevel: 0, }), }, { Tag: "blocked", SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{ StreamSettings: &internet.StreamConfig{ ProtocolName: "tcp", TransportSettings: []*internet.TransportConfig{ { ProtocolName: "http", Settings: serial.ToTypedMessage(&http.Config{ Path: "/test", }), }, }, }, }), ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), }, { SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{ StreamSettings: &internet.StreamConfig{ ProtocolName: "tcp", TransportSettings: []*internet.TransportConfig{ { ProtocolName: "http", Settings: serial.ToTypedMessage(&http.Config{ Path: "/test", }), }, }, }, }), ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{ Server: &net.Endpoint{}, }), }, }, Inbound: []*core.InboundHandlerConfig{ { ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: &net.PortRange{ From: 443, To: 443, }, StreamSettings: &internet.StreamConfig{ ProtocolName: "websocket", TransportSettings: []*internet.TransportConfig{ { ProtocolName: "websocket", Settings: serial.ToTypedMessage(&websocket.Config{ Header: []*websocket.Header{ { Key: "host", Value: "example.domain", }, }, }), }, { ProtocolName: "http", Settings: serial.ToTypedMessage(&http.Config{ Path: "/test", }), }, }, SecurityType: "v2ray.core.transport.internet.tls.Config", SecuritySettings: []*anypb.Any{ serial.ToTypedMessage(&tls.Config{ NextProtocol: []string{"h2"}, }), }, }, }), ProxySettings: serial.ToTypedMessage(&inbound.Config{ User: []*protocol.User{ { Level: 0, Account: serial.ToTypedMessage(&vmess.Account{ Id: "0cdf8a45-303d-4fed-9780-29aa7f54175e", AlterId: 100, SecuritySettings: &protocol.SecurityConfig{ Type: protocol.SecurityType_AES128_GCM, }, }), }, }, }), }, { ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: &net.PortRange{ From: 443, To: 500, }, AllocationStrategy: &proxyman.AllocationStrategy{ Type: proxyman.AllocationStrategy_Random, Concurrency: &proxyman.AllocationStrategy_AllocationStrategyConcurrency{ Value: 3, }, }, StreamSettings: &internet.StreamConfig{ ProtocolName: "websocket", TransportSettings: []*internet.TransportConfig{ { ProtocolName: "websocket", Settings: serial.ToTypedMessage(&websocket.Config{ Header: []*websocket.Header{ { Key: "host", Value: "example.domain", }, }, }), }, { ProtocolName: "http", Settings: serial.ToTypedMessage(&http.Config{ Path: "/test", }), }, }, SecurityType: "v2ray.core.transport.internet.tls.Config", SecuritySettings: []*anypb.Any{ serial.ToTypedMessage(&tls.Config{ NextProtocol: []string{"h2"}, }), }, }, }), ProxySettings: serial.ToTypedMessage(&inbound.Config{ User: []*protocol.User{ { Level: 0, Account: serial.ToTypedMessage(&vmess.Account{ Id: "0cdf8a45-303d-4fed-9780-29aa7f54175e", AlterId: 100, SecuritySettings: &protocol.SecurityConfig{ Type: protocol.SecurityType_AES128_GCM, }, }), }, }, }), }, }, }, }, }) } func TestMuxConfig_Build(t *testing.T) { tests := []struct { name string fields string want *proxyman.MultiplexingConfig }{ {"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{ Enabled: true, Concurrency: 16, }}, {"empty def", `{}`, &proxyman.MultiplexingConfig{ Enabled: false, Concurrency: 8, }}, {"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{ Enabled: false, Concurrency: 4, }}, {"forbidden", `{"enabled": false, "concurrency": -1}`, nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &muxcfg.MuxConfig{} common.Must(json.Unmarshal([]byte(tt.fields), m)) if got := m.Build(); !reflect.DeepEqual(got, tt.want) { t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want) } }) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/blackhole.go
infra/conf/v4/blackhole.go
package v4 import ( "encoding/json" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/loader" "github.com/v2fly/v2ray-core/v5/proxy/blackhole" ) type NoneResponse struct{} func (*NoneResponse) Build() (proto.Message, error) { return new(blackhole.NoneResponse), nil } type HTTPResponse struct{} func (*HTTPResponse) Build() (proto.Message, error) { return new(blackhole.HTTPResponse), nil } type BlackholeConfig struct { Response json.RawMessage `json:"response"` } func (v *BlackholeConfig) Build() (proto.Message, error) { config := new(blackhole.Config) if v.Response != nil { response, _, err := configLoader.Load(v.Response) if err != nil { return nil, newError("Config: Failed to parse Blackhole response config.").Base(err) } responseSettings, err := response.(cfgcommon.Buildable).Build() if err != nil { return nil, err } config.Response = serial.ToTypedMessage(responseSettings) } return config, nil } var configLoader = loader.NewJSONConfigLoader( loader.ConfigCreatorCache{ "none": func() interface{} { return new(NoneResponse) }, "http": func() interface{} { return new(HTTPResponse) }, }, "type", "")
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/lint.go
infra/conf/v4/lint.go
package v4 type ConfigureFilePostProcessingStage interface { Process(conf *Config) error } var configureFilePostProcessingStages map[string]ConfigureFilePostProcessingStage func RegisterConfigureFilePostProcessingStage(name string, stage ConfigureFilePostProcessingStage) { if configureFilePostProcessingStages == nil { configureFilePostProcessingStages = make(map[string]ConfigureFilePostProcessingStage) } configureFilePostProcessingStages[name] = stage } func PostProcessConfigureFile(conf *Config) error { for k, v := range configureFilePostProcessingStages { if err := v.Process(conf); err != nil { return newError("Rejected by Postprocessing Stage ", k).AtError().Base(err) } } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/freedom_test.go
infra/conf/v4/freedom_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/freedom" ) func TestFreedomConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.FreedomConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "domainStrategy": "AsIs", "timeout": 10, "redirect": "127.0.0.1:3366", "userLevel": 1 }`, Parser: testassist.LoadJSON(creator), Output: &freedom.Config{ DomainStrategy: freedom.Config_AS_IS, Timeout: 10, DestinationOverride: &freedom.DestinationOverride{ Server: &protocol.ServerEndpoint{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: 3366, }, }, UserLevel: 1, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/http_test.go
infra/conf/v4/http_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/http" ) func TestHTTPServerConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.HTTPServerConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "timeout": 10, "accounts": [ { "user": "my-username", "pass": "my-password" } ], "allowTransparent": true, "userLevel": 1 }`, Parser: testassist.LoadJSON(creator), Output: &http.ServerConfig{ Accounts: map[string]string{ "my-username": "my-password", }, AllowTransparent: true, UserLevel: 1, Timeout: 10, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/http.go
infra/conf/v4/http.go
package v4 import ( "encoding/json" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/http" ) type HTTPAccount struct { Username string `json:"user"` Password string `json:"pass"` } func (v *HTTPAccount) Build() *http.Account { return &http.Account{ Username: v.Username, Password: v.Password, } } type HTTPServerConfig struct { Timeout uint32 `json:"timeout"` Accounts []*HTTPAccount `json:"accounts"` Transparent bool `json:"allowTransparent"` UserLevel uint32 `json:"userLevel"` } func (c *HTTPServerConfig) Build() (proto.Message, error) { config := &http.ServerConfig{ Timeout: c.Timeout, AllowTransparent: c.Transparent, UserLevel: c.UserLevel, } if len(c.Accounts) > 0 { config.Accounts = make(map[string]string) for _, account := range c.Accounts { config.Accounts[account.Username] = account.Password } } return config, nil } type HTTPRemoteConfig struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } type HTTPClientConfig struct { Servers []*HTTPRemoteConfig `json:"servers"` } func (v *HTTPClientConfig) Build() (proto.Message, error) { config := new(http.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 HTTP user").Base(err).AtError() } account := new(HTTPAccount) if err := json.Unmarshal(rawUser, account); err != nil { return nil, newError("failed to parse HTTP 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
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/services.go
infra/conf/v4/services.go
package v4 import ( "encoding/json" "github.com/golang/protobuf/jsonpb" "github.com/jhump/protoreflect/desc" "github.com/jhump/protoreflect/dynamic" "google.golang.org/protobuf/types/known/anypb" "github.com/v2fly/v2ray-core/v5/common/serial" ) func (c *Config) BuildServices(service map[string]*json.RawMessage) ([]*anypb.Any, error) { var ret []*anypb.Any for k, v := range service { message, err := desc.LoadMessageDescriptor(k) if err != nil || message == nil { return nil, newError("Cannot find service", k, "").Base(err) } serviceConfig := dynamic.NewMessage(message) if err := serviceConfig.UnmarshalJSONPB(&jsonpb.Unmarshaler{AllowUnknownFields: false}, *v); err != nil { return nil, newError("Cannot interpret service configure file", k, "").Base(err) } ret = append(ret, serial.ToTypedMessage(serviceConfig)) } return ret, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/freedom.go
infra/conf/v4/freedom.go
package v4 import ( "net" "strings" "github.com/golang/protobuf/proto" v2net "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/proxy/freedom" ) type FreedomConfig struct { DomainStrategy string `json:"domainStrategy"` Timeout *uint32 `json:"timeout"` Redirect string `json:"redirect"` UserLevel uint32 `json:"userLevel"` } // Build implements Buildable func (c *FreedomConfig) Build() (proto.Message, error) { config := new(freedom.Config) config.DomainStrategy = freedom.Config_AS_IS switch strings.ToLower(c.DomainStrategy) { case "useip", "use_ip", "use-ip": config.DomainStrategy = freedom.Config_USE_IP case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4": config.DomainStrategy = freedom.Config_USE_IP4 case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6": config.DomainStrategy = freedom.Config_USE_IP6 } if c.Timeout != nil { config.Timeout = *c.Timeout } config.UserLevel = c.UserLevel if len(c.Redirect) > 0 { host, portStr, err := net.SplitHostPort(c.Redirect) if err != nil { return nil, newError("invalid redirect address: ", c.Redirect, ": ", err).Base(err) } port, err := v2net.PortFromString(portStr) if err != nil { return nil, newError("invalid redirect port: ", c.Redirect, ": ", err).Base(err) } config.DestinationOverride = &freedom.DestinationOverride{ Server: &protocol.ServerEndpoint{ Port: uint32(port), }, } if len(host) > 0 { config.DestinationOverride.Server.Address = v2net.NewIPOrDomain(v2net.ParseAddress(host)) } } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/trojan.go
infra/conf/v4/trojan.go
package v4 import ( "encoding/json" "path/filepath" "runtime" "strconv" "strings" "syscall" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/trojan" ) // TrojanServerTarget is configuration of a single trojan server type TrojanServerTarget struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Password string `json:"password"` Email string `json:"email"` Level byte `json:"level"` } // TrojanClientConfig is configuration of trojan servers type TrojanClientConfig struct { Servers []*TrojanServerTarget `json:"servers"` } // Build implements Buildable func (c *TrojanClientConfig) Build() (proto.Message, error) { config := new(trojan.ClientConfig) if len(c.Servers) == 0 { return nil, newError("0 Trojan server configured.") } serverSpecs := make([]*protocol.ServerEndpoint, len(c.Servers)) for idx, rec := range c.Servers { if rec.Address == nil { return nil, newError("Trojan server address is not set.") } if rec.Port == 0 { return nil, newError("Invalid Trojan port.") } if rec.Password == "" { return nil, newError("Trojan password is not specified.") } account := &trojan.Account{ Password: rec.Password, } trojan := &protocol.ServerEndpoint{ Address: rec.Address.Build(), Port: uint32(rec.Port), User: []*protocol.User{ { Level: uint32(rec.Level), Email: rec.Email, Account: serial.ToTypedMessage(account), }, }, } serverSpecs[idx] = trojan } config.Server = serverSpecs return config, nil } // TrojanInboundFallback is fallback configuration type TrojanInboundFallback struct { Alpn string `json:"alpn"` Path string `json:"path"` Type string `json:"type"` Dest json.RawMessage `json:"dest"` Xver uint64 `json:"xver"` } // TrojanUserConfig is user configuration type TrojanUserConfig struct { Password string `json:"password"` Level byte `json:"level"` Email string `json:"email"` } // TrojanServerConfig is Inbound configuration type TrojanServerConfig struct { Clients []*TrojanUserConfig `json:"clients"` Fallback json.RawMessage `json:"fallback"` Fallbacks []*TrojanInboundFallback `json:"fallbacks"` PacketEncoding string `json:"packetEncoding"` } // Build implements Buildable func (c *TrojanServerConfig) Build() (proto.Message, error) { config := new(trojan.ServerConfig) config.Users = make([]*protocol.User, len(c.Clients)) for idx, rawUser := range c.Clients { user := new(protocol.User) account := &trojan.Account{ Password: rawUser.Password, } user.Email = rawUser.Email user.Level = uint32(rawUser.Level) user.Account = serial.ToTypedMessage(account) config.Users[idx] = user } if c.Fallback != nil { return nil, newError(`Trojan settings: please use "fallbacks":[{}] instead of "fallback":{}`) } for _, fb := range c.Fallbacks { var i uint16 var s string if err := json.Unmarshal(fb.Dest, &i); err == nil { s = strconv.Itoa(int(i)) } else { _ = json.Unmarshal(fb.Dest, &s) } config.Fallbacks = append(config.Fallbacks, &trojan.Fallback{ Alpn: fb.Alpn, Path: fb.Path, Type: fb.Type, Dest: s, Xver: fb.Xver, }) } for _, fb := range config.Fallbacks { /* if fb.Alpn == "h2" && fb.Path != "" { return nil, newError(`Trojan fallbacks: "alpn":"h2" doesn't support "path"`) } */ if fb.Path != "" && fb.Path[0] != '/' { return nil, newError(`Trojan fallbacks: "path" must be empty or start with "/"`) } if fb.Type == "" && fb.Dest != "" { if fb.Dest == "serve-ws-none" { // nolint:gocritic fb.Type = "serve" } else if filepath.IsAbs(fb.Dest) || fb.Dest[0] == '@' { fb.Type = "unix" if strings.HasPrefix(fb.Dest, "@@") && (runtime.GOOS == "linux" || runtime.GOOS == "android") { fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path)) // may need padding to work with haproxy copy(fullAddr, fb.Dest[1:]) fb.Dest = string(fullAddr) } } else { if _, err := strconv.Atoi(fb.Dest); err == nil { fb.Dest = "127.0.0.1:" + fb.Dest } if _, _, err := net.SplitHostPort(fb.Dest); err == nil { fb.Type = "tcp" } } } if fb.Type == "" { return nil, newError(`Trojan fallbacks: please fill in a valid value for every "dest"`) } if fb.Xver > 2 { return nil, newError(`Trojan fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`) } } switch c.PacketEncoding { case "Packet": config.PacketEncoding = packetaddr.PacketAddrType_Packet case "", "None": config.PacketEncoding = packetaddr.PacketAddrType_None } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/shadowsocks_test.go
infra/conf/v4/shadowsocks_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks" ) func TestShadowsocksServerConfigParsing(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.ShadowsocksServerConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "method": "aes-256-GCM", "password": "v2ray-password" }`, Parser: testassist.LoadJSON(creator), Output: &shadowsocks.ServerConfig{ User: &protocol.User{ Account: serial.ToTypedMessage(&shadowsocks.Account{ CipherType: shadowsocks.CipherType_AES_256_GCM, Password: "v2ray-password", }), }, Network: []net.Network{net.Network_TCP}, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/blackhole_test.go
infra/conf/v4/blackhole_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" "github.com/v2fly/v2ray-core/v5/proxy/blackhole" ) func TestHTTPResponseJSON(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.BlackholeConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "response": { "type": "http" } }`, Parser: testassist.LoadJSON(creator), Output: &blackhole.Config{ Response: serial.ToTypedMessage(&blackhole.HTTPResponse{}), }, }, { Input: `{}`, Parser: testassist.LoadJSON(creator), Output: &blackhole.Config{}, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/transport_authenticators.go
infra/conf/v4/transport_authenticators.go
package v4 import ( "sort" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/http" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/noop" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/srtp" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/tls" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/utp" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/wechat" "github.com/v2fly/v2ray-core/v5/transport/internet/headers/wireguard" ) type NoOpAuthenticator struct{} func (NoOpAuthenticator) Build() (proto.Message, error) { return new(noop.Config), nil } type NoOpConnectionAuthenticator struct{} func (NoOpConnectionAuthenticator) Build() (proto.Message, error) { return new(noop.ConnectionConfig), nil } type SRTPAuthenticator struct{} func (SRTPAuthenticator) Build() (proto.Message, error) { return new(srtp.Config), nil } type UTPAuthenticator struct{} func (UTPAuthenticator) Build() (proto.Message, error) { return new(utp.Config), nil } type WechatVideoAuthenticator struct{} func (WechatVideoAuthenticator) Build() (proto.Message, error) { return new(wechat.VideoConfig), nil } type WireguardAuthenticator struct{} func (WireguardAuthenticator) Build() (proto.Message, error) { return new(wireguard.WireguardConfig), nil } type DTLSAuthenticator struct{} func (DTLSAuthenticator) Build() (proto.Message, error) { return new(tls.PacketConfig), nil } type AuthenticatorRequest struct { Version string `json:"version"` Method string `json:"method"` Path cfgcommon.StringList `json:"path"` Headers map[string]*cfgcommon.StringList `json:"headers"` } func sortMapKeys(m map[string]*cfgcommon.StringList) []string { var keys []string for key := range m { keys = append(keys, key) } sort.Strings(keys) return keys } func (v *AuthenticatorRequest) Build() (*http.RequestConfig, error) { config := &http.RequestConfig{ Uri: []string{"/"}, Header: []*http.Header{ { Name: "Host", Value: []string{"www.baidu.com", "www.bing.com"}, }, { Name: "User-Agent", Value: []string{ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46", }, }, { Name: "Accept-Encoding", Value: []string{"gzip, deflate"}, }, { Name: "Connection", Value: []string{"keep-alive"}, }, { Name: "Pragma", Value: []string{"no-cache"}, }, }, } if len(v.Version) > 0 { config.Version = &http.Version{Value: v.Version} } if len(v.Method) > 0 { config.Method = &http.Method{Value: v.Method} } if len(v.Path) > 0 { config.Uri = append([]string(nil), (v.Path)...) } if len(v.Headers) > 0 { config.Header = make([]*http.Header, 0, len(v.Headers)) headerNames := sortMapKeys(v.Headers) for _, key := range headerNames { value := v.Headers[key] if value == nil { return nil, newError("empty HTTP header value: " + key).AtError() } config.Header = append(config.Header, &http.Header{ Name: key, Value: append([]string(nil), (*value)...), }) } } return config, nil } type AuthenticatorResponse struct { Version string `json:"version"` Status string `json:"status"` Reason string `json:"reason"` Headers map[string]*cfgcommon.StringList `json:"headers"` } func (v *AuthenticatorResponse) Build() (*http.ResponseConfig, error) { config := &http.ResponseConfig{ Header: []*http.Header{ { Name: "Content-Type", Value: []string{"application/octet-stream", "video/mpeg"}, }, { Name: "Transfer-Encoding", Value: []string{"chunked"}, }, { Name: "Connection", Value: []string{"keep-alive"}, }, { Name: "Pragma", Value: []string{"no-cache"}, }, { Name: "Cache-Control", Value: []string{"private", "no-cache"}, }, }, } if len(v.Version) > 0 { config.Version = &http.Version{Value: v.Version} } if len(v.Status) > 0 || len(v.Reason) > 0 { config.Status = &http.Status{ Code: "200", Reason: "OK", } if len(v.Status) > 0 { config.Status.Code = v.Status } if len(v.Reason) > 0 { config.Status.Reason = v.Reason } } if len(v.Headers) > 0 { config.Header = make([]*http.Header, 0, len(v.Headers)) headerNames := sortMapKeys(v.Headers) for _, key := range headerNames { value := v.Headers[key] if value == nil { return nil, newError("empty HTTP header value: " + key).AtError() } config.Header = append(config.Header, &http.Header{ Name: key, Value: append([]string(nil), (*value)...), }) } } return config, nil } type Authenticator struct { Request AuthenticatorRequest `json:"request"` Response AuthenticatorResponse `json:"response"` } func (v *Authenticator) Build() (proto.Message, error) { config := new(http.Config) requestConfig, err := v.Request.Build() if err != nil { return nil, err } config.Request = requestConfig responseConfig, err := v.Response.Build() if err != nil { return nil, err } config.Response = responseConfig return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/transport.go
infra/conf/v4/transport.go
package v4 import ( "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" ) type TransportConfig struct { TCPConfig *TCPConfig `json:"tcpSettings"` KCPConfig *KCPConfig `json:"kcpSettings"` WSConfig *WebSocketConfig `json:"wsSettings"` HTTPConfig *HTTPConfig `json:"httpSettings"` DSConfig *DomainSocketConfig `json:"dsSettings"` QUICConfig *QUICConfig `json:"quicSettings"` GunConfig *GunConfig `json:"gunSettings"` GRPCConfig *GunConfig `json:"grpcSettings"` } // Build implements Buildable. func (c *TransportConfig) Build() (*transport.Config, error) { config := new(transport.Config) if c.TCPConfig != nil { ts, err := c.TCPConfig.Build() if err != nil { return nil, newError("failed to build TCP config").Base(err).AtError() } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "tcp", Settings: serial.ToTypedMessage(ts), }) } if c.KCPConfig != nil { ts, err := c.KCPConfig.Build() if err != nil { return nil, newError("failed to build mKCP config").Base(err).AtError() } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "mkcp", Settings: serial.ToTypedMessage(ts), }) } if c.WSConfig != nil { ts, err := c.WSConfig.Build() if err != nil { return nil, newError("failed to build WebSocket config").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "websocket", Settings: serial.ToTypedMessage(ts), }) } if c.HTTPConfig != nil { ts, err := c.HTTPConfig.Build() if err != nil { return nil, newError("Failed to build HTTP config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "http", Settings: serial.ToTypedMessage(ts), }) } if c.DSConfig != nil { ds, err := c.DSConfig.Build() if err != nil { return nil, newError("Failed to build DomainSocket config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "domainsocket", Settings: serial.ToTypedMessage(ds), }) } if c.QUICConfig != nil { qs, err := c.QUICConfig.Build() if err != nil { return nil, newError("Failed to build QUIC config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "quic", Settings: serial.ToTypedMessage(qs), }) } if c.GunConfig == nil { c.GunConfig = c.GRPCConfig } if c.GunConfig != nil { gs, err := c.GunConfig.Build() if err != nil { return nil, newError("Failed to build Gun config.").Base(err) } config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: "gun", Settings: serial.ToTypedMessage(gs), }) } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/dokodemo.go
infra/conf/v4/dokodemo.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/dokodemo" ) type DokodemoConfig struct { Host *cfgcommon.Address `json:"address"` PortValue uint16 `json:"port"` NetworkList *cfgcommon.NetworkList `json:"network"` TimeoutValue uint32 `json:"timeout"` Redirect bool `json:"followRedirect"` UserLevel uint32 `json:"userLevel"` } func (v *DokodemoConfig) Build() (proto.Message, error) { config := new(dokodemo.Config) if v.Host != nil { config.Address = v.Host.Build() } config.Port = uint32(v.PortValue) config.Networks = v.NetworkList.Build() config.Timeout = v.TimeoutValue config.FollowRedirect = v.Redirect config.UserLevel = v.UserLevel return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/dns_proxy.go
infra/conf/v4/dns_proxy.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/dns" ) type DNSOutboundConfig struct { Network cfgcommon.Network `json:"network"` Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` UserLevel uint32 `json:"userLevel"` } func (c *DNSOutboundConfig) Build() (proto.Message, error) { config := &dns.Config{ Server: &net.Endpoint{ Network: c.Network.Build(), Port: uint32(c.Port), }, UserLevel: c.UserLevel, } if c.Address != nil { config.Server.Address = c.Address.Build() } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/hysteria2.go
infra/conf/v4/hysteria2.go
package v4 import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/proxy/hysteria2" ) // Hysteria2ServerTarget is configuration of a single hysteria2 server type Hysteria2ServerTarget struct { Address *cfgcommon.Address `json:"address"` Port uint16 `json:"port"` Email string `json:"email"` Level byte `json:"level"` } // Hysteria2ClientConfig is configuration of hysteria2 servers type Hysteria2ClientConfig struct { Servers []*Hysteria2ServerTarget `json:"servers"` } // Build implements Buildable func (c *Hysteria2ClientConfig) Build() (proto.Message, error) { config := new(hysteria2.ClientConfig) if len(c.Servers) == 0 { return nil, newError("0 Hysteria2 server configured.") } serverSpecs := make([]*protocol.ServerEndpoint, len(c.Servers)) for idx, rec := range c.Servers { if rec.Address == nil { return nil, newError("Hysteria2 server address is not set.") } if rec.Port == 0 { return nil, newError("Invalid Hysteria2 port.") } account := &hysteria2.Account{} hysteria2 := &protocol.ServerEndpoint{ Address: rec.Address.Build(), Port: uint32(rec.Port), User: []*protocol.User{ { Level: uint32(rec.Level), Email: rec.Email, Account: serial.ToTypedMessage(account), }, }, } serverSpecs[idx] = hysteria2 } config.Server = serverSpecs return config, nil } // Hysteria2ServerConfig is Inbound configuration type Hysteria2ServerConfig struct { PacketEncoding string `json:"packetEncoding"` } // Build implements Buildable func (c *Hysteria2ServerConfig) Build() (proto.Message, error) { config := new(hysteria2.ServerConfig) switch c.PacketEncoding { case "Packet": config.PacketEncoding = packetaddr.PacketAddrType_Packet case "", "None": config.PacketEncoding = packetaddr.PacketAddrType_None } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v4/reverse_test.go
infra/conf/v4/reverse_test.go
package v4_test import ( "testing" "github.com/v2fly/v2ray-core/v5/app/reverse" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" ) func TestReverseConfig(t *testing.T) { creator := func() cfgcommon.Buildable { return new(v4.ReverseConfig) } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "bridges": [{ "tag": "test", "domain": "test.v2fly.org" }] }`, Parser: testassist.LoadJSON(creator), Output: &reverse.Config{ BridgeConfig: []*reverse.BridgeConfig{ {Tag: "test", Domain: "test.v2fly.org"}, }, }, }, { Input: `{ "portals": [{ "tag": "test", "domain": "test.v2fly.org" }] }`, Parser: testassist.LoadJSON(creator), Output: &reverse.Config{ PortalConfig: []*reverse.PortalConfig{ {Tag: "test", Domain: "test.v2fly.org"}, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/rule/rule_test.go
infra/conf/rule/rule_test.go
package rule_test import ( "context" "errors" "io/fs" "os" "path/filepath" "testing" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/standard" "github.com/v2fly/v2ray-core/v5/infra/conf/rule" ) func init() { const geoipURL = "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat" wd, err := os.Getwd() common.Must(err) tempPath := filepath.Join(wd, "..", "..", "..", "testing", "temp") geoipPath := filepath.Join(tempPath, "geoip.dat") os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } } func TestToCidrList(t *testing.T) { t.Log(os.Getenv("v2ray.location.asset")) common.Must(filesystem.CopyFile(platform.GetAssetLocation("geoiptestrouter.dat"), platform.GetAssetLocation("geoip.dat"), 0o600)) ips := cfgcommon.StringList([]string{ "geoip:us", "geoip:cn", "geoip:!cn", "ext:geoiptestrouter.dat:!cn", "ext:geoiptestrouter.dat:ca", "ext-ip:geoiptestrouter.dat:!cn", "ext-ip:geoiptestrouter.dat:!ca", }) cfgctx := cfgcommon.NewConfigureLoadingContext(context.Background()) if loader, err := geodata.GetGeoDataLoader("standard"); err == nil { cfgcommon.SetGeoDataLoader(cfgctx, loader) } else { t.Fatal(err) } _, err := rule.ToCidrList(cfgctx, ips) if err != nil { t.Fatalf("Failed to parse geoip list, got %s", err) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/rule/errors.generated.go
infra/conf/rule/errors.generated.go
package rule import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/rule/rule.go
infra/conf/rule/rule.go
package rule import ( "context" "encoding/json" "strconv" "strings" "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen func parseDomainRule(ctx context.Context, domain string) ([]*routercommon.Domain, error) { cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx) geoLoader := cfgEnv.GetGeoLoader() if strings.HasPrefix(domain, "geosite:") { list := domain[8:] if len(list) == 0 { return nil, newError("empty listname in rule: ", domain) } domains, err := geoLoader.LoadGeoSite(list) if err != nil { return nil, newError("failed to load geosite: ", list).Base(err) } return domains, nil } isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(domain, prefix) { isExtDatFile = len(prefix) } const prefixQualified = "ext-domain:" if strings.HasPrefix(domain, prefixQualified) { isExtDatFile = len(prefixQualified) } } if isExtDatFile != 0 { kv := strings.Split(domain[isExtDatFile:], ":") if len(kv) != 2 { return nil, newError("invalid external resource: ", domain) } filename := kv[0] list := kv[1] domains, err := geoLoader.LoadGeoSiteWithAttr(filename, list) if err != nil { return nil, newError("failed to load external geosite: ", list, " from ", filename).Base(err) } return domains, nil } domainRule := new(routercommon.Domain) switch { case strings.HasPrefix(domain, "regexp:"): regexpVal := domain[7:] if len(regexpVal) == 0 { return nil, newError("empty regexp type of rule: ", domain) } domainRule.Type = routercommon.Domain_Regex domainRule.Value = regexpVal case strings.HasPrefix(domain, "domain:"): domainName := domain[7:] if len(domainName) == 0 { return nil, newError("empty domain type of rule: ", domain) } domainRule.Type = routercommon.Domain_RootDomain domainRule.Value = domainName case strings.HasPrefix(domain, "full:"): fullVal := domain[5:] if len(fullVal) == 0 { return nil, newError("empty full domain type of rule: ", domain) } domainRule.Type = routercommon.Domain_Full domainRule.Value = fullVal case strings.HasPrefix(domain, "keyword:"): keywordVal := domain[8:] if len(keywordVal) == 0 { return nil, newError("empty keyword type of rule: ", domain) } domainRule.Type = routercommon.Domain_Plain domainRule.Value = keywordVal case strings.HasPrefix(domain, "dotless:"): domainRule.Type = routercommon.Domain_Regex switch substr := domain[8:]; { case substr == "": domainRule.Value = "^[^.]*$" case !strings.Contains(substr, "."): domainRule.Value = "^[^.]*" + substr + "[^.]*$" default: return nil, newError("substr in dotless rule should not contain a dot: ", substr) } default: domainRule.Type = routercommon.Domain_Plain domainRule.Value = domain } return []*routercommon.Domain{domainRule}, nil } func toCidrList(ctx context.Context, ips cfgcommon.StringList) ([]*routercommon.GeoIP, error) { cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx) geoLoader := cfgEnv.GetGeoLoader() var geoipList []*routercommon.GeoIP var customCidrs []*routercommon.CIDR for _, ip := range ips { if strings.HasPrefix(ip, "geoip:") { country := ip[6:] isReverseMatch := false if strings.HasPrefix(ip, "geoip:!") { country = ip[7:] isReverseMatch = true } if len(country) == 0 { return nil, newError("empty country name in rule") } geoip, err := geoLoader.LoadGeoIP(country) if err != nil { return nil, newError("failed to load geoip: ", country).Base(err) } geoipList = append(geoipList, &routercommon.GeoIP{ CountryCode: strings.ToUpper(country), Cidr: geoip, InverseMatch: isReverseMatch, }) continue } isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(ip, prefix) { isExtDatFile = len(prefix) } const prefixQualified = "ext-ip:" if strings.HasPrefix(ip, prefixQualified) { isExtDatFile = len(prefixQualified) } } if isExtDatFile != 0 { kv := strings.Split(ip[isExtDatFile:], ":") if len(kv) != 2 { return nil, newError("invalid external resource: ", ip) } filename := kv[0] country := kv[1] if len(filename) == 0 || len(country) == 0 { return nil, newError("empty filename or empty country in rule") } isInverseMatch := false if strings.HasPrefix(country, "!") { country = country[1:] isInverseMatch = true } geoip, err := geoLoader.LoadIP(filename, country) if err != nil { return nil, newError("failed to load geoip: ", country, " from ", filename).Base(err) } geoipList = append(geoipList, &routercommon.GeoIP{ CountryCode: strings.ToUpper(filename + "_" + country), Cidr: geoip, InverseMatch: isInverseMatch, }) continue } ipRule, err := ParseIP(ip) if err != nil { return nil, newError("invalid IP: ", ip).Base(err) } customCidrs = append(customCidrs, ipRule) } if len(customCidrs) > 0 { geoipList = append(geoipList, &routercommon.GeoIP{ Cidr: customCidrs, }) } return geoipList, nil } func parseFieldRule(ctx context.Context, msg json.RawMessage) (*router.RoutingRule, error) { type RawFieldRule struct { RouterRule Domain *cfgcommon.StringList `json:"domain"` Domains *cfgcommon.StringList `json:"domains"` IP *cfgcommon.StringList `json:"ip"` Port *cfgcommon.PortList `json:"port"` Network *cfgcommon.NetworkList `json:"network"` SourceIP *cfgcommon.StringList `json:"source"` SourcePort *cfgcommon.PortList `json:"sourcePort"` User *cfgcommon.StringList `json:"user"` InboundTag *cfgcommon.StringList `json:"inboundTag"` Protocols *cfgcommon.StringList `json:"protocol"` Attributes string `json:"attrs"` } rawFieldRule := new(RawFieldRule) err := json.Unmarshal(msg, rawFieldRule) if err != nil { return nil, err } rule := new(router.RoutingRule) switch { case len(rawFieldRule.OutboundTag) > 0: rule.TargetTag = &router.RoutingRule_Tag{ Tag: rawFieldRule.OutboundTag, } case len(rawFieldRule.BalancerTag) > 0: rule.TargetTag = &router.RoutingRule_BalancingTag{ BalancingTag: rawFieldRule.BalancerTag, } default: return nil, newError("neither outboundTag nor balancerTag is specified in routing rule") } if rawFieldRule.DomainMatcher != "" { rule.DomainMatcher = rawFieldRule.DomainMatcher } if rawFieldRule.Domain != nil { for _, domain := range *rawFieldRule.Domain { rules, err := parseDomainRule(ctx, domain) if err != nil { return nil, newError("failed to parse domain rule: ", domain).Base(err) } rule.Domain = append(rule.Domain, rules...) } } if rawFieldRule.Domains != nil { for _, domain := range *rawFieldRule.Domains { rules, err := parseDomainRule(ctx, domain) if err != nil { return nil, newError("failed to parse domain rule: ", domain).Base(err) } rule.Domain = append(rule.Domain, rules...) } } if rawFieldRule.IP != nil { geoipList, err := toCidrList(ctx, *rawFieldRule.IP) if err != nil { return nil, err } rule.Geoip = geoipList } if rawFieldRule.Port != nil { rule.PortList = rawFieldRule.Port.Build() } if rawFieldRule.Network != nil { rule.Networks = rawFieldRule.Network.Build() } if rawFieldRule.SourceIP != nil { geoipList, err := toCidrList(ctx, *rawFieldRule.SourceIP) if err != nil { return nil, err } rule.SourceGeoip = geoipList } if rawFieldRule.SourcePort != nil { rule.SourcePortList = rawFieldRule.SourcePort.Build() } if rawFieldRule.User != nil { for _, s := range *rawFieldRule.User { rule.UserEmail = append(rule.UserEmail, s) } } if rawFieldRule.InboundTag != nil { for _, s := range *rawFieldRule.InboundTag { rule.InboundTag = append(rule.InboundTag, s) } } if rawFieldRule.Protocols != nil { for _, s := range *rawFieldRule.Protocols { rule.Protocol = append(rule.Protocol, s) } } if len(rawFieldRule.Attributes) > 0 { rule.Attributes = rawFieldRule.Attributes } return rule, nil } func ParseRule(ctx context.Context, msg json.RawMessage) (*router.RoutingRule, error) { rawRule := new(RouterRule) err := json.Unmarshal(msg, rawRule) if err != nil { return nil, newError("invalid router rule").Base(err) } if strings.EqualFold(rawRule.Type, "field") { fieldrule, err := parseFieldRule(ctx, msg) if err != nil { return nil, newError("invalid field rule").Base(err) } return fieldrule, nil } return nil, newError("unknown router rule type: ", rawRule.Type) } func ParseIP(s string) (*routercommon.CIDR, error) { var addr, mask string i := strings.Index(s, "/") if i < 0 { addr = s } else { addr = s[:i] mask = s[i+1:] } ip := net.ParseAddress(addr) switch ip.Family() { case net.AddressFamilyIPv4: bits := uint32(32) if len(mask) > 0 { bits64, err := strconv.ParseUint(mask, 10, 32) if err != nil { return nil, newError("invalid network mask for router: ", mask).Base(err) } bits = uint32(bits64) } if bits > 32 { return nil, newError("invalid network mask for router: ", bits) } return &routercommon.CIDR{ Ip: []byte(ip.IP()), Prefix: bits, }, nil case net.AddressFamilyIPv6: bits := uint32(128) if len(mask) > 0 { bits64, err := strconv.ParseUint(mask, 10, 32) if err != nil { return nil, newError("invalid network mask for router: ", mask).Base(err) } bits = uint32(bits64) } if bits > 128 { return nil, newError("invalid network mask for router: ", bits) } return &routercommon.CIDR{ Ip: []byte(ip.IP()), Prefix: bits, }, nil default: return nil, newError("unsupported address for router: ", s) } } func ParseDomainRule(ctx context.Context, domain string) ([]*routercommon.Domain, error) { return parseDomainRule(ctx, domain) } func ToCidrList(ctx context.Context, ips cfgcommon.StringList) ([]*routercommon.GeoIP, error) { return toCidrList(ctx, ips) } type RouterRule struct { Type string `json:"type"` OutboundTag string `json:"outboundTag"` BalancerTag string `json:"balancerTag"` DomainMatcher string `json:"domainMatcher"` }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/merge.go
infra/conf/mergers/merge.go
package mergers import ( "io" "path/filepath" "strings" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common/cmdarg" ) // MergeAs load input and merge as specified format into m func MergeAs(formatName string, input interface{}, m map[string]interface{}) error { f, found := mergersByName[formatName] if !found { return newError("format merger not found for: ", formatName) } return f.Merge(input, m) } // Merge loads inputs and merges them into m // it detects extension for merger selecting, or try all mergers // if no extension found func Merge(input interface{}, m map[string]interface{}) error { if input == nil { return nil } switch v := input.(type) { case string: err := mergeSingleFile(v, m) if err != nil { return err } case []string: for _, file := range v { err := mergeSingleFile(file, m) if err != nil { return err } } case cmdarg.Arg: for _, file := range v { err := mergeSingleFile(file, m) if err != nil { return err } } case []byte: err := mergeSingleFile(v, m) if err != nil { return err } case io.Reader: // read to []byte incase it tries different mergers bs, err := io.ReadAll(v) if err != nil { return err } err = mergeSingleFile(bs, m) if err != nil { return err } default: return newError("unknown merge input type") } return nil } func mergeSingleFile(input interface{}, m map[string]interface{}) error { if file, ok := input.(string); ok { ext := getExtension(file) if ext != "" { lext := strings.ToLower(ext) f, found := mergersByExt[lext] if !found { return newError("unmergeable format extension: ", ext) } return f.Merge(file, m) } } // no extension, try all mergers for _, f := range mergersByName { if f.Name == core.FormatAuto { continue } err := f.Merge(input, m) if err == nil { return nil } } return newError("tried all mergers but failed for: ", input).AtWarning() } func getExtension(filename string) string { ext := filepath.Ext(filename) return strings.ToLower(ext) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/errors.generated.go
infra/conf/mergers/errors.generated.go
package mergers import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/names.go
infra/conf/mergers/names.go
package mergers // GetAllNames get names of all formats func GetAllNames() []string { names := make([]string, 0) for _, f := range mergersByName { names = append(names, f.Name) } return names }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/mergers.go
infra/conf/mergers/mergers.go
package mergers //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "strings" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/infra/conf/json" ) func init() { common.Must(RegisterMerger(makeMerger( core.FormatJSON, []string{".json", ".jsonc"}, nil, ))) common.Must(RegisterMerger(makeMerger( core.FormatTOML, []string{".toml"}, json.FromTOML, ))) common.Must(RegisterMerger(makeMerger( core.FormatYAML, []string{".yml", ".yaml"}, json.FromYAML, ))) common.Must(RegisterMerger( &Merger{ Name: core.FormatAuto, Extensions: nil, Merge: Merge, }), ) } // Merger is a configurable format merger for V2Ray config files. type Merger struct { Name string Extensions []string Merge MergeFunc } // MergeFunc is a utility to merge V2Ray config from external source into a map and returns it. type MergeFunc func(input interface{}, m map[string]interface{}) error var ( mergersByName = make(map[string]*Merger) mergersByExt = make(map[string]*Merger) ) // RegisterMerger add a new Merger. func RegisterMerger(format *Merger) error { if _, found := mergersByName[format.Name]; found { return newError(format.Name, " already registered.") } mergersByName[format.Name] = format for _, ext := range format.Extensions { lext := strings.ToLower(ext) if f, found := mergersByExt[lext]; found { return newError(ext, " already registered to ", f.Name) } mergersByExt[lext] = format } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/extensions.go
infra/conf/mergers/extensions.go
package mergers import "strings" // GetExtensions get extensions of given format func GetExtensions(formatName string) ([]string, error) { lowerName := strings.ToLower(formatName) if lowerName == "auto" { return GetAllExtensions(), nil } f, found := mergersByName[lowerName] if !found { return nil, newError(formatName+" not found", formatName).AtWarning() } return f.Extensions, nil } // GetAllExtensions get all extensions supported func GetAllExtensions() []string { extensions := make([]string, 0) for _, f := range mergersByName { extensions = append(extensions, f.Extensions...) } return extensions }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/mergers/merger_base.go
infra/conf/mergers/merger_base.go
package mergers import ( "fmt" "io" "github.com/v2fly/v2ray-core/v5/common/cmdarg" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/infra/conf/merge" ) type jsonConverter func(v []byte) ([]byte, error) // makeMerger makes a merger who merge the format by converting it to JSON func makeMerger(name string, extensions []string, converter jsonConverter) *Merger { return &Merger{ Name: name, Extensions: extensions, Merge: makeToJSONMergeFunc(converter), } } // makeToJSONMergeFunc makes a merge func who merge the format by converting it to JSON func makeToJSONMergeFunc(converter func(v []byte) ([]byte, error)) MergeFunc { return func(input interface{}, target map[string]interface{}) error { if input == nil { return nil } if target == nil { return errors.New("merge target is nil") } switch v := input.(type) { case string: err := loadFile(v, target, converter) if err != nil { return err } case []string: err := loadFiles(v, target, converter) if err != nil { return err } case cmdarg.Arg: err := loadFiles(v, target, converter) if err != nil { return err } case []byte: err := loadBytes(v, target, converter) if err != nil { return err } case io.Reader: err := loadReader(v, target, converter) if err != nil { return err } default: return newError("unknown merge input type") } return nil } } func loadFiles(files []string, target map[string]interface{}, converter func(v []byte) ([]byte, error)) error { for _, file := range files { err := loadFile(file, target, converter) if err != nil { return err } } return nil } func loadFile(file string, target map[string]interface{}, converter func(v []byte) ([]byte, error)) error { bs, err := cmdarg.LoadArgToBytes(file) if err != nil { return fmt.Errorf("fail to load %s: %s", file, err) } if converter != nil { bs, err = converter(bs) if err != nil { return fmt.Errorf("error convert to json '%s': %s", file, err) } } _, err = merge.ToMap(bs, target) return err } func loadReader(reader io.Reader, target map[string]interface{}, converter func(v []byte) ([]byte, error)) error { bs, err := io.ReadAll(reader) if err != nil { return err } return loadBytes(bs, target, converter) } func loadBytes(bs []byte, target map[string]interface{}, converter func(v []byte) ([]byte, error)) error { var err error if converter != nil { bs, err = converter(bs) if err != nil { return fmt.Errorf("fail to convert to json: %s", err) } } _, err = merge.ToMap(bs, target) return err }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/jsonpb/jsonpb.go
infra/conf/jsonpb/jsonpb.go
package jsonpb import ( "bytes" "io" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/cmdarg" "github.com/v2fly/v2ray-core/v5/common/serial" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen func loadJSONPB(data io.Reader) (*core.Config, error) { coreconf := &core.Config{} jsonpbloader := &jsonpb.Unmarshaler{AnyResolver: serial.GetResolver()} err := jsonpbloader.Unmarshal(data, coreconf) if err != nil { return nil, err } return coreconf, nil } func dumpJSONPb(config proto.Message, w io.Writer) error { jsonpbdumper := &jsonpb.Marshaler{AnyResolver: serial.GetResolver()} err := jsonpbdumper.Marshal(w, config) if err != nil { return err } return nil } func DumpJSONPb(config proto.Message, w io.Writer) error { return dumpJSONPb(config, w) } const FormatProtobufJSONPB = "jsonpb" func init() { common.Must(core.RegisterConfigLoader(&core.ConfigFormat{ Name: []string{FormatProtobufJSONPB}, Extension: []string{".pb.json", ".pbjson"}, Loader: func(input interface{}) (*core.Config, error) { switch v := input.(type) { case string: r, err := cmdarg.LoadArg(v) if err != nil { return nil, err } data, err := buf.ReadAllToBytes(r) if err != nil { return nil, err } return loadJSONPB(bytes.NewReader(data)) case []byte: return loadJSONPB(bytes.NewReader(v)) case io.Reader: data, err := buf.ReadAllToBytes(v) if err != nil { return nil, err } return loadJSONPB(bytes.NewReader(data)) default: return nil, newError("unknown type") } }, })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/jsonpb/errors.generated.go
infra/conf/jsonpb/errors.generated.go
package jsonpb import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/json_test.go
infra/conf/json/json_test.go
package json_test import ( "encoding/json" "reflect" "testing" ) func assertResult(t *testing.T, value map[string]interface{}, expected string) { e := make(map[string]interface{}) err := json.Unmarshal([]byte(expected), &e) if err != nil { t.Error(err) } if !reflect.DeepEqual(value, e) { bs, _ := json.Marshal(value) t.Fatalf("expected:\n%s\n\nactual:\n%s", expected, string(bs)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/toml_test.go
infra/conf/json/toml_test.go
package json_test import ( "encoding/json" "testing" . "github.com/v2fly/v2ray-core/v5/infra/conf/json" ) func TestTOMLToJSON_V2Style(t *testing.T) { input := ` [log] loglevel = 'debug' [[inbounds]] port = 10800 listen = '127.0.0.1' protocol = 'socks' [inbounds.settings] udp = true [[outbounds]] protocol = 'vmess' [[outbounds.settings.vnext]] port = 443 address = 'example.com' [[outbounds.settings.vnext.users]] id = '98a15fa6-2eb1-edd5-50ea-cfc428aaab78' [outbounds.streamSettings] network = 'tcp' security = 'tls' ` expected := ` { "log": { "loglevel": "debug" }, "inbounds": [{ "port": 10800, "listen": "127.0.0.1", "protocol": "socks", "settings": { "udp": true } }], "outbounds": [{ "protocol": "vmess", "settings": { "vnext": [{ "port": 443, "address": "example.com", "users": [{ "id": "98a15fa6-2eb1-edd5-50ea-cfc428aaab78" }] }] }, "streamSettings": { "network": "tcp", "security": "tls" } }] } ` bs, err := FromTOML([]byte(input)) if err != nil { t.Error(err) } m := make(map[string]interface{}) json.Unmarshal(bs, &m) assertResult(t, m, expected) } func TestTOMLToJSON_ValueTypes(t *testing.T) { input := ` boolean = [ true, false, true, false ] float = [ 3.14, 685_230.15 ] int = [ 123, 685_230 ] string = [ "哈哈", "Hello world", "newline newline2" ] date = [ "2018-02-17" ] datetime = [ "2018-02-17T15:02:31+08:00" ] 1 = 0 true = true str = "hello" [null] nodeName = "node" ` expected := ` { "boolean": [true, false, true, false], "float": [3.14, 685230.15], "int": [123, 685230], "null": { "nodeName": "node" }, "string": ["哈哈", "Hello world", "newline newline2"], "date": ["2018-02-17"], "datetime": ["2018-02-17T15:02:31+08:00"], "1": 0, "true": true, "str": "hello" } ` bs, err := FromTOML([]byte(input)) if err != nil { t.Error(err) } m := make(map[string]interface{}) json.Unmarshal(bs, &m) assertResult(t, m, expected) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/yaml_test.go
infra/conf/json/yaml_test.go
package json_test import ( "encoding/json" "testing" . "github.com/v2fly/v2ray-core/v5/infra/conf/json" ) func TestYMLToJSON_V2Style(t *testing.T) { input := ` log: loglevel: debug inbounds: - port: 10800 listen: 127.0.0.1 protocol: socks settings: udp: true outbounds: - protocol: vmess settings: vnext: - address: example.com port: 443 users: - id: '98a15fa6-2eb1-edd5-50ea-cfc428aaab78' streamSettings: network: tcp security: tls ` expected := ` { "log": { "loglevel": "debug" }, "inbounds": [{ "port": 10800, "listen": "127.0.0.1", "protocol": "socks", "settings": { "udp": true } }], "outbounds": [{ "protocol": "vmess", "settings": { "vnext": [{ "port": 443, "address": "example.com", "users": [{ "id": "98a15fa6-2eb1-edd5-50ea-cfc428aaab78" }] }] }, "streamSettings": { "network": "tcp", "security": "tls" } }] } ` bs, err := FromYAML([]byte(input)) if err != nil { t.Error(err) } m := make(map[string]interface{}) json.Unmarshal(bs, &m) assertResult(t, m, expected) } func TestYMLToJSON_ValueTypes(t *testing.T) { input := ` boolean: - TRUE - FALSE - true - false float: - 3.14 - 6.8523015e+5 int: - 123 - 0b1010_0111_0100_1010_1110 null: nodeName: 'node' parent: ~ # ~ for null string: - 哈哈 - 'Hello world' - newline newline2 # multi-line string date: - 2018-02-17 # yyyy-MM-dd datetime: - 2018-02-17T15:02:31+08:00 # ISO 8601 time mixed: - true - false - 1 - 0 - null - hello # arbitrary keys 1: 0 true: false TRUE: TRUE "str": "hello" ` expected := ` { "boolean": [true, false, true, false], "float": [3.14, 685230.15], "int": [123, 685230], "null": { "nodeName": "node", "parent": null }, "string": ["哈哈", "Hello world", "newline newline2"], "date": ["2018-02-17T00:00:00Z"], "datetime": ["2018-02-17T15:02:31+08:00"], "mixed": [true,false,1,0,null,"hello"], "1": 0, "true": true, "str": "hello" } ` bs, err := FromYAML([]byte(input)) if err != nil { t.Error(err) } m := make(map[string]interface{}) json.Unmarshal(bs, &m) assertResult(t, m, expected) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/reader.go
infra/conf/json/reader.go
package json import ( "io" "github.com/v2fly/v2ray-core/v5/common/buf" ) // State is the internal state of parser. type State byte const ( StateContent State = iota StateEscape StateDoubleQuote StateDoubleQuoteEscape StateSingleQuote StateSingleQuoteEscape StateComment StateSlash StateMultilineComment StateMultilineCommentStar ) // Reader is a reader for filtering comments. // It supports Java style single and multi line comment syntax, and Python style single line comment syntax. type Reader struct { io.Reader state State pending []byte br *buf.BufferedReader } // Read implements io.Reader.Read(). func (v *Reader) Read(b []byte) (int, error) { if v.br == nil { v.br = &buf.BufferedReader{Reader: buf.NewReader(v.Reader)} } p := b[:0] for len(p) < len(b) { if len(v.pending) > 0 { max := len(b) - len(p) if max > len(v.pending) { max = len(v.pending) } p = append(p, v.pending[:max]...) v.pending = v.pending[max:] continue } x, err := v.br.ReadByte() if err != nil { if len(p) == 0 { return 0, err } return len(p), nil } switch v.state { case StateContent: switch x { case '"': v.state = StateDoubleQuote p = append(p, x) case '\'': v.state = StateSingleQuote p = append(p, x) case '\\': v.state = StateEscape p = append(p, x) case '#': v.state = StateComment case '/': v.state = StateSlash default: p = append(p, x) } case StateEscape: p = append(p, x) v.state = StateContent case StateDoubleQuote: switch x { case '"': v.state = StateContent p = append(p, x) case '\\': v.state = StateDoubleQuoteEscape p = append(p, x) default: p = append(p, x) } case StateDoubleQuoteEscape: p = append(p, x) v.state = StateDoubleQuote case StateSingleQuote: switch x { case '\'': v.state = StateContent p = append(p, x) case '\\': v.state = StateSingleQuoteEscape p = append(p, x) default: p = append(p, x) } case StateSingleQuoteEscape: p = append(p, x) v.state = StateSingleQuote case StateComment: if x == '\n' { v.state = StateContent p = append(p, x) } case StateSlash: switch x { case '/': v.state = StateComment case '*': v.state = StateMultilineComment default: v.state = StateContent v.pending = append(v.pending, x) p = append(p, '/') } case StateMultilineComment: switch x { case '*': v.state = StateMultilineCommentStar case '\n': p = append(p, x) } case StateMultilineCommentStar: switch x { case '/': v.state = StateContent case '*': // Stay case '\n': p = append(p, x) default: v.state = StateMultilineComment } default: panic("Unknown state.") } } return len(p), nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/yaml.go
infra/conf/json/yaml.go
package json import ( "encoding/json" "fmt" "gopkg.in/yaml.v3" ) // FromYAML convert yaml to json func FromYAML(v []byte) ([]byte, error) { m1 := make(map[interface{}]interface{}) err := yaml.Unmarshal(v, &m1) if err != nil { return nil, err } m2 := convert(m1) j, err := json.Marshal(m2) if err != nil { return nil, err } return j, nil } func convert(m map[interface{}]interface{}) map[string]interface{} { res := map[string]interface{}{} for k, v := range m { var value interface{} switch v2 := v.(type) { case map[interface{}]interface{}: value = convert(v2) case []interface{}: for i, el := range v2 { if m, ok := el.(map[interface{}]interface{}); ok { v2[i] = convert(m) } } value = v2 default: value = v } key := "null" if k != nil { key = fmt.Sprint(k) } res[key] = value } return res }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/reader_test.go
infra/conf/json/reader_test.go
package json_test import ( "bytes" "io" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/infra/conf/json" ) func TestReader(t *testing.T) { data := []struct { input string output string }{ { ` content #comment 1 #comment 2 content 2`, ` content content 2`, }, {`content`, `content`}, {" ", " "}, {`con/*abcd*/tent`, "content"}, {` text // adlkhdf /* //comment adfkj text 2*/`, ` text text 2*`}, {`"//"content`, `"//"content`}, {`abcd'//'abcd`, `abcd'//'abcd`}, {`"\""`, `"\""`}, {`\"/*abcd*/\"`, `\"\"`}, } for _, testCase := range data { reader := &Reader{ Reader: bytes.NewReader([]byte(testCase.input)), } actual := make([]byte, 1024) n, err := reader.Read(actual) common.Must(err) if r := cmp.Diff(string(actual[:n]), testCase.output); r != "" { t.Error(r) } } } func TestReader1(t *testing.T) { type dataStruct struct { input string output string } bufLen := 1 data := []dataStruct{ {"loooooooooooooooooooooooooooooooooooooooog", "loooooooooooooooooooooooooooooooooooooooog"}, {`{"t": "\/testlooooooooooooooooooooooooooooong"}`, `{"t": "\/testlooooooooooooooooooooooooooooong"}`}, {`{"t": "\/test"}`, `{"t": "\/test"}`}, {`"\// fake comment"`, `"\// fake comment"`}, {`"\/\/\/\/\/"`, `"\/\/\/\/\/"`}, {`/test/test`, `/test/test`}, } for _, testCase := range data { reader := &Reader{ Reader: bytes.NewReader([]byte(testCase.input)), } target := make([]byte, 0) buf := make([]byte, bufLen) var n int var err error for n, err = reader.Read(buf); err == nil; n, err = reader.Read(buf) { if n > len(buf) { t.Error("n: ", n) } target = append(target, buf[:n]...) buf = make([]byte, bufLen) } if err != nil && err != io.EOF { t.Error("error: ", err) } if string(target) != testCase.output { t.Error("got ", string(target), " want ", testCase.output) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/json/toml.go
infra/conf/json/toml.go
package json import ( "bytes" "encoding/json" "io" "github.com/pelletier/go-toml" ) // FromTOML convert toml to json func FromTOML(v []byte) ([]byte, error) { tomlReader := bytes.NewReader(v) jsonStr, err := jsonFromTomlReader(tomlReader) if err != nil { return nil, err } return []byte(jsonStr), nil } func jsonFromTomlReader(r io.Reader) (string, error) { tree, err := toml.LoadReader(r) if err != nil { return "", err } return mapToJSON(tree) } func mapToJSON(tree *toml.Tree) (string, error) { treeMap := tree.ToMap() bytes, err := json.MarshalIndent(treeMap, "", " ") if err != nil { return "", err } return string(bytes), nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/init.go
infra/conf/v5cfg/init.go
package v5cfg import ( "bytes" "io" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/cmdarg" "github.com/v2fly/v2ray-core/v5/infra/conf/json" ) const jsonV5 = "jsonv5" func init() { common.Must(core.RegisterConfigLoader(&core.ConfigFormat{ Name: []string{jsonV5}, Extension: []string{".v5.json", ".v5.jsonc"}, Loader: func(input interface{}) (*core.Config, error) { switch v := input.(type) { case string: r, err := cmdarg.LoadArg(v) if err != nil { return nil, err } data, err := buf.ReadAllToBytes(&json.Reader{ Reader: r, }) if err != nil { return nil, err } return loadJSONConfig(data) case []byte: r := &json.Reader{ Reader: bytes.NewReader(v), } data, err := buf.ReadAllToBytes(r) if err != nil { return nil, err } return loadJSONConfig(data) case io.Reader: data, err := buf.ReadAllToBytes(&json.Reader{ Reader: v, }) if err != nil { return nil, err } return loadJSONConfig(data) default: return nil, newError("unknown type") } }, })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/inbound.go
infra/conf/v5cfg/inbound.go
package v5cfg import ( "context" "path/filepath" "github.com/golang/protobuf/proto" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/proxy/dokodemo" "github.com/v2fly/v2ray-core/v5/transport/internet" ) func (c InboundConfig) BuildV5(ctx context.Context) (proto.Message, error) { receiverSettings := &proxyman.ReceiverConfig{} if c.ListenOn == nil { // Listen on anyip, must set PortRange if c.PortRange == nil { return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.") } receiverSettings.PortRange = c.PortRange.Build() } else { // Listen on specific IP or Unix Domain Socket receiverSettings.Listen = c.ListenOn.Build() listenDS := c.ListenOn.Family().IsDomain() && (filepath.IsAbs(c.ListenOn.Domain()) || c.ListenOn.Domain()[0] == '@') listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost") switch { case listenIP: // Listen on specific IP, must set PortRange if c.PortRange == nil { return nil, newError("Listen on specific ip without port in InboundDetour.") } // Listen on IP:Port receiverSettings.PortRange = c.PortRange.Build() case listenDS: if c.PortRange != nil { // Listen on Unix Domain Socket, PortRange should be nil receiverSettings.PortRange = nil } default: return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain()) } } if c.StreamSetting != nil { ss, err := c.StreamSetting.BuildV5(ctx) if err != nil { return nil, err } receiverSettings.StreamSettings = ss.(*internet.StreamConfig) } if c.SniffingConfig != nil { s, err := c.SniffingConfig.Build() if err != nil { return nil, newError("failed to build sniffing config").Base(err) } receiverSettings.SniffingSettings = s } if c.Settings == nil { c.Settings = []byte("{}") } inboundConfigPack, err := loadHeterogeneousConfigFromRawJSON("inbound", c.Protocol, c.Settings) if err != nil { return nil, newError("unable to load inbound protocol config").Base(err) } if content, ok := inboundConfigPack.(*dokodemo.SimplifiedConfig); ok { receiverSettings.ReceiveOriginalDestination = content.FollowRedirect } if content, ok := inboundConfigPack.(*dokodemo.Config); ok { receiverSettings.ReceiveOriginalDestination = content.FollowRedirect } return &core.InboundHandlerConfig{ Tag: c.Tag, ReceiverSettings: serial.ToTypedMessage(receiverSettings), ProxySettings: serial.ToTypedMessage(inboundConfigPack), }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/root.go
infra/conf/v5cfg/root.go
package v5cfg import ( "bytes" "context" "encoding/json" "fmt" "github.com/golang/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/dispatcher" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/log" ) func (c RootConfig) BuildV5(ctx context.Context) (proto.Message, error) { config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), }, } var logConfMsg *anypb.Any if c.LogConfig != nil { logConfMsgUnpacked, err := loadHeterogeneousConfigFromRawJSON("service", "log", c.LogConfig) if err != nil { return nil, newError("failed to parse Log config").Base(err) } logConfMsg = serial.ToTypedMessage(logConfMsgUnpacked) } else { logConfMsg = serial.ToTypedMessage(log.DefaultLogConfig()) } // let logger module be the first App to start, // so that other modules could print log during initiating config.App = append([]*anypb.Any{logConfMsg}, config.App...) if c.RouterConfig != nil { routerConfig, err := loadHeterogeneousConfigFromRawJSON("service", "router", c.RouterConfig) if err != nil { return nil, newError("failed to parse Router config").Base(err) } config.App = append(config.App, serial.ToTypedMessage(routerConfig)) } if c.DNSConfig != nil { dnsApp, err := loadHeterogeneousConfigFromRawJSON("service", "dns", c.DNSConfig) if err != nil { return nil, newError("failed to parse DNS config").Base(err) } config.App = append(config.App, serial.ToTypedMessage(dnsApp)) } for _, rawInboundConfig := range c.Inbounds { ic, err := rawInboundConfig.BuildV5(ctx) if err != nil { return nil, err } config.Inbound = append(config.Inbound, ic.(*core.InboundHandlerConfig)) } for _, rawOutboundConfig := range c.Outbounds { ic, err := rawOutboundConfig.BuildV5(ctx) if err != nil { return nil, err } config.Outbound = append(config.Outbound, ic.(*core.OutboundHandlerConfig)) } for serviceName, service := range c.Services { servicePackedConfig, err := loadHeterogeneousConfigFromRawJSON("service", serviceName, service) if err != nil { return nil, newError(fmt.Sprintf("failed to parse %v config in Services", serviceName)).Base(err) } config.App = append(config.App, serial.ToTypedMessage(servicePackedConfig)) } return config, nil } func loadJSONConfig(data []byte) (*core.Config, error) { rootConfig := &RootConfig{} rootConfDecoder := json.NewDecoder(bytes.NewReader(data)) rootConfDecoder.DisallowUnknownFields() err := rootConfDecoder.Decode(rootConfig) if err != nil { return nil, newError("unable to load json").Base(err) } buildctx := cfgcommon.NewConfigureLoadingContext(context.Background()) geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string { return "standard" }) if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil { cfgcommon.SetGeoDataLoader(buildctx, loader) } else { return nil, newError("unable to create geo data loader ").Base(err) } message, err := rootConfig.BuildV5(buildctx) if err != nil { return nil, newError("unable to build config").Base(err) } return message.(*core.Config), nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/errors.generated.go
infra/conf/v5cfg/errors.generated.go
package v5cfg import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/stream.go
infra/conf/v5cfg/stream.go
package v5cfg import ( "context" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/transport/internet" ) func (s StreamConfig) BuildV5(ctx context.Context) (proto.Message, error) { config := &internet.StreamConfig{} if s.Transport == "" { s.Transport = "tcp" } if s.Security == "" { s.Security = "none" } if s.TransportSettings == nil { s.TransportSettings = []byte("{}") } transportConfigPack, err := loadHeterogeneousConfigFromRawJSON("transport", s.Transport, s.TransportSettings) if err != nil { return nil, newError("unable to load transport config").Base(err) } config.ProtocolName = s.Transport config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ ProtocolName: s.Transport, Settings: serial.ToTypedMessage(transportConfigPack), }) if s.Security != "none" { if s.SecuritySettings == nil { s.SecuritySettings = []byte("{}") } securityConfigPack, err := loadHeterogeneousConfigFromRawJSON("security", s.Security, s.SecuritySettings) if err != nil { return nil, newError("unable to load security config").Base(err) } securityConfigPackTypedMessage := serial.ToTypedMessage(securityConfigPack) config.SecurityType = serial.V2Type(securityConfigPackTypedMessage) config.SecuritySettings = append(config.SecuritySettings, securityConfigPackTypedMessage) } config.SocketSettings, err = s.SocketSettings.Build() if err != nil { return nil, newError("unable to build socket config").Base(err) } return config, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/outbound.go
infra/conf/v5cfg/outbound.go
package v5cfg import ( "context" "github.com/golang/protobuf/proto" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/transport/internet" ) func (c OutboundConfig) BuildV5(ctx context.Context) (proto.Message, error) { senderSettings := &proxyman.SenderConfig{} if c.SendThrough != nil { address := c.SendThrough if address.Family().IsDomain() { return nil, newError("unable to send through: " + address.String()) } senderSettings.Via = address.Build() } if c.StreamSetting != nil { ss, err := c.StreamSetting.BuildV5(ctx) if err != nil { return nil, err } senderSettings.StreamSettings = ss.(*internet.StreamConfig) } if c.ProxySettings != nil { ps, err := c.ProxySettings.Build() if err != nil { return nil, newError("invalid outbound detour proxy settings.").Base(err) } senderSettings.ProxySettings = ps } if c.MuxSettings != nil { senderSettings.MultiplexSettings = c.MuxSettings.Build() } senderSettings.DomainStrategy = proxyman.SenderConfig_AS_IS switch c.DomainStrategy { case "UseIP": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP case "UseIP4": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP4 case "UseIP6": senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP6 case "AsIs", "": default: return nil, newError("unknown domain strategy: ", c.DomainStrategy) } if c.Settings == nil { c.Settings = []byte("{}") } outboundConfigPack, err := loadHeterogeneousConfigFromRawJSON("outbound", c.Protocol, c.Settings) if err != nil { return nil, newError("unable to load outbound protocol config").Base(err) } return &core.OutboundHandlerConfig{ SenderSettings: serial.ToTypedMessage(senderSettings), Tag: c.Tag, ProxySettings: serial.ToTypedMessage(outboundConfigPack), }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/v5cfg.go
infra/conf/v5cfg/v5cfg.go
package v5cfg //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/skeleton.go
infra/conf/v5cfg/skeleton.go
package v5cfg import ( "encoding/json" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/muxcfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/proxycfg" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/sniffer" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/socketcfg" ) type RootConfig struct { LogConfig json.RawMessage `json:"log"` DNSConfig json.RawMessage `json:"dns"` RouterConfig json.RawMessage `json:"router"` Inbounds []InboundConfig `json:"inbounds"` Outbounds []OutboundConfig `json:"outbounds"` Services map[string]json.RawMessage `json:"services"` Extensions []json.RawMessage `json:"extension"` } type InboundConfig struct { Protocol string `json:"protocol"` PortRange *cfgcommon.PortRange `json:"port"` ListenOn *cfgcommon.Address `json:"listen"` Settings json.RawMessage `json:"settings"` Tag string `json:"tag"` SniffingConfig *sniffer.SniffingConfig `json:"sniffing"` StreamSetting *StreamConfig `json:"streamSettings"` } type OutboundConfig struct { Protocol string `json:"protocol"` SendThrough *cfgcommon.Address `json:"sendThrough"` Tag string `json:"tag"` Settings json.RawMessage `json:"settings"` StreamSetting *StreamConfig `json:"streamSettings"` ProxySettings *proxycfg.ProxyConfig `json:"proxySettings"` MuxSettings *muxcfg.MuxConfig `json:"mux"` DomainStrategy string `json:"domainStrategy"` } type StreamConfig struct { Transport string `json:"transport"` TransportSettings json.RawMessage `json:"transportSettings"` Security string `json:"security"` SecuritySettings json.RawMessage `json:"securitySettings"` SocketSettings socketcfg.SocketConfig `json:"socketSettings"` }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v5cfg/common.go
infra/conf/v5cfg/common.go
package v5cfg import ( "context" "encoding/json" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/environment/envctx" "github.com/v2fly/v2ray-core/v5/common/environment/envimpl" "github.com/v2fly/v2ray-core/v5/common/registry" ) func loadHeterogeneousConfigFromRawJSON(interfaceType, name string, rawJSON json.RawMessage) (proto.Message, error) { fsdef := envimpl.NewDefaultFileSystemDefaultImpl() ctx := envctx.ContextWithEnvironment(context.TODO(), fsdef) if len(rawJSON) == 0 { rawJSON = []byte("{}") } return registry.LoadImplementationByAlias(ctx, interfaceType, name, []byte(rawJSON)) } // LoadHeterogeneousConfigFromRawJSON private API func LoadHeterogeneousConfigFromRawJSON(ctx context.Context, interfaceType, name string, rawJSON json.RawMessage) (proto.Message, error) { return loadHeterogeneousConfigFromRawJSON(interfaceType, name, rawJSON) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/geodata.go
infra/conf/geodata/geodata.go
package geodata import ( "strings" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" ) type loader struct { LoaderImplementation } func (l *loader) LoadGeoSite(list string) ([]*routercommon.Domain, error) { return l.LoadGeoSiteWithAttr("geosite.dat", list) } func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*routercommon.Domain, error) { parts := strings.Split(siteWithAttr, "@") if len(parts) == 0 { return nil, newError("empty rule") } list := strings.TrimSpace(parts[0]) attrVal := parts[1:] if len(list) == 0 { return nil, newError("empty listname in rule: ", siteWithAttr) } domains, err := l.LoadSite(file, list) if err != nil { return nil, err } attrs := parseAttrs(attrVal) if attrs.IsEmpty() { if strings.Contains(siteWithAttr, "@") { newError("empty attribute list: ", siteWithAttr) } return domains, nil } filteredDomains := make([]*routercommon.Domain, 0, len(domains)) hasAttrMatched := false for _, domain := range domains { if attrs.Match(domain) { hasAttrMatched = true filteredDomains = append(filteredDomains, domain) } } if !hasAttrMatched { newError("attribute match no rule: geosite:", siteWithAttr) } return filteredDomains, nil } func (l *loader) LoadGeoIP(country string) ([]*routercommon.CIDR, error) { return l.LoadIP("geoip.dat", country) } var loaders map[string]func() LoaderImplementation func RegisterGeoDataLoaderImplementationCreator(name string, loader func() LoaderImplementation) { if loaders == nil { loaders = map[string]func() LoaderImplementation{} } loaders[name] = loader } func getGeoDataLoaderImplementation(name string) (LoaderImplementation, error) { if geoLoader, ok := loaders[name]; ok { return geoLoader(), nil } return nil, newError("unable to locate GeoData loader ", name) } func GetGeoDataLoader(name string) (Loader, error) { loadImpl, err := getGeoDataLoaderImplementation(name) if err == nil { return &loader{loadImpl}, nil } return nil, err }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/errors.generated.go
infra/conf/geodata/errors.generated.go
package geodata import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/geodataproto.go
infra/conf/geodata/geodataproto.go
package geodata import ( "github.com/v2fly/v2ray-core/v5/app/router/routercommon" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type LoaderImplementation interface { LoadSite(filename, list string) ([]*routercommon.Domain, error) LoadIP(filename, country string) ([]*routercommon.CIDR, error) } type Loader interface { LoaderImplementation LoadGeoSite(list string) ([]*routercommon.Domain, error) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*routercommon.Domain, error) LoadGeoIP(country string) ([]*routercommon.CIDR, error) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/geodata_test.go
infra/conf/geodata/geodata_test.go
package geodata_test import ( "errors" "io/fs" "os" "path/filepath" "runtime" "testing" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/memconservative" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/standard" ) func init() { const ( geoipURL = "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat" geositeURL = "https://raw.githubusercontent.com/v2fly/domain-list-community/release/dlc.dat" ) wd, err := os.Getwd() common.Must(err) tempPath := filepath.Join(wd, "..", "..", "..", "testing", "temp") geoipPath := filepath.Join(tempPath, "geoip.dat") geositePath := filepath.Join(tempPath, "geosite.dat") os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) } } func BenchmarkStandardLoaderGeoIP(b *testing.B) { standardLoader, err := geodata.GetGeoDataLoader("standard") common.Must(err) m1 := runtime.MemStats{} m2 := runtime.MemStats{} runtime.ReadMemStats(&m1) standardLoader.LoadGeoIP("cn") standardLoader.LoadGeoIP("us") standardLoader.LoadGeoIP("private") runtime.ReadMemStats(&m2) b.ReportMetric(float64(m2.Alloc-m1.Alloc)/1024/1024, "MiB(GeoIP-Alloc)") b.ReportMetric(float64(m2.TotalAlloc-m1.TotalAlloc)/1024/1024, "MiB(GeoIP-TotalAlloc)") } func BenchmarkStandardLoaderGeoSite(b *testing.B) { standardLoader, err := geodata.GetGeoDataLoader("standard") common.Must(err) m3 := runtime.MemStats{} m4 := runtime.MemStats{} runtime.ReadMemStats(&m3) standardLoader.LoadGeoSite("cn") standardLoader.LoadGeoSite("geolocation-!cn") standardLoader.LoadGeoSite("private") runtime.ReadMemStats(&m4) b.ReportMetric(float64(m4.Alloc-m3.Alloc)/1024/1024, "MiB(GeoSite-Alloc)") b.ReportMetric(float64(m4.TotalAlloc-m3.TotalAlloc)/1024/1024, "MiB(GeoSite-TotalAlloc)") } func BenchmarkMemconservativeLoaderGeoIP(b *testing.B) { standardLoader, err := geodata.GetGeoDataLoader("memconservative") common.Must(err) m1 := runtime.MemStats{} m2 := runtime.MemStats{} runtime.ReadMemStats(&m1) standardLoader.LoadGeoIP("cn") standardLoader.LoadGeoIP("us") standardLoader.LoadGeoIP("private") runtime.ReadMemStats(&m2) b.ReportMetric(float64(m2.Alloc-m1.Alloc)/1024, "KiB(GeoIP-Alloc)") b.ReportMetric(float64(m2.TotalAlloc-m1.TotalAlloc)/1024/1024, "MiB(GeoIP-TotalAlloc)") } func BenchmarkMemconservativeLoaderGeoSite(b *testing.B) { standardLoader, err := geodata.GetGeoDataLoader("memconservative") common.Must(err) m3 := runtime.MemStats{} m4 := runtime.MemStats{} runtime.ReadMemStats(&m3) standardLoader.LoadGeoSite("cn") standardLoader.LoadGeoSite("geolocation-!cn") standardLoader.LoadGeoSite("private") runtime.ReadMemStats(&m4) b.ReportMetric(float64(m4.Alloc-m3.Alloc)/1024, "KiB(GeoSite-Alloc)") b.ReportMetric(float64(m4.TotalAlloc-m3.TotalAlloc)/1024/1024, "MiB(GeoSite-TotalAlloc)") } func BenchmarkAllLoader(b *testing.B) { type testingProfileForLoader struct { name string } testCase := []testingProfileForLoader{ {"standard"}, {"memconservative"}, } for _, v := range testCase { b.Run(v.name, func(b *testing.B) { b.Run("Geosite", func(b *testing.B) { loader, err := geodata.GetGeoDataLoader(v.name) if err != nil { b.Fatal(err) } m3 := runtime.MemStats{} m4 := runtime.MemStats{} runtime.ReadMemStats(&m3) loader.LoadGeoSite("cn") loader.LoadGeoSite("geolocation-!cn") loader.LoadGeoSite("private") runtime.ReadMemStats(&m4) b.ReportMetric(float64(m4.Alloc-m3.Alloc)/1024, "KiB(GeoSite-Alloc)") b.ReportMetric(float64(m4.TotalAlloc-m3.TotalAlloc)/1024/1024, "MiB(GeoSite-TotalAlloc)") }) b.Run("GeoIP", func(b *testing.B) { loader, err := geodata.GetGeoDataLoader(v.name) if err != nil { b.Fatal(err) } m1 := runtime.MemStats{} m2 := runtime.MemStats{} runtime.ReadMemStats(&m1) loader.LoadGeoIP("cn") loader.LoadGeoIP("us") loader.LoadGeoIP("private") runtime.ReadMemStats(&m2) b.ReportMetric(float64(m2.Alloc-m1.Alloc)/1024/1024, "MiB(GeoIP-Alloc)") b.ReportMetric(float64(m2.TotalAlloc-m1.TotalAlloc)/1024/1024, "MiB(GeoIP-TotalAlloc)") }) }) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/attr.go
infra/conf/geodata/attr.go
package geodata import ( "strings" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" ) type AttributeList struct { matcher []AttributeMatcher } func (al *AttributeList) Match(domain *routercommon.Domain) bool { for _, matcher := range al.matcher { if !matcher.Match(domain) { return false } } return true } func (al *AttributeList) IsEmpty() bool { return len(al.matcher) == 0 } func parseAttrs(attrs []string) *AttributeList { al := new(AttributeList) for _, attr := range attrs { trimmedAttr := strings.ToLower(strings.TrimSpace(attr)) if len(trimmedAttr) == 0 { continue } al.matcher = append(al.matcher, BooleanMatcher(trimmedAttr)) } return al } type AttributeMatcher interface { Match(*routercommon.Domain) bool } type BooleanMatcher string func (m BooleanMatcher) Match(domain *routercommon.Domain) bool { for _, attr := range domain.Attribute { if strings.EqualFold(attr.GetKey(), string(m)) { return true } } return false }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/standard/standard.go
infra/conf/geodata/standard/standard.go
package standard import ( "strings" "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen func loadIP(filename, country string) ([]*routercommon.CIDR, error) { geoipBytes, err := filesystem.ReadAsset(filename) if err != nil { return nil, newError("failed to open file: ", filename).Base(err) } var geoipList routercommon.GeoIPList if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil { return nil, err } for _, geoip := range geoipList.Entry { if strings.EqualFold(geoip.CountryCode, country) { return geoip.Cidr, nil } } return nil, newError("country not found in ", filename, ": ", country) } func loadSite(filename, list string) ([]*routercommon.Domain, error) { geositeBytes, err := filesystem.ReadAsset(filename) if err != nil { return nil, newError("failed to open file: ", filename).Base(err) } var geositeList routercommon.GeoSiteList if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil { return nil, err } for _, site := range geositeList.Entry { if strings.EqualFold(site.CountryCode, list) { return site.Domain, nil } } return nil, newError("list not found in ", filename, ": ", list) } type standardLoader struct{} func (d standardLoader) LoadSite(filename, list string) ([]*routercommon.Domain, error) { return loadSite(filename, list) } func (d standardLoader) LoadIP(filename, country string) ([]*routercommon.CIDR, error) { return loadIP(filename, country) } func init() { geodata.RegisterGeoDataLoaderImplementationCreator("standard", func() geodata.LoaderImplementation { return standardLoader{} }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/standard/errors.generated.go
infra/conf/geodata/standard/errors.generated.go
package standard import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false