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/infra/conf/geodata/memconservative/errors.generated.go
infra/conf/geodata/memconservative/errors.generated.go
package memconservative 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/memconservative/cache.go
infra/conf/geodata/memconservative/cache.go
package memconservative import ( "os" "strings" "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/platform" ) type GeoIPCache map[string]*routercommon.GeoIP func (g GeoIPCache) Has(key string) bool { return !(g.Get(key) == nil) } func (g GeoIPCache) Get(key string) *routercommon.GeoIP { if g == nil { return nil } return g[key] } func (g GeoIPCache) Set(key string, value *routercommon.GeoIP) { if g == nil { g = make(map[string]*routercommon.GeoIP) } g[key] = value } func (g GeoIPCache) Unmarshal(filename, code string) (*routercommon.GeoIP, error) { asset := platform.GetAssetLocation(filename) idx := strings.ToLower(asset + ":" + code) if g.Has(idx) { return g.Get(idx), nil } geoipBytes, err := Decode(asset, code) switch err { case nil: var geoip routercommon.GeoIP if err := proto.Unmarshal(geoipBytes, &geoip); err != nil { return nil, err } g.Set(idx, &geoip) return &geoip, nil case errCodeNotFound: return nil, newError("country code ", code, " not found in ", filename) case errFailedToReadBytes, errFailedToReadExpectedLenBytes, errInvalidGeodataFile, errInvalidGeodataVarintLength: newError("failed to decode geoip file: ", filename, ", fallback to the original ReadFile method") geoipBytes, err = os.ReadFile(asset) if err != nil { return nil, err } var geoipList routercommon.GeoIPList if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil { return nil, err } for _, geoip := range geoipList.GetEntry() { if strings.EqualFold(code, geoip.GetCountryCode()) { g.Set(idx, geoip) return geoip, nil } } default: return nil, err } return nil, newError("country code ", code, " not found in ", filename) } type GeoSiteCache map[string]*routercommon.GeoSite func (g GeoSiteCache) Has(key string) bool { return !(g.Get(key) == nil) } func (g GeoSiteCache) Get(key string) *routercommon.GeoSite { if g == nil { return nil } return g[key] } func (g GeoSiteCache) Set(key string, value *routercommon.GeoSite) { if g == nil { g = make(map[string]*routercommon.GeoSite) } g[key] = value } func (g GeoSiteCache) Unmarshal(filename, code string) (*routercommon.GeoSite, error) { asset := platform.GetAssetLocation(filename) idx := strings.ToLower(asset + ":" + code) if g.Has(idx) { return g.Get(idx), nil } geositeBytes, err := Decode(asset, code) switch err { case nil: var geosite routercommon.GeoSite if err := proto.Unmarshal(geositeBytes, &geosite); err != nil { return nil, err } g.Set(idx, &geosite) return &geosite, nil case errCodeNotFound: return nil, newError("list ", code, " not found in ", filename) case errFailedToReadBytes, errFailedToReadExpectedLenBytes, errInvalidGeodataFile, errInvalidGeodataVarintLength: newError("failed to decode geoip file: ", filename, ", fallback to the original ReadFile method") geositeBytes, err = os.ReadFile(asset) if err != nil { return nil, err } var geositeList routercommon.GeoSiteList if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil { return nil, err } for _, geosite := range geositeList.GetEntry() { if strings.EqualFold(code, geosite.GetCountryCode()) { g.Set(idx, geosite) return geosite, nil } } default: return nil, err } return nil, newError("list ", code, " not found in ", filename) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/memconservative/memc.go
infra/conf/geodata/memconservative/memc.go
package memconservative import ( "runtime" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type memConservativeLoader struct { geoipcache GeoIPCache geositecache GeoSiteCache } func (m *memConservativeLoader) LoadIP(filename, country string) ([]*routercommon.CIDR, error) { defer runtime.GC() geoip, err := m.geoipcache.Unmarshal(filename, country) if err != nil { return nil, newError("failed to decode geodata file: ", filename).Base(err) } return geoip.Cidr, nil } func (m *memConservativeLoader) LoadSite(filename, list string) ([]*routercommon.Domain, error) { defer runtime.GC() geosite, err := m.geositecache.Unmarshal(filename, list) if err != nil { return nil, newError("failed to decode geodata file: ", filename).Base(err) } return geosite.Domain, nil } func newMemConservativeLoader() geodata.LoaderImplementation { return &memConservativeLoader{make(map[string]*routercommon.GeoIP), make(map[string]*routercommon.GeoSite)} } func init() { geodata.RegisterGeoDataLoaderImplementationCreator("memconservative", newMemConservativeLoader) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/memconservative/decode.go
infra/conf/geodata/memconservative/decode.go
package memconservative import ( "errors" "io" "strings" "google.golang.org/protobuf/encoding/protowire" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" ) var ( errFailedToReadBytes = errors.New("failed to read bytes") errFailedToReadExpectedLenBytes = errors.New("failed to read expected length of bytes") errInvalidGeodataFile = errors.New("invalid geodata file") errInvalidGeodataVarintLength = errors.New("invalid geodata varint length") errCodeNotFound = errors.New("code not found") ) func emitBytes(f io.ReadSeeker, code string) ([]byte, error) { count := 1 isInner := false tempContainer := make([]byte, 0, 5) var result []byte var advancedN uint64 = 1 var geoDataVarintLength, codeVarintLength, varintLenByteLen uint64 = 0, 0, 0 Loop: for { container := make([]byte, advancedN) bytesRead, err := f.Read(container) if err == io.EOF { return nil, errCodeNotFound } if err != nil { return nil, errFailedToReadBytes } if bytesRead != len(container) { return nil, errFailedToReadExpectedLenBytes } switch count { case 1, 3: // data type ((field_number << 3) | wire_type) if container[0] != 10 { // byte `0A` equals to `10` in decimal return nil, errInvalidGeodataFile } advancedN = 1 count++ case 2, 4: // data length tempContainer = append(tempContainer, container...) if container[0] > 127 { // max one-byte-length byte `7F`(0FFF FFFF) equals to `127` in decimal advancedN = 1 goto Loop } lenVarint, n := protowire.ConsumeVarint(tempContainer) if n < 0 { return nil, errInvalidGeodataVarintLength } tempContainer = nil if !isInner { isInner = true geoDataVarintLength = lenVarint advancedN = 1 } else { isInner = false codeVarintLength = lenVarint varintLenByteLen = uint64(n) advancedN = codeVarintLength } count++ case 5: // data value if strings.EqualFold(string(container), code) { count++ offset := -(1 + int64(varintLenByteLen) + int64(codeVarintLength)) f.Seek(offset, 1) // back to the start of GeoIP or GeoSite varint advancedN = geoDataVarintLength // the number of bytes to be read in next round } else { count = 1 offset := int64(geoDataVarintLength) - int64(codeVarintLength) - int64(varintLenByteLen) - 1 f.Seek(offset, 1) // skip the unmatched GeoIP or GeoSite varint advancedN = 1 // the next round will be the start of another GeoIPList or GeoSiteList } case 6: // matched GeoIP or GeoSite varint result = container break Loop } } return result, nil } func Decode(filename, code string) ([]byte, error) { f, err := filesystem.NewFileSeeker(filename) if err != nil { return nil, newError("failed to open file: ", filename).Base(err) } defer f.Close() geoBytes, err := emitBytes(f, code) if err != nil { return nil, err } return geoBytes, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/geodata/memconservative/decode_test.go
infra/conf/geodata/memconservative/decode_test.go
package memconservative import ( "bytes" "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" ) 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 TestDecodeGeoIP(t *testing.T) { filename := platform.GetAssetLocation("geoip.dat") result, err := Decode(filename, "test") if err != nil { t.Error(err) } expected := []byte{10, 4, 84, 69, 83, 84, 18, 8, 10, 4, 127, 0, 0, 0, 16, 8} if !bytes.Equal(result, expected) { t.Errorf("failed to load geoip:test, expected: %v, got: %v", expected, result) } } func TestDecodeGeoSite(t *testing.T) { filename := platform.GetAssetLocation("geosite.dat") result, err := Decode(filename, "test") if err != nil { t.Error(err) } expected := []byte{10, 4, 84, 69, 83, 84, 18, 20, 8, 3, 18, 16, 116, 101, 115, 116, 46, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109} if !bytes.Equal(result, expected) { t.Errorf("failed to load geosite:test, expected: %v, got: %v", expected, result) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/serial/loader.go
infra/conf/serial/loader.go
package serial import ( "bytes" "encoding/json" "io" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common/errors" json_reader "github.com/v2fly/v2ray-core/v5/infra/conf/json" v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4" ) type offset struct { line int char int } func findOffset(b []byte, o int) *offset { if o >= len(b) || o < 0 { return nil } line := 1 char := 0 for i, x := range b { if i == o { break } if x == '\n' { line++ char = 0 } else { char++ } } return &offset{line: line, char: char} } // DecodeJSONConfig reads from reader and decode the config into *conf.Config // syntax error could be detected. func DecodeJSONConfig(reader io.Reader) (*v4.Config, error) { jsonConfig := &v4.Config{} err := DecodeJSON(reader, jsonConfig) if err != nil { return nil, err } return jsonConfig, nil } // DecodeJSON reads from reader and decode into target // syntax error could be detected. func DecodeJSON(reader io.Reader, target interface{}) error { jsonContent := bytes.NewBuffer(make([]byte, 0, 10240)) jsonReader := io.TeeReader(&json_reader.Reader{ Reader: reader, }, jsonContent) decoder := json.NewDecoder(jsonReader) if err := decoder.Decode(target); err != nil { var pos *offset cause := errors.Cause(err) switch tErr := cause.(type) { case *json.SyntaxError: pos = findOffset(jsonContent.Bytes(), int(tErr.Offset)) case *json.UnmarshalTypeError: pos = findOffset(jsonContent.Bytes(), int(tErr.Offset)) } if pos != nil { return newError("failed to read config file at line ", pos.line, " char ", pos.char).Base(err) } return newError("failed to read config file").Base(err) } return nil } func LoadJSONConfig(reader io.Reader) (*core.Config, error) { jsonConfig, err := DecodeJSONConfig(reader) if err != nil { return nil, err } pbConfig, err := jsonConfig.Build() if err != nil { return nil, newError("failed to parse json config").Base(err) } return pbConfig, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/serial/errors.generated.go
infra/conf/serial/errors.generated.go
package serial 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/serial/serial.go
infra/conf/serial/serial.go
package serial //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/serial/loader_test.go
infra/conf/serial/loader_test.go
package serial_test import ( "bytes" "strings" "testing" "github.com/v2fly/v2ray-core/v5/infra/conf/serial" ) func TestLoaderError(t *testing.T) { testCases := []struct { Input string Output string }{ { Input: `{ "log": { // abcd 0, "loglevel": "info" } }`, Output: "line 4 char 6", }, { Input: `{ "log": { // abcd "loglevel": "info", } }`, Output: "line 5 char 5", }, { Input: `{ "port": 1, "inbounds": [{ "protocol": "test" }] }`, Output: "parse json config", }, { Input: `{ "inbounds": [{ "port": 1, "listen": 0, "protocol": "test" }] }`, Output: "line 1 char 1", }, } for _, testCase := range testCases { reader := bytes.NewReader([]byte(testCase.Input)) _, err := serial.LoadJSONConfig(reader) errString := err.Error() if !strings.Contains(errString, testCase.Output) { t.Error("unexpected output from json: ", testCase.Input, ". expected ", testCase.Output, ", but actually ", errString) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/common_test.go
infra/conf/cfgcommon/common_test.go
package cfgcommon_test import ( "encoding/json" "os" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "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/infra/conf/cfgcommon" ) func TestStringListUnmarshalError(t *testing.T) { rawJSON := `1234` list := new(cfgcommon.StringList) err := json.Unmarshal([]byte(rawJSON), list) if err == nil { t.Error("expected error, but got nil") } } func TestStringListLen(t *testing.T) { rawJSON := `"a, b, c, d"` var list cfgcommon.StringList err := json.Unmarshal([]byte(rawJSON), &list) common.Must(err) if r := cmp.Diff([]string(list), []string{"a", " b", " c", " d"}); r != "" { t.Error(r) } } func TestIPParsing(t *testing.T) { rawJSON := "\"8.8.8.8\"" var address cfgcommon.Address err := json.Unmarshal([]byte(rawJSON), &address) common.Must(err) if r := cmp.Diff(address.IP(), net.IP{8, 8, 8, 8}); r != "" { t.Error(r) } } func TestDomainParsing(t *testing.T) { rawJSON := "\"v2fly.org\"" var address cfgcommon.Address common.Must(json.Unmarshal([]byte(rawJSON), &address)) if address.Domain() != "v2fly.org" { t.Error("domain: ", address.Domain()) } } func TestURLParsing(t *testing.T) { { rawJSON := "\"https://dns.google/dns-query\"" var address cfgcommon.Address common.Must(json.Unmarshal([]byte(rawJSON), &address)) if address.Domain() != "https://dns.google/dns-query" { t.Error("URL: ", address.Domain()) } } { rawJSON := "\"https+local://dns.google/dns-query\"" var address cfgcommon.Address common.Must(json.Unmarshal([]byte(rawJSON), &address)) if address.Domain() != "https+local://dns.google/dns-query" { t.Error("URL: ", address.Domain()) } } } func TestInvalidAddressJson(t *testing.T) { rawJSON := "1234" var address cfgcommon.Address err := json.Unmarshal([]byte(rawJSON), &address) if err == nil { t.Error("nil error") } } func TestStringNetwork(t *testing.T) { var network cfgcommon.Network common.Must(json.Unmarshal([]byte(`"tcp"`), &network)) if v := network.Build(); v != net.Network_TCP { t.Error("network: ", v) } } func TestArrayNetworkList(t *testing.T) { var list cfgcommon.NetworkList common.Must(json.Unmarshal([]byte("[\"Tcp\"]"), &list)) nlist := list.Build() if !net.HasNetwork(nlist, net.Network_TCP) { t.Error("no tcp network") } if net.HasNetwork(nlist, net.Network_UDP) { t.Error("has udp network") } } func TestStringNetworkList(t *testing.T) { var list cfgcommon.NetworkList common.Must(json.Unmarshal([]byte("\"TCP, ip\""), &list)) nlist := list.Build() if !net.HasNetwork(nlist, net.Network_TCP) { t.Error("no tcp network") } if net.HasNetwork(nlist, net.Network_UDP) { t.Error("has udp network") } } func TestInvalidNetworkJson(t *testing.T) { var list cfgcommon.NetworkList err := json.Unmarshal([]byte("0"), &list) if err == nil { t.Error("nil error") } } func TestIntPort(t *testing.T) { var portRange cfgcommon.PortRange common.Must(json.Unmarshal([]byte("1234"), &portRange)) if r := cmp.Diff(portRange, cfgcommon.PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestOverRangeIntPort(t *testing.T) { var portRange cfgcommon.PortRange err := json.Unmarshal([]byte("70000"), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("-1"), &portRange) if err == nil { t.Error("nil error") } } func TestEnvPort(t *testing.T) { common.Must(os.Setenv("PORT", "1234")) var portRange cfgcommon.PortRange common.Must(json.Unmarshal([]byte("\"env:PORT\""), &portRange)) if r := cmp.Diff(portRange, cfgcommon.PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestSingleStringPort(t *testing.T) { var portRange cfgcommon.PortRange common.Must(json.Unmarshal([]byte("\"1234\""), &portRange)) if r := cmp.Diff(portRange, cfgcommon.PortRange{ From: 1234, To: 1234, }); r != "" { t.Error(r) } } func TestStringPairPort(t *testing.T) { var portRange cfgcommon.PortRange common.Must(json.Unmarshal([]byte("\"1234-5678\""), &portRange)) if r := cmp.Diff(portRange, cfgcommon.PortRange{ From: 1234, To: 5678, }); r != "" { t.Error(r) } } func TestOverRangeStringPort(t *testing.T) { var portRange cfgcommon.PortRange err := json.Unmarshal([]byte("\"65536\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"70000-80000\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"1-90000\""), &portRange) if err == nil { t.Error("nil error") } err = json.Unmarshal([]byte("\"700-600\""), &portRange) if err == nil { t.Error("nil error") } } func TestUserParsing(t *testing.T) { user := new(cfgcommon.User) common.Must(json.Unmarshal([]byte(`{ "id": "96edb838-6d68-42ef-a933-25f7ac3a9d09", "email": "love@v2fly.org", "level": 1, "alterId": 100 }`), user)) nUser := user.Build() if r := cmp.Diff(nUser, &protocol.User{ Level: 1, Email: "love@v2fly.org", }, cmpopts.IgnoreUnexported(protocol.User{})); r != "" { t.Error(r) } } func TestInvalidUserJson(t *testing.T) { user := new(cfgcommon.User) err := json.Unmarshal([]byte(`{"email": 1234}`), user) if err == nil { t.Error("nil error") } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/errors.generated.go
infra/conf/cfgcommon/errors.generated.go
package cfgcommon 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/cfgcommon/buildable.go
infra/conf/cfgcommon/buildable.go
package cfgcommon import ( "context" "github.com/golang/protobuf/proto" ) type Buildable interface { Build() (proto.Message, error) } type BuildableV5 interface { BuildV5(ctx context.Context) (proto.Message, error) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/session.go
infra/conf/cfgcommon/session.go
package cfgcommon import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" ) type configureLoadingContext int const confContextKey = configureLoadingContext(1) type configureLoadingEnvironment struct { geoLoader geodata.Loader } func (c *configureLoadingEnvironment) GetGeoLoader() geodata.Loader { if c.geoLoader == nil { var err error c.geoLoader, err = geodata.GetGeoDataLoader("standard") common.Must(err) } return c.geoLoader } func (c *configureLoadingEnvironment) doNotImpl() {} type ConfigureLoadingEnvironmentCapabilitySet interface { GetGeoLoader() geodata.Loader } type ConfigureLoadingEnvironment interface { ConfigureLoadingEnvironmentCapabilitySet doNotImpl() // TODO environment.BaseEnvironmentCapabilitySet // TODO environment.FileSystemCapabilitySet } func NewConfigureLoadingContext(ctx context.Context) context.Context { environment := &configureLoadingEnvironment{} return context.WithValue(ctx, confContextKey, environment) } func GetConfigureLoadingEnvironment(ctx context.Context) ConfigureLoadingEnvironment { return ctx.Value(confContextKey).(ConfigureLoadingEnvironment) } func SetGeoDataLoader(ctx context.Context, loader geodata.Loader) { GetConfigureLoadingEnvironment(ctx).(*configureLoadingEnvironment).geoLoader = loader }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/common.go
infra/conf/cfgcommon/common.go
package cfgcommon import ( "encoding/json" "os" "strings" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type StringList []string func NewStringList(raw []string) *StringList { list := StringList(raw) return &list } func (v StringList) Len() int { return len(v) } func (v *StringList) UnmarshalJSON(data []byte) error { var strarray []string if err := json.Unmarshal(data, &strarray); err == nil { *v = *NewStringList(strarray) return nil } var rawstr string if err := json.Unmarshal(data, &rawstr); err == nil { strlist := strings.Split(rawstr, ",") *v = *NewStringList(strlist) return nil } return newError("unknown format of a string list: " + string(data)) } type Address struct { net.Address } func (v *Address) UnmarshalJSON(data []byte) error { var rawStr string if err := json.Unmarshal(data, &rawStr); err != nil { return newError("invalid address: ", string(data)).Base(err) } v.Address = net.ParseAddress(rawStr) return nil } func (v *Address) Build() *net.IPOrDomain { return net.NewIPOrDomain(v.Address) } type Network string func (v Network) Build() net.Network { return net.ParseNetwork(string(v)) } type NetworkList []Network func (v *NetworkList) UnmarshalJSON(data []byte) error { var strarray []Network if err := json.Unmarshal(data, &strarray); err == nil { nl := NetworkList(strarray) *v = nl return nil } var rawstr Network if err := json.Unmarshal(data, &rawstr); err == nil { strlist := strings.Split(string(rawstr), ",") nl := make([]Network, len(strlist)) for idx, network := range strlist { nl[idx] = Network(network) } *v = nl return nil } return newError("unknown format of a string list: " + string(data)) } func (v *NetworkList) Build() []net.Network { if v == nil { return []net.Network{net.Network_TCP} } list := make([]net.Network, 0, len(*v)) for _, network := range *v { list = append(list, network.Build()) } return list } func parseIntPort(data []byte) (net.Port, error) { var intPort uint32 err := json.Unmarshal(data, &intPort) if err != nil { return net.Port(0), err } return net.PortFromInt(intPort) } func parseStringPort(s string) (net.Port, net.Port, error) { if strings.HasPrefix(s, "env:") { s = s[4:] s = os.Getenv(s) } pair := strings.SplitN(s, "-", 2) if len(pair) == 0 { return net.Port(0), net.Port(0), newError("invalid port range: ", s) } if len(pair) == 1 { port, err := net.PortFromString(pair[0]) return port, port, err } fromPort, err := net.PortFromString(pair[0]) if err != nil { return net.Port(0), net.Port(0), err } toPort, err := net.PortFromString(pair[1]) if err != nil { return net.Port(0), net.Port(0), err } return fromPort, toPort, nil } func parseJSONStringPort(data []byte) (net.Port, net.Port, error) { var s string err := json.Unmarshal(data, &s) if err != nil { return net.Port(0), net.Port(0), err } return parseStringPort(s) } type PortRange struct { From uint32 To uint32 } func (v *PortRange) Build() *net.PortRange { return &net.PortRange{ From: v.From, To: v.To, } } // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON func (v *PortRange) UnmarshalJSON(data []byte) error { port, err := parseIntPort(data) if err == nil { v.From = uint32(port) v.To = uint32(port) return nil } from, to, err := parseJSONStringPort(data) if err == nil { v.From = uint32(from) v.To = uint32(to) if v.From > v.To { return newError("invalid port range ", v.From, " -> ", v.To) } return nil } return newError("invalid port range: ", string(data)) } type PortList struct { Range []PortRange } func (list *PortList) Build() *net.PortList { portList := new(net.PortList) for _, r := range list.Range { portList.Range = append(portList.Range, r.Build()) } return portList } // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON func (list *PortList) UnmarshalJSON(data []byte) error { var listStr string var number uint32 if err := json.Unmarshal(data, &listStr); err != nil { if err2 := json.Unmarshal(data, &number); err2 != nil { return newError("invalid port: ", string(data)).Base(err2) } } err := list.UnmarshalText(listStr) if err != nil { return err } if number != 0 { list.Range = append(list.Range, PortRange{From: number, To: number}) } return nil } func (list *PortList) UnmarshalText(listStr string) error { rangelist := strings.Split(listStr, ",") for _, rangeStr := range rangelist { trimmed := strings.TrimSpace(rangeStr) if len(trimmed) > 0 { if strings.Contains(trimmed, "-") { from, to, err := parseStringPort(trimmed) if err != nil { return newError("invalid port range: ", trimmed).Base(err) } list.Range = append(list.Range, PortRange{From: uint32(from), To: uint32(to)}) } else { port, err := parseIntPort([]byte(trimmed)) if err != nil { return newError("invalid port: ", trimmed).Base(err) } list.Range = append(list.Range, PortRange{From: uint32(port), To: uint32(port)}) } } } return nil } type User struct { EmailString string `json:"email"` LevelByte byte `json:"level"` } func (v *User) Build() *protocol.User { return &protocol.User{ Email: v.EmailString, Level: uint32(v.LevelByte), } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/tlscfg/errors.generated.go
infra/conf/cfgcommon/tlscfg/errors.generated.go
package tlscfg 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/cfgcommon/tlscfg/tls.go
infra/conf/cfgcommon/tlscfg/tls.go
package tlscfg import ( "encoding/base64" "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/transport/internet/tls" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type TLSConfig struct { Insecure bool `json:"allowInsecure"` Certs []*TLSCertConfig `json:"certificates"` ServerName string `json:"serverName"` ALPN *cfgcommon.StringList `json:"alpn"` EnableSessionResumption bool `json:"enableSessionResumption"` DisableSystemRoot bool `json:"disableSystemRoot"` PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"` VerifyClientCertificate bool `json:"verifyClientCertificate"` ECHConfig string `json:"echConfig"` ECHDOHServer string `json:"echDohServer"` } // Build implements Buildable. func (c *TLSConfig) Build() (proto.Message, error) { config := new(tls.Config) config.Certificate = make([]*tls.Certificate, len(c.Certs)) for idx, certConf := range c.Certs { cert, err := certConf.Build() if err != nil { return nil, err } config.Certificate[idx] = cert } serverName := c.ServerName config.AllowInsecure = c.Insecure config.VerifyClientCertificate = c.VerifyClientCertificate if len(c.ServerName) > 0 { config.ServerName = serverName } if c.ALPN != nil && len(*c.ALPN) > 0 { config.NextProtocol = []string(*c.ALPN) } config.EnableSessionResumption = c.EnableSessionResumption config.DisableSystemRoot = c.DisableSystemRoot if c.PinnedPeerCertificateChainSha256 != nil { config.PinnedPeerCertificateChainSha256 = [][]byte{} for _, v := range *c.PinnedPeerCertificateChainSha256 { hashValue, err := base64.StdEncoding.DecodeString(v) if err != nil { return nil, err } config.PinnedPeerCertificateChainSha256 = append(config.PinnedPeerCertificateChainSha256, hashValue) } } if c.ECHConfig != "" { ECHConfig, err := base64.StdEncoding.DecodeString(c.ECHConfig) if err != nil { return nil, newError("invalid ECH Config", c.ECHConfig) } config.EchConfig = ECHConfig } config.Ech_DOHserver = c.ECHDOHServer return config, nil } type TLSCertConfig struct { CertFile string `json:"certificateFile"` CertStr []string `json:"certificate"` KeyFile string `json:"keyFile"` KeyStr []string `json:"key"` Usage string `json:"usage"` } // Build implements Buildable. func (c *TLSCertConfig) Build() (*tls.Certificate, error) { certificate := new(tls.Certificate) cert, err := readFileOrString(c.CertFile, c.CertStr) if err != nil { return nil, newError("failed to parse certificate").Base(err) } certificate.Certificate = cert if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 { key, err := readFileOrString(c.KeyFile, c.KeyStr) if err != nil { return nil, newError("failed to parse key").Base(err) } certificate.Key = key } switch strings.ToLower(c.Usage) { case "encipherment": certificate.Usage = tls.Certificate_ENCIPHERMENT case "verify": certificate.Usage = tls.Certificate_AUTHORITY_VERIFY case "verifyclient": certificate.Usage = tls.Certificate_AUTHORITY_VERIFY_CLIENT case "issue": certificate.Usage = tls.Certificate_AUTHORITY_ISSUE default: certificate.Usage = tls.Certificate_ENCIPHERMENT } return certificate, nil } func readFileOrString(f string, s []string) ([]byte, error) { if len(f) > 0 { return filesystem.ReadFile(f) } if len(s) > 0 { return []byte(strings.Join(s, "\n")), nil } return nil, newError("both file and bytes are empty.") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/loader/loader.go
infra/conf/cfgcommon/loader/loader.go
package loader import ( "encoding/json" "strings" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type ConfigCreator func() interface{} type ConfigCreatorCache map[string]ConfigCreator func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error { if _, found := v[id]; found { return newError(id, " already registered.").AtError() } v[id] = creator return nil } func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) { creator, found := v[id] if !found { return nil, newError("unknown config id: ", id) } return creator(), nil } type JSONConfigLoader struct { cache ConfigCreatorCache idKey string configKey string } func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey string) *JSONConfigLoader { return &JSONConfigLoader{ idKey: idKey, configKey: configKey, cache: cache, } } func (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) { id = strings.ToLower(id) config, err := v.cache.CreateConfig(id) if err != nil { return nil, err } if err := json.Unmarshal(raw, config); err != nil { return nil, err } return config, nil } func (v *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) { var obj map[string]json.RawMessage if err := json.Unmarshal(raw, &obj); err != nil { return nil, "", err } rawID, found := obj[v.idKey] if !found { return nil, "", newError(v.idKey, " not found in JSON context").AtError() } var id string if err := json.Unmarshal(rawID, &id); err != nil { return nil, "", err } rawConfig := json.RawMessage(raw) if len(v.configKey) > 0 { configValue, found := obj[v.configKey] if found { rawConfig = configValue } else { // Default to empty json object. rawConfig = json.RawMessage([]byte("{}")) } } config, err := v.LoadWithID([]byte(rawConfig), id) if err != nil { return nil, id, err } return config, id, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/loader/errors.generated.go
infra/conf/cfgcommon/loader/errors.generated.go
package loader 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/cfgcommon/proxycfg/proxy.go
infra/conf/cfgcommon/proxycfg/proxy.go
package proxycfg import "github.com/v2fly/v2ray-core/v5/transport/internet" type ProxyConfig struct { Tag string `json:"tag"` TransportLayerProxy bool `json:"transportLayer"` } //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen // Build implements Buildable. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) { if v.Tag == "" { return nil, newError("Proxy tag is not set.") } return &internet.ProxyConfig{ Tag: v.Tag, TransportLayerProxy: v.TransportLayerProxy, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/proxycfg/errors.generated.go
infra/conf/cfgcommon/proxycfg/errors.generated.go
package proxycfg 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/cfgcommon/duration/duration_test.go
infra/conf/cfgcommon/duration/duration_test.go
package duration_test import ( "encoding/json" "testing" "time" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/duration" ) type testWithDuration struct { Duration duration.Duration } func TestDurationJSON(t *testing.T) { expected := &testWithDuration{ Duration: duration.Duration(time.Hour), } data, err := json.Marshal(expected) if err != nil { t.Error(err) return } actual := &testWithDuration{} err = json.Unmarshal(data, &actual) if err != nil { t.Error(err) return } if actual.Duration != expected.Duration { t.Errorf("expected: %s, actual: %s", time.Duration(expected.Duration), time.Duration(actual.Duration)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/duration/duration.go
infra/conf/cfgcommon/duration/duration.go
package duration import ( "encoding/json" "fmt" "time" ) type Duration int64 func (d *Duration) MarshalJSON() ([]byte, error) { dr := time.Duration(*d) return json.Marshal(dr.String()) } func (d *Duration) UnmarshalJSON(b []byte) error { var v interface{} if err := json.Unmarshal(b, &v); err != nil { return err } switch value := v.(type) { case string: var err error dr, err := time.ParseDuration(value) if err != nil { return err } *d = Duration(dr) return nil default: return fmt.Errorf("invalid duration: %v", v) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/sniffer/errors.generated.go
infra/conf/cfgcommon/sniffer/errors.generated.go
package sniffer 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/cfgcommon/sniffer/sniffer.go
infra/conf/cfgcommon/sniffer/sniffer.go
package sniffer import ( "strings" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type SniffingConfig struct { Enabled bool `json:"enabled"` DestOverride *cfgcommon.StringList `json:"destOverride"` MetadataOnly bool `json:"metadataOnly"` } // Build implements Buildable. func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) { var p []string if c.DestOverride != nil { for _, domainOverride := range *c.DestOverride { switch strings.ToLower(domainOverride) { case "http": p = append(p, "http") case "tls", "https", "ssl": p = append(p, "tls") case "quic": p = append(p, "quic") case "fakedns": p = append(p, "fakedns") case "fakedns+others": p = append(p, "fakedns+others") default: return nil, newError("unknown protocol: ", domainOverride) } } } return &proxyman.SniffingConfig{ Enabled: c.Enabled, DestinationOverride: p, MetadataOnly: c.MetadataOnly, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/testassist/general.go
infra/conf/cfgcommon/testassist/general.go
package testassist import ( "encoding/json" "testing" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" ) func LoadJSON(creator func() cfgcommon.Buildable) func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { instance := creator() if err := json.Unmarshal([]byte(s), instance); err != nil { return nil, err } return instance.Build() } } type TestCase struct { Input string Parser func(string) (proto.Message, error) Output proto.Message } func RunMultiTestCase(t *testing.T, testCases []TestCase) { for _, testCase := range testCases { actual, err := testCase.Parser(testCase.Input) common.Must(err) if !proto.Equal(actual, testCase.Output) { t.Fatalf("Failed in test case:\n%s\nActual:\n%v\nExpected:\n%v", testCase.Input, actual, 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/cfgcommon/muxcfg/mux.go
infra/conf/cfgcommon/muxcfg/mux.go
package muxcfg import "github.com/v2fly/v2ray-core/v5/app/proxyman" type MuxConfig struct { Enabled bool `json:"enabled"` Concurrency int16 `json:"concurrency"` } // Build creates MultiplexingConfig, Concurrency < 0 completely disables mux. func (m *MuxConfig) Build() *proxyman.MultiplexingConfig { if m.Concurrency < 0 { return nil } var con uint32 = 8 if m.Concurrency > 0 { con = uint32(m.Concurrency) } return &proxyman.MultiplexingConfig{ Enabled: m.Enabled, Concurrency: con, } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/cfgcommon/socketcfg/socket.go
infra/conf/cfgcommon/socketcfg/socket.go
package socketcfg import ( "strings" "github.com/v2fly/v2ray-core/v5/transport/internet" ) type SocketConfig struct { Mark uint32 `json:"mark"` TFO *bool `json:"tcpFastOpen"` TProxy string `json:"tproxy"` AcceptProxyProtocol bool `json:"acceptProxyProtocol"` TCPKeepAliveInterval int32 `json:"tcpKeepAliveInterval"` TCPKeepAliveIdle int32 `json:"tcpKeepAliveIdle"` TFOQueueLength uint32 `json:"tcpFastOpenQueueLength"` BindToDevice string `json:"bindToDevice"` RxBufSize uint64 `json:"rxBufSize"` TxBufSize uint64 `json:"txBufSize"` ForceBufSize bool `json:"forceBufSize"` MPTCP *bool `json:"mptcp"` } // Build implements Buildable. func (c *SocketConfig) Build() (*internet.SocketConfig, error) { var tfoSettings internet.SocketConfig_TCPFastOpenState if c.TFO != nil { if *c.TFO { tfoSettings = internet.SocketConfig_Enable } else { tfoSettings = internet.SocketConfig_Disable } } tfoQueueLength := c.TFOQueueLength if tfoQueueLength == 0 { tfoQueueLength = 4096 } var tproxy internet.SocketConfig_TProxyMode switch strings.ToLower(c.TProxy) { case "tproxy": tproxy = internet.SocketConfig_TProxy case "redirect": tproxy = internet.SocketConfig_Redirect default: tproxy = internet.SocketConfig_Off } var mptcpSettings internet.MPTCPState if c.MPTCP != nil { if *c.MPTCP { mptcpSettings = internet.MPTCPState_Enable } else { mptcpSettings = internet.MPTCPState_Disable } } return &internet.SocketConfig{ Mark: c.Mark, Tfo: tfoSettings, TfoQueueLength: tfoQueueLength, Tproxy: tproxy, AcceptProxyProtocol: c.AcceptProxyProtocol, TcpKeepAliveInterval: c.TCPKeepAliveInterval, TcpKeepAliveIdle: c.TCPKeepAliveIdle, RxBufSize: int64(c.RxBufSize), TxBufSize: int64(c.TxBufSize), ForceBufSize: c.ForceBufSize, BindToDevice: c.BindToDevice, Mptcp: mptcpSettings, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/synthetic/dns/dns_test.go
infra/conf/synthetic/dns/dns_test.go
package dns_test import ( "encoding/json" "errors" "io/fs" "os" "path/filepath" "testing" "google.golang.org/protobuf/runtime/protoiface" "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/testassist" _ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/standard" dns2 "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/dns" ) 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 TestDNSConfigParsing(t *testing.T) { parserCreator := func() func(string) (protoiface.MessageV1, error) { return func(s string) (protoiface.MessageV1, error) { config := new(dns2.DNSConfig) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "servers": [{ "address": "8.8.8.8", "clientIp": "10.0.0.1", "port": 5353, "skipFallback": true, "domains": ["domain:v2fly.org"] }], "hosts": { "v2fly.org": "127.0.0.1", "www.v2fly.org": ["1.2.3.4", "5.6.7.8"], "domain:example.com": "google.com", "geosite:test": ["127.0.0.1", "127.0.0.2"], "keyword:google": ["8.8.8.8", "8.8.4.4"], "regexp:.*\\.com": "8.8.4.4" }, "clientIp": "10.0.0.1", "queryStrategy": "UseIPv4", "disableCache": true, "disableFallback": true }`, Parser: parserCreator(), Output: &dns.Config{ NameServer: []*dns.NameServer{ { Address: &net.Endpoint{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{8, 8, 8, 8}, }, }, Network: net.Network_UDP, Port: 5353, }, ClientIp: []byte{10, 0, 0, 1}, SkipFallback: true, PrioritizedDomain: []*dns.NameServer_PriorityDomain{ { Type: dns.DomainMatchingType_Subdomain, Domain: "v2fly.org", }, }, OriginalRules: []*dns.NameServer_OriginalRule{ { Rule: "domain:v2fly.org", Size: 1, }, }, }, }, StaticHosts: []*dns.HostMapping{ { Type: dns.DomainMatchingType_Subdomain, Domain: "example.com", ProxiedDomain: "google.com", }, { Type: dns.DomainMatchingType_Full, Domain: "test.example.com", Ip: [][]byte{{127, 0, 0, 1}, {127, 0, 0, 2}}, }, { Type: dns.DomainMatchingType_Keyword, Domain: "google", Ip: [][]byte{{8, 8, 8, 8}, {8, 8, 4, 4}}, }, { Type: dns.DomainMatchingType_Regex, Domain: ".*\\.com", Ip: [][]byte{{8, 8, 4, 4}}, }, { Type: dns.DomainMatchingType_Full, Domain: "v2fly.org", Ip: [][]byte{{127, 0, 0, 1}}, }, { Type: dns.DomainMatchingType_Full, Domain: "www.v2fly.org", Ip: [][]byte{{1, 2, 3, 4}, {5, 6, 7, 8}}, }, }, ClientIp: []byte{10, 0, 0, 1}, QueryStrategy: dns.QueryStrategy_USE_IP4, DisableCache: true, DisableFallback: true, }, }, { Input: `{ "servers": [{ "address": "fakedns", "tag": "fake", "queryStrategy": "UseIPv6", "fallbackStrategy": "disabledIfAnyMatch", "fakedns": true }, { "address": "8.8.8.8", "port": 5353, "tag": "local", "clientIp": "10.0.0.1", "queryStrategy": "UseIP", "cacheStrategy": "enabled", "fallbackStrategy": "disabled", "domains": ["domain:v2fly.org"], "fakedns": ["198.19.0.0/16", "fc01::/18"] }], "hosts": { "v2fly.org": "127.0.0.1", "www.v2fly.org": ["1.2.3.4", "5.6.7.8"], "domain:example.com": "google.com", "geosite:test": ["127.0.0.1", "127.0.0.2"], "keyword:google": ["8.8.8.8", "8.8.4.4"], "regexp:.*\\.com": "8.8.4.4" }, "fakedns": [ { "ipPool": "198.18.0.0/16", "poolSize": 32768 }, { "ipPool": "fc00::/18", "poolSize": 32768 } ], "tag": "global", "clientIp": "10.0.0.1", "queryStrategy": "UseIPv4", "cacheStrategy": "disabled", "fallbackStrategy": "enabled" }`, Parser: parserCreator(), Output: &dns.Config{ NameServer: []*dns.NameServer{ { Address: &net.Endpoint{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Domain{ Domain: "fakedns", }, }, Network: net.Network_UDP, }, Tag: "fake", QueryStrategy: dns.QueryStrategy_USE_IP6.Enum(), FallbackStrategy: dns.FallbackStrategy_DisabledIfAnyMatch.Enum(), FakeDns: &fakedns.FakeDnsPoolMulti{ Pools: []*fakedns.FakeDnsPool{}, }, }, { Address: &net.Endpoint{ Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{8, 8, 8, 8}, }, }, Network: net.Network_UDP, Port: 5353, }, Tag: "local", ClientIp: []byte{10, 0, 0, 1}, QueryStrategy: dns.QueryStrategy_USE_IP.Enum(), CacheStrategy: dns.CacheStrategy_CacheEnabled.Enum(), FallbackStrategy: dns.FallbackStrategy_Disabled.Enum(), PrioritizedDomain: []*dns.NameServer_PriorityDomain{ { Type: dns.DomainMatchingType_Subdomain, Domain: "v2fly.org", }, }, OriginalRules: []*dns.NameServer_OriginalRule{ { Rule: "domain:v2fly.org", Size: 1, }, }, FakeDns: &fakedns.FakeDnsPoolMulti{ Pools: []*fakedns.FakeDnsPool{ {IpPool: "198.19.0.0/16", LruSize: 65535}, {IpPool: "fc01::/18", LruSize: 65535}, }, }, }, }, StaticHosts: []*dns.HostMapping{ { Type: dns.DomainMatchingType_Subdomain, Domain: "example.com", ProxiedDomain: "google.com", }, { Type: dns.DomainMatchingType_Full, Domain: "test.example.com", Ip: [][]byte{{127, 0, 0, 1}, {127, 0, 0, 2}}, }, { Type: dns.DomainMatchingType_Keyword, Domain: "google", Ip: [][]byte{{8, 8, 8, 8}, {8, 8, 4, 4}}, }, { Type: dns.DomainMatchingType_Regex, Domain: ".*\\.com", Ip: [][]byte{{8, 8, 4, 4}}, }, { Type: dns.DomainMatchingType_Full, Domain: "v2fly.org", Ip: [][]byte{{127, 0, 0, 1}}, }, { Type: dns.DomainMatchingType_Full, Domain: "www.v2fly.org", Ip: [][]byte{{1, 2, 3, 4}, {5, 6, 7, 8}}, }, }, FakeDns: &fakedns.FakeDnsPoolMulti{ Pools: []*fakedns.FakeDnsPool{ {IpPool: "198.18.0.0/16", LruSize: 32768}, {IpPool: "fc00::/18", LruSize: 32768}, }, }, Tag: "global", ClientIp: []byte{10, 0, 0, 1}, QueryStrategy: dns.QueryStrategy_USE_IP4, CacheStrategy: dns.CacheStrategy_CacheDisabled, FallbackStrategy: dns.FallbackStrategy_Enabled, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/synthetic/dns/errors.generated.go
infra/conf/synthetic/dns/errors.generated.go
package dns 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/synthetic/dns/dns.go
infra/conf/synthetic/dns/dns.go
package dns //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "encoding/json" "sort" "strings" "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" rule2 "github.com/v2fly/v2ray-core/v5/infra/conf/rule" ) type NameServerConfig struct { Address *cfgcommon.Address ClientIP *cfgcommon.Address Port uint16 Tag string QueryStrategy string CacheStrategy string FallbackStrategy string SkipFallback bool Domains []string ExpectIPs cfgcommon.StringList FakeDNS FakeDNSConfigExtend cfgctx context.Context } func (c *NameServerConfig) UnmarshalJSON(data []byte) error { var address cfgcommon.Address if err := json.Unmarshal(data, &address); err == nil { c.Address = &address return nil } var advanced struct { Address *cfgcommon.Address `json:"address"` ClientIP *cfgcommon.Address `json:"clientIp"` Port uint16 `json:"port"` Tag string `json:"tag"` QueryStrategy string `json:"queryStrategy"` CacheStrategy string `json:"cacheStrategy"` FallbackStrategy string `json:"fallbackStrategy"` SkipFallback bool `json:"skipFallback"` Domains []string `json:"domains"` ExpectIPs cfgcommon.StringList `json:"expectIps"` FakeDNS FakeDNSConfigExtend `json:"fakedns"` } if err := json.Unmarshal(data, &advanced); err == nil { c.Address = advanced.Address c.ClientIP = advanced.ClientIP c.Port = advanced.Port c.Tag = advanced.Tag c.QueryStrategy = advanced.QueryStrategy c.CacheStrategy = advanced.CacheStrategy c.FallbackStrategy = advanced.FallbackStrategy c.SkipFallback = advanced.SkipFallback c.Domains = advanced.Domains c.ExpectIPs = advanced.ExpectIPs c.FakeDNS = advanced.FakeDNS return nil } return newError("failed to parse name server: ", string(data)) } func toDomainMatchingType(t routercommon.Domain_Type) dns.DomainMatchingType { switch t { case routercommon.Domain_RootDomain: return dns.DomainMatchingType_Subdomain case routercommon.Domain_Full: return dns.DomainMatchingType_Full case routercommon.Domain_Plain: return dns.DomainMatchingType_Keyword case routercommon.Domain_Regex: return dns.DomainMatchingType_Regex default: panic("unknown domain type") } } func (c *NameServerConfig) BuildV5(ctx context.Context) (*dns.NameServer, error) { c.cfgctx = ctx return c.Build() } func (c *NameServerConfig) Build() (*dns.NameServer, error) { cfgctx := c.cfgctx if c.Address == nil { return nil, newError("NameServer address is not specified.") } var domains []*dns.NameServer_PriorityDomain var originalRules []*dns.NameServer_OriginalRule for _, rule := range c.Domains { parsedDomain, err := rule2.ParseDomainRule(cfgctx, rule) if err != nil { return nil, newError("invalid domain rule: ", rule).Base(err) } for _, pd := range parsedDomain { domains = append(domains, &dns.NameServer_PriorityDomain{ Type: toDomainMatchingType(pd.Type), Domain: pd.Value, }) } originalRules = append(originalRules, &dns.NameServer_OriginalRule{ Rule: rule, Size: uint32(len(parsedDomain)), }) } geoipList, err := rule2.ToCidrList(cfgctx, c.ExpectIPs) if err != nil { return nil, newError("invalid IP rule: ", c.ExpectIPs).Base(err) } var fakeDNS *fakedns.FakeDnsPoolMulti if c.FakeDNS.FakeDNSConfig != nil { fake, err := c.FakeDNS.FakeDNSConfig.Build() if err != nil { return nil, newError("failed to build fakedns").Base(err) } fakeDNS = fake } var myClientIP []byte if c.ClientIP != nil { if !c.ClientIP.Family().IsIP() { return nil, newError("not an IP address:", c.ClientIP.String()) } myClientIP = []byte(c.ClientIP.IP()) } queryStrategy := new(dns.QueryStrategy) switch strings.ToLower(c.QueryStrategy) { case "useip", "use_ip", "use-ip": *queryStrategy = dns.QueryStrategy_USE_IP case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4": *queryStrategy = dns.QueryStrategy_USE_IP4 case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6": *queryStrategy = dns.QueryStrategy_USE_IP6 default: queryStrategy = nil } cacheStrategy := new(dns.CacheStrategy) switch strings.ToLower(c.CacheStrategy) { case "enabled": *cacheStrategy = dns.CacheStrategy_CacheEnabled case "disabled": *cacheStrategy = dns.CacheStrategy_CacheDisabled default: cacheStrategy = nil } fallbackStrategy := new(dns.FallbackStrategy) switch strings.ToLower(c.FallbackStrategy) { case "enabled": *fallbackStrategy = dns.FallbackStrategy_Enabled case "disabled": *fallbackStrategy = dns.FallbackStrategy_Disabled case "disabledifanymatch", "disabled_if_any_match", "disabled-if-any-match": *fallbackStrategy = dns.FallbackStrategy_DisabledIfAnyMatch default: fallbackStrategy = nil } return &dns.NameServer{ Address: &net.Endpoint{ Network: net.Network_UDP, Address: c.Address.Build(), Port: uint32(c.Port), }, ClientIp: myClientIP, Tag: c.Tag, SkipFallback: c.SkipFallback, QueryStrategy: queryStrategy, CacheStrategy: cacheStrategy, FallbackStrategy: fallbackStrategy, PrioritizedDomain: domains, Geoip: geoipList, OriginalRules: originalRules, FakeDns: fakeDNS, }, nil } var typeMap = map[routercommon.Domain_Type]dns.DomainMatchingType{ routercommon.Domain_Full: dns.DomainMatchingType_Full, routercommon.Domain_RootDomain: dns.DomainMatchingType_Subdomain, routercommon.Domain_Plain: dns.DomainMatchingType_Keyword, routercommon.Domain_Regex: dns.DomainMatchingType_Regex, } // DNSConfig is a JSON serializable object for dns.Config. type DNSConfig struct { // nolint: revive Servers []*NameServerConfig `json:"servers"` Hosts map[string]*HostAddress `json:"hosts"` FakeDNS *FakeDNSConfig `json:"fakedns"` DomainMatcher string `json:"domainMatcher"` ClientIP *cfgcommon.Address `json:"clientIp"` Tag string `json:"tag"` QueryStrategy string `json:"queryStrategy"` CacheStrategy string `json:"cacheStrategy"` FallbackStrategy string `json:"fallbackStrategy"` DisableCache bool `json:"disableCache"` DisableFallback bool `json:"disableFallback"` DisableFallbackIfMatch bool `json:"disableFallbackIfMatch"` cfgctx context.Context } type HostAddress struct { addr *cfgcommon.Address addrs []*cfgcommon.Address } // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON func (h *HostAddress) UnmarshalJSON(data []byte) error { addr := new(cfgcommon.Address) var addrs []*cfgcommon.Address switch { case json.Unmarshal(data, &addr) == nil: h.addr = addr case json.Unmarshal(data, &addrs) == nil: h.addrs = addrs default: return newError("invalid address") } return nil } func getHostMapping(ha *HostAddress) *dns.HostMapping { if ha.addr != nil { if ha.addr.Family().IsDomain() { return &dns.HostMapping{ ProxiedDomain: ha.addr.Domain(), } } return &dns.HostMapping{ Ip: [][]byte{ha.addr.IP()}, } } ips := make([][]byte, 0, len(ha.addrs)) for _, addr := range ha.addrs { if addr.Family().IsDomain() { return &dns.HostMapping{ ProxiedDomain: addr.Domain(), } } ips = append(ips, []byte(addr.IP())) } return &dns.HostMapping{ Ip: ips, } } func (c *DNSConfig) BuildV5(ctx context.Context) (*dns.Config, error) { c.cfgctx = ctx return c.Build() } // Build implements Buildable func (c *DNSConfig) Build() (*dns.Config, error) { if c.cfgctx == nil { c.cfgctx = 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(c.cfgctx, loader) } else { return nil, newError("unable to create geo data loader ").Base(err) } } cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(c.cfgctx) geoLoader := cfgEnv.GetGeoLoader() config := &dns.Config{ Tag: c.Tag, DisableCache: c.DisableCache, DisableFallback: c.DisableFallback, DisableFallbackIfMatch: c.DisableFallbackIfMatch, DomainMatcher: c.DomainMatcher, } if c.ClientIP != nil { if !c.ClientIP.Family().IsIP() { return nil, newError("not an IP address:", c.ClientIP.String()) } config.ClientIp = []byte(c.ClientIP.IP()) } config.QueryStrategy = dns.QueryStrategy_USE_IP switch strings.ToLower(c.QueryStrategy) { case "useip", "use_ip", "use-ip": config.QueryStrategy = dns.QueryStrategy_USE_IP case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4": config.QueryStrategy = dns.QueryStrategy_USE_IP4 case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6": config.QueryStrategy = dns.QueryStrategy_USE_IP6 } config.CacheStrategy = dns.CacheStrategy_CacheEnabled switch strings.ToLower(c.CacheStrategy) { case "enabled": config.CacheStrategy = dns.CacheStrategy_CacheEnabled case "disabled": config.CacheStrategy = dns.CacheStrategy_CacheDisabled } config.FallbackStrategy = dns.FallbackStrategy_Enabled switch strings.ToLower(c.FallbackStrategy) { case "enabled": config.FallbackStrategy = dns.FallbackStrategy_Enabled case "disabled": config.FallbackStrategy = dns.FallbackStrategy_Disabled case "disabledifanymatch", "disabled_if_any_match", "disabled-if-any-match": config.FallbackStrategy = dns.FallbackStrategy_DisabledIfAnyMatch } for _, server := range c.Servers { server.cfgctx = c.cfgctx ns, err := server.Build() if err != nil { return nil, newError("failed to build nameserver").Base(err) } config.NameServer = append(config.NameServer, ns) } if c.Hosts != nil { mappings := make([]*dns.HostMapping, 0, 20) domains := make([]string, 0, len(c.Hosts)) for domain := range c.Hosts { domains = append(domains, domain) } sort.Strings(domains) for _, domain := range domains { switch { case strings.HasPrefix(domain, "domain:"): domainName := domain[7:] if len(domainName) == 0 { return nil, newError("empty domain type of rule: ", domain) } mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Subdomain mapping.Domain = domainName mappings = append(mappings, mapping) case strings.HasPrefix(domain, "geosite:"): listName := domain[8:] if len(listName) == 0 { return nil, newError("empty geosite rule: ", domain) } geositeList, err := geoLoader.LoadGeoSite(listName) if err != nil { return nil, newError("failed to load geosite: ", listName).Base(err) } for _, d := range geositeList { mapping := getHostMapping(c.Hosts[domain]) mapping.Type = typeMap[d.Type] mapping.Domain = d.Value mappings = append(mappings, mapping) } case strings.HasPrefix(domain, "regexp:"): regexpVal := domain[7:] if len(regexpVal) == 0 { return nil, newError("empty regexp type of rule: ", domain) } mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Regex mapping.Domain = regexpVal mappings = append(mappings, mapping) case strings.HasPrefix(domain, "keyword:"): keywordVal := domain[8:] if len(keywordVal) == 0 { return nil, newError("empty keyword type of rule: ", domain) } mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Keyword mapping.Domain = keywordVal mappings = append(mappings, mapping) case strings.HasPrefix(domain, "full:"): fullVal := domain[5:] if len(fullVal) == 0 { return nil, newError("empty full domain type of rule: ", domain) } mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Full mapping.Domain = fullVal mappings = append(mappings, mapping) case strings.HasPrefix(domain, "dotless:"): mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Regex switch substr := domain[8:]; { case substr == "": mapping.Domain = "^[^.]*$" case !strings.Contains(substr, "."): mapping.Domain = "^[^.]*" + substr + "[^.]*$" default: return nil, newError("substr in dotless rule should not contain a dot: ", substr) } mappings = append(mappings, mapping) case strings.HasPrefix(domain, "ext:"): kv := strings.Split(domain[4:], ":") if len(kv) != 2 { return nil, newError("invalid external resource: ", domain) } filename := kv[0] list := kv[1] geositeList, err := geoLoader.LoadGeoSiteWithAttr(filename, list) if err != nil { return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err) } for _, d := range geositeList { mapping := getHostMapping(c.Hosts[domain]) mapping.Type = typeMap[d.Type] mapping.Domain = d.Value mappings = append(mappings, mapping) } default: mapping := getHostMapping(c.Hosts[domain]) mapping.Type = dns.DomainMatchingType_Full mapping.Domain = domain mappings = append(mappings, mapping) } } config.StaticHosts = append(config.StaticHosts, mappings...) } if c.FakeDNS != nil { fakeDNS, err := c.FakeDNS.Build() if err != nil { return nil, newError("failed to build fakedns").Base(err) } config.FakeDns = fakeDNS } 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/synthetic/dns/fakedns.go
infra/conf/synthetic/dns/fakedns.go
package dns import ( "encoding/json" "net" "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" ) type FakeDNSPoolElementConfig struct { IPPool string `json:"ipPool"` LRUSize int64 `json:"poolSize"` } type FakeDNSConfig struct { pool *FakeDNSPoolElementConfig pools []*FakeDNSPoolElementConfig } // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON func (f *FakeDNSConfig) UnmarshalJSON(data []byte) error { var pool FakeDNSPoolElementConfig var pools []*FakeDNSPoolElementConfig var ipPools []string switch { case json.Unmarshal(data, &pool) == nil: f.pool = &pool case json.Unmarshal(data, &pools) == nil: f.pools = pools case json.Unmarshal(data, &ipPools) == nil: f.pools = make([]*FakeDNSPoolElementConfig, 0, len(ipPools)) for _, ipPool := range ipPools { _, ipNet, err := net.ParseCIDR(ipPool) if err != nil { return err } ones, bits := ipNet.Mask.Size() sizeInBits := bits - ones if sizeInBits > 16 { // At most 65536 ips for a IP pool sizeInBits = 16 } f.pools = append(f.pools, &FakeDNSPoolElementConfig{ IPPool: ipPool, LRUSize: (1 << sizeInBits) - 1, }) } default: return newError("invalid fakedns config") } return nil } func (f *FakeDNSConfig) Build() (*fakedns.FakeDnsPoolMulti, error) { fakeDNSPool := fakedns.FakeDnsPoolMulti{} if f.pool != nil { fakeDNSPool.Pools = append(fakeDNSPool.Pools, &fakedns.FakeDnsPool{ IpPool: f.pool.IPPool, LruSize: f.pool.LRUSize, }) return &fakeDNSPool, nil } if f.pools != nil { for _, v := range f.pools { fakeDNSPool.Pools = append(fakeDNSPool.Pools, &fakedns.FakeDnsPool{IpPool: v.IPPool, LruSize: v.LRUSize}) } return &fakeDNSPool, nil } return nil, newError("no valid FakeDNS config") } type FakeDNSConfigExtend struct { // Adds boolean value parsing for "fakedns" config *FakeDNSConfig } func (f *FakeDNSConfigExtend) UnmarshalJSON(data []byte) error { var enabled bool if json.Unmarshal(data, &enabled) == nil { if enabled { f.FakeDNSConfig = &FakeDNSConfig{pools: []*FakeDNSPoolElementConfig{}} } return nil } return json.Unmarshal(data, &f.FakeDNSConfig) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/synthetic/router/errors.generated.go
infra/conf/synthetic/router/errors.generated.go
package router 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/synthetic/router/router.go
infra/conf/synthetic/router/router.go
package router //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "encoding/json" "strings" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/router" "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" rule2 "github.com/v2fly/v2ray-core/v5/infra/conf/rule" ) type RouterRulesConfig struct { // nolint: revive RuleList []json.RawMessage `json:"rules"` DomainStrategy string `json:"domainStrategy"` } // StrategyConfig represents a strategy config type StrategyConfig struct { Type string `json:"type"` Settings *json.RawMessage `json:"settings"` } type BalancingRule struct { Tag string `json:"tag"` Selectors cfgcommon.StringList `json:"selector"` Strategy StrategyConfig `json:"strategy"` FallbackTag string `json:"fallbackTag"` } // Build builds the balancing rule func (r *BalancingRule) Build() (*router.BalancingRule, error) { if r.Tag == "" { return nil, newError("empty balancer tag") } if len(r.Selectors) == 0 { return nil, newError("empty selector list") } var strategy string switch strings.ToLower(r.Strategy.Type) { case strategyRandom, "": r.Strategy.Type = strategyRandom strategy = strategyRandom case strategyLeastLoad: strategy = strategyLeastLoad case strategyLeastPing: strategy = "leastping" default: return nil, newError("unknown balancing strategy: " + r.Strategy.Type) } settings := []byte("{}") if r.Strategy.Settings != nil { settings = ([]byte)(*r.Strategy.Settings) } rawConfig, err := strategyConfigLoader.LoadWithID(settings, r.Strategy.Type) if err != nil { return nil, newError("failed to parse to strategy config.").Base(err) } var ts proto.Message if builder, ok := rawConfig.(cfgcommon.Buildable); ok { ts, err = builder.Build() if err != nil { return nil, err } } return &router.BalancingRule{ Strategy: strategy, StrategySettings: serial.ToTypedMessage(ts), FallbackTag: r.FallbackTag, OutboundSelector: r.Selectors, Tag: r.Tag, }, nil } type RouterConfig struct { // nolint: revive Settings *RouterRulesConfig `json:"settings"` // Deprecated RuleList []json.RawMessage `json:"rules"` DomainStrategy *string `json:"domainStrategy"` Balancers []*BalancingRule `json:"balancers"` DomainMatcher string `json:"domainMatcher"` cfgctx context.Context } func (c *RouterConfig) getDomainStrategy() router.DomainStrategy { ds := "" if c.DomainStrategy != nil { ds = *c.DomainStrategy } else if c.Settings != nil { ds = c.Settings.DomainStrategy } switch strings.ToLower(ds) { case "alwaysip", "always_ip", "always-ip": return router.DomainStrategy_UseIp case "ipifnonmatch", "ip_if_non_match", "ip-if-non-match": return router.DomainStrategy_IpIfNonMatch case "ipondemand", "ip_on_demand", "ip-on-demand": return router.DomainStrategy_IpOnDemand default: return router.DomainStrategy_AsIs } } func (c *RouterConfig) BuildV5(ctx context.Context) (*router.Config, error) { c.cfgctx = ctx return c.Build() } func (c *RouterConfig) Build() (*router.Config, error) { config := new(router.Config) config.DomainStrategy = c.getDomainStrategy() if c.cfgctx == nil { c.cfgctx = 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(c.cfgctx, loader) } else { return nil, newError("unable to create geo data loader ").Base(err) } } var rawRuleList []json.RawMessage if c != nil { rawRuleList = c.RuleList if c.Settings != nil { c.RuleList = append(c.RuleList, c.Settings.RuleList...) rawRuleList = c.RuleList } } for _, rawRule := range rawRuleList { rule, err := rule2.ParseRule(c.cfgctx, rawRule) if err != nil { return nil, err } if rule.DomainMatcher == "" { rule.DomainMatcher = c.DomainMatcher } config.Rule = append(config.Rule, rule) } for _, rawBalancer := range c.Balancers { balancer, err := rawBalancer.Build() if err != nil { return nil, err } config.BalancingRule = append(config.BalancingRule, balancer) } 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/synthetic/router/router_strategy.go
infra/conf/synthetic/router/router_strategy.go
package router import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/observatory/burst" "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/duration" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/loader" ) const ( strategyRandom string = "random" strategyLeastLoad string = "leastload" strategyLeastPing string = "leastping" ) var strategyConfigLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{ strategyRandom: func() interface{} { return new(strategyRandomConfig) }, strategyLeastLoad: func() interface{} { return new(strategyLeastLoadConfig) }, strategyLeastPing: func() interface{} { return new(strategyLeastPingConfig) }, }, "type", "settings") type strategyEmptyConfig struct{} func (v *strategyEmptyConfig) Build() (proto.Message, error) { return nil, nil } type strategyLeastLoadConfig struct { // weight settings Costs []*router.StrategyWeight `json:"costs,omitempty"` // ping rtt baselines Baselines []duration.Duration `json:"baselines,omitempty"` // expected nodes count to select Expected int32 `json:"expected,omitempty"` // max acceptable rtt, filter away high delay nodes. default 0 MaxRTT duration.Duration `json:"maxRTT,omitempty"` // acceptable failure rate Tolerance float64 `json:"tolerance,omitempty"` ObserverTag string `json:"observerTag,omitempty"` } // HealthCheckSettings holds settings for health Checker type HealthCheckSettings struct { Destination string `json:"destination"` Connectivity string `json:"connectivity"` Interval duration.Duration `json:"interval"` SamplingCount int `json:"sampling"` Timeout duration.Duration `json:"timeout"` } func (h HealthCheckSettings) Build() (proto.Message, error) { return &burst.HealthPingConfig{ Destination: h.Destination, Connectivity: h.Connectivity, Interval: int64(h.Interval), Timeout: int64(h.Timeout), SamplingCount: int32(h.SamplingCount), }, nil } // Build implements Buildable. func (v *strategyLeastLoadConfig) Build() (proto.Message, error) { config := &router.StrategyLeastLoadConfig{} config.Costs = v.Costs config.Tolerance = float32(v.Tolerance) config.ObserverTag = v.ObserverTag if config.Tolerance < 0 { config.Tolerance = 0 } if config.Tolerance > 1 { config.Tolerance = 1 } config.Expected = v.Expected if config.Expected < 0 { config.Expected = 0 } config.MaxRTT = int64(v.MaxRTT) if config.MaxRTT < 0 { config.MaxRTT = 0 } config.Baselines = make([]int64, 0) for _, b := range v.Baselines { if b <= 0 { continue } config.Baselines = append(config.Baselines, int64(b)) } return config, nil } type strategyLeastPingConfig struct { ObserverTag string `json:"observerTag,omitempty"` } func (s strategyLeastPingConfig) Build() (proto.Message, error) { return &router.StrategyLeastPingConfig{ObserverTag: s.ObserverTag}, nil } type strategyRandomConfig struct { AliveOnly bool `json:"aliveOnly,omitempty"` ObserverTag string `json:"observerTag,omitempty"` } func (s strategyRandomConfig) Build() (proto.Message, error) { return &router.StrategyRandomConfig{ObserverTag: s.ObserverTag, AliveOnly: s.AliveOnly}, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/synthetic/router/router_test.go
infra/conf/synthetic/router/router_test.go
package router_test import ( "encoding/json" "testing" "time" _ "unsafe" "github.com/golang/protobuf/proto" "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/common/serial" "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" router2 "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/router" ) func TestRouterConfig(t *testing.T) { createParser := func() func(string) (proto.Message, error) { return func(s string) (proto.Message, error) { config := new(router2.RouterConfig) if err := json.Unmarshal([]byte(s), config); err != nil { return nil, err } return config.Build() } } testassist.RunMultiTestCase(t, []testassist.TestCase{ { Input: `{ "strategy": "rules", "settings": { "domainStrategy": "AsIs", "rules": [ { "type": "field", "domain": [ "baidu.com", "qq.com" ], "outboundTag": "direct" }, { "type": "field", "domains": [ "v2fly.org", "github.com" ], "outboundTag": "direct" }, { "type": "field", "ip": [ "10.0.0.0/8", "::1/128" ], "outboundTag": "test" },{ "type": "field", "port": "53, 443, 1000-2000", "outboundTag": "test" },{ "type": "field", "port": 123, "outboundTag": "test" } ] }, "balancers": [ { "tag": "b1", "selector": ["test"] }, { "tag": "b2", "selector": ["test"], "strategy": { "type": "leastload", "settings": { "healthCheck": { "interval": "5m0s", "sampling": 2, "timeout": "5s", "destination": "dest", "connectivity": "conn" }, "costs": [ { "regexp": true, "match": "\\d+(\\.\\d+)", "value": 5 } ], "baselines": ["400ms", "600ms"], "expected": 6, "maxRTT": "1000ms", "tolerance": 0.5 } }, "fallbackTag": "fall" } ] }`, Parser: createParser(), Output: &router.Config{ DomainStrategy: router.DomainStrategy_AsIs, BalancingRule: []*router.BalancingRule{ { Tag: "b1", OutboundSelector: []string{"test"}, Strategy: "random", StrategySettings: serial.ToTypedMessage(&router.StrategyRandomConfig{}), }, { Tag: "b2", OutboundSelector: []string{"test"}, Strategy: "leastload", StrategySettings: serial.ToTypedMessage(&router.StrategyLeastLoadConfig{ Costs: []*router.StrategyWeight{ { Regexp: true, Match: "\\d+(\\.\\d+)", Value: 5, }, }, Baselines: []int64{ int64(time.Duration(400) * time.Millisecond), int64(time.Duration(600) * time.Millisecond), }, Expected: 6, MaxRTT: int64(time.Duration(1000) * time.Millisecond), Tolerance: 0.5, }), FallbackTag: "fall", }, }, Rule: []*router.RoutingRule{ { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "baidu.com", }, { Type: routercommon.Domain_Plain, Value: "qq.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "v2fly.org", }, { Type: routercommon.Domain_Plain, Value: "github.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Geoip: []*routercommon.GeoIP{ { Cidr: []*routercommon.CIDR{ { Ip: []byte{10, 0, 0, 0}, Prefix: 8, }, { Ip: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, Prefix: 128, }, }, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "test", }, }, { PortList: &net.PortList{ Range: []*net.PortRange{ {From: 53, To: 53}, {From: 443, To: 443}, {From: 1000, To: 2000}, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "test", }, }, { PortList: &net.PortList{ Range: []*net.PortRange{ {From: 123, To: 123}, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "test", }, }, }, }, }, { Input: `{ "strategy": "rules", "settings": { "domainStrategy": "IPIfNonMatch", "rules": [ { "type": "field", "domain": [ "baidu.com", "qq.com" ], "outboundTag": "direct" }, { "type": "field", "domains": [ "v2fly.org", "github.com" ], "outboundTag": "direct" }, { "type": "field", "ip": [ "10.0.0.0/8", "::1/128" ], "outboundTag": "test" } ] } }`, Parser: createParser(), Output: &router.Config{ DomainStrategy: router.DomainStrategy_IpIfNonMatch, Rule: []*router.RoutingRule{ { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "baidu.com", }, { Type: routercommon.Domain_Plain, Value: "qq.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "v2fly.org", }, { Type: routercommon.Domain_Plain, Value: "github.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Geoip: []*routercommon.GeoIP{ { Cidr: []*routercommon.CIDR{ { Ip: []byte{10, 0, 0, 0}, Prefix: 8, }, { Ip: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, Prefix: 128, }, }, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "test", }, }, }, }, }, { Input: `{ "domainStrategy": "AsIs", "rules": [ { "type": "field", "domain": [ "baidu.com", "qq.com" ], "outboundTag": "direct" }, { "type": "field", "domains": [ "v2fly.org", "github.com" ], "outboundTag": "direct" }, { "type": "field", "ip": [ "10.0.0.0/8", "::1/128" ], "outboundTag": "test" } ] }`, Parser: createParser(), Output: &router.Config{ DomainStrategy: router.DomainStrategy_AsIs, Rule: []*router.RoutingRule{ { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "baidu.com", }, { Type: routercommon.Domain_Plain, Value: "qq.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Domain: []*routercommon.Domain{ { Type: routercommon.Domain_Plain, Value: "v2fly.org", }, { Type: routercommon.Domain_Plain, Value: "github.com", }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "direct", }, }, { Geoip: []*routercommon.GeoIP{ { Cidr: []*routercommon.CIDR{ { Ip: []byte{10, 0, 0, 0}, Prefix: 8, }, { Ip: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, Prefix: 128, }, }, }, }, TargetTag: &router.RoutingRule_Tag{ Tag: "test", }, }, }, }, }, }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/synthetic/log/log.go
infra/conf/synthetic/log/log.go
package log import ( "strings" "github.com/v2fly/v2ray-core/v5/app/log" clog "github.com/v2fly/v2ray-core/v5/common/log" ) func DefaultLogConfig() *log.Config { return &log.Config{ Access: &log.LogSpecification{Type: log.LogType_None}, Error: &log.LogSpecification{Type: log.LogType_Console, Level: clog.Severity_Warning}, } } type LogConfig struct { // nolint: revive AccessLog string `json:"access"` ErrorLog string `json:"error"` LogLevel string `json:"loglevel"` } func (v *LogConfig) Build() *log.Config { if v == nil { return nil } config := &log.Config{ Access: &log.LogSpecification{Type: log.LogType_Console}, Error: &log.LogSpecification{Type: log.LogType_Console}, } if v.AccessLog == "none" { config.Access.Type = log.LogType_None } else if len(v.AccessLog) > 0 { config.Access.Path = v.AccessLog config.Access.Type = log.LogType_File } if v.ErrorLog == "none" { config.Error.Type = log.LogType_None } else if len(v.ErrorLog) > 0 { config.Error.Path = v.ErrorLog config.Error.Type = log.LogType_File } level := strings.ToLower(v.LogLevel) switch level { case "debug": config.Error.Level = clog.Severity_Debug case "info": config.Error.Level = clog.Severity_Info case "error": config.Error.Level = clog.Severity_Error case "none": config.Error.Type = log.LogType_None config.Error.Type = log.LogType_None default: config.Error.Level = clog.Severity_Warning } return config }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/merge.go
infra/conf/merge/merge.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. /* Package merge provides the capability to merge multiple JSON files or contents into one output. Merge Rules: - Simple values (string, number, boolean) are overwritten, others are merged - Elements with same "tag" (or "_tag") in an array will be merged - Add "_priority" property to array elements will help sort the */ package merge import ( "bytes" "encoding/json" "github.com/v2fly/v2ray-core/v5/infra/conf/serial" ) // JSONs merges multiple json contents into one json. func JSONs(args [][]byte) ([]byte, error) { m := make(map[string]interface{}) for _, arg := range args { if _, err := ToMap(arg, m); err != nil { return nil, err } } return FromMap(m) } // ToMap merges json content to target map and returns it func ToMap(content []byte, target map[string]interface{}) (map[string]interface{}, error) { if target == nil { target = make(map[string]interface{}) } r := bytes.NewReader(content) n := make(map[string]interface{}) err := serial.DecodeJSON(r, &n) if err != nil { return nil, err } if err = mergeMaps(target, n); err != nil { return nil, err } return target, nil } // FromMap apply merge rules to map and convert it to json func FromMap(target map[string]interface{}) ([]byte, error) { if target == nil { target = make(map[string]interface{}) } err := ApplyRules(target) if err != nil { return nil, err } return json.Marshal(target) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/merge_test.go
infra/conf/merge/merge_test.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. package merge_test import ( "bytes" "reflect" "strings" "testing" "github.com/v2fly/v2ray-core/v5/infra/conf/merge" "github.com/v2fly/v2ray-core/v5/infra/conf/serial" ) func TestMergeV2Style(t *testing.T) { json1 := ` { "log": {"access": "some_value", "loglevel": "debug"}, "inbounds": [{"tag": "in-1"}], "outbounds": [{"_priority": 100, "tag": "out-1"}], "routing": {"rules": [ {"_tag":"default_route","inboundTag":["in-1"],"outboundTag":"out-1"} ]} } ` json2 := ` { "log": {"loglevel": "error"}, "inbounds": [{"tag": "in-2"}], "outbounds": [{"_priority": -100, "tag": "out-2"}], "routing": {"rules": [ {"inboundTag":["in-2"],"outboundTag":"out-2"}, {"_tag":"default_route","inboundTag":["in-1.1"],"outboundTag":"out-1.1"} ]} } ` expected := ` { "log": {"access": "some_value", "loglevel": "error"}, "inbounds": [{"tag": "in-1"},{"tag": "in-2"}], "outbounds": [ {"tag": "out-2"}, {"tag": "out-1"} ], "routing": {"rules": [ {"inboundTag":["in-1","in-1.1"],"outboundTag":"out-1.1"}, {"inboundTag":["in-2"],"outboundTag":"out-2"} ]} } ` m, err := merge.JSONs([][]byte{[]byte(json1), []byte(json2)}) if err != nil { t.Error(err) } assertResult(t, m, expected) } func TestMergeTag(t *testing.T) { json1 := ` { "routing": { "rules": [{ "tag":"1", "inboundTag": ["in-1"], "outboundTag": "out-1" }] } } ` json2 := ` { "routing": { "rules": [{ "_tag":"1", "inboundTag": ["in-2"], "outboundTag": "out-2" }] } } ` expected := ` { "routing": { "rules": [{ "tag":"1", "inboundTag": ["in-1", "in-2"], "outboundTag": "out-2" }] } } ` m, err := merge.JSONs([][]byte{[]byte(json1), []byte(json2)}) if err != nil { t.Error(err) } assertResult(t, m, expected) } func TestMergeTagValueTypes(t *testing.T) { json1 := ` { "array_1": [{ "_tag":"1", "array_2": [{ "_tag":"2", "array_3.1": ["string",true,false], "array_3.2": [1,2,3], "number_1": 1, "number_2": 1, "bool_1": true, "bool_2": true }] }] } ` json2 := ` { "array_1": [{ "_tag":"1", "array_2": [{ "_tag":"2", "array_3.1": [0,1,null], "array_3.2": null, "number_1": 0, "number_2": 1, "bool_1": true, "bool_2": false, "null_1": null }] }] } ` expected := ` { "array_1": [{ "array_2": [{ "array_3.1": ["string",true,false,0,1,null], "array_3.2": [1,2,3], "number_1": 0, "number_2": 1, "bool_1": true, "bool_2": false, "null_1": null }] }] } ` m, err := merge.JSONs([][]byte{[]byte(json1), []byte(json2)}) if err != nil { t.Error(err) } assertResult(t, m, expected) } func TestMergeTagDeep(t *testing.T) { json1 := ` { "array_1": [{ "_tag":"1", "array_2": [{ "_tag":"2", "array_3": [true,false,"string"] }] }] } ` json2 := ` { "array_1": [{ "_tag":"1", "array_2": [{ "_tag":"2", "_priority":-100, "array_3": [0,1,null] }] }] } ` expected := ` { "array_1": [{ "array_2": [{ "array_3": [0,1,null,true,false,"string"] }] }] } ` m, err := merge.JSONs([][]byte{[]byte(json1), []byte(json2)}) if err != nil { t.Error(err) } assertResult(t, m, expected) } func TestNoMergeDnsServers(t *testing.T) { json1 := ` { "dns": { "queryStrategy": "UseIPv4", "fallbackStrategy": "disabled-if-any-match", "domainMatcher": "mph", "servers": [ { "address": "aaa.bbb.ccc.ddd", "port": 53, "domains": [ "geosite:cn" ], "tag": "dns-domestic" }, { "address": "114.114.114.114", "port": 53, "domains": [ "geosite:cn" ], "tag": "dns-domestic" }, { "address": "https://1.1.1.1/dns-query", "tag": "dns-international" } ] }, "routing": { "domainStrategy": "IPIfNonMatch", "domainMatcher": "mph", "rules": [ { "type": "field", "inboundTag": "dns-domestic", "outboundTag": "direct" }, { "type": "field", "inboundTag": "dns-international", "outboundTag": "proxy" } ] } } ` expected := ` { "dns": { "queryStrategy": "UseIPv4", "fallbackStrategy": "disabled-if-any-match", "domainMatcher": "mph", "servers": [ { "address": "aaa.bbb.ccc.ddd", "port": 53, "domains": [ "geosite:cn" ], "tag": "dns-domestic" }, { "address": "114.114.114.114", "port": 53, "domains": [ "geosite:cn" ], "tag": "dns-domestic" }, { "address": "https://1.1.1.1/dns-query", "tag": "dns-international" } ] }, "routing": { "domainStrategy": "IPIfNonMatch", "domainMatcher": "mph", "rules": [ { "type": "field", "inboundTag": "dns-domestic", "outboundTag": "direct" }, { "type": "field", "inboundTag": "dns-international", "outboundTag": "proxy" } ] } } ` m, err := merge.JSONs([][]byte{[]byte(json1)}) if err != nil { t.Error(err) } assertResult(t, m, expected) } func assertResult(t *testing.T, value []byte, expected string) { v := make(map[string]interface{}) err := serial.DecodeJSON(bytes.NewReader(value), &v) if err != nil { t.Error(err) } e := make(map[string]interface{}) err = serial.DecodeJSON(strings.NewReader(expected), &e) if err != nil { t.Error(err) } if !reflect.DeepEqual(v, e) { t.Fatalf("expected:\n%s\n\nactual:\n%s", expected, string(value)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/rules.go
infra/conf/merge/rules.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. package merge import "fmt" const ( priorityKey string = "_priority" tagKey string = "_tag" ) // ApplyRules applies merge rules according to _tag, _priority fields, and remove them func ApplyRules(m map[string]interface{}) error { err := sortMergeSlices(m, "") if err != nil { return err } removeHelperFields(m) return nil } // sortMergeSlices enumerates all slices in a map, to sort by priority and merge by tag func sortMergeSlices(target map[string]interface{}, path string) error { for key, value := range target { if slice, ok := value.([]interface{}); ok { sortByPriority(slice) s, err := mergeSameTag(slice, fmt.Sprintf("%s.%s", path, key)) if err != nil { return err } target[key] = s for _, item := range s { if m, ok := item.(map[string]interface{}); ok { sortMergeSlices(m, fmt.Sprintf("%s.%s[]", path, key)) } } } else if field, ok := value.(map[string]interface{}); ok { sortMergeSlices(field, fmt.Sprintf("%s.%s", path, key)) } } return nil } func removeHelperFields(target map[string]interface{}) { for key, value := range target { if key == priorityKey || key == tagKey { delete(target, key) } else if slice, ok := value.([]interface{}); ok { for _, e := range slice { if el, ok := e.(map[string]interface{}); ok { removeHelperFields(el) } } } else if field, ok := value.(map[string]interface{}); ok { removeHelperFields(field) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/errors.generated.go
infra/conf/merge/errors.generated.go
package merge 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/merge/priority.go
infra/conf/merge/priority.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. package merge import "sort" func getPriority(v interface{}) float64 { var m map[string]interface{} var ok bool if m, ok = v.(map[string]interface{}); !ok { return 0 } if i, ok := m[priorityKey]; ok { if p, ok := i.(float64); ok { return p } } return 0 } // sortByPriority sort slice by priority fields of their elements func sortByPriority(slice []interface{}) { sort.Slice( slice, func(i, j int) bool { return getPriority(slice[i]) < getPriority(slice[j]) }, ) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/map.go
infra/conf/merge/map.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. package merge import ( "fmt" "reflect" ) // mergeMaps merges source map into target // it supports only map[string]interface{} type for any children of the map tree func mergeMaps(target map[string]interface{}, source map[string]interface{}) (err error) { for key, value := range source { target[key], err = mergeField(target[key], value) if err != nil { return } } return } func mergeField(target interface{}, source interface{}) (interface{}, error) { if source == nil { return target, nil } if target == nil { return source, nil } if reflect.TypeOf(source) != reflect.TypeOf(target) { return nil, fmt.Errorf("type mismatch, expect %T, incoming %T", target, source) } if slice, ok := source.([]interface{}); ok { tslice, _ := target.([]interface{}) tslice = append(tslice, slice...) return tslice, nil } else if smap, ok := source.(map[string]interface{}); ok { tmap, _ := target.(map[string]interface{}) err := mergeMaps(tmap, smap) return tmap, err } return source, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/merge/tag.go
infra/conf/merge/tag.go
// Copyright 2020 Jebbs. All rights reserved. // Use of this source code is governed by MIT // license that can be found in the LICENSE file. package merge import ( "strings" ) func getTag(v map[string]interface{}, tagKeyOnly bool) string { if !tagKeyOnly { if field, ok := v["tag"]; ok { if t, ok := field.(string); ok { return t } } } if field, ok := v[tagKey]; ok { if t, ok := field.(string); ok { return t } } return "" } func mergeSameTag(s []interface{}, path string) ([]interface{}, error) { // from: [a,"",b,"",a,"",b,""] // to: [a,"",b,"",merged,"",merged,""] merged := &struct{}{} tagKeyOnly := false // See https://github.com/v2fly/v2ray-core/issues/2981 if strings.HasPrefix(path, ".dns.servers") { tagKeyOnly = true } for i, item1 := range s { map1, ok := item1.(map[string]interface{}) if !ok { continue } tag1 := getTag(map1, tagKeyOnly) if tag1 == "" { continue } for j := i + 1; j < len(s); j++ { map2, ok := s[j].(map[string]interface{}) if !ok { continue } tag2 := getTag(map2, tagKeyOnly) if tag1 == tag2 { s[j] = merged err := mergeMaps(map1, map2) if err != nil { return nil, err } } } } // remove merged ns := make([]interface{}, 0) for _, item := range s { if item == merged { continue } ns = append(ns, item) } return ns, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v2jsonpb/followerany.go
infra/conf/v2jsonpb/followerany.go
package v2jsonpb import "google.golang.org/protobuf/reflect/protoreflect" type V2JsonProtobufAnyTypeDescriptor struct { protoreflect.MessageDescriptor } func (v V2JsonProtobufAnyTypeDescriptor) FullName() protoreflect.FullName { return "org.v2fly.SynAny" } func (v V2JsonProtobufAnyTypeDescriptor) Fields() protoreflect.FieldDescriptors { return V2JsonProtobufAnyTypeFields{v.MessageDescriptor.Fields()} } type V2JsonProtobufAnyTypeFields struct { protoreflect.FieldDescriptors } func (v V2JsonProtobufAnyTypeFields) Len() int { panic("implement me") } func (v V2JsonProtobufAnyTypeFields) Get(i int) protoreflect.FieldDescriptor { panic("implement me") } func (v V2JsonProtobufAnyTypeFields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor { panic("implement me") } func (v V2JsonProtobufAnyTypeFields) ByJSONName(s string) protoreflect.FieldDescriptor { switch s { case "type": return &V2JsonProtobufFollowerFieldDescriptor{v.FieldDescriptors.ByName("type_url")} default: return &V2JsonProtobufAnyValueField{v.FieldDescriptors.ByName("value"), "value"} } } func (v V2JsonProtobufAnyTypeFields) ByTextName(s string) protoreflect.FieldDescriptor { panic("implement me") } func (v V2JsonProtobufAnyTypeFields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor { panic("implement me") } type V2JsonProtobufAnyTypeFieldDescriptor struct { protoreflect.FieldDescriptor } func (v V2JsonProtobufAnyTypeFieldDescriptor) JSONName() string { return "type" } func (v V2JsonProtobufAnyTypeFieldDescriptor) TextName() string { return "type" } type V2JsonProtobufAnyValueField struct { protoreflect.FieldDescriptor name string } func (v *V2JsonProtobufAnyValueField) Kind() protoreflect.Kind { return protoreflect.MessageKind } func (v *V2JsonProtobufAnyValueField) JSONName() string { return v.name } func (v *V2JsonProtobufAnyValueField) TextName() string { return v.name } type V2JsonProtobufAnyValueFieldReturn struct { protoreflect.Message } func (v *V2JsonProtobufAnyValueFieldReturn) ProtoReflect() protoreflect.Message { if bufFollow, ok := v.Message.(*V2JsonProtobufFollower); ok { return bufFollow.Message } return v.Message }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v2jsonpb/errors.generated.go
infra/conf/v2jsonpb/errors.generated.go
package v2jsonpb 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/v2jsonpb/followermap.go
infra/conf/v2jsonpb/followermap.go
package v2jsonpb import "google.golang.org/protobuf/reflect/protoreflect" type V2JsonProtobufMapFollower struct { protoreflect.Map ValueKind protoreflect.FieldDescriptor } func (v V2JsonProtobufMapFollower) Len() int { panic("implement me") } func (v V2JsonProtobufMapFollower) Range(f func(protoreflect.MapKey, protoreflect.Value) bool) { v.Map.Range(func(key protoreflect.MapKey, value protoreflect.Value) bool { return followMapValue(v.ValueKind, value, key, f) }) } func (v V2JsonProtobufMapFollower) Has(key protoreflect.MapKey) bool { return v.Map.Has(key) } func (v V2JsonProtobufMapFollower) Clear(key protoreflect.MapKey) { panic("implement me") } func (v V2JsonProtobufMapFollower) Get(key protoreflect.MapKey) protoreflect.Value { panic("implement me") } func (v V2JsonProtobufMapFollower) Set(key protoreflect.MapKey, value protoreflect.Value) { v.Map.Set(key, value) } func (v V2JsonProtobufMapFollower) Mutable(key protoreflect.MapKey) protoreflect.Value { panic("implement me") } func (v V2JsonProtobufMapFollower) NewValue() protoreflect.Value { newelement := v.Map.NewValue() return protoreflect.ValueOfMessage(&V2JsonProtobufFollower{newelement.Message()}) } func (v V2JsonProtobufMapFollower) IsValid() bool { panic("implement me") } func followMapValue(descriptor protoreflect.FieldDescriptor, value protoreflect.Value, mapkey protoreflect.MapKey, f func(protoreflect.MapKey, protoreflect.Value) bool) bool { if descriptor.Kind() == protoreflect.MessageKind { if descriptor.IsList() { value2 := protoreflect.ValueOfList(V2JsonProtobufListFollower{value.List()}) return f(mapkey, value2) } if descriptor.IsMap() { value2 := protoreflect.ValueOfMap(V2JsonProtobufMapFollower{value.Map(), descriptor.MapValue()}) return f(mapkey, value2) } value2 := protoreflect.ValueOfMessage(&V2JsonProtobufFollower{value.Message()}) return f(mapkey, value2) } return f(mapkey, value) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v2jsonpb/follower.go
infra/conf/v2jsonpb/follower.go
package v2jsonpb import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/anypb" "github.com/v2fly/v2ray-core/v5/common/serial" ) type V2JsonProtobufFollowerFieldDescriptor struct { protoreflect.FieldDescriptor } type V2JsonProtobufFollower struct { protoreflect.Message } func (v *V2JsonProtobufFollower) Type() protoreflect.MessageType { panic("implement me") } func (v *V2JsonProtobufFollower) New() protoreflect.Message { panic("implement me") } func (v *V2JsonProtobufFollower) Interface() protoreflect.ProtoMessage { return v.Message.Interface() } func (v *V2JsonProtobufFollower) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { v.Message.Range(func(descriptor protoreflect.FieldDescriptor, value protoreflect.Value) bool { name := descriptor.FullName() fullname := v.Message.Descriptor().FullName() if fullname == "google.protobuf.Any" { switch name { case "google.protobuf.Any.type_url": fd := V2JsonProtobufAnyTypeFieldDescriptor{descriptor} return f(fd, value) case "google.protobuf.Any.value": url := v.Message.Get(v.Message.Descriptor().Fields().ByName("type_url")).String() fd := &V2JsonProtobufAnyValueField{descriptor, url} bytesout := v.Message.Get(v.Message.Descriptor().Fields().Get(1)).Bytes() v2type := serial.V2TypeFromURL(url) instance, err := serial.GetInstance(v2type) if err != nil { panic(err) } unmarshaler := proto.UnmarshalOptions{AllowPartial: true, Resolver: anyresolverv2{backgroundResolver: serial.GetResolver()}} err = unmarshaler.Unmarshal(bytesout, instance.(proto.Message)) if err != nil { panic(err) } return f(fd, protoreflect.ValueOfMessage(&V2JsonProtobufFollower{instance.(proto.Message).ProtoReflect()})) default: panic("unexpected any value") } } return followValue(descriptor, value, f) }) } func followValue(descriptor protoreflect.FieldDescriptor, value protoreflect.Value, f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) bool { fd := V2JsonProtobufFollowerFieldDescriptor{descriptor} if descriptor.Kind() == protoreflect.MessageKind { if descriptor.IsList() { value2 := protoreflect.ValueOfList(V2JsonProtobufListFollower{value.List()}) return f(fd, value2) } if descriptor.IsMap() { value2 := protoreflect.ValueOfMap(V2JsonProtobufMapFollower{value.Map(), descriptor.MapValue()}) return f(fd, value2) } value2 := protoreflect.ValueOfMessage(&V2JsonProtobufFollower{value.Message()}) return f(fd, value2) } return f(fd, value) } func (v *V2JsonProtobufFollower) Has(descriptor protoreflect.FieldDescriptor) bool { panic("implement me") } func (v *V2JsonProtobufFollower) Clear(descriptor protoreflect.FieldDescriptor) { v.Message.Clear(descriptor) } func (v *V2JsonProtobufFollower) Set(descriptor protoreflect.FieldDescriptor, value protoreflect.Value) { switch descriptor := descriptor.(type) { case V2JsonProtobufFollowerFieldDescriptor: v.Message.Set(descriptor.FieldDescriptor, value) case *V2JsonProtobufFollowerFieldDescriptor: v.Message.Set(descriptor.FieldDescriptor, value) case *V2JsonProtobufAnyValueField: protodata := value.Message() bytesw, err := proto.MarshalOptions{AllowPartial: true}.Marshal(&V2JsonProtobufAnyValueFieldReturn{protodata}) if err != nil { panic(err) } v.Message.Set(descriptor.FieldDescriptor, protoreflect.ValueOfBytes(bytesw)) default: v.Message.Set(descriptor, value) } } func (v *V2JsonProtobufFollower) Mutable(descriptor protoreflect.FieldDescriptor) protoreflect.Value { value := v.Message.Mutable(descriptor.(V2JsonProtobufFollowerFieldDescriptor).FieldDescriptor) if descriptor.IsList() { return protoreflect.ValueOfList(&V2JsonProtobufListFollower{value.List()}) } if descriptor.IsMap() { return protoreflect.ValueOfMap(&V2JsonProtobufMapFollower{value.Map(), descriptor}) } if descriptor.Kind() == protoreflect.MessageKind { return protoreflect.ValueOfMessage(&V2JsonProtobufFollower{value.Message()}) } return value } func (v *V2JsonProtobufFollower) NewField(descriptor protoreflect.FieldDescriptor) protoreflect.Value { if _, ok := descriptor.(*V2JsonProtobufAnyValueField); ok { url := v.Message.Get(v.Message.Descriptor().Fields().ByName("type_url")).String() v2type := serial.V2TypeFromURL(url) instance, err := serial.GetInstance(v2type) if err != nil { panic(err) } newvalue := protoreflect.ValueOfMessage(&V2JsonProtobufFollower{instance.(proto.Message).ProtoReflect()}) return newvalue } value := v.Message.NewField(descriptor.(V2JsonProtobufFollowerFieldDescriptor).FieldDescriptor) newvalue := protoreflect.ValueOfMessage(&V2JsonProtobufFollower{value.Message()}) return newvalue } func (v *V2JsonProtobufFollower) WhichOneof(descriptor protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { panic("implement me") } func (v *V2JsonProtobufFollower) GetUnknown() protoreflect.RawFields { panic("implement me") } func (v *V2JsonProtobufFollower) SetUnknown(fields protoreflect.RawFields) { v.Message.SetUnknown(fields) } func (v *V2JsonProtobufFollower) IsValid() bool { return v.Message.IsValid() } func (v *V2JsonProtobufFollower) ProtoReflect() protoreflect.Message { return v } func (v *V2JsonProtobufFollower) Descriptor() protoreflect.MessageDescriptor { fullname := v.Message.Descriptor().FullName() if fullname == "google.protobuf.Any" { desc := &V2JsonProtobufAnyTypeDescriptor{(&anypb.Any{}).ProtoReflect().Descriptor()} return desc } return &V2JsonProtobufFollowerDescriptor{v.Message.Descriptor()} } func (v *V2JsonProtobufFollower) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { panic("implement me") } type V2JsonProtobufFollowerDescriptor struct { protoreflect.MessageDescriptor } func (v *V2JsonProtobufFollowerDescriptor) Fields() protoreflect.FieldDescriptors { return &V2JsonProtobufFollowerFields{v.MessageDescriptor.Fields()} } type V2JsonProtobufFollowerFields struct { protoreflect.FieldDescriptors } func (v *V2JsonProtobufFollowerFields) ByJSONName(s string) protoreflect.FieldDescriptor { return V2JsonProtobufFollowerFieldDescriptor{v.FieldDescriptors.ByJSONName(s)} } func (v *V2JsonProtobufFollowerFields) ByTextName(s string) protoreflect.FieldDescriptor { return V2JsonProtobufFollowerFieldDescriptor{v.FieldDescriptors.ByTextName(s)} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v2jsonpb/v2jsonpb.go
infra/conf/v2jsonpb/v2jsonpb.go
package v2jsonpb import ( "io" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/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 loadV2JsonPb(data []byte) (*core.Config, error) { coreconf := &core.Config{} jsonpbloader := &protojson.UnmarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true} err := jsonpbloader.Unmarshal(data, &V2JsonProtobufFollower{coreconf.ProtoReflect()}) if err != nil { return nil, err } return coreconf, nil } func dumpV2JsonPb(config proto.Message) ([]byte, error) { jsonpbdumper := &protojson.MarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true} bytew, err := jsonpbdumper.Marshal(&V2JsonProtobufFollower{config.ProtoReflect()}) if err != nil { return nil, err } return bytew, nil } func DumpV2JsonPb(config proto.Message) ([]byte, error) { return dumpV2JsonPb(config) } const FormatProtobufV2JSONPB = "v2jsonpb" func init() { common.Must(core.RegisterConfigLoader(&core.ConfigFormat{ Name: []string{FormatProtobufV2JSONPB}, Extension: []string{".v2pb.json", ".v2pbjson"}, 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 loadV2JsonPb(data) case []byte: return loadV2JsonPb(v) case io.Reader: data, err := buf.ReadAllToBytes(v) if err != nil { return nil, err } return loadV2JsonPb(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/v2jsonpb/followerlist.go
infra/conf/v2jsonpb/followerlist.go
package v2jsonpb import "google.golang.org/protobuf/reflect/protoreflect" type V2JsonProtobufListFollower struct { protoreflect.List } func (v V2JsonProtobufListFollower) Len() int { return v.List.Len() } func (v V2JsonProtobufListFollower) Get(i int) protoreflect.Value { return protoreflect.ValueOfMessage(&V2JsonProtobufFollower{v.List.Get(i).Message()}) } func (v V2JsonProtobufListFollower) Set(i int, value protoreflect.Value) { panic("implement me") } func (v V2JsonProtobufListFollower) Append(value protoreflect.Value) { v.List.Append(value) } func (v V2JsonProtobufListFollower) AppendMutable() protoreflect.Value { panic("implement me") } func (v V2JsonProtobufListFollower) Truncate(i int) { panic("implement me") } func (v V2JsonProtobufListFollower) NewElement() protoreflect.Value { newelement := v.List.NewElement() return protoreflect.ValueOfMessage(&V2JsonProtobufFollower{newelement.Message()}) } func (v V2JsonProtobufListFollower) IsValid() bool { panic("implement me") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/infra/conf/v2jsonpb/any2.go
infra/conf/v2jsonpb/any2.go
package v2jsonpb import ( "github.com/golang/protobuf/jsonpb" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) type anyresolverv2 struct { backgroundResolver jsonpb.AnyResolver } func (r anyresolverv2) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { panic("implement me") } func (r anyresolverv2) FindMessageByURL(url string) (protoreflect.MessageType, error) { msg, err := r.backgroundResolver.Resolve(url) if err != nil { return nil, err } return msg.(proto.Message).ProtoReflect().Type(), nil } func (r anyresolverv2) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { panic("implement me") } func (r anyresolverv2) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { panic("implement me") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/errors.generated.go
features/errors.generated.go
package features 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/features/feature.go
features/feature.go
package features import "github.com/v2fly/v2ray-core/v5/common" //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen // Feature is the interface for V2Ray features. All features must implement this interface. // All existing features have an implementation in app directory. These features can be replaced by third-party ones. type Feature interface { common.HasType common.Runnable } // PrintDeprecatedFeatureWarning prints a warning for deprecated feature. func PrintDeprecatedFeatureWarning(feature string) { newError("You are using a deprecated feature: " + feature + ". Please update your config file with latest configuration format, or update your client software.").WriteToLog() } // TaggedFeatures unstable type TaggedFeatures interface { GetFeaturesByTag(tag string) (Feature, error) common.Runnable }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/storage.go
features/extension/storage.go
package extension import ( "context" "github.com/v2fly/v2ray-core/v5/features" ) type PersistentStorageEngine interface { features.Feature PersistentStorageEngine() Put(ctx context.Context, key []byte, value []byte) error Get(ctx context.Context, key []byte) ([]byte, error) List(ctx context.Context, keyPrefix []byte) ([][]byte, error) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/browser.go
features/extension/browser.go
package extension import ( "io" "net/http" ) type BrowserForwarder interface { DialWebsocket(url string, header http.Header) (io.ReadWriteCloser, error) } func BrowserForwarderType() interface{} { return (*BrowserForwarder)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/instance.go
features/extension/instance.go
package extension import ( "context" "github.com/v2fly/v2ray-core/v5/features" ) // InstanceManagement : unstable type InstanceManagement interface { features.Feature ListInstance(ctx context.Context) ([]string, error) AddInstance(ctx context.Context, name string, config []byte, configType string) error StartInstance(ctx context.Context, name string) error StopInstance(ctx context.Context, name string) error UntrackInstance(ctx context.Context, name string) error } func InstanceManagementType() interface{} { return (*InstanceManagement)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/contextreceiver.go
features/extension/contextreceiver.go
package extension import "context" type ContextReceiver interface { InjectContext(ctx context.Context) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/observatory.go
features/extension/observatory.go
package extension import ( "context" "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/features" ) type Observatory interface { features.Feature GetObservation(ctx context.Context) (proto.Message, error) } func ObservatoryType() interface{} { return (*Observatory)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/extension/storage/storage.go
features/extension/storage/storage.go
package storage import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features" ) type ScopedPersistentStorage interface { ScopedPersistentStorageEngine() Put(ctx context.Context, key []byte, value []byte) error Get(ctx context.Context, key []byte) ([]byte, error) List(ctx context.Context, keyPrefix []byte) ([][]byte, error) Clear(ctx context.Context) NarrowScope(ctx context.Context, key []byte) (ScopedPersistentStorage, error) DropScope(ctx context.Context, key []byte) error } type ScopedTransientStorage interface { ScopedTransientStorage() Put(ctx context.Context, key string, value interface{}) error Get(ctx context.Context, key string) (interface{}, error) List(ctx context.Context, keyPrefix string) ([]string, error) Clear(ctx context.Context) NarrowScope(ctx context.Context, key string) (ScopedTransientStorage, error) DropScope(ctx context.Context, key string) error } type ScopedPersistentStorageService interface { ScopedPersistentStorage features.Feature } var ScopedPersistentStorageServiceType = (*ScopedPersistentStorageService)(nil) type TransientStorageLifecycleReceiver interface { IsTransientStorageLifecycleReceiver() common.Closable }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/balancer.go
features/routing/balancer.go
package routing type BalancerOverrider interface { SetOverrideTarget(tag, target string) error GetOverrideTarget(tag string) (string, error) } type BalancerPrincipleTarget interface { GetPrincipleTarget(tag string) ([]string, error) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/router.go
features/routing/router.go
package routing import ( "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features" ) // Router is a feature to choose an outbound tag for the given request. // // v2ray:api:stable type Router interface { features.Feature // PickRoute returns a route decision based on the given routing context. PickRoute(ctx Context) (Route, error) } // Route is the routing result of Router feature. // // v2ray:api:stable type Route interface { // A Route is also a routing context. Context // GetOutboundGroupTags returns the detoured outbound group tags in sequence before a final outbound is chosen. GetOutboundGroupTags() []string // GetOutboundTag returns the tag of the outbound the connection was dispatched to. GetOutboundTag() string } // RouterType return the type of Router interface. Can be used to implement common.HasType. // // v2ray:api:stable func RouterType() interface{} { return (*Router)(nil) } // DefaultRouter is an implementation of Router, which always returns ErrNoClue for routing decisions. type DefaultRouter struct{} // Type implements common.HasType. func (DefaultRouter) Type() interface{} { return RouterType() } // PickRoute implements Router. func (DefaultRouter) PickRoute(ctx Context) (Route, error) { return nil, common.ErrNoClue } // Start implements common.Runnable. func (DefaultRouter) Start() error { return nil } // Close implements common.Closable. func (DefaultRouter) Close() error { return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/dispatcher.go
features/routing/dispatcher.go
package routing import ( "context" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/transport" ) // Dispatcher is a feature that dispatches inbound requests to outbound handlers based on rules. // Dispatcher is required to be registered in a V2Ray instance to make V2Ray function properly. // // v2ray:api:stable type Dispatcher interface { features.Feature // Dispatch returns a Ray for transporting data for the given request. Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) } // DispatcherType returns the type of Dispatcher interface. Can be used to implement common.HasType. // // v2ray:api:stable func DispatcherType() interface{} { return (*Dispatcher)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/context.go
features/routing/context.go
package routing import ( "github.com/v2fly/v2ray-core/v5/common/net" ) // Context is a feature to store connection information for routing. // // v2ray:api:stable type Context interface { // GetInboundTag returns the tag of the inbound the connection was from. GetInboundTag() string // GetSourcesIPs returns the source IPs bound to the connection. GetSourceIPs() []net.IP // GetSourcePort returns the source port of the connection. GetSourcePort() net.Port // GetTargetIPs returns the target IP of the connection or resolved IPs of target domain. GetTargetIPs() []net.IP // GetTargetPort returns the target port of the connection. GetTargetPort() net.Port // GetTargetDomain returns the target domain of the connection, if exists. GetTargetDomain() string // GetNetwork returns the network type of the connection. GetNetwork() net.Network // GetProtocol returns the protocol from the connection content, if sniffed out. GetProtocol() string // GetUser returns the user email from the connection content, if exists. GetUser() string // GetAttributes returns extra attributes from the connection content. GetAttributes() map[string]string // GetSkipDNSResolve returns a flag switch for weather skip dns resolve during route pick. GetSkipDNSResolve() bool }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/session/context.go
features/routing/session/context.go
package session import ( "context" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/routing" ) // Context is an implementation of routing.Context, which is a wrapper of context.context with session info. type Context struct { Inbound *session.Inbound Outbound *session.Outbound Content *session.Content } // GetInboundTag implements routing.Context. func (ctx *Context) GetInboundTag() string { if ctx.Inbound == nil { return "" } return ctx.Inbound.Tag } // GetSourceIPs implements routing.Context. func (ctx *Context) GetSourceIPs() []net.IP { if ctx.Inbound == nil || !ctx.Inbound.Source.IsValid() { return nil } dest := ctx.Inbound.Source if dest.Address.Family().IsDomain() { return nil } return []net.IP{dest.Address.IP()} } // GetSourcePort implements routing.Context. func (ctx *Context) GetSourcePort() net.Port { if ctx.Inbound == nil || !ctx.Inbound.Source.IsValid() { return 0 } return ctx.Inbound.Source.Port } // GetTargetIPs implements routing.Context. func (ctx *Context) GetTargetIPs() []net.IP { if ctx.Outbound == nil || !ctx.Outbound.Target.IsValid() { return nil } if ctx.Outbound.Target.Address.Family().IsIP() { return []net.IP{ctx.Outbound.Target.Address.IP()} } return nil } // GetTargetPort implements routing.Context. func (ctx *Context) GetTargetPort() net.Port { if ctx.Outbound == nil || !ctx.Outbound.Target.IsValid() { return 0 } return ctx.Outbound.Target.Port } // GetTargetDomain implements routing.Context. func (ctx *Context) GetTargetDomain() string { if ctx.Outbound == nil || !ctx.Outbound.Target.IsValid() { return "" } dest := ctx.Outbound.Target if !dest.Address.Family().IsDomain() { return "" } return dest.Address.Domain() } // GetNetwork implements routing.Context. func (ctx *Context) GetNetwork() net.Network { if ctx.Outbound == nil { return net.Network_Unknown } return ctx.Outbound.Target.Network } // GetProtocol implements routing.Context. func (ctx *Context) GetProtocol() string { if ctx.Content == nil { return "" } return ctx.Content.Protocol } // GetUser implements routing.Context. func (ctx *Context) GetUser() string { if ctx.Inbound == nil || ctx.Inbound.User == nil { return "" } return ctx.Inbound.User.Email } // GetAttributes implements routing.Context. func (ctx *Context) GetAttributes() map[string]string { if ctx.Content == nil { return nil } return ctx.Content.Attributes } // GetSkipDNSResolve implements routing.Context. func (ctx *Context) GetSkipDNSResolve() bool { if ctx.Content == nil { return false } return ctx.Content.SkipDNSResolve } // AsRoutingContext creates a context from context.context with session info. func AsRoutingContext(ctx context.Context) routing.Context { return &Context{ Inbound: session.InboundFromContext(ctx), Outbound: session.OutboundFromContext(ctx), Content: session.ContentFromContext(ctx), } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/routing/dns/errors.generated.go
features/routing/dns/errors.generated.go
package dns 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/features/routing/dns/context.go
features/routing/dns/context.go
package dns //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/routing" ) // ResolvableContext is an implementation of routing.Context, with domain resolving capability. type ResolvableContext struct { routing.Context dnsClient dns.Client resolvedIPs []net.IP } // GetTargetIPs overrides original routing.Context's implementation. func (ctx *ResolvableContext) GetTargetIPs() []net.IP { if ips := ctx.Context.GetTargetIPs(); len(ips) != 0 { return ips } if len(ctx.resolvedIPs) > 0 { return ctx.resolvedIPs } if domain := ctx.GetTargetDomain(); len(domain) != 0 { ips, err := ctx.dnsClient.LookupIP(domain) if err == nil { ctx.resolvedIPs = ips return ips } newError("resolve ip for ", domain).Base(err).WriteToLog() } return nil } // ContextWithDNSClient creates a new routing context with domain resolving capability. // Resolved domain IPs can be retrieved by GetTargetIPs(). func ContextWithDNSClient(ctx routing.Context, client dns.Client) routing.Context { return &ResolvableContext{Context: ctx, dnsClient: client} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/stats/stats.go
features/stats/stats.go
package stats //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features" ) // Counter is the interface for stats counters. // // v2ray:api:stable type Counter interface { // Value is the current value of the counter. Value() int64 // Set sets a new value to the counter, and returns the previous one. Set(int64) int64 // Add adds a value to the current counter value, and returns the previous value. Add(int64) int64 } // Channel is the interface for stats channel. // // v2ray:api:stable type Channel interface { // Channel is a runnable unit. common.Runnable // Publish broadcasts a message through the channel with a controlling context. Publish(context.Context, interface{}) // SubscriberCount returns the number of the subscribers. Subscribers() []chan interface{} // Subscribe registers for listening to channel stream and returns a new listener channel. Subscribe() (chan interface{}, error) // Unsubscribe unregisters a listener channel from current Channel object. Unsubscribe(chan interface{}) error } // SubscribeRunnableChannel subscribes the channel and starts it if there is first subscriber coming. func SubscribeRunnableChannel(c Channel) (chan interface{}, error) { if len(c.Subscribers()) == 0 { if err := c.Start(); err != nil { return nil, err } } return c.Subscribe() } // UnsubscribeClosableChannel unsubscribes the channel and close it if there is no more subscriber. func UnsubscribeClosableChannel(c Channel, sub chan interface{}) error { if err := c.Unsubscribe(sub); err != nil { return err } if len(c.Subscribers()) == 0 { return c.Close() } return nil } // Manager is the interface for stats manager. // // v2ray:api:stable type Manager interface { features.Feature // RegisterCounter registers a new counter to the manager. The identifier string must not be empty, and unique among other counters. RegisterCounter(string) (Counter, error) // UnregisterCounter unregisters a counter from the manager by its identifier. UnregisterCounter(string) error // GetCounter returns a counter by its identifier. GetCounter(string) Counter // RegisterChannel registers a new channel to the manager. The identifier string must not be empty, and unique among other channels. RegisterChannel(string) (Channel, error) // UnregisterCounter unregisters a channel from the manager by its identifier. UnregisterChannel(string) error // GetChannel returns a channel by its identifier. GetChannel(string) Channel } // GetOrRegisterCounter tries to get the StatCounter first. If not exist, it then tries to create a new counter. func GetOrRegisterCounter(m Manager, name string) (Counter, error) { counter := m.GetCounter(name) if counter != nil { return counter, nil } return m.RegisterCounter(name) } // GetOrRegisterChannel tries to get the StatChannel first. If not exist, it then tries to create a new channel. func GetOrRegisterChannel(m Manager, name string) (Channel, error) { channel := m.GetChannel(name) if channel != nil { return channel, nil } return m.RegisterChannel(name) } // ManagerType returns the type of Manager interface. Can be used to implement common.HasType. // // v2ray:api:stable func ManagerType() interface{} { return (*Manager)(nil) } // NoopManager is an implementation of Manager, which doesn't has actual functionalities. type NoopManager struct{} // Type implements common.HasType. func (NoopManager) Type() interface{} { return ManagerType() } // RegisterCounter implements Manager. func (NoopManager) RegisterCounter(string) (Counter, error) { return nil, newError("not implemented") } // UnregisterCounter implements Manager. func (NoopManager) UnregisterCounter(string) error { return nil } // GetCounter implements Manager. func (NoopManager) GetCounter(string) Counter { return nil } // RegisterChannel implements Manager. func (NoopManager) RegisterChannel(string) (Channel, error) { return nil, newError("not implemented") } // UnregisterChannel implements Manager. func (NoopManager) UnregisterChannel(string) error { return nil } // GetChannel implements Manager. func (NoopManager) GetChannel(string) Channel { return nil } // Start implements common.Runnable. func (NoopManager) Start() error { return nil } // Close implements common.Closable. func (NoopManager) Close() error { return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/stats/errors.generated.go
features/stats/errors.generated.go
package stats 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/features/dns/client.go
features/dns/client.go
package dns import ( "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/features" ) // IPOption is an object for IP query options. type IPOption struct { IPv4Enable bool IPv6Enable bool FakeEnable bool } func (opt IPOption) With(other IPOption) IPOption { return IPOption{ IPv4Enable: opt.IPv4Enable && other.IPv4Enable, IPv6Enable: opt.IPv6Enable && other.IPv6Enable, FakeEnable: opt.FakeEnable && other.FakeEnable, } } func (opt IPOption) IsValid() bool { return opt.IPv4Enable || opt.IPv6Enable } // Client is a V2Ray feature for querying DNS information. // // v2ray:api:stable type Client interface { features.Feature // LookupIP returns IP address for the given domain. IPs may contain IPv4 and/or IPv6 addresses. LookupIP(domain string) ([]net.IP, error) } // IPv4Lookup is an optional feature for querying IPv4 addresses only. // // v2ray:api:beta type IPv4Lookup interface { LookupIPv4(domain string) ([]net.IP, error) } // IPv6Lookup is an optional feature for querying IPv6 addresses only. // // v2ray:api:beta type IPv6Lookup interface { LookupIPv6(domain string) ([]net.IP, error) } // LookupIPWithOption is a helper function for querying DNS information from a dns.Client with dns.IPOption. // // v2ray:api:beta func LookupIPWithOption(client Client, domain string, option IPOption) ([]net.IP, error) { if option.FakeEnable { if clientWithFakeDNS, ok := client.(ClientWithFakeDNS); ok { client = clientWithFakeDNS.AsFakeDNSClient() } } if option.IPv4Enable && !option.IPv6Enable { if ipv4Lookup, ok := client.(IPv4Lookup); ok { return ipv4Lookup.LookupIPv4(domain) } else { return nil, errors.New("dns.Client doesn't implement IPv4Lookup") } } if option.IPv6Enable && !option.IPv4Enable { if ipv6Lookup, ok := client.(IPv6Lookup); ok { return ipv6Lookup.LookupIPv6(domain) } else { return nil, errors.New("dns.Client doesn't implement IPv6Lookup") } } return client.LookupIP(domain) } // ClientType returns the type of Client interface. Can be used for implementing common.HasType. // // v2ray:api:beta func ClientType() interface{} { return (*Client)(nil) } // ErrEmptyResponse indicates that DNS query succeeded but no answer was returned. var ErrEmptyResponse = errors.New("empty response") type RCodeError uint16 func (e RCodeError) Error() string { return serial.Concat("rcode: ", uint16(e)) } func RCodeFromError(err error) uint16 { if err == nil { return 0 } cause := errors.Cause(err) if r, ok := cause.(RCodeError); ok { return uint16(r) } return 0 }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/dns/fakedns.go
features/dns/fakedns.go
package dns import ( "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features" ) // FakeDNSEngine is a V2Ray feature for converting between domain and fake IPs. // // v2ray:api:beta type FakeDNSEngine interface { features.Feature // GetFakeIPForDomain returns fake IP addresses for the given domain, and registers the domain with the returned IPs. GetFakeIPForDomain(domain string) []net.Address // GetDomainFromFakeDNS returns the bound domain name for the given fake IP. GetDomainFromFakeDNS(ip net.Address) string } // FakeDNSEngineRev0 adds additional APIs for FakeDNSEngine. // // v2ray:api:beta type FakeDNSEngineRev0 interface { FakeDNSEngine // IsIPInIPPool tests whether the given IP address resides in managed fake IP pools. IsIPInIPPool(ip net.Address) bool // GetFakeIPForDomain3 registers and returns fake IP addresses for the given domain in IPv4 and/or IPv6. GetFakeIPForDomain3(domain string, IPv4 bool, IPv6 bool) []net.Address } // ClientWithFakeDNS is an optional feature for utilizing FakeDNS feature of DNS client. // // v2ray:api:beta type ClientWithFakeDNS interface { // AsFakeDNSClient converts the client to dns.Client that enables FakeDNS querying option. AsFakeDNSClient() Client // AsFakeDNSEngine converts the client to dns.FakeDNSEngine that could serve FakeDNSEngine feature. AsFakeDNSEngine() FakeDNSEngine } // FakeDNSEngineType returns the type of FakeDNSEngine interface. Can be used for implementing common.HasType. // // v2ray:api:beta func FakeDNSEngineType() interface{} { return (*FakeDNSEngine)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/dns/localdns/errors.generated.go
features/dns/localdns/errors.generated.go
package localdns 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/features/dns/localdns/client.go
features/dns/localdns/client.go
package localdns import ( "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" ) // Client is an implementation of dns.Client, which queries localhost for DNS. type Client struct{} // Type implements common.HasType. func (*Client) Type() interface{} { return dns.ClientType() } // Start implements common.Runnable. func (*Client) Start() error { return nil } // Close implements common.Closable. func (*Client) Close() error { return nil } // LookupIP implements Client. func (*Client) LookupIP(host string) ([]net.IP, error) { ips, err := net.LookupIP(host) if err != nil { return nil, err } parsedIPs := make([]net.IP, 0, len(ips)) for _, ip := range ips { parsed := net.IPAddress(ip) if parsed != nil { parsedIPs = append(parsedIPs, parsed.IP()) } } if len(parsedIPs) == 0 { return nil, dns.ErrEmptyResponse } return parsedIPs, nil } // LookupIPv4 implements IPv4Lookup. func (c *Client) LookupIPv4(host string) ([]net.IP, error) { ips, err := c.LookupIP(host) if err != nil { return nil, err } ipv4 := make([]net.IP, 0, len(ips)) for _, ip := range ips { if len(ip) == net.IPv4len { ipv4 = append(ipv4, ip) } } if len(ipv4) == 0 { return nil, dns.ErrEmptyResponse } return ipv4, nil } // LookupIPv6 implements IPv6Lookup. func (c *Client) LookupIPv6(host string) ([]net.IP, error) { ips, err := c.LookupIP(host) if err != nil { return nil, err } ipv6 := make([]net.IP, 0, len(ips)) for _, ip := range ips { if len(ip) == net.IPv6len { ipv6 = append(ipv6, ip) } } if len(ipv6) == 0 { return nil, dns.ErrEmptyResponse } return ipv6, nil } // New create a new dns.Client that queries localhost for DNS. func New() *Client { return &Client{} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/outbound/outbound.go
features/outbound/outbound.go
package outbound import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/transport" ) // Handler is the interface for handlers that process outbound connections. // // v2ray:api:stable type Handler interface { common.Runnable Tag() string Dispatch(ctx context.Context, link *transport.Link) } type HandlerSelector interface { Select([]string) []string } // Manager is a feature that manages outbound.Handlers. // // v2ray:api:stable type Manager interface { features.Feature // GetHandler returns an outbound.Handler for the given tag. GetHandler(tag string) Handler // GetDefaultHandler returns the default outbound.Handler. It is usually the first outbound.Handler specified in the configuration. GetDefaultHandler() Handler // AddHandler adds a handler into this outbound.Manager. AddHandler(ctx context.Context, handler Handler) error // RemoveHandler removes a handler from outbound.Manager. RemoveHandler(ctx context.Context, tag string) error } // ManagerType returns the type of Manager interface. Can be used to implement common.HasType. // // v2ray:api:stable func ManagerType() interface{} { return (*Manager)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/inbound/inbound.go
features/inbound/inbound.go
package inbound import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features" ) // Handler is the interface for handlers that process inbound connections. // // v2ray:api:stable type Handler interface { common.Runnable // The tag of this handler. Tag() string // Deprecated: Do not use in new code. GetRandomInboundProxy() (interface{}, net.Port, int) } // Manager is a feature that manages InboundHandlers. // // v2ray:api:stable type Manager interface { features.Feature // GetHandlers returns an InboundHandler for the given tag. GetHandler(ctx context.Context, tag string) (Handler, error) // AddHandler adds the given handler into this Manager. AddHandler(ctx context.Context, handler Handler) error // RemoveHandler removes a handler from Manager. RemoveHandler(ctx context.Context, tag string) error } // ManagerType returns the type of Manager interface. Can be used for implementing common.HasType. // // v2ray:api:stable func ManagerType() interface{} { return (*Manager)(nil) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/policy/policy.go
features/policy/policy.go
package policy import ( "context" "runtime" "time" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/features" ) // Timeout contains limits for connection timeout. type Timeout struct { // Timeout for handshake phase in a connection. Handshake time.Duration // Timeout for connection being idle, i.e., there is no egress or ingress traffic in this connection. ConnectionIdle time.Duration // Timeout for an uplink only connection, i.e., the downlink of the connection has been closed. UplinkOnly time.Duration // Timeout for an downlink only connection, i.e., the uplink of the connection has been closed. DownlinkOnly time.Duration } // Stats contains settings for stats counters. type Stats struct { // Whether or not to enable stat counter for user uplink traffic. UserUplink bool // Whether or not to enable stat counter for user downlink traffic. UserDownlink bool } // Buffer contains settings for internal buffer. type Buffer struct { // Size of buffer per connection, in bytes. -1 for unlimited buffer. PerConnection int32 } // SystemStats contains stat policy settings on system level. type SystemStats struct { // Whether or not to enable stat counter for uplink traffic in inbound handlers. InboundUplink bool // Whether or not to enable stat counter for downlink traffic in inbound handlers. InboundDownlink bool // Whether or not to enable stat counter for uplink traffic in outbound handlers. OutboundUplink bool // Whether or not to enable stat counter for downlink traffic in outbound handlers. OutboundDownlink bool } // System contains policy settings at system level. type System struct { Stats SystemStats OverrideAccessLogDest bool Buffer Buffer } // Session is session based settings for controlling V2Ray requests. It contains various settings (or limits) that may differ for different users in the context. type Session struct { Timeouts Timeout // Timeout settings Stats Stats Buffer Buffer } // Manager is a feature that provides Policy for the given user by its id or level. // // v2ray:api:stable type Manager interface { features.Feature // ForLevel returns the Session policy for the given user level. ForLevel(level uint32) Session // ForSystem returns the System policy for V2Ray system. ForSystem() System } // ManagerType returns the type of Manager interface. Can be used to implement common.HasType. // // v2ray:api:stable func ManagerType() interface{} { return (*Manager)(nil) } var defaultBufferSize int32 func init() { const key = "v2ray.ray.buffer.size" const defaultValue = -17 size := platform.EnvFlag{ Name: key, AltName: platform.NormalizeEnvName(key), }.GetValueAsInt(defaultValue) switch size { case 0: defaultBufferSize = -1 // For pipe to use unlimited size case defaultValue: // Env flag not defined. Use default values per CPU-arch. switch runtime.GOARCH { case "arm", "mips", "mipsle": defaultBufferSize = 0 case "arm64", "mips64", "mips64le": defaultBufferSize = 4 * 1024 // 4k cache for low-end devices default: defaultBufferSize = 512 * 1024 } default: defaultBufferSize = int32(size) * 1024 * 1024 } } func defaultBufferPolicy() Buffer { return Buffer{ PerConnection: defaultBufferSize, } } // SessionDefault returns the Policy when user is not specified. func SessionDefault() Session { return Session{ Timeouts: Timeout{ // Align Handshake timeout with nginx client_header_timeout // So that this value will not indicate server identity Handshake: time.Second * 60, ConnectionIdle: time.Second * 300, UplinkOnly: time.Second * 1, DownlinkOnly: time.Second * 1, }, Stats: Stats{ UserUplink: false, UserDownlink: false, }, Buffer: defaultBufferPolicy(), } } type policyKey int32 const ( bufferPolicyKey policyKey = 0 ) func ContextWithBufferPolicy(ctx context.Context, p Buffer) context.Context { return context.WithValue(ctx, bufferPolicyKey, p) } func BufferPolicyFromContext(ctx context.Context) Buffer { pPolicy := ctx.Value(bufferPolicyKey) if pPolicy == nil { return defaultBufferPolicy() } return pPolicy.(Buffer) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/features/policy/default.go
features/policy/default.go
package policy import ( "time" ) // DefaultManager is the implementation of the Manager. type DefaultManager struct{} // Type implements common.HasType. func (DefaultManager) Type() interface{} { return ManagerType() } // ForLevel implements Manager. func (DefaultManager) ForLevel(level uint32) Session { p := SessionDefault() if level == 1 { p.Timeouts.ConnectionIdle = time.Second * 600 } return p } // ForSystem implements Manager. func (DefaultManager) ForSystem() System { return System{} } // Start implements common.Runnable. func (DefaultManager) Start() error { return nil } // Close implements common.Closable. func (DefaultManager) Close() error { return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/common_test.go
common/common_test.go
package common_test import ( "errors" "testing" . "github.com/v2fly/v2ray-core/v5/common" ) func TestMust(t *testing.T) { hasPanic := func(f func()) (ret bool) { defer func() { if r := recover(); r != nil { ret = true } }() f() return false } testCases := []struct { Input func() Panic bool }{ { Panic: true, Input: func() { Must(func() error { return errors.New("test error") }()) }, }, { Panic: true, Input: func() { Must2(func() (int, error) { return 0, errors.New("test error") }()) }, }, { Panic: false, Input: func() { Must(func() error { return nil }()) }, }, } for idx, test := range testCases { if hasPanic(test.Input) != test.Panic { t.Error("test case #", idx, " expect panic ", test.Panic, " but actually not") } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/type_test.go
common/type_test.go
package common_test import ( "context" "testing" . "github.com/v2fly/v2ray-core/v5/common" ) type TConfig struct { value int } type YConfig struct { value string } func TestObjectCreation(t *testing.T) { f := func(ctx context.Context, t interface{}) (interface{}, error) { return func() int { return t.(*TConfig).value }, nil } Must(RegisterConfig((*TConfig)(nil), f)) err := RegisterConfig((*TConfig)(nil), f) if err == nil { t.Error("expect non-nil error, but got nil") } g, err := CreateObject(context.Background(), &TConfig{value: 2}) Must(err) if v := g.(func() int)(); v != 2 { t.Error("expect return value 2, but got ", v) } _, err = CreateObject(context.Background(), &YConfig{value: "T"}) if err == nil { t.Error("expect non-nil error, but got nil") } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/errors.generated.go
common/errors.generated.go
package common 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/common/interfaces.go
common/interfaces.go
package common import "github.com/v2fly/v2ray-core/v5/common/errors" // Closable is the interface for objects that can release its resources. // // v2ray:api:beta type Closable interface { // Close release all resources used by this object, including goroutines. Close() error } // Interruptible is an interface for objects that can be stopped before its completion. // // v2ray:api:beta type Interruptible interface { Interrupt() } // Close closes the obj if it is a Closable. // // v2ray:api:beta func Close(obj interface{}) error { if c, ok := obj.(Closable); ok { return c.Close() } return nil } // Interrupt calls Interrupt() if object implements Interruptible interface, or Close() if the object implements Closable interface. // // v2ray:api:beta func Interrupt(obj interface{}) error { if c, ok := obj.(Interruptible); ok { c.Interrupt() return nil } return Close(obj) } // Runnable is the interface for objects that can start to work and stop on demand. type Runnable interface { // Start starts the runnable object. Upon the method returning nil, the object begins to function properly. Start() error Closable } // HasType is the interface for objects that knows its type. type HasType interface { // Type returns the type of the object. // Usually it returns (*Type)(nil) of the object. Type() interface{} } // ChainedClosable is a Closable that consists of multiple Closable objects. type ChainedClosable []Closable // Close implements Closable. func (cc ChainedClosable) Close() error { var errs []error for _, c := range cc { if err := c.Close(); err != nil { errs = append(errs, err) } } return errors.Combine(errs...) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/type.go
common/type.go
package common import ( "context" "reflect" "github.com/v2fly/v2ray-core/v5/common/registry" ) // ConfigCreator is a function to create an object by a config. type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error) var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator) // RegisterConfig registers a global config creator. The config can be nil but must have a type. func RegisterConfig(config interface{}, configCreator ConfigCreator) error { configType := reflect.TypeOf(config) if _, found := typeCreatorRegistry[configType]; found { return newError(configType.Name() + " is already registered").AtError() } typeCreatorRegistry[configType] = configCreator registry.RegisterImplementation(config, nil) return nil } // CreateObject creates an object by its config. The config type must be registered through RegisterConfig(). func CreateObject(ctx context.Context, config interface{}) (interface{}, error) { configType := reflect.TypeOf(config) creator, found := typeCreatorRegistry[configType] if !found { return nil, newError(configType.String() + " is not registered").AtError() } return creator(ctx, config) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/common.go
common/common.go
// Package common contains common utilities that are shared among other packages. // See each sub-package for detail. package common import ( "fmt" "go/build" "io" "net/http" "net/url" "os" "path/filepath" "strings" "time" "github.com/v2fly/v2ray-core/v5/common/errors" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen // ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route. var ErrNoClue = errors.New("not enough information for making a decision") // Must panics if err is not nil. func Must(err error) { if err != nil { panic(err) } } // Must2 panics if the second parameter is not nil, otherwise returns the first parameter. func Must2(v interface{}, err error) interface{} { Must(err) return v } // Error2 returns the err from the 2nd parameter. func Error2(v interface{}, err error) error { return err } // 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 } // GetGOPATH returns GOPATH environment variable as a string. It will NOT be empty. func GetGOPATH() string { // The one set by user explicitly by `export GOPATH=/path` or `env GOPATH=/path command` GOPATH := os.Getenv("GOPATH") if GOPATH == "" { var err error // The one set by user by running `go env -w GOPATH=/path` GOPATH, err = GetRuntimeEnv("GOPATH") if err != nil { // The default one that Golang uses return build.Default.GOPATH } if GOPATH == "" { return build.Default.GOPATH } return GOPATH } return GOPATH } // FetchHTTPContent dials http(s) for remote content func FetchHTTPContent(target string) ([]byte, error) { parsedTarget, err := url.Parse(target) if err != nil { return nil, newError("invalid URL: ", target).Base(err) } if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" { return nil, newError("invalid scheme: ", parsedTarget.Scheme) } client := &http.Client{ Timeout: 30 * time.Second, } resp, err := client.Do(&http.Request{ Method: "GET", URL: parsedTarget, Close: true, }) if err != nil { return nil, newError("failed to dial to ", target).Base(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, newError("unexpected HTTP status code: ", resp.StatusCode) } content, err := io.ReadAll(resp.Body) if err != nil { return nil, newError("failed to read HTTP response").Base(err) } return content, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/antireplay/bloomring.go
common/antireplay/bloomring.go
package antireplay import ( "sync" ss_bloomring "github.com/v2fly/ss-bloomring" ) type BloomRing struct { *ss_bloomring.BloomRing lock *sync.Mutex } func (b BloomRing) Interval() int64 { return 9999999 } func (b BloomRing) Check(sum []byte) bool { b.lock.Lock() defer b.lock.Unlock() if b.Test(sum) { return false } b.Add(sum) return true } func NewBloomRing() BloomRing { const ( DefaultSFCapacity = 1e6 // FalsePositiveRate DefaultSFFPR = 1e-6 DefaultSFSlot = 10 ) return BloomRing{ss_bloomring.NewBloomRing(DefaultSFSlot, DefaultSFCapacity, DefaultSFFPR), &sync.Mutex{}} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/antireplay/replayfilter.go
common/antireplay/replayfilter.go
package antireplay import ( "sync" "time" cuckoo "github.com/seiflotfy/cuckoofilter" ) const replayFilterCapacity = 100000 // ReplayFilter checks for replay attacks. type ReplayFilter struct { lock sync.Mutex poolA *cuckoo.Filter poolB *cuckoo.Filter poolSwap bool lastSwap int64 interval int64 } // NewReplayFilter creates a new filter with specifying the expiration time interval in seconds. func NewReplayFilter(interval int64) *ReplayFilter { filter := &ReplayFilter{} filter.interval = interval return filter } // Interval in second for expiration time for duplicate records. func (filter *ReplayFilter) Interval() int64 { return filter.interval } // Check determines if there are duplicate records. func (filter *ReplayFilter) Check(sum []byte) bool { filter.lock.Lock() defer filter.lock.Unlock() now := time.Now().Unix() if filter.lastSwap == 0 { filter.lastSwap = now filter.poolA = cuckoo.NewFilter(replayFilterCapacity) filter.poolB = cuckoo.NewFilter(replayFilterCapacity) } elapsed := now - filter.lastSwap if elapsed >= filter.Interval() { if filter.poolSwap { filter.poolA.Reset() } else { filter.poolB.Reset() } filter.poolSwap = !filter.poolSwap filter.lastSwap = now } return filter.poolA.InsertUnique(sum) && filter.poolB.InsertUnique(sum) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/antireplay/antireplay.go
common/antireplay/antireplay.go
package antireplay type GeneralizedReplayFilter interface { Interval() int64 Check(sum []byte) bool }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/bitmask/byte_test.go
common/bitmask/byte_test.go
package bitmask_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/bitmask" ) func TestBitmaskByte(t *testing.T) { b := Byte(0) b.Set(Byte(1)) if !b.Has(1) { t.Fatal("expected ", b, " to contain 1, but actually not") } b.Set(Byte(2)) if !b.Has(2) { t.Fatal("expected ", b, " to contain 2, but actually not") } if !b.Has(1) { t.Fatal("expected ", b, " to contain 1, but actually not") } b.Clear(Byte(1)) if !b.Has(2) { t.Fatal("expected ", b, " to contain 2, but actually not") } if b.Has(1) { t.Fatal("expected ", b, " to not contain 1, but actually did") } b.Toggle(Byte(2)) if b.Has(2) { t.Fatal("expected ", b, " to not contain 2, but actually did") } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/bitmask/byte.go
common/bitmask/byte.go
package bitmask // Byte is a bitmask in byte. type Byte byte // Has returns true if this bitmask contains another bitmask. func (b Byte) Has(bb Byte) bool { return (b & bb) != 0 } func (b *Byte) Set(bb Byte) { *b |= bb } func (b *Byte) Clear(bb Byte) { *b &= ^bb } func (b *Byte) Toggle(bb Byte) { *b ^= bb }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/cmdarg/errors.generated.go
common/cmdarg/errors.generated.go
package cmdarg 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/common/cmdarg/cmdarg.go
common/cmdarg/cmdarg.go
package cmdarg import "strings" // Arg is used by flag to accept multiple argument. type Arg []string func (c *Arg) String() string { return strings.Join([]string(*c), " ") } // Set is the method flag package calls func (c *Arg) Set(value string) error { *c = append(*c, value) return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/cmdarg/arg.go
common/cmdarg/arg.go
package cmdarg import ( "bytes" "io" "os" ) // LoadArg loads one arg, maybe an remote url, or local file path func LoadArg(arg string) (out io.Reader, err error) { bs, err := LoadArgToBytes(arg) if err != nil { return nil, err } out = bytes.NewBuffer(bs) return } // LoadArgToBytes loads one arg to []byte, maybe an remote url, or local file path func LoadArgToBytes(arg string) (out []byte, err error) { out, err = os.ReadFile(arg) if err != nil { return } return }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/cache/lru_test.go
common/cache/lru_test.go
package cache_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/cache" ) func TestLruReplaceValue(t *testing.T) { lru := NewLru(2) lru.Put(2, 6) lru.Put(1, 5) lru.Put(1, 2) v, _ := lru.Get(1) if v != 2 { t.Error("should get 2", v) } v, _ = lru.Get(2) if v != 6 { t.Error("should get 6", v) } } func TestLruRemoveOld(t *testing.T) { lru := NewLru(2) v, ok := lru.Get(2) if ok { t.Error("should get nil", v) } lru.Put(1, 1) lru.Put(2, 2) v, _ = lru.Get(1) if v != 1 { t.Error("should get 1", v) } lru.Put(3, 3) v, ok = lru.Get(2) if ok { t.Error("should get nil", v) } lru.Put(4, 4) v, ok = lru.Get(1) if ok { t.Error("should get nil", v) } v, _ = lru.Get(3) if v != 3 { t.Error("should get 3", v) } v, _ = lru.Get(4) if v != 4 { t.Error("should get 4", v) } } func TestGetKeyFromValue(t *testing.T) { lru := NewLru(2) lru.Put(3, 3) lru.Put(2, 2) lru.Put(1, 1) v, ok := lru.GetKeyFromValue(3) if ok { t.Error("should get nil", v) } v, _ = lru.GetKeyFromValue(2) if v != 2 { t.Error("should get 2", v) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/cache/lru.go
common/cache/lru.go
package cache import ( "container/list" "sync" ) // Lru simple, fast lru cache implementation type Lru interface { Get(key interface{}) (value interface{}, ok bool) GetKeyFromValue(value interface{}) (key interface{}, ok bool) Put(key, value interface{}) } type lru struct { capacity int doubleLinkedlist *list.List keyToElement *sync.Map valueToElement *sync.Map mu *sync.Mutex } type lruElement struct { key interface{} value interface{} } // NewLru initializes a lru cache func NewLru(cap int) Lru { return &lru{ capacity: cap, doubleLinkedlist: list.New(), keyToElement: new(sync.Map), valueToElement: new(sync.Map), mu: new(sync.Mutex), } } func (l *lru) Get(key interface{}) (value interface{}, ok bool) { l.mu.Lock() defer l.mu.Unlock() if v, ok := l.keyToElement.Load(key); ok { element := v.(*list.Element) l.doubleLinkedlist.MoveToFront(element) return element.Value.(*lruElement).value, true } return nil, false } func (l *lru) GetKeyFromValue(value interface{}) (key interface{}, ok bool) { l.mu.Lock() defer l.mu.Unlock() if k, ok := l.valueToElement.Load(value); ok { element := k.(*list.Element) l.doubleLinkedlist.MoveToFront(element) return element.Value.(*lruElement).key, true } return nil, false } func (l *lru) Put(key, value interface{}) { l.mu.Lock() e := &lruElement{key, value} if v, ok := l.keyToElement.Load(key); ok { element := v.(*list.Element) element.Value = e l.doubleLinkedlist.MoveToFront(element) } else { element := l.doubleLinkedlist.PushFront(e) l.keyToElement.Store(key, element) l.valueToElement.Store(value, element) if l.doubleLinkedlist.Len() > l.capacity { toBeRemove := l.doubleLinkedlist.Back() l.doubleLinkedlist.Remove(toBeRemove) l.keyToElement.Delete(toBeRemove.Value.(*lruElement).key) l.valueToElement.Delete(toBeRemove.Value.(*lruElement).value) } } l.mu.Unlock() }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/units/bytesize.go
common/units/bytesize.go
package units import ( "errors" "strconv" "strings" "unicode" ) var ( errInvalidSize = errors.New("invalid size") errInvalidUnit = errors.New("invalid or unsupported unit") ) // ByteSize is the size of bytes type ByteSize uint64 const ( _ = iota // KB = 1KB KB ByteSize = 1 << (10 * iota) // MB = 1MB MB // GB = 1GB GB // TB = 1TB TB // PB = 1PB PB // EB = 1EB EB ) func (b ByteSize) String() string { unit := "" value := float64(0) switch { case b == 0: return "0" case b < KB: unit = "B" value = float64(b) case b < MB: unit = "KB" value = float64(b) / float64(KB) case b < GB: unit = "MB" value = float64(b) / float64(MB) case b < TB: unit = "GB" value = float64(b) / float64(GB) case b < PB: unit = "TB" value = float64(b) / float64(TB) case b < EB: unit = "PB" value = float64(b) / float64(PB) default: unit = "EB" value = float64(b) / float64(EB) } result := strconv.FormatFloat(value, 'f', 2, 64) result = strings.TrimSuffix(result, ".0") return result + unit } // Parse parses ByteSize from string func (b *ByteSize) Parse(s string) error { s = strings.TrimSpace(s) s = strings.ToUpper(s) i := strings.IndexFunc(s, unicode.IsLetter) if i == -1 { return errInvalidUnit } bytesString, multiple := s[:i], s[i:] bytes, err := strconv.ParseFloat(bytesString, 64) if err != nil || bytes <= 0 { return errInvalidSize } switch multiple { case "B": *b = ByteSize(bytes) case "K", "KB", "KIB": *b = ByteSize(bytes * float64(KB)) case "M", "MB", "MIB": *b = ByteSize(bytes * float64(MB)) case "G", "GB", "GIB": *b = ByteSize(bytes * float64(GB)) case "T", "TB", "TIB": *b = ByteSize(bytes * float64(TB)) case "P", "PB", "PIB": *b = ByteSize(bytes * float64(PB)) case "E", "EB", "EIB": *b = ByteSize(bytes * float64(EB)) default: return errInvalidUnit } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/units/bytesize_test.go
common/units/bytesize_test.go
package units_test import ( "testing" "github.com/v2fly/v2ray-core/v5/common/units" ) func TestByteSizes(t *testing.T) { size := units.ByteSize(0) assertSizeString(t, size, "0") size++ assertSizeValue(t, assertSizeString(t, size, "1.00B"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00KB"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00MB"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00GB"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00TB"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00PB"), size, ) size <<= 10 assertSizeValue(t, assertSizeString(t, size, "1.00EB"), size, ) } func assertSizeValue(t *testing.T, size string, expected units.ByteSize) { actual := units.ByteSize(0) err := actual.Parse(size) if err != nil { t.Error(err) } if actual != expected { t.Errorf("expect %s, but got %s", expected, actual) } } func assertSizeString(t *testing.T, size units.ByteSize, expected string) string { actual := size.String() if actual != expected { t.Errorf("expect %s, but got %s", expected, actual) } return expected }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/errors/errors_test.go
common/errors/errors_test.go
package errors_test import ( "io" "strings" "testing" "github.com/google/go-cmp/cmp" . "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/log" ) func TestError(t *testing.T) { err := New("TestError") if v := GetSeverity(err); v != log.Severity_Info { t.Error("severity: ", v) } err = New("TestError2").Base(io.EOF) if v := GetSeverity(err); v != log.Severity_Info { t.Error("severity: ", v) } err = New("TestError3").Base(io.EOF).AtWarning() if v := GetSeverity(err); v != log.Severity_Warning { t.Error("severity: ", v) } err = New("TestError4").Base(io.EOF).AtWarning() err = New("TestError5").Base(err) if v := GetSeverity(err); v != log.Severity_Warning { t.Error("severity: ", v) } if v := err.Error(); !strings.Contains(v, "EOF") { t.Error("error: ", v) } } type e struct{} func TestErrorMessage(t *testing.T) { data := []struct { err error msg string }{ { err: New("a").Base(New("b")).WithPathObj(e{}), msg: "common/errors_test: a > b", }, { err: New("a").Base(New("b").WithPathObj(e{})), msg: "a > common/errors_test: b", }, } for _, d := range data { if diff := cmp.Diff(d.msg, d.err.Error()); diff != "" { t.Error(diff) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/errors/multi_error.go
common/errors/multi_error.go
package errors import ( "strings" ) type multiError []error func (e multiError) Error() string { var r strings.Builder r.WriteString("multierr: ") for _, err := range e { r.WriteString(err.Error()) r.WriteString(" | ") } return r.String() } func Combine(maybeError ...error) error { var errs multiError for _, err := range maybeError { if err != nil { errs = append(errs, err) } } if len(errs) == 0 { return nil } return errs }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/errors/errors.go
common/errors/errors.go
// Package errors is a drop-in replacement for Golang lib 'errors'. package errors import ( "os" "reflect" "strings" "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/common/serial" ) type hasInnerError interface { // Inner returns the underlying error of this one. Inner() error } type hasSeverity interface { Severity() log.Severity } // Error is an error object with underlying error. type Error struct { pathObj interface{} prefix []interface{} message []interface{} inner error severity log.Severity } func (err *Error) WithPathObj(obj interface{}) *Error { err.pathObj = obj return err } func (err *Error) pkgPath() string { if err.pathObj == nil { return "" } path := reflect.TypeOf(err.pathObj).PkgPath() // TODO update required on release path = strings.TrimPrefix(path, "github.com/v2fly/v2ray-core/v5/") path = strings.TrimPrefix(path, "github.com/v2fly/v2ray-core/v5") return path } // Error implements error.Error(). func (err *Error) Error() string { builder := strings.Builder{} for _, prefix := range err.prefix { builder.WriteByte('[') builder.WriteString(serial.ToString(prefix)) builder.WriteString("] ") } path := err.pkgPath() if len(path) > 0 { builder.WriteString(path) builder.WriteString(": ") } msg := serial.Concat(err.message...) builder.WriteString(msg) if err.inner != nil { builder.WriteString(" > ") builder.WriteString(err.inner.Error()) } return builder.String() } // Inner implements hasInnerError.Inner() func (err *Error) Inner() error { if err.inner == nil { return nil } return err.inner } func (err *Error) Base(e error) *Error { err.inner = e return err } func (err *Error) atSeverity(s log.Severity) *Error { err.severity = s return err } func (err *Error) Severity() log.Severity { if err.inner == nil { return err.severity } if s, ok := err.inner.(hasSeverity); ok { as := s.Severity() if as < err.severity { return as } } return err.severity } // AtDebug sets the severity to debug. func (err *Error) AtDebug() *Error { return err.atSeverity(log.Severity_Debug) } // AtInfo sets the severity to info. func (err *Error) AtInfo() *Error { return err.atSeverity(log.Severity_Info) } // AtWarning sets the severity to warning. func (err *Error) AtWarning() *Error { return err.atSeverity(log.Severity_Warning) } // AtError sets the severity to error. func (err *Error) AtError() *Error { return err.atSeverity(log.Severity_Error) } // String returns the string representation of this error. func (err *Error) String() string { return err.Error() } // WriteToLog writes current error into log. func (err *Error) WriteToLog(opts ...ExportOption) { var holder ExportOptionHolder for _, opt := range opts { opt(&holder) } if holder.SessionID > 0 { err.prefix = append(err.prefix, holder.SessionID) } log.Record(&log.GeneralMessage{ Severity: GetSeverity(err), Content: err, }) } type ExportOptionHolder struct { SessionID uint32 } type ExportOption func(*ExportOptionHolder) // New returns a new error object with message formed from given arguments. func New(msg ...interface{}) *Error { return &Error{ message: msg, severity: log.Severity_Info, } } // Cause returns the root cause of this error. func Cause(err error) error { if err == nil { return nil } L: for { switch inner := err.(type) { case hasInnerError: if inner.Inner() == nil { break L } err = inner.Inner() case *os.PathError: if inner.Err == nil { break L } err = inner.Err case *os.SyscallError: if inner.Err == nil { break L } err = inner.Err default: break L } } return err } // GetSeverity returns the actual severity of the error, including inner errors. func GetSeverity(err error) log.Severity { if s, ok := err.(hasSeverity); ok { return s.Severity() } return log.Severity_Info }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/errors/errorgen/main.go
common/errors/errorgen/main.go
package main import ( "fmt" "os" "path/filepath" ) func main() { pwd, err := os.Getwd() if err != nil { fmt.Println("can not get current working directory") os.Exit(1) } pkg := filepath.Base(pwd) if pkg == "v2ray-core" { pkg = "core" } file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644) if err != nil { fmt.Printf("Failed to generate errors.generated.go: %v", err) os.Exit(1) } defer file.Close() fmt.Fprintf(file, `package %s import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) } `, pkg) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/buf/writer_test.go
common/buf/writer_test.go
package buf_test import ( "bufio" "bytes" "crypto/rand" "io" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/transport/pipe" ) func TestWriter(t *testing.T) { lb := New() common.Must2(lb.ReadFrom(rand.Reader)) expectedBytes := append([]byte(nil), lb.Bytes()...) writeBuffer := bytes.NewBuffer(make([]byte, 0, 1024*1024)) writer := NewBufferedWriter(NewWriter(writeBuffer)) writer.SetBuffered(false) common.Must(writer.WriteMultiBuffer(MultiBuffer{lb})) common.Must(writer.Flush()) if r := cmp.Diff(expectedBytes, writeBuffer.Bytes()); r != "" { t.Error(r) } } func TestBytesWriterReadFrom(t *testing.T) { const size = 50000 pReader, pWriter := pipe.New(pipe.WithSizeLimit(size)) reader := bufio.NewReader(io.LimitReader(rand.Reader, size)) writer := NewBufferedWriter(pWriter) writer.SetBuffered(false) nBytes, err := reader.WriteTo(writer) if nBytes != size { t.Fatal("unexpected size of bytes written: ", nBytes) } if err != nil { t.Fatal("expect success, but actually error: ", err.Error()) } mb, err := pReader.ReadMultiBuffer() common.Must(err) if mb.Len() != size { t.Fatal("unexpected size read: ", mb.Len()) } } func TestDiscardBytes(t *testing.T) { b := New() common.Must2(b.ReadFullFrom(rand.Reader, Size)) nBytes, err := io.Copy(DiscardBytes, b) common.Must(err) if nBytes != Size { t.Error("copy size: ", nBytes) } } func TestDiscardBytesMultiBuffer(t *testing.T) { const size = 10240*1024 + 1 buffer := bytes.NewBuffer(make([]byte, 0, size)) common.Must2(buffer.ReadFrom(io.LimitReader(rand.Reader, size))) r := NewReader(buffer) nBytes, err := io.Copy(DiscardBytes, &BufferedReader{Reader: r}) common.Must(err) if nBytes != size { t.Error("copy size: ", nBytes) } } func TestWriterInterface(t *testing.T) { { var writer interface{} = (*BufferToBytesWriter)(nil) switch writer.(type) { case Writer, io.Writer, io.ReaderFrom: default: t.Error("BufferToBytesWriter is not Writer, io.Writer or io.ReaderFrom") } } { var writer interface{} = (*BufferedWriter)(nil) switch writer.(type) { case Writer, io.Writer, io.ReaderFrom, io.ByteWriter: default: t.Error("BufferedWriter is not Writer, io.Writer, io.ReaderFrom or io.ByteWriter") } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/buf/readv_posix.go
common/buf/readv_posix.go
//go:build !windows && !wasm && !illumos // +build !windows,!wasm,!illumos package buf import ( "syscall" "unsafe" ) type posixReader struct { iovecs []syscall.Iovec } func (r *posixReader) Init(bs []*Buffer) { iovecs := r.iovecs if iovecs == nil { iovecs = make([]syscall.Iovec, 0, len(bs)) } for idx, b := range bs { iovecs = append(iovecs, syscall.Iovec{ Base: &(b.v[0]), }) iovecs[idx].SetLen(int(Size)) } r.iovecs = iovecs } func (r *posixReader) Read(fd uintptr) int32 { n, _, e := syscall.Syscall(syscall.SYS_READV, fd, uintptr(unsafe.Pointer(&r.iovecs[0])), uintptr(len(r.iovecs))) if e != 0 { return -1 } return int32(n) } func (r *posixReader) Clear() { for idx := range r.iovecs { r.iovecs[idx].Base = nil } r.iovecs = r.iovecs[:0] } func newMultiReader() multiReader { return &posixReader{} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/buf/readv_windows.go
common/buf/readv_windows.go
package buf import ( "syscall" ) type windowsReader struct { bufs []syscall.WSABuf } func (r *windowsReader) Init(bs []*Buffer) { if r.bufs == nil { r.bufs = make([]syscall.WSABuf, 0, len(bs)) } for _, b := range bs { r.bufs = append(r.bufs, syscall.WSABuf{Len: uint32(Size), Buf: &b.v[0]}) } } func (r *windowsReader) Clear() { for idx := range r.bufs { r.bufs[idx].Buf = nil } r.bufs = r.bufs[:0] } func (r *windowsReader) Read(fd uintptr) int32 { var nBytes uint32 var flags uint32 err := syscall.WSARecv(syscall.Handle(fd), &r.bufs[0], uint32(len(r.bufs)), &nBytes, &flags, nil, nil) if err != nil { return -1 } return int32(nBytes) } func newMultiReader() multiReader { return new(windowsReader) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false