repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/mtproto_test.go | infra/conf/mtproto_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/mtproto"
)
func TestMTProtoServerConfig(t *testing.T) {
creator := func() Buildable {
return new(MTProtoServerConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"users": [{
"email": "love@v2ray.com",
"level": 1,
"secret": "b0cbcef5a486d9636472ac27f8e11a9d"
}]
}`,
Parser: loadJSON(creator),
Output: &mtproto.ServerConfig{
User: []*protocol.User{
{
Email: "love@v2ray.com",
Level: 1,
Account: serial.ToTypedMessage(&mtproto.Account{
Secret: []byte{176, 203, 206, 245, 164, 134, 217, 99, 100, 114, 172, 39, 248, 225, 26, 157},
}),
},
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/errors.generated.go | infra/conf/errors.generated.go | package conf
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/vless_test.go | infra/conf/vless_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/vless"
"v2ray.com/core/proxy/vless/inbound"
"v2ray.com/core/proxy/vless/outbound"
)
func TestVLessOutbound(t *testing.T) {
creator := func() Buildable {
return new(VLessOutboundConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "example.com",
"port": 443,
"users": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"flow": "xtls-rprx-origin-udp443",
"encryption": "none",
"level": 0
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Vnext: []*protocol.ServerEndpoint{
{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Domain{
Domain: "example.com",
},
},
Port: 443,
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vless.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
Flow: "xtls-rprx-origin-udp443",
Encryption: "none",
}),
Level: 0,
},
},
},
},
},
},
})
}
func TestVLessInbound(t *testing.T) {
creator := func() Buildable {
return new(VLessInboundConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"clients": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"flow": "xtls-rprx-origin",
"level": 0,
"email": "love@v2fly.org"
}
],
"decryption": "none",
"fallbacks": [
{
"dest": 80
},
{
"alpn": "h2",
"dest": "@/dev/shm/domain.socket",
"xver": 2
},
{
"path": "/innerws",
"dest": "serve-ws-none"
}
]
}`,
Parser: loadJSON(creator),
Output: &inbound.Config{
Clients: []*protocol.User{
{
Account: serial.ToTypedMessage(&vless.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
Flow: "xtls-rprx-origin",
}),
Level: 0,
Email: "love@v2fly.org",
},
},
Decryption: "none",
Fallbacks: []*inbound.Fallback{
{
Alpn: "",
Path: "",
Type: "tcp",
Dest: "127.0.0.1:80",
Xver: 0,
},
{
Alpn: "h2",
Path: "",
Type: "unix",
Dest: "@/dev/shm/domain.socket",
Xver: 2,
},
{
Alpn: "",
Path: "/innerws",
Type: "serve",
Dest: "serve-ws-none",
Xver: 0,
},
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/buildable.go | infra/conf/buildable.go | package conf
import "github.com/golang/protobuf/proto"
type Buildable interface {
Build() (proto.Message, error)
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/transport_test.go | infra/conf/transport_test.go | package conf_test
import (
"encoding/json"
"testing"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/transport"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/headers/http"
"v2ray.com/core/transport/internet/headers/noop"
"v2ray.com/core/transport/internet/headers/tls"
"v2ray.com/core/transport/internet/kcp"
"v2ray.com/core/transport/internet/quic"
"v2ray.com/core/transport/internet/tcp"
"v2ray.com/core/transport/internet/websocket"
)
func TestSocketConfig(t *testing.T) {
createParser := func() func(string) (proto.Message, error) {
return func(s string) (proto.Message, error) {
config := new(SocketConfig)
if err := json.Unmarshal([]byte(s), config); err != nil {
return nil, err
}
return config.Build()
}
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"mark": 1,
"tcpFastOpen": true
}`,
Parser: createParser(),
Output: &internet.SocketConfig{
Mark: 1,
Tfo: internet.SocketConfig_Enable,
},
},
})
}
func TestTransportConfig(t *testing.T) {
createParser := func() func(string) (proto.Message, error) {
return func(s string) (proto.Message, error) {
config := new(TransportConfig)
if err := json.Unmarshal([]byte(s), config); err != nil {
return nil, err
}
return config.Build()
}
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"tcpSettings": {
"header": {
"type": "http",
"request": {
"version": "1.1",
"method": "GET",
"path": "/b",
"headers": {
"a": "b",
"c": "d"
}
},
"response": {
"version": "1.0",
"status": "404",
"reason": "Not Found"
}
}
},
"kcpSettings": {
"mtu": 1200,
"header": {
"type": "none"
}
},
"wsSettings": {
"path": "/t"
},
"quicSettings": {
"key": "abcd",
"header": {
"type": "dtls"
}
}
}`,
Parser: createParser(),
Output: &transport.Config{
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "tcp",
Settings: serial.ToTypedMessage(&tcp.Config{
HeaderSettings: serial.ToTypedMessage(&http.Config{
Request: &http.RequestConfig{
Version: &http.Version{Value: "1.1"},
Method: &http.Method{Value: "GET"},
Uri: []string{"/b"},
Header: []*http.Header{
{Name: "a", Value: []string{"b"}},
{Name: "c", Value: []string{"d"}},
},
},
Response: &http.ResponseConfig{
Version: &http.Version{Value: "1.0"},
Status: &http.Status{Code: "404", Reason: "Not Found"},
Header: []*http.Header{
{
Name: "Content-Type",
Value: []string{"application/octet-stream", "video/mpeg"},
},
{
Name: "Transfer-Encoding",
Value: []string{"chunked"},
},
{
Name: "Connection",
Value: []string{"keep-alive"},
},
{
Name: "Pragma",
Value: []string{"no-cache"},
},
{
Name: "Cache-Control",
Value: []string{"private", "no-cache"},
},
},
},
}),
}),
},
{
ProtocolName: "mkcp",
Settings: serial.ToTypedMessage(&kcp.Config{
Mtu: &kcp.MTU{Value: 1200},
HeaderConfig: serial.ToTypedMessage(&noop.Config{}),
}),
},
{
ProtocolName: "websocket",
Settings: serial.ToTypedMessage(&websocket.Config{
Path: "/t",
}),
},
{
ProtocolName: "quic",
Settings: serial.ToTypedMessage(&quic.Config{
Key: "abcd",
Security: &protocol.SecurityConfig{
Type: protocol.SecurityType_NONE,
},
Header: serial.ToTypedMessage(&tls.PacketConfig{}),
}),
},
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/shadowsocks.go | infra/conf/shadowsocks.go | package conf
import (
"strings"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/shadowsocks"
)
func cipherFromString(c string) shadowsocks.CipherType {
switch strings.ToLower(c) {
case "aes-256-cfb":
return shadowsocks.CipherType_AES_256_CFB
case "aes-128-cfb":
return shadowsocks.CipherType_AES_128_CFB
case "chacha20":
return shadowsocks.CipherType_CHACHA20
case "chacha20-ietf":
return shadowsocks.CipherType_CHACHA20_IETF
case "aes-128-gcm", "aead_aes_128_gcm":
return shadowsocks.CipherType_AES_128_GCM
case "aes-256-gcm", "aead_aes_256_gcm":
return shadowsocks.CipherType_AES_256_GCM
case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
return shadowsocks.CipherType_CHACHA20_POLY1305
case "none", "plain":
return shadowsocks.CipherType_NONE
default:
return shadowsocks.CipherType_UNKNOWN
}
}
type ShadowsocksServerConfig struct {
Cipher string `json:"method"`
Password string `json:"password"`
UDP bool `json:"udp"`
Level byte `json:"level"`
Email string `json:"email"`
NetworkList *NetworkList `json:"network"`
}
func (v *ShadowsocksServerConfig) Build() (proto.Message, error) {
config := new(shadowsocks.ServerConfig)
config.UdpEnabled = v.UDP
config.Network = v.NetworkList.Build()
if v.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
}
account := &shadowsocks.Account{
Password: v.Password,
}
account.CipherType = cipherFromString(v.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, newError("unknown cipher method: ", v.Cipher)
}
config.User = &protocol.User{
Email: v.Email,
Level: uint32(v.Level),
Account: serial.ToTypedMessage(account),
}
return config, nil
}
type ShadowsocksServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Cipher string `json:"method"`
Password string `json:"password"`
Email string `json:"email"`
Ota bool `json:"ota"`
Level byte `json:"level"`
}
type ShadowsocksClientConfig struct {
Servers []*ShadowsocksServerTarget `json:"servers"`
}
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
config := new(shadowsocks.ClientConfig)
if len(v.Servers) == 0 {
return nil, newError("0 Shadowsocks server configured.")
}
serverSpecs := make([]*protocol.ServerEndpoint, len(v.Servers))
for idx, server := range v.Servers {
if server.Address == nil {
return nil, newError("Shadowsocks server address is not set.")
}
if server.Port == 0 {
return nil, newError("Invalid Shadowsocks port.")
}
if server.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
}
account := &shadowsocks.Account{
Password: server.Password,
}
account.CipherType = cipherFromString(server.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, newError("unknown cipher method: ", server.Cipher)
}
ss := &protocol.ServerEndpoint{
Address: server.Address.Build(),
Port: uint32(server.Port),
User: []*protocol.User{
{
Level: uint32(server.Level),
Email: server.Email,
Account: serial.ToTypedMessage(account),
},
},
}
serverSpecs[idx] = ss
}
config.Server = serverSpecs
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/transport_internet.go | infra/conf/transport_internet.go | package conf
import (
"encoding/json"
"strings"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/platform/filesystem"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/domainsocket"
"v2ray.com/core/transport/internet/http"
"v2ray.com/core/transport/internet/kcp"
"v2ray.com/core/transport/internet/quic"
"v2ray.com/core/transport/internet/tcp"
"v2ray.com/core/transport/internet/tls"
"v2ray.com/core/transport/internet/websocket"
"v2ray.com/core/transport/internet/xtls"
)
var (
kcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
"none": func() interface{} { return new(NoOpAuthenticator) },
"srtp": func() interface{} { return new(SRTPAuthenticator) },
"utp": func() interface{} { return new(UTPAuthenticator) },
"wechat-video": func() interface{} { return new(WechatVideoAuthenticator) },
"dtls": func() interface{} { return new(DTLSAuthenticator) },
"wireguard": func() interface{} { return new(WireguardAuthenticator) },
}, "type", "")
tcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
"none": func() interface{} { return new(NoOpConnectionAuthenticator) },
"http": func() interface{} { return new(HTTPAuthenticator) },
}, "type", "")
)
type KCPConfig struct {
Mtu *uint32 `json:"mtu"`
Tti *uint32 `json:"tti"`
UpCap *uint32 `json:"uplinkCapacity"`
DownCap *uint32 `json:"downlinkCapacity"`
Congestion *bool `json:"congestion"`
ReadBufferSize *uint32 `json:"readBufferSize"`
WriteBufferSize *uint32 `json:"writeBufferSize"`
HeaderConfig json.RawMessage `json:"header"`
Seed *string `json:"seed"`
}
// Build implements Buildable.
func (c *KCPConfig) Build() (proto.Message, error) {
config := new(kcp.Config)
if c.Mtu != nil {
mtu := *c.Mtu
if mtu < 576 || mtu > 1460 {
return nil, newError("invalid mKCP MTU size: ", mtu).AtError()
}
config.Mtu = &kcp.MTU{Value: mtu}
}
if c.Tti != nil {
tti := *c.Tti
if tti < 10 || tti > 100 {
return nil, newError("invalid mKCP TTI: ", tti).AtError()
}
config.Tti = &kcp.TTI{Value: tti}
}
if c.UpCap != nil {
config.UplinkCapacity = &kcp.UplinkCapacity{Value: *c.UpCap}
}
if c.DownCap != nil {
config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *c.DownCap}
}
if c.Congestion != nil {
config.Congestion = *c.Congestion
}
if c.ReadBufferSize != nil {
size := *c.ReadBufferSize
if size > 0 {
config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024}
} else {
config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024}
}
}
if c.WriteBufferSize != nil {
size := *c.WriteBufferSize
if size > 0 {
config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024}
} else {
config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024}
}
}
if len(c.HeaderConfig) > 0 {
headerConfig, _, err := kcpHeaderLoader.Load(c.HeaderConfig)
if err != nil {
return nil, newError("invalid mKCP header config.").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid mKCP header config").Base(err).AtError()
}
config.HeaderConfig = serial.ToTypedMessage(ts)
}
if c.Seed != nil {
config.Seed = &kcp.EncryptionSeed{Seed: *c.Seed}
}
return config, nil
}
type TCPConfig struct {
HeaderConfig json.RawMessage `json:"header"`
AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
}
// Build implements Buildable.
func (c *TCPConfig) Build() (proto.Message, error) {
config := new(tcp.Config)
if len(c.HeaderConfig) > 0 {
headerConfig, _, err := tcpHeaderLoader.Load(c.HeaderConfig)
if err != nil {
return nil, newError("invalid TCP header config").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid TCP header config").Base(err).AtError()
}
config.HeaderSettings = serial.ToTypedMessage(ts)
}
if c.AcceptProxyProtocol {
config.AcceptProxyProtocol = c.AcceptProxyProtocol
}
return config, nil
}
type WebSocketConfig struct {
Path string `json:"path"`
Path2 string `json:"Path"` // The key was misspelled. For backward compatibility, we have to keep track the old key.
Headers map[string]string `json:"headers"`
AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
}
// Build implements Buildable.
func (c *WebSocketConfig) Build() (proto.Message, error) {
path := c.Path
if path == "" && c.Path2 != "" {
path = c.Path2
}
header := make([]*websocket.Header, 0, 32)
for key, value := range c.Headers {
header = append(header, &websocket.Header{
Key: key,
Value: value,
})
}
config := &websocket.Config{
Path: path,
Header: header,
}
if c.AcceptProxyProtocol {
config.AcceptProxyProtocol = c.AcceptProxyProtocol
}
return config, nil
}
type HTTPConfig struct {
Host *StringList `json:"host"`
Path string `json:"path"`
}
// Build implements Buildable.
func (c *HTTPConfig) Build() (proto.Message, error) {
config := &http.Config{
Path: c.Path,
}
if c.Host != nil {
config.Host = []string(*c.Host)
}
return config, nil
}
type QUICConfig struct {
Header json.RawMessage `json:"header"`
Security string `json:"security"`
Key string `json:"key"`
}
// Build implements Buildable.
func (c *QUICConfig) Build() (proto.Message, error) {
config := &quic.Config{
Key: c.Key,
}
if len(c.Header) > 0 {
headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
if err != nil {
return nil, newError("invalid QUIC header config.").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid QUIC header config").Base(err).AtError()
}
config.Header = serial.ToTypedMessage(ts)
}
var st protocol.SecurityType
switch strings.ToLower(c.Security) {
case "aes-128-gcm":
st = protocol.SecurityType_AES128_GCM
case "chacha20-poly1305":
st = protocol.SecurityType_CHACHA20_POLY1305
default:
st = protocol.SecurityType_NONE
}
config.Security = &protocol.SecurityConfig{
Type: st,
}
return config, nil
}
type DomainSocketConfig struct {
Path string `json:"path"`
Abstract bool `json:"abstract"`
Padding bool `json:"padding"`
AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
}
// Build implements Buildable.
func (c *DomainSocketConfig) Build() (proto.Message, error) {
return &domainsocket.Config{
Path: c.Path,
Abstract: c.Abstract,
Padding: c.Padding,
AcceptProxyProtocol: c.AcceptProxyProtocol,
}, 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.")
}
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 "issue":
certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
default:
certificate.Usage = tls.Certificate_ENCIPHERMENT
}
return certificate, nil
}
type TLSConfig struct {
Insecure bool `json:"allowInsecure"`
InsecureCiphers bool `json:"allowInsecureCiphers"`
Certs []*TLSCertConfig `json:"certificates"`
ServerName string `json:"serverName"`
ALPN *StringList `json:"alpn"`
DisableSessionResumption bool `json:"disableSessionResumption"`
DisableSystemRoot bool `json:"disableSystemRoot"`
}
// 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.AllowInsecureCiphers = c.InsecureCiphers
if len(c.ServerName) > 0 {
config.ServerName = serverName
}
if c.ALPN != nil && len(*c.ALPN) > 0 {
config.NextProtocol = []string(*c.ALPN)
}
config.DisableSessionResumption = c.DisableSessionResumption
config.DisableSystemRoot = c.DisableSystemRoot
return config, nil
}
type XTLSCertConfig 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 *XTLSCertConfig) Build() (*xtls.Certificate, error) {
certificate := new(xtls.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 = xtls.Certificate_ENCIPHERMENT
case "verify":
certificate.Usage = xtls.Certificate_AUTHORITY_VERIFY
case "issue":
certificate.Usage = xtls.Certificate_AUTHORITY_ISSUE
default:
certificate.Usage = xtls.Certificate_ENCIPHERMENT
}
return certificate, nil
}
type XTLSConfig struct {
Insecure bool `json:"allowInsecure"`
InsecureCiphers bool `json:"allowInsecureCiphers"`
Certs []*XTLSCertConfig `json:"certificates"`
ServerName string `json:"serverName"`
ALPN *StringList `json:"alpn"`
DisableSessionResumption bool `json:"disableSessionResumption"`
DisableSystemRoot bool `json:"disableSystemRoot"`
}
// Build implements Buildable.
func (c *XTLSConfig) Build() (proto.Message, error) {
config := new(xtls.Config)
config.Certificate = make([]*xtls.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.AllowInsecureCiphers = c.InsecureCiphers
if len(c.ServerName) > 0 {
config.ServerName = serverName
}
if c.ALPN != nil && len(*c.ALPN) > 0 {
config.NextProtocol = []string(*c.ALPN)
}
config.DisableSessionResumption = c.DisableSessionResumption
config.DisableSystemRoot = c.DisableSystemRoot
return config, nil
}
type TransportProtocol string
// Build implements Buildable.
func (p TransportProtocol) Build() (string, error) {
switch strings.ToLower(string(p)) {
case "tcp":
return "tcp", nil
case "kcp", "mkcp":
return "mkcp", nil
case "ws", "websocket":
return "websocket", nil
case "h2", "http":
return "http", nil
case "ds", "domainsocket":
return "domainsocket", nil
case "quic":
return "quic", nil
default:
return "", newError("Config: unknown transport protocol: ", p)
}
}
type SocketConfig struct {
Mark int32 `json:"mark"`
TFO *bool `json:"tcpFastOpen"`
TProxy string `json:"tproxy"`
}
// 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
}
}
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
}
return &internet.SocketConfig{
Mark: c.Mark,
Tfo: tfoSettings,
Tproxy: tproxy,
}, nil
}
type StreamConfig struct {
Network *TransportProtocol `json:"network"`
Security string `json:"security"`
TLSSettings *TLSConfig `json:"tlsSettings"`
XTLSSettings *XTLSConfig `json:"xtlsSettings"`
TCPSettings *TCPConfig `json:"tcpSettings"`
KCPSettings *KCPConfig `json:"kcpSettings"`
WSSettings *WebSocketConfig `json:"wsSettings"`
HTTPSettings *HTTPConfig `json:"httpSettings"`
DSSettings *DomainSocketConfig `json:"dsSettings"`
QUICSettings *QUICConfig `json:"quicSettings"`
SocketSettings *SocketConfig `json:"sockopt"`
}
// Build implements Buildable.
func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
config := &internet.StreamConfig{
ProtocolName: "tcp",
}
if c.Network != nil {
protocol, err := (*c.Network).Build()
if err != nil {
return nil, err
}
config.ProtocolName = protocol
}
if strings.EqualFold(c.Security, "tls") {
tlsSettings := c.TLSSettings
if tlsSettings == nil {
if c.XTLSSettings != nil {
return nil, newError(`TLS: Please use "tlsSettings" instead of "xtlsSettings".`)
}
tlsSettings = &TLSConfig{}
}
ts, err := tlsSettings.Build()
if err != nil {
return nil, newError("Failed to build TLS config.").Base(err)
}
tm := serial.ToTypedMessage(ts)
config.SecuritySettings = append(config.SecuritySettings, tm)
config.SecurityType = tm.Type
}
if strings.EqualFold(c.Security, "xtls") {
if config.ProtocolName != "tcp" && config.ProtocolName != "mkcp" && config.ProtocolName != "domainsocket" {
return nil, newError("XTLS only supports TCP, mKCP and DomainSocket for now.")
}
xtlsSettings := c.XTLSSettings
if xtlsSettings == nil {
if c.TLSSettings != nil {
return nil, newError(`XTLS: Please use "xtlsSettings" instead of "tlsSettings".`)
}
xtlsSettings = &XTLSConfig{}
}
ts, err := xtlsSettings.Build()
if err != nil {
return nil, newError("Failed to build XTLS config.").Base(err)
}
tm := serial.ToTypedMessage(ts)
config.SecuritySettings = append(config.SecuritySettings, tm)
config.SecurityType = tm.Type
}
if c.TCPSettings != nil {
ts, err := c.TCPSettings.Build()
if err != nil {
return nil, newError("Failed to build TCP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "tcp",
Settings: serial.ToTypedMessage(ts),
})
}
if c.KCPSettings != nil {
ts, err := c.KCPSettings.Build()
if err != nil {
return nil, newError("Failed to build mKCP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "mkcp",
Settings: serial.ToTypedMessage(ts),
})
}
if c.WSSettings != nil {
ts, err := c.WSSettings.Build()
if err != nil {
return nil, newError("Failed to build WebSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "websocket",
Settings: serial.ToTypedMessage(ts),
})
}
if c.HTTPSettings != nil {
ts, err := c.HTTPSettings.Build()
if err != nil {
return nil, newError("Failed to build HTTP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "http",
Settings: serial.ToTypedMessage(ts),
})
}
if c.DSSettings != nil {
ds, err := c.DSSettings.Build()
if err != nil {
return nil, newError("Failed to build DomainSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "domainsocket",
Settings: serial.ToTypedMessage(ds),
})
}
if c.QUICSettings != nil {
qs, err := c.QUICSettings.Build()
if err != nil {
return nil, newError("Failed to build QUIC config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "quic",
Settings: serial.ToTypedMessage(qs),
})
}
if c.SocketSettings != nil {
ss, err := c.SocketSettings.Build()
if err != nil {
return nil, newError("Failed to build sockopt").Base(err)
}
config.SocketSettings = ss
}
return config, nil
}
type ProxyConfig struct {
Tag string `json:"tag"`
}
// 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,
}, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dns_proxy_test.go | infra/conf/dns_proxy_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/dns"
)
func TestDnsProxyConfig(t *testing.T) {
creator := func() Buildable {
return new(DnsOutboundConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"address": "8.8.8.8",
"port": 53,
"network": "tcp"
}`,
Parser: loadJSON(creator),
Output: &dns.Config{
Server: &net.Endpoint{
Network: net.Network_TCP,
Address: net.NewIPOrDomain(net.IPAddress([]byte{8, 8, 8, 8})),
Port: 53,
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/router.go | infra/conf/router.go | package conf
import (
"encoding/json"
"strconv"
"strings"
"v2ray.com/core/app/router"
"v2ray.com/core/common/net"
"v2ray.com/core/common/platform/filesystem"
"github.com/golang/protobuf/proto"
)
type RouterRulesConfig struct {
RuleList []json.RawMessage `json:"rules"`
DomainStrategy string `json:"domainStrategy"`
}
type BalancingRule struct {
Tag string `json:"tag"`
Selectors StringList `json:"selector"`
}
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")
}
return &router.BalancingRule{
Tag: r.Tag,
OutboundSelector: []string(r.Selectors),
}, nil
}
type RouterConfig struct {
Settings *RouterRulesConfig `json:"settings"` // Deprecated
RuleList []json.RawMessage `json:"rules"`
DomainStrategy *string `json:"domainStrategy"`
Balancers []*BalancingRule `json:"balancers"`
}
func (c *RouterConfig) getDomainStrategy() router.Config_DomainStrategy {
ds := ""
if c.DomainStrategy != nil {
ds = *c.DomainStrategy
} else if c.Settings != nil {
ds = c.Settings.DomainStrategy
}
switch strings.ToLower(ds) {
case "alwaysip":
return router.Config_UseIp
case "ipifnonmatch":
return router.Config_IpIfNonMatch
case "ipondemand":
return router.Config_IpOnDemand
default:
return router.Config_AsIs
}
}
func (c *RouterConfig) Build() (*router.Config, error) {
config := new(router.Config)
config.DomainStrategy = c.getDomainStrategy()
rawRuleList := c.RuleList
if c.Settings != nil {
rawRuleList = append(c.RuleList, c.Settings.RuleList...)
}
for _, rawRule := range rawRuleList {
rule, err := ParseRule(rawRule)
if err != nil {
return nil, err
}
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
}
type RouterRule struct {
Type string `json:"type"`
OutboundTag string `json:"outboundTag"`
BalancerTag string `json:"balancerTag"`
}
func ParseIP(s string) (*router.CIDR, error) {
var addr, mask string
i := strings.Index(s, "/")
if i < 0 {
addr = s
} else {
addr = s[:i]
mask = s[i+1:]
}
ip := net.ParseAddress(addr)
switch ip.Family() {
case net.AddressFamilyIPv4:
bits := uint32(32)
if len(mask) > 0 {
bits64, err := strconv.ParseUint(mask, 10, 32)
if err != nil {
return nil, newError("invalid network mask for router: ", mask).Base(err)
}
bits = uint32(bits64)
}
if bits > 32 {
return nil, newError("invalid network mask for router: ", bits)
}
return &router.CIDR{
Ip: []byte(ip.IP()),
Prefix: bits,
}, nil
case net.AddressFamilyIPv6:
bits := uint32(128)
if len(mask) > 0 {
bits64, err := strconv.ParseUint(mask, 10, 32)
if err != nil {
return nil, newError("invalid network mask for router: ", mask).Base(err)
}
bits = uint32(bits64)
}
if bits > 128 {
return nil, newError("invalid network mask for router: ", bits)
}
return &router.CIDR{
Ip: []byte(ip.IP()),
Prefix: bits,
}, nil
default:
return nil, newError("unsupported address for router: ", s)
}
}
func loadGeoIP(country string) ([]*router.CIDR, error) {
return loadIP("geoip.dat", country)
}
func loadIP(filename, country string) ([]*router.CIDR, error) {
geoipBytes, err := filesystem.ReadAsset(filename)
if err != nil {
return nil, newError("failed to open file: ", filename).Base(err)
}
var geoipList router.GeoIPList
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
return nil, err
}
for _, geoip := range geoipList.Entry {
if geoip.CountryCode == country {
return geoip.Cidr, nil
}
}
return nil, newError("country not found in ", filename, ": ", country)
}
func loadSite(filename, country string) ([]*router.Domain, error) {
geositeBytes, err := filesystem.ReadAsset(filename)
if err != nil {
return nil, newError("failed to open file: ", filename).Base(err)
}
var geositeList router.GeoSiteList
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
return nil, err
}
for _, site := range geositeList.Entry {
if site.CountryCode == country {
return site.Domain, nil
}
}
return nil, newError("list not found in ", filename, ": ", country)
}
type AttributeMatcher interface {
Match(*router.Domain) bool
}
type BooleanMatcher string
func (m BooleanMatcher) Match(domain *router.Domain) bool {
for _, attr := range domain.Attribute {
if attr.Key == string(m) {
return true
}
}
return false
}
type AttributeList struct {
matcher []AttributeMatcher
}
func (al *AttributeList) Match(domain *router.Domain) bool {
for _, matcher := range al.matcher {
if !matcher.Match(domain) {
return false
}
}
return true
}
func (al *AttributeList) IsEmpty() bool {
return len(al.matcher) == 0
}
func parseAttrs(attrs []string) *AttributeList {
al := new(AttributeList)
for _, attr := range attrs {
lc := strings.ToLower(attr)
al.matcher = append(al.matcher, BooleanMatcher(lc))
}
return al
}
func loadGeositeWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
parts := strings.Split(siteWithAttr, "@")
if len(parts) == 0 {
return nil, newError("empty site")
}
country := strings.ToUpper(parts[0])
attrs := parseAttrs(parts[1:])
domains, err := loadSite(file, country)
if err != nil {
return nil, err
}
if attrs.IsEmpty() {
return domains, nil
}
filteredDomains := make([]*router.Domain, 0, len(domains))
for _, domain := range domains {
if attrs.Match(domain) {
filteredDomains = append(filteredDomains, domain)
}
}
return filteredDomains, nil
}
func parseDomainRule(domain string) ([]*router.Domain, error) {
if strings.HasPrefix(domain, "geosite:") {
country := strings.ToUpper(domain[8:])
domains, err := loadGeositeWithAttr("geosite.dat", country)
if err != nil {
return nil, newError("failed to load geosite: ", country).Base(err)
}
return domains, nil
}
var isExtDatFile = 0
{
const prefix = "ext:"
if strings.HasPrefix(domain, prefix) {
isExtDatFile = len(prefix)
}
const prefixQualified = "ext-domain:"
if strings.HasPrefix(domain, prefixQualified) {
isExtDatFile = len(prefixQualified)
}
}
if isExtDatFile != 0 {
kv := strings.Split(domain[isExtDatFile:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", domain)
}
filename := kv[0]
country := kv[1]
domains, err := loadGeositeWithAttr(filename, country)
if err != nil {
return nil, newError("failed to load external sites: ", country, " from ", filename).Base(err)
}
return domains, nil
}
domainRule := new(router.Domain)
switch {
case strings.HasPrefix(domain, "regexp:"):
domainRule.Type = router.Domain_Regex
domainRule.Value = domain[7:]
case strings.HasPrefix(domain, "domain:"):
domainRule.Type = router.Domain_Domain
domainRule.Value = domain[7:]
case strings.HasPrefix(domain, "full:"):
domainRule.Type = router.Domain_Full
domainRule.Value = domain[5:]
case strings.HasPrefix(domain, "keyword:"):
domainRule.Type = router.Domain_Plain
domainRule.Value = domain[8:]
case strings.HasPrefix(domain, "dotless:"):
domainRule.Type = router.Domain_Regex
switch substr := domain[8:]; {
case substr == "":
domainRule.Value = "^[^.]*$"
case !strings.Contains(substr, "."):
domainRule.Value = "^[^.]*" + substr + "[^.]*$"
default:
return nil, newError("substr in dotless rule should not contain a dot: ", substr)
}
default:
domainRule.Type = router.Domain_Plain
domainRule.Value = domain
}
return []*router.Domain{domainRule}, nil
}
func toCidrList(ips StringList) ([]*router.GeoIP, error) {
var geoipList []*router.GeoIP
var customCidrs []*router.CIDR
for _, ip := range ips {
if strings.HasPrefix(ip, "geoip:") {
country := ip[6:]
geoip, err := loadGeoIP(strings.ToUpper(country))
if err != nil {
return nil, newError("failed to load GeoIP: ", country).Base(err)
}
geoipList = append(geoipList, &router.GeoIP{
CountryCode: strings.ToUpper(country),
Cidr: geoip,
})
continue
}
var isExtDatFile = 0
{
const prefix = "ext:"
if strings.HasPrefix(ip, prefix) {
isExtDatFile = len(prefix)
}
const prefixQualified = "ext-ip:"
if strings.HasPrefix(ip, prefixQualified) {
isExtDatFile = len(prefixQualified)
}
}
if isExtDatFile != 0 {
kv := strings.Split(ip[isExtDatFile:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", ip)
}
filename := kv[0]
country := kv[1]
geoip, err := loadIP(filename, strings.ToUpper(country))
if err != nil {
return nil, newError("failed to load IPs: ", country, " from ", filename).Base(err)
}
geoipList = append(geoipList, &router.GeoIP{
CountryCode: strings.ToUpper(filename + "_" + country),
Cidr: geoip,
})
continue
}
ipRule, err := ParseIP(ip)
if err != nil {
return nil, newError("invalid IP: ", ip).Base(err)
}
customCidrs = append(customCidrs, ipRule)
}
if len(customCidrs) > 0 {
geoipList = append(geoipList, &router.GeoIP{
Cidr: customCidrs,
})
}
return geoipList, nil
}
func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
type RawFieldRule struct {
RouterRule
Domain *StringList `json:"domain"`
IP *StringList `json:"ip"`
Port *PortList `json:"port"`
Network *NetworkList `json:"network"`
SourceIP *StringList `json:"source"`
SourcePort *PortList `json:"sourcePort"`
User *StringList `json:"user"`
InboundTag *StringList `json:"inboundTag"`
Protocols *StringList `json:"protocol"`
Attributes string `json:"attrs"`
}
rawFieldRule := new(RawFieldRule)
err := json.Unmarshal(msg, rawFieldRule)
if err != nil {
return nil, err
}
rule := new(router.RoutingRule)
if len(rawFieldRule.OutboundTag) > 0 {
rule.TargetTag = &router.RoutingRule_Tag{
Tag: rawFieldRule.OutboundTag,
}
} else if len(rawFieldRule.BalancerTag) > 0 {
rule.TargetTag = &router.RoutingRule_BalancingTag{
BalancingTag: rawFieldRule.BalancerTag,
}
} else {
return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
}
if rawFieldRule.Domain != nil {
for _, domain := range *rawFieldRule.Domain {
rules, err := parseDomainRule(domain)
if err != nil {
return nil, newError("failed to parse domain rule: ", domain).Base(err)
}
rule.Domain = append(rule.Domain, rules...)
}
}
if rawFieldRule.IP != nil {
geoipList, err := toCidrList(*rawFieldRule.IP)
if err != nil {
return nil, err
}
rule.Geoip = geoipList
}
if rawFieldRule.Port != nil {
rule.PortList = rawFieldRule.Port.Build()
}
if rawFieldRule.Network != nil {
rule.Networks = rawFieldRule.Network.Build()
}
if rawFieldRule.SourceIP != nil {
geoipList, err := toCidrList(*rawFieldRule.SourceIP)
if err != nil {
return nil, err
}
rule.SourceGeoip = geoipList
}
if rawFieldRule.SourcePort != nil {
rule.SourcePortList = rawFieldRule.SourcePort.Build()
}
if rawFieldRule.User != nil {
for _, s := range *rawFieldRule.User {
rule.UserEmail = append(rule.UserEmail, s)
}
}
if rawFieldRule.InboundTag != nil {
for _, s := range *rawFieldRule.InboundTag {
rule.InboundTag = append(rule.InboundTag, s)
}
}
if rawFieldRule.Protocols != nil {
for _, s := range *rawFieldRule.Protocols {
rule.Protocol = append(rule.Protocol, s)
}
}
if len(rawFieldRule.Attributes) > 0 {
rule.Attributes = rawFieldRule.Attributes
}
return rule, nil
}
func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
rawRule := new(RouterRule)
err := json.Unmarshal(msg, rawRule)
if err != nil {
return nil, newError("invalid router rule").Base(err)
}
if rawRule.Type == "field" {
fieldrule, err := parseFieldRule(msg)
if err != nil {
return nil, newError("invalid field rule").Base(err)
}
return fieldrule, nil
}
if rawRule.Type == "chinaip" {
chinaiprule, err := parseChinaIPRule(msg)
if err != nil {
return nil, newError("invalid chinaip rule").Base(err)
}
return chinaiprule, nil
}
if rawRule.Type == "chinasites" {
chinasitesrule, err := parseChinaSitesRule(msg)
if err != nil {
return nil, newError("invalid chinasites rule").Base(err)
}
return chinasitesrule, nil
}
return nil, newError("unknown router rule type: ", rawRule.Type)
}
func parseChinaIPRule(data []byte) (*router.RoutingRule, error) {
rawRule := new(RouterRule)
err := json.Unmarshal(data, rawRule)
if err != nil {
return nil, newError("invalid router rule").Base(err)
}
chinaIPs, err := loadGeoIP("CN")
if err != nil {
return nil, newError("failed to load geoip:cn").Base(err)
}
return &router.RoutingRule{
TargetTag: &router.RoutingRule_Tag{
Tag: rawRule.OutboundTag,
},
Cidr: chinaIPs,
}, nil
}
func parseChinaSitesRule(data []byte) (*router.RoutingRule, error) {
rawRule := new(RouterRule)
err := json.Unmarshal(data, rawRule)
if err != nil {
return nil, newError("invalid router rule").Base(err).AtError()
}
domains, err := loadGeositeWithAttr("geosite.dat", "CN")
if err != nil {
return nil, newError("failed to load geosite:cn.").Base(err)
}
return &router.RoutingRule{
TargetTag: &router.RoutingRule_Tag{
Tag: rawRule.OutboundTag,
},
Domain: domains,
}, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/vless.go | infra/conf/vless.go | package conf
import (
"encoding/json"
"runtime"
"strconv"
"syscall"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/vless"
"v2ray.com/core/proxy/vless/inbound"
"v2ray.com/core/proxy/vless/outbound"
)
type VLessInboundFallback struct {
Alpn string `json:"alpn"`
Path string `json:"path"`
Type string `json:"type"`
Dest json.RawMessage `json:"dest"`
Xver uint64 `json:"xver"`
}
type VLessInboundConfig struct {
Clients []json.RawMessage `json:"clients"`
Decryption string `json:"decryption"`
Fallback json.RawMessage `json:"fallback"`
Fallbacks []*VLessInboundFallback `json:"fallbacks"`
}
// Build implements Buildable
func (c *VLessInboundConfig) Build() (proto.Message, error) {
config := new(inbound.Config)
if len(c.Clients) == 0 {
//return nil, newError(`VLESS settings: "clients" is empty`)
}
config.Clients = make([]*protocol.User, len(c.Clients))
for idx, rawUser := range c.Clients {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError(`VLESS clients: invalid user`).Base(err)
}
account := new(vless.Account)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError(`VLESS clients: invalid user`).Base(err)
}
switch account.Flow {
case "", "xtls-rprx-origin", "xtls-rprx-direct":
default:
return nil, newError(`VLESS clients: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if account.Encryption != "" {
return nil, newError(`VLESS clients: "encryption" should not in inbound settings`)
}
user.Account = serial.ToTypedMessage(account)
config.Clients[idx] = user
}
if c.Decryption != "none" {
return nil, newError(`VLESS settings: please add/set "decryption":"none" to every settings`)
}
config.Decryption = c.Decryption
if c.Fallback != nil {
return nil, newError(`VLESS settings: please use "fallbacks":[{}] instead of "fallback":{}`)
}
for _, fb := range c.Fallbacks {
var i uint16
var s string
if err := json.Unmarshal(fb.Dest, &i); err == nil {
s = strconv.Itoa(int(i))
} else {
_ = json.Unmarshal(fb.Dest, &s)
}
config.Fallbacks = append(config.Fallbacks, &inbound.Fallback{
Alpn: fb.Alpn,
Path: fb.Path,
Type: fb.Type,
Dest: s,
Xver: fb.Xver,
})
}
for _, fb := range config.Fallbacks {
/*
if fb.Alpn == "h2" && fb.Path != "" {
return nil, newError(`VLESS fallbacks: "alpn":"h2" doesn't support "path"`)
}
*/
if fb.Path != "" && fb.Path[0] != '/' {
return nil, newError(`VLESS fallbacks: "path" must be empty or start with "/"`)
}
if fb.Type == "" && fb.Dest != "" {
if fb.Dest == "serve-ws-none" {
fb.Type = "serve"
} else {
switch fb.Dest[0] {
case '@', '/':
fb.Type = "unix"
if fb.Dest[0] == '@' && len(fb.Dest) > 1 && fb.Dest[1] == '@' && runtime.GOOS == "linux" {
fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path)) // may need padding to work in front of haproxy
copy(fullAddr, fb.Dest[1:])
fb.Dest = string(fullAddr)
}
default:
if _, err := strconv.Atoi(fb.Dest); err == nil {
fb.Dest = "127.0.0.1:" + fb.Dest
}
if _, _, err := net.SplitHostPort(fb.Dest); err == nil {
fb.Type = "tcp"
}
}
}
}
if fb.Type == "" {
return nil, newError(`VLESS fallbacks: please fill in a valid value for every "dest"`)
}
if fb.Xver > 2 {
return nil, newError(`VLESS fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
}
}
return config, nil
}
type VLessOutboundVnext struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VLessOutboundConfig struct {
Vnext []*VLessOutboundVnext `json:"vnext"`
}
// Build implements Buildable
func (c *VLessOutboundConfig) Build() (proto.Message, error) {
config := new(outbound.Config)
if len(c.Vnext) == 0 {
return nil, newError(`VLESS settings: "vnext" is empty`)
}
config.Vnext = make([]*protocol.ServerEndpoint, len(c.Vnext))
for idx, rec := range c.Vnext {
if rec.Address == nil {
return nil, newError(`VLESS vnext: "address" is not set`)
}
if len(rec.Users) == 0 {
return nil, newError(`VLESS vnext: "users" is empty`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
User: make([]*protocol.User, len(rec.Users)),
}
for idx, rawUser := range rec.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError(`VLESS users: invalid user`).Base(err)
}
account := new(vless.Account)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError(`VLESS users: invalid user`).Base(err)
}
switch account.Flow {
case "", "xtls-rprx-origin", "xtls-rprx-origin-udp443", "xtls-rprx-direct", "xtls-rprx-direct-udp443":
default:
return nil, newError(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if account.Encryption != "none" {
return nil, newError(`VLESS users: please add/set "encryption":"none" for every user`)
}
user.Account = serial.ToTypedMessage(account)
spec.User[idx] = user
}
config.Vnext[idx] = spec
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/v2ray.go | infra/conf/v2ray.go | package conf
import (
"encoding/json"
"log"
"os"
"strings"
"v2ray.com/core"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/app/stats"
"v2ray.com/core/common/serial"
"v2ray.com/core/transport/internet/xtls"
)
var (
inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
"dokodemo-door": func() interface{} { return new(DokodemoConfig) },
"http": func() interface{} { return new(HttpServerConfig) },
"shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
"socks": func() interface{} { return new(SocksServerConfig) },
"vless": func() interface{} { return new(VLessInboundConfig) },
"vmess": func() interface{} { return new(VMessInboundConfig) },
"trojan": func() interface{} { return new(TrojanServerConfig) },
"mtproto": func() interface{} { return new(MTProtoServerConfig) },
}, "protocol", "settings")
outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
"blackhole": func() interface{} { return new(BlackholeConfig) },
"freedom": func() interface{} { return new(FreedomConfig) },
"http": func() interface{} { return new(HttpClientConfig) },
"shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
"socks": func() interface{} { return new(SocksClientConfig) },
"vless": func() interface{} { return new(VLessOutboundConfig) },
"vmess": func() interface{} { return new(VMessOutboundConfig) },
"trojan": func() interface{} { return new(TrojanClientConfig) },
"mtproto": func() interface{} { return new(MTProtoClientConfig) },
"dns": func() interface{} { return new(DnsOutboundConfig) },
}, "protocol", "settings")
ctllog = log.New(os.Stderr, "v2ctl> ", 0)
)
func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
kp := make([]proxyman.KnownProtocols, 0, 8)
for _, p := range s {
switch strings.ToLower(p) {
case "http":
kp = append(kp, proxyman.KnownProtocols_HTTP)
case "https", "tls", "ssl":
kp = append(kp, proxyman.KnownProtocols_TLS)
default:
return nil, newError("Unknown protocol: ", p)
}
}
return kp, nil
}
type SniffingConfig struct {
Enabled bool `json:"enabled"`
DestOverride *StringList `json:"destOverride"`
}
// 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")
default:
return nil, newError("unknown protocol: ", domainOverride)
}
}
}
return &proxyman.SniffingConfig{
Enabled: c.Enabled,
DestinationOverride: p,
}, nil
}
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,
}
}
type InboundDetourAllocationConfig struct {
Strategy string `json:"strategy"`
Concurrency *uint32 `json:"concurrency"`
RefreshMin *uint32 `json:"refresh"`
}
// Build implements Buildable.
func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
config := new(proxyman.AllocationStrategy)
switch strings.ToLower(c.Strategy) {
case "always":
config.Type = proxyman.AllocationStrategy_Always
case "random":
config.Type = proxyman.AllocationStrategy_Random
case "external":
config.Type = proxyman.AllocationStrategy_External
default:
return nil, newError("unknown allocation strategy: ", c.Strategy)
}
if c.Concurrency != nil {
config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
Value: *c.Concurrency,
}
}
if c.RefreshMin != nil {
config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
Value: *c.RefreshMin,
}
}
return config, nil
}
type InboundDetourConfig struct {
Protocol string `json:"protocol"`
PortRange *PortRange `json:"port"`
ListenOn *Address `json:"listen"`
Settings *json.RawMessage `json:"settings"`
Tag string `json:"tag"`
Allocation *InboundDetourAllocationConfig `json:"allocate"`
StreamSetting *StreamConfig `json:"streamSettings"`
DomainOverride *StringList `json:"domainOverride"`
SniffingConfig *SniffingConfig `json:"sniffing"`
}
// Build implements Buildable.
func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
receiverSettings := &proxyman.ReceiverConfig{}
if c.PortRange == nil {
return nil, newError("port range not specified in InboundDetour.")
}
receiverSettings.PortRange = c.PortRange.Build()
if c.ListenOn != nil {
if c.ListenOn.Family().IsDomain() {
return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
}
receiverSettings.Listen = c.ListenOn.Build()
}
if c.Allocation != nil {
concurrency := -1
if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
concurrency = int(*c.Allocation.Concurrency)
}
portRange := int(c.PortRange.To - c.PortRange.From + 1)
if concurrency >= 0 && concurrency >= portRange {
return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
}
as, err := c.Allocation.Build()
if err != nil {
return nil, err
}
receiverSettings.AllocationStrategy = as
}
if c.StreamSetting != nil {
ss, err := c.StreamSetting.Build()
if err != nil {
return nil, err
}
if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") {
return nil, newError("XTLS only supports VLESS for now.")
}
receiverSettings.StreamSettings = ss
}
if c.SniffingConfig != nil {
s, err := c.SniffingConfig.Build()
if err != nil {
return nil, newError("failed to build sniffing config").Base(err)
}
receiverSettings.SniffingSettings = s
}
if c.DomainOverride != nil {
kp, err := toProtocolList(*c.DomainOverride)
if err != nil {
return nil, newError("failed to parse inbound detour config").Base(err)
}
receiverSettings.DomainOverride = kp
}
settings := []byte("{}")
if c.Settings != nil {
settings = ([]byte)(*c.Settings)
}
rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to load inbound detour config.").Base(err)
}
if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
}
ts, err := rawConfig.(Buildable).Build()
if err != nil {
return nil, err
}
return &core.InboundHandlerConfig{
Tag: c.Tag,
ReceiverSettings: serial.ToTypedMessage(receiverSettings),
ProxySettings: serial.ToTypedMessage(ts),
}, nil
}
type OutboundDetourConfig struct {
Protocol string `json:"protocol"`
SendThrough *Address `json:"sendThrough"`
Tag string `json:"tag"`
Settings *json.RawMessage `json:"settings"`
StreamSetting *StreamConfig `json:"streamSettings"`
ProxySettings *ProxyConfig `json:"proxySettings"`
MuxSettings *MuxConfig `json:"mux"`
}
// Build implements Buildable.
func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
senderSettings := &proxyman.SenderConfig{}
if c.SendThrough != nil {
address := c.SendThrough
if address.Family().IsDomain() {
return nil, newError("unable to send through: " + address.String())
}
senderSettings.Via = address.Build()
}
if c.StreamSetting != nil {
ss, err := c.StreamSetting.Build()
if err != nil {
return nil, err
}
if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") {
return nil, newError("XTLS only supports VLESS for now.")
}
senderSettings.StreamSettings = ss
}
if c.ProxySettings != nil {
ps, err := c.ProxySettings.Build()
if err != nil {
return nil, newError("invalid outbound detour proxy settings.").Base(err)
}
senderSettings.ProxySettings = ps
}
if c.MuxSettings != nil {
ms := c.MuxSettings.Build()
if ms != nil && ms.Enabled {
if ss := senderSettings.StreamSettings; ss != nil {
if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) {
return nil, newError("XTLS doesn't support Mux for now.")
}
}
}
senderSettings.MultiplexSettings = ms
}
settings := []byte("{}")
if c.Settings != nil {
settings = ([]byte)(*c.Settings)
}
rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to parse to outbound detour config.").Base(err)
}
ts, err := rawConfig.(Buildable).Build()
if err != nil {
return nil, err
}
return &core.OutboundHandlerConfig{
SenderSettings: serial.ToTypedMessage(senderSettings),
Tag: c.Tag,
ProxySettings: serial.ToTypedMessage(ts),
}, nil
}
type StatsConfig struct{}
// Build implements Buildable.
func (c *StatsConfig) Build() (*stats.Config, error) {
return &stats.Config{}, nil
}
type Config struct {
Port uint16 `json:"port"` // Port of this Point server. Deprecated.
LogConfig *LogConfig `json:"log"`
RouterConfig *RouterConfig `json:"routing"`
DNSConfig *DnsConfig `json:"dns"`
InboundConfigs []InboundDetourConfig `json:"inbounds"`
OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
InboundConfig *InboundDetourConfig `json:"inbound"` // Deprecated.
OutboundConfig *OutboundDetourConfig `json:"outbound"` // Deprecated.
InboundDetours []InboundDetourConfig `json:"inboundDetour"` // Deprecated.
OutboundDetours []OutboundDetourConfig `json:"outboundDetour"` // Deprecated.
Transport *TransportConfig `json:"transport"`
Policy *PolicyConfig `json:"policy"`
Api *ApiConfig `json:"api"`
Stats *StatsConfig `json:"stats"`
Reverse *ReverseConfig `json:"reverse"`
}
func (c *Config) findInboundTag(tag string) int {
found := -1
for idx, ib := range c.InboundConfigs {
if ib.Tag == tag {
found = idx
break
}
}
return found
}
func (c *Config) findOutboundTag(tag string) int {
found := -1
for idx, ob := range c.OutboundConfigs {
if ob.Tag == tag {
found = idx
break
}
}
return found
}
// Override method accepts another Config overrides the current attribute
func (c *Config) Override(o *Config, fn string) {
// only process the non-deprecated members
if o.LogConfig != nil {
c.LogConfig = o.LogConfig
}
if o.RouterConfig != nil {
c.RouterConfig = o.RouterConfig
}
if o.DNSConfig != nil {
c.DNSConfig = o.DNSConfig
}
if o.Transport != nil {
c.Transport = o.Transport
}
if o.Policy != nil {
c.Policy = o.Policy
}
if o.Api != nil {
c.Api = o.Api
}
if o.Stats != nil {
c.Stats = o.Stats
}
if o.Reverse != nil {
c.Reverse = o.Reverse
}
// deprecated attrs... keep them for now
if o.InboundConfig != nil {
c.InboundConfig = o.InboundConfig
}
if o.OutboundConfig != nil {
c.OutboundConfig = o.OutboundConfig
}
if o.InboundDetours != nil {
c.InboundDetours = o.InboundDetours
}
if o.OutboundDetours != nil {
c.OutboundDetours = o.OutboundDetours
}
// deprecated attrs
// update the Inbound in slice if the only one in overide config has same tag
if len(o.InboundConfigs) > 0 {
if len(c.InboundConfigs) > 0 && len(o.InboundConfigs) == 1 {
if idx := c.findInboundTag(o.InboundConfigs[0].Tag); idx > -1 {
c.InboundConfigs[idx] = o.InboundConfigs[0]
ctllog.Println("[", fn, "] updated inbound with tag: ", o.InboundConfigs[0].Tag)
} else {
c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[0])
ctllog.Println("[", fn, "] appended inbound with tag: ", o.InboundConfigs[0].Tag)
}
} else {
c.InboundConfigs = o.InboundConfigs
}
}
// update the Outbound in slice if the only one in overide config has same tag
if len(o.OutboundConfigs) > 0 {
if len(c.OutboundConfigs) > 0 && len(o.OutboundConfigs) == 1 {
if idx := c.findOutboundTag(o.OutboundConfigs[0].Tag); idx > -1 {
c.OutboundConfigs[idx] = o.OutboundConfigs[0]
ctllog.Println("[", fn, "] updated outbound with tag: ", o.OutboundConfigs[0].Tag)
} else {
if strings.Contains(strings.ToLower(fn), "tail") {
c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[0])
ctllog.Println("[", fn, "] appended outbound with tag: ", o.OutboundConfigs[0].Tag)
} else {
c.OutboundConfigs = append(o.OutboundConfigs, c.OutboundConfigs...)
ctllog.Println("[", fn, "] prepended outbound with tag: ", o.OutboundConfigs[0].Tag)
}
}
} else {
c.OutboundConfigs = o.OutboundConfigs
}
}
}
func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
if s.TCPSettings == nil {
s.TCPSettings = t.TCPConfig
}
if s.KCPSettings == nil {
s.KCPSettings = t.KCPConfig
}
if s.WSSettings == nil {
s.WSSettings = t.WSConfig
}
if s.HTTPSettings == nil {
s.HTTPSettings = t.HTTPConfig
}
if s.DSSettings == nil {
s.DSSettings = t.DSConfig
}
}
// Build implements Buildable.
func (c *Config) Build() (*core.Config, error) {
config := &core.Config{
App: []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
}
if c.Api != nil {
apiConf, err := c.Api.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(apiConf))
}
if c.Stats != nil {
statsConf, err := c.Stats.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(statsConf))
}
var logConfMsg *serial.TypedMessage
if c.LogConfig != nil {
logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
} else {
logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
}
// let logger module be the first App to start,
// so that other modules could print log during initiating
config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
if c.RouterConfig != nil {
routerConfig, err := c.RouterConfig.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(routerConfig))
}
if c.DNSConfig != nil {
dnsApp, err := c.DNSConfig.Build()
if err != nil {
return nil, newError("failed to parse DNS config").Base(err)
}
config.App = append(config.App, serial.ToTypedMessage(dnsApp))
}
if c.Policy != nil {
pc, err := c.Policy.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(pc))
}
if c.Reverse != nil {
r, err := c.Reverse.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(r))
}
var inbounds []InboundDetourConfig
if c.InboundConfig != nil {
inbounds = append(inbounds, *c.InboundConfig)
}
if len(c.InboundDetours) > 0 {
inbounds = append(inbounds, c.InboundDetours...)
}
if len(c.InboundConfigs) > 0 {
inbounds = append(inbounds, c.InboundConfigs...)
}
// Backward compatibility.
if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
inbounds[0].PortRange = &PortRange{
From: uint32(c.Port),
To: uint32(c.Port),
}
}
for _, rawInboundConfig := range inbounds {
if c.Transport != nil {
if rawInboundConfig.StreamSetting == nil {
rawInboundConfig.StreamSetting = &StreamConfig{}
}
applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
}
ic, err := rawInboundConfig.Build()
if err != nil {
return nil, err
}
config.Inbound = append(config.Inbound, ic)
}
var outbounds []OutboundDetourConfig
if c.OutboundConfig != nil {
outbounds = append(outbounds, *c.OutboundConfig)
}
if len(c.OutboundDetours) > 0 {
outbounds = append(outbounds, c.OutboundDetours...)
}
if len(c.OutboundConfigs) > 0 {
outbounds = append(outbounds, c.OutboundConfigs...)
}
for _, rawOutboundConfig := range outbounds {
if c.Transport != nil {
if rawOutboundConfig.StreamSetting == nil {
rawOutboundConfig.StreamSetting = &StreamConfig{}
}
applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
}
oc, err := rawOutboundConfig.Build()
if err != nil {
return nil, err
}
config.Outbound = append(config.Outbound, oc)
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dns.go | infra/conf/dns.go | package conf
import (
"encoding/json"
"sort"
"strings"
"v2ray.com/core/app/dns"
"v2ray.com/core/app/router"
"v2ray.com/core/common/net"
)
type NameServerConfig struct {
Address *Address
Port uint16
Domains []string
ExpectIPs StringList
}
func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
var address Address
if err := json.Unmarshal(data, &address); err == nil {
c.Address = &address
return nil
}
var advanced struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Domains []string `json:"domains"`
ExpectIPs StringList `json:"expectIps"`
}
if err := json.Unmarshal(data, &advanced); err == nil {
c.Address = advanced.Address
c.Port = advanced.Port
c.Domains = advanced.Domains
c.ExpectIPs = advanced.ExpectIPs
return nil
}
return newError("failed to parse name server: ", string(data))
}
func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
switch t {
case router.Domain_Domain:
return dns.DomainMatchingType_Subdomain
case router.Domain_Full:
return dns.DomainMatchingType_Full
case router.Domain_Plain:
return dns.DomainMatchingType_Keyword
case router.Domain_Regex:
return dns.DomainMatchingType_Regex
default:
panic("unknown domain type")
}
}
func (c *NameServerConfig) Build() (*dns.NameServer, error) {
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 := parseDomainRule(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 := toCidrList(c.ExpectIPs)
if err != nil {
return nil, newError("invalid ip rule: ", c.ExpectIPs).Base(err)
}
return &dns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: c.Address.Build(),
Port: uint32(c.Port),
},
PrioritizedDomain: domains,
Geoip: geoipList,
OriginalRules: originalRules,
}, nil
}
var typeMap = map[router.Domain_Type]dns.DomainMatchingType{
router.Domain_Full: dns.DomainMatchingType_Full,
router.Domain_Domain: dns.DomainMatchingType_Subdomain,
router.Domain_Plain: dns.DomainMatchingType_Keyword,
router.Domain_Regex: dns.DomainMatchingType_Regex,
}
// DnsConfig is a JSON serializable object for dns.Config.
type DnsConfig struct {
Servers []*NameServerConfig `json:"servers"`
Hosts map[string]*Address `json:"hosts"`
ClientIP *Address `json:"clientIp"`
Tag string `json:"tag"`
}
func getHostMapping(addr *Address) *dns.Config_HostMapping {
if addr.Family().IsIP() {
return &dns.Config_HostMapping{
Ip: [][]byte{[]byte(addr.IP())},
}
} else {
return &dns.Config_HostMapping{
ProxiedDomain: addr.Domain(),
}
}
}
// Build implements Buildable
func (c *DnsConfig) Build() (*dns.Config, error) {
config := &dns.Config{
Tag: c.Tag,
}
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())
}
for _, server := range c.Servers {
ns, err := server.Build()
if err != nil {
return nil, newError("failed to build name server").Base(err)
}
config.NameServer = append(config.NameServer, ns)
}
if c.Hosts != nil && len(c.Hosts) > 0 {
domains := make([]string, 0, len(c.Hosts))
for domain := range c.Hosts {
domains = append(domains, domain)
}
sort.Strings(domains)
for _, domain := range domains {
addr := c.Hosts[domain]
var mappings []*dns.Config_HostMapping
if strings.HasPrefix(domain, "domain:") {
mapping := getHostMapping(addr)
mapping.Type = dns.DomainMatchingType_Subdomain
mapping.Domain = domain[7:]
mappings = append(mappings, mapping)
} else if strings.HasPrefix(domain, "geosite:") {
domains, err := loadGeositeWithAttr("geosite.dat", strings.ToUpper(domain[8:]))
if err != nil {
return nil, newError("invalid geosite settings: ", domain).Base(err)
}
for _, d := range domains {
mapping := getHostMapping(addr)
mapping.Type = typeMap[d.Type]
mapping.Domain = d.Value
mappings = append(mappings, mapping)
}
} else if strings.HasPrefix(domain, "regexp:") {
mapping := getHostMapping(addr)
mapping.Type = dns.DomainMatchingType_Regex
mapping.Domain = domain[7:]
mappings = append(mappings, mapping)
} else if strings.HasPrefix(domain, "keyword:") {
mapping := getHostMapping(addr)
mapping.Type = dns.DomainMatchingType_Keyword
mapping.Domain = domain[8:]
mappings = append(mappings, mapping)
} else if strings.HasPrefix(domain, "full:") {
mapping := getHostMapping(addr)
mapping.Type = dns.DomainMatchingType_Full
mapping.Domain = domain[5:]
mappings = append(mappings, mapping)
} else if strings.HasPrefix(domain, "dotless:") {
mapping := getHostMapping(addr)
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)
} else if strings.HasPrefix(domain, "ext:") {
kv := strings.Split(domain[4:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", domain)
}
filename := kv[0]
country := kv[1]
domains, err := loadGeositeWithAttr(filename, country)
if err != nil {
return nil, newError("failed to load domains: ", country, " from ", filename).Base(err)
}
for _, d := range domains {
mapping := getHostMapping(addr)
mapping.Type = typeMap[d.Type]
mapping.Domain = d.Value
mappings = append(mappings, mapping)
}
} else {
mapping := getHostMapping(addr)
mapping.Type = dns.DomainMatchingType_Full
mapping.Domain = domain
mappings = append(mappings, mapping)
}
config.StaticHosts = append(config.StaticHosts, mappings...)
}
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/conf.go | infra/conf/conf.go | package conf
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/vmess_test.go | infra/conf/vmess_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/vmess"
"v2ray.com/core/proxy/vmess/inbound"
"v2ray.com/core/proxy/vmess/outbound"
)
func TestVMessOutbound(t *testing.T) {
creator := func() Buildable {
return new(VMessOutboundConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "127.0.0.1",
"port": 80,
"users": [
{
"id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
"email": "love@v2ray.com",
"level": 255
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 80,
User: []*protocol.User{
{
Email: "love@v2ray.com",
Level: 255,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019",
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AUTO,
},
}),
},
},
},
},
},
},
})
}
func TestVMessInbound(t *testing.T) {
creator := func() Buildable {
return new(VMessInboundConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"clients": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"level": 0,
"alterId": 16,
"email": "love@v2ray.com",
"security": "aes-128-gcm"
}
],
"default": {
"level": 0,
"alterId": 32
},
"detour": {
"to": "tag_to_detour"
},
"disableInsecureEncryption": true
}`,
Parser: loadJSON(creator),
Output: &inbound.Config{
User: []*protocol.User{
{
Level: 0,
Email: "love@v2ray.com",
Account: serial.ToTypedMessage(&vmess.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
AlterId: 16,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
Default: &inbound.DefaultConfig{
Level: 0,
AlterId: 32,
},
Detour: &inbound.DetourConfig{
To: "tag_to_detour",
},
SecureEncryptionOnly: true,
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/log.go | infra/conf/log.go | package conf
import (
"strings"
"v2ray.com/core/app/log"
clog "v2ray.com/core/common/log"
)
func DefaultLogConfig() *log.Config {
return &log.Config{
AccessLogType: log.LogType_None,
ErrorLogType: log.LogType_Console,
ErrorLogLevel: clog.Severity_Warning,
}
}
type LogConfig struct {
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{
ErrorLogType: log.LogType_Console,
AccessLogType: log.LogType_Console,
}
if v.AccessLog == "none" {
config.AccessLogType = log.LogType_None
} else if len(v.AccessLog) > 0 {
config.AccessLogPath = v.AccessLog
config.AccessLogType = log.LogType_File
}
if v.ErrorLog == "none" {
config.ErrorLogType = log.LogType_None
} else if len(v.ErrorLog) > 0 {
config.ErrorLogPath = v.ErrorLog
config.ErrorLogType = log.LogType_File
}
level := strings.ToLower(v.LogLevel)
switch level {
case "debug":
config.ErrorLogLevel = clog.Severity_Debug
case "info":
config.ErrorLogLevel = clog.Severity_Info
case "error":
config.ErrorLogLevel = clog.Severity_Error
case "none":
config.ErrorLogType = log.LogType_None
config.AccessLogType = log.LogType_None
default:
config.ErrorLogLevel = clog.Severity_Warning
}
return config
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dokodemo_test.go | infra/conf/dokodemo_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/dokodemo"
)
func TestDokodemoConfig(t *testing.T) {
creator := func() Buildable {
return new(DokodemoConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"address": "8.8.8.8",
"port": 53,
"network": "tcp",
"timeout": 10,
"followRedirect": true,
"userLevel": 1
}`,
Parser: loadJSON(creator),
Output: &dokodemo.Config{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{8, 8, 8, 8},
},
},
Port: 53,
Networks: []net.Network{net.Network_TCP},
Timeout: 10,
FollowRedirect: true,
UserLevel: 1,
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/socks_test.go | infra/conf/socks_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/socks"
)
func TestSocksInboundConfig(t *testing.T) {
creator := func() Buildable {
return new(SocksServerConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"auth": "password",
"accounts": [
{
"user": "my-username",
"pass": "my-password"
}
],
"udp": false,
"ip": "127.0.0.1",
"timeout": 5,
"userLevel": 1
}`,
Parser: loadJSON(creator),
Output: &socks.ServerConfig{
AuthType: socks.AuthType_PASSWORD,
Accounts: map[string]string{
"my-username": "my-password",
},
UdpEnabled: false,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Timeout: 5,
UserLevel: 1,
},
},
})
}
func TestSocksOutboundConfig(t *testing.T) {
creator := func() Buildable {
return new(SocksClientConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"servers": [{
"address": "127.0.0.1",
"port": 1234,
"users": [
{"user": "test user", "pass": "test pass", "email": "test@email.com"}
]
}]
}`,
Parser: loadJSON(creator),
Output: &socks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 1234,
User: []*protocol.User{
{
Email: "test@email.com",
Account: serial.ToTypedMessage(&socks.Account{
Username: "test user",
Password: "test pass",
}),
},
},
},
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/v2ray_test.go | infra/conf/v2ray_test.go | package conf_test
import (
"encoding/json"
"reflect"
"testing"
"github.com/golang/protobuf/proto"
"github.com/google/go-cmp/cmp"
"v2ray.com/core"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/app/router"
"v2ray.com/core/common"
clog "v2ray.com/core/common/log"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/blackhole"
dns_proxy "v2ray.com/core/proxy/dns"
"v2ray.com/core/proxy/freedom"
"v2ray.com/core/proxy/vmess"
"v2ray.com/core/proxy/vmess/inbound"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/http"
"v2ray.com/core/transport/internet/tls"
"v2ray.com/core/transport/internet/websocket"
)
func TestV2RayConfig(t *testing.T) {
createParser := func() func(string) (proto.Message, error) {
return func(s string) (proto.Message, error) {
config := new(Config)
if err := json.Unmarshal([]byte(s), config); err != nil {
return nil, err
}
return config.Build()
}
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"outbound": {
"protocol": "freedom",
"settings": {}
},
"log": {
"access": "/var/log/v2ray/access.log",
"loglevel": "error",
"error": "/var/log/v2ray/error.log"
},
"inbound": {
"streamSettings": {
"network": "ws",
"wsSettings": {
"headers": {
"host": "example.domain"
},
"path": ""
},
"tlsSettings": {
"alpn": "h2"
},
"security": "tls"
},
"protocol": "vmess",
"port": 443,
"settings": {
"clients": [
{
"alterId": 100,
"security": "aes-128-gcm",
"id": "0cdf8a45-303d-4fed-9780-29aa7f54175e"
}
]
}
},
"inbounds": [{
"streamSettings": {
"network": "ws",
"wsSettings": {
"headers": {
"host": "example.domain"
},
"path": ""
},
"tlsSettings": {
"alpn": "h2"
},
"security": "tls"
},
"protocol": "vmess",
"port": "443-500",
"allocate": {
"strategy": "random",
"concurrency": 3
},
"settings": {
"clients": [
{
"alterId": 100,
"security": "aes-128-gcm",
"id": "0cdf8a45-303d-4fed-9780-29aa7f54175e"
}
]
}
}],
"outboundDetour": [
{
"tag": "blocked",
"protocol": "blackhole"
},
{
"protocol": "dns"
}
],
"routing": {
"strategy": "rules",
"settings": {
"rules": [
{
"ip": [
"10.0.0.0/8"
],
"type": "field",
"outboundTag": "blocked"
}
]
}
},
"transport": {
"httpSettings": {
"path": "/test"
}
}
}`,
Parser: createParser(),
Output: &core.Config{
App: []*serial.TypedMessage{
serial.ToTypedMessage(&log.Config{
ErrorLogType: log.LogType_File,
ErrorLogPath: "/var/log/v2ray/error.log",
ErrorLogLevel: clog.Severity_Error,
AccessLogType: log.LogType_File,
AccessLogPath: "/var/log/v2ray/access.log",
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{
DomainStrategy: router.Config_AsIs,
Rule: []*router.RoutingRule{
{
Geoip: []*router.GeoIP{
{
Cidr: []*router.CIDR{
{
Ip: []byte{10, 0, 0, 0},
Prefix: 8,
},
},
},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "blocked",
},
},
},
}),
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "tcp",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "http",
Settings: serial.ToTypedMessage(&http.Config{
Path: "/test",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{
DomainStrategy: freedom.Config_AS_IS,
UserLevel: 0,
}),
},
{
Tag: "blocked",
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "tcp",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "http",
Settings: serial.ToTypedMessage(&http.Config{
Path: "/test",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "tcp",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "http",
Settings: serial.ToTypedMessage(&http.Config{
Path: "/test",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{
Server: &net.Endpoint{},
}),
},
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: &net.PortRange{
From: 443,
To: 443,
},
StreamSettings: &internet.StreamConfig{
ProtocolName: "websocket",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "websocket",
Settings: serial.ToTypedMessage(&websocket.Config{
Header: []*websocket.Header{
{
Key: "host",
Value: "example.domain",
},
},
}),
},
{
ProtocolName: "http",
Settings: serial.ToTypedMessage(&http.Config{
Path: "/test",
}),
},
},
SecurityType: "v2ray.core.transport.internet.tls.Config",
SecuritySettings: []*serial.TypedMessage{
serial.ToTypedMessage(&tls.Config{
NextProtocol: []string{"h2"},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Level: 0,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "0cdf8a45-303d-4fed-9780-29aa7f54175e",
AlterId: 100,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: &net.PortRange{
From: 443,
To: 500,
},
AllocationStrategy: &proxyman.AllocationStrategy{
Type: proxyman.AllocationStrategy_Random,
Concurrency: &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
Value: 3,
},
},
StreamSettings: &internet.StreamConfig{
ProtocolName: "websocket",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "websocket",
Settings: serial.ToTypedMessage(&websocket.Config{
Header: []*websocket.Header{
{
Key: "host",
Value: "example.domain",
},
},
}),
},
{
ProtocolName: "http",
Settings: serial.ToTypedMessage(&http.Config{
Path: "/test",
}),
},
},
SecurityType: "v2ray.core.transport.internet.tls.Config",
SecuritySettings: []*serial.TypedMessage{
serial.ToTypedMessage(&tls.Config{
NextProtocol: []string{"h2"},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Level: 0,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "0cdf8a45-303d-4fed-9780-29aa7f54175e",
AlterId: 100,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
}),
},
},
},
},
})
}
func TestMuxConfig_Build(t *testing.T) {
tests := []struct {
name string
fields string
want *proxyman.MultiplexingConfig
}{
{"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{
Enabled: true,
Concurrency: 16,
}},
{"empty def", `{}`, &proxyman.MultiplexingConfig{
Enabled: false,
Concurrency: 8,
}},
{"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{
Enabled: false,
Concurrency: 4,
}},
{"forbidden", `{"enabled": false, "concurrency": -1}`, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := &MuxConfig{}
common.Must(json.Unmarshal([]byte(tt.fields), m))
if got := m.Build(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
}
})
}
}
func TestConfig_Override(t *testing.T) {
tests := []struct {
name string
orig *Config
over *Config
fn string
want *Config
}{
{"combine/empty",
&Config{},
&Config{
LogConfig: &LogConfig{},
RouterConfig: &RouterConfig{},
DNSConfig: &DnsConfig{},
Transport: &TransportConfig{},
Policy: &PolicyConfig{},
Api: &ApiConfig{},
Stats: &StatsConfig{},
Reverse: &ReverseConfig{},
},
"",
&Config{
LogConfig: &LogConfig{},
RouterConfig: &RouterConfig{},
DNSConfig: &DnsConfig{},
Transport: &TransportConfig{},
Policy: &PolicyConfig{},
Api: &ApiConfig{},
Stats: &StatsConfig{},
Reverse: &ReverseConfig{},
},
},
{"combine/newattr",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}},
&Config{LogConfig: &LogConfig{}}, "",
&Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}},
{"replace/inbounds",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}},
{"replace/inbounds-replaceall",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}},
{"replace/notag-append",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}}},
{"replace/outbounds",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}},
{"replace/outbounds-prepend",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"config.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}},
{"replace/outbounds-append",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}},
"config_tail.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}, {Tag: "pos2", Protocol: "kcp"}}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.orig.Override(tt.over, tt.fn)
if r := cmp.Diff(tt.orig, tt.want); r != "" {
t.Error(r)
}
})
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/mtproto.go | infra/conf/mtproto.go | package conf
import (
"encoding/hex"
"encoding/json"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/mtproto"
)
type MTProtoAccount struct {
Secret string `json:"secret"`
}
// Build implements Buildable
func (a *MTProtoAccount) Build() (*mtproto.Account, error) {
if len(a.Secret) != 32 {
return nil, newError("MTProto secret must have 32 chars")
}
secret, err := hex.DecodeString(a.Secret)
if err != nil {
return nil, newError("failed to decode secret: ", a.Secret).Base(err)
}
return &mtproto.Account{
Secret: secret,
}, nil
}
type MTProtoServerConfig struct {
Users []json.RawMessage `json:"users"`
}
func (c *MTProtoServerConfig) Build() (proto.Message, error) {
config := &mtproto.ServerConfig{}
if len(c.Users) == 0 {
return nil, newError("zero MTProto users configured.")
}
config.User = make([]*protocol.User, len(c.Users))
for idx, rawData := range c.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawData, user); err != nil {
return nil, newError("invalid MTProto user").Base(err)
}
account := new(MTProtoAccount)
if err := json.Unmarshal(rawData, account); err != nil {
return nil, newError("invalid MTProto user").Base(err)
}
accountProto, err := account.Build()
if err != nil {
return nil, newError("failed to parse MTProto user").Base(err)
}
user.Account = serial.ToTypedMessage(accountProto)
config.User[idx] = user
}
return config, nil
}
type MTProtoClientConfig struct {
}
func (c *MTProtoClientConfig) Build() (proto.Message, error) {
config := new(mtproto.ClientConfig)
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/blackhole.go | infra/conf/blackhole.go | package conf
import (
"encoding/json"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/blackhole"
)
type NoneResponse struct{}
func (*NoneResponse) Build() (proto.Message, error) {
return new(blackhole.NoneResponse), nil
}
type HttpResponse struct{}
func (*HttpResponse) Build() (proto.Message, error) {
return new(blackhole.HTTPResponse), nil
}
type BlackholeConfig struct {
Response json.RawMessage `json:"response"`
}
func (v *BlackholeConfig) Build() (proto.Message, error) {
config := new(blackhole.Config)
if v.Response != nil {
response, _, err := configLoader.Load(v.Response)
if err != nil {
return nil, newError("Config: Failed to parse Blackhole response config.").Base(err)
}
responseSettings, err := response.(Buildable).Build()
if err != nil {
return nil, err
}
config.Response = serial.ToTypedMessage(responseSettings)
}
return config, nil
}
var (
configLoader = NewJSONConfigLoader(
ConfigCreatorCache{
"none": func() interface{} { return new(NoneResponse) },
"http": func() interface{} { return new(HttpResponse) },
},
"type",
"")
)
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/freedom_test.go | infra/conf/freedom_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/freedom"
)
func TestFreedomConfig(t *testing.T) {
creator := func() Buildable {
return new(FreedomConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"domainStrategy": "AsIs",
"timeout": 10,
"redirect": "127.0.0.1:3366",
"userLevel": 1
}`,
Parser: loadJSON(creator),
Output: &freedom.Config{
DomainStrategy: freedom.Config_AS_IS,
Timeout: 10,
DestinationOverride: &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 3366,
},
},
UserLevel: 1,
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/http_test.go | infra/conf/http_test.go | package conf_test
import (
"testing"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/http"
)
func TestHttpServerConfig(t *testing.T) {
creator := func() Buildable {
return new(HttpServerConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"timeout": 10,
"accounts": [
{
"user": "my-username",
"pass": "my-password"
}
],
"allowTransparent": true,
"userLevel": 1
}`,
Parser: loadJSON(creator),
Output: &http.ServerConfig{
Accounts: map[string]string{
"my-username": "my-password",
},
AllowTransparent: true,
UserLevel: 1,
Timeout: 10,
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/http.go | infra/conf/http.go | package conf
import (
"encoding/json"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/http"
)
type HttpAccount struct {
Username string `json:"user"`
Password string `json:"pass"`
}
func (v *HttpAccount) Build() *http.Account {
return &http.Account{
Username: v.Username,
Password: v.Password,
}
}
type HttpServerConfig struct {
Timeout uint32 `json:"timeout"`
Accounts []*HttpAccount `json:"accounts"`
Transparent bool `json:"allowTransparent"`
UserLevel uint32 `json:"userLevel"`
}
func (c *HttpServerConfig) Build() (proto.Message, error) {
config := &http.ServerConfig{
Timeout: c.Timeout,
AllowTransparent: c.Transparent,
UserLevel: c.UserLevel,
}
if len(c.Accounts) > 0 {
config.Accounts = make(map[string]string)
for _, account := range c.Accounts {
config.Accounts[account.Username] = account.Password
}
}
return config, nil
}
type HttpRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type HttpClientConfig struct {
Servers []*HttpRemoteConfig `json:"servers"`
}
func (v *HttpClientConfig) Build() (proto.Message, error) {
config := new(http.ClientConfig)
config.Server = make([]*protocol.ServerEndpoint, len(v.Servers))
for idx, serverConfig := range v.Servers {
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError("failed to parse HTTP user").Base(err).AtError()
}
account := new(HttpAccount)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError("failed to parse HTTP account").Base(err).AtError()
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = append(server.User, user)
}
config.Server[idx] = server
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/router_test.go | infra/conf/router_test.go | package conf_test
import (
"encoding/json"
"testing"
"github.com/golang/protobuf/proto"
"v2ray.com/core/app/router"
"v2ray.com/core/common/net"
. "v2ray.com/core/infra/conf"
)
func TestRouterConfig(t *testing.T) {
createParser := func() func(string) (proto.Message, error) {
return func(s string) (proto.Message, error) {
config := new(RouterConfig)
if err := json.Unmarshal([]byte(s), config); err != nil {
return nil, err
}
return config.Build()
}
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"strategy": "rules",
"settings": {
"domainStrategy": "AsIs",
"rules": [
{
"type": "field",
"domain": [
"baidu.com",
"qq.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"]
}
]
}`,
Parser: createParser(),
Output: &router.Config{
DomainStrategy: router.Config_AsIs,
BalancingRule: []*router.BalancingRule{
{
Tag: "b1",
OutboundSelector: []string{"test"},
},
},
Rule: []*router.RoutingRule{
{
Domain: []*router.Domain{
{
Type: router.Domain_Plain,
Value: "baidu.com",
},
{
Type: router.Domain_Plain,
Value: "qq.com",
},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "direct",
},
},
{
Geoip: []*router.GeoIP{
{
Cidr: []*router.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",
"ip": [
"10.0.0.0/8",
"::1/128"
],
"outboundTag": "test"
}
]
}
}`,
Parser: createParser(),
Output: &router.Config{
DomainStrategy: router.Config_IpIfNonMatch,
Rule: []*router.RoutingRule{
{
Domain: []*router.Domain{
{
Type: router.Domain_Plain,
Value: "baidu.com",
},
{
Type: router.Domain_Plain,
Value: "qq.com",
},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "direct",
},
},
{
Geoip: []*router.GeoIP{
{
Cidr: []*router.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",
"ip": [
"10.0.0.0/8",
"::1/128"
],
"outboundTag": "test"
}
]
}`,
Parser: createParser(),
Output: &router.Config{
DomainStrategy: router.Config_AsIs,
Rule: []*router.RoutingRule{
{
Domain: []*router.Domain{
{
Type: router.Domain_Plain,
Value: "baidu.com",
},
{
Type: router.Domain_Plain,
Value: "qq.com",
},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "direct",
},
},
{
Geoip: []*router.GeoIP{
{
Cidr: []*router.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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/freedom.go | infra/conf/freedom.go | package conf
import (
"net"
"strings"
"github.com/golang/protobuf/proto"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/proxy/freedom"
)
type FreedomConfig struct {
DomainStrategy string `json:"domainStrategy"`
Timeout *uint32 `json:"timeout"`
Redirect string `json:"redirect"`
UserLevel uint32 `json:"userLevel"`
}
// Build implements Buildable
func (c *FreedomConfig) Build() (proto.Message, error) {
config := new(freedom.Config)
config.DomainStrategy = freedom.Config_AS_IS
switch strings.ToLower(c.DomainStrategy) {
case "useip", "use_ip":
config.DomainStrategy = freedom.Config_USE_IP
case "useip4", "useipv4", "use_ipv4", "use_ip_v4", "use_ip4":
config.DomainStrategy = freedom.Config_USE_IP4
case "useip6", "useipv6", "use_ipv6", "use_ip_v6", "use_ip6":
config.DomainStrategy = freedom.Config_USE_IP6
}
if c.Timeout != nil {
config.Timeout = *c.Timeout
}
config.UserLevel = c.UserLevel
if len(c.Redirect) > 0 {
host, portStr, err := net.SplitHostPort(c.Redirect)
if err != nil {
return nil, newError("invalid redirect address: ", c.Redirect, ": ", err).Base(err)
}
port, err := v2net.PortFromString(portStr)
if err != nil {
return nil, newError("invalid redirect port: ", c.Redirect, ": ", err).Base(err)
}
config.DestinationOverride = &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{
Port: uint32(port),
},
}
if len(host) > 0 {
config.DestinationOverride.Server.Address = v2net.NewIPOrDomain(v2net.ParseAddress(host))
}
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/trojan.go | infra/conf/trojan.go | package conf
import (
"encoding/json"
"runtime"
"strconv"
"syscall"
"github.com/golang/protobuf/proto" // nolint: staticcheck
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/trojan"
)
// TrojanServerTarget is configuration of a single trojan server
type TrojanServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Password string `json:"password"`
Email string `json:"email"`
Level byte `json:"level"`
}
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
Servers []*TrojanServerTarget `json:"servers"`
}
// Build implements Buildable
func (c *TrojanClientConfig) Build() (proto.Message, error) {
config := new(trojan.ClientConfig)
if len(c.Servers) == 0 {
return nil, newError("0 Trojan server configured.")
}
serverSpecs := make([]*protocol.ServerEndpoint, len(c.Servers))
for idx, rec := range c.Servers {
if rec.Address == nil {
return nil, newError("Trojan server address is not set.")
}
if rec.Port == 0 {
return nil, newError("Invalid Trojan port.")
}
if rec.Password == "" {
return nil, newError("Trojan password is not specified.")
}
account := &trojan.Account{
Password: rec.Password,
}
trojan := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
User: []*protocol.User{
{
Level: uint32(rec.Level),
Email: rec.Email,
Account: serial.ToTypedMessage(account),
},
},
}
serverSpecs[idx] = trojan
}
config.Server = serverSpecs
return config, nil
}
// TrojanInboundFallback is fallback configuration
type TrojanInboundFallback struct {
Alpn string `json:"alpn"`
Path string `json:"path"`
Type string `json:"type"`
Dest json.RawMessage `json:"dest"`
Xver uint64 `json:"xver"`
}
// TrojanUserConfig is user configuration
type TrojanUserConfig struct {
Password string `json:"password"`
Level byte `json:"level"`
Email string `json:"email"`
}
// TrojanServerConfig is Inbound configuration
type TrojanServerConfig struct {
Clients []*TrojanUserConfig `json:"clients"`
Fallback json.RawMessage `json:"fallback"`
Fallbacks []*TrojanInboundFallback `json:"fallbacks"`
}
// Build implements Buildable
func (c *TrojanServerConfig) Build() (proto.Message, error) {
config := new(trojan.ServerConfig)
if len(c.Clients) == 0 {
return nil, newError("No trojan user settings.")
}
config.Users = make([]*protocol.User, len(c.Clients))
for idx, rawUser := range c.Clients {
user := new(protocol.User)
account := &trojan.Account{
Password: rawUser.Password,
}
user.Email = rawUser.Email
user.Level = uint32(rawUser.Level)
user.Account = serial.ToTypedMessage(account)
config.Users[idx] = user
}
if c.Fallback != nil {
return nil, newError(`Trojan settings: please use "fallbacks":[{}] instead of "fallback":{}`)
}
for _, fb := range c.Fallbacks {
var i uint16
var s string
if err := json.Unmarshal(fb.Dest, &i); err == nil {
s = strconv.Itoa(int(i))
} else {
_ = json.Unmarshal(fb.Dest, &s)
}
config.Fallbacks = append(config.Fallbacks, &trojan.Fallback{
Alpn: fb.Alpn,
Path: fb.Path,
Type: fb.Type,
Dest: s,
Xver: fb.Xver,
})
}
for _, fb := range config.Fallbacks {
/*
if fb.Alpn == "h2" && fb.Path != "" {
return nil, newError(`Trojan fallbacks: "alpn":"h2" doesn't support "path"`)
}
*/
if fb.Path != "" && fb.Path[0] != '/' {
return nil, newError(`Trojan fallbacks: "path" must be empty or start with "/"`)
}
if fb.Type == "" && fb.Dest != "" {
if fb.Dest == "serve-ws-none" {
fb.Type = "serve"
} else {
switch fb.Dest[0] {
case '@', '/':
fb.Type = "unix"
if fb.Dest[0] == '@' && len(fb.Dest) > 1 && fb.Dest[1] == '@' && runtime.GOOS == "linux" {
fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path)) // may need padding to work in front of haproxy
copy(fullAddr, fb.Dest[1:])
fb.Dest = string(fullAddr)
}
default:
if _, err := strconv.Atoi(fb.Dest); err == nil {
fb.Dest = "127.0.0.1:" + fb.Dest
}
if _, _, err := net.SplitHostPort(fb.Dest); err == nil {
fb.Type = "tcp"
}
}
}
}
if fb.Type == "" {
return nil, newError(`Trojan fallbacks: please fill in a valid value for every "dest"`)
}
if fb.Xver > 2 {
return nil, newError(`Trojan fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
}
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/shadowsocks_test.go | infra/conf/shadowsocks_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/shadowsocks"
)
func TestShadowsocksServerConfigParsing(t *testing.T) {
creator := func() Buildable {
return new(ShadowsocksServerConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"method": "aes-128-cfb",
"password": "v2ray-password"
}`,
Parser: loadJSON(creator),
Output: &shadowsocks.ServerConfig{
User: &protocol.User{
Account: serial.ToTypedMessage(&shadowsocks.Account{
CipherType: shadowsocks.CipherType_AES_128_CFB,
Password: "v2ray-password",
}),
},
Network: []net.Network{net.Network_TCP},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/blackhole_test.go | infra/conf/blackhole_test.go | package conf_test
import (
"testing"
"v2ray.com/core/common/serial"
. "v2ray.com/core/infra/conf"
"v2ray.com/core/proxy/blackhole"
)
func TestHTTPResponseJSON(t *testing.T) {
creator := func() Buildable {
return new(BlackholeConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"response": {
"type": "http"
}
}`,
Parser: loadJSON(creator),
Output: &blackhole.Config{
Response: serial.ToTypedMessage(&blackhole.HTTPResponse{}),
},
},
{
Input: `{}`,
Parser: loadJSON(creator),
Output: &blackhole.Config{},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/transport_authenticators.go | infra/conf/transport_authenticators.go | package conf
import (
"sort"
"github.com/golang/protobuf/proto"
"v2ray.com/core/transport/internet/headers/http"
"v2ray.com/core/transport/internet/headers/noop"
"v2ray.com/core/transport/internet/headers/srtp"
"v2ray.com/core/transport/internet/headers/tls"
"v2ray.com/core/transport/internet/headers/utp"
"v2ray.com/core/transport/internet/headers/wechat"
"v2ray.com/core/transport/internet/headers/wireguard"
)
type NoOpAuthenticator struct{}
func (NoOpAuthenticator) Build() (proto.Message, error) {
return new(noop.Config), nil
}
type NoOpConnectionAuthenticator struct{}
func (NoOpConnectionAuthenticator) Build() (proto.Message, error) {
return new(noop.ConnectionConfig), nil
}
type SRTPAuthenticator struct{}
func (SRTPAuthenticator) Build() (proto.Message, error) {
return new(srtp.Config), nil
}
type UTPAuthenticator struct{}
func (UTPAuthenticator) Build() (proto.Message, error) {
return new(utp.Config), nil
}
type WechatVideoAuthenticator struct{}
func (WechatVideoAuthenticator) Build() (proto.Message, error) {
return new(wechat.VideoConfig), nil
}
type WireguardAuthenticator struct{}
func (WireguardAuthenticator) Build() (proto.Message, error) {
return new(wireguard.WireguardConfig), nil
}
type DTLSAuthenticator struct{}
func (DTLSAuthenticator) Build() (proto.Message, error) {
return new(tls.PacketConfig), nil
}
type HTTPAuthenticatorRequest struct {
Version string `json:"version"`
Method string `json:"method"`
Path StringList `json:"path"`
Headers map[string]*StringList `json:"headers"`
}
func sortMapKeys(m map[string]*StringList) []string {
var keys []string
for key := range m {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func (v *HTTPAuthenticatorRequest) Build() (*http.RequestConfig, error) {
config := &http.RequestConfig{
Uri: []string{"/"},
Header: []*http.Header{
{
Name: "Host",
Value: []string{"www.baidu.com", "www.bing.com"},
},
{
Name: "User-Agent",
Value: []string{
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46",
},
},
{
Name: "Accept-Encoding",
Value: []string{"gzip, deflate"},
},
{
Name: "Connection",
Value: []string{"keep-alive"},
},
{
Name: "Pragma",
Value: []string{"no-cache"},
},
},
}
if len(v.Version) > 0 {
config.Version = &http.Version{Value: v.Version}
}
if len(v.Method) > 0 {
config.Method = &http.Method{Value: v.Method}
}
if len(v.Path) > 0 {
config.Uri = append([]string(nil), (v.Path)...)
}
if len(v.Headers) > 0 {
config.Header = make([]*http.Header, 0, len(v.Headers))
headerNames := sortMapKeys(v.Headers)
for _, key := range headerNames {
value := v.Headers[key]
if value == nil {
return nil, newError("empty HTTP header value: " + key).AtError()
}
config.Header = append(config.Header, &http.Header{
Name: key,
Value: append([]string(nil), (*value)...),
})
}
}
return config, nil
}
type HTTPAuthenticatorResponse struct {
Version string `json:"version"`
Status string `json:"status"`
Reason string `json:"reason"`
Headers map[string]*StringList `json:"headers"`
}
func (v *HTTPAuthenticatorResponse) Build() (*http.ResponseConfig, error) {
config := &http.ResponseConfig{
Header: []*http.Header{
{
Name: "Content-Type",
Value: []string{"application/octet-stream", "video/mpeg"},
},
{
Name: "Transfer-Encoding",
Value: []string{"chunked"},
},
{
Name: "Connection",
Value: []string{"keep-alive"},
},
{
Name: "Pragma",
Value: []string{"no-cache"},
},
{
Name: "Cache-Control",
Value: []string{"private", "no-cache"},
},
},
}
if len(v.Version) > 0 {
config.Version = &http.Version{Value: v.Version}
}
if len(v.Status) > 0 || len(v.Reason) > 0 {
config.Status = &http.Status{
Code: "200",
Reason: "OK",
}
if len(v.Status) > 0 {
config.Status.Code = v.Status
}
if len(v.Reason) > 0 {
config.Status.Reason = v.Reason
}
}
if len(v.Headers) > 0 {
config.Header = make([]*http.Header, 0, len(v.Headers))
headerNames := sortMapKeys(v.Headers)
for _, key := range headerNames {
value := v.Headers[key]
if value == nil {
return nil, newError("empty HTTP header value: " + key).AtError()
}
config.Header = append(config.Header, &http.Header{
Name: key,
Value: append([]string(nil), (*value)...),
})
}
}
return config, nil
}
type HTTPAuthenticator struct {
Request HTTPAuthenticatorRequest `json:"request"`
Response HTTPAuthenticatorResponse `json:"response"`
}
func (v *HTTPAuthenticator) Build() (proto.Message, error) {
config := new(http.Config)
requestConfig, err := v.Request.Build()
if err != nil {
return nil, err
}
config.Request = requestConfig
responseConfig, err := v.Response.Build()
if err != nil {
return nil, err
}
config.Response = responseConfig
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/transport.go | infra/conf/transport.go | package conf
import (
"v2ray.com/core/common/serial"
"v2ray.com/core/transport"
"v2ray.com/core/transport/internet"
)
type TransportConfig struct {
TCPConfig *TCPConfig `json:"tcpSettings"`
KCPConfig *KCPConfig `json:"kcpSettings"`
WSConfig *WebSocketConfig `json:"wsSettings"`
HTTPConfig *HTTPConfig `json:"httpSettings"`
DSConfig *DomainSocketConfig `json:"dsSettings"`
QUICConfig *QUICConfig `json:"quicSettings"`
}
// Build implements Buildable.
func (c *TransportConfig) Build() (*transport.Config, error) {
config := new(transport.Config)
if c.TCPConfig != nil {
ts, err := c.TCPConfig.Build()
if err != nil {
return nil, newError("failed to build TCP config").Base(err).AtError()
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "tcp",
Settings: serial.ToTypedMessage(ts),
})
}
if c.KCPConfig != nil {
ts, err := c.KCPConfig.Build()
if err != nil {
return nil, newError("failed to build mKCP config").Base(err).AtError()
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "mkcp",
Settings: serial.ToTypedMessage(ts),
})
}
if c.WSConfig != nil {
ts, err := c.WSConfig.Build()
if err != nil {
return nil, newError("failed to build WebSocket config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "websocket",
Settings: serial.ToTypedMessage(ts),
})
}
if c.HTTPConfig != nil {
ts, err := c.HTTPConfig.Build()
if err != nil {
return nil, newError("Failed to build HTTP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "http",
Settings: serial.ToTypedMessage(ts),
})
}
if c.DSConfig != nil {
ds, err := c.DSConfig.Build()
if err != nil {
return nil, newError("Failed to build DomainSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "domainsocket",
Settings: serial.ToTypedMessage(ds),
})
}
if c.QUICConfig != nil {
qs, err := c.QUICConfig.Build()
if err != nil {
return nil, newError("Failed to build QUIC config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "quic",
Settings: serial.ToTypedMessage(qs),
})
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dokodemo.go | infra/conf/dokodemo.go | package conf
import (
"github.com/golang/protobuf/proto"
"v2ray.com/core/proxy/dokodemo"
)
type DokodemoConfig struct {
Host *Address `json:"address"`
PortValue uint16 `json:"port"`
NetworkList *NetworkList `json:"network"`
TimeoutValue uint32 `json:"timeout"`
Redirect bool `json:"followRedirect"`
UserLevel uint32 `json:"userLevel"`
}
func (v *DokodemoConfig) Build() (proto.Message, error) {
config := new(dokodemo.Config)
if v.Host != nil {
config.Address = v.Host.Build()
}
config.Port = uint32(v.PortValue)
config.Networks = v.NetworkList.Build()
config.Timeout = v.TimeoutValue
config.FollowRedirect = v.Redirect
config.UserLevel = v.UserLevel
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/general_test.go | infra/conf/general_test.go | package conf_test
import (
"encoding/json"
"testing"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common"
. "v2ray.com/core/infra/conf"
)
func loadJSON(creator func() 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/dns_proxy.go | infra/conf/dns_proxy.go | package conf
import (
"github.com/golang/protobuf/proto"
"v2ray.com/core/common/net"
"v2ray.com/core/proxy/dns"
)
type DnsOutboundConfig struct {
Network Network `json:"network"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
}
func (c *DnsOutboundConfig) Build() (proto.Message, error) {
config := &dns.Config{
Server: &net.Endpoint{
Network: c.Network.Build(),
Port: uint32(c.Port),
},
}
if c.Address != nil {
config.Server.Address = c.Address.Build()
}
return config, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/common.go | infra/conf/common.go | package conf
import (
"encoding/json"
"os"
"strings"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
)
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 {
switch strings.ToLower(string(v)) {
case "tcp":
return net.Network_TCP
case "udp":
return net.Network_UDP
default:
return net.Network_Unknown
}
}
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)
}
}
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)})
}
}
}
if number != 0 {
list.Range = append(list.Range, PortRange{From: uint32(number), To: uint32(number)})
}
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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/reverse_test.go | infra/conf/reverse_test.go | package conf_test
import (
"testing"
"v2ray.com/core/app/reverse"
"v2ray.com/core/infra/conf"
)
func TestReverseConfig(t *testing.T) {
creator := func() conf.Buildable {
return new(conf.ReverseConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"bridges": [{
"tag": "test",
"domain": "test.v2ray.com"
}]
}`,
Parser: loadJSON(creator),
Output: &reverse.Config{
BridgeConfig: []*reverse.BridgeConfig{
{Tag: "test", Domain: "test.v2ray.com"},
},
},
},
{
Input: `{
"portals": [{
"tag": "test",
"domain": "test.v2ray.com"
}]
}`,
Parser: loadJSON(creator),
Output: &reverse.Config{
PortalConfig: []*reverse.PortalConfig{
{Tag: "test", Domain: "test.v2ray.com"},
},
},
},
})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/command/errors.generated.go | infra/conf/command/errors.generated.go | package command
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/command/command.go | infra/conf/command/command.go | package command
//go:generate go run v2ray.com/core/common/errors/errorgen
import (
"os"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common"
"v2ray.com/core/infra/conf/serial"
"v2ray.com/core/infra/control"
)
type ConfigCommand struct{}
func (c *ConfigCommand) Name() string {
return "config"
}
func (c *ConfigCommand) Description() control.Description {
return control.Description{
Short: "Convert config among different formats.",
Usage: []string{
"v2ctl config",
},
}
}
func (c *ConfigCommand) Execute(args []string) error {
pbConfig, err := serial.LoadJSONConfig(os.Stdin)
if err != nil {
return newError("failed to parse json config").Base(err)
}
bytesConfig, err := proto.Marshal(pbConfig)
if err != nil {
return newError("failed to marshal proto config").Base(err)
}
if _, err := os.Stdout.Write(bytesConfig); err != nil {
return newError("failed to write proto config").Base(err)
}
return nil
}
func init() {
common.Must(control.RegisterCommand(&ConfigCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/json/reader.go | infra/conf/json/reader.go | package json
import (
"io"
"v2ray.com/core/common/buf"
)
// State is the internal state of parser.
type State byte
const (
StateContent State = iota
StateEscape
StateDoubleQuote
StateDoubleQuoteEscape
StateSingleQuote
StateSingleQuoteEscape
StateComment
StateSlash
StateMultilineComment
StateMultilineCommentStar
)
// Reader is a reader for filtering comments.
// It supports Java style single and multi line comment syntax, and Python style single line comment syntax.
type Reader struct {
io.Reader
state State
br *buf.BufferedReader
}
// Read implements io.Reader.Read(). Buffer must be at least 3 bytes.
func (v *Reader) Read(b []byte) (int, error) {
if v.br == nil {
v.br = &buf.BufferedReader{Reader: buf.NewReader(v.Reader)}
}
p := b[:0]
for len(p) < len(b)-2 {
x, err := v.br.ReadByte()
if err != nil {
if len(p) == 0 {
return 0, err
}
return len(p), nil
}
switch v.state {
case StateContent:
switch x {
case '"':
v.state = StateDoubleQuote
p = append(p, x)
case '\'':
v.state = StateSingleQuote
p = append(p, x)
case '\\':
v.state = StateEscape
case '#':
v.state = StateComment
case '/':
v.state = StateSlash
default:
p = append(p, x)
}
case StateEscape:
p = append(p, '\\', x)
v.state = StateContent
case StateDoubleQuote:
switch x {
case '"':
v.state = StateContent
p = append(p, x)
case '\\':
v.state = StateDoubleQuoteEscape
default:
p = append(p, x)
}
case StateDoubleQuoteEscape:
p = append(p, '\\', x)
v.state = StateDoubleQuote
case StateSingleQuote:
switch x {
case '\'':
v.state = StateContent
p = append(p, x)
case '\\':
v.state = StateSingleQuoteEscape
default:
p = append(p, x)
}
case StateSingleQuoteEscape:
p = append(p, '\\', x)
v.state = StateSingleQuote
case StateComment:
if x == '\n' {
v.state = StateContent
p = append(p, '\n')
}
case StateSlash:
switch x {
case '/':
v.state = StateComment
case '*':
v.state = StateMultilineComment
default:
p = append(p, '/', x)
}
case StateMultilineComment:
switch x {
case '*':
v.state = StateMultilineCommentStar
case '\n':
p = append(p, '\n')
}
case StateMultilineCommentStar:
switch x {
case '/':
v.state = StateContent
case '*':
// Stay
case '\n':
p = append(p, '\n')
default:
v.state = StateMultilineComment
}
default:
panic("Unknown state.")
}
}
return len(p), nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/json/reader_test.go | infra/conf/json/reader_test.go | package json_test
import (
"bytes"
"io"
"testing"
"github.com/google/go-cmp/cmp"
"v2ray.com/core/common"
. "v2ray.com/core/infra/conf/json"
)
func TestReader(t *testing.T) {
data := []struct {
input string
output string
}{
{
`
content #comment 1
#comment 2
content 2`,
`
content
content 2`},
{`content`, `content`},
{" ", " "},
{`con/*abcd*/tent`, "content"},
{`
text // adlkhdf /*
//comment adfkj
text 2*/`, `
text
text 2*`},
{`"//"content`, `"//"content`},
{`abcd'//'abcd`, `abcd'//'abcd`},
{`"\""`, `"\""`},
{`\"/*abcd*/\"`, `\"\"`},
}
for _, testCase := range data {
reader := &Reader{
Reader: bytes.NewReader([]byte(testCase.input)),
}
actual := make([]byte, 1024)
n, err := reader.Read(actual)
common.Must(err)
if r := cmp.Diff(string(actual[:n]), testCase.output); r != "" {
t.Error(r)
}
}
}
func TestReader1(t *testing.T) {
type dataStruct struct {
input string
output string
}
bufLen := 8
data := []dataStruct{
{"loooooooooooooooooooooooooooooooooooooooog", "loooooooooooooooooooooooooooooooooooooooog"},
{`{"t": "\/testlooooooooooooooooooooooooooooong"}`, `{"t": "\/testlooooooooooooooooooooooooooooong"}`},
{`{"t": "\/test"}`, `{"t": "\/test"}`},
{`"\// fake comment"`, `"\// fake comment"`},
{`"\/\/\/\/\/"`, `"\/\/\/\/\/"`},
}
for _, testCase := range data {
reader := &Reader{
Reader: bytes.NewReader([]byte(testCase.input)),
}
target := make([]byte, 0)
buf := make([]byte, bufLen)
var n int
var err error
for n, err = reader.Read(buf); err == nil; n, err = reader.Read(buf) {
if n > len(buf) {
t.Error("n: ", n)
}
target = append(target, buf[:n]...)
buf = make([]byte, bufLen)
}
if err != nil && err != io.EOF {
t.Error("error: ", err)
}
if string(target) != testCase.output {
t.Error("got ", string(target), " want ", testCase.output)
}
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/serial/loader.go | infra/conf/serial/loader.go | package serial
import (
"bytes"
"encoding/json"
"io"
"v2ray.com/core"
"v2ray.com/core/common/errors"
"v2ray.com/core/infra/conf"
json_reader "v2ray.com/core/infra/conf/json"
)
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) (*conf.Config, error) {
jsonConfig := &conf.Config{}
jsonContent := bytes.NewBuffer(make([]byte, 0, 10240))
jsonReader := io.TeeReader(&json_reader.Reader{
Reader: reader,
}, jsonContent)
decoder := json.NewDecoder(jsonReader)
if err := decoder.Decode(jsonConfig); 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 nil, newError("failed to read config file at line ", pos.line, " char ", pos.char).Base(err)
}
return nil, newError("failed to read config file").Base(err)
}
return jsonConfig, 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/serial/errors.generated.go | infra/conf/serial/errors.generated.go | package serial
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/serial/serial.go | infra/conf/serial/serial.go | package serial
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/conf/serial/loader_test.go | infra/conf/serial/loader_test.go | package serial_test
import (
"bytes"
"strings"
"testing"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/uuid.go | infra/control/uuid.go | package control
import (
"fmt"
"v2ray.com/core/common"
"v2ray.com/core/common/uuid"
)
type UUIDCommand struct{}
func (c *UUIDCommand) Name() string {
return "uuid"
}
func (c *UUIDCommand) Description() Description {
return Description{
Short: "Generate new UUIDs",
Usage: []string{"v2ctl uuid"},
}
}
func (c *UUIDCommand) Execute([]string) error {
u := uuid.New()
fmt.Println(u.String())
return nil
}
func init() {
common.Must(RegisterCommand(&UUIDCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/verify.go | infra/control/verify.go | package control
import (
"flag"
"github.com/xiaokangwang/VSign/signerVerify"
"os"
"v2ray.com/core/common"
)
type VerifyCommand struct{}
func (c *VerifyCommand) Name() string {
return "verify"
}
func (c *VerifyCommand) Description() Description {
return Description{
Short: "Verify if a binary is officially signed.",
Usage: []string{
"v2ctl verify --sig=<sig-file> file...",
"Verify the file officially signed by V2Ray.",
},
}
}
func (c *VerifyCommand) Execute(args []string) error {
fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
sigFile := fs.String("sig", "", "Path to the signature file")
if err := fs.Parse(args); err != nil {
return err
}
target := fs.Arg(0)
if target == "" {
return newError("empty file path.")
}
if *sigFile == "" {
return newError("empty signature path.")
}
sigReader, err := os.Open(os.ExpandEnv(*sigFile))
if err != nil {
return newError("failed to open file ", *sigFile).Base(err)
}
files := fs.Args()
err = signerVerify.OutputAndJudge(signerVerify.CheckSignaturesV2Fly(sigReader, files))
if err == nil {
return nil
}
return newError("file is not officially signed by V2Ray").Base(err)
}
func init() {
common.Must(RegisterCommand(&VerifyCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/api.go | infra/control/api.go | package control
import (
"context"
"errors"
"flag"
"fmt"
"strings"
"time"
"github.com/golang/protobuf/proto"
"google.golang.org/grpc"
logService "v2ray.com/core/app/log/command"
statsService "v2ray.com/core/app/stats/command"
"v2ray.com/core/common"
)
type ApiCommand struct{}
func (c *ApiCommand) Name() string {
return "api"
}
func (c *ApiCommand) Description() Description {
return Description{
Short: "Call V2Ray API",
Usage: []string{
"v2ctl api [--server=127.0.0.1:8080] Service.Method Request",
"Call an API in an V2Ray process.",
"The following methods are currently supported:",
"\tLoggerService.RestartLogger",
"\tStatsService.GetStats",
"\tStatsService.QueryStats",
"API calls in this command have a timeout to the server of 3 seconds.",
"Examples:",
"v2ctl api --server=127.0.0.1:8080 LoggerService.RestartLogger '' ",
"v2ctl api --server=127.0.0.1:8080 StatsService.QueryStats 'pattern: \"\" reset: false'",
"v2ctl api --server=127.0.0.1:8080 StatsService.GetStats 'name: \"inbound>>>statin>>>traffic>>>downlink\" reset: false'",
"v2ctl api --server=127.0.0.1:8080 StatsService.GetSysStats ''",
},
}
}
func (c *ApiCommand) Execute(args []string) error {
fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
serverAddrPtr := fs.String("server", "127.0.0.1:8080", "Server address")
if err := fs.Parse(args); err != nil {
return err
}
unnamedArgs := fs.Args()
if len(unnamedArgs) < 2 {
return newError("service name or request not specified.")
}
service, method := getServiceMethod(unnamedArgs[0])
handler, found := serivceHandlerMap[strings.ToLower(service)]
if !found {
return newError("unknown service: ", service)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, *serverAddrPtr, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
return newError("failed to dial ", *serverAddrPtr).Base(err)
}
defer conn.Close()
response, err := handler(ctx, conn, method, unnamedArgs[1])
if err != nil {
return newError("failed to call service ", unnamedArgs[0]).Base(err)
}
fmt.Println(response)
return nil
}
func getServiceMethod(s string) (string, string) {
ss := strings.Split(s, ".")
service := ss[0]
var method string
if len(ss) > 1 {
method = ss[1]
}
return service, method
}
type serviceHandler func(ctx context.Context, conn *grpc.ClientConn, method string, request string) (string, error)
var serivceHandlerMap = map[string]serviceHandler{
"statsservice": callStatsService,
"loggerservice": callLogService,
}
func callLogService(ctx context.Context, conn *grpc.ClientConn, method string, request string) (string, error) {
client := logService.NewLoggerServiceClient(conn)
switch strings.ToLower(method) {
case "restartlogger":
r := &logService.RestartLoggerRequest{}
if err := proto.UnmarshalText(request, r); err != nil {
return "", err
}
resp, err := client.RestartLogger(ctx, r)
if err != nil {
return "", err
}
return proto.MarshalTextString(resp), nil
default:
return "", errors.New("Unknown method: " + method)
}
}
func callStatsService(ctx context.Context, conn *grpc.ClientConn, method string, request string) (string, error) {
client := statsService.NewStatsServiceClient(conn)
switch strings.ToLower(method) {
case "getstats":
r := &statsService.GetStatsRequest{}
if err := proto.UnmarshalText(request, r); err != nil {
return "", err
}
resp, err := client.GetStats(ctx, r)
if err != nil {
return "", err
}
return proto.MarshalTextString(resp), nil
case "querystats":
r := &statsService.QueryStatsRequest{}
if err := proto.UnmarshalText(request, r); err != nil {
return "", err
}
resp, err := client.QueryStats(ctx, r)
if err != nil {
return "", err
}
return proto.MarshalTextString(resp), nil
case "getsysstats":
// SysStatsRequest is an empty message
r := &statsService.SysStatsRequest{}
resp, err := client.GetSysStats(ctx, r)
if err != nil {
return "", err
}
return proto.MarshalTextString(resp), nil
default:
return "", errors.New("Unknown method: " + method)
}
}
func init() {
common.Must(RegisterCommand(&ApiCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/errors.generated.go | infra/control/errors.generated.go | package control
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/config.go | infra/control/config.go | package control
import (
"bytes"
"io"
"io/ioutil"
"os"
"strings"
"github.com/golang/protobuf/proto"
"v2ray.com/core/common"
"v2ray.com/core/infra/conf"
"v2ray.com/core/infra/conf/serial"
)
// ConfigCommand is the json to pb convert struct
type ConfigCommand struct{}
// Name for cmd usage
func (c *ConfigCommand) Name() string {
return "config"
}
// Description for help usage
func (c *ConfigCommand) Description() Description {
return Description{
Short: "merge multiple json config",
Usage: []string{"v2ctl config config.json c1.json c2.json <url>.json"},
}
}
// Execute real work here.
func (c *ConfigCommand) Execute(args []string) error {
if len(args) < 1 {
return newError("empty config list")
}
conf := &conf.Config{}
for _, arg := range args {
ctllog.Println("Read config: ", arg)
r, err := c.LoadArg(arg)
common.Must(err)
c, err := serial.DecodeJSONConfig(r)
if err != nil {
ctllog.Fatalln(err)
}
conf.Override(c, arg)
}
pbConfig, err := conf.Build()
if err != nil {
return err
}
bytesConfig, err := proto.Marshal(pbConfig)
if err != nil {
return newError("failed to marshal proto config").Base(err)
}
if _, err := os.Stdout.Write(bytesConfig); err != nil {
return newError("failed to write proto config").Base(err)
}
return nil
}
// LoadArg loads one arg, maybe an remote url, or local file path
func (c *ConfigCommand) LoadArg(arg string) (out io.Reader, err error) {
var data []byte
if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
data, err = FetchHTTPContent(arg)
} else if arg == "stdin:" {
data, err = ioutil.ReadAll(os.Stdin)
} else {
data, err = ioutil.ReadFile(arg)
}
if err != nil {
return
}
out = bytes.NewBuffer(data)
return
}
func init() {
common.Must(RegisterCommand(&ConfigCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/tlsping.go | infra/control/tlsping.go | package control
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"net"
"v2ray.com/core/common"
)
type TlsPingCommand struct{}
func (c *TlsPingCommand) Name() string {
return "tlsping"
}
func (c *TlsPingCommand) Description() Description {
return Description{
Short: "Ping the domain with TLS handshake",
Usage: []string{"v2ctl tlsping <domain> --ip <ip>"},
}
}
func printCertificates(certs []*x509.Certificate) {
for _, cert := range certs {
if len(cert.DNSNames) == 0 {
continue
}
fmt.Println("Allowed domains: ", cert.DNSNames)
}
}
func (c *TlsPingCommand) Execute(args []string) error {
fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
ipStr := fs.String("ip", "", "IP address of the domain")
if err := fs.Parse(args); err != nil {
return newError("flag parsing").Base(err)
}
if fs.NArg() < 1 {
return newError("domain not specified")
}
domain := fs.Arg(0)
fmt.Println("Tls ping: ", domain)
var ip net.IP
if len(*ipStr) > 0 {
v := net.ParseIP(*ipStr)
if v == nil {
return newError("invalid IP: ", *ipStr)
}
ip = v
} else {
v, err := net.ResolveIPAddr("ip", domain)
if err != nil {
return newError("resolve IP").Base(err)
}
ip = v.IP
}
fmt.Println("Using IP: ", ip.String())
fmt.Println("-------------------")
fmt.Println("Pinging without SNI")
{
tcpConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: 443})
if err != nil {
return newError("dial tcp").Base(err)
}
tlsConn := tls.Client(tcpConn, &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"http/1.1"},
MaxVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS12,
})
err = tlsConn.Handshake()
if err != nil {
fmt.Println("Handshake failure: ", err)
} else {
fmt.Println("Handshake succeeded")
printCertificates(tlsConn.ConnectionState().PeerCertificates)
}
tlsConn.Close()
}
fmt.Println("-------------------")
fmt.Println("Pinging with SNI")
{
tcpConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: 443})
if err != nil {
return newError("dial tcp").Base(err)
}
tlsConn := tls.Client(tcpConn, &tls.Config{
ServerName: domain,
NextProtos: []string{"http/1.1"},
MaxVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS12,
})
err = tlsConn.Handshake()
if err != nil {
fmt.Println("handshake failure: ", err)
} else {
fmt.Println("handshake succeeded")
printCertificates(tlsConn.ConnectionState().PeerCertificates)
}
tlsConn.Close()
}
fmt.Println("Tls ping finished")
return nil
}
func init() {
common.Must(RegisterCommand(&TlsPingCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/fetch.go | infra/control/fetch.go | package control
import (
"net/http"
"net/url"
"os"
"strings"
"time"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
)
type FetchCommand struct{}
func (c *FetchCommand) Name() string {
return "fetch"
}
func (c *FetchCommand) Description() Description {
return Description{
Short: "Fetch resources",
Usage: []string{"v2ctl fetch <url>"},
}
}
func (c *FetchCommand) Execute(args []string) error {
if len(args) < 1 {
return newError("empty url")
}
content, err := FetchHTTPContent(args[0])
if err != nil {
return newError("failed to read HTTP response").Base(err)
}
os.Stdout.Write(content)
return nil
}
// FetchHTTPContent dials https 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 != 200 {
return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
}
content, err := buf.ReadAllToBytes(resp.Body)
if err != nil {
return nil, newError("failed to read HTTP response").Base(err)
}
return content, nil
}
func init() {
common.Must(RegisterCommand(&FetchCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/control.go | infra/control/control.go | package control
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/cert.go | infra/control/cert.go | package control
import (
"context"
"crypto/x509"
"encoding/json"
"flag"
"os"
"strings"
"time"
"v2ray.com/core/common"
"v2ray.com/core/common/protocol/tls/cert"
"v2ray.com/core/common/task"
)
type stringList []string
func (l *stringList) String() string {
return "String list"
}
func (l *stringList) Set(v string) error {
if v == "" {
return newError("empty value")
}
*l = append(*l, v)
return nil
}
type jsonCert struct {
Certificate []string `json:"certificate"`
Key []string `json:"key"`
}
type CertificateCommand struct {
}
func (c *CertificateCommand) Name() string {
return "cert"
}
func (c *CertificateCommand) Description() Description {
return Description{
Short: "Generate TLS certificates.",
Usage: []string{
"v2ctl cert [--ca] [--domain=v2ray.com] [--expire=240h]",
"Generate new TLS certificate",
"--ca The new certificate is a CA certificate",
"--domain Common name for the certificate",
"--expire Time until certificate expires. 240h = 10 days.",
},
}
}
func (c *CertificateCommand) printJson(certificate *cert.Certificate) {
certPEM, keyPEM := certificate.ToPEM()
jCert := &jsonCert{
Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"),
Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"),
}
content, err := json.MarshalIndent(jCert, "", " ")
common.Must(err)
os.Stdout.Write(content)
os.Stdout.WriteString("\n")
}
func (c *CertificateCommand) writeFile(content []byte, name string) error {
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
return common.Error2(f.Write(content))
}
func (c *CertificateCommand) printFile(certificate *cert.Certificate, name string) error {
certPEM, keyPEM := certificate.ToPEM()
return task.Run(context.Background(), func() error {
return c.writeFile(certPEM, name+"_cert.pem")
}, func() error {
return c.writeFile(keyPEM, name+"_key.pem")
})
}
func (c *CertificateCommand) Execute(args []string) error {
fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
var domainNames stringList
fs.Var(&domainNames, "domain", "Domain name for the certificate")
commonName := fs.String("name", "V2Ray Inc", "The common name of this certificate")
organization := fs.String("org", "V2Ray Inc", "Organization of the certificate")
isCA := fs.Bool("ca", false, "Whether this certificate is a CA")
jsonOutput := fs.Bool("json", true, "Print certificate in JSON format")
fileOutput := fs.String("file", "", "Save certificate in file.")
expire := fs.Duration("expire", time.Hour*24*90 /* 90 days */, "Time until the certificate expires. Default value 3 months.")
if err := fs.Parse(args); err != nil {
return err
}
var opts []cert.Option
if *isCA {
opts = append(opts, cert.Authority(*isCA))
opts = append(opts, cert.KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature))
}
opts = append(opts, cert.NotAfter(time.Now().Add(*expire)))
opts = append(opts, cert.CommonName(*commonName))
if len(domainNames) > 0 {
opts = append(opts, cert.DNSNames(domainNames...))
}
opts = append(opts, cert.Organization(*organization))
cert, err := cert.Generate(nil, opts...)
if err != nil {
return newError("failed to generate TLS certificate").Base(err)
}
if *jsonOutput {
c.printJson(cert)
}
if len(*fileOutput) > 0 {
if err := c.printFile(cert, *fileOutput); err != nil {
return err
}
}
return nil
}
func init() {
common.Must(RegisterCommand(&CertificateCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/command.go | infra/control/command.go | package control
import (
"fmt"
"log"
"os"
"strings"
)
type Description struct {
Short string
Usage []string
}
type Command interface {
Name() string
Description() Description
Execute(args []string) error
}
var (
commandRegistry = make(map[string]Command)
ctllog = log.New(os.Stderr, "v2ctl> ", 0)
)
func RegisterCommand(cmd Command) error {
entry := strings.ToLower(cmd.Name())
if entry == "" {
return newError("empty command name")
}
commandRegistry[entry] = cmd
return nil
}
func GetCommand(name string) Command {
cmd, found := commandRegistry[name]
if !found {
return nil
}
return cmd
}
type hiddenCommand interface {
Hidden() bool
}
func PrintUsage() {
for name, cmd := range commandRegistry {
if _, ok := cmd.(hiddenCommand); ok {
continue
}
fmt.Println(" ", name, "\t\t\t", cmd.Description())
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/love.go | infra/control/love.go | package control
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"v2ray.com/core/common"
"v2ray.com/core/common/platform"
)
const content = "H4sIAAAAAAAC/4SVMaskNwzH+/kUW6izcSthMGrcqLhVk0rdQS5cSMg7Xu4S0vizB8meZd57M3ta2GHX/ukvyZZmY2ZKDMzCzJyY5yOlxKII1omsf+qkBiiC6WhbYsbkjDAfySQsJqD3jtrD0EBM3sBHzG3kUsrglIQREXonpd47kYIi4AHmgI9Wcq2jlJITC6JZJ+v3ECYzBMAHyYm392yuY4zWsjACmHZSh6l3A0JETzGlWZqDsnArpTg62mhJONhOdO90p97V1BAnteoaOcuummtrrtuERQwUiJwP8a4KGKcyxdOCw1spOY+WHueFqmakAIgUSSuhwKNgobxKXSLbtg6r5cFmBiAeF6yCkYycmv+BiCIiW8ScHa3DgxAuZQbRhFNrLTFo96RBmx9jKWWG5nBsjyJzuIkftUblonppZU5t5LzwIks5L1a4lijagQxLokbIYwxfytNDC+XQqrWW9fzAunhqh5/Tg8PuaMw0d/Tcw3iDO81bHfWM/AnutMh2xqSUntMzd3wHDy9iHMQz8bmUZYvqedTJ5GgOnrNt7FIbSlwXE3wDI19n/KA38MsLaP4l89b5F8AV3ESOMIEhIBgezHBc0H6xV9KbaXwMvPcNvIHcC0C7UPZQx4JVTb35/AneSQq+bAYXsBmY7TCRupF2NTdVm/+ch22xa0pvRERKqt1oxj9DUbXzU84Gvj5hc5a81SlAUwMwgEs4T9+7sg9lb9h+908MWiKV8xtWciVTmnB3tivRjNerfXdxpfEBbq2NUvLMM5R9NLuyQg8nXT0PIh1xPd/wrcV49oJ6zbZaPlj2V87IY9T3F2XCOcW2MbZyZd49H+9m81E1N9SxlU+ff/1y+/f3719vf7788+Ugv/ffbMIH7ZNj0dsT4WMHHwLPu/Rp2O75uh99AK+N2xn7ZHq1OK6gczkN+9ngdOl1Qvki5xwSR8vFX6D+9vXA97B/+fr5rz9u/738uP328urP19vfP759e3n9Xs6jamvqlfJ/AAAA//+YAMZjDgkAAA=="
type LoveCommand struct{}
func (*LoveCommand) Name() string {
return "lovevictoria"
}
func (*LoveCommand) Hidden() bool {
return false
}
func (c *LoveCommand) Description() Description {
return Description{
Short: "",
Usage: []string{""},
}
}
func (*LoveCommand) Execute([]string) error {
c, err := base64.StdEncoding.DecodeString(content)
common.Must(err)
reader, err := gzip.NewReader(bytes.NewBuffer(c))
common.Must(err)
b := make([]byte, 4096)
nBytes, _ := reader.Read(b)
bb := bytes.NewBuffer(b[:nBytes])
scanner := bufio.NewScanner(bb)
for scanner.Scan() {
s := scanner.Text()
fmt.Print(s + platform.LineSeparator())
}
return nil
}
func init() {
common.Must(RegisterCommand(&LoveCommand{}))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/infra/control/main/main.go | infra/control/main/main.go | package main
import (
"flag"
"fmt"
"os"
commlog "v2ray.com/core/common/log"
// _ "v2ray.com/core/infra/conf/command"
"v2ray.com/core/infra/control"
)
func getCommandName() string {
if len(os.Args) > 1 {
return os.Args[1]
}
return ""
}
func main() {
// let the v2ctl prints log at stderr
commlog.RegisterHandler(commlog.NewLogger(commlog.CreateStderrLogWriter()))
name := getCommandName()
cmd := control.GetCommand(name)
if cmd == nil {
fmt.Fprintln(os.Stderr, "Unknown command:", name)
fmt.Fprintln(os.Stderr)
fmt.Println("v2ctl <command>")
fmt.Println("Available commands:")
control.PrintUsage()
return
}
if err := cmd.Execute(os.Args[2:]); err != nil {
hasError := false
if err != flag.ErrHelp {
fmt.Fprintln(os.Stderr, err.Error())
fmt.Fprintln(os.Stderr)
hasError = true
}
for _, line := range cmd.Description().Usage {
fmt.Println(line)
}
if hasError {
os.Exit(-1)
}
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/errors.generated.go | features/errors.generated.go | package features
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/feature.go | features/feature.go | package features
import "v2ray.com/core/common"
//go:generate go run v2ray.com/core/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()
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/router.go | features/routing/router.go | package routing
import (
"v2ray.com/core/common"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/dispatcher.go | features/routing/dispatcher.go | package routing
import (
"context"
"v2ray.com/core/common/net"
"v2ray.com/core/features"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/context.go | features/routing/context.go | package routing
import (
"v2ray.com/core/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 conneciont content.
GetAttributes() map[string]string
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/session/context.go | features/routing/session/context.go | package session
import (
"context"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
"v2ray.com/core/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
}
// 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/dns/errors.generated.go | features/routing/dns/errors.generated.go | package dns
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/routing/dns/context.go | features/routing/dns/context.go | package dns
//go:generate go run v2ray.com/core/common/errors/errorgen
import (
"v2ray.com/core/common/net"
"v2ray.com/core/features/dns"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/stats/stats.go | features/stats/stats.go | package stats
//go:generate go run v2ray.com/core/common/errors/errorgen
import (
"context"
"v2ray.com/core/common"
"v2ray.com/core/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 unsubcribes 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/stats/errors.generated.go | features/stats/errors.generated.go | package stats
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/dns/client.go | features/dns/client.go | package dns
import (
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/common/serial"
"v2ray.com/core/features"
)
// 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)
}
// 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/dns/localdns/client.go | features/dns/localdns/client.go | package localdns
import (
"v2ray.com/core/common/net"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/outbound/outbound.go | features/outbound/outbound.go | package outbound
import (
"context"
"v2ray.com/core/common"
"v2ray.com/core/features"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/inbound/inbound.go | features/inbound/inbound.go | package inbound
import (
"context"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/features/policy/policy.go | features/policy/policy.go | package policy
import (
"context"
"runtime"
"time"
"v2ray.com/core/common/platform"
"v2ray.com/core/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
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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/common_test.go | common/common_test.go | package common_test
import (
"errors"
"testing"
. "v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/type_test.go | common/type_test.go | package common_test
import (
"context"
"testing"
. "v2ray.com/core/common"
)
type TConfig struct {
value int
}
type YConfig struct {
value string
}
func TestObjectCreation(t *testing.T) {
var 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/errors.generated.go | common/errors.generated.go | package common
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/interfaces.go | common/interfaces.go | package common
import "v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/type.go | common/type.go | package common
import (
"context"
"reflect"
)
// 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
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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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/ioutil"
"os"
"path/filepath"
"strings"
"v2ray.com/core/common/errors"
)
//go:generate go run v2ray.com/core/common/errors/errorgen
var (
// 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.
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 := ioutil.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
}
// GetModuleName returns the value of module in `go.mod` file.
func GetModuleName(pathToProjectRoot string) (string, error) {
var moduleName string
loopPath := pathToProjectRoot
for {
if idx := strings.LastIndex(loopPath, string(filepath.Separator)); idx >= 0 {
gomodPath := filepath.Join(loopPath, "go.mod")
gomodBytes, err := ioutil.ReadFile(gomodPath)
if err != nil {
loopPath = loopPath[:idx]
continue
}
gomodContent := string(gomodBytes)
moduleIdx := strings.Index(gomodContent, "module ")
newLineIdx := strings.Index(gomodContent, "\n")
if moduleIdx >= 0 {
if newLineIdx >= 0 {
moduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx])
moduleName = strings.TrimSuffix(moduleName, "\r")
} else {
moduleName = strings.TrimSpace(gomodContent[moduleIdx+6:])
}
return moduleName, nil
}
return "", fmt.Errorf("can not get module path in `%s`", gomodPath)
}
break
}
return moduleName, fmt.Errorf("no `go.mod` file in every parent directory of `%s`", pathToProjectRoot)
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/antireplay/antireplay.go | common/antireplay/antireplay.go | package antireplay
import (
cuckoo "github.com/seiflotfy/cuckoofilter"
"sync"
"time"
)
func NewAntiReplayWindow(AntiReplayTime int64) *AntiReplayWindow {
arw := &AntiReplayWindow{}
arw.AntiReplayTime = AntiReplayTime
return arw
}
type AntiReplayWindow struct {
lock sync.Mutex
poolA *cuckoo.Filter
poolB *cuckoo.Filter
lastSwapTime int64
PoolSwap bool
AntiReplayTime int64
}
func (aw *AntiReplayWindow) Check(sum []byte) bool {
aw.lock.Lock()
if aw.lastSwapTime == 0 {
aw.lastSwapTime = time.Now().Unix()
aw.poolA = cuckoo.NewFilter(100000)
aw.poolB = cuckoo.NewFilter(100000)
}
tnow := time.Now().Unix()
timediff := tnow - aw.lastSwapTime
if timediff >= aw.AntiReplayTime {
if aw.PoolSwap {
aw.PoolSwap = false
aw.poolA.Reset()
} else {
aw.PoolSwap = true
aw.poolB.Reset()
}
aw.lastSwapTime = tnow
}
ret := aw.poolA.InsertUnique(sum) && aw.poolB.InsertUnique(sum)
aw.lock.Unlock()
return ret
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/bitmask/byte_test.go | common/bitmask/byte_test.go | package bitmask_test
import (
"testing"
. "v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/errors/errors_test.go | common/errors/errors_test.go | package errors_test
import (
"io"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
. "v2ray.com/core/common/errors"
"v2ray.com/core/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: "v2ray.com/core/common/errors_test: a > b",
},
{
err: New("a").Base(New("b").WithPathObj(e{})),
msg: "a > v2ray.com/core/common/errors_test: b",
},
}
for _, d := range data {
if diff := cmp.Diff(d.msg, d.err.Error()); diff != "" {
t.Error(diff)
}
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/errors/errors.go | common/errors/errors.go | // Package errors is a drop-in replacement for Golang lib 'errors'.
package errors // import "v2ray.com/core/common/errors"
import (
"os"
"reflect"
"strings"
"v2ray.com/core/common/log"
"v2ray.com/core/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 ""
}
return reflect.TypeOf(err.pathObj).PkgPath()
}
// 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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/errors/errorgen/main.go | common/errors/errorgen/main.go | package main
import (
"fmt"
"log"
"os"
"path/filepath"
"v2ray.com/core/common"
)
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"
}
moduleName, gmnErr := common.GetModuleName(pwd)
if gmnErr != nil {
fmt.Println("can not get module path", gmnErr)
os.Exit(1)
}
file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
log.Fatalf("Failed to generate errors.generated.go: %v", err)
os.Exit(1)
}
defer file.Close()
fmt.Fprintln(file, "package", pkg)
fmt.Fprintln(file, "")
fmt.Fprintln(file, "import \""+moduleName+"/common/errors\"")
fmt.Fprintln(file, "")
fmt.Fprintln(file, "type errPathObjHolder struct{}")
fmt.Fprintln(file, "")
fmt.Fprintln(file, "func newError(values ...interface{}) *errors.Error {")
fmt.Fprintln(file, " return errors.New(values...).WithPathObj(errPathObjHolder{})")
fmt.Fprintln(file, "}")
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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"
"v2ray.com/core/common"
. "v2ray.com/core/common/buf"
"v2ray.com/core/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/readv_posix.go | common/buf/readv_posix.go | // +build !windows
// +build !wasm
// +build !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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/errors.generated.go | common/buf/errors.generated.go | package buf
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/buffer.go | common/buf/buffer.go | package buf
import (
"io"
"v2ray.com/core/common/bytespool"
)
const (
// Size of a regular buffer.
Size = 2048
)
// Buffer is a recyclable allocation of a byte array. Buffer.Release() recycles
// the buffer into an internal buffer pool, in order to recreate a buffer more
// quickly.
type Buffer struct {
v []byte
start int32
end int32
}
// Release recycles the buffer into an internal buffer pool.
func (b *Buffer) Release() {
if b == nil || b.v == nil {
return
}
p := b.v
b.v = nil
b.Clear()
pool.Put(p)
}
// Clear clears the content of the buffer, results an empty buffer with
// Len() = 0.
func (b *Buffer) Clear() {
b.start = 0
b.end = 0
}
// Byte returns the bytes at index.
func (b *Buffer) Byte(index int32) byte {
return b.v[b.start+index]
}
// SetByte sets the byte value at index.
func (b *Buffer) SetByte(index int32, value byte) {
b.v[b.start+index] = value
}
// Bytes returns the content bytes of this Buffer.
func (b *Buffer) Bytes() []byte {
return b.v[b.start:b.end]
}
// Extend increases the buffer size by n bytes, and returns the extended part.
// It panics if result size is larger than buf.Size.
func (b *Buffer) Extend(n int32) []byte {
end := b.end + n
if end > int32(len(b.v)) {
panic("extending out of bound")
}
ext := b.v[b.end:end]
b.end = end
return ext
}
// BytesRange returns a slice of this buffer with given from and to boundary.
func (b *Buffer) BytesRange(from, to int32) []byte {
if from < 0 {
from += b.Len()
}
if to < 0 {
to += b.Len()
}
return b.v[b.start+from : b.start+to]
}
// BytesFrom returns a slice of this Buffer starting from the given position.
func (b *Buffer) BytesFrom(from int32) []byte {
if from < 0 {
from += b.Len()
}
return b.v[b.start+from : b.end]
}
// BytesTo returns a slice of this Buffer from start to the given position.
func (b *Buffer) BytesTo(to int32) []byte {
if to < 0 {
to += b.Len()
}
return b.v[b.start : b.start+to]
}
// Resize cuts the buffer at the given position.
func (b *Buffer) Resize(from, to int32) {
if from < 0 {
from += b.Len()
}
if to < 0 {
to += b.Len()
}
if to < from {
panic("Invalid slice")
}
b.end = b.start + to
b.start += from
}
// Advance cuts the buffer at the given position.
func (b *Buffer) Advance(from int32) {
if from < 0 {
from += b.Len()
}
b.start += from
}
// Len returns the length of the buffer content.
func (b *Buffer) Len() int32 {
if b == nil {
return 0
}
return b.end - b.start
}
// IsEmpty returns true if the buffer is empty.
func (b *Buffer) IsEmpty() bool {
return b.Len() == 0
}
// IsFull returns true if the buffer has no more room to grow.
func (b *Buffer) IsFull() bool {
return b != nil && b.end == int32(len(b.v))
}
// Write implements Write method in io.Writer.
func (b *Buffer) Write(data []byte) (int, error) {
nBytes := copy(b.v[b.end:], data)
b.end += int32(nBytes)
return nBytes, nil
}
// WriteByte writes a single byte into the buffer.
func (b *Buffer) WriteByte(v byte) error {
if b.IsFull() {
return newError("buffer full")
}
b.v[b.end] = v
b.end++
return nil
}
// WriteString implements io.StringWriter.
func (b *Buffer) WriteString(s string) (int, error) {
return b.Write([]byte(s))
}
// Read implements io.Reader.Read().
func (b *Buffer) Read(data []byte) (int, error) {
if b.Len() == 0 {
return 0, io.EOF
}
nBytes := copy(data, b.v[b.start:b.end])
if int32(nBytes) == b.Len() {
b.Clear()
} else {
b.start += int32(nBytes)
}
return nBytes, nil
}
// ReadFrom implements io.ReaderFrom.
func (b *Buffer) ReadFrom(reader io.Reader) (int64, error) {
n, err := reader.Read(b.v[b.end:])
b.end += int32(n)
return int64(n), err
}
// ReadFullFrom reads exact size of bytes from given reader, or until error occurs.
func (b *Buffer) ReadFullFrom(reader io.Reader, size int32) (int64, error) {
end := b.end + size
if end > int32(len(b.v)) {
v := end
return 0, newError("out of bound: ", v)
}
n, err := io.ReadFull(reader, b.v[b.end:end])
b.end += int32(n)
return int64(n), err
}
// String returns the string form of this Buffer.
func (b *Buffer) String() string {
return string(b.Bytes())
}
var pool = bytespool.GetPool(Size)
// New creates a Buffer with 0 length and 2K capacity.
func New() *Buffer {
return &Buffer{
v: pool.Get().([]byte),
}
}
// StackNew creates a new Buffer object on stack.
// This method is for buffers that is released in the same function.
func StackNew() Buffer {
return Buffer{
v: pool.Get().([]byte),
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/multi_buffer.go | common/buf/multi_buffer.go | package buf
import (
"io"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/serial"
)
// ReadAllToBytes reads all content from the reader into a byte array, until EOF.
func ReadAllToBytes(reader io.Reader) ([]byte, error) {
mb, err := ReadFrom(reader)
if err != nil {
return nil, err
}
if mb.Len() == 0 {
return nil, nil
}
b := make([]byte, mb.Len())
mb, _ = SplitBytes(mb, b)
ReleaseMulti(mb)
return b, nil
}
// MultiBuffer is a list of Buffers. The order of Buffer matters.
type MultiBuffer []*Buffer
// MergeMulti merges content from src to dest, and returns the new address of dest and src
func MergeMulti(dest MultiBuffer, src MultiBuffer) (MultiBuffer, MultiBuffer) {
dest = append(dest, src...)
for idx := range src {
src[idx] = nil
}
return dest, src[:0]
}
// MergeBytes merges the given bytes into MultiBuffer and return the new address of the merged MultiBuffer.
func MergeBytes(dest MultiBuffer, src []byte) MultiBuffer {
n := len(dest)
if n > 0 && !(dest)[n-1].IsFull() {
nBytes, _ := (dest)[n-1].Write(src)
src = src[nBytes:]
}
for len(src) > 0 {
b := New()
nBytes, _ := b.Write(src)
src = src[nBytes:]
dest = append(dest, b)
}
return dest
}
// ReleaseMulti release all content of the MultiBuffer, and returns an empty MultiBuffer.
func ReleaseMulti(mb MultiBuffer) MultiBuffer {
for i := range mb {
mb[i].Release()
mb[i] = nil
}
return mb[:0]
}
// Copy copied the beginning part of the MultiBuffer into the given byte array.
func (mb MultiBuffer) Copy(b []byte) int {
total := 0
for _, bb := range mb {
nBytes := copy(b[total:], bb.Bytes())
total += nBytes
if int32(nBytes) < bb.Len() {
break
}
}
return total
}
// ReadFrom reads all content from reader until EOF.
func ReadFrom(reader io.Reader) (MultiBuffer, error) {
mb := make(MultiBuffer, 0, 16)
for {
b := New()
_, err := b.ReadFullFrom(reader, Size)
if b.IsEmpty() {
b.Release()
} else {
mb = append(mb, b)
}
if err != nil {
if errors.Cause(err) == io.EOF || errors.Cause(err) == io.ErrUnexpectedEOF {
return mb, nil
}
return mb, err
}
}
}
// SplitBytes splits the given amount of bytes from the beginning of the MultiBuffer.
// It returns the new address of MultiBuffer leftover, and number of bytes written into the input byte slice.
func SplitBytes(mb MultiBuffer, b []byte) (MultiBuffer, int) {
totalBytes := 0
endIndex := -1
for i := range mb {
pBuffer := mb[i]
nBytes, _ := pBuffer.Read(b)
totalBytes += nBytes
b = b[nBytes:]
if !pBuffer.IsEmpty() {
endIndex = i
break
}
pBuffer.Release()
mb[i] = nil
}
if endIndex == -1 {
mb = mb[:0]
} else {
mb = mb[endIndex:]
}
return mb, totalBytes
}
// SplitFirstBytes splits the first buffer from MultiBuffer, and then copy its content into the given slice.
func SplitFirstBytes(mb MultiBuffer, p []byte) (MultiBuffer, int) {
mb, b := SplitFirst(mb)
if b == nil {
return mb, 0
}
n := copy(p, b.Bytes())
b.Release()
return mb, n
}
// Compact returns another MultiBuffer by merging all content of the given one together.
func Compact(mb MultiBuffer) MultiBuffer {
if len(mb) == 0 {
return mb
}
mb2 := make(MultiBuffer, 0, len(mb))
last := mb[0]
for i := 1; i < len(mb); i++ {
curr := mb[i]
if last.Len()+curr.Len() > Size {
mb2 = append(mb2, last)
last = curr
} else {
common.Must2(last.ReadFrom(curr))
curr.Release()
}
}
mb2 = append(mb2, last)
return mb2
}
// SplitFirst splits the first Buffer from the beginning of the MultiBuffer.
func SplitFirst(mb MultiBuffer) (MultiBuffer, *Buffer) {
if len(mb) == 0 {
return mb, nil
}
b := mb[0]
mb[0] = nil
mb = mb[1:]
return mb, b
}
// SplitSize splits the beginning of the MultiBuffer into another one, for at most size bytes.
func SplitSize(mb MultiBuffer, size int32) (MultiBuffer, MultiBuffer) {
if len(mb) == 0 {
return mb, nil
}
if mb[0].Len() > size {
b := New()
copy(b.Extend(size), mb[0].BytesTo(size))
mb[0].Advance(size)
return mb, MultiBuffer{b}
}
totalBytes := int32(0)
var r MultiBuffer
endIndex := -1
for i := range mb {
if totalBytes+mb[i].Len() > size {
endIndex = i
break
}
totalBytes += mb[i].Len()
r = append(r, mb[i])
mb[i] = nil
}
if endIndex == -1 {
// To reuse mb array
mb = mb[:0]
} else {
mb = mb[endIndex:]
}
return mb, r
}
// WriteMultiBuffer writes all buffers from the MultiBuffer to the Writer one by one, and return error if any, with leftover MultiBuffer.
func WriteMultiBuffer(writer io.Writer, mb MultiBuffer) (MultiBuffer, error) {
for {
mb2, b := SplitFirst(mb)
mb = mb2
if b == nil {
break
}
_, err := writer.Write(b.Bytes())
b.Release()
if err != nil {
return mb, err
}
}
return nil, nil
}
// Len returns the total number of bytes in the MultiBuffer.
func (mb MultiBuffer) Len() int32 {
if mb == nil {
return 0
}
size := int32(0)
for _, b := range mb {
size += b.Len()
}
return size
}
// IsEmpty return true if the MultiBuffer has no content.
func (mb MultiBuffer) IsEmpty() bool {
for _, b := range mb {
if !b.IsEmpty() {
return false
}
}
return true
}
// String returns the content of the MultiBuffer in string.
func (mb MultiBuffer) String() string {
v := make([]interface{}, len(mb))
for i, b := range mb {
v[i] = b
}
return serial.Concat(v...)
}
// MultiBufferContainer is a ReadWriteCloser wrapper over MultiBuffer.
type MultiBufferContainer struct {
MultiBuffer
}
// Read implements io.Reader.
func (c *MultiBufferContainer) Read(b []byte) (int, error) {
if c.MultiBuffer.IsEmpty() {
return 0, io.EOF
}
mb, nBytes := SplitBytes(c.MultiBuffer, b)
c.MultiBuffer = mb
return nBytes, nil
}
// ReadMultiBuffer implements Reader.
func (c *MultiBufferContainer) ReadMultiBuffer() (MultiBuffer, error) {
mb := c.MultiBuffer
c.MultiBuffer = nil
return mb, nil
}
// Write implements io.Writer.
func (c *MultiBufferContainer) Write(b []byte) (int, error) {
c.MultiBuffer = MergeBytes(c.MultiBuffer, b)
return len(b), nil
}
// WriteMultiBuffer implement Writer.
func (c *MultiBufferContainer) WriteMultiBuffer(b MultiBuffer) error {
mb, _ := MergeMulti(c.MultiBuffer, b)
c.MultiBuffer = mb
return nil
}
// Close implement io.Closer.
func (c *MultiBufferContainer) Close() error {
c.MultiBuffer = ReleaseMulti(c.MultiBuffer)
return nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/io_test.go | common/buf/io_test.go | package buf_test
import (
"crypto/tls"
"io"
"testing"
. "v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
"v2ray.com/core/testing/servers/tcp"
)
func TestWriterCreation(t *testing.T) {
tcpServer := tcp.Server{}
dest, err := tcpServer.Start()
if err != nil {
t.Fatal("failed to start tcp server: ", err)
}
defer tcpServer.Close()
conn, err := net.Dial("tcp", dest.NetAddr())
if err != nil {
t.Fatal("failed to dial a TCP connection: ", err)
}
defer conn.Close()
{
writer := NewWriter(conn)
if _, ok := writer.(*BufferToBytesWriter); !ok {
t.Fatal("writer is not a BufferToBytesWriter")
}
writer2 := NewWriter(writer.(io.Writer))
if writer2 != writer {
t.Fatal("writer is not reused")
}
}
tlsConn := tls.Client(conn, &tls.Config{
InsecureSkipVerify: true,
})
defer tlsConn.Close()
{
writer := NewWriter(tlsConn)
if _, ok := writer.(*SequentialWriter); !ok {
t.Fatal("writer is not a SequentialWriter")
}
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/buf.go | common/buf/buf.go | // Package buf provides a light-weight memory allocation mechanism.
package buf // import "v2ray.com/core/common/buf"
//go:generate go run v2ray.com/core/common/errors/errorgen
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/writer.go | common/buf/writer.go | package buf
import (
"io"
"net"
"sync"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
)
// BufferToBytesWriter is a Writer that writes alloc.Buffer into underlying writer.
type BufferToBytesWriter struct {
io.Writer
cache [][]byte
}
// WriteMultiBuffer implements Writer. This method takes ownership of the given buffer.
func (w *BufferToBytesWriter) WriteMultiBuffer(mb MultiBuffer) error {
defer ReleaseMulti(mb)
size := mb.Len()
if size == 0 {
return nil
}
if len(mb) == 1 {
return WriteAllBytes(w.Writer, mb[0].Bytes())
}
if cap(w.cache) < len(mb) {
w.cache = make([][]byte, 0, len(mb))
}
bs := w.cache
for _, b := range mb {
bs = append(bs, b.Bytes())
}
defer func() {
for idx := range bs {
bs[idx] = nil
}
}()
nb := net.Buffers(bs)
for size > 0 {
n, err := nb.WriteTo(w.Writer)
if err != nil {
return err
}
size -= int32(n)
}
return nil
}
// ReadFrom implements io.ReaderFrom.
func (w *BufferToBytesWriter) ReadFrom(reader io.Reader) (int64, error) {
var sc SizeCounter
err := Copy(NewReader(reader), w, CountSize(&sc))
return sc.Size, err
}
// BufferedWriter is a Writer with internal buffer.
type BufferedWriter struct {
sync.Mutex
writer Writer
buffer *Buffer
buffered bool
}
// NewBufferedWriter creates a new BufferedWriter.
func NewBufferedWriter(writer Writer) *BufferedWriter {
return &BufferedWriter{
writer: writer,
buffer: New(),
buffered: true,
}
}
// WriteByte implements io.ByteWriter.
func (w *BufferedWriter) WriteByte(c byte) error {
return common.Error2(w.Write([]byte{c}))
}
// Write implements io.Writer.
func (w *BufferedWriter) Write(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
w.Lock()
defer w.Unlock()
if !w.buffered {
if writer, ok := w.writer.(io.Writer); ok {
return writer.Write(b)
}
}
totalBytes := 0
for len(b) > 0 {
if w.buffer == nil {
w.buffer = New()
}
nBytes, err := w.buffer.Write(b)
totalBytes += nBytes
if err != nil {
return totalBytes, err
}
if !w.buffered || w.buffer.IsFull() {
if err := w.flushInternal(); err != nil {
return totalBytes, err
}
}
b = b[nBytes:]
}
return totalBytes, nil
}
// WriteMultiBuffer implements Writer. It takes ownership of the given MultiBuffer.
func (w *BufferedWriter) WriteMultiBuffer(b MultiBuffer) error {
if b.IsEmpty() {
return nil
}
w.Lock()
defer w.Unlock()
if !w.buffered {
return w.writer.WriteMultiBuffer(b)
}
reader := MultiBufferContainer{
MultiBuffer: b,
}
defer reader.Close()
for !reader.MultiBuffer.IsEmpty() {
if w.buffer == nil {
w.buffer = New()
}
common.Must2(w.buffer.ReadFrom(&reader))
if w.buffer.IsFull() {
if err := w.flushInternal(); err != nil {
return err
}
}
}
return nil
}
// Flush flushes buffered content into underlying writer.
func (w *BufferedWriter) Flush() error {
w.Lock()
defer w.Unlock()
return w.flushInternal()
}
func (w *BufferedWriter) flushInternal() error {
if w.buffer.IsEmpty() {
return nil
}
b := w.buffer
w.buffer = nil
if writer, ok := w.writer.(io.Writer); ok {
err := WriteAllBytes(writer, b.Bytes())
b.Release()
return err
}
return w.writer.WriteMultiBuffer(MultiBuffer{b})
}
// SetBuffered sets whether the internal buffer is used. If set to false, Flush() will be called to clear the buffer.
func (w *BufferedWriter) SetBuffered(f bool) error {
w.Lock()
defer w.Unlock()
w.buffered = f
if !f {
return w.flushInternal()
}
return nil
}
// ReadFrom implements io.ReaderFrom.
func (w *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) {
if err := w.SetBuffered(false); err != nil {
return 0, err
}
var sc SizeCounter
err := Copy(NewReader(reader), w, CountSize(&sc))
return sc.Size, err
}
// Close implements io.Closable.
func (w *BufferedWriter) Close() error {
if err := w.Flush(); err != nil {
return err
}
return common.Close(w.writer)
}
// SequentialWriter is a Writer that writes MultiBuffer sequentially into the underlying io.Writer.
type SequentialWriter struct {
io.Writer
}
// WriteMultiBuffer implements Writer.
func (w *SequentialWriter) WriteMultiBuffer(mb MultiBuffer) error {
mb, err := WriteMultiBuffer(w.Writer, mb)
ReleaseMulti(mb)
return err
}
type noOpWriter byte
func (noOpWriter) WriteMultiBuffer(b MultiBuffer) error {
ReleaseMulti(b)
return nil
}
func (noOpWriter) Write(b []byte) (int, error) {
return len(b), nil
}
func (noOpWriter) ReadFrom(reader io.Reader) (int64, error) {
b := New()
defer b.Release()
totalBytes := int64(0)
for {
b.Clear()
_, err := b.ReadFrom(reader)
totalBytes += int64(b.Len())
if err != nil {
if errors.Cause(err) == io.EOF {
return totalBytes, nil
}
return totalBytes, err
}
}
}
var (
// Discard is a Writer that swallows all contents written in.
Discard Writer = noOpWriter(0)
// DiscardBytes is an io.Writer that swallows all contents written in.
DiscardBytes io.Writer = noOpWriter(0)
)
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/reader.go | common/buf/reader.go | package buf
import (
"io"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
)
func readOneUDP(r io.Reader) (*Buffer, error) {
b := New()
for i := 0; i < 64; i++ {
_, err := b.ReadFrom(r)
if !b.IsEmpty() {
return b, nil
}
if err != nil {
b.Release()
return nil, err
}
}
b.Release()
return nil, newError("Reader returns too many empty payloads.")
}
// ReadBuffer reads a Buffer from the given reader.
func ReadBuffer(r io.Reader) (*Buffer, error) {
b := New()
n, err := b.ReadFrom(r)
if n > 0 {
return b, err
}
b.Release()
return nil, err
}
// BufferedReader is a Reader that keeps its internal buffer.
type BufferedReader struct {
// Reader is the underlying reader to be read from
Reader Reader
// Buffer is the internal buffer to be read from first
Buffer MultiBuffer
// Spliter is a function to read bytes from MultiBuffer
Spliter func(MultiBuffer, []byte) (MultiBuffer, int)
}
// BufferedBytes returns the number of bytes that is cached in this reader.
func (r *BufferedReader) BufferedBytes() int32 {
return r.Buffer.Len()
}
// ReadByte implements io.ByteReader.
func (r *BufferedReader) ReadByte() (byte, error) {
var b [1]byte
_, err := r.Read(b[:])
return b[0], err
}
// Read implements io.Reader. It reads from internal buffer first (if available) and then reads from the underlying reader.
func (r *BufferedReader) Read(b []byte) (int, error) {
spliter := r.Spliter
if spliter == nil {
spliter = SplitBytes
}
if !r.Buffer.IsEmpty() {
buffer, nBytes := spliter(r.Buffer, b)
r.Buffer = buffer
if r.Buffer.IsEmpty() {
r.Buffer = nil
}
return nBytes, nil
}
mb, err := r.Reader.ReadMultiBuffer()
if err != nil {
return 0, err
}
mb, nBytes := spliter(mb, b)
if !mb.IsEmpty() {
r.Buffer = mb
}
return nBytes, nil
}
// ReadMultiBuffer implements Reader.
func (r *BufferedReader) ReadMultiBuffer() (MultiBuffer, error) {
if !r.Buffer.IsEmpty() {
mb := r.Buffer
r.Buffer = nil
return mb, nil
}
return r.Reader.ReadMultiBuffer()
}
// ReadAtMost returns a MultiBuffer with at most size.
func (r *BufferedReader) ReadAtMost(size int32) (MultiBuffer, error) {
if r.Buffer.IsEmpty() {
mb, err := r.Reader.ReadMultiBuffer()
if mb.IsEmpty() && err != nil {
return nil, err
}
r.Buffer = mb
}
rb, mb := SplitSize(r.Buffer, size)
r.Buffer = rb
if r.Buffer.IsEmpty() {
r.Buffer = nil
}
return mb, nil
}
func (r *BufferedReader) writeToInternal(writer io.Writer) (int64, error) {
mbWriter := NewWriter(writer)
var sc SizeCounter
if r.Buffer != nil {
sc.Size = int64(r.Buffer.Len())
if err := mbWriter.WriteMultiBuffer(r.Buffer); err != nil {
return 0, err
}
r.Buffer = nil
}
err := Copy(r.Reader, mbWriter, CountSize(&sc))
return sc.Size, err
}
// WriteTo implements io.WriterTo.
func (r *BufferedReader) WriteTo(writer io.Writer) (int64, error) {
nBytes, err := r.writeToInternal(writer)
if errors.Cause(err) == io.EOF {
return nBytes, nil
}
return nBytes, err
}
// Interrupt implements common.Interruptible.
func (r *BufferedReader) Interrupt() {
common.Interrupt(r.Reader)
}
// Close implements io.Closer.
func (r *BufferedReader) Close() error {
return common.Close(r.Reader)
}
// SingleReader is a Reader that read one Buffer every time.
type SingleReader struct {
io.Reader
}
// ReadMultiBuffer implements Reader.
func (r *SingleReader) ReadMultiBuffer() (MultiBuffer, error) {
b, err := ReadBuffer(r.Reader)
return MultiBuffer{b}, err
}
// PacketReader is a Reader that read one Buffer every time.
type PacketReader struct {
io.Reader
}
// ReadMultiBuffer implements Reader.
func (r *PacketReader) ReadMultiBuffer() (MultiBuffer, error) {
b, err := readOneUDP(r.Reader)
if err != nil {
return nil, err
}
return MultiBuffer{b}, nil
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/reader_test.go | common/buf/reader_test.go | package buf_test
import (
"bytes"
"io"
"strings"
"testing"
"v2ray.com/core/common"
. "v2ray.com/core/common/buf"
"v2ray.com/core/transport/pipe"
)
func TestBytesReaderWriteTo(t *testing.T) {
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
reader := &BufferedReader{Reader: pReader}
b1 := New()
b1.WriteString("abc")
b2 := New()
b2.WriteString("efg")
common.Must(pWriter.WriteMultiBuffer(MultiBuffer{b1, b2}))
pWriter.Close()
pReader2, pWriter2 := pipe.New(pipe.WithSizeLimit(1024))
writer := NewBufferedWriter(pWriter2)
writer.SetBuffered(false)
nBytes, err := io.Copy(writer, reader)
common.Must(err)
if nBytes != 6 {
t.Error("copy: ", nBytes)
}
mb, err := pReader2.ReadMultiBuffer()
common.Must(err)
if s := mb.String(); s != "abcefg" {
t.Error("content: ", s)
}
}
func TestBytesReaderMultiBuffer(t *testing.T) {
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
reader := &BufferedReader{Reader: pReader}
b1 := New()
b1.WriteString("abc")
b2 := New()
b2.WriteString("efg")
common.Must(pWriter.WriteMultiBuffer(MultiBuffer{b1, b2}))
pWriter.Close()
mbReader := NewReader(reader)
mb, err := mbReader.ReadMultiBuffer()
common.Must(err)
if s := mb.String(); s != "abcefg" {
t.Error("content: ", s)
}
}
func TestReadByte(t *testing.T) {
sr := strings.NewReader("abcd")
reader := &BufferedReader{
Reader: NewReader(sr),
}
b, err := reader.ReadByte()
common.Must(err)
if b != 'a' {
t.Error("unexpected byte: ", b, " want a")
}
if reader.BufferedBytes() != 3 { // 3 bytes left in buffer
t.Error("unexpected buffered Bytes: ", reader.BufferedBytes())
}
nBytes, err := reader.WriteTo(DiscardBytes)
common.Must(err)
if nBytes != 3 {
t.Error("unexpect bytes written: ", nBytes)
}
}
func TestReadBuffer(t *testing.T) {
{
sr := strings.NewReader("abcd")
buf, err := ReadBuffer(sr)
common.Must(err)
if s := buf.String(); s != "abcd" {
t.Error("unexpected str: ", s, " want abcd")
}
buf.Release()
}
}
func TestReadAtMost(t *testing.T) {
sr := strings.NewReader("abcd")
reader := &BufferedReader{
Reader: NewReader(sr),
}
mb, err := reader.ReadAtMost(3)
common.Must(err)
if s := mb.String(); s != "abc" {
t.Error("unexpected read result: ", s)
}
nBytes, err := reader.WriteTo(DiscardBytes)
common.Must(err)
if nBytes != 1 {
t.Error("unexpect bytes written: ", nBytes)
}
}
func TestPacketReader_ReadMultiBuffer(t *testing.T) {
const alpha = "abcefg"
buf := bytes.NewBufferString(alpha)
reader := &PacketReader{buf}
mb, err := reader.ReadMultiBuffer()
common.Must(err)
if s := mb.String(); s != alpha {
t.Error("content: ", s)
}
}
func TestReaderInterface(t *testing.T) {
_ = (io.Reader)(new(ReadVReader))
_ = (Reader)(new(ReadVReader))
_ = (Reader)(new(BufferedReader))
_ = (io.Reader)(new(BufferedReader))
_ = (io.ByteReader)(new(BufferedReader))
_ = (io.WriterTo)(new(BufferedReader))
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/io.go | common/buf/io.go | package buf
import (
"io"
"net"
"os"
"syscall"
"time"
)
// Reader extends io.Reader with MultiBuffer.
type Reader interface {
// ReadMultiBuffer reads content from underlying reader, and put it into a MultiBuffer.
ReadMultiBuffer() (MultiBuffer, error)
}
// ErrReadTimeout is an error that happens with IO timeout.
var ErrReadTimeout = newError("IO timeout")
// TimeoutReader is a reader that returns error if Read() operation takes longer than the given timeout.
type TimeoutReader interface {
ReadMultiBufferTimeout(time.Duration) (MultiBuffer, error)
}
// Writer extends io.Writer with MultiBuffer.
type Writer interface {
// WriteMultiBuffer writes a MultiBuffer into underlying writer.
WriteMultiBuffer(MultiBuffer) error
}
// WriteAllBytes ensures all bytes are written into the given writer.
func WriteAllBytes(writer io.Writer, payload []byte) error {
for len(payload) > 0 {
n, err := writer.Write(payload)
if err != nil {
return err
}
payload = payload[n:]
}
return nil
}
func isPacketReader(reader io.Reader) bool {
_, ok := reader.(net.PacketConn)
return ok
}
// NewReader creates a new Reader.
// The Reader instance doesn't take the ownership of reader.
func NewReader(reader io.Reader) Reader {
if mr, ok := reader.(Reader); ok {
return mr
}
if isPacketReader(reader) {
return &PacketReader{
Reader: reader,
}
}
_, isFile := reader.(*os.File)
if !isFile && useReadv {
if sc, ok := reader.(syscall.Conn); ok {
rawConn, err := sc.SyscallConn()
if err != nil {
newError("failed to get sysconn").Base(err).WriteToLog()
} else {
return NewReadVReader(reader, rawConn)
}
}
}
return &SingleReader{
Reader: reader,
}
}
// NewPacketReader creates a new PacketReader based on the given reader.
func NewPacketReader(reader io.Reader) Reader {
if mr, ok := reader.(Reader); ok {
return mr
}
return &PacketReader{
Reader: reader,
}
}
func isPacketWriter(writer io.Writer) bool {
if _, ok := writer.(net.PacketConn); ok {
return true
}
// If the writer doesn't implement syscall.Conn, it is probably not a TCP connection.
if _, ok := writer.(syscall.Conn); !ok {
return true
}
return false
}
// NewWriter creates a new Writer.
func NewWriter(writer io.Writer) Writer {
if mw, ok := writer.(Writer); ok {
return mw
}
if isPacketWriter(writer) {
return &SequentialWriter{
Writer: writer,
}
}
return &BufferToBytesWriter{
Writer: writer,
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/copy.go | common/buf/copy.go | package buf
import (
"io"
"time"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/signal"
)
type dataHandler func(MultiBuffer)
type copyHandler struct {
onData []dataHandler
}
// SizeCounter is for counting bytes copied by Copy().
type SizeCounter struct {
Size int64
}
// CopyOption is an option for copying data.
type CopyOption func(*copyHandler)
// UpdateActivity is a CopyOption to update activity on each data copy operation.
func UpdateActivity(timer signal.ActivityUpdater) CopyOption {
return func(handler *copyHandler) {
handler.onData = append(handler.onData, func(MultiBuffer) {
timer.Update()
})
}
}
// CountSize is a CopyOption that sums the total size of data copied into the given SizeCounter.
func CountSize(sc *SizeCounter) CopyOption {
return func(handler *copyHandler) {
handler.onData = append(handler.onData, func(b MultiBuffer) {
sc.Size += int64(b.Len())
})
}
}
type readError struct {
error
}
func (e readError) Error() string {
return e.error.Error()
}
func (e readError) Inner() error {
return e.error
}
// IsReadError returns true if the error in Copy() comes from reading.
func IsReadError(err error) bool {
_, ok := err.(readError)
return ok
}
type writeError struct {
error
}
func (e writeError) Error() string {
return e.error.Error()
}
func (e writeError) Inner() error {
return e.error
}
// IsWriteError returns true if the error in Copy() comes from writing.
func IsWriteError(err error) bool {
_, ok := err.(writeError)
return ok
}
func copyInternal(reader Reader, writer Writer, handler *copyHandler) error {
for {
buffer, err := reader.ReadMultiBuffer()
if !buffer.IsEmpty() {
for _, handler := range handler.onData {
handler(buffer)
}
if werr := writer.WriteMultiBuffer(buffer); werr != nil {
return writeError{werr}
}
}
if err != nil {
return readError{err}
}
}
}
// Copy dumps all payload from reader to writer or stops when an error occurs. It returns nil when EOF.
func Copy(reader Reader, writer Writer, options ...CopyOption) error {
var handler copyHandler
for _, option := range options {
option(&handler)
}
err := copyInternal(reader, writer, &handler)
if err != nil && errors.Cause(err) != io.EOF {
return err
}
return nil
}
var ErrNotTimeoutReader = newError("not a TimeoutReader")
func CopyOnceTimeout(reader Reader, writer Writer, timeout time.Duration) error {
timeoutReader, ok := reader.(TimeoutReader)
if !ok {
return ErrNotTimeoutReader
}
mb, err := timeoutReader.ReadMultiBufferTimeout(timeout)
if err != nil {
return err
}
return writer.WriteMultiBuffer(mb)
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/buffer_test.go | common/buf/buffer_test.go | package buf_test
import (
"bytes"
"crypto/rand"
"testing"
"github.com/google/go-cmp/cmp"
"v2ray.com/core/common"
. "v2ray.com/core/common/buf"
)
func TestBufferClear(t *testing.T) {
buffer := New()
defer buffer.Release()
payload := "Bytes"
buffer.Write([]byte(payload))
if diff := cmp.Diff(buffer.Bytes(), []byte(payload)); diff != "" {
t.Error(diff)
}
buffer.Clear()
if buffer.Len() != 0 {
t.Error("expect 0 length, but got ", buffer.Len())
}
}
func TestBufferIsEmpty(t *testing.T) {
buffer := New()
defer buffer.Release()
if buffer.IsEmpty() != true {
t.Error("expect empty buffer, but not")
}
}
func TestBufferString(t *testing.T) {
buffer := New()
defer buffer.Release()
const payload = "Test String"
common.Must2(buffer.WriteString(payload))
if buffer.String() != payload {
t.Error("expect buffer content as ", payload, " but actually ", buffer.String())
}
}
func TestBufferByte(t *testing.T) {
{
buffer := New()
common.Must(buffer.WriteByte('m'))
if buffer.String() != "m" {
t.Error("expect buffer content as ", "m", " but actually ", buffer.String())
}
buffer.Release()
}
{
buffer := StackNew()
common.Must(buffer.WriteByte('n'))
if buffer.String() != "n" {
t.Error("expect buffer content as ", "n", " but actually ", buffer.String())
}
buffer.Release()
}
{
buffer := StackNew()
common.Must2(buffer.WriteString("HELLOWORLD"))
if b := buffer.Byte(5); b != 'W' {
t.Error("unexpected byte ", b)
}
buffer.SetByte(5, 'M')
if buffer.String() != "HELLOMORLD" {
t.Error("expect buffer content as ", "n", " but actually ", buffer.String())
}
buffer.Release()
}
}
func TestBufferResize(t *testing.T) {
buffer := New()
defer buffer.Release()
const payload = "Test String"
common.Must2(buffer.WriteString(payload))
if buffer.String() != payload {
t.Error("expect buffer content as ", payload, " but actually ", buffer.String())
}
buffer.Resize(-6, -3)
if l := buffer.Len(); int(l) != 3 {
t.Error("len error ", l)
}
if s := buffer.String(); s != "Str" {
t.Error("unexpect buffer ", s)
}
buffer.Resize(int32(len(payload)), 200)
if l := buffer.Len(); int(l) != 200-len(payload) {
t.Error("len error ", l)
}
}
func TestBufferSlice(t *testing.T) {
{
b := New()
common.Must2(b.Write([]byte("abcd")))
bytes := b.BytesFrom(-2)
if diff := cmp.Diff(bytes, []byte{'c', 'd'}); diff != "" {
t.Error(diff)
}
}
{
b := New()
common.Must2(b.Write([]byte("abcd")))
bytes := b.BytesTo(-2)
if diff := cmp.Diff(bytes, []byte{'a', 'b'}); diff != "" {
t.Error(diff)
}
}
{
b := New()
common.Must2(b.Write([]byte("abcd")))
bytes := b.BytesRange(-3, -1)
if diff := cmp.Diff(bytes, []byte{'b', 'c'}); diff != "" {
t.Error(diff)
}
}
}
func TestBufferReadFullFrom(t *testing.T) {
payload := make([]byte, 1024)
common.Must2(rand.Read(payload))
reader := bytes.NewReader(payload)
b := New()
n, err := b.ReadFullFrom(reader, 1024)
common.Must(err)
if n != 1024 {
t.Error("expect reading 1024 bytes, but actually ", n)
}
if diff := cmp.Diff(payload, b.Bytes()); diff != "" {
t.Error(diff)
}
}
func BenchmarkNewBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
buffer := New()
buffer.Release()
}
}
func BenchmarkNewBufferStack(b *testing.B) {
for i := 0; i < b.N; i++ {
buffer := StackNew()
buffer.Release()
}
}
func BenchmarkWrite2(b *testing.B) {
buffer := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = buffer.Write([]byte{'a', 'b'})
buffer.Clear()
}
}
func BenchmarkWrite8(b *testing.B) {
buffer := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = buffer.Write([]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'})
buffer.Clear()
}
}
func BenchmarkWrite32(b *testing.B) {
buffer := New()
payload := make([]byte, 32)
rand.Read(payload)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = buffer.Write(payload)
buffer.Clear()
}
}
func BenchmarkWriteByte2(b *testing.B) {
buffer := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = buffer.WriteByte('a')
_ = buffer.WriteByte('b')
buffer.Clear()
}
}
func BenchmarkWriteByte8(b *testing.B) {
buffer := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = buffer.WriteByte('a')
_ = buffer.WriteByte('b')
_ = buffer.WriteByte('c')
_ = buffer.WriteByte('d')
_ = buffer.WriteByte('e')
_ = buffer.WriteByte('f')
_ = buffer.WriteByte('g')
_ = buffer.WriteByte('h')
buffer.Clear()
}
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
v2ray/v2ray-core | https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/readv_reader_wasm.go | common/buf/readv_reader_wasm.go | // +build wasm
package buf
import (
"io"
"syscall"
)
const useReadv = false
func NewReadVReader(reader io.Reader, rawConn syscall.RawConn) Reader {
panic("not implemented")
}
| go | MIT | d80440f3d57b45c829dbf513306f7adf9a0f3f76 | 2026-01-07T08:35:44.381088Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.