repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_quic_test.go
app/dns/nameserver_quic_test.go
package dns_test import ( "context" "net/url" "testing" "time" "github.com/google/go-cmp/cmp" . "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" ) func TestQUICNameServer(t *testing.T) { url, err := url.Parse("quic://dns.adguard.com") common.Must(err) s, err := NewQUICNameServer(url) common.Must(err) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, false) cancel() common.Must(err) if len(ips) == 0 { t.Error("expect some ips, but got 0") } } func TestQUICNameServerWithCache(t *testing.T) { url, err := url.Parse("quic://dns.adguard.com") common.Must(err) s, err := NewQUICNameServer(url) common.Must(err) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, false) cancel() common.Must(err) if len(ips) == 0 { t.Error("expect some ips, but got 0") } ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5) ips2, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, true) cancel() common.Must(err) if r := cmp.Diff(ips2, ips); r != "" { t.Fatal(r) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_local.go
app/dns/nameserver_local.go
//go:build !confonly // +build !confonly package dns import ( "context" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/dns/localdns" ) // LocalNameServer is an wrapper over local DNS feature. type LocalNameServer struct { client *localdns.Client } // QueryIP implements Server. func (s *LocalNameServer) QueryIP(_ context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) ([]net.IP, error) { var ips []net.IP var err error switch { case option.IPv4Enable && option.IPv6Enable: ips, err = s.client.LookupIP(domain) case option.IPv4Enable: ips, err = s.client.LookupIPv4(domain) case option.IPv6Enable: ips, err = s.client.LookupIPv6(domain) } if len(ips) > 0 { newError("Localhost got answer: ", domain, " -> ", ips).AtInfo().WriteToLog() } return ips, err } // Name implements Server. func (s *LocalNameServer) Name() string { return "localhost" } // NewLocalNameServer creates localdns server object for directly lookup in system DNS. func NewLocalNameServer() *LocalNameServer { newError("DNS: created localhost client").AtInfo().WriteToLog() return &LocalNameServer{ client: localdns.New(), } } // NewLocalDNSClient creates localdns client object for directly lookup in system DNS. func NewLocalDNSClient() *Client { return &Client{server: NewLocalNameServer()} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_tcp.go
app/dns/nameserver_tcp.go
//go:build !confonly // +build !confonly package dns import ( "bytes" "context" "encoding/binary" "net/url" "sync" "sync/atomic" "time" "golang.org/x/net/dns/dnsmessage" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol/dns" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal/pubsub" "github.com/v2fly/v2ray-core/v5/common/task" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/transport/internet" ) // TCPNameServer implemented DNS over TCP (RFC7766). type TCPNameServer struct { sync.RWMutex name string destination net.Destination ips map[string]record pub *pubsub.Service cleanup *task.Periodic reqID uint32 dial func(context.Context) (net.Conn, error) } // NewTCPNameServer creates DNS over TCP server object for remote resolving. func NewTCPNameServer(url *url.URL, dispatcher routing.Dispatcher) (*TCPNameServer, error) { s, err := baseTCPNameServer(url, "TCP") if err != nil { return nil, err } s.dial = func(ctx context.Context) (net.Conn, error) { link, err := dispatcher.Dispatch(ctx, s.destination) if err != nil { return nil, err } return net.NewConnection( net.ConnectionInputMulti(link.Writer), net.ConnectionOutputMulti(link.Reader), ), nil } return s, nil } // NewTCPLocalNameServer creates DNS over TCP client object for local resolving func NewTCPLocalNameServer(url *url.URL) (*TCPNameServer, error) { s, err := baseTCPNameServer(url, "TCPL") if err != nil { return nil, err } s.dial = func(ctx context.Context) (net.Conn, error) { return internet.DialSystem(ctx, s.destination, nil) } return s, nil } func baseTCPNameServer(url *url.URL, prefix string) (*TCPNameServer, error) { var err error port := net.Port(53) if url.Port() != "" { port, err = net.PortFromString(url.Port()) if err != nil { return nil, err } } dest := net.TCPDestination(net.ParseAddress(url.Hostname()), port) s := &TCPNameServer{ destination: dest, ips: make(map[string]record), pub: pubsub.NewService(), name: prefix + "//" + dest.NetAddr(), } s.cleanup = &task.Periodic{ Interval: time.Minute, Execute: s.Cleanup, } return s, nil } // Name implements Server. func (s *TCPNameServer) Name() string { return s.name } // Cleanup clears expired items from cache func (s *TCPNameServer) Cleanup() error { now := time.Now() s.Lock() defer s.Unlock() if len(s.ips) == 0 { return newError("nothing to do. stopping...") } for domain, record := range s.ips { if record.A != nil && record.A.Expire.Before(now) { record.A = nil } if record.AAAA != nil && record.AAAA.Expire.Before(now) { record.AAAA = nil } if record.A == nil && record.AAAA == nil { newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() delete(s.ips, domain) } else { s.ips[domain] = record } } if len(s.ips) == 0 { s.ips = make(map[string]record) } return nil } func (s *TCPNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { elapsed := time.Since(req.start) s.Lock() rec := s.ips[req.domain] updated := false switch req.reqType { case dnsmessage.TypeA: if isNewer(rec.A, ipRec) { rec.A = ipRec updated = true } case dnsmessage.TypeAAAA: addr := make([]net.Address, 0) for _, ip := range ipRec.IP { if len(ip.IP()) == net.IPv6len { addr = append(addr, ip) } } ipRec.IP = addr if isNewer(rec.AAAA, ipRec) { rec.AAAA = ipRec updated = true } } newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() if updated { s.ips[req.domain] = rec } switch req.reqType { case dnsmessage.TypeA: s.pub.Publish(req.domain+"4", nil) case dnsmessage.TypeAAAA: s.pub.Publish(req.domain+"6", nil) } s.Unlock() common.Must(s.cleanup.Start()) } func (s *TCPNameServer) newReqID() uint16 { return uint16(atomic.AddUint32(&s.reqID, 1)) } func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) var deadline time.Time if d, ok := ctx.Deadline(); ok { deadline = d } else { deadline = time.Now().Add(time.Second * 5) } for _, req := range reqs { go func(r *dnsRequest) { dnsCtx := ctx if inbound := session.InboundFromContext(ctx); inbound != nil { dnsCtx = session.ContextWithInbound(dnsCtx, inbound) } dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{ Protocol: "dns", SkipDNSResolve: true, }) var cancel context.CancelFunc dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline) defer cancel() b, err := dns.PackMessage(r.msg) if err != nil { newError("failed to pack dns query").Base(err).AtError().WriteToLog() return } conn, err := s.dial(dnsCtx) if err != nil { newError("failed to dial namesever").Base(err).AtError().WriteToLog() return } defer conn.Close() dnsReqBuf := buf.New() binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len())) dnsReqBuf.Write(b.Bytes()) b.Release() _, err = conn.Write(dnsReqBuf.Bytes()) if err != nil { newError("failed to send query").Base(err).AtError().WriteToLog() return } dnsReqBuf.Release() respBuf := buf.New() defer respBuf.Release() n, err := respBuf.ReadFullFrom(conn, 2) if err != nil && n == 0 { newError("failed to read response length").Base(err).AtError().WriteToLog() return } var length int16 err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length) if err != nil { newError("failed to parse response length").Base(err).AtError().WriteToLog() return } respBuf.Clear() n, err = respBuf.ReadFullFrom(conn, int32(length)) if err != nil && n == 0 { newError("failed to read response length").Base(err).AtError().WriteToLog() return } rec, err := parseResponse(respBuf.Bytes()) if err != nil { newError("failed to parse DNS over TCP response").Base(err).AtError().WriteToLog() return } s.updateIP(r, rec) }(req) } } func (s *TCPNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { s.RLock() record, found := s.ips[domain] s.RUnlock() if !found { return nil, errRecordNotFound } var ips []net.Address var lastErr error if option.IPv4Enable { a, err := record.A.getIPs() if err != nil { lastErr = err } ips = append(ips, a...) } if option.IPv6Enable { aaaa, err := record.AAAA.getIPs() if err != nil { lastErr = err } ips = append(ips, aaaa...) } if len(ips) > 0 { return toNetIP(ips) } if lastErr != nil { return nil, lastErr } return nil, dns_feature.ErrEmptyResponse } // QueryIP implements Server. func (s *TCPNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { fqdn := Fqdn(domain) if disableCache { newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() return ips, err } } // ipv4 and ipv6 belong to different subscription groups var sub4, sub6 *pubsub.Subscriber if option.IPv4Enable { sub4 = s.pub.Subscribe(fqdn + "4") defer sub4.Close() } if option.IPv6Enable { sub6 = s.pub.Subscribe(fqdn + "6") defer sub6.Close() } done := make(chan interface{}) go func() { if sub4 != nil { select { case <-sub4.Wait(): case <-ctx.Done(): } } if sub6 != nil { select { case <-sub6.Wait(): case <-ctx.Done(): } } close(done) }() s.sendQuery(ctx, fqdn, clientIP, option) for { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { return ips, err } select { case <-ctx.Done(): return nil, ctx.Err() case <-done: } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_doh_test.go
app/dns/nameserver_doh_test.go
package dns_test import ( "context" "net/url" "testing" "time" "github.com/google/go-cmp/cmp" . "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" ) func TestDoHLocalNameServer(t *testing.T) { url, err := url.Parse("https+local://1.1.1.1/dns-query") common.Must(err) s := NewDoHLocalNameServer(url) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, false) cancel() common.Must(err) if len(ips) == 0 { t.Error("expect some ips, but got 0") } } func TestDoHLocalNameServerWithCache(t *testing.T) { url, err := url.Parse("https+local://1.1.1.1/dns-query") common.Must(err) s := NewDoHLocalNameServer(url) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, false) cancel() common.Must(err) if len(ips) == 0 { t.Error("expect some ips, but got 0") } ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5) ips2, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{ IPv4Enable: true, IPv6Enable: true, }, true) cancel() common.Must(err) if r := cmp.Diff(ips2, ips); r != "" { t.Fatal(r) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_udp.go
app/dns/nameserver_udp.go
//go:build !confonly // +build !confonly package dns import ( "context" "strings" "sync" "sync/atomic" "time" "golang.org/x/net/dns/dnsmessage" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol/dns" udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal/pubsub" "github.com/v2fly/v2ray-core/v5/common/task" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/transport/internet/udp" ) // ClassicNameServer implemented traditional UDP DNS. type ClassicNameServer struct { sync.RWMutex name string address net.Destination ips map[string]record requests map[uint16]dnsRequest pub *pubsub.Service udpServer udp.DispatcherI cleanup *task.Periodic reqID uint32 } // NewClassicNameServer creates udp server object for remote resolving. func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher) *ClassicNameServer { // default to 53 if unspecific if address.Port == 0 { address.Port = net.Port(53) } s := &ClassicNameServer{ address: address, ips: make(map[string]record), requests: make(map[uint16]dnsRequest), pub: pubsub.NewService(), name: strings.ToUpper(address.String()), } s.cleanup = &task.Periodic{ Interval: time.Minute, Execute: s.Cleanup, } s.udpServer = udp.NewSplitDispatcher(dispatcher, s.HandleResponse) newError("DNS: created UDP client initialized for ", address.NetAddr()).AtInfo().WriteToLog() return s } // Name implements Server. func (s *ClassicNameServer) Name() string { return s.name } // Cleanup clears expired items from cache func (s *ClassicNameServer) Cleanup() error { now := time.Now() s.Lock() defer s.Unlock() if len(s.ips) == 0 && len(s.requests) == 0 { return newError(s.name, " nothing to do. stopping...") } for domain, record := range s.ips { if record.A != nil && record.A.Expire.Before(now) { record.A = nil } if record.AAAA != nil && record.AAAA.Expire.Before(now) { record.AAAA = nil } if record.A == nil && record.AAAA == nil { delete(s.ips, domain) } else { s.ips[domain] = record } } if len(s.ips) == 0 { s.ips = make(map[string]record) } for id, req := range s.requests { if req.expire.Before(now) { delete(s.requests, id) } } if len(s.requests) == 0 { s.requests = make(map[uint16]dnsRequest) } return nil } // HandleResponse handles udp response packet from remote DNS server. func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) { ipRec, err := parseResponse(packet.Payload.Bytes()) if err != nil { newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog() return } s.Lock() id := ipRec.ReqID req, ok := s.requests[id] if ok { // remove the pending request delete(s.requests, id) } s.Unlock() if !ok { newError(s.name, " cannot find the pending request").AtError().WriteToLog() return } var rec record switch req.reqType { case dnsmessage.TypeA: rec.A = ipRec case dnsmessage.TypeAAAA: rec.AAAA = ipRec } elapsed := time.Since(req.start) newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() if len(req.domain) > 0 && (rec.A != nil || rec.AAAA != nil) { s.updateIP(req.domain, rec) } } func (s *ClassicNameServer) updateIP(domain string, newRec record) { s.Lock() newError(s.name, " updating IP records for domain:", domain).AtDebug().WriteToLog() rec := s.ips[domain] updated := false if isNewer(rec.A, newRec.A) { rec.A = newRec.A updated = true } if isNewer(rec.AAAA, newRec.AAAA) { rec.AAAA = newRec.AAAA updated = true } if updated { s.ips[domain] = rec } if newRec.A != nil { s.pub.Publish(domain+"4", nil) } if newRec.AAAA != nil { s.pub.Publish(domain+"6", nil) } s.Unlock() common.Must(s.cleanup.Start()) } func (s *ClassicNameServer) newReqID() uint16 { return uint16(atomic.AddUint32(&s.reqID, 1)) } func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) { s.Lock() defer s.Unlock() id := req.msg.ID req.expire = time.Now().Add(time.Second * 8) s.requests[id] = *req } func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) for _, req := range reqs { s.addPendingRequest(req) b, _ := dns.PackMessage(req.msg) udpCtx := core.ToBackgroundDetachedContext(ctx) if inbound := session.InboundFromContext(ctx); inbound != nil { udpCtx = session.ContextWithInbound(udpCtx, inbound) } udpCtx = session.ContextWithContent(udpCtx, &session.Content{ Protocol: "dns", }) s.udpServer.Dispatch(udpCtx, s.address, b) } } func (s *ClassicNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { s.RLock() record, found := s.ips[domain] s.RUnlock() if !found { return nil, errRecordNotFound } var ips []net.Address var lastErr error if option.IPv4Enable { a, err := record.A.getIPs() if err != nil { lastErr = err } ips = append(ips, a...) } if option.IPv6Enable { aaaa, err := record.AAAA.getIPs() if err != nil { lastErr = err } ips = append(ips, aaaa...) } if len(ips) > 0 { return toNetIP(ips) } if lastErr != nil { return nil, lastErr } return nil, dns_feature.ErrEmptyResponse } // QueryIP implements Server. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { fqdn := Fqdn(domain) if disableCache { newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() return ips, err } } // ipv4 and ipv6 belong to different subscription groups var sub4, sub6 *pubsub.Subscriber if option.IPv4Enable { sub4 = s.pub.Subscribe(fqdn + "4") defer sub4.Close() } if option.IPv6Enable { sub6 = s.pub.Subscribe(fqdn + "6") defer sub6.Close() } done := make(chan interface{}) go func() { if sub4 != nil { select { case <-sub4.Wait(): case <-ctx.Done(): } } if sub6 != nil { select { case <-sub6.Wait(): case <-ctx.Done(): } } close(done) }() s.sendQuery(ctx, fqdn, clientIP, option) for { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { return ips, err } select { case <-ctx.Done(): return nil, ctx.Err() case <-done: } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns_test.go
app/dns/fakedns_test.go
package dns_test import ( "testing" "time" "github.com/google/go-cmp/cmp" "github.com/miekg/dns" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/dispatcher" . "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" "github.com/v2fly/v2ray-core/v5/app/policy" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" feature_dns "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/proxy/freedom" "github.com/v2fly/v2ray-core/v5/testing/servers/udp" ) func TestFakeDNS(t *testing.T) { port := udp.PickPort() dnsServer := dns.Server{ Addr: "127.0.0.1:" + port.String(), Net: "udp", Handler: &staticHandler{}, UDPSize: 1200, } go dnsServer.ListenAndServe() time.Sleep(time.Second) config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&Config{ NameServer: []*NameServer{ { // "fakedns" Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Domain{ Domain: "fakedns", }, }, Port: uint32(53), }, }, { // { "address": "127.0.0.1", "port": "<port>", "domains": ["domain:google.com"], "fakedns": "198.19.0.0/16", "fallbackStrategy": "disabled" } Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Ip{ Ip: []byte{127, 0, 0, 1}, }, }, Port: uint32(port), }, PrioritizedDomain: []*NameServer_PriorityDomain{ {Type: DomainMatchingType_Subdomain, Domain: "google.com"}, }, FakeDns: &fakedns.FakeDnsPoolMulti{ Pools: []*fakedns.FakeDnsPool{ {IpPool: "198.19.0.0/16", LruSize: 256}, }, }, FallbackStrategy: FallbackStrategy_Disabled.Enum(), }, }, FakeDns: &fakedns.FakeDnsPoolMulti{ // "fakedns": "198.18.0.0/16" Pools: []*fakedns.FakeDnsPool{ {IpPool: "198.18.0.0/16", LruSize: 256}, }, }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&policy.Config{}), }, Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{}), }, }, } v, err := core.New(config) common.Must(err) common.Must(v.Start()) dnsClient := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) fakeClient := dnsClient.(feature_dns.ClientWithFakeDNS).AsFakeDNSClient() var fakeIPForFacebook net.IP var fakeIPForGoogle net.IP { // Lookup facebook.com with Fake Client will return 198.18.0.0/16 (global fake pool) ips, err := fakeClient.LookupIP("facebook.com") if err != nil { t.Fatal("unexpected error: ", err) } for _, ip := range ips { if !(&net.IPNet{IP: net.IP{198, 18, 0, 0}, Mask: net.CIDRMask(16, 8*net.IPv4len)}).Contains(ip) { t.Fatal("Lookup facebook.com with fake client not in global pool 198.18.0.0/16") } } fakeIPForFacebook = ips[0] } { // Lookup facebook.com with Normal Client with return empty record (because UDP server matching "domain:google.com" are configured with fallback disabled) _, err := dnsClient.LookupIP("facebook.com") if err != feature_dns.ErrEmptyResponse { t.Fatal("Lookup facebook.com with normal client not returning empty response") } } { // Lookup google.com with Fake Client will return 198.19.0.0/16 (local fake pool) ips, err := fakeClient.LookupIP("google.com") if err != nil { t.Fatal("unexpected error: ", err) } for _, ip := range ips { if !(&net.IPNet{IP: net.IP{198, 19, 0, 0}, Mask: net.CIDRMask(16, 8*net.IPv4len)}).Contains(ip) { t.Fatal("Lookup google.com with fake client not in global pool 198.19.0.0/16") } } fakeIPForGoogle = ips[0] } { // Lookup google.com with Normal Client will return 8.8.8.8 ips, err := dnsClient.LookupIP("google.com") if err != nil { t.Fatal("unexpected error: ", err) } if r := cmp.Diff(ips, []net.IP{{8, 8, 8, 8}}); r != "" { t.Fatal("Lookup google.com with normal client not returning 8.8.8.8") } } fakeEngine := dnsClient.(feature_dns.ClientWithFakeDNS).AsFakeDNSEngine().(feature_dns.FakeDNSEngineRev0) { if !fakeEngine.IsIPInIPPool(net.IPAddress(fakeIPForFacebook)) { t.Fatal("Fake IP of domain facebook.com not in FakeDNSEngine's pool.") } if !fakeEngine.IsIPInIPPool(net.IPAddress(fakeIPForGoogle)) { t.Fatal("Fake IP of domain google.com not in FakeDNSEngine's pool.") } } { if domain := fakeEngine.GetDomainFromFakeDNS(net.IPAddress(fakeIPForFacebook)); domain != "facebook.com" { t.Fatal("Recover fake IP to get domain facebook.com failed.") } if domain := fakeEngine.GetDomainFromFakeDNS(net.IPAddress(fakeIPForGoogle)); domain != "google.com" { t.Fatal("Recover fake IP to get domain google.com failed.") } } { ips := fakeEngine.GetFakeIPForDomain("api.google.com") for _, ip := range ips { if !(&net.IPNet{IP: net.IP{198, 19, 0, 0}, Mask: net.CIDRMask(16, 8*net.IPv4len)}).Contains(ip.IP()) { t.Fatal("Fake IP for api.google.com not in local pool 198.19.0.0/16") } } } { ips := fakeEngine.GetFakeIPForDomain3("v2fly.org", true, false) for _, ip := range ips { if !(&net.IPNet{IP: net.IP{198, 18, 0, 0}, Mask: net.CIDRMask(16, 8*net.IPv4len)}).Contains(ip.IP()) { t.Fatal("Fake IP for v2fly.org not in global pool 198.18.0.0/16") } } } } func TestFakeDNSEmptyGlobalConfig(t *testing.T) { config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&Config{ NameServer: []*NameServer{ { // "fakedns" Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Domain{ Domain: "fakedns", }, }, }, QueryStrategy: QueryStrategy_USE_IP4.Enum(), }, { // "localhost" Address: &net.Endpoint{ Network: net.Network_UDP, Address: &net.IPOrDomain{ Address: &net.IPOrDomain_Domain{ Domain: "localhost", }, }, }, QueryStrategy: QueryStrategy_USE_IP6.Enum(), PrioritizedDomain: []*NameServer_PriorityDomain{ {Type: DomainMatchingType_Subdomain, Domain: "google.com"}, }, FakeDns: &fakedns.FakeDnsPoolMulti{Pools: []*fakedns.FakeDnsPool{}}, // "fakedns": true }, }, }), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&policy.Config{}), }, Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{}), }, }, } v, err := core.New(config) common.Must(err) common.Must(v.Start()) dnsClient := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) fakeClient := dnsClient.(feature_dns.ClientWithFakeDNS).AsFakeDNSClient() { // Lookup facebook.com will return 198.18.0.0/15 (default IPv4 pool) ips, err := fakeClient.LookupIP("facebook.com") if err != nil { t.Fatal("unexpected error: ", err) } for _, ip := range ips { if !(&net.IPNet{IP: net.IP{198, 18, 0, 0}, Mask: net.CIDRMask(15, 8*net.IPv4len)}).Contains(ip) { t.Fatal("Lookup facebook.com with fake client not in default IPv4 pool 198.18.0.0/15") } } } { // Lookup google.com will return fc00::/18 (default IPv6 pool) ips, err := fakeClient.LookupIP("google.com") if err != nil { t.Fatal("unexpected error: ", err) } for _, ip := range ips { if !(&net.IPNet{IP: net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Mask: net.CIDRMask(18, 8*net.IPv6len)}).Contains(ip) { t.Fatal("Lookup google.com with fake client not in default IPv6 pool fc00::/18") } } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/config.pb.go
app/dns/config.pb.go
package dns import ( fakedns "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" routercommon "github.com/v2fly/v2ray-core/v5/app/router/routercommon" net "github.com/v2fly/v2ray-core/v5/common/net" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type DomainMatchingType int32 const ( DomainMatchingType_Full DomainMatchingType = 0 DomainMatchingType_Subdomain DomainMatchingType = 1 DomainMatchingType_Keyword DomainMatchingType = 2 DomainMatchingType_Regex DomainMatchingType = 3 ) // Enum value maps for DomainMatchingType. var ( DomainMatchingType_name = map[int32]string{ 0: "Full", 1: "Subdomain", 2: "Keyword", 3: "Regex", } DomainMatchingType_value = map[string]int32{ "Full": 0, "Subdomain": 1, "Keyword": 2, "Regex": 3, } ) func (x DomainMatchingType) Enum() *DomainMatchingType { p := new(DomainMatchingType) *p = x return p } func (x DomainMatchingType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (DomainMatchingType) Descriptor() protoreflect.EnumDescriptor { return file_app_dns_config_proto_enumTypes[0].Descriptor() } func (DomainMatchingType) Type() protoreflect.EnumType { return &file_app_dns_config_proto_enumTypes[0] } func (x DomainMatchingType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use DomainMatchingType.Descriptor instead. func (DomainMatchingType) EnumDescriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{0} } type QueryStrategy int32 const ( QueryStrategy_USE_IP QueryStrategy = 0 QueryStrategy_USE_IP4 QueryStrategy = 1 QueryStrategy_USE_IP6 QueryStrategy = 2 ) // Enum value maps for QueryStrategy. var ( QueryStrategy_name = map[int32]string{ 0: "USE_IP", 1: "USE_IP4", 2: "USE_IP6", } QueryStrategy_value = map[string]int32{ "USE_IP": 0, "USE_IP4": 1, "USE_IP6": 2, } ) func (x QueryStrategy) Enum() *QueryStrategy { p := new(QueryStrategy) *p = x return p } func (x QueryStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (QueryStrategy) Descriptor() protoreflect.EnumDescriptor { return file_app_dns_config_proto_enumTypes[1].Descriptor() } func (QueryStrategy) Type() protoreflect.EnumType { return &file_app_dns_config_proto_enumTypes[1] } func (x QueryStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use QueryStrategy.Descriptor instead. func (QueryStrategy) EnumDescriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{1} } type CacheStrategy int32 const ( CacheStrategy_CacheEnabled CacheStrategy = 0 CacheStrategy_CacheDisabled CacheStrategy = 1 ) // Enum value maps for CacheStrategy. var ( CacheStrategy_name = map[int32]string{ 0: "CacheEnabled", 1: "CacheDisabled", } CacheStrategy_value = map[string]int32{ "CacheEnabled": 0, "CacheDisabled": 1, } ) func (x CacheStrategy) Enum() *CacheStrategy { p := new(CacheStrategy) *p = x return p } func (x CacheStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (CacheStrategy) Descriptor() protoreflect.EnumDescriptor { return file_app_dns_config_proto_enumTypes[2].Descriptor() } func (CacheStrategy) Type() protoreflect.EnumType { return &file_app_dns_config_proto_enumTypes[2] } func (x CacheStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use CacheStrategy.Descriptor instead. func (CacheStrategy) EnumDescriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{2} } type FallbackStrategy int32 const ( FallbackStrategy_Enabled FallbackStrategy = 0 FallbackStrategy_Disabled FallbackStrategy = 1 FallbackStrategy_DisabledIfAnyMatch FallbackStrategy = 2 ) // Enum value maps for FallbackStrategy. var ( FallbackStrategy_name = map[int32]string{ 0: "Enabled", 1: "Disabled", 2: "DisabledIfAnyMatch", } FallbackStrategy_value = map[string]int32{ "Enabled": 0, "Disabled": 1, "DisabledIfAnyMatch": 2, } ) func (x FallbackStrategy) Enum() *FallbackStrategy { p := new(FallbackStrategy) *p = x return p } func (x FallbackStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FallbackStrategy) Descriptor() protoreflect.EnumDescriptor { return file_app_dns_config_proto_enumTypes[3].Descriptor() } func (FallbackStrategy) Type() protoreflect.EnumType { return &file_app_dns_config_proto_enumTypes[3] } func (x FallbackStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use FallbackStrategy.Descriptor instead. func (FallbackStrategy) EnumDescriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{3} } type NameServer struct { state protoimpl.MessageState `protogen:"open.v1"` Address *net.Endpoint `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` ClientIp []byte `protobuf:"bytes,5,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` Tag string `protobuf:"bytes,7,opt,name=tag,proto3" json:"tag,omitempty"` PrioritizedDomain []*NameServer_PriorityDomain `protobuf:"bytes,2,rep,name=prioritized_domain,json=prioritizedDomain,proto3" json:"prioritized_domain,omitempty"` Geoip []*routercommon.GeoIP `protobuf:"bytes,3,rep,name=geoip,proto3" json:"geoip,omitempty"` OriginalRules []*NameServer_OriginalRule `protobuf:"bytes,4,rep,name=original_rules,json=originalRules,proto3" json:"original_rules,omitempty"` FakeDns *fakedns.FakeDnsPoolMulti `protobuf:"bytes,11,opt,name=fake_dns,json=fakeDns,proto3" json:"fake_dns,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. SkipFallback bool `protobuf:"varint,6,opt,name=skipFallback,proto3" json:"skipFallback,omitempty"` QueryStrategy *QueryStrategy `protobuf:"varint,8,opt,name=query_strategy,json=queryStrategy,proto3,enum=v2ray.core.app.dns.QueryStrategy,oneof" json:"query_strategy,omitempty"` CacheStrategy *CacheStrategy `protobuf:"varint,9,opt,name=cache_strategy,json=cacheStrategy,proto3,enum=v2ray.core.app.dns.CacheStrategy,oneof" json:"cache_strategy,omitempty"` FallbackStrategy *FallbackStrategy `protobuf:"varint,10,opt,name=fallback_strategy,json=fallbackStrategy,proto3,enum=v2ray.core.app.dns.FallbackStrategy,oneof" json:"fallback_strategy,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NameServer) Reset() { *x = NameServer{} mi := &file_app_dns_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NameServer) String() string { return protoimpl.X.MessageStringOf(x) } func (*NameServer) ProtoMessage() {} func (x *NameServer) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NameServer.ProtoReflect.Descriptor instead. func (*NameServer) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{0} } func (x *NameServer) GetAddress() *net.Endpoint { if x != nil { return x.Address } return nil } func (x *NameServer) GetClientIp() []byte { if x != nil { return x.ClientIp } return nil } func (x *NameServer) GetTag() string { if x != nil { return x.Tag } return "" } func (x *NameServer) GetPrioritizedDomain() []*NameServer_PriorityDomain { if x != nil { return x.PrioritizedDomain } return nil } func (x *NameServer) GetGeoip() []*routercommon.GeoIP { if x != nil { return x.Geoip } return nil } func (x *NameServer) GetOriginalRules() []*NameServer_OriginalRule { if x != nil { return x.OriginalRules } return nil } func (x *NameServer) GetFakeDns() *fakedns.FakeDnsPoolMulti { if x != nil { return x.FakeDns } return nil } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *NameServer) GetSkipFallback() bool { if x != nil { return x.SkipFallback } return false } func (x *NameServer) GetQueryStrategy() QueryStrategy { if x != nil && x.QueryStrategy != nil { return *x.QueryStrategy } return QueryStrategy_USE_IP } func (x *NameServer) GetCacheStrategy() CacheStrategy { if x != nil && x.CacheStrategy != nil { return *x.CacheStrategy } return CacheStrategy_CacheEnabled } func (x *NameServer) GetFallbackStrategy() FallbackStrategy { if x != nil && x.FallbackStrategy != nil { return *x.FallbackStrategy } return FallbackStrategy_Enabled } type HostMapping struct { state protoimpl.MessageState `protogen:"open.v1"` Type DomainMatchingType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.dns.DomainMatchingType" json:"type,omitempty"` Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"` Ip [][]byte `protobuf:"bytes,3,rep,name=ip,proto3" json:"ip,omitempty"` // ProxiedDomain indicates the mapped domain has the same IP address on this // domain. V2Ray will use this domain for IP queries. ProxiedDomain string `protobuf:"bytes,4,opt,name=proxied_domain,json=proxiedDomain,proto3" json:"proxied_domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *HostMapping) Reset() { *x = HostMapping{} mi := &file_app_dns_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *HostMapping) String() string { return protoimpl.X.MessageStringOf(x) } func (*HostMapping) ProtoMessage() {} func (x *HostMapping) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use HostMapping.ProtoReflect.Descriptor instead. func (*HostMapping) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{1} } func (x *HostMapping) GetType() DomainMatchingType { if x != nil { return x.Type } return DomainMatchingType_Full } func (x *HostMapping) GetDomain() string { if x != nil { return x.Domain } return "" } func (x *HostMapping) GetIp() [][]byte { if x != nil { return x.Ip } return nil } func (x *HostMapping) GetProxiedDomain() string { if x != nil { return x.ProxiedDomain } return "" } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` // Nameservers used by this DNS. Only traditional UDP servers are support at // the moment. A special value 'localhost' as a domain address can be set to // use DNS on local system. // // Deprecated: Marked as deprecated in app/dns/config.proto. NameServers []*net.Endpoint `protobuf:"bytes,1,rep,name=NameServers,proto3" json:"NameServers,omitempty"` // NameServer list used by this DNS client. NameServer []*NameServer `protobuf:"bytes,5,rep,name=name_server,json=nameServer,proto3" json:"name_server,omitempty"` // Static hosts. Domain to IP. // Deprecated. Use static_hosts. // // Deprecated: Marked as deprecated in app/dns/config.proto. Hosts map[string]*net.IPOrDomain `protobuf:"bytes,2,rep,name=Hosts,proto3" json:"Hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // Client IP for EDNS client subnet. Must be 4 bytes (IPv4) or 16 bytes // (IPv6). ClientIp []byte `protobuf:"bytes,3,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` // Static domain-ip mapping in DNS server. StaticHosts []*HostMapping `protobuf:"bytes,4,rep,name=static_hosts,json=staticHosts,proto3" json:"static_hosts,omitempty"` // Global fakedns object. FakeDns *fakedns.FakeDnsPoolMulti `protobuf:"bytes,16,opt,name=fake_dns,json=fakeDns,proto3" json:"fake_dns,omitempty"` // Tag is the inbound tag of DNS client. Tag string `protobuf:"bytes,6,opt,name=tag,proto3" json:"tag,omitempty"` // Domain matcher to use DomainMatcher string `protobuf:"bytes,15,opt,name=domain_matcher,json=domainMatcher,proto3" json:"domain_matcher,omitempty"` // DisableCache disables DNS cache // Deprecated. Use cache_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableCache bool `protobuf:"varint,8,opt,name=disableCache,proto3" json:"disableCache,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableFallback bool `protobuf:"varint,10,opt,name=disableFallback,proto3" json:"disableFallback,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableFallbackIfMatch bool `protobuf:"varint,11,opt,name=disableFallbackIfMatch,proto3" json:"disableFallbackIfMatch,omitempty"` // Default query strategy (IPv4, IPv6, or both) for each name server. QueryStrategy QueryStrategy `protobuf:"varint,9,opt,name=query_strategy,json=queryStrategy,proto3,enum=v2ray.core.app.dns.QueryStrategy" json:"query_strategy,omitempty"` // Default cache strategy for each name server. CacheStrategy CacheStrategy `protobuf:"varint,12,opt,name=cache_strategy,json=cacheStrategy,proto3,enum=v2ray.core.app.dns.CacheStrategy" json:"cache_strategy,omitempty"` // Default fallback strategy for each name server. FallbackStrategy FallbackStrategy `protobuf:"varint,13,opt,name=fallback_strategy,json=fallbackStrategy,proto3,enum=v2ray.core.app.dns.FallbackStrategy" json:"fallback_strategy,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_dns_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{2} } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *Config) GetNameServers() []*net.Endpoint { if x != nil { return x.NameServers } return nil } func (x *Config) GetNameServer() []*NameServer { if x != nil { return x.NameServer } return nil } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *Config) GetHosts() map[string]*net.IPOrDomain { if x != nil { return x.Hosts } return nil } func (x *Config) GetClientIp() []byte { if x != nil { return x.ClientIp } return nil } func (x *Config) GetStaticHosts() []*HostMapping { if x != nil { return x.StaticHosts } return nil } func (x *Config) GetFakeDns() *fakedns.FakeDnsPoolMulti { if x != nil { return x.FakeDns } return nil } func (x *Config) GetTag() string { if x != nil { return x.Tag } return "" } func (x *Config) GetDomainMatcher() string { if x != nil { return x.DomainMatcher } return "" } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *Config) GetDisableCache() bool { if x != nil { return x.DisableCache } return false } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *Config) GetDisableFallback() bool { if x != nil { return x.DisableFallback } return false } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *Config) GetDisableFallbackIfMatch() bool { if x != nil { return x.DisableFallbackIfMatch } return false } func (x *Config) GetQueryStrategy() QueryStrategy { if x != nil { return x.QueryStrategy } return QueryStrategy_USE_IP } func (x *Config) GetCacheStrategy() CacheStrategy { if x != nil { return x.CacheStrategy } return CacheStrategy_CacheEnabled } func (x *Config) GetFallbackStrategy() FallbackStrategy { if x != nil { return x.FallbackStrategy } return FallbackStrategy_Enabled } type SimplifiedConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // NameServer list used by this DNS client. NameServer []*SimplifiedNameServer `protobuf:"bytes,5,rep,name=name_server,json=nameServer,proto3" json:"name_server,omitempty"` // Client IP for EDNS client subnet. Must be 4 bytes (IPv4) or 16 bytes // (IPv6). ClientIp string `protobuf:"bytes,3,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` // Static domain-ip mapping in DNS server. StaticHosts []*SimplifiedHostMapping `protobuf:"bytes,4,rep,name=static_hosts,json=staticHosts,proto3" json:"static_hosts,omitempty"` // Global fakedns object. FakeDns *fakedns.FakeDnsPoolMulti `protobuf:"bytes,16,opt,name=fake_dns,json=fakeDns,proto3" json:"fake_dns,omitempty"` // Tag is the inbound tag of DNS client. Tag string `protobuf:"bytes,6,opt,name=tag,proto3" json:"tag,omitempty"` // Domain matcher to use DomainMatcher string `protobuf:"bytes,15,opt,name=domain_matcher,json=domainMatcher,proto3" json:"domain_matcher,omitempty"` // DisableCache disables DNS cache // Deprecated. Use cache_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableCache bool `protobuf:"varint,8,opt,name=disableCache,proto3" json:"disableCache,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableFallback bool `protobuf:"varint,10,opt,name=disableFallback,proto3" json:"disableFallback,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. DisableFallbackIfMatch bool `protobuf:"varint,11,opt,name=disableFallbackIfMatch,proto3" json:"disableFallbackIfMatch,omitempty"` // Default query strategy (IPv4, IPv6, or both) for each name server. QueryStrategy QueryStrategy `protobuf:"varint,9,opt,name=query_strategy,json=queryStrategy,proto3,enum=v2ray.core.app.dns.QueryStrategy" json:"query_strategy,omitempty"` // Default cache strategy for each name server. CacheStrategy CacheStrategy `protobuf:"varint,12,opt,name=cache_strategy,json=cacheStrategy,proto3,enum=v2ray.core.app.dns.CacheStrategy" json:"cache_strategy,omitempty"` // Default fallback strategy for each name server. FallbackStrategy FallbackStrategy `protobuf:"varint,13,opt,name=fallback_strategy,json=fallbackStrategy,proto3,enum=v2ray.core.app.dns.FallbackStrategy" json:"fallback_strategy,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedConfig) Reset() { *x = SimplifiedConfig{} mi := &file_app_dns_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedConfig) ProtoMessage() {} func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead. func (*SimplifiedConfig) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{3} } func (x *SimplifiedConfig) GetNameServer() []*SimplifiedNameServer { if x != nil { return x.NameServer } return nil } func (x *SimplifiedConfig) GetClientIp() string { if x != nil { return x.ClientIp } return "" } func (x *SimplifiedConfig) GetStaticHosts() []*SimplifiedHostMapping { if x != nil { return x.StaticHosts } return nil } func (x *SimplifiedConfig) GetFakeDns() *fakedns.FakeDnsPoolMulti { if x != nil { return x.FakeDns } return nil } func (x *SimplifiedConfig) GetTag() string { if x != nil { return x.Tag } return "" } func (x *SimplifiedConfig) GetDomainMatcher() string { if x != nil { return x.DomainMatcher } return "" } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *SimplifiedConfig) GetDisableCache() bool { if x != nil { return x.DisableCache } return false } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *SimplifiedConfig) GetDisableFallback() bool { if x != nil { return x.DisableFallback } return false } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *SimplifiedConfig) GetDisableFallbackIfMatch() bool { if x != nil { return x.DisableFallbackIfMatch } return false } func (x *SimplifiedConfig) GetQueryStrategy() QueryStrategy { if x != nil { return x.QueryStrategy } return QueryStrategy_USE_IP } func (x *SimplifiedConfig) GetCacheStrategy() CacheStrategy { if x != nil { return x.CacheStrategy } return CacheStrategy_CacheEnabled } func (x *SimplifiedConfig) GetFallbackStrategy() FallbackStrategy { if x != nil { return x.FallbackStrategy } return FallbackStrategy_Enabled } type SimplifiedHostMapping struct { state protoimpl.MessageState `protogen:"open.v1"` Type DomainMatchingType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.dns.DomainMatchingType" json:"type,omitempty"` Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"` Ip []string `protobuf:"bytes,3,rep,name=ip,proto3" json:"ip,omitempty"` // ProxiedDomain indicates the mapped domain has the same IP address on this // domain. V2Ray will use this domain for IP queries. ProxiedDomain string `protobuf:"bytes,4,opt,name=proxied_domain,json=proxiedDomain,proto3" json:"proxied_domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedHostMapping) Reset() { *x = SimplifiedHostMapping{} mi := &file_app_dns_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedHostMapping) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedHostMapping) ProtoMessage() {} func (x *SimplifiedHostMapping) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedHostMapping.ProtoReflect.Descriptor instead. func (*SimplifiedHostMapping) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{4} } func (x *SimplifiedHostMapping) GetType() DomainMatchingType { if x != nil { return x.Type } return DomainMatchingType_Full } func (x *SimplifiedHostMapping) GetDomain() string { if x != nil { return x.Domain } return "" } func (x *SimplifiedHostMapping) GetIp() []string { if x != nil { return x.Ip } return nil } func (x *SimplifiedHostMapping) GetProxiedDomain() string { if x != nil { return x.ProxiedDomain } return "" } type SimplifiedNameServer struct { state protoimpl.MessageState `protogen:"open.v1"` Address *net.Endpoint `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` ClientIp string `protobuf:"bytes,5,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` Tag string `protobuf:"bytes,7,opt,name=tag,proto3" json:"tag,omitempty"` PrioritizedDomain []*SimplifiedNameServer_PriorityDomain `protobuf:"bytes,2,rep,name=prioritized_domain,json=prioritizedDomain,proto3" json:"prioritized_domain,omitempty"` Geoip []*routercommon.GeoIP `protobuf:"bytes,3,rep,name=geoip,proto3" json:"geoip,omitempty"` OriginalRules []*SimplifiedNameServer_OriginalRule `protobuf:"bytes,4,rep,name=original_rules,json=originalRules,proto3" json:"original_rules,omitempty"` FakeDns *fakedns.FakeDnsPoolMulti `protobuf:"bytes,11,opt,name=fake_dns,json=fakeDns,proto3" json:"fake_dns,omitempty"` // Deprecated. Use fallback_strategy. // // Deprecated: Marked as deprecated in app/dns/config.proto. SkipFallback bool `protobuf:"varint,6,opt,name=skipFallback,proto3" json:"skipFallback,omitempty"` QueryStrategy *QueryStrategy `protobuf:"varint,8,opt,name=query_strategy,json=queryStrategy,proto3,enum=v2ray.core.app.dns.QueryStrategy,oneof" json:"query_strategy,omitempty"` CacheStrategy *CacheStrategy `protobuf:"varint,9,opt,name=cache_strategy,json=cacheStrategy,proto3,enum=v2ray.core.app.dns.CacheStrategy,oneof" json:"cache_strategy,omitempty"` FallbackStrategy *FallbackStrategy `protobuf:"varint,10,opt,name=fallback_strategy,json=fallbackStrategy,proto3,enum=v2ray.core.app.dns.FallbackStrategy,oneof" json:"fallback_strategy,omitempty"` GeoDomain []*routercommon.GeoSite `protobuf:"bytes,68001,rep,name=geo_domain,json=geoDomain,proto3" json:"geo_domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedNameServer) Reset() { *x = SimplifiedNameServer{} mi := &file_app_dns_config_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedNameServer) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedNameServer) ProtoMessage() {} func (x *SimplifiedNameServer) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedNameServer.ProtoReflect.Descriptor instead. func (*SimplifiedNameServer) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{5} } func (x *SimplifiedNameServer) GetAddress() *net.Endpoint { if x != nil { return x.Address } return nil } func (x *SimplifiedNameServer) GetClientIp() string { if x != nil { return x.ClientIp } return "" } func (x *SimplifiedNameServer) GetTag() string { if x != nil { return x.Tag } return "" } func (x *SimplifiedNameServer) GetPrioritizedDomain() []*SimplifiedNameServer_PriorityDomain { if x != nil { return x.PrioritizedDomain } return nil } func (x *SimplifiedNameServer) GetGeoip() []*routercommon.GeoIP { if x != nil { return x.Geoip } return nil } func (x *SimplifiedNameServer) GetOriginalRules() []*SimplifiedNameServer_OriginalRule { if x != nil { return x.OriginalRules } return nil } func (x *SimplifiedNameServer) GetFakeDns() *fakedns.FakeDnsPoolMulti { if x != nil { return x.FakeDns } return nil } // Deprecated: Marked as deprecated in app/dns/config.proto. func (x *SimplifiedNameServer) GetSkipFallback() bool { if x != nil { return x.SkipFallback } return false } func (x *SimplifiedNameServer) GetQueryStrategy() QueryStrategy { if x != nil && x.QueryStrategy != nil { return *x.QueryStrategy } return QueryStrategy_USE_IP } func (x *SimplifiedNameServer) GetCacheStrategy() CacheStrategy { if x != nil && x.CacheStrategy != nil { return *x.CacheStrategy } return CacheStrategy_CacheEnabled } func (x *SimplifiedNameServer) GetFallbackStrategy() FallbackStrategy { if x != nil && x.FallbackStrategy != nil { return *x.FallbackStrategy } return FallbackStrategy_Enabled } func (x *SimplifiedNameServer) GetGeoDomain() []*routercommon.GeoSite { if x != nil { return x.GeoDomain } return nil } type NameServer_PriorityDomain struct { state protoimpl.MessageState `protogen:"open.v1"` Type DomainMatchingType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.dns.DomainMatchingType" json:"type,omitempty"` Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NameServer_PriorityDomain) Reset() { *x = NameServer_PriorityDomain{} mi := &file_app_dns_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NameServer_PriorityDomain) String() string { return protoimpl.X.MessageStringOf(x) } func (*NameServer_PriorityDomain) ProtoMessage() {} func (x *NameServer_PriorityDomain) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NameServer_PriorityDomain.ProtoReflect.Descriptor instead. func (*NameServer_PriorityDomain) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{0, 0} } func (x *NameServer_PriorityDomain) GetType() DomainMatchingType { if x != nil { return x.Type } return DomainMatchingType_Full } func (x *NameServer_PriorityDomain) GetDomain() string { if x != nil { return x.Domain } return "" } type NameServer_OriginalRule struct { state protoimpl.MessageState `protogen:"open.v1"` Rule string `protobuf:"bytes,1,opt,name=rule,proto3" json:"rule,omitempty"` Size uint32 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *NameServer_OriginalRule) Reset() { *x = NameServer_OriginalRule{} mi := &file_app_dns_config_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *NameServer_OriginalRule) String() string { return protoimpl.X.MessageStringOf(x) } func (*NameServer_OriginalRule) ProtoMessage() {} func (x *NameServer_OriginalRule) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NameServer_OriginalRule.ProtoReflect.Descriptor instead. func (*NameServer_OriginalRule) Descriptor() ([]byte, []int) { return file_app_dns_config_proto_rawDescGZIP(), []int{0, 1} } func (x *NameServer_OriginalRule) GetRule() string { if x != nil { return x.Rule } return "" } func (x *NameServer_OriginalRule) GetSize() uint32 { if x != nil { return x.Size } return 0 } type SimplifiedNameServer_PriorityDomain struct { state protoimpl.MessageState `protogen:"open.v1"` Type DomainMatchingType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.dns.DomainMatchingType" json:"type,omitempty"` Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedNameServer_PriorityDomain) Reset() { *x = SimplifiedNameServer_PriorityDomain{} mi := &file_app_dns_config_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedNameServer_PriorityDomain) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedNameServer_PriorityDomain) ProtoMessage() {} func (x *SimplifiedNameServer_PriorityDomain) ProtoReflect() protoreflect.Message { mi := &file_app_dns_config_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
true
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/hosts_test.go
app/dns/hosts_test.go
package dns_test import ( "testing" "github.com/google/go-cmp/cmp" . "github.com/v2fly/v2ray-core/v5/app/dns" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" ) func TestStaticHosts(t *testing.T) { pb := []*HostMapping{ { Type: DomainMatchingType_Full, Domain: "v2fly.org", Ip: [][]byte{ {1, 1, 1, 1}, }, }, { Type: DomainMatchingType_Full, Domain: "proxy.v2fly.org", Ip: [][]byte{ {1, 2, 3, 4}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, }, ProxiedDomain: "another-proxy.v2fly.org", }, { Type: DomainMatchingType_Full, Domain: "proxy2.v2fly.org", ProxiedDomain: "proxy.v2fly.org", }, { Type: DomainMatchingType_Subdomain, Domain: "v2ray.cn", Ip: [][]byte{ {2, 2, 2, 2}, }, }, { Type: DomainMatchingType_Subdomain, Domain: "baidu.com", Ip: [][]byte{ {127, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, }, }, } hosts, err := NewStaticHosts(pb, nil) common.Must(err) { ips := hosts.Lookup("v2fly.org", dns.IPOption{ IPv4Enable: true, IPv6Enable: true, }) if len(ips) != 1 { t.Error("expect 1 IP, but got ", len(ips)) } if diff := cmp.Diff([]byte(ips[0].IP()), []byte{1, 1, 1, 1}); diff != "" { t.Error(diff) } } { domain := hosts.Lookup("proxy.v2fly.org", dns.IPOption{ IPv4Enable: true, IPv6Enable: false, }) if len(domain) != 1 { t.Error("expect 1 domain, but got ", len(domain)) } if diff := cmp.Diff(domain[0].Domain(), "another-proxy.v2fly.org"); diff != "" { t.Error(diff) } } { domain := hosts.Lookup("proxy2.v2fly.org", dns.IPOption{ IPv4Enable: true, IPv6Enable: false, }) if len(domain) != 1 { t.Error("expect 1 domain, but got ", len(domain)) } if diff := cmp.Diff(domain[0].Domain(), "another-proxy.v2fly.org"); diff != "" { t.Error(diff) } } { ips := hosts.Lookup("www.v2ray.cn", dns.IPOption{ IPv4Enable: true, IPv6Enable: true, }) if len(ips) != 1 { t.Error("expect 1 IP, but got ", len(ips)) } if diff := cmp.Diff([]byte(ips[0].IP()), []byte{2, 2, 2, 2}); diff != "" { t.Error(diff) } } { ips := hosts.Lookup("baidu.com", dns.IPOption{ IPv4Enable: false, IPv6Enable: true, }) if len(ips) != 1 { t.Error("expect 1 IP, but got ", len(ips)) } if diff := cmp.Diff([]byte(ips[0].IP()), []byte(net.LocalHostIPv6.IP())); diff != "" { t.Error(diff) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/dnscommon.go
app/dns/dnscommon.go
package dns import ( "encoding/binary" "strings" "time" "golang.org/x/net/dns/dnsmessage" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/net" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" ) // Fqdn normalizes domain make sure it ends with '.' func Fqdn(domain string) string { if len(domain) > 0 && strings.HasSuffix(domain, ".") { return domain } return domain + "." } type record struct { A *IPRecord AAAA *IPRecord } // IPRecord is a cacheable item for a resolved domain type IPRecord struct { ReqID uint16 IP []net.Address Expire time.Time RCode dnsmessage.RCode } func (r *IPRecord) getIPs() ([]net.Address, error) { if r == nil || r.Expire.Before(time.Now()) { return nil, errRecordNotFound } if r.RCode != dnsmessage.RCodeSuccess { return nil, dns_feature.RCodeError(r.RCode) } return r.IP, nil } func isNewer(baseRec *IPRecord, newRec *IPRecord) bool { if newRec == nil { return false } if baseRec == nil { return true } return baseRec.Expire.Before(newRec.Expire) } var errRecordNotFound = errors.New("record not found") type dnsRequest struct { reqType dnsmessage.Type domain string start time.Time expire time.Time msg *dnsmessage.Message } func genEDNS0Options(clientIP net.IP) *dnsmessage.Resource { if len(clientIP) == 0 { return nil } var netmask int var family uint16 if len(clientIP) == 4 { family = 1 netmask = 24 // 24 for IPV4, 96 for IPv6 } else { family = 2 netmask = 96 } b := make([]byte, 4) binary.BigEndian.PutUint16(b[0:], family) b[2] = byte(netmask) b[3] = 0 switch family { case 1: ip := clientIP.To4().Mask(net.CIDRMask(netmask, net.IPv4len*8)) needLength := (netmask + 8 - 1) / 8 // division rounding up b = append(b, ip[:needLength]...) case 2: ip := clientIP.Mask(net.CIDRMask(netmask, net.IPv6len*8)) needLength := (netmask + 8 - 1) / 8 // division rounding up b = append(b, ip[:needLength]...) } const EDNS0SUBNET = 0x08 opt := new(dnsmessage.Resource) common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true)) opt.Body = &dnsmessage.OPTResource{ Options: []dnsmessage.Option{ { Code: EDNS0SUBNET, Data: b, }, }, } return opt } func buildReqMsgs(domain string, option dns_feature.IPOption, reqIDGen func() uint16, reqOpts *dnsmessage.Resource) []*dnsRequest { qA := dnsmessage.Question{ Name: dnsmessage.MustNewName(domain), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, } qAAAA := dnsmessage.Question{ Name: dnsmessage.MustNewName(domain), Type: dnsmessage.TypeAAAA, Class: dnsmessage.ClassINET, } var reqs []*dnsRequest now := time.Now() if option.IPv4Enable { msg := new(dnsmessage.Message) msg.Header.ID = reqIDGen() msg.Header.RecursionDesired = true msg.Questions = []dnsmessage.Question{qA} if reqOpts != nil { msg.Additionals = append(msg.Additionals, *reqOpts) } reqs = append(reqs, &dnsRequest{ reqType: dnsmessage.TypeA, domain: domain, start: now, msg: msg, }) } if option.IPv6Enable { msg := new(dnsmessage.Message) msg.Header.ID = reqIDGen() msg.Header.RecursionDesired = true msg.Questions = []dnsmessage.Question{qAAAA} if reqOpts != nil { msg.Additionals = append(msg.Additionals, *reqOpts) } reqs = append(reqs, &dnsRequest{ reqType: dnsmessage.TypeAAAA, domain: domain, start: now, msg: msg, }) } return reqs } // parseResponse parses DNS answers from the returned payload func parseResponse(payload []byte) (*IPRecord, error) { var parser dnsmessage.Parser h, err := parser.Start(payload) if err != nil { return nil, newError("failed to parse DNS response").Base(err).AtWarning() } if err := parser.SkipAllQuestions(); err != nil { return nil, newError("failed to skip questions in DNS response").Base(err).AtWarning() } now := time.Now() ipRecord := &IPRecord{ ReqID: h.ID, RCode: h.RCode, Expire: now.Add(time.Second * 600), } L: for { ah, err := parser.AnswerHeader() if err != nil { if err != dnsmessage.ErrSectionDone { newError("failed to parse answer section for domain: ", ah.Name.String()).Base(err).WriteToLog() } break } ttl := ah.TTL if ttl == 0 { ttl = 600 } expire := now.Add(time.Duration(ttl) * time.Second) if ipRecord.Expire.After(expire) { ipRecord.Expire = expire } switch ah.Type { case dnsmessage.TypeA: ans, err := parser.AResource() if err != nil { newError("failed to parse A record for domain: ", ah.Name).Base(err).WriteToLog() break L } ipRecord.IP = append(ipRecord.IP, net.IPAddress(ans.A[:])) case dnsmessage.TypeAAAA: ans, err := parser.AAAAResource() if err != nil { newError("failed to parse AAAA record for domain: ", ah.Name).Base(err).WriteToLog() break L } ipRecord.IP = append(ipRecord.IP, net.IPAddress(ans.AAAA[:])) default: if err := parser.SkipAnswer(); err != nil { newError("failed to skip answer").Base(err).WriteToLog() break L } continue } } return ipRecord, nil } func filterIP(ips []net.Address, option dns_feature.IPOption) []net.Address { filtered := make([]net.Address, 0, len(ips)) for _, ip := range ips { if (ip.Family().IsIPv4() && option.IPv4Enable) || (ip.Family().IsIPv6() && option.IPv6Enable) { filtered = append(filtered, ip) } } return filtered }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_quic.go
app/dns/nameserver_quic.go
package dns import ( "bytes" "context" "encoding/binary" "net/url" "sync" "time" "github.com/quic-go/quic-go" "golang.org/x/net/dns/dnsmessage" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol/dns" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal/pubsub" "github.com/v2fly/v2ray-core/v5/common/task" dns_feature "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/transport/internet/tls" ) // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated // by selecting the ALPN token "doq" in the crypto handshake. const NextProtoDQ = "doq" const handshakeIdleTimeout = time.Second * 8 // QUICNameServer implemented DNS over QUIC type QUICNameServer struct { sync.RWMutex ips map[string]record pub *pubsub.Service cleanup *task.Periodic name string destination net.Destination connection *quic.Conn } // NewQUICNameServer creates DNS-over-QUIC client object for local resolving func NewQUICNameServer(url *url.URL) (*QUICNameServer, error) { newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog() var err error port := net.Port(853) if url.Port() != "" { port, err = net.PortFromString(url.Port()) if err != nil { return nil, err } } dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port) s := &QUICNameServer{ ips: make(map[string]record), pub: pubsub.NewService(), name: url.String(), destination: dest, } s.cleanup = &task.Periodic{ Interval: time.Minute, Execute: s.Cleanup, } return s, nil } // Name returns client name func (s *QUICNameServer) Name() string { return s.name } // Cleanup clears expired items from cache func (s *QUICNameServer) Cleanup() error { now := time.Now() s.Lock() defer s.Unlock() if len(s.ips) == 0 { return newError("nothing to do. stopping...") } for domain, record := range s.ips { if record.A != nil && record.A.Expire.Before(now) { record.A = nil } if record.AAAA != nil && record.AAAA.Expire.Before(now) { record.AAAA = nil } if record.A == nil && record.AAAA == nil { newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() delete(s.ips, domain) } else { s.ips[domain] = record } } if len(s.ips) == 0 { s.ips = make(map[string]record) } return nil } func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { elapsed := time.Since(req.start) s.Lock() rec := s.ips[req.domain] updated := false switch req.reqType { case dnsmessage.TypeA: if isNewer(rec.A, ipRec) { rec.A = ipRec updated = true } case dnsmessage.TypeAAAA: addr := make([]net.Address, 0) for _, ip := range ipRec.IP { if len(ip.IP()) == net.IPv6len { addr = append(addr, ip) } } ipRec.IP = addr if isNewer(rec.AAAA, ipRec) { rec.AAAA = ipRec updated = true } } newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() if updated { s.ips[req.domain] = rec } switch req.reqType { case dnsmessage.TypeA: s.pub.Publish(req.domain+"4", nil) case dnsmessage.TypeAAAA: s.pub.Publish(req.domain+"6", nil) } s.Unlock() common.Must(s.cleanup.Start()) } func (s *QUICNameServer) newReqID() uint16 { return 0 } func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) var deadline time.Time if d, ok := ctx.Deadline(); ok { deadline = d } else { deadline = time.Now().Add(time.Second * 5) } for _, req := range reqs { go func(r *dnsRequest) { // generate new context for each req, using same context // may cause reqs all aborted if any one encounter an error dnsCtx := ctx // reserve internal dns server requested Inbound if inbound := session.InboundFromContext(ctx); inbound != nil { dnsCtx = session.ContextWithInbound(dnsCtx, inbound) } dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{ Protocol: "quic", SkipDNSResolve: true, }) var cancel context.CancelFunc dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline) defer cancel() b, err := dns.PackMessage(r.msg) if err != nil { newError("failed to pack dns query").Base(err).AtError().WriteToLog() return } dnsReqBuf := buf.New() binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len())) dnsReqBuf.Write(b.Bytes()) b.Release() conn, err := s.openStream(dnsCtx) if err != nil { newError("failed to open quic connection").Base(err).AtError().WriteToLog() return } _, err = conn.Write(dnsReqBuf.Bytes()) if err != nil { newError("failed to send query").Base(err).AtError().WriteToLog() return } _ = conn.Close() respBuf := buf.New() defer respBuf.Release() n, err := respBuf.ReadFullFrom(conn, 2) if err != nil && n == 0 { newError("failed to read response length").Base(err).AtError().WriteToLog() return } var length int16 err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length) if err != nil { newError("failed to parse response length").Base(err).AtError().WriteToLog() return } respBuf.Clear() n, err = respBuf.ReadFullFrom(conn, int32(length)) if err != nil && n == 0 { newError("failed to read response length").Base(err).AtError().WriteToLog() return } rec, err := parseResponse(respBuf.Bytes()) if err != nil { newError("failed to handle response").Base(err).AtError().WriteToLog() return } s.updateIP(r, rec) }(req) } } func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { s.RLock() record, found := s.ips[domain] s.RUnlock() if !found { return nil, errRecordNotFound } var ips []net.Address var lastErr error if option.IPv4Enable { a, err := record.A.getIPs() if err != nil { lastErr = err } ips = append(ips, a...) } if option.IPv6Enable { aaaa, err := record.AAAA.getIPs() if err != nil { lastErr = err } ips = append(ips, aaaa...) } if len(ips) > 0 { return toNetIP(ips) } if lastErr != nil { return nil, lastErr } return nil, dns_feature.ErrEmptyResponse } // QueryIP is called from dns.Server->queryIPTimeout func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { fqdn := Fqdn(domain) if disableCache { newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() return ips, err } } // ipv4 and ipv6 belong to different subscription groups var sub4, sub6 *pubsub.Subscriber if option.IPv4Enable { sub4 = s.pub.Subscribe(fqdn + "4") defer sub4.Close() } if option.IPv6Enable { sub6 = s.pub.Subscribe(fqdn + "6") defer sub6.Close() } done := make(chan interface{}) go func() { if sub4 != nil { select { case <-sub4.Wait(): case <-ctx.Done(): } } if sub6 != nil { select { case <-sub6.Wait(): case <-ctx.Done(): } } close(done) }() s.sendQuery(ctx, fqdn, clientIP, option) for { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { return ips, err } select { case <-ctx.Done(): return nil, ctx.Err() case <-done: } } } func isActive(s *quic.Conn) bool { select { case <-s.Context().Done(): return false default: return true } } func (s *QUICNameServer) getConnection(ctx context.Context) (*quic.Conn, error) { var conn *quic.Conn s.RLock() conn = s.connection if conn != nil && isActive(conn) { s.RUnlock() return conn, nil } if conn != nil { // we're recreating the connection, let's create a new one _ = conn.CloseWithError(0, "") } s.RUnlock() s.Lock() defer s.Unlock() var err error conn, err = s.openConnection(ctx) if err != nil { // This does not look too nice, but QUIC (or maybe quic-go) // doesn't seem stable enough. // Maybe retransmissions aren't fully implemented in quic-go? // Anyways, the simple solution is to make a second try when // it fails to open the QUIC connection. conn, err = s.openConnection(ctx) if err != nil { return nil, err } } s.connection = conn return conn, nil } func (s *QUICNameServer) openConnection(ctx context.Context) (*quic.Conn, error) { tlsConfig := tls.Config{ ServerName: func() string { switch s.destination.Address.Family() { case net.AddressFamilyIPv4, net.AddressFamilyIPv6: return s.destination.Address.IP().String() case net.AddressFamilyDomain: return s.destination.Address.Domain() default: panic("unknown address family") } }(), } quicConfig := &quic.Config{ HandshakeIdleTimeout: handshakeIdleTimeout, } conn, err := quic.DialAddr(ctx, s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto(NextProtoDQ)), quicConfig) if err != nil { return nil, err } return conn, nil } func (s *QUICNameServer) openStream(ctx context.Context) (*quic.Stream, error) { conn, err := s.getConnection(ctx) if err != nil { return nil, err } // open a new stream return conn.OpenStreamSync(ctx) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver_fakedns.go
app/dns/nameserver_fakedns.go
//go:build !confonly // +build !confonly package dns import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" ) type FakeDNSServer struct { fakeDNSEngine dns.FakeDNSEngine } func NewFakeDNSServer(fakeDNSEngine dns.FakeDNSEngine) *FakeDNSServer { return &FakeDNSServer{fakeDNSEngine: fakeDNSEngine} } func (FakeDNSServer) Name() string { return "fakedns" } func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, opt dns.IPOption, _ bool) ([]net.IP, error) { if !opt.FakeEnable { return nil, nil // Returning empty ip record with no error will continue DNS lookup, effectively indicating that this server is disabled. } if f.fakeDNSEngine == nil { if err := core.RequireFeatures(ctx, func(fd dns.FakeDNSEngine) { f.fakeDNSEngine = fd }); err != nil { return nil, newError("Unable to locate a fake DNS Engine").Base(err).AtError() } } var ips []net.Address if fkr0, ok := f.fakeDNSEngine.(dns.FakeDNSEngineRev0); ok { ips = fkr0.GetFakeIPForDomain3(domain, opt.IPv4Enable, opt.IPv6Enable) } else { ips = filterIP(f.fakeDNSEngine.GetFakeIPForDomain(domain), opt) } netIP, err := toNetIP(ips) if err != nil { return nil, newError("Unable to convert IP to net ip").Base(err).AtError() } newError(f.Name(), " got answer: ", domain, " -> ", ips).AtInfo().WriteToLog() if len(netIP) > 0 { return netIP, nil } return nil, dns.ErrEmptyResponse } func isFakeDNS(server Server) bool { _, ok := server.(*FakeDNSServer) return ok }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns.go
app/dns/fakedns.go
//go:build !confonly // +build !confonly package dns import ( fakedns "github.com/v2fly/v2ray-core/v5/app/dns/fakedns" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" ) // FakeDNSClient is an implementation of dns.Client with FakeDNS enabled. type FakeDNSClient struct { *DNS } // LookupIP implements dns.Client. func (s *FakeDNSClient) LookupIP(domain string) ([]net.IP, error) { return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, IPv6Enable: true, FakeEnable: true}) } // LookupIPv4 implements dns.IPv4Lookup. func (s *FakeDNSClient) LookupIPv4(domain string) ([]net.IP, error) { return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, FakeEnable: true}) } // LookupIPv6 implements dns.IPv6Lookup. func (s *FakeDNSClient) LookupIPv6(domain string) ([]net.IP, error) { return s.lookupIPInternal(domain, dns.IPOption{IPv6Enable: true, FakeEnable: true}) } // FakeDNSEngine is an implementation of dns.FakeDNSEngine based on a fully functional DNS. type FakeDNSEngine struct { dns *DNS fakeHolders *fakedns.HolderMulti fakeDefault *fakedns.HolderMulti } // Type implements common.HasType. func (*FakeDNSEngine) Type() interface{} { return dns.FakeDNSEngineType() } // Start implements common.Runnable. func (f *FakeDNSEngine) Start() error { return f.fakeHolders.Start() } // Close implements common.Closable. func (f *FakeDNSEngine) Close() error { return f.fakeHolders.Close() } // GetFakeIPForDomain implements dns.FakeDNSEngine. func (f *FakeDNSEngine) GetFakeIPForDomain(domain string) []net.Address { return f.GetFakeIPForDomain3(domain, true, true) } // GetDomainFromFakeDNS implements dns.FakeDNSEngine. func (f *FakeDNSEngine) GetDomainFromFakeDNS(ip net.Address) string { return f.fakeHolders.GetDomainFromFakeDNS(ip) } // IsIPInIPPool implements dns.FakeDNSEngineRev0. func (f *FakeDNSEngine) IsIPInIPPool(ip net.Address) bool { return f.fakeHolders.IsIPInIPPool(ip) } // GetFakeIPForDomain3 implements dns.FakeDNSEngineRev0. func (f *FakeDNSEngine) GetFakeIPForDomain3(domain string, IPv4 bool, IPv6 bool) []net.Address { // nolint: gocritic option := dns.IPOption{IPv4Enable: IPv4, IPv6Enable: IPv6, FakeEnable: true} for _, client := range f.dns.sortClients(domain, option) { fakeServer, ok := client.fakeDNS.(*FakeDNSServer) if !ok { continue } fakeEngine, ok := fakeServer.fakeDNSEngine.(dns.FakeDNSEngineRev0) if !ok { return filterIP(fakeServer.fakeDNSEngine.GetFakeIPForDomain(domain), option) } return fakeEngine.GetFakeIPForDomain3(domain, IPv4, IPv6) } if f.fakeDefault != nil { return f.fakeDefault.GetFakeIPForDomain3(domain, IPv4, IPv6) } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns/fake.go
app/dns/fakedns/fake.go
//go:build !confonly // +build !confonly package fakedns import ( "context" "math" "math/big" gonet "net" "sync" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/cache" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/dns" ) type Holder struct { domainToIP cache.Lru nextIP *big.Int mu *sync.Mutex ipRange *gonet.IPNet config *FakeDnsPool } func (fkdns *Holder) IsIPInIPPool(ip net.Address) bool { if ip.Family().IsDomain() { return false } return fkdns.ipRange.Contains(ip.IP()) } func (fkdns *Holder) GetFakeIPForDomain3(domain string, ipv4, ipv6 bool) []net.Address { isIPv6 := fkdns.ipRange.IP.To4() == nil if (isIPv6 && ipv6) || (!isIPv6 && ipv4) { return fkdns.GetFakeIPForDomain(domain) } return []net.Address{} } func (*Holder) Type() interface{} { return dns.FakeDNSEngineType() } func (fkdns *Holder) Start() error { if fkdns.config != nil && fkdns.config.IpPool != "" && fkdns.config.LruSize != 0 { return fkdns.initializeFromConfig() } return newError("invalid fakeDNS setting") } func (fkdns *Holder) Close() error { fkdns.domainToIP = nil fkdns.nextIP = nil fkdns.ipRange = nil fkdns.mu = nil return nil } func NewFakeDNSHolder() (*Holder, error) { var fkdns *Holder var err error if fkdns, err = NewFakeDNSHolderConfigOnly(nil); err != nil { return nil, newError("Unable to create Fake Dns Engine").Base(err).AtError() } err = fkdns.initialize("198.18.0.0/15", 65535) if err != nil { return nil, err } return fkdns, nil } func NewFakeDNSHolderConfigOnly(conf *FakeDnsPool) (*Holder, error) { return &Holder{nil, nil, nil, nil, conf}, nil } func (fkdns *Holder) initializeFromConfig() error { return fkdns.initialize(fkdns.config.IpPool, int(fkdns.config.LruSize)) } func (fkdns *Holder) initialize(ipPoolCidr string, lruSize int) error { var ipRange *gonet.IPNet var ipaddr gonet.IP var currentIP *big.Int var err error if ipaddr, ipRange, err = gonet.ParseCIDR(ipPoolCidr); err != nil { return newError("Unable to parse CIDR for Fake DNS IP assignment").Base(err).AtError() } currentIP = big.NewInt(0).SetBytes(ipaddr) if ipaddr.To4() != nil { currentIP = big.NewInt(0).SetBytes(ipaddr.To4()) } ones, bits := ipRange.Mask.Size() rooms := bits - ones if math.Log2(float64(lruSize)) >= float64(rooms) { return newError("LRU size is bigger than subnet size").AtError() } fkdns.domainToIP = cache.NewLru(lruSize) fkdns.ipRange = ipRange fkdns.nextIP = currentIP fkdns.mu = new(sync.Mutex) return nil } // GetFakeIPForDomain checks and generate a fake IP for a domain name func (fkdns *Holder) GetFakeIPForDomain(domain string) []net.Address { fkdns.mu.Lock() defer fkdns.mu.Unlock() if v, ok := fkdns.domainToIP.Get(domain); ok { return []net.Address{v.(net.Address)} } var ip net.Address for { ip = net.IPAddress(fkdns.nextIP.Bytes()) fkdns.nextIP = fkdns.nextIP.Add(fkdns.nextIP, big.NewInt(1)) if !fkdns.ipRange.Contains(fkdns.nextIP.Bytes()) { fkdns.nextIP = big.NewInt(0).SetBytes(fkdns.ipRange.IP) } // if we run for a long time, we may go back to beginning and start seeing the IP in use if _, ok := fkdns.domainToIP.GetKeyFromValue(ip); !ok { break } } fkdns.domainToIP.Put(domain, ip) return []net.Address{ip} } // GetDomainFromFakeDNS checks if an IP is a fake IP and have corresponding domain name func (fkdns *Holder) GetDomainFromFakeDNS(ip net.Address) string { if !ip.Family().IsIP() || !fkdns.ipRange.Contains(ip.IP()) { return "" } if k, ok := fkdns.domainToIP.GetKeyFromValue(ip); ok { return k.(string) } return "" } type HolderMulti struct { holders []*Holder } func (h *HolderMulti) IsIPInIPPool(ip net.Address) bool { if ip.Family().IsDomain() { return false } for _, v := range h.holders { if v.IsIPInIPPool(ip) { return true } } return false } func (h *HolderMulti) GetFakeIPForDomain3(domain string, ipv4, ipv6 bool) []net.Address { var ret []net.Address for _, v := range h.holders { ret = append(ret, v.GetFakeIPForDomain3(domain, ipv4, ipv6)...) } return ret } func (h *HolderMulti) GetFakeIPForDomain(domain string) []net.Address { var ret []net.Address for _, v := range h.holders { ret = append(ret, v.GetFakeIPForDomain(domain)...) } return ret } func (h *HolderMulti) GetDomainFromFakeDNS(ip net.Address) string { for _, v := range h.holders { if domain := v.GetDomainFromFakeDNS(ip); domain != "" { return domain } } return "" } func (h *HolderMulti) IsEmpty() bool { return len(h.holders) == 0 } func (h *HolderMulti) AddPool(poolConfig *FakeDnsPool) (*Holder, error) { _, newIPRange, err := gonet.ParseCIDR(poolConfig.IpPool) if err != nil { return nil, err } running := false for _, v := range h.holders { var ipRange *gonet.IPNet if v.ipRange != nil { ipRange = v.ipRange running = true } else { _, ipRange, err = gonet.ParseCIDR(v.config.IpPool) if err != nil { return nil, err } } if ipRange.String() == newIPRange.String() { return v, nil } if ipRange.Contains(newIPRange.IP) || newIPRange.Contains(ipRange.IP) { return nil, newError("Trying to add ip pool ", newIPRange, " that overlaps with existing ip pool ", ipRange) } } holder, err := NewFakeDNSHolderConfigOnly(poolConfig) if err != nil { return nil, err } if running { if err := holder.Start(); err != nil { return nil, err } } h.holders = append(h.holders, holder) return holder, nil } func (h *HolderMulti) AddPoolMulti(poolMultiConfig *FakeDnsPoolMulti) (*HolderMulti, error) { holderMulti := &HolderMulti{} for _, poolConfig := range poolMultiConfig.Pools { pool, err := h.AddPool(poolConfig) if err != nil { return nil, err } holderMulti.holders = append(holderMulti.holders, pool) } return holderMulti, nil // Returned holderMulti holds references to pools managed by `h` } func (h *HolderMulti) Type() interface{} { return dns.FakeDNSEngineType() } func (h *HolderMulti) Start() error { for _, v := range h.holders { if err := v.Start(); err != nil { return newError("Cannot start all fake dns pools").Base(err) } } return nil } func (h *HolderMulti) Close() error { for _, v := range h.holders { if err := v.Close(); err != nil { return newError("Cannot close all fake dns pools").Base(err) } } return nil } func (h *HolderMulti) createHolderGroups(conf *FakeDnsPoolMulti) error { for _, pool := range conf.Pools { _, err := h.AddPool(pool) if err != nil { return err } } return nil } func NewFakeDNSHolderMulti(conf *FakeDnsPoolMulti) (*HolderMulti, error) { holderMulti := &HolderMulti{} if err := holderMulti.createHolderGroups(conf); err != nil { return nil, err } return holderMulti, nil } func init() { common.Must(common.RegisterConfig((*FakeDnsPool)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { var f *Holder var err error if f, err = NewFakeDNSHolderConfigOnly(config.(*FakeDnsPool)); err != nil { return nil, err } return f, nil })) common.Must(common.RegisterConfig((*FakeDnsPoolMulti)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { var f *HolderMulti var err error if f, err = NewFakeDNSHolderMulti(config.(*FakeDnsPoolMulti)); err != nil { return nil, err } return f, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns/errors.generated.go
app/dns/fakedns/errors.generated.go
package fakedns import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns/fakedns_test.go
app/dns/fakedns/fakedns_test.go
package fakedns import ( gonet "net" "strconv" "testing" "github.com/stretchr/testify/assert" "golang.org/x/sync/errgroup" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/uuid" ) func TestNewFakeDnsHolder(_ *testing.T) { _, err := NewFakeDNSHolder() common.Must(err) } func TestFakeDnsHolderCreateMapping(t *testing.T) { fkdns, err := NewFakeDNSHolder() common.Must(err) addr := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "198.18.0.0", addr[0].IP().String()) } func TestFakeDnsHolderCreateMappingMany(t *testing.T) { fkdns, err := NewFakeDNSHolder() common.Must(err) addr := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "198.18.0.0", addr[0].IP().String()) addr2 := fkdns.GetFakeIPForDomain("fakednstest2.v2fly.org") assert.Equal(t, "198.18.0.1", addr2[0].IP().String()) } func TestFakeDnsHolderCreateMappingManyAndResolve(t *testing.T) { fkdns, err := NewFakeDNSHolder() common.Must(err) { addr := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "198.18.0.0", addr[0].IP().String()) } { addr2 := fkdns.GetFakeIPForDomain("fakednstest2.v2fly.org") assert.Equal(t, "198.18.0.1", addr2[0].IP().String()) } { result := fkdns.GetDomainFromFakeDNS(net.ParseAddress("198.18.0.0")) assert.Equal(t, "fakednstest.v2fly.org", result) } { result := fkdns.GetDomainFromFakeDNS(net.ParseAddress("198.18.0.1")) assert.Equal(t, "fakednstest2.v2fly.org", result) } } func TestFakeDnsHolderCreateMappingManySingleDomain(t *testing.T) { fkdns, err := NewFakeDNSHolder() common.Must(err) addr := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "198.18.0.0", addr[0].IP().String()) addr2 := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "198.18.0.0", addr2[0].IP().String()) } func TestGetFakeIPForDomainConcurrently(t *testing.T) { fkdns, err := NewFakeDNSHolder() common.Must(err) total := 200 addr := make([][]net.Address, total+1) var errg errgroup.Group for i := 0; i < total; i++ { errg.Go(testGetFakeIP(i, addr, fkdns)) } errg.Wait() for i := 0; i < total; i++ { for j := i + 1; j < total; j++ { assert.NotEqual(t, addr[i][0].IP().String(), addr[j][0].IP().String()) } } } func testGetFakeIP(index int, addr [][]net.Address, fkdns *Holder) func() error { return func() error { addr[index] = fkdns.GetFakeIPForDomain("fakednstest" + strconv.Itoa(index) + ".example.com") return nil } } func TestFakeDnsHolderCreateMappingAndRollOver(t *testing.T) { fkdns, err := NewFakeDNSHolderConfigOnly(&FakeDnsPool{ IpPool: "240.0.0.0/12", LruSize: 256, }) common.Must(err) err = fkdns.Start() common.Must(err) { addr := fkdns.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Equal(t, "240.0.0.0", addr[0].IP().String()) } { addr2 := fkdns.GetFakeIPForDomain("fakednstest2.v2fly.org") assert.Equal(t, "240.0.0.1", addr2[0].IP().String()) } for i := 0; i <= 8192; i++ { { result := fkdns.GetDomainFromFakeDNS(net.ParseAddress("240.0.0.0")) assert.Equal(t, "fakednstest.v2fly.org", result) } { result := fkdns.GetDomainFromFakeDNS(net.ParseAddress("240.0.0.1")) assert.Equal(t, "fakednstest2.v2fly.org", result) } { uuid := uuid.New() domain := uuid.String() + ".fakednstest.v2fly.org" addr := fkdns.GetFakeIPForDomain(domain) rsaddr := addr[0].IP().String() result := fkdns.GetDomainFromFakeDNS(net.ParseAddress(rsaddr)) assert.Equal(t, domain, result) } } } func TestFakeDNSMulti(t *testing.T) { fakeMulti, err := NewFakeDNSHolderMulti(&FakeDnsPoolMulti{ Pools: []*FakeDnsPool{{ IpPool: "240.0.0.0/12", LruSize: 256, }, { IpPool: "fddd:c5b4:ff5f:f4f0::/64", LruSize: 256, }}, }, ) common.Must(err) err = fakeMulti.Start() common.Must(err) assert.Nil(t, err, "Should not throw error") _ = fakeMulti t.Run("checkInRange", func(t *testing.T) { t.Run("ipv4", func(t *testing.T) { inPool := fakeMulti.IsIPInIPPool(net.IPAddress([]byte{240, 0, 0, 5})) assert.True(t, inPool) }) t.Run("ipv6", func(t *testing.T) { ip, err := gonet.ResolveIPAddr("ip", "fddd:c5b4:ff5f:f4f0::5") assert.Nil(t, err) inPool := fakeMulti.IsIPInIPPool(net.IPAddress(ip.IP)) assert.True(t, inPool) }) t.Run("ipv4_inverse", func(t *testing.T) { inPool := fakeMulti.IsIPInIPPool(net.IPAddress([]byte{241, 0, 0, 5})) assert.False(t, inPool) }) t.Run("ipv6_inverse", func(t *testing.T) { ip, err := gonet.ResolveIPAddr("ip", "fcdd:c5b4:ff5f:f4f0::5") assert.Nil(t, err) inPool := fakeMulti.IsIPInIPPool(net.IPAddress(ip.IP)) assert.False(t, inPool) }) }) t.Run("allocateTwoAddressForTwoPool", func(t *testing.T) { address := fakeMulti.GetFakeIPForDomain("fakednstest.v2fly.org") assert.Len(t, address, 2, "should be 2 address one for each pool") t.Run("eachOfThemShouldResolve:0", func(t *testing.T) { domain := fakeMulti.GetDomainFromFakeDNS(address[0]) assert.Equal(t, "fakednstest.v2fly.org", domain) }) t.Run("eachOfThemShouldResolve:1", func(t *testing.T) { domain := fakeMulti.GetDomainFromFakeDNS(address[1]) assert.Equal(t, "fakednstest.v2fly.org", domain) }) }) t.Run("understandIPTypeSelector", func(t *testing.T) { t.Run("ipv4", func(t *testing.T) { address := fakeMulti.GetFakeIPForDomain3("fakednstestipv4.v2fly.org", true, false) assert.Len(t, address, 1, "should be 1 address") assert.True(t, address[0].Family().IsIPv4()) }) t.Run("ipv6", func(t *testing.T) { address := fakeMulti.GetFakeIPForDomain3("fakednstestipv6.v2fly.org", false, true) assert.Len(t, address, 1, "should be 1 address") assert.True(t, address[0].Family().IsIPv6()) }) t.Run("ipv46", func(t *testing.T) { address := fakeMulti.GetFakeIPForDomain3("fakednstestipv46.v2fly.org", true, true) assert.Len(t, address, 2, "should be 2 address") assert.True(t, address[0].Family().IsIPv4()) assert.True(t, address[1].Family().IsIPv6()) }) }) } func TestFakeDNSMultiAddPool(t *testing.T) { runTest := func(runTestBeforeStart bool) { fakeMulti, err := NewFakeDNSHolderMulti(&FakeDnsPoolMulti{ Pools: []*FakeDnsPool{{ IpPool: "240.0.0.0/12", LruSize: 256, }, { IpPool: "fddd:c5b4:ff5f:f4f0::/64", LruSize: 256, }}, }) common.Must(err) if !runTestBeforeStart { err = fakeMulti.Start() common.Must(err) } t.Run("ipv4_return_existing", func(t *testing.T) { pool, err := fakeMulti.AddPool(&FakeDnsPool{ IpPool: "240.0.0.1/12", LruSize: 256, }) common.Must(err) if pool != fakeMulti.holders[0] { t.Error("HolderMulti.AddPool not returning same holder for existing IPv4 pool") } }) t.Run("ipv6_return_existing", func(t *testing.T) { pool, err := fakeMulti.AddPool(&FakeDnsPool{ IpPool: "fddd:c5b4:ff5f:f4f0::1/64", LruSize: 256, }) common.Must(err) if pool != fakeMulti.holders[1] { t.Error("HolderMulti.AddPool not returning same holder for existing IPv6 pool") } }) t.Run("ipv4_reject_overlap", func(t *testing.T) { _, err := fakeMulti.AddPool(&FakeDnsPool{ IpPool: "240.8.0.0/13", LruSize: 256, }) if err == nil { t.Error("HolderMulti.AddPool not rejecting IPv4 pool that is subnet of existing ones") } _, err = fakeMulti.AddPool(&FakeDnsPool{ IpPool: "240.0.0.0/11", LruSize: 256, }) if err == nil { t.Error("HolderMulti.AddPool not rejecting IPv4 pool that contains existing ones") } }) t.Run("new_pool", func(t *testing.T) { pool, err := fakeMulti.AddPool(&FakeDnsPool{ IpPool: "192.168.168.0/16", LruSize: 256, }) common.Must(err) if pool != fakeMulti.holders[2] { t.Error("HolderMulti.AddPool not creating new holder for new IPv4 pool") } }) t.Run("add_pool_multi", func(t *testing.T) { pools, err := fakeMulti.AddPoolMulti(&FakeDnsPoolMulti{ Pools: []*FakeDnsPool{{ IpPool: "192.168.168.0/16", LruSize: 256, }, { IpPool: "2001:1111::/64", LruSize: 256, }}, }) common.Must(err) if len(pools.holders) != 2 { t.Error("HolderMulti.AddPoolMutli not returning holderMulti that has the same length as passed PoolMulti config") } if pools.holders[0] != fakeMulti.holders[2] { t.Error("HolderMulti.AddPoolMulti not returning same holder for existing IPv4 pool 192.168.168.0/16") } if pools.holders[1] != fakeMulti.holders[3] { t.Error("HolderMulti.AddPoolMulti not creating new holder for new IPv6 pool 2001:1111::/64") } }) if runTestBeforeStart { err = fakeMulti.Start() common.Must(err) } } t.Run("addPoolBeforeStart", func(t *testing.T) { runTest(true) }) t.Run("addPoolAfterStart", func(t *testing.T) { runTest(false) }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns/fakedns.pb.go
app/dns/fakedns/fakedns.pb.go
package fakedns import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type FakeDnsPool struct { state protoimpl.MessageState `protogen:"open.v1"` IpPool string `protobuf:"bytes,1,opt,name=ip_pool,json=ipPool,proto3" json:"ip_pool,omitempty"` //CIDR of IP pool used as fake DNS IP LruSize int64 `protobuf:"varint,2,opt,name=lruSize,proto3" json:"lruSize,omitempty"` //Size of Pool for remembering relationship between domain name and IP address unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FakeDnsPool) Reset() { *x = FakeDnsPool{} mi := &file_app_dns_fakedns_fakedns_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *FakeDnsPool) String() string { return protoimpl.X.MessageStringOf(x) } func (*FakeDnsPool) ProtoMessage() {} func (x *FakeDnsPool) ProtoReflect() protoreflect.Message { mi := &file_app_dns_fakedns_fakedns_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FakeDnsPool.ProtoReflect.Descriptor instead. func (*FakeDnsPool) Descriptor() ([]byte, []int) { return file_app_dns_fakedns_fakedns_proto_rawDescGZIP(), []int{0} } func (x *FakeDnsPool) GetIpPool() string { if x != nil { return x.IpPool } return "" } func (x *FakeDnsPool) GetLruSize() int64 { if x != nil { return x.LruSize } return 0 } type FakeDnsPoolMulti struct { state protoimpl.MessageState `protogen:"open.v1"` Pools []*FakeDnsPool `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FakeDnsPoolMulti) Reset() { *x = FakeDnsPoolMulti{} mi := &file_app_dns_fakedns_fakedns_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *FakeDnsPoolMulti) String() string { return protoimpl.X.MessageStringOf(x) } func (*FakeDnsPoolMulti) ProtoMessage() {} func (x *FakeDnsPoolMulti) ProtoReflect() protoreflect.Message { mi := &file_app_dns_fakedns_fakedns_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FakeDnsPoolMulti.ProtoReflect.Descriptor instead. func (*FakeDnsPoolMulti) Descriptor() ([]byte, []int) { return file_app_dns_fakedns_fakedns_proto_rawDescGZIP(), []int{1} } func (x *FakeDnsPoolMulti) GetPools() []*FakeDnsPool { if x != nil { return x.Pools } return nil } var File_app_dns_fakedns_fakedns_proto protoreflect.FileDescriptor const file_app_dns_fakedns_fakedns_proto_rawDesc = "" + "\n" + "\x1dapp/dns/fakedns/fakedns.proto\x12\x1av2ray.core.app.dns.fakedns\x1a common/protoext/extensions.proto\"X\n" + "\vFakeDnsPool\x12\x17\n" + "\aip_pool\x18\x01 \x01(\tR\x06ipPool\x12\x18\n" + "\alruSize\x18\x02 \x01(\x03R\alruSize:\x16\x82\xb5\x18\x12\n" + "\aservice\x12\afakeDns\"n\n" + "\x10FakeDnsPoolMulti\x12=\n" + "\x05pools\x18\x01 \x03(\v2'.v2ray.core.app.dns.fakedns.FakeDnsPoolR\x05pools:\x1b\x82\xb5\x18\x17\n" + "\aservice\x12\ffakeDnsMultiBo\n" + "\x1ecom.v2ray.core.app.dns.fakednsP\x01Z.github.com/v2fly/v2ray-core/v5/app/dns/fakedns\xaa\x02\x1aV2Ray.Core.App.Dns.Fakednsb\x06proto3" var ( file_app_dns_fakedns_fakedns_proto_rawDescOnce sync.Once file_app_dns_fakedns_fakedns_proto_rawDescData []byte ) func file_app_dns_fakedns_fakedns_proto_rawDescGZIP() []byte { file_app_dns_fakedns_fakedns_proto_rawDescOnce.Do(func() { file_app_dns_fakedns_fakedns_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_dns_fakedns_fakedns_proto_rawDesc), len(file_app_dns_fakedns_fakedns_proto_rawDesc))) }) return file_app_dns_fakedns_fakedns_proto_rawDescData } var file_app_dns_fakedns_fakedns_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_app_dns_fakedns_fakedns_proto_goTypes = []any{ (*FakeDnsPool)(nil), // 0: v2ray.core.app.dns.fakedns.FakeDnsPool (*FakeDnsPoolMulti)(nil), // 1: v2ray.core.app.dns.fakedns.FakeDnsPoolMulti } var file_app_dns_fakedns_fakedns_proto_depIdxs = []int32{ 0, // 0: v2ray.core.app.dns.fakedns.FakeDnsPoolMulti.pools:type_name -> v2ray.core.app.dns.fakedns.FakeDnsPool 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_app_dns_fakedns_fakedns_proto_init() } func file_app_dns_fakedns_fakedns_proto_init() { if File_app_dns_fakedns_fakedns_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_dns_fakedns_fakedns_proto_rawDesc), len(file_app_dns_fakedns_fakedns_proto_rawDesc)), NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_dns_fakedns_fakedns_proto_goTypes, DependencyIndexes: file_app_dns_fakedns_fakedns_proto_depIdxs, MessageInfos: file_app_dns_fakedns_fakedns_proto_msgTypes, }.Build() File_app_dns_fakedns_fakedns_proto = out.File file_app_dns_fakedns_fakedns_proto_goTypes = nil file_app_dns_fakedns_fakedns_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/fakedns/fakedns.go
app/dns/fakedns/fakedns.go
//go:build !confonly // +build !confonly package fakedns //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/config.go
app/proxyman/config.go
package proxyman func (s *AllocationStrategy) GetConcurrencyValue() uint32 { if s == nil || s.Concurrency == nil { return 3 } return s.Concurrency.Value } func (s *AllocationStrategy) GetRefreshValue() uint32 { if s == nil || s.Refresh == nil { return 5 } return s.Refresh.Value } func (c *ReceiverConfig) GetEffectiveSniffingSettings() *SniffingConfig { if c.SniffingSettings != nil { return c.SniffingSettings } if len(c.DomainOverride) > 0 { var p []string for _, kd := range c.DomainOverride { switch kd { case KnownProtocols_HTTP: p = append(p, "http") case KnownProtocols_TLS: p = append(p, "tls") } } return &SniffingConfig{ Enabled: true, DestinationOverride: p, } } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/config.pb.go
app/proxyman/config.pb.go
package proxyman import ( net "github.com/v2fly/v2ray-core/v5/common/net" internet "github.com/v2fly/v2ray-core/v5/transport/internet" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type KnownProtocols int32 const ( KnownProtocols_HTTP KnownProtocols = 0 KnownProtocols_TLS KnownProtocols = 1 ) // Enum value maps for KnownProtocols. var ( KnownProtocols_name = map[int32]string{ 0: "HTTP", 1: "TLS", } KnownProtocols_value = map[string]int32{ "HTTP": 0, "TLS": 1, } ) func (x KnownProtocols) Enum() *KnownProtocols { p := new(KnownProtocols) *p = x return p } func (x KnownProtocols) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (KnownProtocols) Descriptor() protoreflect.EnumDescriptor { return file_app_proxyman_config_proto_enumTypes[0].Descriptor() } func (KnownProtocols) Type() protoreflect.EnumType { return &file_app_proxyman_config_proto_enumTypes[0] } func (x KnownProtocols) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use KnownProtocols.Descriptor instead. func (KnownProtocols) EnumDescriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{0} } type AllocationStrategy_Type int32 const ( // Always allocate all connection handlers. AllocationStrategy_Always AllocationStrategy_Type = 0 // Randomly allocate specific range of handlers. AllocationStrategy_Random AllocationStrategy_Type = 1 // External. Not supported yet. AllocationStrategy_External AllocationStrategy_Type = 2 ) // Enum value maps for AllocationStrategy_Type. var ( AllocationStrategy_Type_name = map[int32]string{ 0: "Always", 1: "Random", 2: "External", } AllocationStrategy_Type_value = map[string]int32{ "Always": 0, "Random": 1, "External": 2, } ) func (x AllocationStrategy_Type) Enum() *AllocationStrategy_Type { p := new(AllocationStrategy_Type) *p = x return p } func (x AllocationStrategy_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AllocationStrategy_Type) Descriptor() protoreflect.EnumDescriptor { return file_app_proxyman_config_proto_enumTypes[1].Descriptor() } func (AllocationStrategy_Type) Type() protoreflect.EnumType { return &file_app_proxyman_config_proto_enumTypes[1] } func (x AllocationStrategy_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AllocationStrategy_Type.Descriptor instead. func (AllocationStrategy_Type) EnumDescriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{1, 0} } type SenderConfig_DomainStrategy int32 const ( SenderConfig_AS_IS SenderConfig_DomainStrategy = 0 SenderConfig_USE_IP SenderConfig_DomainStrategy = 1 SenderConfig_USE_IP4 SenderConfig_DomainStrategy = 2 SenderConfig_USE_IP6 SenderConfig_DomainStrategy = 3 ) // Enum value maps for SenderConfig_DomainStrategy. var ( SenderConfig_DomainStrategy_name = map[int32]string{ 0: "AS_IS", 1: "USE_IP", 2: "USE_IP4", 3: "USE_IP6", } SenderConfig_DomainStrategy_value = map[string]int32{ "AS_IS": 0, "USE_IP": 1, "USE_IP4": 2, "USE_IP6": 3, } ) func (x SenderConfig_DomainStrategy) Enum() *SenderConfig_DomainStrategy { p := new(SenderConfig_DomainStrategy) *p = x return p } func (x SenderConfig_DomainStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SenderConfig_DomainStrategy) Descriptor() protoreflect.EnumDescriptor { return file_app_proxyman_config_proto_enumTypes[2].Descriptor() } func (SenderConfig_DomainStrategy) Type() protoreflect.EnumType { return &file_app_proxyman_config_proto_enumTypes[2] } func (x SenderConfig_DomainStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SenderConfig_DomainStrategy.Descriptor instead. func (SenderConfig_DomainStrategy) EnumDescriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{6, 0} } type InboundConfig struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InboundConfig) Reset() { *x = InboundConfig{} mi := &file_app_proxyman_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InboundConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*InboundConfig) ProtoMessage() {} func (x *InboundConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InboundConfig.ProtoReflect.Descriptor instead. func (*InboundConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{0} } type AllocationStrategy struct { state protoimpl.MessageState `protogen:"open.v1"` Type AllocationStrategy_Type `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.proxyman.AllocationStrategy_Type" json:"type,omitempty"` // Number of handlers (ports) running in parallel. // Default value is 3 if unset. Concurrency *AllocationStrategy_AllocationStrategyConcurrency `protobuf:"bytes,2,opt,name=concurrency,proto3" json:"concurrency,omitempty"` // Number of minutes before a handler is regenerated. // Default value is 5 if unset. Refresh *AllocationStrategy_AllocationStrategyRefresh `protobuf:"bytes,3,opt,name=refresh,proto3" json:"refresh,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AllocationStrategy) Reset() { *x = AllocationStrategy{} mi := &file_app_proxyman_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AllocationStrategy) String() string { return protoimpl.X.MessageStringOf(x) } func (*AllocationStrategy) ProtoMessage() {} func (x *AllocationStrategy) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AllocationStrategy.ProtoReflect.Descriptor instead. func (*AllocationStrategy) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{1} } func (x *AllocationStrategy) GetType() AllocationStrategy_Type { if x != nil { return x.Type } return AllocationStrategy_Always } func (x *AllocationStrategy) GetConcurrency() *AllocationStrategy_AllocationStrategyConcurrency { if x != nil { return x.Concurrency } return nil } func (x *AllocationStrategy) GetRefresh() *AllocationStrategy_AllocationStrategyRefresh { if x != nil { return x.Refresh } return nil } type SniffingConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // Whether or not to enable content sniffing on an inbound connection. Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` // Override target destination if sniff'ed protocol is in the given list. // Supported values are "http", "tls", "fakedns". DestinationOverride []string `protobuf:"bytes,2,rep,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"` // Whether should only try to sniff metadata without waiting for client input. // Can be used to support SMTP like protocol where server send the first message. MetadataOnly bool `protobuf:"varint,3,opt,name=metadata_only,json=metadataOnly,proto3" json:"metadata_only,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SniffingConfig) Reset() { *x = SniffingConfig{} mi := &file_app_proxyman_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SniffingConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SniffingConfig) ProtoMessage() {} func (x *SniffingConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SniffingConfig.ProtoReflect.Descriptor instead. func (*SniffingConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{2} } func (x *SniffingConfig) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *SniffingConfig) GetDestinationOverride() []string { if x != nil { return x.DestinationOverride } return nil } func (x *SniffingConfig) GetMetadataOnly() bool { if x != nil { return x.MetadataOnly } return false } type ReceiverConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // PortRange specifies the ports which the Receiver should listen on. PortRange *net.PortRange `protobuf:"bytes,1,opt,name=port_range,json=portRange,proto3" json:"port_range,omitempty"` // Listen specifies the IP address that the Receiver should listen on. Listen *net.IPOrDomain `protobuf:"bytes,2,opt,name=listen,proto3" json:"listen,omitempty"` AllocationStrategy *AllocationStrategy `protobuf:"bytes,3,opt,name=allocation_strategy,json=allocationStrategy,proto3" json:"allocation_strategy,omitempty"` StreamSettings *internet.StreamConfig `protobuf:"bytes,4,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"` ReceiveOriginalDestination bool `protobuf:"varint,5,opt,name=receive_original_destination,json=receiveOriginalDestination,proto3" json:"receive_original_destination,omitempty"` // Override domains for the given protocol. // Deprecated. Use sniffing_settings. // // Deprecated: Marked as deprecated in app/proxyman/config.proto. DomainOverride []KnownProtocols `protobuf:"varint,7,rep,packed,name=domain_override,json=domainOverride,proto3,enum=v2ray.core.app.proxyman.KnownProtocols" json:"domain_override,omitempty"` SniffingSettings *SniffingConfig `protobuf:"bytes,8,opt,name=sniffing_settings,json=sniffingSettings,proto3" json:"sniffing_settings,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ReceiverConfig) Reset() { *x = ReceiverConfig{} mi := &file_app_proxyman_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ReceiverConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ReceiverConfig) ProtoMessage() {} func (x *ReceiverConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ReceiverConfig.ProtoReflect.Descriptor instead. func (*ReceiverConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{3} } func (x *ReceiverConfig) GetPortRange() *net.PortRange { if x != nil { return x.PortRange } return nil } func (x *ReceiverConfig) GetListen() *net.IPOrDomain { if x != nil { return x.Listen } return nil } func (x *ReceiverConfig) GetAllocationStrategy() *AllocationStrategy { if x != nil { return x.AllocationStrategy } return nil } func (x *ReceiverConfig) GetStreamSettings() *internet.StreamConfig { if x != nil { return x.StreamSettings } return nil } func (x *ReceiverConfig) GetReceiveOriginalDestination() bool { if x != nil { return x.ReceiveOriginalDestination } return false } // Deprecated: Marked as deprecated in app/proxyman/config.proto. func (x *ReceiverConfig) GetDomainOverride() []KnownProtocols { if x != nil { return x.DomainOverride } return nil } func (x *ReceiverConfig) GetSniffingSettings() *SniffingConfig { if x != nil { return x.SniffingSettings } return nil } type InboundHandlerConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` ReceiverSettings *anypb.Any `protobuf:"bytes,2,opt,name=receiver_settings,json=receiverSettings,proto3" json:"receiver_settings,omitempty"` ProxySettings *anypb.Any `protobuf:"bytes,3,opt,name=proxy_settings,json=proxySettings,proto3" json:"proxy_settings,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InboundHandlerConfig) Reset() { *x = InboundHandlerConfig{} mi := &file_app_proxyman_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InboundHandlerConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*InboundHandlerConfig) ProtoMessage() {} func (x *InboundHandlerConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InboundHandlerConfig.ProtoReflect.Descriptor instead. func (*InboundHandlerConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{4} } func (x *InboundHandlerConfig) GetTag() string { if x != nil { return x.Tag } return "" } func (x *InboundHandlerConfig) GetReceiverSettings() *anypb.Any { if x != nil { return x.ReceiverSettings } return nil } func (x *InboundHandlerConfig) GetProxySettings() *anypb.Any { if x != nil { return x.ProxySettings } return nil } type OutboundConfig struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *OutboundConfig) Reset() { *x = OutboundConfig{} mi := &file_app_proxyman_config_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *OutboundConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*OutboundConfig) ProtoMessage() {} func (x *OutboundConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OutboundConfig.ProtoReflect.Descriptor instead. func (*OutboundConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{5} } type SenderConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // Send traffic through the given IP. Only IP is allowed. Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"` StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"` ProxySettings *internet.ProxyConfig `protobuf:"bytes,3,opt,name=proxy_settings,json=proxySettings,proto3" json:"proxy_settings,omitempty"` MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"` DomainStrategy SenderConfig_DomainStrategy `protobuf:"varint,5,opt,name=domain_strategy,json=domainStrategy,proto3,enum=v2ray.core.app.proxyman.SenderConfig_DomainStrategy" json:"domain_strategy,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SenderConfig) Reset() { *x = SenderConfig{} mi := &file_app_proxyman_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SenderConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SenderConfig) ProtoMessage() {} func (x *SenderConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SenderConfig.ProtoReflect.Descriptor instead. func (*SenderConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{6} } func (x *SenderConfig) GetVia() *net.IPOrDomain { if x != nil { return x.Via } return nil } func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig { if x != nil { return x.StreamSettings } return nil } func (x *SenderConfig) GetProxySettings() *internet.ProxyConfig { if x != nil { return x.ProxySettings } return nil } func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig { if x != nil { return x.MultiplexSettings } return nil } func (x *SenderConfig) GetDomainStrategy() SenderConfig_DomainStrategy { if x != nil { return x.DomainStrategy } return SenderConfig_AS_IS } type MultiplexingConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // Whether or not Mux is enabled. Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"` // Max number of concurrent connections that one Mux connection can handle. Concurrency uint32 `protobuf:"varint,2,opt,name=concurrency,proto3" json:"concurrency,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MultiplexingConfig) Reset() { *x = MultiplexingConfig{} mi := &file_app_proxyman_config_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *MultiplexingConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*MultiplexingConfig) ProtoMessage() {} func (x *MultiplexingConfig) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MultiplexingConfig.ProtoReflect.Descriptor instead. func (*MultiplexingConfig) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{7} } func (x *MultiplexingConfig) GetEnabled() bool { if x != nil { return x.Enabled } return false } func (x *MultiplexingConfig) GetConcurrency() uint32 { if x != nil { return x.Concurrency } return 0 } type AllocationStrategy_AllocationStrategyConcurrency struct { state protoimpl.MessageState `protogen:"open.v1"` Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AllocationStrategy_AllocationStrategyConcurrency) Reset() { *x = AllocationStrategy_AllocationStrategyConcurrency{} mi := &file_app_proxyman_config_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AllocationStrategy_AllocationStrategyConcurrency) String() string { return protoimpl.X.MessageStringOf(x) } func (*AllocationStrategy_AllocationStrategyConcurrency) ProtoMessage() {} func (x *AllocationStrategy_AllocationStrategyConcurrency) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AllocationStrategy_AllocationStrategyConcurrency.ProtoReflect.Descriptor instead. func (*AllocationStrategy_AllocationStrategyConcurrency) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{1, 0} } func (x *AllocationStrategy_AllocationStrategyConcurrency) GetValue() uint32 { if x != nil { return x.Value } return 0 } type AllocationStrategy_AllocationStrategyRefresh struct { state protoimpl.MessageState `protogen:"open.v1"` Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AllocationStrategy_AllocationStrategyRefresh) Reset() { *x = AllocationStrategy_AllocationStrategyRefresh{} mi := &file_app_proxyman_config_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AllocationStrategy_AllocationStrategyRefresh) String() string { return protoimpl.X.MessageStringOf(x) } func (*AllocationStrategy_AllocationStrategyRefresh) ProtoMessage() {} func (x *AllocationStrategy_AllocationStrategyRefresh) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_config_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AllocationStrategy_AllocationStrategyRefresh.ProtoReflect.Descriptor instead. func (*AllocationStrategy_AllocationStrategyRefresh) Descriptor() ([]byte, []int) { return file_app_proxyman_config_proto_rawDescGZIP(), []int{1, 1} } func (x *AllocationStrategy_AllocationStrategyRefresh) GetValue() uint32 { if x != nil { return x.Value } return 0 } var File_app_proxyman_config_proto protoreflect.FileDescriptor const file_app_proxyman_config_proto_rawDesc = "" + "\n" + "\x19app/proxyman/config.proto\x12\x17v2ray.core.app.proxyman\x1a\x18common/net/address.proto\x1a\x15common/net/port.proto\x1a\x1ftransport/internet/config.proto\x1a\x19google/protobuf/any.proto\"\x0f\n" + "\rInboundConfig\"\xc0\x03\n" + "\x12AllocationStrategy\x12D\n" + "\x04type\x18\x01 \x01(\x0e20.v2ray.core.app.proxyman.AllocationStrategy.TypeR\x04type\x12k\n" + "\vconcurrency\x18\x02 \x01(\v2I.v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyConcurrencyR\vconcurrency\x12_\n" + "\arefresh\x18\x03 \x01(\v2E.v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyRefreshR\arefresh\x1a5\n" + "\x1dAllocationStrategyConcurrency\x12\x14\n" + "\x05value\x18\x01 \x01(\rR\x05value\x1a1\n" + "\x19AllocationStrategyRefresh\x12\x14\n" + "\x05value\x18\x01 \x01(\rR\x05value\",\n" + "\x04Type\x12\n" + "\n" + "\x06Always\x10\x00\x12\n" + "\n" + "\x06Random\x10\x01\x12\f\n" + "\bExternal\x10\x02\"\x82\x01\n" + "\x0eSniffingConfig\x12\x18\n" + "\aenabled\x18\x01 \x01(\bR\aenabled\x121\n" + "\x14destination_override\x18\x02 \x03(\tR\x13destinationOverride\x12#\n" + "\rmetadata_only\x18\x03 \x01(\bR\fmetadataOnly\"\xb4\x04\n" + "\x0eReceiverConfig\x12?\n" + "\n" + "port_range\x18\x01 \x01(\v2 .v2ray.core.common.net.PortRangeR\tportRange\x129\n" + "\x06listen\x18\x02 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\x06listen\x12\\\n" + "\x13allocation_strategy\x18\x03 \x01(\v2+.v2ray.core.app.proxyman.AllocationStrategyR\x12allocationStrategy\x12T\n" + "\x0fstream_settings\x18\x04 \x01(\v2+.v2ray.core.transport.internet.StreamConfigR\x0estreamSettings\x12@\n" + "\x1creceive_original_destination\x18\x05 \x01(\bR\x1areceiveOriginalDestination\x12T\n" + "\x0fdomain_override\x18\a \x03(\x0e2'.v2ray.core.app.proxyman.KnownProtocolsB\x02\x18\x01R\x0edomainOverride\x12T\n" + "\x11sniffing_settings\x18\b \x01(\v2'.v2ray.core.app.proxyman.SniffingConfigR\x10sniffingSettingsJ\x04\b\x06\x10\a\"\xa8\x01\n" + "\x14InboundHandlerConfig\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12A\n" + "\x11receiver_settings\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\x10receiverSettings\x12;\n" + "\x0eproxy_settings\x18\x03 \x01(\v2\x14.google.protobuf.AnyR\rproxySettings\"\x10\n" + "\x0eOutboundConfig\"\xea\x03\n" + "\fSenderConfig\x123\n" + "\x03via\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\x03via\x12T\n" + "\x0fstream_settings\x18\x02 \x01(\v2+.v2ray.core.transport.internet.StreamConfigR\x0estreamSettings\x12Q\n" + "\x0eproxy_settings\x18\x03 \x01(\v2*.v2ray.core.transport.internet.ProxyConfigR\rproxySettings\x12Z\n" + "\x12multiplex_settings\x18\x04 \x01(\v2+.v2ray.core.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12]\n" + "\x0fdomain_strategy\x18\x05 \x01(\x0e24.v2ray.core.app.proxyman.SenderConfig.DomainStrategyR\x0edomainStrategy\"A\n" + "\x0eDomainStrategy\x12\t\n" + "\x05AS_IS\x10\x00\x12\n" + "\n" + "\x06USE_IP\x10\x01\x12\v\n" + "\aUSE_IP4\x10\x02\x12\v\n" + "\aUSE_IP6\x10\x03\"P\n" + "\x12MultiplexingConfig\x12\x18\n" + "\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" + "\vconcurrency\x18\x02 \x01(\rR\vconcurrency*#\n" + "\x0eKnownProtocols\x12\b\n" + "\x04HTTP\x10\x00\x12\a\n" + "\x03TLS\x10\x01Bf\n" + "\x1bcom.v2ray.core.app.proxymanP\x01Z+github.com/v2fly/v2ray-core/v5/app/proxyman\xaa\x02\x17V2Ray.Core.App.Proxymanb\x06proto3" var ( file_app_proxyman_config_proto_rawDescOnce sync.Once file_app_proxyman_config_proto_rawDescData []byte ) func file_app_proxyman_config_proto_rawDescGZIP() []byte { file_app_proxyman_config_proto_rawDescOnce.Do(func() { file_app_proxyman_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc))) }) return file_app_proxyman_config_proto_rawDescData } var file_app_proxyman_config_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 10) var file_app_proxyman_config_proto_goTypes = []any{ (KnownProtocols)(0), // 0: v2ray.core.app.proxyman.KnownProtocols (AllocationStrategy_Type)(0), // 1: v2ray.core.app.proxyman.AllocationStrategy.Type (SenderConfig_DomainStrategy)(0), // 2: v2ray.core.app.proxyman.SenderConfig.DomainStrategy (*InboundConfig)(nil), // 3: v2ray.core.app.proxyman.InboundConfig (*AllocationStrategy)(nil), // 4: v2ray.core.app.proxyman.AllocationStrategy (*SniffingConfig)(nil), // 5: v2ray.core.app.proxyman.SniffingConfig (*ReceiverConfig)(nil), // 6: v2ray.core.app.proxyman.ReceiverConfig (*InboundHandlerConfig)(nil), // 7: v2ray.core.app.proxyman.InboundHandlerConfig (*OutboundConfig)(nil), // 8: v2ray.core.app.proxyman.OutboundConfig (*SenderConfig)(nil), // 9: v2ray.core.app.proxyman.SenderConfig (*MultiplexingConfig)(nil), // 10: v2ray.core.app.proxyman.MultiplexingConfig (*AllocationStrategy_AllocationStrategyConcurrency)(nil), // 11: v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyConcurrency (*AllocationStrategy_AllocationStrategyRefresh)(nil), // 12: v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyRefresh (*net.PortRange)(nil), // 13: v2ray.core.common.net.PortRange (*net.IPOrDomain)(nil), // 14: v2ray.core.common.net.IPOrDomain (*internet.StreamConfig)(nil), // 15: v2ray.core.transport.internet.StreamConfig (*anypb.Any)(nil), // 16: google.protobuf.Any (*internet.ProxyConfig)(nil), // 17: v2ray.core.transport.internet.ProxyConfig } var file_app_proxyman_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.app.proxyman.AllocationStrategy.type:type_name -> v2ray.core.app.proxyman.AllocationStrategy.Type 11, // 1: v2ray.core.app.proxyman.AllocationStrategy.concurrency:type_name -> v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyConcurrency 12, // 2: v2ray.core.app.proxyman.AllocationStrategy.refresh:type_name -> v2ray.core.app.proxyman.AllocationStrategy.AllocationStrategyRefresh 13, // 3: v2ray.core.app.proxyman.ReceiverConfig.port_range:type_name -> v2ray.core.common.net.PortRange 14, // 4: v2ray.core.app.proxyman.ReceiverConfig.listen:type_name -> v2ray.core.common.net.IPOrDomain 4, // 5: v2ray.core.app.proxyman.ReceiverConfig.allocation_strategy:type_name -> v2ray.core.app.proxyman.AllocationStrategy 15, // 6: v2ray.core.app.proxyman.ReceiverConfig.stream_settings:type_name -> v2ray.core.transport.internet.StreamConfig 0, // 7: v2ray.core.app.proxyman.ReceiverConfig.domain_override:type_name -> v2ray.core.app.proxyman.KnownProtocols 5, // 8: v2ray.core.app.proxyman.ReceiverConfig.sniffing_settings:type_name -> v2ray.core.app.proxyman.SniffingConfig 16, // 9: v2ray.core.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> google.protobuf.Any 16, // 10: v2ray.core.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> google.protobuf.Any 14, // 11: v2ray.core.app.proxyman.SenderConfig.via:type_name -> v2ray.core.common.net.IPOrDomain 15, // 12: v2ray.core.app.proxyman.SenderConfig.stream_settings:type_name -> v2ray.core.transport.internet.StreamConfig 17, // 13: v2ray.core.app.proxyman.SenderConfig.proxy_settings:type_name -> v2ray.core.transport.internet.ProxyConfig 10, // 14: v2ray.core.app.proxyman.SenderConfig.multiplex_settings:type_name -> v2ray.core.app.proxyman.MultiplexingConfig 2, // 15: v2ray.core.app.proxyman.SenderConfig.domain_strategy:type_name -> v2ray.core.app.proxyman.SenderConfig.DomainStrategy 16, // [16:16] is the sub-list for method output_type 16, // [16:16] is the sub-list for method input_type 16, // [16:16] is the sub-list for extension type_name 16, // [16:16] is the sub-list for extension extendee 0, // [0:16] is the sub-list for field type_name } func init() { file_app_proxyman_config_proto_init() } func file_app_proxyman_config_proto_init() { if File_app_proxyman_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)), NumEnums: 3, NumMessages: 10, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_proxyman_config_proto_goTypes, DependencyIndexes: file_app_proxyman_config_proto_depIdxs, EnumInfos: file_app_proxyman_config_proto_enumTypes, MessageInfos: file_app_proxyman_config_proto_msgTypes, }.Build() File_app_proxyman_config_proto = out.File file_app_proxyman_config_proto_goTypes = nil file_app_proxyman_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/command/command.pb.go
app/proxyman/command/command.pb.go
package command import ( v5 "github.com/v2fly/v2ray-core/v5" protocol "github.com/v2fly/v2ray-core/v5/common/protocol" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type AddUserOperation struct { state protoimpl.MessageState `protogen:"open.v1"` User *protocol.User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddUserOperation) Reset() { *x = AddUserOperation{} mi := &file_app_proxyman_command_command_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddUserOperation) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddUserOperation) ProtoMessage() {} func (x *AddUserOperation) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddUserOperation.ProtoReflect.Descriptor instead. func (*AddUserOperation) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{0} } func (x *AddUserOperation) GetUser() *protocol.User { if x != nil { return x.User } return nil } type RemoveUserOperation struct { state protoimpl.MessageState `protogen:"open.v1"` Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RemoveUserOperation) Reset() { *x = RemoveUserOperation{} mi := &file_app_proxyman_command_command_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RemoveUserOperation) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveUserOperation) ProtoMessage() {} func (x *RemoveUserOperation) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveUserOperation.ProtoReflect.Descriptor instead. func (*RemoveUserOperation) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{1} } func (x *RemoveUserOperation) GetEmail() string { if x != nil { return x.Email } return "" } type AddInboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Inbound *v5.InboundHandlerConfig `protobuf:"bytes,1,opt,name=inbound,proto3" json:"inbound,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddInboundRequest) Reset() { *x = AddInboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddInboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddInboundRequest) ProtoMessage() {} func (x *AddInboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddInboundRequest.ProtoReflect.Descriptor instead. func (*AddInboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{2} } func (x *AddInboundRequest) GetInbound() *v5.InboundHandlerConfig { if x != nil { return x.Inbound } return nil } type AddInboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddInboundResponse) Reset() { *x = AddInboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddInboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddInboundResponse) ProtoMessage() {} func (x *AddInboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddInboundResponse.ProtoReflect.Descriptor instead. func (*AddInboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{3} } type RemoveInboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RemoveInboundRequest) Reset() { *x = RemoveInboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RemoveInboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveInboundRequest) ProtoMessage() {} func (x *RemoveInboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveInboundRequest.ProtoReflect.Descriptor instead. func (*RemoveInboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{4} } func (x *RemoveInboundRequest) GetTag() string { if x != nil { return x.Tag } return "" } type RemoveInboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RemoveInboundResponse) Reset() { *x = RemoveInboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RemoveInboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveInboundResponse) ProtoMessage() {} func (x *RemoveInboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveInboundResponse.ProtoReflect.Descriptor instead. func (*RemoveInboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{5} } type AlterInboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` Operation *anypb.Any `protobuf:"bytes,2,opt,name=operation,proto3" json:"operation,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AlterInboundRequest) Reset() { *x = AlterInboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AlterInboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlterInboundRequest) ProtoMessage() {} func (x *AlterInboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlterInboundRequest.ProtoReflect.Descriptor instead. func (*AlterInboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{6} } func (x *AlterInboundRequest) GetTag() string { if x != nil { return x.Tag } return "" } func (x *AlterInboundRequest) GetOperation() *anypb.Any { if x != nil { return x.Operation } return nil } type AlterInboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AlterInboundResponse) Reset() { *x = AlterInboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AlterInboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlterInboundResponse) ProtoMessage() {} func (x *AlterInboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlterInboundResponse.ProtoReflect.Descriptor instead. func (*AlterInboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{7} } type AddOutboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Outbound *v5.OutboundHandlerConfig `protobuf:"bytes,1,opt,name=outbound,proto3" json:"outbound,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddOutboundRequest) Reset() { *x = AddOutboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddOutboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddOutboundRequest) ProtoMessage() {} func (x *AddOutboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddOutboundRequest.ProtoReflect.Descriptor instead. func (*AddOutboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{8} } func (x *AddOutboundRequest) GetOutbound() *v5.OutboundHandlerConfig { if x != nil { return x.Outbound } return nil } type AddOutboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddOutboundResponse) Reset() { *x = AddOutboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AddOutboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddOutboundResponse) ProtoMessage() {} func (x *AddOutboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddOutboundResponse.ProtoReflect.Descriptor instead. func (*AddOutboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{9} } type RemoveOutboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RemoveOutboundRequest) Reset() { *x = RemoveOutboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RemoveOutboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveOutboundRequest) ProtoMessage() {} func (x *RemoveOutboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveOutboundRequest.ProtoReflect.Descriptor instead. func (*RemoveOutboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{10} } func (x *RemoveOutboundRequest) GetTag() string { if x != nil { return x.Tag } return "" } type RemoveOutboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RemoveOutboundResponse) Reset() { *x = RemoveOutboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RemoveOutboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveOutboundResponse) ProtoMessage() {} func (x *RemoveOutboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveOutboundResponse.ProtoReflect.Descriptor instead. func (*RemoveOutboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{11} } type AlterOutboundRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` Operation *anypb.Any `protobuf:"bytes,2,opt,name=operation,proto3" json:"operation,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AlterOutboundRequest) Reset() { *x = AlterOutboundRequest{} mi := &file_app_proxyman_command_command_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AlterOutboundRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlterOutboundRequest) ProtoMessage() {} func (x *AlterOutboundRequest) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlterOutboundRequest.ProtoReflect.Descriptor instead. func (*AlterOutboundRequest) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{12} } func (x *AlterOutboundRequest) GetTag() string { if x != nil { return x.Tag } return "" } func (x *AlterOutboundRequest) GetOperation() *anypb.Any { if x != nil { return x.Operation } return nil } type AlterOutboundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AlterOutboundResponse) Reset() { *x = AlterOutboundResponse{} mi := &file_app_proxyman_command_command_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AlterOutboundResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlterOutboundResponse) ProtoMessage() {} func (x *AlterOutboundResponse) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlterOutboundResponse.ProtoReflect.Descriptor instead. func (*AlterOutboundResponse) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{13} } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_proxyman_command_command_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_proxyman_command_command_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_proxyman_command_command_proto_rawDescGZIP(), []int{14} } var File_app_proxyman_command_command_proto protoreflect.FileDescriptor const file_app_proxyman_command_command_proto_rawDesc = "" + "\n" + "\"app/proxyman/command/command.proto\x12\x1fv2ray.core.app.proxyman.command\x1a\x1acommon/protocol/user.proto\x1a\x19google/protobuf/any.proto\x1a common/protoext/extensions.proto\x1a\fconfig.proto\"H\n" + "\x10AddUserOperation\x124\n" + "\x04user\x18\x01 \x01(\v2 .v2ray.core.common.protocol.UserR\x04user\"+\n" + "\x13RemoveUserOperation\x12\x14\n" + "\x05email\x18\x01 \x01(\tR\x05email\"O\n" + "\x11AddInboundRequest\x12:\n" + "\ainbound\x18\x01 \x01(\v2 .v2ray.core.InboundHandlerConfigR\ainbound\"\x14\n" + "\x12AddInboundResponse\"(\n" + "\x14RemoveInboundRequest\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\"\x17\n" + "\x15RemoveInboundResponse\"[\n" + "\x13AlterInboundRequest\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x122\n" + "\toperation\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\toperation\"\x16\n" + "\x14AlterInboundResponse\"S\n" + "\x12AddOutboundRequest\x12=\n" + "\boutbound\x18\x01 \x01(\v2!.v2ray.core.OutboundHandlerConfigR\boutbound\"\x15\n" + "\x13AddOutboundResponse\")\n" + "\x15RemoveOutboundRequest\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\"\x18\n" + "\x16RemoveOutboundResponse\"\\\n" + "\x14AlterOutboundRequest\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x122\n" + "\toperation\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\toperation\"\x17\n" + "\x15AlterOutboundResponse\"%\n" + "\x06Config:\x1b\x82\xb5\x18\x17\n" + "\vgrpcservice\x12\bproxyman2\x90\x06\n" + "\x0eHandlerService\x12w\n" + "\n" + "AddInbound\x122.v2ray.core.app.proxyman.command.AddInboundRequest\x1a3.v2ray.core.app.proxyman.command.AddInboundResponse\"\x00\x12\x80\x01\n" + "\rRemoveInbound\x125.v2ray.core.app.proxyman.command.RemoveInboundRequest\x1a6.v2ray.core.app.proxyman.command.RemoveInboundResponse\"\x00\x12}\n" + "\fAlterInbound\x124.v2ray.core.app.proxyman.command.AlterInboundRequest\x1a5.v2ray.core.app.proxyman.command.AlterInboundResponse\"\x00\x12z\n" + "\vAddOutbound\x123.v2ray.core.app.proxyman.command.AddOutboundRequest\x1a4.v2ray.core.app.proxyman.command.AddOutboundResponse\"\x00\x12\x83\x01\n" + "\x0eRemoveOutbound\x126.v2ray.core.app.proxyman.command.RemoveOutboundRequest\x1a7.v2ray.core.app.proxyman.command.RemoveOutboundResponse\"\x00\x12\x80\x01\n" + "\rAlterOutbound\x125.v2ray.core.app.proxyman.command.AlterOutboundRequest\x1a6.v2ray.core.app.proxyman.command.AlterOutboundResponse\"\x00B~\n" + "#com.v2ray.core.app.proxyman.commandP\x01Z3github.com/v2fly/v2ray-core/v5/app/proxyman/command\xaa\x02\x1fV2Ray.Core.App.Proxyman.Commandb\x06proto3" var ( file_app_proxyman_command_command_proto_rawDescOnce sync.Once file_app_proxyman_command_command_proto_rawDescData []byte ) func file_app_proxyman_command_command_proto_rawDescGZIP() []byte { file_app_proxyman_command_command_proto_rawDescOnce.Do(func() { file_app_proxyman_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_proxyman_command_command_proto_rawDesc), len(file_app_proxyman_command_command_proto_rawDesc))) }) return file_app_proxyman_command_command_proto_rawDescData } var file_app_proxyman_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 15) var file_app_proxyman_command_command_proto_goTypes = []any{ (*AddUserOperation)(nil), // 0: v2ray.core.app.proxyman.command.AddUserOperation (*RemoveUserOperation)(nil), // 1: v2ray.core.app.proxyman.command.RemoveUserOperation (*AddInboundRequest)(nil), // 2: v2ray.core.app.proxyman.command.AddInboundRequest (*AddInboundResponse)(nil), // 3: v2ray.core.app.proxyman.command.AddInboundResponse (*RemoveInboundRequest)(nil), // 4: v2ray.core.app.proxyman.command.RemoveInboundRequest (*RemoveInboundResponse)(nil), // 5: v2ray.core.app.proxyman.command.RemoveInboundResponse (*AlterInboundRequest)(nil), // 6: v2ray.core.app.proxyman.command.AlterInboundRequest (*AlterInboundResponse)(nil), // 7: v2ray.core.app.proxyman.command.AlterInboundResponse (*AddOutboundRequest)(nil), // 8: v2ray.core.app.proxyman.command.AddOutboundRequest (*AddOutboundResponse)(nil), // 9: v2ray.core.app.proxyman.command.AddOutboundResponse (*RemoveOutboundRequest)(nil), // 10: v2ray.core.app.proxyman.command.RemoveOutboundRequest (*RemoveOutboundResponse)(nil), // 11: v2ray.core.app.proxyman.command.RemoveOutboundResponse (*AlterOutboundRequest)(nil), // 12: v2ray.core.app.proxyman.command.AlterOutboundRequest (*AlterOutboundResponse)(nil), // 13: v2ray.core.app.proxyman.command.AlterOutboundResponse (*Config)(nil), // 14: v2ray.core.app.proxyman.command.Config (*protocol.User)(nil), // 15: v2ray.core.common.protocol.User (*v5.InboundHandlerConfig)(nil), // 16: v2ray.core.InboundHandlerConfig (*anypb.Any)(nil), // 17: google.protobuf.Any (*v5.OutboundHandlerConfig)(nil), // 18: v2ray.core.OutboundHandlerConfig } var file_app_proxyman_command_command_proto_depIdxs = []int32{ 15, // 0: v2ray.core.app.proxyman.command.AddUserOperation.user:type_name -> v2ray.core.common.protocol.User 16, // 1: v2ray.core.app.proxyman.command.AddInboundRequest.inbound:type_name -> v2ray.core.InboundHandlerConfig 17, // 2: v2ray.core.app.proxyman.command.AlterInboundRequest.operation:type_name -> google.protobuf.Any 18, // 3: v2ray.core.app.proxyman.command.AddOutboundRequest.outbound:type_name -> v2ray.core.OutboundHandlerConfig 17, // 4: v2ray.core.app.proxyman.command.AlterOutboundRequest.operation:type_name -> google.protobuf.Any 2, // 5: v2ray.core.app.proxyman.command.HandlerService.AddInbound:input_type -> v2ray.core.app.proxyman.command.AddInboundRequest 4, // 6: v2ray.core.app.proxyman.command.HandlerService.RemoveInbound:input_type -> v2ray.core.app.proxyman.command.RemoveInboundRequest 6, // 7: v2ray.core.app.proxyman.command.HandlerService.AlterInbound:input_type -> v2ray.core.app.proxyman.command.AlterInboundRequest 8, // 8: v2ray.core.app.proxyman.command.HandlerService.AddOutbound:input_type -> v2ray.core.app.proxyman.command.AddOutboundRequest 10, // 9: v2ray.core.app.proxyman.command.HandlerService.RemoveOutbound:input_type -> v2ray.core.app.proxyman.command.RemoveOutboundRequest 12, // 10: v2ray.core.app.proxyman.command.HandlerService.AlterOutbound:input_type -> v2ray.core.app.proxyman.command.AlterOutboundRequest 3, // 11: v2ray.core.app.proxyman.command.HandlerService.AddInbound:output_type -> v2ray.core.app.proxyman.command.AddInboundResponse 5, // 12: v2ray.core.app.proxyman.command.HandlerService.RemoveInbound:output_type -> v2ray.core.app.proxyman.command.RemoveInboundResponse 7, // 13: v2ray.core.app.proxyman.command.HandlerService.AlterInbound:output_type -> v2ray.core.app.proxyman.command.AlterInboundResponse 9, // 14: v2ray.core.app.proxyman.command.HandlerService.AddOutbound:output_type -> v2ray.core.app.proxyman.command.AddOutboundResponse 11, // 15: v2ray.core.app.proxyman.command.HandlerService.RemoveOutbound:output_type -> v2ray.core.app.proxyman.command.RemoveOutboundResponse 13, // 16: v2ray.core.app.proxyman.command.HandlerService.AlterOutbound:output_type -> v2ray.core.app.proxyman.command.AlterOutboundResponse 11, // [11:17] is the sub-list for method output_type 5, // [5:11] is the sub-list for method input_type 5, // [5:5] is the sub-list for extension type_name 5, // [5:5] is the sub-list for extension extendee 0, // [0:5] is the sub-list for field type_name } func init() { file_app_proxyman_command_command_proto_init() } func file_app_proxyman_command_command_proto_init() { if File_app_proxyman_command_command_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_command_command_proto_rawDesc), len(file_app_proxyman_command_command_proto_rawDesc)), NumEnums: 0, NumMessages: 15, NumExtensions: 0, NumServices: 1, }, GoTypes: file_app_proxyman_command_command_proto_goTypes, DependencyIndexes: file_app_proxyman_command_command_proto_depIdxs, MessageInfos: file_app_proxyman_command_command_proto_msgTypes, }.Build() File_app_proxyman_command_command_proto = out.File file_app_proxyman_command_command_proto_goTypes = nil file_app_proxyman_command_command_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/command/errors.generated.go
app/proxyman/command/errors.generated.go
package command import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/command/command_grpc.pb.go
app/proxyman/command/command_grpc.pb.go
package command import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( HandlerService_AddInbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/AddInbound" HandlerService_RemoveInbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/RemoveInbound" HandlerService_AlterInbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/AlterInbound" HandlerService_AddOutbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/AddOutbound" HandlerService_RemoveOutbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/RemoveOutbound" HandlerService_AlterOutbound_FullMethodName = "/v2ray.core.app.proxyman.command.HandlerService/AlterOutbound" ) // HandlerServiceClient is the client API for HandlerService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type HandlerServiceClient interface { AddInbound(ctx context.Context, in *AddInboundRequest, opts ...grpc.CallOption) (*AddInboundResponse, error) RemoveInbound(ctx context.Context, in *RemoveInboundRequest, opts ...grpc.CallOption) (*RemoveInboundResponse, error) AlterInbound(ctx context.Context, in *AlterInboundRequest, opts ...grpc.CallOption) (*AlterInboundResponse, error) AddOutbound(ctx context.Context, in *AddOutboundRequest, opts ...grpc.CallOption) (*AddOutboundResponse, error) RemoveOutbound(ctx context.Context, in *RemoveOutboundRequest, opts ...grpc.CallOption) (*RemoveOutboundResponse, error) AlterOutbound(ctx context.Context, in *AlterOutboundRequest, opts ...grpc.CallOption) (*AlterOutboundResponse, error) } type handlerServiceClient struct { cc grpc.ClientConnInterface } func NewHandlerServiceClient(cc grpc.ClientConnInterface) HandlerServiceClient { return &handlerServiceClient{cc} } func (c *handlerServiceClient) AddInbound(ctx context.Context, in *AddInboundRequest, opts ...grpc.CallOption) (*AddInboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(AddInboundResponse) err := c.cc.Invoke(ctx, HandlerService_AddInbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *handlerServiceClient) RemoveInbound(ctx context.Context, in *RemoveInboundRequest, opts ...grpc.CallOption) (*RemoveInboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(RemoveInboundResponse) err := c.cc.Invoke(ctx, HandlerService_RemoveInbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *handlerServiceClient) AlterInbound(ctx context.Context, in *AlterInboundRequest, opts ...grpc.CallOption) (*AlterInboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(AlterInboundResponse) err := c.cc.Invoke(ctx, HandlerService_AlterInbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *handlerServiceClient) AddOutbound(ctx context.Context, in *AddOutboundRequest, opts ...grpc.CallOption) (*AddOutboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(AddOutboundResponse) err := c.cc.Invoke(ctx, HandlerService_AddOutbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *handlerServiceClient) RemoveOutbound(ctx context.Context, in *RemoveOutboundRequest, opts ...grpc.CallOption) (*RemoveOutboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(RemoveOutboundResponse) err := c.cc.Invoke(ctx, HandlerService_RemoveOutbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *handlerServiceClient) AlterOutbound(ctx context.Context, in *AlterOutboundRequest, opts ...grpc.CallOption) (*AlterOutboundResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(AlterOutboundResponse) err := c.cc.Invoke(ctx, HandlerService_AlterOutbound_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // HandlerServiceServer is the server API for HandlerService service. // All implementations must embed UnimplementedHandlerServiceServer // for forward compatibility. type HandlerServiceServer interface { AddInbound(context.Context, *AddInboundRequest) (*AddInboundResponse, error) RemoveInbound(context.Context, *RemoveInboundRequest) (*RemoveInboundResponse, error) AlterInbound(context.Context, *AlterInboundRequest) (*AlterInboundResponse, error) AddOutbound(context.Context, *AddOutboundRequest) (*AddOutboundResponse, error) RemoveOutbound(context.Context, *RemoveOutboundRequest) (*RemoveOutboundResponse, error) AlterOutbound(context.Context, *AlterOutboundRequest) (*AlterOutboundResponse, error) mustEmbedUnimplementedHandlerServiceServer() } // UnimplementedHandlerServiceServer must be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedHandlerServiceServer struct{} func (UnimplementedHandlerServiceServer) AddInbound(context.Context, *AddInboundRequest) (*AddInboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method AddInbound not implemented") } func (UnimplementedHandlerServiceServer) RemoveInbound(context.Context, *RemoveInboundRequest) (*RemoveInboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RemoveInbound not implemented") } func (UnimplementedHandlerServiceServer) AlterInbound(context.Context, *AlterInboundRequest) (*AlterInboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method AlterInbound not implemented") } func (UnimplementedHandlerServiceServer) AddOutbound(context.Context, *AddOutboundRequest) (*AddOutboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method AddOutbound not implemented") } func (UnimplementedHandlerServiceServer) RemoveOutbound(context.Context, *RemoveOutboundRequest) (*RemoveOutboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RemoveOutbound not implemented") } func (UnimplementedHandlerServiceServer) AlterOutbound(context.Context, *AlterOutboundRequest) (*AlterOutboundResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method AlterOutbound not implemented") } func (UnimplementedHandlerServiceServer) mustEmbedUnimplementedHandlerServiceServer() {} func (UnimplementedHandlerServiceServer) testEmbeddedByValue() {} // UnsafeHandlerServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to HandlerServiceServer will // result in compilation errors. type UnsafeHandlerServiceServer interface { mustEmbedUnimplementedHandlerServiceServer() } func RegisterHandlerServiceServer(s grpc.ServiceRegistrar, srv HandlerServiceServer) { // If the following call pancis, it indicates UnimplementedHandlerServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&HandlerService_ServiceDesc, srv) } func _HandlerService_AddInbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddInboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).AddInbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_AddInbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).AddInbound(ctx, req.(*AddInboundRequest)) } return interceptor(ctx, in, info, handler) } func _HandlerService_RemoveInbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RemoveInboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).RemoveInbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_RemoveInbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).RemoveInbound(ctx, req.(*RemoveInboundRequest)) } return interceptor(ctx, in, info, handler) } func _HandlerService_AlterInbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AlterInboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).AlterInbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_AlterInbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).AlterInbound(ctx, req.(*AlterInboundRequest)) } return interceptor(ctx, in, info, handler) } func _HandlerService_AddOutbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddOutboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).AddOutbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_AddOutbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).AddOutbound(ctx, req.(*AddOutboundRequest)) } return interceptor(ctx, in, info, handler) } func _HandlerService_RemoveOutbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RemoveOutboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).RemoveOutbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_RemoveOutbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).RemoveOutbound(ctx, req.(*RemoveOutboundRequest)) } return interceptor(ctx, in, info, handler) } func _HandlerService_AlterOutbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AlterOutboundRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(HandlerServiceServer).AlterOutbound(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: HandlerService_AlterOutbound_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HandlerServiceServer).AlterOutbound(ctx, req.(*AlterOutboundRequest)) } return interceptor(ctx, in, info, handler) } // HandlerService_ServiceDesc is the grpc.ServiceDesc for HandlerService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var HandlerService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "v2ray.core.app.proxyman.command.HandlerService", HandlerType: (*HandlerServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "AddInbound", Handler: _HandlerService_AddInbound_Handler, }, { MethodName: "RemoveInbound", Handler: _HandlerService_RemoveInbound_Handler, }, { MethodName: "AlterInbound", Handler: _HandlerService_AlterInbound_Handler, }, { MethodName: "AddOutbound", Handler: _HandlerService_AddOutbound_Handler, }, { MethodName: "RemoveOutbound", Handler: _HandlerService_RemoveOutbound_Handler, }, { MethodName: "AlterOutbound", Handler: _HandlerService_AlterOutbound_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "app/proxyman/command/command.proto", }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/command/command.go
app/proxyman/command/command.go
package command import ( "context" grpc "google.golang.org/grpc" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/features/inbound" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/proxy" ) // InboundOperation is the interface for operations that applies to inbound handlers. type InboundOperation interface { // ApplyInbound applies this operation to the given inbound handler. ApplyInbound(context.Context, inbound.Handler) error } // OutboundOperation is the interface for operations that applies to outbound handlers. type OutboundOperation interface { // ApplyOutbound applies this operation to the given outbound handler. ApplyOutbound(context.Context, outbound.Handler) error } func getInbound(handler inbound.Handler) (proxy.Inbound, error) { gi, ok := handler.(proxy.GetInbound) if !ok { return nil, newError("can't get inbound proxy from handler.") } return gi.GetInbound(), nil } // ApplyInbound implements InboundOperation. func (op *AddUserOperation) ApplyInbound(ctx context.Context, handler inbound.Handler) error { p, err := getInbound(handler) if err != nil { return err } um, ok := p.(proxy.UserManager) if !ok { return newError("proxy is not a UserManager") } mUser, err := op.User.ToMemoryUser() if err != nil { return newError("failed to parse user").Base(err) } return um.AddUser(ctx, mUser) } // ApplyInbound implements InboundOperation. func (op *RemoveUserOperation) ApplyInbound(ctx context.Context, handler inbound.Handler) error { p, err := getInbound(handler) if err != nil { return err } um, ok := p.(proxy.UserManager) if !ok { return newError("proxy is not a UserManager") } return um.RemoveUser(ctx, op.Email) } type handlerServer struct { s *core.Instance ihm inbound.Manager ohm outbound.Manager } func (s *handlerServer) AddInbound(ctx context.Context, request *AddInboundRequest) (*AddInboundResponse, error) { if err := core.AddInboundHandler(s.s, request.Inbound); err != nil { return nil, err } return &AddInboundResponse{}, nil } func (s *handlerServer) RemoveInbound(ctx context.Context, request *RemoveInboundRequest) (*RemoveInboundResponse, error) { return &RemoveInboundResponse{}, s.ihm.RemoveHandler(ctx, request.Tag) } func (s *handlerServer) AlterInbound(ctx context.Context, request *AlterInboundRequest) (*AlterInboundResponse, error) { rawOperation, err := serial.GetInstanceOf(request.Operation) if err != nil { return nil, newError("unknown operation").Base(err) } operation, ok := rawOperation.(InboundOperation) if !ok { return nil, newError("not an inbound operation") } handler, err := s.ihm.GetHandler(ctx, request.Tag) if err != nil { return nil, newError("failed to get handler: ", request.Tag).Base(err) } return &AlterInboundResponse{}, operation.ApplyInbound(ctx, handler) } func (s *handlerServer) AddOutbound(ctx context.Context, request *AddOutboundRequest) (*AddOutboundResponse, error) { if err := core.AddOutboundHandler(s.s, request.Outbound); err != nil { return nil, err } return &AddOutboundResponse{}, nil } func (s *handlerServer) RemoveOutbound(ctx context.Context, request *RemoveOutboundRequest) (*RemoveOutboundResponse, error) { return &RemoveOutboundResponse{}, core.RemoveOutboundHandler(s.s, request.Tag) } func (s *handlerServer) AlterOutbound(ctx context.Context, request *AlterOutboundRequest) (*AlterOutboundResponse, error) { rawOperation, err := serial.GetInstanceOf(request.Operation) if err != nil { return nil, newError("unknown operation").Base(err) } operation, ok := rawOperation.(OutboundOperation) if !ok { return nil, newError("not an outbound operation") } handler := s.ohm.GetHandler(request.Tag) return &AlterOutboundResponse{}, operation.ApplyOutbound(ctx, handler) } func (s *handlerServer) mustEmbedUnimplementedHandlerServiceServer() {} type service struct { v *core.Instance } func (s *service) Register(server *grpc.Server) { hs := &handlerServer{ s: s.v, } common.Must(s.v.RequireFeatures(func(im inbound.Manager, om outbound.Manager) { hs.ihm = im hs.ohm = om })) RegisterHandlerServiceServer(server, hs) } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { s := core.MustFromContext(ctx) return &service{v: s}, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/command/doc.go
app/proxyman/command/doc.go
package command //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/outbound/handler_test.go
app/proxyman/outbound/handler_test.go
package outbound_test import ( "context" "testing" _ "unsafe" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/policy" . "github.com/v2fly/v2ray-core/v5/app/proxyman/outbound" "github.com/v2fly/v2ray-core/v5/app/stats" "github.com/v2fly/v2ray-core/v5/common/environment" "github.com/v2fly/v2ray-core/v5/common/environment/deferredpersistentstorage" "github.com/v2fly/v2ray-core/v5/common/environment/envctx" "github.com/v2fly/v2ray-core/v5/common/environment/filesystemimpl" "github.com/v2fly/v2ray-core/v5/common/environment/systemnetworkimpl" "github.com/v2fly/v2ray-core/v5/common/environment/transientstorageimpl" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/proxy/freedom" "github.com/v2fly/v2ray-core/v5/transport/internet" ) func TestInterfaces(t *testing.T) { _ = (outbound.Handler)(new(Handler)) _ = (outbound.Manager)(new(Manager)) } //go:linkname toContext github.com/v2fly/v2ray-core/v5.toContext func toContext(ctx context.Context, v *core.Instance) context.Context func TestOutboundWithoutStatCounter(t *testing.T) { config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&stats.Config{}), serial.ToTypedMessage(&policy.Config{ System: &policy.SystemPolicy{ Stats: &policy.SystemPolicy_Stats{ InboundUplink: true, }, }, }), }, } v, _ := core.New(config) v.AddFeature((outbound.Manager)(new(Manager))) ctx := toContext(context.Background(), v) defaultNetworkImpl := systemnetworkimpl.NewSystemNetworkDefault() defaultFilesystemImpl := filesystemimpl.NewDefaultFileSystemDefaultImpl() deferredPersistentStorageImpl := deferredpersistentstorage.NewDeferredPersistentStorage(ctx) rootEnv := environment.NewRootEnvImpl(ctx, transientstorageimpl.NewScopedTransientStorageImpl(), defaultNetworkImpl.Dialer(), defaultNetworkImpl.Listener(), defaultFilesystemImpl, deferredPersistentStorageImpl) proxyEnvironment := rootEnv.ProxyEnvironment("o") ctx = envctx.ContextWithEnvironment(ctx, proxyEnvironment) h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ Tag: "tag", ProxySettings: serial.ToTypedMessage(&freedom.Config{}), }) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) _, ok := conn.(*internet.StatCouterConnection) if ok { t.Errorf("Expected conn to not be StatCouterConnection") } } func TestOutboundWithStatCounter(t *testing.T) { config := &core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&stats.Config{}), serial.ToTypedMessage(&policy.Config{ System: &policy.SystemPolicy{ Stats: &policy.SystemPolicy_Stats{ OutboundUplink: true, OutboundDownlink: true, }, }, }), }, } v, _ := core.New(config) v.AddFeature((outbound.Manager)(new(Manager))) ctx := toContext(context.Background(), v) defaultNetworkImpl := systemnetworkimpl.NewSystemNetworkDefault() defaultFilesystemImpl := filesystemimpl.NewDefaultFileSystemDefaultImpl() deferredPersistentStorageImpl := deferredpersistentstorage.NewDeferredPersistentStorage(ctx) rootEnv := environment.NewRootEnvImpl(ctx, transientstorageimpl.NewScopedTransientStorageImpl(), defaultNetworkImpl.Dialer(), defaultNetworkImpl.Listener(), defaultFilesystemImpl, deferredPersistentStorageImpl) proxyEnvironment := rootEnv.ProxyEnvironment("o") ctx = envctx.ContextWithEnvironment(ctx, proxyEnvironment) h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ Tag: "tag", ProxySettings: serial.ToTypedMessage(&freedom.Config{}), }) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) _, ok := conn.(*internet.StatCouterConnection) if !ok { t.Errorf("Expected conn to be StatCouterConnection") } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/outbound/errors.generated.go
app/proxyman/outbound/errors.generated.go
package outbound import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/outbound/outbound.go
app/proxyman/outbound/outbound.go
package outbound //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "strings" "sync" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/outbound" ) // Manager is to manage all outbound handlers. type Manager struct { access sync.RWMutex defaultHandler outbound.Handler taggedHandler map[string]outbound.Handler untaggedHandlers []outbound.Handler running bool } // New creates a new Manager. func New(ctx context.Context, config *proxyman.OutboundConfig) (*Manager, error) { m := &Manager{ taggedHandler: make(map[string]outbound.Handler), } return m, nil } // Type implements common.HasType. func (m *Manager) Type() interface{} { return outbound.ManagerType() } // Start implements core.Feature func (m *Manager) Start() error { m.access.Lock() defer m.access.Unlock() m.running = true for _, h := range m.taggedHandler { if err := h.Start(); err != nil { return err } } for _, h := range m.untaggedHandlers { if err := h.Start(); err != nil { return err } } return nil } // Close implements core.Feature func (m *Manager) Close() error { m.access.Lock() defer m.access.Unlock() m.running = false var errs []error for _, h := range m.taggedHandler { errs = append(errs, h.Close()) } for _, h := range m.untaggedHandlers { errs = append(errs, h.Close()) } return errors.Combine(errs...) } // GetDefaultHandler implements outbound.Manager. func (m *Manager) GetDefaultHandler() outbound.Handler { m.access.RLock() defer m.access.RUnlock() return m.defaultHandler } // GetHandler implements outbound.Manager. func (m *Manager) GetHandler(tag string) outbound.Handler { m.access.RLock() defer m.access.RUnlock() if handler, found := m.taggedHandler[tag]; found { return handler } return nil } // AddHandler implements outbound.Manager. func (m *Manager) AddHandler(ctx context.Context, handler outbound.Handler) error { m.access.Lock() defer m.access.Unlock() tag := handler.Tag() if m.defaultHandler == nil || (len(tag) > 0 && tag == m.defaultHandler.Tag()) { m.defaultHandler = handler } if len(tag) > 0 { if oldHandler, found := m.taggedHandler[tag]; found { errors.New("will replace the existed outbound with the tag: " + tag).AtWarning().WriteToLog() _ = oldHandler.Close() } m.taggedHandler[tag] = handler } else { m.untaggedHandlers = append(m.untaggedHandlers, handler) } if m.running { return handler.Start() } return nil } // RemoveHandler implements outbound.Manager. func (m *Manager) RemoveHandler(ctx context.Context, tag string) error { if tag == "" { return common.ErrNoClue } m.access.Lock() defer m.access.Unlock() if handler, found := m.taggedHandler[tag]; found { if err := handler.Close(); err != nil { newError("failed to close handler ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) } delete(m.taggedHandler, tag) if m.defaultHandler != nil && m.defaultHandler.Tag() == tag { m.defaultHandler = nil } return nil } return common.ErrNoClue } // Select implements outbound.HandlerSelector. func (m *Manager) Select(selectors []string) []string { m.access.RLock() defer m.access.RUnlock() tags := make([]string, 0, len(selectors)) for tag := range m.taggedHandler { match := false for _, selector := range selectors { if strings.HasPrefix(tag, selector) { match = true break } } if match { tags = append(tags, tag) } } return tags } func init() { common.Must(common.RegisterConfig((*proxyman.OutboundConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*proxyman.OutboundConfig)) })) common.Must(common.RegisterConfig((*core.OutboundHandlerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewHandler(ctx, config.(*core.OutboundHandlerConfig)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/outbound/handler.go
app/proxyman/outbound/handler.go
package outbound import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/common/environment" "github.com/v2fly/v2ray-core/v5/common/environment/envctx" "github.com/v2fly/v2ray-core/v5/common/mux" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/features/stats" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/security" "github.com/v2fly/v2ray-core/v5/transport/pipe" ) func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) { var uplinkCounter stats.Counter var downlinkCounter stats.Counter policy := v.GetFeature(policy.ManagerType()).(policy.Manager) if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink { statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager) name := "outbound>>>" + tag + ">>>traffic>>>uplink" c, _ := stats.GetOrRegisterCounter(statsManager, name) if c != nil { uplinkCounter = c } } if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink { statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager) name := "outbound>>>" + tag + ">>>traffic>>>downlink" c, _ := stats.GetOrRegisterCounter(statsManager, name) if c != nil { downlinkCounter = c } } return uplinkCounter, downlinkCounter } // Handler is an implements of outbound.Handler. type Handler struct { ctx context.Context tag string senderSettings *proxyman.SenderConfig streamSettings *internet.MemoryStreamConfig proxy proxy.Outbound outboundManager outbound.Manager mux *mux.ClientManager uplinkCounter stats.Counter downlinkCounter stats.Counter dns dns.Client } // NewHandler create a new Handler based on the given configuration. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) { v := core.MustFromContext(ctx) uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag) h := &Handler{ ctx: ctx, tag: config.Tag, outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, } if config.SenderSettings != nil { senderSettings, err := serial.GetInstanceOf(config.SenderSettings) if err != nil { return nil, err } switch s := senderSettings.(type) { case *proxyman.SenderConfig: h.senderSettings = s mss, err := internet.ToMemoryStreamConfig(s.StreamSettings) if err != nil { return nil, newError("failed to parse stream settings").Base(err).AtWarning() } h.streamSettings = mss default: return nil, newError("settings is not SenderConfig") } } proxyConfig, err := serial.GetInstanceOf(config.ProxySettings) if err != nil { return nil, err } rawProxyHandler, err := common.CreateObject(ctx, proxyConfig) if err != nil { return nil, err } proxyHandler, ok := rawProxyHandler.(proxy.Outbound) if !ok { return nil, newError("not an outbound handler") } if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil { config := h.senderSettings.MultiplexSettings if config.Concurrency < 1 || config.Concurrency > 1024 { return nil, newError("invalid mux concurrency: ", config.Concurrency).AtWarning() } h.mux = &mux.ClientManager{ Enabled: h.senderSettings.MultiplexSettings.Enabled, Picker: &mux.IncrementalWorkerPicker{ Factory: mux.NewDialingWorkerFactory( ctx, proxyHandler, h, mux.ClientStrategy{ MaxConcurrency: config.Concurrency, MaxConnection: 128, }, ), }, } } if h.senderSettings != nil && h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS { err := core.RequireFeatures(ctx, func(d dns.Client) error { h.dns = d return nil }) if err != nil { return nil, err } } h.proxy = proxyHandler return h, nil } // Tag implements outbound.Handler. func (h *Handler) Tag() string { return h.tag } // Dispatch implements proxy.Outbound.Dispatch. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { if h.senderSettings != nil && h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS { outbound := session.OutboundFromContext(ctx) if outbound == nil { outbound = new(session.Outbound) ctx = session.ContextWithOutbound(ctx, outbound) } if outbound.Target.Address != nil && outbound.Target.Address.Family().IsDomain() { if addr := h.resolveIP(ctx, outbound.Target.Address.Domain(), h.Address()); addr != nil { outbound.Target.Address = addr } } } if h.mux != nil && (h.mux.Enabled || session.MuxPreferedFromContext(ctx)) { if err := h.mux.Dispatch(ctx, link); err != nil { err := newError("failed to process mux outbound traffic").Base(err) session.SubmitOutboundErrorToOriginator(ctx, err) err.WriteToLog(session.ExportIDToError(ctx)) common.Interrupt(link.Writer) } } else { if err := h.proxy.Process(ctx, link, h); err != nil { // Ensure outbound ray is properly closed. err := newError("failed to process outbound traffic").Base(err) session.SubmitOutboundErrorToOriginator(ctx, err) err.WriteToLog(session.ExportIDToError(ctx)) common.Interrupt(link.Writer) } else { common.Must(common.Close(link.Writer)) } common.Interrupt(link.Reader) } } // Address implements internet.Dialer. func (h *Handler) Address() net.Address { if h.senderSettings == nil || h.senderSettings.Via == nil { return nil } return h.senderSettings.Via.AsAddress() } // Dial implements internet.Dialer. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) { if h.senderSettings != nil { if h.senderSettings.ProxySettings.HasTag() && !h.senderSettings.ProxySettings.TransportLayerProxy { tag := h.senderSettings.ProxySettings.Tag handler := h.outboundManager.GetHandler(tag) if handler != nil { newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx)) ctx = session.ContextWithOutbound(ctx, &session.Outbound{ Target: dest, }) opts := pipe.OptionsFromContext(ctx) uplinkReader, uplinkWriter := pipe.New(opts...) downlinkReader, downlinkWriter := pipe.New(opts...) go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}) conn := net.NewConnection(net.ConnectionInputMulti(uplinkWriter), net.ConnectionOutputMulti(downlinkReader)) securityEngine, err := security.CreateSecurityEngineFromSettings(ctx, h.streamSettings) if err != nil { return nil, newError("unable to create security engine").Base(err) } if securityEngine != nil { conn, err = securityEngine.Client(conn, security.OptionWithDestination{Dest: dest}) if err != nil { return nil, newError("unable to create security protocol client from security engine").Base(err) } } return h.getStatCouterConnection(conn), nil } newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx)) } if h.senderSettings.Via != nil { outbound := session.OutboundFromContext(ctx) if outbound == nil { outbound = new(session.Outbound) ctx = session.ContextWithOutbound(ctx, outbound) } outbound.Gateway = h.senderSettings.Via.AsAddress() } if h.senderSettings.DomainStrategy != proxyman.SenderConfig_AS_IS { outbound := session.OutboundFromContext(ctx) if outbound == nil { outbound = new(session.Outbound) ctx = session.ContextWithOutbound(ctx, outbound) } outbound.Resolver = func(ctx context.Context, domain string) net.Address { return h.resolveIP(ctx, domain, h.Address()) } } } enablePacketAddrCapture := true if h.senderSettings != nil && h.senderSettings.ProxySettings != nil && h.senderSettings.ProxySettings.HasTag() && h.senderSettings.ProxySettings.TransportLayerProxy { tag := h.senderSettings.ProxySettings.Tag newError("transport layer proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx)) ctx = session.SetTransportLayerProxyTagToContext(ctx, tag) enablePacketAddrCapture = false } if isStream, err := packetaddr.GetDestinationSubsetOf(dest); err == nil && enablePacketAddrCapture { packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings) if err != nil { return nil, newError("unable to listen socket").Base(err) } conn := packetaddr.ToPacketAddrConnWrapper(packetConn, isStream) return h.getStatCouterConnection(conn), nil } proxyEnvironment := envctx.EnvironmentFromContext(h.ctx).(environment.ProxyEnvironment) transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport") if err != nil { return nil, newError("unable to narrow environment to transport").Base(err) } ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment) conn, err := internet.Dial(ctx, dest, h.streamSettings) return h.getStatCouterConnection(conn), err } func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address { strategy := h.senderSettings.DomainStrategy ips, err := dns.LookupIPWithOption(h.dns, domain, dns.IPOption{ IPv4Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()), IPv6Enable: strategy == proxyman.SenderConfig_USE_IP || strategy == proxyman.SenderConfig_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()), FakeEnable: false, }) if err != nil { newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx)) } if len(ips) == 0 { return nil } return net.IPAddress(ips[dice.Roll(len(ips))]) } func (h *Handler) getStatCouterConnection(conn internet.Connection) internet.Connection { if h.uplinkCounter != nil || h.downlinkCounter != nil { return &internet.StatCouterConnection{ Connection: conn, ReadCounter: h.downlinkCounter, WriteCounter: h.uplinkCounter, } } return conn } // GetOutbound implements proxy.GetOutbound. func (h *Handler) GetOutbound() proxy.Outbound { return h.proxy } // Start implements common.Runnable. func (h *Handler) Start() error { return nil } // Close implements common.Closable. func (h *Handler) Close() error { common.Close(h.mux) if closableProxy, ok := h.proxy.(common.Closable); ok { if err := closableProxy.Close(); err != nil { return newError("unable to close proxy").Base(err) } } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/inbound/inbound.go
app/proxyman/inbound/inbound.go
package inbound //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "sync" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/inbound" ) // Manager is to manage all inbound handlers. type Manager struct { ctx context.Context access sync.RWMutex untaggedHandler []inbound.Handler taggedHandlers map[string]inbound.Handler running bool } // New returns a new Manager for inbound handlers. func New(ctx context.Context, config *proxyman.InboundConfig) (*Manager, error) { m := &Manager{ ctx: ctx, taggedHandlers: make(map[string]inbound.Handler), } return m, nil } // Type implements common.HasType. func (*Manager) Type() interface{} { return inbound.ManagerType() } // AddHandler implements inbound.Manager. func (m *Manager) AddHandler(ctx context.Context, handler inbound.Handler) error { m.access.Lock() defer m.access.Unlock() tag := handler.Tag() if len(tag) > 0 { m.taggedHandlers[tag] = handler } else { m.untaggedHandler = append(m.untaggedHandler, handler) } if m.running { return handler.Start() } return nil } // GetHandler implements inbound.Manager. func (m *Manager) GetHandler(ctx context.Context, tag string) (inbound.Handler, error) { m.access.RLock() defer m.access.RUnlock() handler, found := m.taggedHandlers[tag] if !found { return nil, newError("handler not found: ", tag) } return handler, nil } // RemoveHandler implements inbound.Manager. func (m *Manager) RemoveHandler(ctx context.Context, tag string) error { if tag == "" { return common.ErrNoClue } m.access.Lock() defer m.access.Unlock() if handler, found := m.taggedHandlers[tag]; found { if err := handler.Close(); err != nil { newError("failed to close handler ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) } delete(m.taggedHandlers, tag) return nil } return common.ErrNoClue } // Start implements common.Runnable. func (m *Manager) Start() error { m.access.Lock() defer m.access.Unlock() m.running = true for _, handler := range m.taggedHandlers { if err := handler.Start(); err != nil { return err } } for _, handler := range m.untaggedHandler { if err := handler.Start(); err != nil { return err } } return nil } // Close implements common.Closable. func (m *Manager) Close() error { m.access.Lock() defer m.access.Unlock() m.running = false var errors []interface{} for _, handler := range m.taggedHandlers { if err := handler.Close(); err != nil { errors = append(errors, err) } } for _, handler := range m.untaggedHandler { if err := handler.Close(); err != nil { errors = append(errors, err) } } if len(errors) > 0 { return newError("failed to close all handlers").Base(newError(serial.Concat(errors...))) } return nil } // NewHandler creates a new inbound.Handler based on the given config. func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound.Handler, error) { rawReceiverSettings, err := serial.GetInstanceOf(config.ReceiverSettings) if err != nil { return nil, err } proxySettings, err := serial.GetInstanceOf(config.ProxySettings) if err != nil { return nil, err } tag := config.Tag receiverSettings, ok := rawReceiverSettings.(*proxyman.ReceiverConfig) if !ok { return nil, newError("not a ReceiverConfig").AtError() } streamSettings := receiverSettings.StreamSettings if streamSettings != nil && streamSettings.SocketSettings != nil { ctx = session.ContextWithSockopt(ctx, &session.Sockopt{ Mark: streamSettings.SocketSettings.Mark, }) } allocStrategy := receiverSettings.AllocationStrategy if allocStrategy == nil || allocStrategy.Type == proxyman.AllocationStrategy_Always { return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings) } if allocStrategy.Type == proxyman.AllocationStrategy_Random { return NewDynamicInboundHandler(ctx, tag, receiverSettings, proxySettings) } return nil, newError("unknown allocation strategy: ", receiverSettings.AllocationStrategy.Type).AtError() } func init() { common.Must(common.RegisterConfig((*proxyman.InboundConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*proxyman.InboundConfig)) })) common.Must(common.RegisterConfig((*core.InboundHandlerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewHandler(ctx, config.(*core.InboundHandlerConfig)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/inbound/errors.generated.go
app/proxyman/inbound/errors.generated.go
package inbound import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/inbound/dynamic.go
app/proxyman/inbound/dynamic.go
package inbound import ( "context" "sync" "time" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/common/mux" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport/internet" ) type DynamicInboundHandler struct { tag string v *core.Instance proxyConfig interface{} receiverConfig *proxyman.ReceiverConfig streamSettings *internet.MemoryStreamConfig portMutex sync.Mutex portsInUse map[net.Port]bool workerMutex sync.RWMutex worker []worker lastRefresh time.Time mux *mux.Server task *task.Periodic ctx context.Context } func NewDynamicInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*DynamicInboundHandler, error) { v := core.MustFromContext(ctx) h := &DynamicInboundHandler{ tag: tag, proxyConfig: proxyConfig, receiverConfig: receiverConfig, portsInUse: make(map[net.Port]bool), mux: mux.NewServer(ctx), v: v, ctx: ctx, } mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings) if err != nil { return nil, newError("failed to parse stream settings").Base(err).AtWarning() } if receiverConfig.ReceiveOriginalDestination { if mss.SocketSettings == nil { mss.SocketSettings = &internet.SocketConfig{} } if mss.SocketSettings.Tproxy == internet.SocketConfig_Off { mss.SocketSettings.Tproxy = internet.SocketConfig_Redirect } mss.SocketSettings.ReceiveOriginalDestAddress = true } h.streamSettings = mss h.task = &task.Periodic{ Interval: time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()), Execute: h.refresh, } return h, nil } func (h *DynamicInboundHandler) allocatePort() net.Port { from := int(h.receiverConfig.PortRange.From) delta := int(h.receiverConfig.PortRange.To) - from + 1 h.portMutex.Lock() defer h.portMutex.Unlock() for { r := dice.Roll(delta) port := net.Port(from + r) _, used := h.portsInUse[port] if !used { h.portsInUse[port] = true return port } } } func (h *DynamicInboundHandler) closeWorkers(workers []worker) { ports2Del := make([]net.Port, len(workers)) for idx, worker := range workers { ports2Del[idx] = worker.Port() if err := worker.Close(); err != nil { newError("failed to close worker").Base(err).WriteToLog() } } h.portMutex.Lock() for _, port := range ports2Del { delete(h.portsInUse, port) } h.portMutex.Unlock() } func (h *DynamicInboundHandler) refresh() error { h.lastRefresh = time.Now() timeout := time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()) * 2 concurrency := h.receiverConfig.AllocationStrategy.GetConcurrencyValue() workers := make([]worker, 0, concurrency) address := h.receiverConfig.Listen.AsAddress() if address == nil { address = net.AnyIP } uplinkCounter, downlinkCounter := getStatCounter(h.v, h.tag) for i := uint32(0); i < concurrency; i++ { port := h.allocatePort() rawProxy, err := core.CreateObject(h.v, h.proxyConfig) if err != nil { newError("failed to create proxy instance").Base(err).AtWarning().WriteToLog() continue } p := rawProxy.(proxy.Inbound) nl := p.Network() if net.HasNetwork(nl, net.Network_TCP) { worker := &tcpWorker{ tag: h.tag, address: address, port: port, proxy: p, stream: h.streamSettings, recvOrigDest: h.receiverConfig.ReceiveOriginalDestination, dispatcher: h.mux, sniffingConfig: h.receiverConfig.GetEffectiveSniffingSettings(), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, ctx: h.ctx, } if err := worker.Start(); err != nil { newError("failed to create TCP worker").Base(err).AtWarning().WriteToLog() continue } workers = append(workers, worker) } if net.HasNetwork(nl, net.Network_UDP) { worker := &udpWorker{ ctx: h.ctx, tag: h.tag, proxy: p, address: address, port: port, dispatcher: h.mux, sniffingConfig: h.receiverConfig.GetEffectiveSniffingSettings(), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, stream: h.streamSettings, } if err := worker.Start(); err != nil { newError("failed to create UDP worker").Base(err).AtWarning().WriteToLog() continue } workers = append(workers, worker) } } h.workerMutex.Lock() h.worker = workers h.workerMutex.Unlock() time.AfterFunc(timeout, func() { h.closeWorkers(workers) }) return nil } func (h *DynamicInboundHandler) Start() error { return h.task.Start() } func (h *DynamicInboundHandler) Close() error { return h.task.Close() } func (h *DynamicInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) { h.workerMutex.RLock() defer h.workerMutex.RUnlock() if len(h.worker) == 0 { return nil, 0, 0 } w := h.worker[dice.Roll(len(h.worker))] expire := h.receiverConfig.AllocationStrategy.GetRefreshValue() - uint32(time.Since(h.lastRefresh)/time.Minute) return w.Proxy(), w.Port(), int(expire) } func (h *DynamicInboundHandler) Tag() string { return h.tag }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/inbound/always.go
app/proxyman/inbound/always.go
package inbound import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/mux" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/features/stats" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport/internet" ) func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) { var uplinkCounter stats.Counter var downlinkCounter stats.Counter policy := v.GetFeature(policy.ManagerType()).(policy.Manager) if len(tag) > 0 && policy.ForSystem().Stats.InboundUplink { statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager) name := "inbound>>>" + tag + ">>>traffic>>>uplink" c, _ := stats.GetOrRegisterCounter(statsManager, name) if c != nil { uplinkCounter = c } } if len(tag) > 0 && policy.ForSystem().Stats.InboundDownlink { statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager) name := "inbound>>>" + tag + ">>>traffic>>>downlink" c, _ := stats.GetOrRegisterCounter(statsManager, name) if c != nil { downlinkCounter = c } } return uplinkCounter, downlinkCounter } type AlwaysOnInboundHandler struct { proxy proxy.Inbound workers []worker mux *mux.Server tag string } func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*AlwaysOnInboundHandler, error) { rawProxy, err := common.CreateObject(ctx, proxyConfig) if err != nil { return nil, err } p, ok := rawProxy.(proxy.Inbound) if !ok { return nil, newError("not an inbound proxy.") } h := &AlwaysOnInboundHandler{ proxy: p, mux: mux.NewServer(ctx), tag: tag, } uplinkCounter, downlinkCounter := getStatCounter(core.MustFromContext(ctx), tag) nl := p.Network() pr := receiverConfig.PortRange address := receiverConfig.Listen.AsAddress() if address == nil { address = net.AnyIP } mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings) if err != nil { return nil, newError("failed to parse stream config").Base(err).AtWarning() } if receiverConfig.ReceiveOriginalDestination { if mss.SocketSettings == nil { mss.SocketSettings = &internet.SocketConfig{} } if mss.SocketSettings.Tproxy == internet.SocketConfig_Off { mss.SocketSettings.Tproxy = internet.SocketConfig_Redirect } mss.SocketSettings.ReceiveOriginalDestAddress = true } if pr == nil { if net.HasNetwork(nl, net.Network_UNIX) { newError("creating unix domain socket worker on ", address).AtDebug().WriteToLog() worker := &dsWorker{ address: address, proxy: p, stream: mss, tag: tag, dispatcher: h.mux, sniffingConfig: receiverConfig.GetEffectiveSniffingSettings(), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, ctx: ctx, } h.workers = append(h.workers, worker) } } if pr != nil { for port := pr.From; port <= pr.To; port++ { if net.HasNetwork(nl, net.Network_TCP) { newError("creating stream worker on ", address, ":", port).AtDebug().WriteToLog() worker := &tcpWorker{ address: address, port: net.Port(port), proxy: p, stream: mss, recvOrigDest: receiverConfig.ReceiveOriginalDestination, tag: tag, dispatcher: h.mux, sniffingConfig: receiverConfig.GetEffectiveSniffingSettings(), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, ctx: ctx, } h.workers = append(h.workers, worker) } if net.HasNetwork(nl, net.Network_UDP) { worker := &udpWorker{ ctx: ctx, tag: tag, proxy: p, address: address, port: net.Port(port), dispatcher: h.mux, sniffingConfig: receiverConfig.GetEffectiveSniffingSettings(), uplinkCounter: uplinkCounter, downlinkCounter: downlinkCounter, stream: mss, } h.workers = append(h.workers, worker) } } } return h, nil } // Start implements common.Runnable. func (h *AlwaysOnInboundHandler) Start() error { for _, worker := range h.workers { if err := worker.Start(); err != nil { return err } } return nil } // Close implements common.Closable. func (h *AlwaysOnInboundHandler) Close() error { var errs []error for _, worker := range h.workers { errs = append(errs, worker.Close()) } errs = append(errs, h.mux.Close()) if err := errors.Combine(errs...); err != nil { return newError("failed to close all resources").Base(err) } return nil } func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) { if len(h.workers) == 0 { return nil, 0, 0 } w := h.workers[dice.Roll(len(h.workers))] return w.Proxy(), w.Port(), 9999 } func (h *AlwaysOnInboundHandler) Tag() string { return h.tag } func (h *AlwaysOnInboundHandler) GetInbound() proxy.Inbound { return h.proxy }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/proxyman/inbound/worker.go
app/proxyman/inbound/worker.go
package inbound import ( "context" "sync" "sync/atomic" "time" "github.com/v2fly/v2ray-core/v5/app/proxyman" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/environment" "github.com/v2fly/v2ray-core/v5/common/environment/envctx" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal/done" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/features/stats" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/tcp" "github.com/v2fly/v2ray-core/v5/transport/internet/udp" "github.com/v2fly/v2ray-core/v5/transport/pipe" ) type worker interface { Start() error Close() error Port() net.Port Proxy() proxy.Inbound } type tcpWorker struct { address net.Address port net.Port proxy proxy.Inbound stream *internet.MemoryStreamConfig recvOrigDest bool tag string dispatcher routing.Dispatcher sniffingConfig *proxyman.SniffingConfig uplinkCounter stats.Counter downlinkCounter stats.Counter hub internet.Listener ctx context.Context } func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode { if s == nil || s.SocketSettings == nil { return internet.SocketConfig_Off } return s.SocketSettings.Tproxy } func (w *tcpWorker) callback(conn internet.Connection) { ctx, cancel := context.WithCancel(w.ctx) sid := session.NewID() ctx = session.ContextWithID(ctx, sid) if w.recvOrigDest { var dest net.Destination switch getTProxyType(w.stream) { case internet.SocketConfig_Redirect: d, err := tcp.GetOriginalDestination(conn) if err != nil { newError("failed to get original destination").Base(err).WriteToLog(session.ExportIDToError(ctx)) } else { dest = d } case internet.SocketConfig_TProxy: dest = net.DestinationFromAddr(conn.LocalAddr()) } if dest.IsValid() { ctx = session.ContextWithOutbound(ctx, &session.Outbound{ Target: dest, }) } } ctx = session.ContextWithInbound(ctx, &session.Inbound{ Source: net.DestinationFromAddr(conn.RemoteAddr()), Gateway: net.TCPDestination(w.address, w.port), Tag: w.tag, }) content := new(session.Content) if w.sniffingConfig != nil { content.SniffingRequest.Enabled = w.sniffingConfig.Enabled content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly } ctx = session.ContextWithContent(ctx, content) if w.uplinkCounter != nil || w.downlinkCounter != nil { conn = &internet.StatCouterConnection{ Connection: conn, ReadCounter: w.uplinkCounter, WriteCounter: w.downlinkCounter, } } if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil { newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) } cancel() if err := conn.Close(); err != nil { newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) } } func (w *tcpWorker) Proxy() proxy.Inbound { return w.proxy } func (w *tcpWorker) Start() error { ctx := w.ctx proxyEnvironment := envctx.EnvironmentFromContext(w.ctx).(environment.ProxyEnvironment) transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport") if err != nil { return newError("unable to narrow environment to transport").Base(err) } ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment) hub, err := internet.ListenTCP(ctx, w.address, w.port, w.stream, func(conn internet.Connection) { go w.callback(conn) }) if err != nil { return newError("failed to listen TCP on ", w.port).AtWarning().Base(err) } w.hub = hub return nil } func (w *tcpWorker) Close() error { var errors []interface{} if w.hub != nil { if err := common.Close(w.hub); err != nil { errors = append(errors, err) } if err := common.Close(w.proxy); err != nil { errors = append(errors, err) } } if len(errors) > 0 { return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) } return nil } func (w *tcpWorker) Port() net.Port { return w.port } type udpConn struct { lastActivityTime int64 // in seconds reader buf.Reader writer buf.Writer output func([]byte) (int, error) remote net.Addr local net.Addr done *done.Instance uplink stats.Counter downlink stats.Counter inactive bool } func (c *udpConn) setInactive() { c.inactive = true } func (c *udpConn) updateActivity() { atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix()) } // ReadMultiBuffer implements buf.Reader func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) { mb, err := c.reader.ReadMultiBuffer() if err != nil { return nil, err } c.updateActivity() if c.uplink != nil { c.uplink.Add(int64(mb.Len())) } return mb, nil } func (c *udpConn) Read(buf []byte) (int, error) { panic("not implemented") } // Write implements io.Writer. func (c *udpConn) Write(buf []byte) (int, error) { n, err := c.output(buf) if c.downlink != nil { c.downlink.Add(int64(n)) } if err == nil { c.updateActivity() } return n, err } func (c *udpConn) Close() error { common.Must(c.done.Close()) common.Must(common.Close(c.writer)) return nil } func (c *udpConn) RemoteAddr() net.Addr { return c.remote } func (c *udpConn) LocalAddr() net.Addr { return c.local } func (*udpConn) SetDeadline(time.Time) error { return nil } func (*udpConn) SetReadDeadline(time.Time) error { return nil } func (*udpConn) SetWriteDeadline(time.Time) error { return nil } type connID struct { src net.Destination dest net.Destination } type udpWorker struct { sync.RWMutex proxy proxy.Inbound hub *udp.Hub address net.Address port net.Port tag string stream *internet.MemoryStreamConfig dispatcher routing.Dispatcher sniffingConfig *proxyman.SniffingConfig uplinkCounter stats.Counter downlinkCounter stats.Counter checker *task.Periodic activeConn map[connID]*udpConn ctx context.Context } func (w *udpWorker) getConnection(id connID) (*udpConn, bool) { w.Lock() defer w.Unlock() if conn, found := w.activeConn[id]; found && !conn.done.Done() { return conn, true } pReader, pWriter := pipe.New(pipe.DiscardOverflow(), pipe.WithSizeLimit(16*1024)) conn := &udpConn{ reader: pReader, writer: pWriter, output: func(b []byte) (int, error) { return w.hub.WriteTo(b, id.src) }, remote: &net.UDPAddr{ IP: id.src.Address.IP(), Port: int(id.src.Port), }, local: &net.UDPAddr{ IP: w.address.IP(), Port: int(w.port), }, done: done.New(), uplink: w.uplinkCounter, downlink: w.downlinkCounter, } w.activeConn[id] = conn conn.updateActivity() return conn, false } func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) { id := connID{ src: source, } if originalDest.IsValid() { id.dest = originalDest } conn, existing := w.getConnection(id) // payload will be discarded in pipe is full. conn.writer.WriteMultiBuffer(buf.MultiBuffer{b}) if !existing { common.Must(w.checker.Start()) go func() { ctx := w.ctx sid := session.NewID() ctx = session.ContextWithID(ctx, sid) if originalDest.IsValid() { ctx = session.ContextWithOutbound(ctx, &session.Outbound{ Target: originalDest, }) } ctx = session.ContextWithInbound(ctx, &session.Inbound{ Source: source, Gateway: net.UDPDestination(w.address, w.port), Tag: w.tag, }) content := new(session.Content) if w.sniffingConfig != nil { content.SniffingRequest.Enabled = w.sniffingConfig.Enabled content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly } ctx = session.ContextWithContent(ctx, content) if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil { newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) } conn.Close() // conn not removed by checker TODO may be lock worker here is better if !conn.inactive { conn.setInactive() w.removeConn(id) } }() } } func (w *udpWorker) removeConn(id connID) { w.Lock() delete(w.activeConn, id) w.Unlock() } func (w *udpWorker) handlePackets() { receive := w.hub.Receive() for payload := range receive { w.callback(payload.Payload, payload.Source, payload.Target) } } func (w *udpWorker) clean() error { nowSec := time.Now().Unix() w.Lock() defer w.Unlock() if len(w.activeConn) == 0 { return newError("no more connections. stopping...") } for addr, conn := range w.activeConn { if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 { // TODO Timeout too small if !conn.inactive { conn.setInactive() delete(w.activeConn, addr) } conn.Close() } } if len(w.activeConn) == 0 { w.activeConn = make(map[connID]*udpConn, 16) } return nil } func (w *udpWorker) Start() error { w.activeConn = make(map[connID]*udpConn, 16) ctx := context.Background() proxyEnvironment := envctx.EnvironmentFromContext(w.ctx).(environment.ProxyEnvironment) transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport") if err != nil { return newError("unable to narrow environment to transport").Base(err) } ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment) h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256)) if err != nil { return err } w.checker = &task.Periodic{ Interval: time.Second * 16, Execute: w.clean, } w.hub = h go w.handlePackets() return nil } func (w *udpWorker) Close() error { w.Lock() defer w.Unlock() var errors []interface{} if w.hub != nil { if err := w.hub.Close(); err != nil { errors = append(errors, err) } } if w.checker != nil { if err := w.checker.Close(); err != nil { errors = append(errors, err) } } if err := common.Close(w.proxy); err != nil { errors = append(errors, err) } if len(errors) > 0 { return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) } return nil } func (w *udpWorker) Port() net.Port { return w.port } func (w *udpWorker) Proxy() proxy.Inbound { return w.proxy } type dsWorker struct { address net.Address proxy proxy.Inbound stream *internet.MemoryStreamConfig tag string dispatcher routing.Dispatcher sniffingConfig *proxyman.SniffingConfig uplinkCounter stats.Counter downlinkCounter stats.Counter hub internet.Listener ctx context.Context } func (w *dsWorker) callback(conn internet.Connection) { ctx, cancel := context.WithCancel(w.ctx) sid := session.NewID() ctx = session.ContextWithID(ctx, sid) ctx = session.ContextWithInbound(ctx, &session.Inbound{ Source: net.DestinationFromAddr(conn.RemoteAddr()), Gateway: net.UnixDestination(w.address), Tag: w.tag, }) content := new(session.Content) if w.sniffingConfig != nil { content.SniffingRequest.Enabled = w.sniffingConfig.Enabled content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly } ctx = session.ContextWithContent(ctx, content) if w.uplinkCounter != nil || w.downlinkCounter != nil { conn = &internet.StatCouterConnection{ Connection: conn, ReadCounter: w.uplinkCounter, WriteCounter: w.downlinkCounter, } } if err := w.proxy.Process(ctx, net.Network_UNIX, conn, w.dispatcher); err != nil { newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) } cancel() if err := conn.Close(); err != nil { newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) } } func (w *dsWorker) Proxy() proxy.Inbound { return w.proxy } func (w *dsWorker) Port() net.Port { return net.Port(0) } func (w *dsWorker) Start() error { ctx := context.Background() proxyEnvironment := envctx.EnvironmentFromContext(w.ctx).(environment.ProxyEnvironment) transportEnvironment, err := proxyEnvironment.NarrowScopeToTransport("transport") if err != nil { return newError("unable to narrow environment to transport").Base(err) } ctx = envctx.ContextWithEnvironment(ctx, transportEnvironment) hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn internet.Connection) { go w.callback(conn) }) if err != nil { return newError("failed to listen Unix Domain Socket on ", w.address).AtWarning().Base(err) } w.hub = hub return nil } func (w *dsWorker) Close() error { var errors []interface{} if w.hub != nil { if err := common.Close(w.hub); err != nil { errors = append(errors, err) } if err := common.Close(w.proxy); err != nil { errors = append(errors, err) } } if len(errors) > 0 { return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/errors.generated.go
app/router/errors.generated.go
package router import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/strategy_leastping.go
app/router/strategy_leastping.go
//go:build !confonly // +build !confonly package router import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/observatory" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/features/extension" ) type LeastPingStrategy struct { ctx context.Context observatory extension.Observatory config *StrategyLeastPingConfig } func (l *LeastPingStrategy) GetPrincipleTarget(strings []string) []string { return []string{l.PickOutbound(strings)} } func (l *LeastPingStrategy) InjectContext(ctx context.Context) { l.ctx = ctx } func (l *LeastPingStrategy) PickOutbound(strings []string) string { if l.observatory == nil { common.Must(core.RequireFeatures(l.ctx, func(observatory extension.Observatory) error { if l.config.ObserverTag != "" { l.observatory = common.Must2(observatory.(features.TaggedFeatures).GetFeaturesByTag(l.config.ObserverTag)).(extension.Observatory) } else { l.observatory = observatory } return nil })) } if l.observatory == nil { newError("cannot find observatory").WriteToLog() return "" } observeReport, err := l.observatory.GetObservation(l.ctx) if err != nil { newError("cannot get observe report").Base(err).WriteToLog() return "" } outboundsList := outboundList(strings) if result, ok := observeReport.(*observatory.ObservationResult); ok { status := result.Status leastPing := int64(99999999) selectedOutboundName := "" for _, v := range status { if outboundsList.contains(v.OutboundTag) && v.Alive && v.Delay < leastPing { selectedOutboundName = v.OutboundTag leastPing = v.Delay } } return selectedOutboundName } // No way to understand observeReport return "" } type outboundList []string func (o outboundList) contains(name string) bool { for _, v := range o { if v == name { return true } } return false } func init() { common.Must(common.RegisterConfig((*StrategyLeastPingConfig)(nil), nil)) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/balancing.go
app/router/balancing.go
//go:build !confonly // +build !confonly package router import ( "context" "github.com/v2fly/v2ray-core/v5/features/extension" "github.com/v2fly/v2ray-core/v5/features/outbound" ) type BalancingStrategy interface { PickOutbound([]string) string } type BalancingPrincipleTarget interface { GetPrincipleTarget([]string) []string } type Balancer struct { selectors []string strategy BalancingStrategy ohm outbound.Manager fallbackTag string override override } // PickOutbound picks the tag of an outbound func (b *Balancer) PickOutbound() (string, error) { candidates, err := b.SelectOutbounds() if err != nil { if b.fallbackTag != "" { newError("fallback to [", b.fallbackTag, "], due to error: ", err).AtInfo().WriteToLog() return b.fallbackTag, nil } return "", err } var tag string if o := b.override.Get(); o != "" { tag = o } else { tag = b.strategy.PickOutbound(candidates) } if tag == "" { if b.fallbackTag != "" { newError("fallback to [", b.fallbackTag, "], due to empty tag returned").AtInfo().WriteToLog() return b.fallbackTag, nil } // will use default handler return "", newError("balancing strategy returns empty tag") } return tag, nil } func (b *Balancer) InjectContext(ctx context.Context) { if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok { contextReceiver.InjectContext(ctx) } } // SelectOutbounds select outbounds with selectors of the Balancer func (b *Balancer) SelectOutbounds() ([]string, error) { hs, ok := b.ohm.(outbound.HandlerSelector) if !ok { return nil, newError("outbound.Manager is not a HandlerSelector") } tags := hs.Select(b.selectors) return tags, nil } // GetPrincipleTarget implements routing.BalancerPrincipleTarget func (r *Router) GetPrincipleTarget(tag string) ([]string, error) { if b, ok := r.balancers[tag]; ok { if s, ok := b.strategy.(BalancingPrincipleTarget); ok { candidates, err := b.SelectOutbounds() if err != nil { return nil, newError("unable to select outbounds").Base(err) } return s.GetPrincipleTarget(candidates), nil } return nil, newError("unsupported GetPrincipleTarget") } return nil, newError("cannot find tag") } // SetOverrideTarget implements routing.BalancerOverrider func (r *Router) SetOverrideTarget(tag, target string) error { if b, ok := r.balancers[tag]; ok { b.override.Put(target) return nil } return newError("cannot find tag") } // GetOverrideTarget implements routing.BalancerOverrider func (r *Router) GetOverrideTarget(tag string) (string, error) { if b, ok := r.balancers[tag]; ok { return b.override.Get(), nil } return "", newError("cannot find tag") }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/config.go
app/router/config.go
//go:build !confonly // +build !confonly package router import ( "context" "encoding/json" "github.com/golang/protobuf/jsonpb" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/infra/conf/v5cfg" ) type Rule struct { Tag string Balancer *Balancer Condition Condition } func (r *Rule) GetTag() (string, error) { if r.Balancer != nil { return r.Balancer.PickOutbound() } return r.Tag, nil } // Apply checks rule matching of current routing context. func (r *Rule) Apply(ctx routing.Context) bool { return r.Condition.Apply(ctx) } func (rr *RoutingRule) BuildCondition() (Condition, error) { conds := NewConditionChan() if len(rr.Domain) > 0 { cond, err := NewDomainMatcher(rr.DomainMatcher, rr.Domain) if err != nil { return nil, newError("failed to build domain condition").Base(err) } conds.Add(cond) } var geoDomains []*routercommon.Domain for _, geo := range rr.GeoDomain { geoDomains = append(geoDomains, geo.Domain...) } if len(geoDomains) > 0 { cond, err := NewDomainMatcher(rr.DomainMatcher, geoDomains) if err != nil { return nil, newError("failed to build geo domain condition").Base(err) } conds.Add(cond) } if len(rr.UserEmail) > 0 { conds.Add(NewUserMatcher(rr.UserEmail)) } if len(rr.InboundTag) > 0 { conds.Add(NewInboundTagMatcher(rr.InboundTag)) } if rr.PortList != nil { conds.Add(NewPortMatcher(rr.PortList, false)) } else if rr.PortRange != nil { conds.Add(NewPortMatcher(&net.PortList{Range: []*net.PortRange{rr.PortRange}}, false)) } if rr.SourcePortList != nil { conds.Add(NewPortMatcher(rr.SourcePortList, true)) } if len(rr.Networks) > 0 { conds.Add(NewNetworkMatcher(rr.Networks)) } else if rr.NetworkList != nil { conds.Add(NewNetworkMatcher(rr.NetworkList.Network)) } if len(rr.Geoip) > 0 { cond, err := NewMultiGeoIPMatcher(rr.Geoip, false) if err != nil { return nil, err } conds.Add(cond) } else if len(rr.Cidr) > 0 { cond, err := NewMultiGeoIPMatcher([]*routercommon.GeoIP{{Cidr: rr.Cidr}}, false) if err != nil { return nil, err } conds.Add(cond) } if len(rr.SourceGeoip) > 0 { cond, err := NewMultiGeoIPMatcher(rr.SourceGeoip, true) if err != nil { return nil, err } conds.Add(cond) } else if len(rr.SourceCidr) > 0 { cond, err := NewMultiGeoIPMatcher([]*routercommon.GeoIP{{Cidr: rr.SourceCidr}}, true) if err != nil { return nil, err } conds.Add(cond) } if len(rr.Protocol) > 0 { conds.Add(NewProtocolMatcher(rr.Protocol)) } if len(rr.Attributes) > 0 { cond, err := NewAttributeMatcher(rr.Attributes) if err != nil { return nil, err } conds.Add(cond) } if conds.Len() == 0 { return nil, newError("this rule has no effective fields").AtWarning() } return conds, nil } // Build builds the balancing rule func (br *BalancingRule) Build(ohm outbound.Manager, dispatcher routing.Dispatcher) (*Balancer, error) { switch br.Strategy { case "leastping": i, err := serial.GetInstanceOf(br.StrategySettings) if err != nil { return nil, err } s, ok := i.(*StrategyLeastPingConfig) if !ok { return nil, newError("not a StrategyLeastPingConfig").AtError() } return &Balancer{ selectors: br.OutboundSelector, strategy: &LeastPingStrategy{config: s}, ohm: ohm, fallbackTag: br.FallbackTag, }, nil case "leastload": i, err := serial.GetInstanceOf(br.StrategySettings) if err != nil { return nil, err } s, ok := i.(*StrategyLeastLoadConfig) if !ok { return nil, newError("not a StrategyLeastLoadConfig").AtError() } leastLoadStrategy := NewLeastLoadStrategy(s) return &Balancer{ selectors: br.OutboundSelector, ohm: ohm, fallbackTag: br.FallbackTag, strategy: leastLoadStrategy, }, nil case "random": fallthrough case "": var randomStrategy *RandomStrategy if br.StrategySettings != nil { i, err := serial.GetInstanceOf(br.StrategySettings) if err != nil { return nil, err } s, ok := i.(*StrategyRandomConfig) if !ok { return nil, newError("not a StrategyRandomConfig").AtError() } randomStrategy = NewRandomStrategy(s) } return &Balancer{ selectors: br.OutboundSelector, ohm: ohm, fallbackTag: br.FallbackTag, strategy: randomStrategy, }, nil default: return nil, newError("unrecognized balancer type") } } func (br *BalancingRule) UnmarshalJSONPB(unmarshaler *jsonpb.Unmarshaler, bytes []byte) error { type BalancingRuleStub struct { Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` OutboundSelector []string `protobuf:"bytes,2,rep,name=outbound_selector,json=outboundSelector,proto3" json:"outbound_selector,omitempty"` Strategy string `protobuf:"bytes,3,opt,name=strategy,proto3" json:"strategy,omitempty"` StrategySettings json.RawMessage `protobuf:"bytes,4,opt,name=strategy_settings,json=strategySettings,proto3" json:"strategy_settings,omitempty"` FallbackTag string `protobuf:"bytes,5,opt,name=fallback_tag,json=fallbackTag,proto3" json:"fallback_tag,omitempty"` } var stub BalancingRuleStub if err := json.Unmarshal(bytes, &stub); err != nil { return err } if stub.Strategy == "" { stub.Strategy = "random" } settingsPack, err := v5cfg.LoadHeterogeneousConfigFromRawJSON(context.TODO(), "balancer", stub.Strategy, stub.StrategySettings) if err != nil { return err } br.StrategySettings = serial.ToTypedMessage(settingsPack) br.Tag = stub.Tag br.Strategy = stub.Strategy br.OutboundSelector = stub.OutboundSelector br.FallbackTag = stub.FallbackTag return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/strategy_leastload.go
app/router/strategy_leastload.go
package router import ( "context" "math" "sort" "time" "github.com/golang/protobuf/proto" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/observatory" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/features/extension" ) // LeastLoadStrategy represents a least load balancing strategy type LeastLoadStrategy struct { settings *StrategyLeastLoadConfig costs *WeightManager observer extension.Observatory ctx context.Context } func (l *LeastLoadStrategy) GetPrincipleTarget(strings []string) []string { var ret []string nodes := l.pickOutbounds(strings) for _, v := range nodes { ret = append(ret, v.Tag) } return ret } // NewLeastLoadStrategy creates a new LeastLoadStrategy with settings func NewLeastLoadStrategy(settings *StrategyLeastLoadConfig) *LeastLoadStrategy { return &LeastLoadStrategy{ settings: settings, costs: NewWeightManager( settings.Costs, 1, func(value, cost float64) float64 { return value * math.Pow(cost, 0.5) }, ), } } // node is a minimal copy of HealthCheckResult // we don't use HealthCheckResult directly because // it may change by health checker during routing type node struct { Tag string CountAll int CountFail int RTTAverage time.Duration RTTDeviation time.Duration RTTDeviationCost time.Duration } func (l *LeastLoadStrategy) InjectContext(ctx context.Context) { l.ctx = ctx } func (l *LeastLoadStrategy) PickOutbound(candidates []string) string { selects := l.pickOutbounds(candidates) count := len(selects) if count == 0 { // goes to fallbackTag return "" } return selects[dice.Roll(count)].Tag } func (l *LeastLoadStrategy) pickOutbounds(candidates []string) []*node { qualified := l.getNodes(candidates, time.Duration(l.settings.MaxRTT)) selects := l.selectLeastLoad(qualified) return selects } // selectLeastLoad selects nodes according to Baselines and Expected Count. // // The strategy always improves network response speed, not matter which mode below is configured. // But they can still have different priorities. // // 1. Bandwidth priority: no Baseline + Expected Count > 0.: selects `Expected Count` of nodes. // (one if Expected Count <= 0) // // 2. Bandwidth priority advanced: Baselines + Expected Count > 0. // Select `Expected Count` amount of nodes, and also those near them according to baselines. // In other words, it selects according to different Baselines, until one of them matches // the Expected Count, if no Baseline matches, Expected Count applied. // // 3. Speed priority: Baselines + `Expected Count <= 0`. // go through all baselines until find selects, if not, select none. Used in combination // with 'balancer.fallbackTag', it means: selects qualified nodes or use the fallback. func (l *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node { if len(nodes) == 0 { newError("least load: no qualified outbound").AtInfo().WriteToLog() return nil } expected := int(l.settings.Expected) availableCount := len(nodes) if expected > availableCount { return nodes } if expected <= 0 { expected = 1 } if len(l.settings.Baselines) == 0 { return nodes[:expected] } count := 0 // go through all base line until find expected selects for _, b := range l.settings.Baselines { baseline := time.Duration(b) for i := count; i < availableCount; i++ { if nodes[i].RTTDeviationCost >= baseline { break } count = i + 1 } // don't continue if find expected selects if count >= expected { newError("applied baseline: ", baseline).AtDebug().WriteToLog() break } } if l.settings.Expected > 0 && count < expected { count = expected } return nodes[:count] } func (l *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) []*node { if l.observer == nil { common.Must(core.RequireFeatures(l.ctx, func(observatory extension.Observatory) error { l.observer = observatory return nil })) } var result proto.Message if l.settings.ObserverTag == "" { observeResult, err := l.observer.GetObservation(l.ctx) if err != nil { newError("cannot get observation").Base(err).WriteToLog() return make([]*node, 0) } result = observeResult } else { observeResult, err := common.Must2(l.observer.(features.TaggedFeatures).GetFeaturesByTag(l.settings.ObserverTag)).(extension.Observatory).GetObservation(l.ctx) if err != nil { newError("cannot get observation").Base(err).WriteToLog() return make([]*node, 0) } result = observeResult } results := result.(*observatory.ObservationResult) outboundlist := outboundList(candidates) var ret []*node for _, v := range results.Status { if v.Alive && (v.Delay < maxRTT.Milliseconds() || maxRTT == 0) && outboundlist.contains(v.OutboundTag) { record := &node{ Tag: v.OutboundTag, CountAll: 1, CountFail: 1, RTTAverage: time.Duration(v.Delay) * time.Millisecond, RTTDeviation: time.Duration(v.Delay) * time.Millisecond, RTTDeviationCost: time.Duration(l.costs.Apply(v.OutboundTag, float64(time.Duration(v.Delay)*time.Millisecond))), } if v.HealthPing != nil { record.RTTAverage = time.Duration(v.HealthPing.Average) record.RTTDeviation = time.Duration(v.HealthPing.Deviation) record.RTTDeviationCost = time.Duration(l.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation))) record.CountAll = int(v.HealthPing.All) record.CountFail = int(v.HealthPing.Fail) } ret = append(ret, record) } } leastloadSort(ret) return ret } func leastloadSort(nodes []*node) { sort.Slice(nodes, func(i, j int) bool { left := nodes[i] right := nodes[j] if left.RTTDeviationCost != right.RTTDeviationCost { return left.RTTDeviationCost < right.RTTDeviationCost } if left.RTTAverage != right.RTTAverage { return left.RTTAverage < right.RTTAverage } if left.CountFail != right.CountFail { return left.CountFail < right.CountFail } if left.CountAll != right.CountAll { return left.CountAll > right.CountAll } return left.Tag < right.Tag }) } func init() { common.Must(common.RegisterConfig((*StrategyLeastLoadConfig)(nil), nil)) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/router.go
app/router/router.go
package router //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/features/dns" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/features/routing" routing_dns "github.com/v2fly/v2ray-core/v5/features/routing/dns" "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon" "github.com/v2fly/v2ray-core/v5/infra/conf/geodata" ) // Router is an implementation of routing.Router. type Router struct { domainStrategy DomainStrategy rules []*Rule balancers map[string]*Balancer dns dns.Client } // Route is an implementation of routing.Route. type Route struct { routing.Context outboundGroupTags []string outboundTag string } // Init initializes the Router. func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm outbound.Manager, dispatcher routing.Dispatcher) error { r.domainStrategy = config.DomainStrategy r.dns = d r.balancers = make(map[string]*Balancer, len(config.BalancingRule)) for _, rule := range config.BalancingRule { balancer, err := rule.Build(ohm, dispatcher) if err != nil { return err } balancer.InjectContext(ctx) r.balancers[rule.Tag] = balancer } r.rules = make([]*Rule, 0, len(config.Rule)) for _, rule := range config.Rule { cond, err := rule.BuildCondition() if err != nil { return err } rr := &Rule{ Condition: cond, Tag: rule.GetTag(), } btag := rule.GetBalancingTag() if len(btag) > 0 { brule, found := r.balancers[btag] if !found { return newError("balancer ", btag, " not found") } rr.Balancer = brule } r.rules = append(r.rules, rr) } return nil } // PickRoute implements routing.Router. func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) { rule, ctx, err := r.pickRouteInternal(ctx) if err != nil { return nil, err } tag, err := rule.GetTag() if err != nil { return nil, err } return &Route{Context: ctx, outboundTag: tag}, nil } func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context, error) { // SkipDNSResolve is set from DNS module. // the DOH remote server maybe a domain name, // this prevents cycle resolving dead loop skipDNSResolve := ctx.GetSkipDNSResolve() if r.domainStrategy == DomainStrategy_IpOnDemand && !skipDNSResolve { ctx = routing_dns.ContextWithDNSClient(ctx, r.dns) } for _, rule := range r.rules { if rule.Apply(ctx) { return rule, ctx, nil } } if r.domainStrategy != DomainStrategy_IpIfNonMatch || len(ctx.GetTargetDomain()) == 0 || skipDNSResolve { return nil, ctx, common.ErrNoClue } ctx = routing_dns.ContextWithDNSClient(ctx, r.dns) // Try applying rules again if we have IPs. for _, rule := range r.rules { if rule.Apply(ctx) { return rule, ctx, nil } } return nil, ctx, common.ErrNoClue } // Start implements common.Runnable. func (r *Router) Start() error { return nil } // Close implements common.Closable. func (r *Router) Close() error { return nil } // Type implements common.HasType. func (*Router) Type() interface{} { return routing.RouterType() } // GetOutboundGroupTags implements routing.Route. func (r *Route) GetOutboundGroupTags() []string { return r.outboundGroupTags } // GetOutboundTag implements routing.Route. func (r *Route) GetOutboundTag() string { return r.outboundTag } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { r := new(Router) if err := core.RequireFeatures(ctx, func(d dns.Client, ohm outbound.Manager, dispatcher routing.Dispatcher) error { return r.Init(ctx, config.(*Config), d, ohm, dispatcher) }); err != nil { return nil, err } return r, nil })) common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { ctx = cfgcommon.NewConfigureLoadingContext(ctx) geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string { return "standard" }) if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil { cfgcommon.SetGeoDataLoader(ctx, loader) } else { return nil, newError("unable to create geo data loader ").Base(err) } cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx) geoLoader := cfgEnv.GetGeoLoader() simplifiedConfig := config.(*SimplifiedConfig) var routingRules []*RoutingRule for _, v := range simplifiedConfig.Rule { rule := new(RoutingRule) for _, geo := range v.Geoip { if geo.Code != "" { filepath := "geoip.dat" if geo.FilePath != "" { filepath = geo.FilePath } else { geo.CountryCode = geo.Code } var err error geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code) if err != nil { return nil, newError("unable to load geoip").Base(err) } } } rule.Geoip = v.Geoip for _, geo := range v.SourceGeoip { if geo.Code != "" { filepath := "geoip.dat" if geo.FilePath != "" { filepath = geo.FilePath } else { geo.CountryCode = geo.Code } var err error geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code) if err != nil { return nil, newError("unable to load geoip").Base(err) } } } rule.SourceGeoip = v.SourceGeoip for _, geo := range v.GeoDomain { if geo.Code != "" { filepath := "geosite.dat" if geo.FilePath != "" { filepath = geo.FilePath } var err error geo.Domain, err = geoLoader.LoadGeoSiteWithAttr(filepath, geo.Code) if err != nil { return nil, newError("unable to load geodomain").Base(err) } } } if v.PortList != "" { portList := &cfgcommon.PortList{} err := portList.UnmarshalText(v.PortList) if err != nil { return nil, err } rule.PortList = portList.Build() } if v.SourcePortList != "" { portList := &cfgcommon.PortList{} err := portList.UnmarshalText(v.SourcePortList) if err != nil { return nil, err } rule.SourcePortList = portList.Build() } rule.Domain = v.Domain rule.GeoDomain = v.GeoDomain rule.Networks = v.Networks.GetNetwork() rule.Protocol = v.Protocol rule.Attributes = v.Attributes rule.UserEmail = v.UserEmail rule.InboundTag = v.InboundTag rule.DomainMatcher = v.DomainMatcher switch s := v.TargetTag.(type) { case *SimplifiedRoutingRule_Tag: rule.TargetTag = &RoutingRule_Tag{s.Tag} case *SimplifiedRoutingRule_BalancingTag: rule.TargetTag = &RoutingRule_BalancingTag{s.BalancingTag} } routingRules = append(routingRules, rule) } fullConfig := &Config{ DomainStrategy: simplifiedConfig.DomainStrategy, Rule: routingRules, BalancingRule: simplifiedConfig.BalancingRule, } return common.CreateObject(ctx, fullConfig) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/weight.go
app/router/weight.go
package router import ( "regexp" "strconv" "strings" "sync" ) type weightScaler func(value, weight float64) float64 var numberFinder = regexp.MustCompile(`\d+(\.\d+)?`) // NewWeightManager creates a new WeightManager with settings func NewWeightManager(s []*StrategyWeight, defaultWeight float64, scaler weightScaler) *WeightManager { return &WeightManager{ settings: s, cache: make(map[string]float64), scaler: scaler, defaultWeight: defaultWeight, } } // WeightManager manages weights for specific settings type WeightManager struct { settings []*StrategyWeight cache map[string]float64 scaler weightScaler defaultWeight float64 mu sync.Mutex } // Get gets the weight of specified tag func (s *WeightManager) Get(tag string) float64 { s.mu.Lock() defer s.mu.Unlock() weight, ok := s.cache[tag] if ok { return weight } weight = s.findValue(tag) s.cache[tag] = weight return weight } // Apply applies weight to the value func (s *WeightManager) Apply(tag string, value float64) float64 { return s.scaler(value, s.Get(tag)) } func (s *WeightManager) findValue(tag string) float64 { for _, w := range s.settings { matched := s.getMatch(tag, w.Match, w.Regexp) if matched == "" { continue } if w.Value > 0 { return float64(w.Value) } // auto weight from matched numStr := numberFinder.FindString(matched) if numStr == "" { return s.defaultWeight } weight, err := strconv.ParseFloat(numStr, 64) if err != nil { newError("unexpected error from ParseFloat: ", err).AtError().WriteToLog() return s.defaultWeight } return weight } return s.defaultWeight } func (s *WeightManager) getMatch(tag, find string, isRegexp bool) string { if !isRegexp { idx := strings.Index(tag, find) if idx < 0 { return "" } return find } r, err := regexp.Compile(find) if err != nil { newError("invalid regexp: ", find, "err: ", err).AtError().WriteToLog() return "" } return r.FindString(tag) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/condition_geoip_test.go
app/router/condition_geoip_test.go
package router_test import ( "errors" "io/fs" "os" "path/filepath" "strings" "testing" "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" ) func init() { const geoipURL = "https://github.com/v2fly/geoip/releases/download/202507050144/geoip.dat" wd, err := os.Getwd() common.Must(err) tempPath := filepath.Join(wd, "..", "..", "testing", "temp") geoipPath := filepath.Join(tempPath, "geoip-202507050144.dat") os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } } func TestGeoIPMatcherContainer(t *testing.T) { container := &router.GeoIPMatcherContainer{} m1, err := container.Add(&routercommon.GeoIP{ CountryCode: "CN", }) common.Must(err) m2, err := container.Add(&routercommon.GeoIP{ CountryCode: "US", }) common.Must(err) m3, err := container.Add(&routercommon.GeoIP{ CountryCode: "CN", }) common.Must(err) if m1 != m3 { t.Error("expect same matcher for same geoip, but not") } if m1 == m2 { t.Error("expect different matcher for different geoip, but actually same") } } func TestGeoIPMatcher(t *testing.T) { cidrList := []*routercommon.CIDR{ {Ip: []byte{0, 0, 0, 0}, Prefix: 8}, {Ip: []byte{10, 0, 0, 0}, Prefix: 8}, {Ip: []byte{100, 64, 0, 0}, Prefix: 10}, {Ip: []byte{127, 0, 0, 0}, Prefix: 8}, {Ip: []byte{169, 254, 0, 0}, Prefix: 16}, {Ip: []byte{172, 16, 0, 0}, Prefix: 12}, {Ip: []byte{192, 0, 0, 0}, Prefix: 24}, {Ip: []byte{192, 0, 2, 0}, Prefix: 24}, {Ip: []byte{192, 168, 0, 0}, Prefix: 16}, {Ip: []byte{192, 18, 0, 0}, Prefix: 15}, {Ip: []byte{198, 51, 100, 0}, Prefix: 24}, {Ip: []byte{203, 0, 113, 0}, Prefix: 24}, {Ip: []byte{8, 8, 8, 8}, Prefix: 32}, {Ip: []byte{91, 108, 4, 0}, Prefix: 16}, } matcher := &router.GeoIPMatcher{} common.Must(matcher.Init(cidrList)) testCases := []struct { Input string Output bool }{ { Input: "192.168.1.1", Output: true, }, { Input: "192.0.0.0", Output: true, }, { Input: "192.0.1.0", Output: false, }, { Input: "0.1.0.0", Output: true, }, { Input: "1.0.0.1", Output: false, }, { Input: "8.8.8.7", Output: false, }, { Input: "8.8.8.8", Output: true, }, { Input: "2001:cdba::3257:9652", Output: false, }, { Input: "91.108.255.254", Output: true, }, } for _, testCase := range testCases { ip := net.ParseAddress(testCase.Input).IP() actual := matcher.Match(ip) if actual != testCase.Output { t.Error("expect input", testCase.Input, "to be", testCase.Output, ", but actually", actual) } } } func TestGeoIPReverseMatcher(t *testing.T) { cidrList := []*routercommon.CIDR{ {Ip: []byte{8, 8, 8, 8}, Prefix: 32}, {Ip: []byte{91, 108, 4, 0}, Prefix: 16}, } matcher := &router.GeoIPMatcher{} matcher.SetReverseMatch(true) // Reverse match common.Must(matcher.Init(cidrList)) testCases := []struct { Input string Output bool }{ { Input: "8.8.8.8", Output: false, }, { Input: "2001:cdba::3257:9652", Output: true, }, { Input: "91.108.255.254", Output: false, }, } for _, testCase := range testCases { ip := net.ParseAddress(testCase.Input).IP() actual := matcher.Match(ip) if actual != testCase.Output { t.Error("expect input", testCase.Input, "to be", testCase.Output, ", but actually", actual) } } } func TestGeoIPMatcher4CN(t *testing.T) { ips, err := loadGeoIP("CN") common.Must(err) matcher := &router.GeoIPMatcher{} common.Must(matcher.Init(ips)) if matcher.Match([]byte{8, 8, 8, 8}) { t.Error("expect CN geoip doesn't contain 8.8.8.8, but actually does") } } func TestGeoIPMatcher6US(t *testing.T) { ips, err := loadGeoIP("US") common.Must(err) matcher := &router.GeoIPMatcher{} common.Must(matcher.Init(ips)) if !matcher.Match(net.ParseAddress("2001:4860:4860::8888").IP()) { t.Error("expect US geoip contain 2001:4860:4860::8888, but actually not") } } func loadGeoIP(country string) ([]*routercommon.CIDR, error) { geoipBytes, err := filesystem.ReadAsset("geoip-202507050144.dat") if err != nil { return nil, err } var geoipList routercommon.GeoIPList if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil { return nil, err } for _, geoip := range geoipList.Entry { if strings.EqualFold(geoip.CountryCode, country) { return geoip.Cidr, nil } } panic("country not found: " + country) } func BenchmarkGeoIPMatcher4CN(b *testing.B) { ips, err := loadGeoIP("CN") common.Must(err) matcher := &router.GeoIPMatcher{} common.Must(matcher.Init(ips)) b.ResetTimer() for i := 0; i < b.N; i++ { _ = matcher.Match([]byte{8, 8, 8, 8}) } } func BenchmarkGeoIPMatcher6US(b *testing.B) { ips, err := loadGeoIP("US") common.Must(err) matcher := &router.GeoIPMatcher{} common.Must(matcher.Init(ips)) b.ResetTimer() for i := 0; i < b.N; i++ { _ = matcher.Match(net.ParseAddress("2001:4860:4860::8888").IP()) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/strategy_leastload_test.go
app/router/strategy_leastload_test.go
package router import ( "testing" ) /* Split into multiple package, need to be tested separately func TestSelectLeastLoad(t *testing.T) { settings := &StrategyLeastLoadConfig{ HealthCheck: &HealthPingConfig{ SamplingCount: 10, }, Expected: 1, MaxRTT: int64(time.Millisecond * time.Duration(800)), } strategy := NewLeastLoadStrategy(settings) // std 40 strategy.PutResult("a", time.Millisecond*time.Duration(60)) strategy.PutResult("a", time.Millisecond*time.Duration(140)) strategy.PutResult("a", time.Millisecond*time.Duration(60)) strategy.PutResult("a", time.Millisecond*time.Duration(140)) // std 60 strategy.PutResult("b", time.Millisecond*time.Duration(40)) strategy.PutResult("b", time.Millisecond*time.Duration(160)) strategy.PutResult("b", time.Millisecond*time.Duration(40)) strategy.PutResult("b", time.Millisecond*time.Duration(160)) // std 0, but >MaxRTT strategy.PutResult("c", time.Millisecond*time.Duration(1000)) strategy.PutResult("c", time.Millisecond*time.Duration(1000)) strategy.PutResult("c", time.Millisecond*time.Duration(1000)) strategy.PutResult("c", time.Millisecond*time.Duration(1000)) expected := "a" actual := strategy.SelectAndPick([]string{"a", "b", "c", "untested"}) if actual != expected { t.Errorf("expected: %v, actual: %v", expected, actual) } } func TestSelectLeastLoadWithCost(t *testing.T) { settings := &StrategyLeastLoadConfig{ HealthCheck: &HealthPingConfig{ SamplingCount: 10, }, Costs: []*StrategyWeight{ {Match: "a", Value: 9}, }, Expected: 1, } strategy := NewLeastLoadStrategy(settings, nil) // std 40, std+c 120 strategy.PutResult("a", time.Millisecond*time.Duration(60)) strategy.PutResult("a", time.Millisecond*time.Duration(140)) strategy.PutResult("a", time.Millisecond*time.Duration(60)) strategy.PutResult("a", time.Millisecond*time.Duration(140)) // std 60 strategy.PutResult("b", time.Millisecond*time.Duration(40)) strategy.PutResult("b", time.Millisecond*time.Duration(160)) strategy.PutResult("b", time.Millisecond*time.Duration(40)) strategy.PutResult("b", time.Millisecond*time.Duration(160)) expected := "b" actual := strategy.SelectAndPick([]string{"a", "b", "untested"}) if actual != expected { t.Errorf("expected: %v, actual: %v", expected, actual) } } */ func TestSelectLeastExpected(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: nil, Expected: 3, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 100}, {Tag: "b", RTTDeviationCost: 200}, {Tag: "c", RTTDeviationCost: 300}, {Tag: "d", RTTDeviationCost: 350}, } expected := 3 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } } func TestSelectLeastExpected2(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: nil, Expected: 3, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 100}, {Tag: "b", RTTDeviationCost: 200}, } expected := 2 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } } func TestSelectLeastExpectedAndBaselines(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: []int64{200, 300, 400}, Expected: 3, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 100}, {Tag: "b", RTTDeviationCost: 200}, {Tag: "c", RTTDeviationCost: 250}, {Tag: "d", RTTDeviationCost: 300}, {Tag: "e", RTTDeviationCost: 310}, } expected := 3 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } } func TestSelectLeastExpectedAndBaselines2(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: []int64{200, 300, 400}, Expected: 3, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 500}, {Tag: "b", RTTDeviationCost: 600}, {Tag: "c", RTTDeviationCost: 700}, {Tag: "d", RTTDeviationCost: 800}, {Tag: "e", RTTDeviationCost: 900}, } expected := 3 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } } func TestSelectLeastLoadBaselines(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: []int64{200, 400, 600}, Expected: 0, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 100}, {Tag: "b", RTTDeviationCost: 200}, {Tag: "c", RTTDeviationCost: 300}, } expected := 1 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } } func TestSelectLeastLoadBaselinesNoQualified(t *testing.T) { strategy := &LeastLoadStrategy{ settings: &StrategyLeastLoadConfig{ Baselines: []int64{200, 400, 600}, Expected: 0, }, } nodes := []*node{ {Tag: "a", RTTDeviationCost: 800}, {Tag: "b", RTTDeviationCost: 1000}, } expected := 0 ns := strategy.selectLeastLoad(nodes) if len(ns) != expected { t.Errorf("expected: %v, actual: %v", expected, len(ns)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/balancing_override.go
app/router/balancing_override.go
package router import ( sync "sync" ) func (r *Router) OverrideBalancer(balancer string, target string) error { var b *Balancer for tag, bl := range r.balancers { if tag == balancer { b = bl break } } if b == nil { return newError("balancer '", balancer, "' not found") } b.override.Put(target) return nil } type overrideSettings struct { target string } type override struct { access sync.RWMutex settings overrideSettings } // Get gets the override settings func (o *override) Get() string { o.access.RLock() defer o.access.RUnlock() return o.settings.target } // Put updates the override settings func (o *override) Put(target string) { o.access.Lock() defer o.access.Unlock() o.settings.target = target } // Clear clears the override settings func (o *override) Clear() { o.access.Lock() defer o.access.Unlock() o.settings.target = "" }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/condition_geoip.go
app/router/condition_geoip.go
package router import ( "net/netip" "go4.org/netipx" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/net" ) type GeoIPMatcher struct { countryCode string reverseMatch bool ip4 *netipx.IPSet ip6 *netipx.IPSet } func (m *GeoIPMatcher) Init(cidrs []*routercommon.CIDR) error { var builder4, builder6 netipx.IPSetBuilder for _, cidr := range cidrs { netaddrIP, ok := netip.AddrFromSlice(cidr.GetIp()) if !ok { return newError("invalid IP address ", cidr) } netaddrIP = netaddrIP.Unmap() ipPrefix := netip.PrefixFrom(netaddrIP, int(cidr.GetPrefix())) switch { case netaddrIP.Is4(): builder4.AddPrefix(ipPrefix) case netaddrIP.Is6(): builder6.AddPrefix(ipPrefix) } } var err error m.ip4, err = builder4.IPSet() if err != nil { return err } m.ip6, err = builder6.IPSet() if err != nil { return err } return nil } func (m *GeoIPMatcher) SetReverseMatch(isReverseMatch bool) { m.reverseMatch = isReverseMatch } func (m *GeoIPMatcher) match4(ip net.IP) bool { nip, ok := netipx.FromStdIP(ip) if !ok { return false } return m.ip4.Contains(nip) } func (m *GeoIPMatcher) match6(ip net.IP) bool { nip, ok := netipx.FromStdIP(ip) if !ok { return false } return m.ip6.Contains(nip) } // Match returns true if the given ip is included by the GeoIP. func (m *GeoIPMatcher) Match(ip net.IP) bool { isMatched := false switch len(ip) { case net.IPv4len: isMatched = m.match4(ip) case net.IPv6len: isMatched = m.match6(ip) } if m.reverseMatch { return !isMatched } return isMatched } // GeoIPMatcherContainer is a container for GeoIPMatchers. It keeps unique copies of GeoIPMatcher by country code. type GeoIPMatcherContainer struct { matchers []*GeoIPMatcher } // Add adds a new GeoIP set into the container. // If the country code of GeoIP is not empty, GeoIPMatcherContainer will try to find an existing one, instead of adding a new one. func (c *GeoIPMatcherContainer) Add(geoip *routercommon.GeoIP) (*GeoIPMatcher, error) { if geoip.CountryCode != "" { for _, m := range c.matchers { if m.countryCode == geoip.CountryCode && m.reverseMatch == geoip.InverseMatch { return m, nil } } } m := &GeoIPMatcher{ countryCode: geoip.CountryCode, reverseMatch: geoip.InverseMatch, } if err := m.Init(geoip.Cidr); err != nil { return nil, err } if geoip.CountryCode != "" { c.matchers = append(c.matchers, m) } return m, nil } var globalGeoIPContainer GeoIPMatcherContainer
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/weight_test.go
app/router/weight_test.go
package router_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/app/router" ) func TestWeight(t *testing.T) { manager := router.NewWeightManager( []*router.StrategyWeight{ { Match: "x5", Value: 100, }, { Match: "x8", }, { Regexp: true, Match: `\bx0+(\.\d+)?\b`, Value: 1, }, { Regexp: true, Match: `\bx\d+(\.\d+)?\b`, }, }, 1, func(v, w float64) float64 { return v * w }, ) tags := []string{ "node name, x5, and more", "node name, x8", "node name, x15", "node name, x0100, and more", "node name, x10.1", "node name, x00.1, and more", } // test weight expected := []float64{100, 8, 15, 100, 10.1, 1} actual := make([]float64, 0) for _, tag := range tags { actual = append(actual, manager.Get(tag)) } if !reflect.DeepEqual(expected, actual) { t.Errorf("expected: %v, actual: %v", expected, actual) } // test scale expected2 := []float64{1000, 80, 150, 1000, 101, 10} actual2 := make([]float64, 0) for _, tag := range tags { actual2 = append(actual2, manager.Apply(tag, 10)) } if !reflect.DeepEqual(expected2, actual2) { t.Errorf("expected2: %v, actual2: %v", expected2, actual2) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/strategy_random.go
app/router/strategy_random.go
package router import ( "context" "google.golang.org/protobuf/runtime/protoiface" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/observatory" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/features/extension" ) // RandomStrategy represents a random balancing strategy type RandomStrategy struct { ctx context.Context settings *StrategyRandomConfig observatory extension.Observatory } func (s *RandomStrategy) GetPrincipleTarget(strings []string) []string { return strings } // NewRandomStrategy creates a new RandomStrategy with settings func NewRandomStrategy(settings *StrategyRandomConfig) *RandomStrategy { return &RandomStrategy{ settings: settings, } } func (s *RandomStrategy) InjectContext(ctx context.Context) { if s != nil { s.ctx = ctx } } func (s *RandomStrategy) PickOutbound(candidates []string) string { if s != nil && s.settings.AliveOnly { // candidates are considered alive unless observed otherwise if s.observatory == nil { core.RequireFeatures(s.ctx, func(observatory extension.Observatory) error { s.observatory = observatory return nil }) } if s.observatory != nil { var observeReport protoiface.MessageV1 var err error if s.settings.ObserverTag == "" { observeReport, err = s.observatory.GetObservation(s.ctx) } else { observeReport, err = common.Must2(s.observatory.(features.TaggedFeatures).GetFeaturesByTag(s.settings.ObserverTag)).(extension.Observatory).GetObservation(s.ctx) } if err == nil { aliveTags := make([]string, 0) if result, ok := observeReport.(*observatory.ObservationResult); ok { status := result.Status statusMap := make(map[string]*observatory.OutboundStatus) for _, outboundStatus := range status { statusMap[outboundStatus.OutboundTag] = outboundStatus } for _, candidate := range candidates { if outboundStatus, found := statusMap[candidate]; found { if outboundStatus.Alive { aliveTags = append(aliveTags, candidate) } } else { // unfound candidate is considered alive aliveTags = append(aliveTags, candidate) } } candidates = aliveTags } } } } count := len(candidates) if count == 0 { // goes to fallbackTag return "" } return candidates[dice.Roll(count)] } func init() { common.Must(common.RegisterConfig((*StrategyRandomConfig)(nil), nil)) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/config.pb.go
app/router/config.pb.go
package router import ( routercommon "github.com/v2fly/v2ray-core/v5/app/router/routercommon" net "github.com/v2fly/v2ray-core/v5/common/net" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type DomainStrategy int32 const ( // Use domain as is. DomainStrategy_AsIs DomainStrategy = 0 // Always resolve IP for domains. DomainStrategy_UseIp DomainStrategy = 1 // Resolve to IP if the domain doesn't match any rules. DomainStrategy_IpIfNonMatch DomainStrategy = 2 // Resolve to IP if any rule requires IP matching. DomainStrategy_IpOnDemand DomainStrategy = 3 ) // Enum value maps for DomainStrategy. var ( DomainStrategy_name = map[int32]string{ 0: "AsIs", 1: "UseIp", 2: "IpIfNonMatch", 3: "IpOnDemand", } DomainStrategy_value = map[string]int32{ "AsIs": 0, "UseIp": 1, "IpIfNonMatch": 2, "IpOnDemand": 3, } ) func (x DomainStrategy) Enum() *DomainStrategy { p := new(DomainStrategy) *p = x return p } func (x DomainStrategy) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (DomainStrategy) Descriptor() protoreflect.EnumDescriptor { return file_app_router_config_proto_enumTypes[0].Descriptor() } func (DomainStrategy) Type() protoreflect.EnumType { return &file_app_router_config_proto_enumTypes[0] } func (x DomainStrategy) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use DomainStrategy.Descriptor instead. func (DomainStrategy) EnumDescriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{0} } type RoutingRule struct { state protoimpl.MessageState `protogen:"open.v1"` // Types that are valid to be assigned to TargetTag: // // *RoutingRule_Tag // *RoutingRule_BalancingTag TargetTag isRoutingRule_TargetTag `protobuf_oneof:"target_tag"` // List of domains for target domain matching. Domain []*routercommon.Domain `protobuf:"bytes,2,rep,name=domain,proto3" json:"domain,omitempty"` // List of CIDRs for target IP address matching. // Deprecated. Use geoip below. // // Deprecated: Marked as deprecated in app/router/config.proto. Cidr []*routercommon.CIDR `protobuf:"bytes,3,rep,name=cidr,proto3" json:"cidr,omitempty"` // List of GeoIPs for target IP address matching. If this entry exists, the // cidr above will have no effect. GeoIP fields with the same country code are // supposed to contain exactly same content. They will be merged during // runtime. For customized GeoIPs, please leave country code empty. Geoip []*routercommon.GeoIP `protobuf:"bytes,10,rep,name=geoip,proto3" json:"geoip,omitempty"` // A range of port [from, to]. If the destination port is in this range, this // rule takes effect. Deprecated. Use port_list. // // Deprecated: Marked as deprecated in app/router/config.proto. PortRange *net.PortRange `protobuf:"bytes,4,opt,name=port_range,json=portRange,proto3" json:"port_range,omitempty"` // List of ports. PortList *net.PortList `protobuf:"bytes,14,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"` // List of networks. Deprecated. Use networks. // // Deprecated: Marked as deprecated in app/router/config.proto. NetworkList *net.NetworkList `protobuf:"bytes,5,opt,name=network_list,json=networkList,proto3" json:"network_list,omitempty"` // List of networks for matching. Networks []net.Network `protobuf:"varint,13,rep,packed,name=networks,proto3,enum=v2ray.core.common.net.Network" json:"networks,omitempty"` // List of CIDRs for source IP address matching. // // Deprecated: Marked as deprecated in app/router/config.proto. SourceCidr []*routercommon.CIDR `protobuf:"bytes,6,rep,name=source_cidr,json=sourceCidr,proto3" json:"source_cidr,omitempty"` // List of GeoIPs for source IP address matching. If this entry exists, the // source_cidr above will have no effect. SourceGeoip []*routercommon.GeoIP `protobuf:"bytes,11,rep,name=source_geoip,json=sourceGeoip,proto3" json:"source_geoip,omitempty"` // List of ports for source port matching. SourcePortList *net.PortList `protobuf:"bytes,16,opt,name=source_port_list,json=sourcePortList,proto3" json:"source_port_list,omitempty"` UserEmail []string `protobuf:"bytes,7,rep,name=user_email,json=userEmail,proto3" json:"user_email,omitempty"` InboundTag []string `protobuf:"bytes,8,rep,name=inbound_tag,json=inboundTag,proto3" json:"inbound_tag,omitempty"` Protocol []string `protobuf:"bytes,9,rep,name=protocol,proto3" json:"protocol,omitempty"` Attributes string `protobuf:"bytes,15,opt,name=attributes,proto3" json:"attributes,omitempty"` DomainMatcher string `protobuf:"bytes,17,opt,name=domain_matcher,json=domainMatcher,proto3" json:"domain_matcher,omitempty"` // geo_domain instruct simplified config loader to load geo domain rule and fill in domain field. GeoDomain []*routercommon.GeoSite `protobuf:"bytes,68001,rep,name=geo_domain,json=geoDomain,proto3" json:"geo_domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RoutingRule) Reset() { *x = RoutingRule{} mi := &file_app_router_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RoutingRule) String() string { return protoimpl.X.MessageStringOf(x) } func (*RoutingRule) ProtoMessage() {} func (x *RoutingRule) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RoutingRule.ProtoReflect.Descriptor instead. func (*RoutingRule) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{0} } func (x *RoutingRule) GetTargetTag() isRoutingRule_TargetTag { if x != nil { return x.TargetTag } return nil } func (x *RoutingRule) GetTag() string { if x != nil { if x, ok := x.TargetTag.(*RoutingRule_Tag); ok { return x.Tag } } return "" } func (x *RoutingRule) GetBalancingTag() string { if x != nil { if x, ok := x.TargetTag.(*RoutingRule_BalancingTag); ok { return x.BalancingTag } } return "" } func (x *RoutingRule) GetDomain() []*routercommon.Domain { if x != nil { return x.Domain } return nil } // Deprecated: Marked as deprecated in app/router/config.proto. func (x *RoutingRule) GetCidr() []*routercommon.CIDR { if x != nil { return x.Cidr } return nil } func (x *RoutingRule) GetGeoip() []*routercommon.GeoIP { if x != nil { return x.Geoip } return nil } // Deprecated: Marked as deprecated in app/router/config.proto. func (x *RoutingRule) GetPortRange() *net.PortRange { if x != nil { return x.PortRange } return nil } func (x *RoutingRule) GetPortList() *net.PortList { if x != nil { return x.PortList } return nil } // Deprecated: Marked as deprecated in app/router/config.proto. func (x *RoutingRule) GetNetworkList() *net.NetworkList { if x != nil { return x.NetworkList } return nil } func (x *RoutingRule) GetNetworks() []net.Network { if x != nil { return x.Networks } return nil } // Deprecated: Marked as deprecated in app/router/config.proto. func (x *RoutingRule) GetSourceCidr() []*routercommon.CIDR { if x != nil { return x.SourceCidr } return nil } func (x *RoutingRule) GetSourceGeoip() []*routercommon.GeoIP { if x != nil { return x.SourceGeoip } return nil } func (x *RoutingRule) GetSourcePortList() *net.PortList { if x != nil { return x.SourcePortList } return nil } func (x *RoutingRule) GetUserEmail() []string { if x != nil { return x.UserEmail } return nil } func (x *RoutingRule) GetInboundTag() []string { if x != nil { return x.InboundTag } return nil } func (x *RoutingRule) GetProtocol() []string { if x != nil { return x.Protocol } return nil } func (x *RoutingRule) GetAttributes() string { if x != nil { return x.Attributes } return "" } func (x *RoutingRule) GetDomainMatcher() string { if x != nil { return x.DomainMatcher } return "" } func (x *RoutingRule) GetGeoDomain() []*routercommon.GeoSite { if x != nil { return x.GeoDomain } return nil } type isRoutingRule_TargetTag interface { isRoutingRule_TargetTag() } type RoutingRule_Tag struct { // Tag of outbound that this rule is pointing to. Tag string `protobuf:"bytes,1,opt,name=tag,proto3,oneof"` } type RoutingRule_BalancingTag struct { // Tag of routing balancer. BalancingTag string `protobuf:"bytes,12,opt,name=balancing_tag,json=balancingTag,proto3,oneof"` } func (*RoutingRule_Tag) isRoutingRule_TargetTag() {} func (*RoutingRule_BalancingTag) isRoutingRule_TargetTag() {} type BalancingRule struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` OutboundSelector []string `protobuf:"bytes,2,rep,name=outbound_selector,json=outboundSelector,proto3" json:"outbound_selector,omitempty"` Strategy string `protobuf:"bytes,3,opt,name=strategy,proto3" json:"strategy,omitempty"` StrategySettings *anypb.Any `protobuf:"bytes,4,opt,name=strategy_settings,json=strategySettings,proto3" json:"strategy_settings,omitempty"` FallbackTag string `protobuf:"bytes,5,opt,name=fallback_tag,json=fallbackTag,proto3" json:"fallback_tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *BalancingRule) Reset() { *x = BalancingRule{} mi := &file_app_router_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *BalancingRule) String() string { return protoimpl.X.MessageStringOf(x) } func (*BalancingRule) ProtoMessage() {} func (x *BalancingRule) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BalancingRule.ProtoReflect.Descriptor instead. func (*BalancingRule) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{1} } func (x *BalancingRule) GetTag() string { if x != nil { return x.Tag } return "" } func (x *BalancingRule) GetOutboundSelector() []string { if x != nil { return x.OutboundSelector } return nil } func (x *BalancingRule) GetStrategy() string { if x != nil { return x.Strategy } return "" } func (x *BalancingRule) GetStrategySettings() *anypb.Any { if x != nil { return x.StrategySettings } return nil } func (x *BalancingRule) GetFallbackTag() string { if x != nil { return x.FallbackTag } return "" } type StrategyWeight struct { state protoimpl.MessageState `protogen:"open.v1"` Regexp bool `protobuf:"varint,1,opt,name=regexp,proto3" json:"regexp,omitempty"` Match string `protobuf:"bytes,2,opt,name=match,proto3" json:"match,omitempty"` Value float32 `protobuf:"fixed32,3,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *StrategyWeight) Reset() { *x = StrategyWeight{} mi := &file_app_router_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *StrategyWeight) String() string { return protoimpl.X.MessageStringOf(x) } func (*StrategyWeight) ProtoMessage() {} func (x *StrategyWeight) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StrategyWeight.ProtoReflect.Descriptor instead. func (*StrategyWeight) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{2} } func (x *StrategyWeight) GetRegexp() bool { if x != nil { return x.Regexp } return false } func (x *StrategyWeight) GetMatch() string { if x != nil { return x.Match } return "" } func (x *StrategyWeight) GetValue() float32 { if x != nil { return x.Value } return 0 } type StrategyRandomConfig struct { state protoimpl.MessageState `protogen:"open.v1"` ObserverTag string `protobuf:"bytes,7,opt,name=observer_tag,json=observerTag,proto3" json:"observer_tag,omitempty"` AliveOnly bool `protobuf:"varint,8,opt,name=alive_only,json=aliveOnly,proto3" json:"alive_only,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *StrategyRandomConfig) Reset() { *x = StrategyRandomConfig{} mi := &file_app_router_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *StrategyRandomConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*StrategyRandomConfig) ProtoMessage() {} func (x *StrategyRandomConfig) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StrategyRandomConfig.ProtoReflect.Descriptor instead. func (*StrategyRandomConfig) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{3} } func (x *StrategyRandomConfig) GetObserverTag() string { if x != nil { return x.ObserverTag } return "" } func (x *StrategyRandomConfig) GetAliveOnly() bool { if x != nil { return x.AliveOnly } return false } type StrategyLeastPingConfig struct { state protoimpl.MessageState `protogen:"open.v1"` ObserverTag string `protobuf:"bytes,7,opt,name=observer_tag,json=observerTag,proto3" json:"observer_tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *StrategyLeastPingConfig) Reset() { *x = StrategyLeastPingConfig{} mi := &file_app_router_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *StrategyLeastPingConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*StrategyLeastPingConfig) ProtoMessage() {} func (x *StrategyLeastPingConfig) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StrategyLeastPingConfig.ProtoReflect.Descriptor instead. func (*StrategyLeastPingConfig) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{4} } func (x *StrategyLeastPingConfig) GetObserverTag() string { if x != nil { return x.ObserverTag } return "" } type StrategyLeastLoadConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // weight settings Costs []*StrategyWeight `protobuf:"bytes,2,rep,name=costs,proto3" json:"costs,omitempty"` // RTT baselines for selecting, int64 values of time.Duration Baselines []int64 `protobuf:"varint,3,rep,packed,name=baselines,proto3" json:"baselines,omitempty"` // expected nodes count to select Expected int32 `protobuf:"varint,4,opt,name=expected,proto3" json:"expected,omitempty"` // max acceptable rtt, filter away high delay nodes. defalut 0 MaxRTT int64 `protobuf:"varint,5,opt,name=maxRTT,proto3" json:"maxRTT,omitempty"` // acceptable failure rate Tolerance float32 `protobuf:"fixed32,6,opt,name=tolerance,proto3" json:"tolerance,omitempty"` ObserverTag string `protobuf:"bytes,7,opt,name=observer_tag,json=observerTag,proto3" json:"observer_tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *StrategyLeastLoadConfig) Reset() { *x = StrategyLeastLoadConfig{} mi := &file_app_router_config_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *StrategyLeastLoadConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*StrategyLeastLoadConfig) ProtoMessage() {} func (x *StrategyLeastLoadConfig) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StrategyLeastLoadConfig.ProtoReflect.Descriptor instead. func (*StrategyLeastLoadConfig) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{5} } func (x *StrategyLeastLoadConfig) GetCosts() []*StrategyWeight { if x != nil { return x.Costs } return nil } func (x *StrategyLeastLoadConfig) GetBaselines() []int64 { if x != nil { return x.Baselines } return nil } func (x *StrategyLeastLoadConfig) GetExpected() int32 { if x != nil { return x.Expected } return 0 } func (x *StrategyLeastLoadConfig) GetMaxRTT() int64 { if x != nil { return x.MaxRTT } return 0 } func (x *StrategyLeastLoadConfig) GetTolerance() float32 { if x != nil { return x.Tolerance } return 0 } func (x *StrategyLeastLoadConfig) GetObserverTag() string { if x != nil { return x.ObserverTag } return "" } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` DomainStrategy DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=v2ray.core.app.router.DomainStrategy" json:"domain_strategy,omitempty"` Rule []*RoutingRule `protobuf:"bytes,2,rep,name=rule,proto3" json:"rule,omitempty"` BalancingRule []*BalancingRule `protobuf:"bytes,3,rep,name=balancing_rule,json=balancingRule,proto3" json:"balancing_rule,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_router_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{6} } func (x *Config) GetDomainStrategy() DomainStrategy { if x != nil { return x.DomainStrategy } return DomainStrategy_AsIs } func (x *Config) GetRule() []*RoutingRule { if x != nil { return x.Rule } return nil } func (x *Config) GetBalancingRule() []*BalancingRule { if x != nil { return x.BalancingRule } return nil } type SimplifiedRoutingRule struct { state protoimpl.MessageState `protogen:"open.v1"` // Types that are valid to be assigned to TargetTag: // // *SimplifiedRoutingRule_Tag // *SimplifiedRoutingRule_BalancingTag TargetTag isSimplifiedRoutingRule_TargetTag `protobuf_oneof:"target_tag"` // List of domains for target domain matching. Domain []*routercommon.Domain `protobuf:"bytes,2,rep,name=domain,proto3" json:"domain,omitempty"` // List of GeoIPs for target IP address matching. If this entry exists, the // cidr above will have no effect. GeoIP fields with the same country code are // supposed to contain exactly same content. They will be merged during // runtime. For customized GeoIPs, please leave country code empty. Geoip []*routercommon.GeoIP `protobuf:"bytes,10,rep,name=geoip,proto3" json:"geoip,omitempty"` // List of ports. PortList string `protobuf:"bytes,14,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"` // List of networks for matching. Networks *net.NetworkList `protobuf:"bytes,13,opt,name=networks,proto3" json:"networks,omitempty"` // List of GeoIPs for source IP address matching. If this entry exists, the // source_cidr above will have no effect. SourceGeoip []*routercommon.GeoIP `protobuf:"bytes,11,rep,name=source_geoip,json=sourceGeoip,proto3" json:"source_geoip,omitempty"` // List of ports for source port matching. SourcePortList string `protobuf:"bytes,16,opt,name=source_port_list,json=sourcePortList,proto3" json:"source_port_list,omitempty"` UserEmail []string `protobuf:"bytes,7,rep,name=user_email,json=userEmail,proto3" json:"user_email,omitempty"` InboundTag []string `protobuf:"bytes,8,rep,name=inbound_tag,json=inboundTag,proto3" json:"inbound_tag,omitempty"` Protocol []string `protobuf:"bytes,9,rep,name=protocol,proto3" json:"protocol,omitempty"` Attributes string `protobuf:"bytes,15,opt,name=attributes,proto3" json:"attributes,omitempty"` DomainMatcher string `protobuf:"bytes,17,opt,name=domain_matcher,json=domainMatcher,proto3" json:"domain_matcher,omitempty"` // geo_domain instruct simplified config loader to load geo domain rule and fill in domain field. GeoDomain []*routercommon.GeoSite `protobuf:"bytes,68001,rep,name=geo_domain,json=geoDomain,proto3" json:"geo_domain,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedRoutingRule) Reset() { *x = SimplifiedRoutingRule{} mi := &file_app_router_config_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedRoutingRule) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedRoutingRule) ProtoMessage() {} func (x *SimplifiedRoutingRule) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedRoutingRule.ProtoReflect.Descriptor instead. func (*SimplifiedRoutingRule) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{7} } func (x *SimplifiedRoutingRule) GetTargetTag() isSimplifiedRoutingRule_TargetTag { if x != nil { return x.TargetTag } return nil } func (x *SimplifiedRoutingRule) GetTag() string { if x != nil { if x, ok := x.TargetTag.(*SimplifiedRoutingRule_Tag); ok { return x.Tag } } return "" } func (x *SimplifiedRoutingRule) GetBalancingTag() string { if x != nil { if x, ok := x.TargetTag.(*SimplifiedRoutingRule_BalancingTag); ok { return x.BalancingTag } } return "" } func (x *SimplifiedRoutingRule) GetDomain() []*routercommon.Domain { if x != nil { return x.Domain } return nil } func (x *SimplifiedRoutingRule) GetGeoip() []*routercommon.GeoIP { if x != nil { return x.Geoip } return nil } func (x *SimplifiedRoutingRule) GetPortList() string { if x != nil { return x.PortList } return "" } func (x *SimplifiedRoutingRule) GetNetworks() *net.NetworkList { if x != nil { return x.Networks } return nil } func (x *SimplifiedRoutingRule) GetSourceGeoip() []*routercommon.GeoIP { if x != nil { return x.SourceGeoip } return nil } func (x *SimplifiedRoutingRule) GetSourcePortList() string { if x != nil { return x.SourcePortList } return "" } func (x *SimplifiedRoutingRule) GetUserEmail() []string { if x != nil { return x.UserEmail } return nil } func (x *SimplifiedRoutingRule) GetInboundTag() []string { if x != nil { return x.InboundTag } return nil } func (x *SimplifiedRoutingRule) GetProtocol() []string { if x != nil { return x.Protocol } return nil } func (x *SimplifiedRoutingRule) GetAttributes() string { if x != nil { return x.Attributes } return "" } func (x *SimplifiedRoutingRule) GetDomainMatcher() string { if x != nil { return x.DomainMatcher } return "" } func (x *SimplifiedRoutingRule) GetGeoDomain() []*routercommon.GeoSite { if x != nil { return x.GeoDomain } return nil } type isSimplifiedRoutingRule_TargetTag interface { isSimplifiedRoutingRule_TargetTag() } type SimplifiedRoutingRule_Tag struct { // Tag of outbound that this rule is pointing to. Tag string `protobuf:"bytes,1,opt,name=tag,proto3,oneof"` } type SimplifiedRoutingRule_BalancingTag struct { // Tag of routing balancer. BalancingTag string `protobuf:"bytes,12,opt,name=balancing_tag,json=balancingTag,proto3,oneof"` } func (*SimplifiedRoutingRule_Tag) isSimplifiedRoutingRule_TargetTag() {} func (*SimplifiedRoutingRule_BalancingTag) isSimplifiedRoutingRule_TargetTag() {} type SimplifiedConfig struct { state protoimpl.MessageState `protogen:"open.v1"` DomainStrategy DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=v2ray.core.app.router.DomainStrategy" json:"domain_strategy,omitempty"` Rule []*SimplifiedRoutingRule `protobuf:"bytes,2,rep,name=rule,proto3" json:"rule,omitempty"` BalancingRule []*BalancingRule `protobuf:"bytes,3,rep,name=balancing_rule,json=balancingRule,proto3" json:"balancing_rule,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedConfig) Reset() { *x = SimplifiedConfig{} mi := &file_app_router_config_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedConfig) ProtoMessage() {} func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message { mi := &file_app_router_config_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead. func (*SimplifiedConfig) Descriptor() ([]byte, []int) { return file_app_router_config_proto_rawDescGZIP(), []int{8} } func (x *SimplifiedConfig) GetDomainStrategy() DomainStrategy { if x != nil { return x.DomainStrategy } return DomainStrategy_AsIs } func (x *SimplifiedConfig) GetRule() []*SimplifiedRoutingRule { if x != nil { return x.Rule } return nil } func (x *SimplifiedConfig) GetBalancingRule() []*BalancingRule { if x != nil { return x.BalancingRule } return nil } var File_app_router_config_proto protoreflect.FileDescriptor const file_app_router_config_proto_rawDesc = "" + "\n" + "\x17app/router/config.proto\x12\x15v2ray.core.app.router\x1a\x19google/protobuf/any.proto\x1a\x15common/net/port.proto\x1a\x18common/net/network.proto\x1a common/protoext/extensions.proto\x1a$app/router/routercommon/common.proto\"\x80\b\n" + "\vRoutingRule\x12\x12\n" + "\x03tag\x18\x01 \x01(\tH\x00R\x03tag\x12%\n" + "\rbalancing_tag\x18\f \x01(\tH\x00R\fbalancingTag\x12B\n" + "\x06domain\x18\x02 \x03(\v2*.v2ray.core.app.router.routercommon.DomainR\x06domain\x12@\n" + "\x04cidr\x18\x03 \x03(\v2(.v2ray.core.app.router.routercommon.CIDRB\x02\x18\x01R\x04cidr\x12?\n" + "\x05geoip\x18\n" + " \x03(\v2).v2ray.core.app.router.routercommon.GeoIPR\x05geoip\x12C\n" + "\n" + "port_range\x18\x04 \x01(\v2 .v2ray.core.common.net.PortRangeB\x02\x18\x01R\tportRange\x12<\n" + "\tport_list\x18\x0e \x01(\v2\x1f.v2ray.core.common.net.PortListR\bportList\x12I\n" + "\fnetwork_list\x18\x05 \x01(\v2\".v2ray.core.common.net.NetworkListB\x02\x18\x01R\vnetworkList\x12:\n" + "\bnetworks\x18\r \x03(\x0e2\x1e.v2ray.core.common.net.NetworkR\bnetworks\x12M\n" + "\vsource_cidr\x18\x06 \x03(\v2(.v2ray.core.app.router.routercommon.CIDRB\x02\x18\x01R\n" + "sourceCidr\x12L\n" + "\fsource_geoip\x18\v \x03(\v2).v2ray.core.app.router.routercommon.GeoIPR\vsourceGeoip\x12I\n" + "\x10source_port_list\x18\x10 \x01(\v2\x1f.v2ray.core.common.net.PortListR\x0esourcePortList\x12\x1d\n" + "\n" + "user_email\x18\a \x03(\tR\tuserEmail\x12\x1f\n" + "\vinbound_tag\x18\b \x03(\tR\n" + "inboundTag\x12\x1a\n" + "\bprotocol\x18\t \x03(\tR\bprotocol\x12\x1e\n" + "\n" + "attributes\x18\x0f \x01(\tR\n" + "attributes\x12%\n" + "\x0edomain_matcher\x18\x11 \x01(\tR\rdomainMatcher\x12L\n" + "\n" + "geo_domain\x18\xa1\x93\x04 \x03(\v2+.v2ray.core.app.router.routercommon.GeoSiteR\tgeoDomainB\f\n" + "\n" + "target_tag\"\xd0\x01\n" + "\rBalancingRule\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12+\n" + "\x11outbound_selector\x18\x02 \x03(\tR\x10outboundSelector\x12\x1a\n" + "\bstrategy\x18\x03 \x01(\tR\bstrategy\x12A\n" + "\x11strategy_settings\x18\x04 \x01(\v2\x14.google.protobuf.AnyR\x10strategySettings\x12!\n" + "\ffallback_tag\x18\x05 \x01(\tR\vfallbackTag\"T\n" + "\x0eStrategyWeight\x12\x16\n" + "\x06regexp\x18\x01 \x01(\bR\x06regexp\x12\x14\n" + "\x05match\x18\x02 \x01(\tR\x05match\x12\x14\n" + "\x05value\x18\x03 \x01(\x02R\x05value\"p\n" + "\x14StrategyRandomConfig\x12!\n" + "\fobserver_tag\x18\a \x01(\tR\vobserverTag\x12\x1d\n" + "\n" + "alive_only\x18\b \x01(\bR\taliveOnly:\x16\x82\xb5\x18\x12\n" + "\bbalancer\x12\x06random\"W\n" + "\x17StrategyLeastPingConfig\x12!\n" + "\fobserver_tag\x18\a \x01(\tR\vobserverTag:\x19\x82\xb5\x18\x15\n" + "\bbalancer\x12\tleastping\"\x84\x02\n" + "\x17StrategyLeastLoadConfig\x12;\n" + "\x05costs\x18\x02 \x03(\v2%.v2ray.core.app.router.StrategyWeightR\x05costs\x12\x1c\n" + "\tbaselines\x18\x03 \x03(\x03R\tbaselines\x12\x1a\n" + "\bexpected\x18\x04 \x01(\x05R\bexpected\x12\x16\n" + "\x06maxRTT\x18\x05 \x01(\x03R\x06maxRTT\x12\x1c\n" + "\ttolerance\x18\x06 \x01(\x02R\ttolerance\x12!\n" + "\fobserver_tag\x18\a \x01(\tR\vobserverTag:\x19\x82\xb5\x18\x15\n" + "\bbalancer\x12\tleastload\"\xdd\x01\n" + "\x06Config\x12N\n" + "\x0fdomain_strategy\x18\x01 \x01(\x0e2%.v2ray.core.app.router.DomainStrategyR\x0edomainStrategy\x126\n" + "\x04rule\x18\x02 \x03(\v2\".v2ray.core.app.router.RoutingRuleR\x04rule\x12K\n" + "\x0ebalancing_rule\x18\x03 \x03(\v2$.v2ray.core.app.router.BalancingRuleR\rbalancingRule\"\xab\x05\n" + "\x15SimplifiedRoutingRule\x12\x12\n" + "\x03tag\x18\x01 \x01(\tH\x00R\x03tag\x12%\n" + "\rbalancing_tag\x18\f \x01(\tH\x00R\fbalancingTag\x12B\n" + "\x06domain\x18\x02 \x03(\v2*.v2ray.core.app.router.routercommon.DomainR\x06domain\x12?\n" + "\x05geoip\x18\n" + " \x03(\v2).v2ray.core.app.router.routercommon.GeoIPR\x05geoip\x12\x1b\n" + "\tport_list\x18\x0e \x01(\tR\bportList\x12>\n" + "\bnetworks\x18\r \x01(\v2\".v2ray.core.common.net.NetworkListR\bnetworks\x12L\n" + "\fsource_geoip\x18\v \x03(\v2).v2ray.core.app.router.routercommon.GeoIPR\vsourceGeoip\x12(\n" + "\x10source_port_list\x18\x10 \x01(\tR\x0esourcePortList\x12\x1d\n" + "\n" + "user_email\x18\a \x03(\tR\tuserEmail\x12\x1f\n" + "\vinbound_tag\x18\b \x03(\tR\n" + "inboundTag\x12\x1a\n" + "\bprotocol\x18\t \x03(\tR\bprotocol\x12\x1e\n" + "\n" + "attributes\x18\x0f \x01(\tR\n" + "attributes\x12%\n" + "\x0edomain_matcher\x18\x11 \x01(\tR\rdomainMatcher\x12L\n" + "\n" + "geo_domain\x18\xa1\x93\x04 \x03(\v2+.v2ray.core.app.router.routercommon.GeoSiteR\tgeoDomainB\f\n" + "\n" + "target_tag\"\x88\x02\n" + "\x10SimplifiedConfig\x12N\n" + "\x0fdomain_strategy\x18\x01 \x01(\x0e2%.v2ray.core.app.router.DomainStrategyR\x0edomainStrategy\x12@\n" + "\x04rule\x18\x02 \x03(\v2,.v2ray.core.app.router.SimplifiedRoutingRuleR\x04rule\x12K\n" + "\x0ebalancing_rule\x18\x03 \x03(\v2$.v2ray.core.app.router.BalancingRuleR\rbalancingRule:\x15\x82\xb5\x18\x11\n" + "\aservice\x12\x06router*G\n" + "\x0eDomainStrategy\x12\b\n" + "\x04AsIs\x10\x00\x12\t\n" + "\x05UseIp\x10\x01\x12\x10\n" + "\fIpIfNonMatch\x10\x02\x12\x0e\n" + "\n" + "IpOnDemand\x10\x03B`\n" +
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
true
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/router_test.go
app/router/router_test.go
package router_test import ( "context" "testing" "github.com/golang/mock/gomock" . "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/outbound" routing_session "github.com/v2fly/v2ray-core/v5/features/routing/session" "github.com/v2fly/v2ray-core/v5/testing/mocks" ) type mockOutboundManager struct { outbound.Manager outbound.HandlerSelector } func TestSimpleRouter(t *testing.T) { config := &Config{ Rule: []*RoutingRule{ { TargetTag: &RoutingRule_Tag{ Tag: "test", }, Networks: []net.Network{net.Network_TCP}, }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) mockOhm := mocks.NewOutboundManager(mockCtl) mockHs := mocks.NewOutboundHandlerSelector(mockCtl) r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, &mockOutboundManager{ Manager: mockOhm, HandlerSelector: mockHs, }, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2fly.org"), 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test" { t.Error("expect tag 'test', bug actually ", tag) } } func TestSimpleBalancer(t *testing.T) { config := &Config{ Rule: []*RoutingRule{ { TargetTag: &RoutingRule_BalancingTag{ BalancingTag: "balance", }, Networks: []net.Network{net.Network_TCP}, }, }, BalancingRule: []*BalancingRule{ { Tag: "balance", OutboundSelector: []string{"test-"}, }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) mockOhm := mocks.NewOutboundManager(mockCtl) mockHs := mocks.NewOutboundHandlerSelector(mockCtl) mockHs.EXPECT().Select(gomock.Eq([]string{"test-"})).Return([]string{"test"}) r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, &mockOutboundManager{ Manager: mockOhm, HandlerSelector: mockHs, }, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2fly.org"), 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test" { t.Error("expect tag 'test', bug actually ", tag) } } /* Do not work right now: need a full client setup func TestLeastLoadBalancer(t *testing.T) { config := &Config{ Rule: []*RoutingRule{ { TargetTag: &RoutingRule_BalancingTag{ BalancingTag: "balance", }, Networks: []net.Network{net.Network_TCP}, }, }, BalancingRule: []*BalancingRule{ { Tag: "balance", OutboundSelector: []string{"test-"}, Strategy: "leastLoad", StrategySettings: serial.ToTypedMessage(&StrategyLeastLoadConfig{ Baselines: nil, Expected: 1, }), }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) mockOhm := mocks.NewOutboundManager(mockCtl) mockHs := mocks.NewOutboundHandlerSelector(mockCtl) mockHs.EXPECT().Select(gomock.Eq([]string{"test-"})).Return([]string{"test1"}) r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, &mockOutboundManager{ Manager: mockOhm, HandlerSelector: mockHs, }, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2ray.com"), 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test1" { t.Error("expect tag 'test1', bug actually ", tag) } }*/ func TestIPOnDemand(t *testing.T) { config := &Config{ DomainStrategy: DomainStrategy_IpOnDemand, Rule: []*RoutingRule{ { TargetTag: &RoutingRule_Tag{ Tag: "test", }, Cidr: []*routercommon.CIDR{ { Ip: []byte{192, 168, 0, 0}, Prefix: 16, }, }, }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) mockDNS.EXPECT().LookupIP(gomock.Eq("v2fly.org")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes() r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2fly.org"), 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test" { t.Error("expect tag 'test', bug actually ", tag) } } func TestIPIfNonMatchDomain(t *testing.T) { config := &Config{ DomainStrategy: DomainStrategy_IpIfNonMatch, Rule: []*RoutingRule{ { TargetTag: &RoutingRule_Tag{ Tag: "test", }, Cidr: []*routercommon.CIDR{ { Ip: []byte{192, 168, 0, 0}, Prefix: 16, }, }, }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) mockDNS.EXPECT().LookupIP(gomock.Eq("v2fly.org")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes() r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2fly.org"), 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test" { t.Error("expect tag 'test', bug actually ", tag) } } func TestIPIfNonMatchIP(t *testing.T) { config := &Config{ DomainStrategy: DomainStrategy_IpIfNonMatch, Rule: []*RoutingRule{ { TargetTag: &RoutingRule_Tag{ Tag: "test", }, Cidr: []*routercommon.CIDR{ { Ip: []byte{127, 0, 0, 0}, Prefix: 8, }, }, }, }, } mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockDNS := mocks.NewDNSClient(mockCtl) r := new(Router) common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil)) ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 80)}) route, err := r.PickRoute(routing_session.AsRoutingContext(ctx)) common.Must(err) if tag := route.GetOutboundTag(); tag != "test" { t.Error("expect tag 'test', bug actually ", tag) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/condition.go
app/router/condition.go
package router import ( "strings" "go.starlark.net/starlark" "go.starlark.net/syntax" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/strmatcher" "github.com/v2fly/v2ray-core/v5/features/routing" ) type Condition interface { Apply(ctx routing.Context) bool } type ConditionChan []Condition func NewConditionChan() *ConditionChan { var condChan ConditionChan = make([]Condition, 0, 8) return &condChan } func (v *ConditionChan) Add(cond Condition) *ConditionChan { *v = append(*v, cond) return v } // Apply applies all conditions registered in this chan. func (v *ConditionChan) Apply(ctx routing.Context) bool { for _, cond := range *v { if !cond.Apply(ctx) { return false } } return true } func (v *ConditionChan) Len() int { return len(*v) } var matcherTypeMap = map[routercommon.Domain_Type]strmatcher.Type{ routercommon.Domain_Plain: strmatcher.Substr, routercommon.Domain_Regex: strmatcher.Regex, routercommon.Domain_RootDomain: strmatcher.Domain, routercommon.Domain_Full: strmatcher.Full, } func domainToMatcher(domain *routercommon.Domain) (strmatcher.Matcher, error) { matcherType, f := matcherTypeMap[domain.Type] if !f { return nil, newError("unsupported domain type", domain.Type) } matcher, err := matcherType.New(domain.Value) if err != nil { return nil, newError("failed to create domain matcher").Base(err) } return matcher, nil } type DomainMatcher struct { matcher strmatcher.IndexMatcher } func NewDomainMatcher(matcherType string, domains []*routercommon.Domain) (*DomainMatcher, error) { var indexMatcher strmatcher.IndexMatcher switch matcherType { case "mph", "hybrid": indexMatcher = strmatcher.NewMphIndexMatcher() case "linear": indexMatcher = strmatcher.NewLinearIndexMatcher() default: indexMatcher = strmatcher.NewLinearIndexMatcher() } for _, domain := range domains { matcher, err := domainToMatcher(domain) if err != nil { return nil, err } indexMatcher.Add(matcher) } if err := indexMatcher.Build(); err != nil { return nil, err } return &DomainMatcher{matcher: indexMatcher}, nil } func (m *DomainMatcher) Match(domain string) bool { return m.matcher.MatchAny(domain) } // Apply implements Condition. func (m *DomainMatcher) Apply(ctx routing.Context) bool { domain := ctx.GetTargetDomain() if len(domain) == 0 { return false } return m.Match(domain) } type MultiGeoIPMatcher struct { matchers []*GeoIPMatcher onSource bool } func NewMultiGeoIPMatcher(geoips []*routercommon.GeoIP, onSource bool) (*MultiGeoIPMatcher, error) { var matchers []*GeoIPMatcher for _, geoip := range geoips { matcher, err := globalGeoIPContainer.Add(geoip) if err != nil { return nil, err } matchers = append(matchers, matcher) } matcher := &MultiGeoIPMatcher{ matchers: matchers, onSource: onSource, } return matcher, nil } // Apply implements Condition. func (m *MultiGeoIPMatcher) Apply(ctx routing.Context) bool { var ips []net.IP if m.onSource { ips = ctx.GetSourceIPs() } else { ips = ctx.GetTargetIPs() } for _, ip := range ips { for _, matcher := range m.matchers { if matcher.Match(ip) { return true } } } return false } type PortMatcher struct { port net.MemoryPortList onSource bool } // NewPortMatcher creates a new port matcher that can match source or destination port func NewPortMatcher(list *net.PortList, onSource bool) *PortMatcher { return &PortMatcher{ port: net.PortListFromProto(list), onSource: onSource, } } // Apply implements Condition. func (v *PortMatcher) Apply(ctx routing.Context) bool { if v.onSource { return v.port.Contains(ctx.GetSourcePort()) } return v.port.Contains(ctx.GetTargetPort()) } type NetworkMatcher struct { list [8]bool } func NewNetworkMatcher(network []net.Network) NetworkMatcher { var matcher NetworkMatcher for _, n := range network { matcher.list[int(n)] = true } return matcher } // Apply implements Condition. func (v NetworkMatcher) Apply(ctx routing.Context) bool { return v.list[int(ctx.GetNetwork())] } type UserMatcher struct { user []string } func NewUserMatcher(users []string) *UserMatcher { usersCopy := make([]string, 0, len(users)) for _, user := range users { if len(user) > 0 { usersCopy = append(usersCopy, user) } } return &UserMatcher{ user: usersCopy, } } // Apply implements Condition. func (v *UserMatcher) Apply(ctx routing.Context) bool { user := ctx.GetUser() if len(user) == 0 { return false } for _, u := range v.user { if u == user { return true } } return false } type InboundTagMatcher struct { tags []string } func NewInboundTagMatcher(tags []string) *InboundTagMatcher { tagsCopy := make([]string, 0, len(tags)) for _, tag := range tags { if len(tag) > 0 { tagsCopy = append(tagsCopy, tag) } } return &InboundTagMatcher{ tags: tagsCopy, } } // Apply implements Condition. func (v *InboundTagMatcher) Apply(ctx routing.Context) bool { tag := ctx.GetInboundTag() if len(tag) == 0 { return false } for _, t := range v.tags { if t == tag { return true } } return false } type ProtocolMatcher struct { protocols []string } func NewProtocolMatcher(protocols []string) *ProtocolMatcher { pCopy := make([]string, 0, len(protocols)) for _, p := range protocols { if len(p) > 0 { pCopy = append(pCopy, p) } } return &ProtocolMatcher{ protocols: pCopy, } } // Apply implements Condition. func (m *ProtocolMatcher) Apply(ctx routing.Context) bool { protocol := ctx.GetProtocol() if len(protocol) == 0 { return false } for _, p := range m.protocols { if strings.HasPrefix(protocol, p) { return true } } return false } type AttributeMatcher struct { program *starlark.Program } func NewAttributeMatcher(code string) (*AttributeMatcher, error) { starFile, err := syntax.Parse("attr.star", "satisfied=("+code+")", 0) if err != nil { return nil, newError("attr rule").Base(err) } p, err := starlark.FileProgram(starFile, func(name string) bool { return name == "attrs" }) if err != nil { return nil, err } return &AttributeMatcher{ program: p, }, nil } // Match implements attributes matching. func (m *AttributeMatcher) Match(attrs map[string]string) bool { attrsDict := new(starlark.Dict) for key, value := range attrs { attrsDict.SetKey(starlark.String(key), starlark.String(value)) } predefined := make(starlark.StringDict) predefined["attrs"] = attrsDict thread := &starlark.Thread{ Name: "matcher", } results, err := m.program.Init(thread, predefined) if err != nil { newError("attr matcher").Base(err).WriteToLog() } satisfied := results["satisfied"] return satisfied != nil && bool(satisfied.Truth()) } // Apply implements Condition. func (m *AttributeMatcher) Apply(ctx routing.Context) bool { attributes := ctx.GetAttributes() if attributes == nil { return false } return m.Match(attributes) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/condition_test.go
app/router/condition_test.go
package router_test import ( "errors" "io/fs" "os" "path/filepath" "strconv" "strings" "testing" "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/app/router" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/protocol/http" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/features/routing" routing_session "github.com/v2fly/v2ray-core/v5/features/routing/session" ) func init() { const ( geoipURL = "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat" geositeURL = "https://raw.githubusercontent.com/v2fly/domain-list-community/release/dlc.dat" ) wd, err := os.Getwd() common.Must(err) tempPath := filepath.Join(wd, "..", "..", "testing", "temp") geoipPath := filepath.Join(tempPath, "geoip.dat") geositePath := filepath.Join(tempPath, "geosite.dat") os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) } } func withBackground() routing.Context { return &routing_session.Context{} } func withOutbound(outbound *session.Outbound) routing.Context { return &routing_session.Context{Outbound: outbound} } func withInbound(inbound *session.Inbound) routing.Context { return &routing_session.Context{Inbound: inbound} } func withContent(content *session.Content) routing.Context { return &routing_session.Context{Content: content} } func TestRoutingRule(t *testing.T) { type ruleTest struct { input routing.Context output bool } cases := []struct { rule *router.RoutingRule test []ruleTest }{ { rule: &router.RoutingRule{ Domain: []*routercommon.Domain{ { Value: "v2fly.org", Type: routercommon.Domain_Plain, }, { Value: "google.com", Type: routercommon.Domain_RootDomain, }, { Value: "^facebook\\.com$", Type: routercommon.Domain_Regex, }, }, }, test: []ruleTest{ { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2fly.org"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.v2fly.org.www"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2ray.co"), 80)}), output: false, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.google.com"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("facebook.com"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.DomainAddress("www.facebook.com"), 80)}), output: false, }, { input: withBackground(), output: false, }, }, }, { rule: &router.RoutingRule{ Cidr: []*routercommon.CIDR{ { Ip: []byte{8, 8, 8, 8}, Prefix: 32, }, { Ip: []byte{8, 8, 8, 8}, Prefix: 32, }, { Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(), Prefix: 128, }, }, }, test: []ruleTest{ { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.4.4"), 80)}), output: false, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), 80)}), output: true, }, { input: withBackground(), output: false, }, }, }, { rule: &router.RoutingRule{ Geoip: []*routercommon.GeoIP{ { Cidr: []*routercommon.CIDR{ { Ip: []byte{8, 8, 8, 8}, Prefix: 32, }, { Ip: []byte{8, 8, 8, 8}, Prefix: 32, }, { Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(), Prefix: 128, }, }, }, }, }, test: []ruleTest{ { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.4.4"), 80)}), output: false, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), 80)}), output: true, }, { input: withBackground(), output: false, }, }, }, { rule: &router.RoutingRule{ SourceCidr: []*routercommon.CIDR{ { Ip: []byte{192, 168, 0, 0}, Prefix: 16, }, }, }, test: []ruleTest{ { input: withInbound(&session.Inbound{Source: net.TCPDestination(net.ParseAddress("192.168.0.1"), 80)}), output: true, }, { input: withInbound(&session.Inbound{Source: net.TCPDestination(net.ParseAddress("10.0.0.1"), 80)}), output: false, }, }, }, { rule: &router.RoutingRule{ UserEmail: []string{ "admin@v2fly.org", }, }, test: []ruleTest{ { input: withInbound(&session.Inbound{User: &protocol.MemoryUser{Email: "admin@v2fly.org"}}), output: true, }, { input: withInbound(&session.Inbound{User: &protocol.MemoryUser{Email: "love@v2fly.org"}}), output: false, }, { input: withBackground(), output: false, }, }, }, { rule: &router.RoutingRule{ Protocol: []string{"http"}, }, test: []ruleTest{ { input: withContent(&session.Content{Protocol: (&http.SniffHeader{}).Protocol()}), output: true, }, }, }, { rule: &router.RoutingRule{ InboundTag: []string{"test", "test1"}, }, test: []ruleTest{ { input: withInbound(&session.Inbound{Tag: "test"}), output: true, }, { input: withInbound(&session.Inbound{Tag: "test2"}), output: false, }, }, }, { rule: &router.RoutingRule{ PortList: &net.PortList{ Range: []*net.PortRange{ {From: 443, To: 443}, {From: 1000, To: 1100}, }, }, }, test: []ruleTest{ { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 443)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 1100)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 1005)}), output: true, }, { input: withOutbound(&session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 53)}), output: false, }, }, }, { rule: &router.RoutingRule{ SourcePortList: &net.PortList{ Range: []*net.PortRange{ {From: 123, To: 123}, {From: 9993, To: 9999}, }, }, }, test: []ruleTest{ { input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 123)}), output: true, }, { input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 9999)}), output: true, }, { input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 9994)}), output: true, }, { input: withInbound(&session.Inbound{Source: net.UDPDestination(net.LocalHostIP, 53)}), output: false, }, }, }, { rule: &router.RoutingRule{ Protocol: []string{"http"}, Attributes: "attrs[':path'].startswith('/test')", }, test: []ruleTest{ { input: withContent(&session.Content{Protocol: "http/1.1", Attributes: map[string]string{":path": "/test/1"}}), output: true, }, }, }, } for _, test := range cases { cond, err := test.rule.BuildCondition() common.Must(err) for _, subtest := range test.test { actual := cond.Apply(subtest.input) if actual != subtest.output { t.Error("test case failed: ", subtest.input, " expected ", subtest.output, " but got ", actual) } } } } func loadGeoSite(country string) ([]*routercommon.Domain, error) { geositeBytes, err := filesystem.ReadAsset("geosite.dat") if err != nil { return nil, err } var geositeList routercommon.GeoSiteList if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil { return nil, err } for _, site := range geositeList.Entry { if strings.EqualFold(site.CountryCode, country) { return site.Domain, nil } } return nil, errors.New("country not found: " + country) } func TestChinaSites(t *testing.T) { domains, err := loadGeoSite("CN") common.Must(err) matcher, err := router.NewDomainMatcher("linear", domains) common.Must(err) mphMatcher, err := router.NewDomainMatcher("mph", domains) common.Must(err) type TestCase struct { Domain string Output bool } testCases := []TestCase{ { Domain: "163.com", Output: true, }, { Domain: "163.com", Output: true, }, { Domain: "164.com", Output: false, }, { Domain: "164.com", Output: false, }, } for i := 0; i < 1024; i++ { testCases = append(testCases, TestCase{Domain: strconv.Itoa(i) + ".not-exists.com", Output: false}) } for _, testCase := range testCases { r1 := matcher.Match(testCase.Domain) r2 := mphMatcher.Match(testCase.Domain) if r1 != testCase.Output { t.Error("DomainMatcher expected output ", testCase.Output, " for domain ", testCase.Domain, " but got ", r1) } else if r2 != testCase.Output { t.Error("ACDomainMatcher expected output ", testCase.Output, " for domain ", testCase.Domain, " but got ", r2) } } } func BenchmarkMphDomainMatcher(b *testing.B) { domains, err := loadGeoSite("CN") common.Must(err) matcher, err := router.NewDomainMatcher("mph", domains) common.Must(err) type TestCase struct { Domain string Output bool } testCases := []TestCase{ { Domain: "163.com", Output: true, }, { Domain: "163.com", Output: true, }, { Domain: "164.com", Output: false, }, { Domain: "164.com", Output: false, }, } for i := 0; i < 1024; i++ { testCases = append(testCases, TestCase{Domain: strconv.Itoa(i) + ".not-exists.com", Output: false}) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, testCase := range testCases { _ = matcher.Match(testCase.Domain) } } } func BenchmarkDomainMatcher(b *testing.B) { domains, err := loadGeoSite("CN") common.Must(err) matcher, err := router.NewDomainMatcher("linear", domains) common.Must(err) type TestCase struct { Domain string Output bool } testCases := []TestCase{ { Domain: "163.com", Output: true, }, { Domain: "163.com", Output: true, }, { Domain: "164.com", Output: false, }, { Domain: "164.com", Output: false, }, } for i := 0; i < 1024; i++ { testCases = append(testCases, TestCase{Domain: strconv.Itoa(i) + ".not-exists.com", Output: false}) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, testCase := range testCases { _ = matcher.Match(testCase.Domain) } } } func BenchmarkMultiGeoIPMatcher(b *testing.B) { var geoips []*routercommon.GeoIP { ips, err := loadGeoIP("CN") common.Must(err) geoips = append(geoips, &routercommon.GeoIP{ CountryCode: "CN", Cidr: ips, }) } { ips, err := loadGeoIP("JP") common.Must(err) geoips = append(geoips, &routercommon.GeoIP{ CountryCode: "JP", Cidr: ips, }) } { ips, err := loadGeoIP("CA") common.Must(err) geoips = append(geoips, &routercommon.GeoIP{ CountryCode: "CA", Cidr: ips, }) } { ips, err := loadGeoIP("US") common.Must(err) geoips = append(geoips, &routercommon.GeoIP{ CountryCode: "US", Cidr: ips, }) } matcher, err := router.NewMultiGeoIPMatcher(geoips, false) common.Must(err) ctx := withOutbound(&session.Outbound{Target: net.TCPDestination(net.ParseAddress("8.8.8.8"), 80)}) b.ResetTimer() for i := 0; i < b.N; i++ { _ = matcher.Apply(ctx) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/command_test.go
app/router/command/command_test.go
package command_test import ( "context" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/test/bufconn" "github.com/v2fly/v2ray-core/v5/app/router" . "github.com/v2fly/v2ray-core/v5/app/router/command" "github.com/v2fly/v2ray-core/v5/app/router/routercommon" "github.com/v2fly/v2ray-core/v5/app/stats" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/testing/mocks" ) func TestServiceSubscribeRoutingStats(t *testing.T) { c := stats.NewChannel(&stats.ChannelConfig{ SubscriberLimit: 1, BufferSize: 0, Blocking: true, }) common.Must(c.Start()) defer c.Close() lis := bufconn.Listen(1024 * 1024) bufDialer := func(context.Context, string) (net.Conn, error) { return lis.Dial() } testCases := []*RoutingContext{ {InboundTag: "in", OutboundTag: "out"}, {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"}, {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"}, {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"}, {Network: net.Network_UDP, OutboundGroupTags: []string{"outergroup", "innergroup"}, OutboundTag: "out"}, {Protocol: "bittorrent", OutboundTag: "blocked"}, {User: "example@v2fly.org", OutboundTag: "out"}, {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"}, } errCh := make(chan error) nextPub := make(chan struct{}) // Server goroutine go func() { server := grpc.NewServer() RegisterRoutingServiceServer(server, NewRoutingServer(nil, c)) errCh <- server.Serve(lis) }() // Publisher goroutine go func() { publishTestCases := func() error { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() for { // Wait until there's one subscriber in routing stats channel if len(c.Subscribers()) > 0 { break } if ctx.Err() != nil { return ctx.Err() } } for _, tc := range testCases { c.Publish(context.Background(), AsRoutingRoute(tc)) time.Sleep(time.Millisecond) } return nil } if err := publishTestCases(); err != nil { errCh <- err } // Wait for next round of publishing <-nextPub if err := publishTestCases(); err != nil { errCh <- err } }() // Client goroutine go func() { defer lis.Close() conn, err := grpc.DialContext( context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { errCh <- err return } defer conn.Close() client := NewRoutingServiceClient(conn) // Test retrieving all fields testRetrievingAllFields := func() error { streamCtx, streamClose := context.WithCancel(context.Background()) // Test the unsubscription of stream works well defer func() { streamClose() timeOutCtx, timeout := context.WithTimeout(context.Background(), time.Second) defer timeout() for { // Wait until there's no subscriber in routing stats channel if len(c.Subscribers()) == 0 { break } if timeOutCtx.Err() != nil { t.Error("unexpected subscribers not decreased in channel", timeOutCtx.Err()) } } }() stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{}) if err != nil { return err } for _, tc := range testCases { msg, err := stream.Recv() if err != nil { return err } if r := cmp.Diff(msg, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" { t.Error(r) } } // Test that double subscription will fail errStream, err := client.SubscribeRoutingStats(context.Background(), &SubscribeRoutingStatsRequest{ FieldSelectors: []string{"ip", "port", "domain", "outbound"}, }) if err != nil { return err } if _, err := errStream.Recv(); err == nil { t.Error("unexpected successful subscription") } return nil } // Test retrieving only a subset of fields testRetrievingSubsetOfFields := func() error { streamCtx, streamClose := context.WithCancel(context.Background()) defer streamClose() stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{ FieldSelectors: []string{"ip", "port", "domain", "outbound"}, }) if err != nil { return err } // Send nextPub signal to start next round of publishing close(nextPub) for _, tc := range testCases { msg, err := stream.Recv() if err != nil { return err } stat := &RoutingContext{ // Only a subset of stats is retrieved SourceIPs: tc.SourceIPs, TargetIPs: tc.TargetIPs, SourcePort: tc.SourcePort, TargetPort: tc.TargetPort, TargetDomain: tc.TargetDomain, OutboundGroupTags: tc.OutboundGroupTags, OutboundTag: tc.OutboundTag, } if r := cmp.Diff(msg, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" { t.Error(r) } } return nil } if err := testRetrievingAllFields(); err != nil { errCh <- err } if err := testRetrievingSubsetOfFields(); err != nil { errCh <- err } errCh <- nil // Client passed all tests successfully }() // Wait for goroutines to complete select { case <-time.After(2 * time.Second): t.Fatal("Test timeout after 2s") case err := <-errCh: if err != nil { t.Fatal(err) } } } func TestSerivceTestRoute(t *testing.T) { c := stats.NewChannel(&stats.ChannelConfig{ SubscriberLimit: 1, BufferSize: 16, Blocking: true, }) common.Must(c.Start()) defer c.Close() r := new(router.Router) mockCtl := gomock.NewController(t) defer mockCtl.Finish() common.Must(r.Init(context.TODO(), &router.Config{ Rule: []*router.RoutingRule{ { InboundTag: []string{"in"}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { Protocol: []string{"bittorrent"}, TargetTag: &router.RoutingRule_Tag{Tag: "blocked"}, }, { PortList: &net.PortList{Range: []*net.PortRange{{From: 8080, To: 8080}}}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { SourcePortList: &net.PortList{Range: []*net.PortRange{{From: 9999, To: 9999}}}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { Domain: []*routercommon.Domain{{Type: routercommon.Domain_RootDomain, Value: "com"}}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { SourceGeoip: []*routercommon.GeoIP{{CountryCode: "private", Cidr: []*routercommon.CIDR{{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { UserEmail: []string{"example@v2fly.org"}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, { Networks: []net.Network{net.Network_UDP, net.Network_TCP}, TargetTag: &router.RoutingRule_Tag{Tag: "out"}, }, }, }, mocks.NewDNSClient(mockCtl), mocks.NewOutboundManager(mockCtl), nil)) lis := bufconn.Listen(1024 * 1024) bufDialer := func(context.Context, string) (net.Conn, error) { return lis.Dial() } errCh := make(chan error) // Server goroutine go func() { server := grpc.NewServer() RegisterRoutingServiceServer(server, NewRoutingServer(r, c)) errCh <- server.Serve(lis) }() // Client goroutine go func() { defer lis.Close() conn, err := grpc.DialContext( context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { errCh <- err } defer conn.Close() client := NewRoutingServiceClient(conn) testCases := []*RoutingContext{ {InboundTag: "in", OutboundTag: "out"}, {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"}, {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"}, {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"}, {Network: net.Network_UDP, Protocol: "bittorrent", OutboundTag: "blocked"}, {User: "example@v2fly.org", OutboundTag: "out"}, {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"}, } // Test simple TestRoute testSimple := func() error { for _, tc := range testCases { route, err := client.TestRoute(context.Background(), &TestRouteRequest{RoutingContext: tc}) if err != nil { return err } if r := cmp.Diff(route, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" { t.Error(r) } } return nil } // Test TestRoute with special options testOptions := func() error { sub, err := c.Subscribe() if err != nil { return err } for _, tc := range testCases { route, err := client.TestRoute(context.Background(), &TestRouteRequest{ RoutingContext: tc, FieldSelectors: []string{"ip", "port", "domain", "outbound"}, PublishResult: true, }) if err != nil { return err } stat := &RoutingContext{ // Only a subset of stats is retrieved SourceIPs: tc.SourceIPs, TargetIPs: tc.TargetIPs, SourcePort: tc.SourcePort, TargetPort: tc.TargetPort, TargetDomain: tc.TargetDomain, OutboundGroupTags: tc.OutboundGroupTags, OutboundTag: tc.OutboundTag, } if r := cmp.Diff(route, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" { t.Error(r) } select { // Check that routing result has been published to statistics channel case msg, received := <-sub: if route, ok := msg.(routing.Route); received && ok { if r := cmp.Diff(AsProtobufMessage(nil)(route), tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" { t.Error(r) } } else { t.Error("unexpected failure in receiving published routing result for testcase", tc) } case <-time.After(100 * time.Millisecond): t.Error("unexpected failure in receiving published routing result", tc) } } return nil } if err := testSimple(); err != nil { errCh <- err } if err := testOptions(); err != nil { errCh <- err } errCh <- nil // Client passed all tests successfully }() // Wait for goroutines to complete select { case <-time.After(2 * time.Second): t.Fatal("Test timeout after 2s") case err := <-errCh: if err != nil { t.Fatal(err) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/command.pb.go
app/router/command/command.pb.go
package command import ( net "github.com/v2fly/v2ray-core/v5/common/net" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // RoutingContext is the context with information relative to routing process. // It conforms to the structure of v2ray.core.features.routing.Context and // v2ray.core.features.routing.Route. type RoutingContext struct { state protoimpl.MessageState `protogen:"open.v1"` InboundTag string `protobuf:"bytes,1,opt,name=InboundTag,proto3" json:"InboundTag,omitempty"` Network net.Network `protobuf:"varint,2,opt,name=Network,proto3,enum=v2ray.core.common.net.Network" json:"Network,omitempty"` SourceIPs [][]byte `protobuf:"bytes,3,rep,name=SourceIPs,proto3" json:"SourceIPs,omitempty"` TargetIPs [][]byte `protobuf:"bytes,4,rep,name=TargetIPs,proto3" json:"TargetIPs,omitempty"` SourcePort uint32 `protobuf:"varint,5,opt,name=SourcePort,proto3" json:"SourcePort,omitempty"` TargetPort uint32 `protobuf:"varint,6,opt,name=TargetPort,proto3" json:"TargetPort,omitempty"` TargetDomain string `protobuf:"bytes,7,opt,name=TargetDomain,proto3" json:"TargetDomain,omitempty"` Protocol string `protobuf:"bytes,8,opt,name=Protocol,proto3" json:"Protocol,omitempty"` User string `protobuf:"bytes,9,opt,name=User,proto3" json:"User,omitempty"` Attributes map[string]string `protobuf:"bytes,10,rep,name=Attributes,proto3" json:"Attributes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` OutboundGroupTags []string `protobuf:"bytes,11,rep,name=OutboundGroupTags,proto3" json:"OutboundGroupTags,omitempty"` OutboundTag string `protobuf:"bytes,12,opt,name=OutboundTag,proto3" json:"OutboundTag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RoutingContext) Reset() { *x = RoutingContext{} mi := &file_app_router_command_command_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RoutingContext) String() string { return protoimpl.X.MessageStringOf(x) } func (*RoutingContext) ProtoMessage() {} func (x *RoutingContext) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RoutingContext.ProtoReflect.Descriptor instead. func (*RoutingContext) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{0} } func (x *RoutingContext) GetInboundTag() string { if x != nil { return x.InboundTag } return "" } func (x *RoutingContext) GetNetwork() net.Network { if x != nil { return x.Network } return net.Network(0) } func (x *RoutingContext) GetSourceIPs() [][]byte { if x != nil { return x.SourceIPs } return nil } func (x *RoutingContext) GetTargetIPs() [][]byte { if x != nil { return x.TargetIPs } return nil } func (x *RoutingContext) GetSourcePort() uint32 { if x != nil { return x.SourcePort } return 0 } func (x *RoutingContext) GetTargetPort() uint32 { if x != nil { return x.TargetPort } return 0 } func (x *RoutingContext) GetTargetDomain() string { if x != nil { return x.TargetDomain } return "" } func (x *RoutingContext) GetProtocol() string { if x != nil { return x.Protocol } return "" } func (x *RoutingContext) GetUser() string { if x != nil { return x.User } return "" } func (x *RoutingContext) GetAttributes() map[string]string { if x != nil { return x.Attributes } return nil } func (x *RoutingContext) GetOutboundGroupTags() []string { if x != nil { return x.OutboundGroupTags } return nil } func (x *RoutingContext) GetOutboundTag() string { if x != nil { return x.OutboundTag } return "" } // SubscribeRoutingStatsRequest subscribes to routing statistics channel if // opened by v2ray-core. // * FieldSelectors selects a subset of fields in routing statistics to return. // Valid selectors: // - inbound: Selects connection's inbound tag. // - network: Selects connection's network. // - ip: Equivalent as "ip_source" and "ip_target", selects both source and // target IP. // - port: Equivalent as "port_source" and "port_target", selects both source // and target port. // - domain: Selects target domain. // - protocol: Select connection's protocol. // - user: Select connection's inbound user email. // - attributes: Select connection's additional attributes. // - outbound: Equivalent as "outbound" and "outbound_group", select both // outbound tag and outbound group tags. // // * If FieldSelectors is left empty, all fields will be returned. type SubscribeRoutingStatsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` FieldSelectors []string `protobuf:"bytes,1,rep,name=FieldSelectors,proto3" json:"FieldSelectors,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SubscribeRoutingStatsRequest) Reset() { *x = SubscribeRoutingStatsRequest{} mi := &file_app_router_command_command_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SubscribeRoutingStatsRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*SubscribeRoutingStatsRequest) ProtoMessage() {} func (x *SubscribeRoutingStatsRequest) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SubscribeRoutingStatsRequest.ProtoReflect.Descriptor instead. func (*SubscribeRoutingStatsRequest) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{1} } func (x *SubscribeRoutingStatsRequest) GetFieldSelectors() []string { if x != nil { return x.FieldSelectors } return nil } // TestRouteRequest manually tests a routing result according to the routing // context message. // * RoutingContext is the routing message without outbound information. // * FieldSelectors selects the fields to return in the routing result. All // fields are returned if left empty. // * PublishResult broadcasts the routing result to routing statistics channel // if set true. type TestRouteRequest struct { state protoimpl.MessageState `protogen:"open.v1"` RoutingContext *RoutingContext `protobuf:"bytes,1,opt,name=RoutingContext,proto3" json:"RoutingContext,omitempty"` FieldSelectors []string `protobuf:"bytes,2,rep,name=FieldSelectors,proto3" json:"FieldSelectors,omitempty"` PublishResult bool `protobuf:"varint,3,opt,name=PublishResult,proto3" json:"PublishResult,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *TestRouteRequest) Reset() { *x = TestRouteRequest{} mi := &file_app_router_command_command_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *TestRouteRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TestRouteRequest) ProtoMessage() {} func (x *TestRouteRequest) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TestRouteRequest.ProtoReflect.Descriptor instead. func (*TestRouteRequest) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{2} } func (x *TestRouteRequest) GetRoutingContext() *RoutingContext { if x != nil { return x.RoutingContext } return nil } func (x *TestRouteRequest) GetFieldSelectors() []string { if x != nil { return x.FieldSelectors } return nil } func (x *TestRouteRequest) GetPublishResult() bool { if x != nil { return x.PublishResult } return false } type PrincipleTargetInfo struct { state protoimpl.MessageState `protogen:"open.v1"` Tag []string `protobuf:"bytes,1,rep,name=tag,proto3" json:"tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PrincipleTargetInfo) Reset() { *x = PrincipleTargetInfo{} mi := &file_app_router_command_command_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PrincipleTargetInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*PrincipleTargetInfo) ProtoMessage() {} func (x *PrincipleTargetInfo) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PrincipleTargetInfo.ProtoReflect.Descriptor instead. func (*PrincipleTargetInfo) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{3} } func (x *PrincipleTargetInfo) GetTag() []string { if x != nil { return x.Tag } return nil } type OverrideInfo struct { state protoimpl.MessageState `protogen:"open.v1"` Target string `protobuf:"bytes,2,opt,name=target,proto3" json:"target,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *OverrideInfo) Reset() { *x = OverrideInfo{} mi := &file_app_router_command_command_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *OverrideInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*OverrideInfo) ProtoMessage() {} func (x *OverrideInfo) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OverrideInfo.ProtoReflect.Descriptor instead. func (*OverrideInfo) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{4} } func (x *OverrideInfo) GetTarget() string { if x != nil { return x.Target } return "" } type BalancerMsg struct { state protoimpl.MessageState `protogen:"open.v1"` Override *OverrideInfo `protobuf:"bytes,5,opt,name=override,proto3" json:"override,omitempty"` PrincipleTarget *PrincipleTargetInfo `protobuf:"bytes,6,opt,name=principle_target,json=principleTarget,proto3" json:"principle_target,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *BalancerMsg) Reset() { *x = BalancerMsg{} mi := &file_app_router_command_command_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *BalancerMsg) String() string { return protoimpl.X.MessageStringOf(x) } func (*BalancerMsg) ProtoMessage() {} func (x *BalancerMsg) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BalancerMsg.ProtoReflect.Descriptor instead. func (*BalancerMsg) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{5} } func (x *BalancerMsg) GetOverride() *OverrideInfo { if x != nil { return x.Override } return nil } func (x *BalancerMsg) GetPrincipleTarget() *PrincipleTargetInfo { if x != nil { return x.PrincipleTarget } return nil } type GetBalancerInfoRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBalancerInfoRequest) Reset() { *x = GetBalancerInfoRequest{} mi := &file_app_router_command_command_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBalancerInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBalancerInfoRequest) ProtoMessage() {} func (x *GetBalancerInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBalancerInfoRequest.ProtoReflect.Descriptor instead. func (*GetBalancerInfoRequest) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{6} } func (x *GetBalancerInfoRequest) GetTag() string { if x != nil { return x.Tag } return "" } type GetBalancerInfoResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Balancer *BalancerMsg `protobuf:"bytes,1,opt,name=balancer,proto3" json:"balancer,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GetBalancerInfoResponse) Reset() { *x = GetBalancerInfoResponse{} mi := &file_app_router_command_command_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GetBalancerInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetBalancerInfoResponse) ProtoMessage() {} func (x *GetBalancerInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetBalancerInfoResponse.ProtoReflect.Descriptor instead. func (*GetBalancerInfoResponse) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{7} } func (x *GetBalancerInfoResponse) GetBalancer() *BalancerMsg { if x != nil { return x.Balancer } return nil } type OverrideBalancerTargetRequest struct { state protoimpl.MessageState `protogen:"open.v1"` BalancerTag string `protobuf:"bytes,1,opt,name=balancerTag,proto3" json:"balancerTag,omitempty"` Target string `protobuf:"bytes,2,opt,name=target,proto3" json:"target,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *OverrideBalancerTargetRequest) Reset() { *x = OverrideBalancerTargetRequest{} mi := &file_app_router_command_command_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *OverrideBalancerTargetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*OverrideBalancerTargetRequest) ProtoMessage() {} func (x *OverrideBalancerTargetRequest) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OverrideBalancerTargetRequest.ProtoReflect.Descriptor instead. func (*OverrideBalancerTargetRequest) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{8} } func (x *OverrideBalancerTargetRequest) GetBalancerTag() string { if x != nil { return x.BalancerTag } return "" } func (x *OverrideBalancerTargetRequest) GetTarget() string { if x != nil { return x.Target } return "" } type OverrideBalancerTargetResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *OverrideBalancerTargetResponse) Reset() { *x = OverrideBalancerTargetResponse{} mi := &file_app_router_command_command_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *OverrideBalancerTargetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*OverrideBalancerTargetResponse) ProtoMessage() {} func (x *OverrideBalancerTargetResponse) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OverrideBalancerTargetResponse.ProtoReflect.Descriptor instead. func (*OverrideBalancerTargetResponse) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{9} } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_router_command_command_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_router_command_command_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_router_command_command_proto_rawDescGZIP(), []int{10} } var File_app_router_command_command_proto protoreflect.FileDescriptor const file_app_router_command_command_proto_rawDesc = "" + "\n" + " app/router/command/command.proto\x12\x1dv2ray.core.app.router.command\x1a common/protoext/extensions.proto\x1a\x18common/net/network.proto\"\xa8\x04\n" + "\x0eRoutingContext\x12\x1e\n" + "\n" + "InboundTag\x18\x01 \x01(\tR\n" + "InboundTag\x128\n" + "\aNetwork\x18\x02 \x01(\x0e2\x1e.v2ray.core.common.net.NetworkR\aNetwork\x12\x1c\n" + "\tSourceIPs\x18\x03 \x03(\fR\tSourceIPs\x12\x1c\n" + "\tTargetIPs\x18\x04 \x03(\fR\tTargetIPs\x12\x1e\n" + "\n" + "SourcePort\x18\x05 \x01(\rR\n" + "SourcePort\x12\x1e\n" + "\n" + "TargetPort\x18\x06 \x01(\rR\n" + "TargetPort\x12\"\n" + "\fTargetDomain\x18\a \x01(\tR\fTargetDomain\x12\x1a\n" + "\bProtocol\x18\b \x01(\tR\bProtocol\x12\x12\n" + "\x04User\x18\t \x01(\tR\x04User\x12]\n" + "\n" + "Attributes\x18\n" + " \x03(\v2=.v2ray.core.app.router.command.RoutingContext.AttributesEntryR\n" + "Attributes\x12,\n" + "\x11OutboundGroupTags\x18\v \x03(\tR\x11OutboundGroupTags\x12 \n" + "\vOutboundTag\x18\f \x01(\tR\vOutboundTag\x1a=\n" + "\x0fAttributesEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"F\n" + "\x1cSubscribeRoutingStatsRequest\x12&\n" + "\x0eFieldSelectors\x18\x01 \x03(\tR\x0eFieldSelectors\"\xb7\x01\n" + "\x10TestRouteRequest\x12U\n" + "\x0eRoutingContext\x18\x01 \x01(\v2-.v2ray.core.app.router.command.RoutingContextR\x0eRoutingContext\x12&\n" + "\x0eFieldSelectors\x18\x02 \x03(\tR\x0eFieldSelectors\x12$\n" + "\rPublishResult\x18\x03 \x01(\bR\rPublishResult\"'\n" + "\x13PrincipleTargetInfo\x12\x10\n" + "\x03tag\x18\x01 \x03(\tR\x03tag\"&\n" + "\fOverrideInfo\x12\x16\n" + "\x06target\x18\x02 \x01(\tR\x06target\"\xb5\x01\n" + "\vBalancerMsg\x12G\n" + "\boverride\x18\x05 \x01(\v2+.v2ray.core.app.router.command.OverrideInfoR\boverride\x12]\n" + "\x10principle_target\x18\x06 \x01(\v22.v2ray.core.app.router.command.PrincipleTargetInfoR\x0fprincipleTarget\"*\n" + "\x16GetBalancerInfoRequest\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\"a\n" + "\x17GetBalancerInfoResponse\x12F\n" + "\bbalancer\x18\x01 \x01(\v2*.v2ray.core.app.router.command.BalancerMsgR\bbalancer\"Y\n" + "\x1dOverrideBalancerTargetRequest\x12 \n" + "\vbalancerTag\x18\x01 \x01(\tR\vbalancerTag\x12\x16\n" + "\x06target\x18\x02 \x01(\tR\x06target\" \n" + "\x1eOverrideBalancerTargetResponse\"#\n" + "\x06Config:\x19\x82\xb5\x18\x15\n" + "\vgrpcservice\x12\x06router2\xa8\x04\n" + "\x0eRoutingService\x12\x87\x01\n" + "\x15SubscribeRoutingStats\x12;.v2ray.core.app.router.command.SubscribeRoutingStatsRequest\x1a-.v2ray.core.app.router.command.RoutingContext\"\x000\x01\x12m\n" + "\tTestRoute\x12/.v2ray.core.app.router.command.TestRouteRequest\x1a-.v2ray.core.app.router.command.RoutingContext\"\x00\x12\x82\x01\n" + "\x0fGetBalancerInfo\x125.v2ray.core.app.router.command.GetBalancerInfoRequest\x1a6.v2ray.core.app.router.command.GetBalancerInfoResponse\"\x00\x12\x97\x01\n" + "\x16OverrideBalancerTarget\x12<.v2ray.core.app.router.command.OverrideBalancerTargetRequest\x1a=.v2ray.core.app.router.command.OverrideBalancerTargetResponse\"\x00Bx\n" + "!com.v2ray.core.app.router.commandP\x01Z1github.com/v2fly/v2ray-core/v5/app/router/command\xaa\x02\x1dV2Ray.Core.App.Router.Commandb\x06proto3" var ( file_app_router_command_command_proto_rawDescOnce sync.Once file_app_router_command_command_proto_rawDescData []byte ) func file_app_router_command_command_proto_rawDescGZIP() []byte { file_app_router_command_command_proto_rawDescOnce.Do(func() { file_app_router_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_router_command_command_proto_rawDesc), len(file_app_router_command_command_proto_rawDesc))) }) return file_app_router_command_command_proto_rawDescData } var file_app_router_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 12) var file_app_router_command_command_proto_goTypes = []any{ (*RoutingContext)(nil), // 0: v2ray.core.app.router.command.RoutingContext (*SubscribeRoutingStatsRequest)(nil), // 1: v2ray.core.app.router.command.SubscribeRoutingStatsRequest (*TestRouteRequest)(nil), // 2: v2ray.core.app.router.command.TestRouteRequest (*PrincipleTargetInfo)(nil), // 3: v2ray.core.app.router.command.PrincipleTargetInfo (*OverrideInfo)(nil), // 4: v2ray.core.app.router.command.OverrideInfo (*BalancerMsg)(nil), // 5: v2ray.core.app.router.command.BalancerMsg (*GetBalancerInfoRequest)(nil), // 6: v2ray.core.app.router.command.GetBalancerInfoRequest (*GetBalancerInfoResponse)(nil), // 7: v2ray.core.app.router.command.GetBalancerInfoResponse (*OverrideBalancerTargetRequest)(nil), // 8: v2ray.core.app.router.command.OverrideBalancerTargetRequest (*OverrideBalancerTargetResponse)(nil), // 9: v2ray.core.app.router.command.OverrideBalancerTargetResponse (*Config)(nil), // 10: v2ray.core.app.router.command.Config nil, // 11: v2ray.core.app.router.command.RoutingContext.AttributesEntry (net.Network)(0), // 12: v2ray.core.common.net.Network } var file_app_router_command_command_proto_depIdxs = []int32{ 12, // 0: v2ray.core.app.router.command.RoutingContext.Network:type_name -> v2ray.core.common.net.Network 11, // 1: v2ray.core.app.router.command.RoutingContext.Attributes:type_name -> v2ray.core.app.router.command.RoutingContext.AttributesEntry 0, // 2: v2ray.core.app.router.command.TestRouteRequest.RoutingContext:type_name -> v2ray.core.app.router.command.RoutingContext 4, // 3: v2ray.core.app.router.command.BalancerMsg.override:type_name -> v2ray.core.app.router.command.OverrideInfo 3, // 4: v2ray.core.app.router.command.BalancerMsg.principle_target:type_name -> v2ray.core.app.router.command.PrincipleTargetInfo 5, // 5: v2ray.core.app.router.command.GetBalancerInfoResponse.balancer:type_name -> v2ray.core.app.router.command.BalancerMsg 1, // 6: v2ray.core.app.router.command.RoutingService.SubscribeRoutingStats:input_type -> v2ray.core.app.router.command.SubscribeRoutingStatsRequest 2, // 7: v2ray.core.app.router.command.RoutingService.TestRoute:input_type -> v2ray.core.app.router.command.TestRouteRequest 6, // 8: v2ray.core.app.router.command.RoutingService.GetBalancerInfo:input_type -> v2ray.core.app.router.command.GetBalancerInfoRequest 8, // 9: v2ray.core.app.router.command.RoutingService.OverrideBalancerTarget:input_type -> v2ray.core.app.router.command.OverrideBalancerTargetRequest 0, // 10: v2ray.core.app.router.command.RoutingService.SubscribeRoutingStats:output_type -> v2ray.core.app.router.command.RoutingContext 0, // 11: v2ray.core.app.router.command.RoutingService.TestRoute:output_type -> v2ray.core.app.router.command.RoutingContext 7, // 12: v2ray.core.app.router.command.RoutingService.GetBalancerInfo:output_type -> v2ray.core.app.router.command.GetBalancerInfoResponse 9, // 13: v2ray.core.app.router.command.RoutingService.OverrideBalancerTarget:output_type -> v2ray.core.app.router.command.OverrideBalancerTargetResponse 10, // [10:14] is the sub-list for method output_type 6, // [6:10] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_app_router_command_command_proto_init() } func file_app_router_command_command_proto_init() { if File_app_router_command_command_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_router_command_command_proto_rawDesc), len(file_app_router_command_command_proto_rawDesc)), NumEnums: 0, NumMessages: 12, NumExtensions: 0, NumServices: 1, }, GoTypes: file_app_router_command_command_proto_goTypes, DependencyIndexes: file_app_router_command_command_proto_depIdxs, MessageInfos: file_app_router_command_command_proto_msgTypes, }.Build() File_app_router_command_command_proto = out.File file_app_router_command_command_proto_goTypes = nil file_app_router_command_command_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/errors.generated.go
app/router/command/errors.generated.go
package command import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/config.go
app/router/command/config.go
package command import ( "strings" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/features/routing" ) // routingContext is an wrapper of protobuf RoutingContext as implementation of routing.Context and routing.Route. type routingContext struct { *RoutingContext } func (c routingContext) GetSourceIPs() []net.IP { return mapBytesToIPs(c.RoutingContext.GetSourceIPs()) } func (c routingContext) GetSourcePort() net.Port { return net.Port(c.RoutingContext.GetSourcePort()) } func (c routingContext) GetTargetIPs() []net.IP { return mapBytesToIPs(c.RoutingContext.GetTargetIPs()) } func (c routingContext) GetTargetPort() net.Port { return net.Port(c.RoutingContext.GetTargetPort()) } // GetSkipDNSResolve is a mock implementation here to match the interface, // SkipDNSResolve is set from dns module, no use if coming from a protobuf object? // TODO: please confirm @Vigilans func (c routingContext) GetSkipDNSResolve() bool { return false } // AsRoutingContext converts a protobuf RoutingContext into an implementation of routing.Context. func AsRoutingContext(r *RoutingContext) routing.Context { return routingContext{r} } // AsRoutingRoute converts a protobuf RoutingContext into an implementation of routing.Route. func AsRoutingRoute(r *RoutingContext) routing.Route { return routingContext{r} } var fieldMap = map[string]func(*RoutingContext, routing.Route){ "inbound": func(s *RoutingContext, r routing.Route) { s.InboundTag = r.GetInboundTag() }, "network": func(s *RoutingContext, r routing.Route) { s.Network = r.GetNetwork() }, "ip_source": func(s *RoutingContext, r routing.Route) { s.SourceIPs = mapIPsToBytes(r.GetSourceIPs()) }, "ip_target": func(s *RoutingContext, r routing.Route) { s.TargetIPs = mapIPsToBytes(r.GetTargetIPs()) }, "port_source": func(s *RoutingContext, r routing.Route) { s.SourcePort = uint32(r.GetSourcePort()) }, "port_target": func(s *RoutingContext, r routing.Route) { s.TargetPort = uint32(r.GetTargetPort()) }, "domain": func(s *RoutingContext, r routing.Route) { s.TargetDomain = r.GetTargetDomain() }, "protocol": func(s *RoutingContext, r routing.Route) { s.Protocol = r.GetProtocol() }, "user": func(s *RoutingContext, r routing.Route) { s.User = r.GetUser() }, "attributes": func(s *RoutingContext, r routing.Route) { s.Attributes = r.GetAttributes() }, "outbound_group": func(s *RoutingContext, r routing.Route) { s.OutboundGroupTags = r.GetOutboundGroupTags() }, "outbound": func(s *RoutingContext, r routing.Route) { s.OutboundTag = r.GetOutboundTag() }, } // AsProtobufMessage takes selectors of fields and returns a function to convert routing.Route to protobuf RoutingContext. func AsProtobufMessage(fieldSelectors []string) func(routing.Route) *RoutingContext { initializers := []func(*RoutingContext, routing.Route){} for field, init := range fieldMap { if len(fieldSelectors) == 0 { // If selectors not set, retrieve all fields initializers = append(initializers, init) continue } for _, selector := range fieldSelectors { if strings.HasPrefix(field, selector) { initializers = append(initializers, init) break } } } return func(ctx routing.Route) *RoutingContext { message := new(RoutingContext) for _, init := range initializers { init(message, ctx) } return message } } func mapBytesToIPs(bytes [][]byte) []net.IP { var ips []net.IP for _, rawIP := range bytes { ips = append(ips, net.IP(rawIP)) } return ips } func mapIPsToBytes(ips []net.IP) [][]byte { var bytes [][]byte for _, ip := range ips { bytes = append(bytes, []byte(ip)) } return bytes }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/command_grpc.pb.go
app/router/command/command_grpc.pb.go
package command import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( RoutingService_SubscribeRoutingStats_FullMethodName = "/v2ray.core.app.router.command.RoutingService/SubscribeRoutingStats" RoutingService_TestRoute_FullMethodName = "/v2ray.core.app.router.command.RoutingService/TestRoute" RoutingService_GetBalancerInfo_FullMethodName = "/v2ray.core.app.router.command.RoutingService/GetBalancerInfo" RoutingService_OverrideBalancerTarget_FullMethodName = "/v2ray.core.app.router.command.RoutingService/OverrideBalancerTarget" ) // RoutingServiceClient is the client API for RoutingService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type RoutingServiceClient interface { SubscribeRoutingStats(ctx context.Context, in *SubscribeRoutingStatsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[RoutingContext], error) TestRoute(ctx context.Context, in *TestRouteRequest, opts ...grpc.CallOption) (*RoutingContext, error) GetBalancerInfo(ctx context.Context, in *GetBalancerInfoRequest, opts ...grpc.CallOption) (*GetBalancerInfoResponse, error) OverrideBalancerTarget(ctx context.Context, in *OverrideBalancerTargetRequest, opts ...grpc.CallOption) (*OverrideBalancerTargetResponse, error) } type routingServiceClient struct { cc grpc.ClientConnInterface } func NewRoutingServiceClient(cc grpc.ClientConnInterface) RoutingServiceClient { return &routingServiceClient{cc} } func (c *routingServiceClient) SubscribeRoutingStats(ctx context.Context, in *SubscribeRoutingStatsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[RoutingContext], error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) stream, err := c.cc.NewStream(ctx, &RoutingService_ServiceDesc.Streams[0], RoutingService_SubscribeRoutingStats_FullMethodName, cOpts...) if err != nil { return nil, err } x := &grpc.GenericClientStream[SubscribeRoutingStatsRequest, RoutingContext]{ClientStream: stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } // This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. type RoutingService_SubscribeRoutingStatsClient = grpc.ServerStreamingClient[RoutingContext] func (c *routingServiceClient) TestRoute(ctx context.Context, in *TestRouteRequest, opts ...grpc.CallOption) (*RoutingContext, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(RoutingContext) err := c.cc.Invoke(ctx, RoutingService_TestRoute_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *routingServiceClient) GetBalancerInfo(ctx context.Context, in *GetBalancerInfoRequest, opts ...grpc.CallOption) (*GetBalancerInfoResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetBalancerInfoResponse) err := c.cc.Invoke(ctx, RoutingService_GetBalancerInfo_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *routingServiceClient) OverrideBalancerTarget(ctx context.Context, in *OverrideBalancerTargetRequest, opts ...grpc.CallOption) (*OverrideBalancerTargetResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(OverrideBalancerTargetResponse) err := c.cc.Invoke(ctx, RoutingService_OverrideBalancerTarget_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } // RoutingServiceServer is the server API for RoutingService service. // All implementations must embed UnimplementedRoutingServiceServer // for forward compatibility. type RoutingServiceServer interface { SubscribeRoutingStats(*SubscribeRoutingStatsRequest, grpc.ServerStreamingServer[RoutingContext]) error TestRoute(context.Context, *TestRouteRequest) (*RoutingContext, error) GetBalancerInfo(context.Context, *GetBalancerInfoRequest) (*GetBalancerInfoResponse, error) OverrideBalancerTarget(context.Context, *OverrideBalancerTargetRequest) (*OverrideBalancerTargetResponse, error) mustEmbedUnimplementedRoutingServiceServer() } // UnimplementedRoutingServiceServer must be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedRoutingServiceServer struct{} func (UnimplementedRoutingServiceServer) SubscribeRoutingStats(*SubscribeRoutingStatsRequest, grpc.ServerStreamingServer[RoutingContext]) error { return status.Errorf(codes.Unimplemented, "method SubscribeRoutingStats not implemented") } func (UnimplementedRoutingServiceServer) TestRoute(context.Context, *TestRouteRequest) (*RoutingContext, error) { return nil, status.Errorf(codes.Unimplemented, "method TestRoute not implemented") } func (UnimplementedRoutingServiceServer) GetBalancerInfo(context.Context, *GetBalancerInfoRequest) (*GetBalancerInfoResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetBalancerInfo not implemented") } func (UnimplementedRoutingServiceServer) OverrideBalancerTarget(context.Context, *OverrideBalancerTargetRequest) (*OverrideBalancerTargetResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method OverrideBalancerTarget not implemented") } func (UnimplementedRoutingServiceServer) mustEmbedUnimplementedRoutingServiceServer() {} func (UnimplementedRoutingServiceServer) testEmbeddedByValue() {} // UnsafeRoutingServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to RoutingServiceServer will // result in compilation errors. type UnsafeRoutingServiceServer interface { mustEmbedUnimplementedRoutingServiceServer() } func RegisterRoutingServiceServer(s grpc.ServiceRegistrar, srv RoutingServiceServer) { // If the following call pancis, it indicates UnimplementedRoutingServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&RoutingService_ServiceDesc, srv) } func _RoutingService_SubscribeRoutingStats_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(SubscribeRoutingStatsRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(RoutingServiceServer).SubscribeRoutingStats(m, &grpc.GenericServerStream[SubscribeRoutingStatsRequest, RoutingContext]{ServerStream: stream}) } // This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. type RoutingService_SubscribeRoutingStatsServer = grpc.ServerStreamingServer[RoutingContext] func _RoutingService_TestRoute_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(TestRouteRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(RoutingServiceServer).TestRoute(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: RoutingService_TestRoute_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(RoutingServiceServer).TestRoute(ctx, req.(*TestRouteRequest)) } return interceptor(ctx, in, info, handler) } func _RoutingService_GetBalancerInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetBalancerInfoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(RoutingServiceServer).GetBalancerInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: RoutingService_GetBalancerInfo_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(RoutingServiceServer).GetBalancerInfo(ctx, req.(*GetBalancerInfoRequest)) } return interceptor(ctx, in, info, handler) } func _RoutingService_OverrideBalancerTarget_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(OverrideBalancerTargetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(RoutingServiceServer).OverrideBalancerTarget(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: RoutingService_OverrideBalancerTarget_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(RoutingServiceServer).OverrideBalancerTarget(ctx, req.(*OverrideBalancerTargetRequest)) } return interceptor(ctx, in, info, handler) } // RoutingService_ServiceDesc is the grpc.ServiceDesc for RoutingService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var RoutingService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "v2ray.core.app.router.command.RoutingService", HandlerType: (*RoutingServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "TestRoute", Handler: _RoutingService_TestRoute_Handler, }, { MethodName: "GetBalancerInfo", Handler: _RoutingService_GetBalancerInfo_Handler, }, { MethodName: "OverrideBalancerTarget", Handler: _RoutingService_OverrideBalancerTarget_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "SubscribeRoutingStats", Handler: _RoutingService_SubscribeRoutingStats_Handler, ServerStreams: true, }, }, Metadata: "app/router/command/command.proto", }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/command/command.go
app/router/command/command.go
package command //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "time" "google.golang.org/grpc" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/features/stats" ) // routingServer is an implementation of RoutingService. type routingServer struct { router routing.Router routingStats stats.Channel } func (s *routingServer) GetBalancerInfo(ctx context.Context, request *GetBalancerInfoRequest) (*GetBalancerInfoResponse, error) { var ret GetBalancerInfoResponse ret.Balancer = &BalancerMsg{} if bo, ok := s.router.(routing.BalancerOverrider); ok { { res, err := bo.GetOverrideTarget(request.GetTag()) if err != nil { return nil, err } ret.Balancer.Override = &OverrideInfo{ Target: res, } } } if pt, ok := s.router.(routing.BalancerPrincipleTarget); ok { { res, err := pt.GetPrincipleTarget(request.GetTag()) if err != nil { newError("unable to obtain principle target").Base(err).AtInfo().WriteToLog() } else { ret.Balancer.PrincipleTarget = &PrincipleTargetInfo{Tag: res} } } } return &ret, nil } func (s *routingServer) OverrideBalancerTarget(ctx context.Context, request *OverrideBalancerTargetRequest) (*OverrideBalancerTargetResponse, error) { if bo, ok := s.router.(routing.BalancerOverrider); ok { return &OverrideBalancerTargetResponse{}, bo.SetOverrideTarget(request.BalancerTag, request.Target) } return nil, newError("unsupported router implementation") } // NewRoutingServer creates a statistics service with statistics manager. func NewRoutingServer(router routing.Router, routingStats stats.Channel) RoutingServiceServer { return &routingServer{ router: router, routingStats: routingStats, } } func (s *routingServer) TestRoute(ctx context.Context, request *TestRouteRequest) (*RoutingContext, error) { if request.RoutingContext == nil { return nil, newError("Invalid routing request.") } route, err := s.router.PickRoute(AsRoutingContext(request.RoutingContext)) if err != nil { return nil, err } if request.PublishResult && s.routingStats != nil { ctx, _ := context.WithTimeout(context.Background(), 4*time.Second) // nolint: govet s.routingStats.Publish(ctx, route) } return AsProtobufMessage(request.FieldSelectors)(route), nil } func (s *routingServer) SubscribeRoutingStats(request *SubscribeRoutingStatsRequest, stream RoutingService_SubscribeRoutingStatsServer) error { if s.routingStats == nil { return newError("Routing statistics not enabled.") } genMessage := AsProtobufMessage(request.FieldSelectors) subscriber, err := stats.SubscribeRunnableChannel(s.routingStats) if err != nil { return err } defer stats.UnsubscribeClosableChannel(s.routingStats, subscriber) for { select { case value, ok := <-subscriber: if !ok { return newError("Upstream closed the subscriber channel.") } route, ok := value.(routing.Route) if !ok { return newError("Upstream sent malformed statistics.") } err := stream.Send(genMessage(route)) if err != nil { return err } case <-stream.Context().Done(): return stream.Context().Err() } } } func (s *routingServer) mustEmbedUnimplementedRoutingServiceServer() {} type service struct { v *core.Instance } func (s *service) Register(server *grpc.Server) { common.Must(s.v.RequireFeatures(func(router routing.Router, stats stats.Manager) { RegisterRoutingServiceServer(server, NewRoutingServer(router, nil)) })) } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { s := core.MustFromContext(ctx) return &service{v: s}, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/router/routercommon/common.pb.go
app/router/routercommon/common.pb.go
package routercommon import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Type of domain value. type Domain_Type int32 const ( // The value is used as is. Domain_Plain Domain_Type = 0 // The value is used as a regular expression. Domain_Regex Domain_Type = 1 // The value is a root domain. Domain_RootDomain Domain_Type = 2 // The value is a domain. Domain_Full Domain_Type = 3 ) // Enum value maps for Domain_Type. var ( Domain_Type_name = map[int32]string{ 0: "Plain", 1: "Regex", 2: "RootDomain", 3: "Full", } Domain_Type_value = map[string]int32{ "Plain": 0, "Regex": 1, "RootDomain": 2, "Full": 3, } ) func (x Domain_Type) Enum() *Domain_Type { p := new(Domain_Type) *p = x return p } func (x Domain_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Domain_Type) Descriptor() protoreflect.EnumDescriptor { return file_app_router_routercommon_common_proto_enumTypes[0].Descriptor() } func (Domain_Type) Type() protoreflect.EnumType { return &file_app_router_routercommon_common_proto_enumTypes[0] } func (x Domain_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Domain_Type.Descriptor instead. func (Domain_Type) EnumDescriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0, 0} } // Domain for routing decision. type Domain struct { state protoimpl.MessageState `protogen:"open.v1"` // Domain matching type. Type Domain_Type `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.router.routercommon.Domain_Type" json:"type,omitempty"` // Domain value. Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` // Attributes of this domain. May be used for filtering. Attribute []*Domain_Attribute `protobuf:"bytes,3,rep,name=attribute,proto3" json:"attribute,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Domain) Reset() { *x = Domain{} mi := &file_app_router_routercommon_common_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Domain) String() string { return protoimpl.X.MessageStringOf(x) } func (*Domain) ProtoMessage() {} func (x *Domain) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Domain.ProtoReflect.Descriptor instead. func (*Domain) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0} } func (x *Domain) GetType() Domain_Type { if x != nil { return x.Type } return Domain_Plain } func (x *Domain) GetValue() string { if x != nil { return x.Value } return "" } func (x *Domain) GetAttribute() []*Domain_Attribute { if x != nil { return x.Attribute } return nil } // IP for routing decision, in CIDR form. type CIDR struct { state protoimpl.MessageState `protogen:"open.v1"` // IP address, should be either 4 or 16 bytes. Ip []byte `protobuf:"bytes,1,opt,name=ip,proto3" json:"ip,omitempty"` // Number of leading ones in the network mask. Prefix uint32 `protobuf:"varint,2,opt,name=prefix,proto3" json:"prefix,omitempty"` IpAddr string `protobuf:"bytes,68000,opt,name=ip_addr,json=ipAddr,proto3" json:"ip_addr,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CIDR) Reset() { *x = CIDR{} mi := &file_app_router_routercommon_common_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *CIDR) String() string { return protoimpl.X.MessageStringOf(x) } func (*CIDR) ProtoMessage() {} func (x *CIDR) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CIDR.ProtoReflect.Descriptor instead. func (*CIDR) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{1} } func (x *CIDR) GetIp() []byte { if x != nil { return x.Ip } return nil } func (x *CIDR) GetPrefix() uint32 { if x != nil { return x.Prefix } return 0 } func (x *CIDR) GetIpAddr() string { if x != nil { return x.IpAddr } return "" } type GeoIP struct { state protoimpl.MessageState `protogen:"open.v1"` CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"` Cidr []*CIDR `protobuf:"bytes,2,rep,name=cidr,proto3" json:"cidr,omitempty"` InverseMatch bool `protobuf:"varint,3,opt,name=inverse_match,json=inverseMatch,proto3" json:"inverse_match,omitempty"` // resource_hash instruct simplified config converter to load domain from geo file. ResourceHash []byte `protobuf:"bytes,4,opt,name=resource_hash,json=resourceHash,proto3" json:"resource_hash,omitempty"` Code string `protobuf:"bytes,5,opt,name=code,proto3" json:"code,omitempty"` FilePath string `protobuf:"bytes,68000,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GeoIP) Reset() { *x = GeoIP{} mi := &file_app_router_routercommon_common_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GeoIP) String() string { return protoimpl.X.MessageStringOf(x) } func (*GeoIP) ProtoMessage() {} func (x *GeoIP) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GeoIP.ProtoReflect.Descriptor instead. func (*GeoIP) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{2} } func (x *GeoIP) GetCountryCode() string { if x != nil { return x.CountryCode } return "" } func (x *GeoIP) GetCidr() []*CIDR { if x != nil { return x.Cidr } return nil } func (x *GeoIP) GetInverseMatch() bool { if x != nil { return x.InverseMatch } return false } func (x *GeoIP) GetResourceHash() []byte { if x != nil { return x.ResourceHash } return nil } func (x *GeoIP) GetCode() string { if x != nil { return x.Code } return "" } func (x *GeoIP) GetFilePath() string { if x != nil { return x.FilePath } return "" } type GeoIPList struct { state protoimpl.MessageState `protogen:"open.v1"` Entry []*GeoIP `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GeoIPList) Reset() { *x = GeoIPList{} mi := &file_app_router_routercommon_common_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GeoIPList) String() string { return protoimpl.X.MessageStringOf(x) } func (*GeoIPList) ProtoMessage() {} func (x *GeoIPList) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GeoIPList.ProtoReflect.Descriptor instead. func (*GeoIPList) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{3} } func (x *GeoIPList) GetEntry() []*GeoIP { if x != nil { return x.Entry } return nil } type GeoSite struct { state protoimpl.MessageState `protogen:"open.v1"` CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"` Domain []*Domain `protobuf:"bytes,2,rep,name=domain,proto3" json:"domain,omitempty"` // resource_hash instruct simplified config converter to load domain from geo file. ResourceHash []byte `protobuf:"bytes,3,opt,name=resource_hash,json=resourceHash,proto3" json:"resource_hash,omitempty"` Code string `protobuf:"bytes,4,opt,name=code,proto3" json:"code,omitempty"` FilePath string `protobuf:"bytes,68000,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GeoSite) Reset() { *x = GeoSite{} mi := &file_app_router_routercommon_common_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GeoSite) String() string { return protoimpl.X.MessageStringOf(x) } func (*GeoSite) ProtoMessage() {} func (x *GeoSite) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GeoSite.ProtoReflect.Descriptor instead. func (*GeoSite) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{4} } func (x *GeoSite) GetCountryCode() string { if x != nil { return x.CountryCode } return "" } func (x *GeoSite) GetDomain() []*Domain { if x != nil { return x.Domain } return nil } func (x *GeoSite) GetResourceHash() []byte { if x != nil { return x.ResourceHash } return nil } func (x *GeoSite) GetCode() string { if x != nil { return x.Code } return "" } func (x *GeoSite) GetFilePath() string { if x != nil { return x.FilePath } return "" } type GeoSiteList struct { state protoimpl.MessageState `protogen:"open.v1"` Entry []*GeoSite `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GeoSiteList) Reset() { *x = GeoSiteList{} mi := &file_app_router_routercommon_common_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GeoSiteList) String() string { return protoimpl.X.MessageStringOf(x) } func (*GeoSiteList) ProtoMessage() {} func (x *GeoSiteList) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GeoSiteList.ProtoReflect.Descriptor instead. func (*GeoSiteList) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{5} } func (x *GeoSiteList) GetEntry() []*GeoSite { if x != nil { return x.Entry } return nil } type Domain_Attribute struct { state protoimpl.MessageState `protogen:"open.v1"` Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Types that are valid to be assigned to TypedValue: // // *Domain_Attribute_BoolValue // *Domain_Attribute_IntValue TypedValue isDomain_Attribute_TypedValue `protobuf_oneof:"typed_value"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Domain_Attribute) Reset() { *x = Domain_Attribute{} mi := &file_app_router_routercommon_common_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Domain_Attribute) String() string { return protoimpl.X.MessageStringOf(x) } func (*Domain_Attribute) ProtoMessage() {} func (x *Domain_Attribute) ProtoReflect() protoreflect.Message { mi := &file_app_router_routercommon_common_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Domain_Attribute.ProtoReflect.Descriptor instead. func (*Domain_Attribute) Descriptor() ([]byte, []int) { return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0, 0} } func (x *Domain_Attribute) GetKey() string { if x != nil { return x.Key } return "" } func (x *Domain_Attribute) GetTypedValue() isDomain_Attribute_TypedValue { if x != nil { return x.TypedValue } return nil } func (x *Domain_Attribute) GetBoolValue() bool { if x != nil { if x, ok := x.TypedValue.(*Domain_Attribute_BoolValue); ok { return x.BoolValue } } return false } func (x *Domain_Attribute) GetIntValue() int64 { if x != nil { if x, ok := x.TypedValue.(*Domain_Attribute_IntValue); ok { return x.IntValue } } return 0 } type isDomain_Attribute_TypedValue interface { isDomain_Attribute_TypedValue() } type Domain_Attribute_BoolValue struct { BoolValue bool `protobuf:"varint,2,opt,name=bool_value,json=boolValue,proto3,oneof"` } type Domain_Attribute_IntValue struct { IntValue int64 `protobuf:"varint,3,opt,name=int_value,json=intValue,proto3,oneof"` } func (*Domain_Attribute_BoolValue) isDomain_Attribute_TypedValue() {} func (*Domain_Attribute_IntValue) isDomain_Attribute_TypedValue() {} var File_app_router_routercommon_common_proto protoreflect.FileDescriptor const file_app_router_routercommon_common_proto_rawDesc = "" + "\n" + "$app/router/routercommon/common.proto\x12\"v2ray.core.app.router.routercommon\x1a common/protoext/extensions.proto\"\xdd\x02\n" + "\x06Domain\x12C\n" + "\x04type\x18\x01 \x01(\x0e2/.v2ray.core.app.router.routercommon.Domain.TypeR\x04type\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value\x12R\n" + "\tattribute\x18\x03 \x03(\v24.v2ray.core.app.router.routercommon.Domain.AttributeR\tattribute\x1al\n" + "\tAttribute\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x1f\n" + "\n" + "bool_value\x18\x02 \x01(\bH\x00R\tboolValue\x12\x1d\n" + "\tint_value\x18\x03 \x01(\x03H\x00R\bintValueB\r\n" + "\vtyped_value\"6\n" + "\x04Type\x12\t\n" + "\x05Plain\x10\x00\x12\t\n" + "\x05Regex\x10\x01\x12\x0e\n" + "\n" + "RootDomain\x10\x02\x12\b\n" + "\x04Full\x10\x03\"S\n" + "\x04CIDR\x12\x0e\n" + "\x02ip\x18\x01 \x01(\fR\x02ip\x12\x16\n" + "\x06prefix\x18\x02 \x01(\rR\x06prefix\x12#\n" + "\aip_addr\x18\xa0\x93\x04 \x01(\tB\b\x82\xb5\x18\x04:\x02ipR\x06ipAddr\"\xfa\x01\n" + "\x05GeoIP\x12!\n" + "\fcountry_code\x18\x01 \x01(\tR\vcountryCode\x12<\n" + "\x04cidr\x18\x02 \x03(\v2(.v2ray.core.app.router.routercommon.CIDRR\x04cidr\x12#\n" + "\rinverse_match\x18\x03 \x01(\bR\finverseMatch\x12#\n" + "\rresource_hash\x18\x04 \x01(\fR\fresourceHash\x12\x12\n" + "\x04code\x18\x05 \x01(\tR\x04code\x122\n" + "\tfile_path\x18\xa0\x93\x04 \x01(\tB\x13\x82\xb5\x18\x0f2\rresource_hashR\bfilePath\"L\n" + "\tGeoIPList\x12?\n" + "\x05entry\x18\x01 \x03(\v2).v2ray.core.app.router.routercommon.GeoIPR\x05entry\"\xdd\x01\n" + "\aGeoSite\x12!\n" + "\fcountry_code\x18\x01 \x01(\tR\vcountryCode\x12B\n" + "\x06domain\x18\x02 \x03(\v2*.v2ray.core.app.router.routercommon.DomainR\x06domain\x12#\n" + "\rresource_hash\x18\x03 \x01(\fR\fresourceHash\x12\x12\n" + "\x04code\x18\x04 \x01(\tR\x04code\x122\n" + "\tfile_path\x18\xa0\x93\x04 \x01(\tB\x13\x82\xb5\x18\x0f2\rresource_hashR\bfilePath\"P\n" + "\vGeoSiteList\x12A\n" + "\x05entry\x18\x01 \x03(\v2+.v2ray.core.app.router.routercommon.GeoSiteR\x05entryB\x87\x01\n" + "&com.v2ray.core.app.router.routercommonP\x01Z6github.com/v2fly/v2ray-core/v5/app/router/routercommon\xaa\x02\"V2Ray.Core.App.Router.Routercommonb\x06proto3" var ( file_app_router_routercommon_common_proto_rawDescOnce sync.Once file_app_router_routercommon_common_proto_rawDescData []byte ) func file_app_router_routercommon_common_proto_rawDescGZIP() []byte { file_app_router_routercommon_common_proto_rawDescOnce.Do(func() { file_app_router_routercommon_common_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_router_routercommon_common_proto_rawDesc), len(file_app_router_routercommon_common_proto_rawDesc))) }) return file_app_router_routercommon_common_proto_rawDescData } var file_app_router_routercommon_common_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_app_router_routercommon_common_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_app_router_routercommon_common_proto_goTypes = []any{ (Domain_Type)(0), // 0: v2ray.core.app.router.routercommon.Domain.Type (*Domain)(nil), // 1: v2ray.core.app.router.routercommon.Domain (*CIDR)(nil), // 2: v2ray.core.app.router.routercommon.CIDR (*GeoIP)(nil), // 3: v2ray.core.app.router.routercommon.GeoIP (*GeoIPList)(nil), // 4: v2ray.core.app.router.routercommon.GeoIPList (*GeoSite)(nil), // 5: v2ray.core.app.router.routercommon.GeoSite (*GeoSiteList)(nil), // 6: v2ray.core.app.router.routercommon.GeoSiteList (*Domain_Attribute)(nil), // 7: v2ray.core.app.router.routercommon.Domain.Attribute } var file_app_router_routercommon_common_proto_depIdxs = []int32{ 0, // 0: v2ray.core.app.router.routercommon.Domain.type:type_name -> v2ray.core.app.router.routercommon.Domain.Type 7, // 1: v2ray.core.app.router.routercommon.Domain.attribute:type_name -> v2ray.core.app.router.routercommon.Domain.Attribute 2, // 2: v2ray.core.app.router.routercommon.GeoIP.cidr:type_name -> v2ray.core.app.router.routercommon.CIDR 3, // 3: v2ray.core.app.router.routercommon.GeoIPList.entry:type_name -> v2ray.core.app.router.routercommon.GeoIP 1, // 4: v2ray.core.app.router.routercommon.GeoSite.domain:type_name -> v2ray.core.app.router.routercommon.Domain 5, // 5: v2ray.core.app.router.routercommon.GeoSiteList.entry:type_name -> v2ray.core.app.router.routercommon.GeoSite 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_app_router_routercommon_common_proto_init() } func file_app_router_routercommon_common_proto_init() { if File_app_router_routercommon_common_proto != nil { return } file_app_router_routercommon_common_proto_msgTypes[6].OneofWrappers = []any{ (*Domain_Attribute_BoolValue)(nil), (*Domain_Attribute_IntValue)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_router_routercommon_common_proto_rawDesc), len(file_app_router_routercommon_common_proto_rawDesc)), NumEnums: 1, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_router_routercommon_common_proto_goTypes, DependencyIndexes: file_app_router_routercommon_common_proto_depIdxs, EnumInfos: file_app_router_routercommon_common_proto_enumTypes, MessageInfos: file_app_router_routercommon_common_proto_msgTypes, }.Build() File_app_router_routercommon_common_proto = out.File file_app_router_routercommon_common_proto_goTypes = nil file_app_router_routercommon_common_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/errors.generated.go
app/log/errors.generated.go
package log import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/log_test.go
app/log/log_test.go
package log_test import ( "context" "testing" "github.com/golang/mock/gomock" "github.com/v2fly/v2ray-core/v5/app/log" "github.com/v2fly/v2ray-core/v5/common" clog "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/testing/mocks" ) func TestCustomLogHandler(t *testing.T) { mockCtl := gomock.NewController(t) defer mockCtl.Finish() var loggedValue []string mockHandler := mocks.NewLogHandler(mockCtl) mockHandler.EXPECT().Handle(gomock.Any()).AnyTimes().DoAndReturn(func(msg clog.Message) { loggedValue = append(loggedValue, msg.String()) }) log.RegisterHandlerCreator(log.LogType_Console, func(lt log.LogType, options log.HandlerCreatorOptions) (clog.Handler, error) { return mockHandler, nil }) logger, err := log.New(context.Background(), &log.Config{ Error: &log.LogSpecification{Type: log.LogType_Console, Level: clog.Severity_Debug}, Access: &log.LogSpecification{Type: log.LogType_None}, }) common.Must(err) common.Must(logger.Start()) clog.Record(&clog.GeneralMessage{ Severity: clog.Severity_Debug, Content: "test", }) if len(loggedValue) < 2 { t.Fatal("expected 2 log messages, but actually ", loggedValue) } if loggedValue[1] != "[Debug] test" { t.Fatal("expected '[Debug] test', but actually ", loggedValue[1]) } common.Must(logger.Close()) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/log.go
app/log/log.go
package log //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "reflect" "sync" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/log" ) // Instance is a log.Handler that handles logs. type Instance struct { sync.RWMutex config *Config accessLogger log.Handler errorLogger log.Handler followers map[reflect.Value]func(msg log.Message) active bool } // New creates a new log.Instance based on the given config. func New(ctx context.Context, config *Config) (*Instance, error) { if config.Error == nil { config.Error = &LogSpecification{Type: LogType_Console, Level: log.Severity_Warning} } if config.Access == nil { config.Access = &LogSpecification{Type: LogType_None} } g := &Instance{ config: config, active: false, } log.RegisterHandler(g) // start logger instantly on inited // other modules would log during init if err := g.startInternal(); err != nil { return nil, err } newError("Logger started").AtDebug().WriteToLog() return g, nil } func (g *Instance) initAccessLogger() error { handler, err := createHandler(g.config.Access.Type, HandlerCreatorOptions{ Path: g.config.Access.Path, }) if err != nil { return err } g.accessLogger = handler return nil } func (g *Instance) initErrorLogger() error { handler, err := createHandler(g.config.Error.Type, HandlerCreatorOptions{ Path: g.config.Error.Path, }) if err != nil { return err } g.errorLogger = handler return nil } // Type implements common.HasType. func (*Instance) Type() interface{} { return (*Instance)(nil) } func (g *Instance) startInternal() error { g.Lock() defer g.Unlock() if g.active { return nil } g.active = true if err := g.initAccessLogger(); err != nil { return newError("failed to initialize access logger").Base(err).AtWarning() } if err := g.initErrorLogger(); err != nil { return newError("failed to initialize error logger").Base(err).AtWarning() } return nil } // Start implements common.Runnable.Start(). func (g *Instance) Start() error { return g.startInternal() } // AddFollower implements log.Follower. func (g *Instance) AddFollower(f func(msg log.Message)) { g.Lock() defer g.Unlock() if g.followers == nil { g.followers = make(map[reflect.Value]func(msg log.Message)) } g.followers[reflect.ValueOf(f)] = f } // RemoveFollower implements log.Follower. func (g *Instance) RemoveFollower(f func(msg log.Message)) { g.Lock() defer g.Unlock() delete(g.followers, reflect.ValueOf(f)) } // Handle implements log.Handler. func (g *Instance) Handle(msg log.Message) { g.RLock() defer g.RUnlock() if !g.active { return } for _, f := range g.followers { f(msg) } switch msg := msg.(type) { case *log.AccessMessage: if g.accessLogger != nil { g.accessLogger.Handle(msg) } case *log.GeneralMessage: if g.errorLogger != nil && msg.Severity <= g.config.Error.Level { g.errorLogger.Handle(msg) } default: // Swallow } } // Close implements common.Closable.Close(). func (g *Instance) Close() error { newError("Logger closing").AtDebug().WriteToLog() g.Lock() defer g.Unlock() if !g.active { return nil } g.active = false common.Close(g.accessLogger) g.accessLogger = nil common.Close(g.errorLogger) g.errorLogger = nil return nil } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/log_creator.go
app/log/log_creator.go
package log import ( "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/log" ) type HandlerCreatorOptions struct { Path string } type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error) var handlerCreatorMap = make(map[LogType]HandlerCreator) func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { if f == nil { return newError("nil HandlerCreator") } handlerCreatorMap[logType] = f return nil } func createHandler(logType LogType, options HandlerCreatorOptions) (log.Handler, error) { creator, found := handlerCreatorMap[logType] if !found { return nil, newError("unable to create log handler for ", logType) } return creator(logType, options) } func init() { common.Must(RegisterHandlerCreator(LogType_Console, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { return log.NewLogger(log.CreateStdoutLogWriter()), nil })) common.Must(RegisterHandlerCreator(LogType_File, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { creator, err := log.CreateFileLogWriter(options.Path) if err != nil { return nil, err } return log.NewLogger(creator), nil })) common.Must(RegisterHandlerCreator(LogType_None, func(lt LogType, options HandlerCreatorOptions) (log.Handler, error) { return nil, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/config.pb.go
app/log/config.pb.go
package log import ( log "github.com/v2fly/v2ray-core/v5/common/log" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type LogType int32 const ( LogType_None LogType = 0 LogType_Console LogType = 1 LogType_File LogType = 2 LogType_Event LogType = 3 ) // Enum value maps for LogType. var ( LogType_name = map[int32]string{ 0: "None", 1: "Console", 2: "File", 3: "Event", } LogType_value = map[string]int32{ "None": 0, "Console": 1, "File": 2, "Event": 3, } ) func (x LogType) Enum() *LogType { p := new(LogType) *p = x return p } func (x LogType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (LogType) Descriptor() protoreflect.EnumDescriptor { return file_app_log_config_proto_enumTypes[0].Descriptor() } func (LogType) Type() protoreflect.EnumType { return &file_app_log_config_proto_enumTypes[0] } func (x LogType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use LogType.Descriptor instead. func (LogType) EnumDescriptor() ([]byte, []int) { return file_app_log_config_proto_rawDescGZIP(), []int{0} } type LogSpecification struct { state protoimpl.MessageState `protogen:"open.v1"` Type LogType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.log.LogType" json:"type,omitempty"` Level log.Severity `protobuf:"varint,2,opt,name=level,proto3,enum=v2ray.core.common.log.Severity" json:"level,omitempty"` Path string `protobuf:"bytes,3,opt,name=path,proto3" json:"path,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *LogSpecification) Reset() { *x = LogSpecification{} mi := &file_app_log_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *LogSpecification) String() string { return protoimpl.X.MessageStringOf(x) } func (*LogSpecification) ProtoMessage() {} func (x *LogSpecification) ProtoReflect() protoreflect.Message { mi := &file_app_log_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LogSpecification.ProtoReflect.Descriptor instead. func (*LogSpecification) Descriptor() ([]byte, []int) { return file_app_log_config_proto_rawDescGZIP(), []int{0} } func (x *LogSpecification) GetType() LogType { if x != nil { return x.Type } return LogType_None } func (x *LogSpecification) GetLevel() log.Severity { if x != nil { return x.Level } return log.Severity(0) } func (x *LogSpecification) GetPath() string { if x != nil { return x.Path } return "" } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` Error *LogSpecification `protobuf:"bytes,6,opt,name=error,proto3" json:"error,omitempty"` Access *LogSpecification `protobuf:"bytes,7,opt,name=access,proto3" json:"access,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_log_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_log_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_log_config_proto_rawDescGZIP(), []int{1} } func (x *Config) GetError() *LogSpecification { if x != nil { return x.Error } return nil } func (x *Config) GetAccess() *LogSpecification { if x != nil { return x.Access } return nil } var File_app_log_config_proto protoreflect.FileDescriptor const file_app_log_config_proto_rawDesc = "" + "\n" + "\x14app/log/config.proto\x12\x12v2ray.core.app.log\x1a\x14common/log/log.proto\x1a common/protoext/extensions.proto\"\x8e\x01\n" + "\x10LogSpecification\x12/\n" + "\x04type\x18\x01 \x01(\x0e2\x1b.v2ray.core.app.log.LogTypeR\x04type\x125\n" + "\x05level\x18\x02 \x01(\x0e2\x1f.v2ray.core.common.log.SeverityR\x05level\x12\x12\n" + "\x04path\x18\x03 \x01(\tR\x04path\"\xb4\x01\n" + "\x06Config\x12:\n" + "\x05error\x18\x06 \x01(\v2$.v2ray.core.app.log.LogSpecificationR\x05error\x12<\n" + "\x06access\x18\a \x01(\v2$.v2ray.core.app.log.LogSpecificationR\x06access:\x12\x82\xb5\x18\x0e\n" + "\aservice\x12\x03logJ\x04\b\x01\x10\x02J\x04\b\x02\x10\x03J\x04\b\x03\x10\x04J\x04\b\x04\x10\x05J\x04\b\x05\x10\x06*5\n" + "\aLogType\x12\b\n" + "\x04None\x10\x00\x12\v\n" + "\aConsole\x10\x01\x12\b\n" + "\x04File\x10\x02\x12\t\n" + "\x05Event\x10\x03BW\n" + "\x16com.v2ray.core.app.logP\x01Z&github.com/v2fly/v2ray-core/v5/app/log\xaa\x02\x12V2Ray.Core.App.Logb\x06proto3" var ( file_app_log_config_proto_rawDescOnce sync.Once file_app_log_config_proto_rawDescData []byte ) func file_app_log_config_proto_rawDescGZIP() []byte { file_app_log_config_proto_rawDescOnce.Do(func() { file_app_log_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_log_config_proto_rawDesc), len(file_app_log_config_proto_rawDesc))) }) return file_app_log_config_proto_rawDescData } var file_app_log_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_app_log_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_app_log_config_proto_goTypes = []any{ (LogType)(0), // 0: v2ray.core.app.log.LogType (*LogSpecification)(nil), // 1: v2ray.core.app.log.LogSpecification (*Config)(nil), // 2: v2ray.core.app.log.Config (log.Severity)(0), // 3: v2ray.core.common.log.Severity } var file_app_log_config_proto_depIdxs = []int32{ 0, // 0: v2ray.core.app.log.LogSpecification.type:type_name -> v2ray.core.app.log.LogType 3, // 1: v2ray.core.app.log.LogSpecification.level:type_name -> v2ray.core.common.log.Severity 1, // 2: v2ray.core.app.log.Config.error:type_name -> v2ray.core.app.log.LogSpecification 1, // 3: v2ray.core.app.log.Config.access:type_name -> v2ray.core.app.log.LogSpecification 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_app_log_config_proto_init() } func file_app_log_config_proto_init() { if File_app_log_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_log_config_proto_rawDesc), len(file_app_log_config_proto_rawDesc)), NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_log_config_proto_goTypes, DependencyIndexes: file_app_log_config_proto_depIdxs, EnumInfos: file_app_log_config_proto_enumTypes, MessageInfos: file_app_log_config_proto_msgTypes, }.Build() File_app_log_config_proto = out.File file_app_log_config_proto_goTypes = nil file_app_log_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/command/command_test.go
app/log/command/command_test.go
package command_test import ( "context" "testing" "google.golang.org/protobuf/types/known/anypb" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/dispatcher" "github.com/v2fly/v2ray-core/v5/app/log" . "github.com/v2fly/v2ray-core/v5/app/log/command" "github.com/v2fly/v2ray-core/v5/app/proxyman" _ "github.com/v2fly/v2ray-core/v5/app/proxyman/inbound" _ "github.com/v2fly/v2ray-core/v5/app/proxyman/outbound" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/serial" ) func TestLoggerRestart(t *testing.T) { v, err := core.New(&core.Config{ App: []*anypb.Any{ serial.ToTypedMessage(&log.Config{}), serial.ToTypedMessage(&dispatcher.Config{}), serial.ToTypedMessage(&proxyman.InboundConfig{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}), }, }) common.Must(err) common.Must(v.Start()) server := &LoggerServer{ V: v, } common.Must2(server.RestartLogger(context.Background(), &RestartLoggerRequest{})) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/command/errors.generated.go
app/log/command/errors.generated.go
package command import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/command/config_grpc.pb.go
app/log/command/config_grpc.pb.go
package command import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.64.0 or later. const _ = grpc.SupportPackageIsVersion9 const ( LoggerService_RestartLogger_FullMethodName = "/v2ray.core.app.log.command.LoggerService/RestartLogger" LoggerService_FollowLog_FullMethodName = "/v2ray.core.app.log.command.LoggerService/FollowLog" ) // LoggerServiceClient is the client API for LoggerService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type LoggerServiceClient interface { RestartLogger(ctx context.Context, in *RestartLoggerRequest, opts ...grpc.CallOption) (*RestartLoggerResponse, error) // Unstable interface FollowLog(ctx context.Context, in *FollowLogRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FollowLogResponse], error) } type loggerServiceClient struct { cc grpc.ClientConnInterface } func NewLoggerServiceClient(cc grpc.ClientConnInterface) LoggerServiceClient { return &loggerServiceClient{cc} } func (c *loggerServiceClient) RestartLogger(ctx context.Context, in *RestartLoggerRequest, opts ...grpc.CallOption) (*RestartLoggerResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(RestartLoggerResponse) err := c.cc.Invoke(ctx, LoggerService_RestartLogger_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } func (c *loggerServiceClient) FollowLog(ctx context.Context, in *FollowLogRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FollowLogResponse], error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) stream, err := c.cc.NewStream(ctx, &LoggerService_ServiceDesc.Streams[0], LoggerService_FollowLog_FullMethodName, cOpts...) if err != nil { return nil, err } x := &grpc.GenericClientStream[FollowLogRequest, FollowLogResponse]{ClientStream: stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } // This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. type LoggerService_FollowLogClient = grpc.ServerStreamingClient[FollowLogResponse] // LoggerServiceServer is the server API for LoggerService service. // All implementations must embed UnimplementedLoggerServiceServer // for forward compatibility. type LoggerServiceServer interface { RestartLogger(context.Context, *RestartLoggerRequest) (*RestartLoggerResponse, error) // Unstable interface FollowLog(*FollowLogRequest, grpc.ServerStreamingServer[FollowLogResponse]) error mustEmbedUnimplementedLoggerServiceServer() } // UnimplementedLoggerServiceServer must be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. type UnimplementedLoggerServiceServer struct{} func (UnimplementedLoggerServiceServer) RestartLogger(context.Context, *RestartLoggerRequest) (*RestartLoggerResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RestartLogger not implemented") } func (UnimplementedLoggerServiceServer) FollowLog(*FollowLogRequest, grpc.ServerStreamingServer[FollowLogResponse]) error { return status.Errorf(codes.Unimplemented, "method FollowLog not implemented") } func (UnimplementedLoggerServiceServer) mustEmbedUnimplementedLoggerServiceServer() {} func (UnimplementedLoggerServiceServer) testEmbeddedByValue() {} // UnsafeLoggerServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to LoggerServiceServer will // result in compilation errors. type UnsafeLoggerServiceServer interface { mustEmbedUnimplementedLoggerServiceServer() } func RegisterLoggerServiceServer(s grpc.ServiceRegistrar, srv LoggerServiceServer) { // If the following call pancis, it indicates UnimplementedLoggerServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } s.RegisterService(&LoggerService_ServiceDesc, srv) } func _LoggerService_RestartLogger_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RestartLoggerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(LoggerServiceServer).RestartLogger(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: LoggerService_RestartLogger_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(LoggerServiceServer).RestartLogger(ctx, req.(*RestartLoggerRequest)) } return interceptor(ctx, in, info, handler) } func _LoggerService_FollowLog_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(FollowLogRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(LoggerServiceServer).FollowLog(m, &grpc.GenericServerStream[FollowLogRequest, FollowLogResponse]{ServerStream: stream}) } // This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. type LoggerService_FollowLogServer = grpc.ServerStreamingServer[FollowLogResponse] // LoggerService_ServiceDesc is the grpc.ServiceDesc for LoggerService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var LoggerService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "v2ray.core.app.log.command.LoggerService", HandlerType: (*LoggerServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "RestartLogger", Handler: _LoggerService_RestartLogger_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "FollowLog", Handler: _LoggerService_FollowLog_Handler, ServerStreams: true, }, }, Metadata: "app/log/command/config.proto", }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/command/config.pb.go
app/log/command/config.pb.go
package command import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Config struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_log_command_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_log_command_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_log_command_config_proto_rawDescGZIP(), []int{0} } type RestartLoggerRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RestartLoggerRequest) Reset() { *x = RestartLoggerRequest{} mi := &file_app_log_command_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RestartLoggerRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RestartLoggerRequest) ProtoMessage() {} func (x *RestartLoggerRequest) ProtoReflect() protoreflect.Message { mi := &file_app_log_command_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RestartLoggerRequest.ProtoReflect.Descriptor instead. func (*RestartLoggerRequest) Descriptor() ([]byte, []int) { return file_app_log_command_config_proto_rawDescGZIP(), []int{1} } type RestartLoggerResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RestartLoggerResponse) Reset() { *x = RestartLoggerResponse{} mi := &file_app_log_command_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RestartLoggerResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RestartLoggerResponse) ProtoMessage() {} func (x *RestartLoggerResponse) ProtoReflect() protoreflect.Message { mi := &file_app_log_command_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RestartLoggerResponse.ProtoReflect.Descriptor instead. func (*RestartLoggerResponse) Descriptor() ([]byte, []int) { return file_app_log_command_config_proto_rawDescGZIP(), []int{2} } type FollowLogRequest struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FollowLogRequest) Reset() { *x = FollowLogRequest{} mi := &file_app_log_command_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *FollowLogRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*FollowLogRequest) ProtoMessage() {} func (x *FollowLogRequest) ProtoReflect() protoreflect.Message { mi := &file_app_log_command_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FollowLogRequest.ProtoReflect.Descriptor instead. func (*FollowLogRequest) Descriptor() ([]byte, []int) { return file_app_log_command_config_proto_rawDescGZIP(), []int{3} } type FollowLogResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FollowLogResponse) Reset() { *x = FollowLogResponse{} mi := &file_app_log_command_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *FollowLogResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*FollowLogResponse) ProtoMessage() {} func (x *FollowLogResponse) ProtoReflect() protoreflect.Message { mi := &file_app_log_command_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FollowLogResponse.ProtoReflect.Descriptor instead. func (*FollowLogResponse) Descriptor() ([]byte, []int) { return file_app_log_command_config_proto_rawDescGZIP(), []int{4} } func (x *FollowLogResponse) GetMessage() string { if x != nil { return x.Message } return "" } var File_app_log_command_config_proto protoreflect.FileDescriptor const file_app_log_command_config_proto_rawDesc = "" + "\n" + "\x1capp/log/command/config.proto\x12\x1av2ray.core.app.log.command\"\b\n" + "\x06Config\"\x16\n" + "\x14RestartLoggerRequest\"\x17\n" + "\x15RestartLoggerResponse\"\x12\n" + "\x10FollowLogRequest\"-\n" + "\x11FollowLogResponse\x12\x18\n" + "\amessage\x18\x01 \x01(\tR\amessage2\xf5\x01\n" + "\rLoggerService\x12v\n" + "\rRestartLogger\x120.v2ray.core.app.log.command.RestartLoggerRequest\x1a1.v2ray.core.app.log.command.RestartLoggerResponse\"\x00\x12l\n" + "\tFollowLog\x12,.v2ray.core.app.log.command.FollowLogRequest\x1a-.v2ray.core.app.log.command.FollowLogResponse\"\x000\x01Bo\n" + "\x1ecom.v2ray.core.app.log.commandP\x01Z.github.com/v2fly/v2ray-core/v5/app/log/command\xaa\x02\x1aV2Ray.Core.App.Log.Commandb\x06proto3" var ( file_app_log_command_config_proto_rawDescOnce sync.Once file_app_log_command_config_proto_rawDescData []byte ) func file_app_log_command_config_proto_rawDescGZIP() []byte { file_app_log_command_config_proto_rawDescOnce.Do(func() { file_app_log_command_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_log_command_config_proto_rawDesc), len(file_app_log_command_config_proto_rawDesc))) }) return file_app_log_command_config_proto_rawDescData } var file_app_log_command_config_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_app_log_command_config_proto_goTypes = []any{ (*Config)(nil), // 0: v2ray.core.app.log.command.Config (*RestartLoggerRequest)(nil), // 1: v2ray.core.app.log.command.RestartLoggerRequest (*RestartLoggerResponse)(nil), // 2: v2ray.core.app.log.command.RestartLoggerResponse (*FollowLogRequest)(nil), // 3: v2ray.core.app.log.command.FollowLogRequest (*FollowLogResponse)(nil), // 4: v2ray.core.app.log.command.FollowLogResponse } var file_app_log_command_config_proto_depIdxs = []int32{ 1, // 0: v2ray.core.app.log.command.LoggerService.RestartLogger:input_type -> v2ray.core.app.log.command.RestartLoggerRequest 3, // 1: v2ray.core.app.log.command.LoggerService.FollowLog:input_type -> v2ray.core.app.log.command.FollowLogRequest 2, // 2: v2ray.core.app.log.command.LoggerService.RestartLogger:output_type -> v2ray.core.app.log.command.RestartLoggerResponse 4, // 3: v2ray.core.app.log.command.LoggerService.FollowLog:output_type -> v2ray.core.app.log.command.FollowLogResponse 2, // [2:4] is the sub-list for method output_type 0, // [0:2] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_app_log_command_config_proto_init() } func file_app_log_command_config_proto_init() { if File_app_log_command_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_log_command_config_proto_rawDesc), len(file_app_log_command_config_proto_rawDesc)), NumEnums: 0, NumMessages: 5, NumExtensions: 0, NumServices: 1, }, GoTypes: file_app_log_command_config_proto_goTypes, DependencyIndexes: file_app_log_command_config_proto_depIdxs, MessageInfos: file_app_log_command_config_proto_msgTypes, }.Build() File_app_log_command_config_proto = out.File file_app_log_command_config_proto_goTypes = nil file_app_log_command_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/log/command/command.go
app/log/command/command.go
package command //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" grpc "google.golang.org/grpc" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/log" "github.com/v2fly/v2ray-core/v5/common" cmlog "github.com/v2fly/v2ray-core/v5/common/log" ) // LoggerServer is the implemention of LoggerService type LoggerServer struct { V *core.Instance } // RestartLogger implements LoggerService. func (s *LoggerServer) RestartLogger(ctx context.Context, request *RestartLoggerRequest) (*RestartLoggerResponse, error) { logger := s.V.GetFeature((*log.Instance)(nil)) if logger == nil { return nil, newError("unable to get logger instance") } if err := logger.Close(); err != nil { return nil, newError("failed to close logger").Base(err) } if err := logger.Start(); err != nil { return nil, newError("failed to start logger").Base(err) } return &RestartLoggerResponse{}, nil } // FollowLog implements LoggerService. func (s *LoggerServer) FollowLog(_ *FollowLogRequest, stream LoggerService_FollowLogServer) error { logger := s.V.GetFeature((*log.Instance)(nil)) if logger == nil { return newError("unable to get logger instance") } follower, ok := logger.(cmlog.Follower) if !ok { return newError("logger not support following") } ctx, cancel := context.WithCancel(stream.Context()) defer cancel() f := func(msg cmlog.Message) { err := stream.Send(&FollowLogResponse{ Message: msg.String(), }) if err != nil { cancel() } } follower.AddFollower(f) defer follower.RemoveFollower(f) <-ctx.Done() return nil } func (s *LoggerServer) mustEmbedUnimplementedLoggerServiceServer() {} type service struct { v *core.Instance } func (s *service) Register(server *grpc.Server) { RegisterLoggerServiceServer(server, &LoggerServer{ V: s.v, }) } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { s := core.MustFromContext(ctx) return &service{v: s}, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/commander.go
app/commander/commander.go
package commander //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen import ( "context" "net" "sync" "google.golang.org/grpc" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/common/signal/done" "github.com/v2fly/v2ray-core/v5/features" "github.com/v2fly/v2ray-core/v5/features/outbound" "github.com/v2fly/v2ray-core/v5/infra/conf/v5cfg" ) type CommanderIfce interface { features.Feature ExtractGrpcServer() *grpc.Server } // Commander is a V2Ray feature that provides gRPC methods to external clients. type Commander struct { sync.Mutex server *grpc.Server services []Service ohm outbound.Manager tag string } // NewCommander creates a new Commander based on the given config. func NewCommander(ctx context.Context, config *Config) (*Commander, error) { c := &Commander{ tag: config.Tag, } common.Must(core.RequireFeatures(ctx, func(om outbound.Manager) { c.ohm = om })) for _, rawConfig := range config.Service { config, err := serial.GetInstanceOf(rawConfig) if err != nil { return nil, err } rawService, err := common.CreateObject(ctx, config) if err != nil { return nil, err } service, ok := rawService.(Service) if !ok { return nil, newError("not a Service.") } c.services = append(c.services, service) } return c, nil } // Type implements common.HasType. func (c *Commander) Type() interface{} { return (*CommanderIfce)(nil) } // Start implements common.Runnable. func (c *Commander) Start() error { c.Lock() c.server = grpc.NewServer() for _, service := range c.services { service.Register(c.server) } c.Unlock() listener := &OutboundListener{ buffer: make(chan net.Conn, 4), done: done.New(), } go func() { if err := c.server.Serve(listener); err != nil { newError("failed to start grpc server").Base(err).AtError().WriteToLog() } }() if err := c.ohm.RemoveHandler(context.Background(), c.tag); err != nil { newError("failed to remove existing handler").WriteToLog() } return c.ohm.AddHandler(context.Background(), &Outbound{ tag: c.tag, listener: listener, }) } // Close implements common.Closable. func (c *Commander) Close() error { c.Lock() defer c.Unlock() if c.server != nil { c.server.Stop() c.server = nil } return nil } // ExtractGrpcServer extracts the gRPC server from Commander. // Private function for core code base. func (c *Commander) ExtractGrpcServer() *grpc.Server { c.Lock() defer c.Unlock() return c.server } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { return NewCommander(ctx, cfg.(*Config)) })) } func init() { common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { simplifiedConfig := cfg.(*SimplifiedConfig) fullConfig := &Config{ Tag: simplifiedConfig.Tag, Service: nil, } for _, v := range simplifiedConfig.Name { pack, err := v5cfg.LoadHeterogeneousConfigFromRawJSON(ctx, "grpcservice", v, []byte("{}")) if err != nil { return nil, err } fullConfig.Service = append(fullConfig.Service, serial.ToTypedMessage(pack)) } return common.CreateObject(ctx, fullConfig) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/errors.generated.go
app/commander/errors.generated.go
package commander import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/service.go
app/commander/service.go
package commander import ( "context" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "github.com/v2fly/v2ray-core/v5/common" ) // Service is a Commander service. type Service interface { // Register registers the service itself to a gRPC server. Register(*grpc.Server) } type reflectionService struct{} func (r reflectionService) Register(s *grpc.Server) { reflection.Register(s) } func init() { common.Must(common.RegisterConfig((*ReflectionConfig)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { return reflectionService{}, nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/outbound.go
app/commander/outbound.go
package commander import ( "context" "sync" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/signal/done" "github.com/v2fly/v2ray-core/v5/transport" ) func NewOutboundListener() *OutboundListener { return &OutboundListener{ buffer: make(chan net.Conn, 4), done: done.New(), } } // OutboundListener is a net.Listener for listening gRPC connections. type OutboundListener struct { buffer chan net.Conn done *done.Instance } func (l *OutboundListener) add(conn net.Conn) { select { case l.buffer <- conn: case <-l.done.Wait(): conn.Close() default: conn.Close() } } // Accept implements net.Listener. func (l *OutboundListener) Accept() (net.Conn, error) { select { case <-l.done.Wait(): return nil, newError("listen closed") case c := <-l.buffer: return c, nil } } // Close implement net.Listener. func (l *OutboundListener) Close() error { common.Must(l.done.Close()) L: for { select { case c := <-l.buffer: c.Close() default: break L } } return nil } // Addr implements net.Listener. func (l *OutboundListener) Addr() net.Addr { return &net.TCPAddr{ IP: net.IP{0, 0, 0, 0}, Port: 0, } } func NewOutbound(tag string, listener *OutboundListener) *Outbound { return &Outbound{ tag: tag, listener: listener, } } // Outbound is a outbound.Handler that handles gRPC connections. type Outbound struct { tag string listener *OutboundListener access sync.RWMutex closed bool } // Dispatch implements outbound.Handler. func (co *Outbound) Dispatch(ctx context.Context, link *transport.Link) { co.access.RLock() if co.closed { common.Interrupt(link.Reader) common.Interrupt(link.Writer) co.access.RUnlock() return } closeSignal := done.New() c := net.NewConnection(net.ConnectionInputMulti(link.Writer), net.ConnectionOutputMulti(link.Reader), net.ConnectionOnClose(closeSignal)) co.listener.add(c) co.access.RUnlock() <-closeSignal.Wait() } // Tag implements outbound.Handler. func (co *Outbound) Tag() string { return co.tag } // Start implements common.Runnable. func (co *Outbound) Start() error { co.access.Lock() co.closed = false co.access.Unlock() return nil } // Close implements common.Closable. func (co *Outbound) Close() error { co.access.Lock() defer co.access.Unlock() co.closed = true return co.listener.Close() }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/config.pb.go
app/commander/config.pb.go
package commander import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Config is the settings for Commander. type Config struct { state protoimpl.MessageState `protogen:"open.v1"` // Tag of the outbound handler that handles grpc connections. Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` // Services that supported by this server. All services must implement Service // interface. Service []*anypb.Any `protobuf:"bytes,2,rep,name=service,proto3" json:"service,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_commander_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_commander_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_commander_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetTag() string { if x != nil { return x.Tag } return "" } func (x *Config) GetService() []*anypb.Any { if x != nil { return x.Service } return nil } // ReflectionConfig is the placeholder config for ReflectionService. type ReflectionConfig struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ReflectionConfig) Reset() { *x = ReflectionConfig{} mi := &file_app_commander_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ReflectionConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ReflectionConfig) ProtoMessage() {} func (x *ReflectionConfig) ProtoReflect() protoreflect.Message { mi := &file_app_commander_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ReflectionConfig.ProtoReflect.Descriptor instead. func (*ReflectionConfig) Descriptor() ([]byte, []int) { return file_app_commander_config_proto_rawDescGZIP(), []int{1} } type SimplifiedConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` Name []string `protobuf:"bytes,2,rep,name=name,proto3" json:"name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SimplifiedConfig) Reset() { *x = SimplifiedConfig{} mi := &file_app_commander_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SimplifiedConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SimplifiedConfig) ProtoMessage() {} func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message { mi := &file_app_commander_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead. func (*SimplifiedConfig) Descriptor() ([]byte, []int) { return file_app_commander_config_proto_rawDescGZIP(), []int{2} } func (x *SimplifiedConfig) GetTag() string { if x != nil { return x.Tag } return "" } func (x *SimplifiedConfig) GetName() []string { if x != nil { return x.Name } return nil } var File_app_commander_config_proto protoreflect.FileDescriptor const file_app_commander_config_proto_rawDesc = "" + "\n" + "\x1aapp/commander/config.proto\x12\x18v2ray.core.app.commander\x1a\x19google/protobuf/any.proto\x1a common/protoext/extensions.proto\"J\n" + "\x06Config\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12.\n" + "\aservice\x18\x02 \x03(\v2\x14.google.protobuf.AnyR\aservice\"1\n" + "\x10ReflectionConfig:\x1d\x82\xb5\x18\x19\n" + "\vgrpcservice\x12\n" + "reflection\"R\n" + "\x10SimplifiedConfig\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12\x12\n" + "\x04name\x18\x02 \x03(\tR\x04name:\x18\x82\xb5\x18\x14\n" + "\aservice\x12\tcommanderBi\n" + "\x1ccom.v2ray.core.app.commanderP\x01Z,github.com/v2fly/v2ray-core/v5/app/commander\xaa\x02\x18V2Ray.Core.App.Commanderb\x06proto3" var ( file_app_commander_config_proto_rawDescOnce sync.Once file_app_commander_config_proto_rawDescData []byte ) func file_app_commander_config_proto_rawDescGZIP() []byte { file_app_commander_config_proto_rawDescOnce.Do(func() { file_app_commander_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_commander_config_proto_rawDesc), len(file_app_commander_config_proto_rawDesc))) }) return file_app_commander_config_proto_rawDescData } var file_app_commander_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_app_commander_config_proto_goTypes = []any{ (*Config)(nil), // 0: v2ray.core.app.commander.Config (*ReflectionConfig)(nil), // 1: v2ray.core.app.commander.ReflectionConfig (*SimplifiedConfig)(nil), // 2: v2ray.core.app.commander.SimplifiedConfig (*anypb.Any)(nil), // 3: google.protobuf.Any } var file_app_commander_config_proto_depIdxs = []int32{ 3, // 0: v2ray.core.app.commander.Config.service:type_name -> google.protobuf.Any 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_app_commander_config_proto_init() } func file_app_commander_config_proto_init() { if File_app_commander_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_commander_config_proto_rawDesc), len(file_app_commander_config_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_commander_config_proto_goTypes, DependencyIndexes: file_app_commander_config_proto_depIdxs, MessageInfos: file_app_commander_config_proto_msgTypes, }.Build() File_app_commander_config_proto = out.File file_app_commander_config_proto_goTypes = nil file_app_commander_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/webcommander/errors.generated.go
app/commander/webcommander/errors.generated.go
package webcommander import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/webcommander/config.pb.go
app/commander/webcommander/config.pb.go
package webcommander import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Config struct { state protoimpl.MessageState `protogen:"open.v1"` Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` WebRoot []byte `protobuf:"bytes,2,opt,name=web_root,json=webRoot,proto3" json:"web_root,omitempty"` WebRootFile string `protobuf:"bytes,96002,opt,name=web_root_file,json=webRootFile,proto3" json:"web_root_file,omitempty"` ApiMountpoint string `protobuf:"bytes,3,opt,name=api_mountpoint,json=apiMountpoint,proto3" json:"api_mountpoint,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_commander_webcommander_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_commander_webcommander_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_commander_webcommander_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetTag() string { if x != nil { return x.Tag } return "" } func (x *Config) GetWebRoot() []byte { if x != nil { return x.WebRoot } return nil } func (x *Config) GetWebRootFile() string { if x != nil { return x.WebRootFile } return "" } func (x *Config) GetApiMountpoint() string { if x != nil { return x.ApiMountpoint } return "" } var File_app_commander_webcommander_config_proto protoreflect.FileDescriptor const file_app_commander_webcommander_config_proto_rawDesc = "" + "\n" + "'app/commander/webcommander/config.proto\x12%v2ray.core.app.commander.webcommander\x1a common/protoext/extensions.proto\"\xaf\x01\n" + "\x06Config\x12\x10\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12\x19\n" + "\bweb_root\x18\x02 \x01(\fR\awebRoot\x124\n" + "\rweb_root_file\x18\x82\xee\x05 \x01(\tB\x0e\x82\xb5\x18\n" + "\"\bweb_rootR\vwebRootFile\x12%\n" + "\x0eapi_mountpoint\x18\x03 \x01(\tR\rapiMountpoint:\x1b\x82\xb5\x18\x17\n" + "\aservice\x12\fwebcommanderB\x90\x01\n" + ")com.v2ray.core.app.commander.webcommanderP\x01Z9github.com/v2fly/v2ray-core/v5/app/commander/webcommander\xaa\x02%V2Ray.Core.App.Commander.WebCommanderb\x06proto3" var ( file_app_commander_webcommander_config_proto_rawDescOnce sync.Once file_app_commander_webcommander_config_proto_rawDescData []byte ) func file_app_commander_webcommander_config_proto_rawDescGZIP() []byte { file_app_commander_webcommander_config_proto_rawDescOnce.Do(func() { file_app_commander_webcommander_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_commander_webcommander_config_proto_rawDesc), len(file_app_commander_webcommander_config_proto_rawDesc))) }) return file_app_commander_webcommander_config_proto_rawDescData } var file_app_commander_webcommander_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_app_commander_webcommander_config_proto_goTypes = []any{ (*Config)(nil), // 0: v2ray.core.app.commander.webcommander.Config } var file_app_commander_webcommander_config_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_app_commander_webcommander_config_proto_init() } func file_app_commander_webcommander_config_proto_init() { if File_app_commander_webcommander_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_commander_webcommander_config_proto_rawDesc), len(file_app_commander_webcommander_config_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_commander_webcommander_config_proto_goTypes, DependencyIndexes: file_app_commander_webcommander_config_proto_depIdxs, MessageInfos: file_app_commander_webcommander_config_proto_msgTypes, }.Build() File_app_commander_webcommander_config_proto = out.File file_app_commander_webcommander_config_proto_goTypes = nil file_app_commander_webcommander_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/commander/webcommander/webcommander.go
app/commander/webcommander/webcommander.go
package webcommander import ( "archive/zip" "bytes" "context" "io/fs" "net/http" "strings" "sync" "time" "github.com/improbable-eng/grpc-web/go/grpcweb" "google.golang.org/grpc" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/app/commander" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features/outbound" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen func newWebCommander(ctx context.Context, config *Config) (*WebCommander, error) { if config == nil { return nil, newError("config is nil") } if config.Tag == "" { return nil, newError("config.Tag is empty") } var webRootfs fs.FS if config.WebRoot != nil { zipReader, err := zip.NewReader(bytes.NewReader(config.WebRoot), int64(len(config.WebRoot))) if err != nil { return nil, newError("failed to create zip reader").Base(err) } webRootfs = zipReader } return &WebCommander{ctx: ctx, config: config, webRootfs: webRootfs}, nil } type WebCommander struct { sync.Mutex ctx context.Context ohm outbound.Manager cm commander.CommanderIfce server *http.Server wrappedGrpc *grpcweb.WrappedGrpcServer webRootfs fs.FS config *Config } func (w *WebCommander) ServeHTTP(writer http.ResponseWriter, request *http.Request) { apiPath := w.config.ApiMountpoint if strings.HasPrefix(request.URL.Path, apiPath) { request.URL.Path = strings.TrimPrefix(request.URL.Path, apiPath) if w.wrappedGrpc.IsGrpcWebRequest(request) { w.wrappedGrpc.ServeHTTP(writer, request) return } } if w.webRootfs != nil { http.ServeFileFS(writer, request, w.webRootfs, request.URL.Path) return } writer.WriteHeader(http.StatusNotFound) } func (w *WebCommander) asyncStart() { var grpcServer *grpc.Server for { grpcServer = w.cm.ExtractGrpcServer() if grpcServer != nil { break } time.Sleep(time.Second) } listener := commander.NewOutboundListener() wrappedGrpc := grpcweb.WrapServer(grpcServer) w.server = &http.Server{} w.wrappedGrpc = wrappedGrpc w.server.Handler = w go func() { err := w.server.Serve(listener) if err != nil { newError("failed to serve HTTP").Base(err).WriteToLog() } }() if err := w.ohm.RemoveHandler(context.Background(), w.config.Tag); err != nil { newError("failed to remove existing handler").WriteToLog() } if err := w.ohm.AddHandler(context.Background(), commander.NewOutbound(w.config.Tag, listener)); err != nil { newError("failed to add handler").Base(err).WriteToLog() } } func (w *WebCommander) Type() interface{} { return (*WebCommander)(nil) } func (w *WebCommander) Start() error { if err := core.RequireFeatures(w.ctx, func(cm commander.CommanderIfce, om outbound.Manager) { w.Lock() defer w.Unlock() w.cm = cm w.ohm = om go w.asyncStart() }); err != nil { return err } return nil } func (w *WebCommander) Close() error { w.Lock() defer w.Unlock() if w.server != nil { if err := w.server.Close(); err != nil { return newError("failed to close http server").Base(err) } w.server = nil } return nil } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return newWebCommander(ctx, config.(*Config)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/browserforwarder/errors.generated.go
app/browserforwarder/errors.generated.go
package browserforwarder import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/browserforwarder/forwarder.go
app/browserforwarder/forwarder.go
package browserforwarder import ( "bytes" "context" "io" "net/http" "strings" "time" "github.com/v2fly/BrowserBridge/handler" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/platform/securedload" "github.com/v2fly/v2ray-core/v5/features/extension" "github.com/v2fly/v2ray-core/v5/transport/internet" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type Forwarder struct { ctx context.Context forwarder *handler.HTTPHandle httpserver *http.Server config *Config } func (f *Forwarder) ServeHTTP(writer http.ResponseWriter, request *http.Request) { requestPath := request.URL.Path[1:] switch requestPath { case "": fallthrough case "index.js": BridgeResource(writer, request, requestPath) case "link": f.forwarder.ServeBridge(writer, request) } } func (f *Forwarder) DialWebsocket(url string, header http.Header) (io.ReadWriteCloser, error) { protocolHeader := false protocolHeaderValue := "" unsupportedHeader := false for k, v := range header { if k == "Sec-Websocket-Protocol" { protocolHeader = true protocolHeaderValue = v[0] } else { unsupportedHeader = true } } if unsupportedHeader { return nil, newError("unsupported header used, only Sec-Websocket-Protocol is supported for forwarder") } if !protocolHeader { return f.forwarder.Dial(url) } return f.forwarder.Dial2(url, protocolHeaderValue) } func (f *Forwarder) Type() interface{} { return extension.BrowserForwarderType() } func (f *Forwarder) Start() error { if f.config.ListenAddr != "" { f.forwarder = handler.NewHttpHandle() f.httpserver = &http.Server{Handler: f} var listener net.Listener var err error address := net.ParseAddress(f.config.ListenAddr) switch { case address.Family().IsIP(): listener, err = internet.ListenSystem(f.ctx, &net.TCPAddr{IP: address.IP(), Port: int(f.config.ListenPort)}, nil) case strings.EqualFold(address.Domain(), "localhost"): listener, err = internet.ListenSystem(f.ctx, &net.TCPAddr{IP: net.IP{127, 0, 0, 1}, Port: int(f.config.ListenPort)}, nil) default: return newError("forwarder cannot listen on the address: ", address) } if err != nil { return newError("forwarder cannot listen on the port ", f.config.ListenPort).Base(err) } go func() { if err := f.httpserver.Serve(listener); err != nil { newError("cannot serve http forward server").Base(err).WriteToLog() } }() } return nil } func (f *Forwarder) Close() error { if f.httpserver != nil { return f.httpserver.Close() } return nil } func BridgeResource(rw http.ResponseWriter, r *http.Request, path string) { content := path if content == "" { content = "index.html" } data, err := securedload.GetAssetSecured("browserforwarder/" + content) if err != nil { err = newError("cannot load necessary resources").Base(err) http.Error(rw, err.Error(), http.StatusForbidden) return } http.ServeContent(rw, r, path, time.Now(), bytes.NewReader(data)) } func NewForwarder(ctx context.Context, cfg *Config) *Forwarder { return &Forwarder{config: cfg, ctx: ctx} } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) { return NewForwarder(ctx, cfg.(*Config)), nil })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/browserforwarder/config.pb.go
app/browserforwarder/config.pb.go
package browserforwarder import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Config is the settings for BrowserForwarder. type Config struct { state protoimpl.MessageState `protogen:"open.v1"` ListenAddr string `protobuf:"bytes,1,opt,name=listen_addr,json=listenAddr,proto3" json:"listen_addr,omitempty"` ListenPort int32 `protobuf:"varint,2,opt,name=listen_port,json=listenPort,proto3" json:"listen_port,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_browserforwarder_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_browserforwarder_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_browserforwarder_config_proto_rawDescGZIP(), []int{0} } func (x *Config) GetListenAddr() string { if x != nil { return x.ListenAddr } return "" } func (x *Config) GetListenPort() int32 { if x != nil { return x.ListenPort } return 0 } var File_app_browserforwarder_config_proto protoreflect.FileDescriptor const file_app_browserforwarder_config_proto_rawDesc = "" + "\n" + "!app/browserforwarder/config.proto\x12\x1fv2ray.core.app.browserforwarder\x1a common/protoext/extensions.proto\"b\n" + "\x06Config\x12\x1f\n" + "\vlisten_addr\x18\x01 \x01(\tR\n" + "listenAddr\x12\x1f\n" + "\vlisten_port\x18\x02 \x01(\x05R\n" + "listenPort:\x16\x82\xb5\x18\x12\n" + "\aservice\x12\abrowserB~\n" + "#com.v2ray.core.app.browserforwarderP\x01Z3github.com/v2fly/v2ray-core/v5/app/browserforwarder\xaa\x02\x1fV2Ray.Core.App.Browserforwarderb\x06proto3" var ( file_app_browserforwarder_config_proto_rawDescOnce sync.Once file_app_browserforwarder_config_proto_rawDescData []byte ) func file_app_browserforwarder_config_proto_rawDescGZIP() []byte { file_app_browserforwarder_config_proto_rawDescOnce.Do(func() { file_app_browserforwarder_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_browserforwarder_config_proto_rawDesc), len(file_app_browserforwarder_config_proto_rawDesc))) }) return file_app_browserforwarder_config_proto_rawDescData } var file_app_browserforwarder_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_app_browserforwarder_config_proto_goTypes = []any{ (*Config)(nil), // 0: v2ray.core.app.browserforwarder.Config } var file_app_browserforwarder_config_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_app_browserforwarder_config_proto_init() } func file_app_browserforwarder_config_proto_init() { if File_app_browserforwarder_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_browserforwarder_config_proto_rawDesc), len(file_app_browserforwarder_config_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_browserforwarder_config_proto_goTypes, DependencyIndexes: file_app_browserforwarder_config_proto_depIdxs, MessageInfos: file_app_browserforwarder_config_proto_msgTypes, }.Build() File_app_browserforwarder_config_proto = out.File file_app_browserforwarder_config_proto_goTypes = nil file_app_browserforwarder_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/manager_test.go
app/policy/manager_test.go
package policy_test import ( "context" "testing" "time" . "github.com/v2fly/v2ray-core/v5/app/policy" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features/policy" ) func TestPolicy(t *testing.T) { manager, err := New(context.Background(), &Config{ Level: map[uint32]*Policy{ 0: { Timeout: &Policy_Timeout{ Handshake: &Second{ Value: 2, }, }, }, }, }) common.Must(err) pDefault := policy.SessionDefault() { p := manager.ForLevel(0) if p.Timeouts.Handshake != 2*time.Second { t.Error("expect 2 sec timeout, but got ", p.Timeouts.Handshake) } if p.Timeouts.ConnectionIdle != pDefault.Timeouts.ConnectionIdle { t.Error("expect ", pDefault.Timeouts.ConnectionIdle, " sec timeout, but got ", p.Timeouts.ConnectionIdle) } } { p := manager.ForLevel(1) if p.Timeouts.Handshake != pDefault.Timeouts.Handshake { t.Error("expect ", pDefault.Timeouts.Handshake, " sec timeout, but got ", p.Timeouts.Handshake) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/policy.go
app/policy/policy.go
// Package policy is an implementation of policy.Manager feature. package policy //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/errors.generated.go
app/policy/errors.generated.go
package policy import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/config.go
app/policy/config.go
package policy import ( "time" "github.com/v2fly/v2ray-core/v5/features/policy" ) // Duration converts Second to time.Duration. func (s *Second) Duration() time.Duration { if s == nil { return 0 } return time.Second * time.Duration(s.Value) } func defaultPolicy() *Policy { p := policy.SessionDefault() return &Policy{ Timeout: &Policy_Timeout{ Handshake: &Second{Value: uint32(p.Timeouts.Handshake / time.Second)}, ConnectionIdle: &Second{Value: uint32(p.Timeouts.ConnectionIdle / time.Second)}, UplinkOnly: &Second{Value: uint32(p.Timeouts.UplinkOnly / time.Second)}, DownlinkOnly: &Second{Value: uint32(p.Timeouts.DownlinkOnly / time.Second)}, }, Buffer: &Policy_Buffer{ Connection: p.Buffer.PerConnection, }, } } func (p *Policy_Timeout) overrideWith(another *Policy_Timeout) { if another.Handshake != nil { p.Handshake = &Second{Value: another.Handshake.Value} } if another.ConnectionIdle != nil { p.ConnectionIdle = &Second{Value: another.ConnectionIdle.Value} } if another.UplinkOnly != nil { p.UplinkOnly = &Second{Value: another.UplinkOnly.Value} } if another.DownlinkOnly != nil { p.DownlinkOnly = &Second{Value: another.DownlinkOnly.Value} } } func (p *Policy) overrideWith(another *Policy) { if another.Timeout != nil { p.Timeout.overrideWith(another.Timeout) } if another.Stats != nil && p.Stats == nil { p.Stats = &Policy_Stats{} p.Stats = another.Stats } if another.Buffer != nil { p.Buffer = &Policy_Buffer{ Connection: another.Buffer.Connection, } } } // ToCorePolicy converts this Policy to policy.Session. func (p *Policy) ToCorePolicy() policy.Session { cp := policy.SessionDefault() if p.Timeout != nil { cp.Timeouts.ConnectionIdle = p.Timeout.ConnectionIdle.Duration() cp.Timeouts.Handshake = p.Timeout.Handshake.Duration() cp.Timeouts.DownlinkOnly = p.Timeout.DownlinkOnly.Duration() cp.Timeouts.UplinkOnly = p.Timeout.UplinkOnly.Duration() } if p.Stats != nil { cp.Stats.UserUplink = p.Stats.UserUplink cp.Stats.UserDownlink = p.Stats.UserDownlink } if p.Buffer != nil { cp.Buffer.PerConnection = p.Buffer.Connection } return cp } // ToCorePolicy converts this SystemPolicy to policy.System. func (p *SystemPolicy) ToCorePolicy() policy.System { return policy.System{ Stats: policy.SystemStats{ InboundUplink: p.Stats.InboundUplink, InboundDownlink: p.Stats.InboundDownlink, OutboundUplink: p.Stats.OutboundUplink, OutboundDownlink: p.Stats.OutboundDownlink, }, OverrideAccessLogDest: p.OverrideAccessLogDest, } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/config.pb.go
app/policy/config.pb.go
package policy import ( _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Second struct { state protoimpl.MessageState `protogen:"open.v1"` Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Second) Reset() { *x = Second{} mi := &file_app_policy_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Second) String() string { return protoimpl.X.MessageStringOf(x) } func (*Second) ProtoMessage() {} func (x *Second) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Second.ProtoReflect.Descriptor instead. func (*Second) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{0} } func (x *Second) GetValue() uint32 { if x != nil { return x.Value } return 0 } type Policy struct { state protoimpl.MessageState `protogen:"open.v1"` Timeout *Policy_Timeout `protobuf:"bytes,1,opt,name=timeout,proto3" json:"timeout,omitempty"` Stats *Policy_Stats `protobuf:"bytes,2,opt,name=stats,proto3" json:"stats,omitempty"` Buffer *Policy_Buffer `protobuf:"bytes,3,opt,name=buffer,proto3" json:"buffer,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Policy) Reset() { *x = Policy{} mi := &file_app_policy_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Policy) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy) ProtoMessage() {} func (x *Policy) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy.ProtoReflect.Descriptor instead. func (*Policy) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{1} } func (x *Policy) GetTimeout() *Policy_Timeout { if x != nil { return x.Timeout } return nil } func (x *Policy) GetStats() *Policy_Stats { if x != nil { return x.Stats } return nil } func (x *Policy) GetBuffer() *Policy_Buffer { if x != nil { return x.Buffer } return nil } type SystemPolicy struct { state protoimpl.MessageState `protogen:"open.v1"` Stats *SystemPolicy_Stats `protobuf:"bytes,1,opt,name=stats,proto3" json:"stats,omitempty"` OverrideAccessLogDest bool `protobuf:"varint,2,opt,name=override_access_log_dest,json=overrideAccessLogDest,proto3" json:"override_access_log_dest,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SystemPolicy) Reset() { *x = SystemPolicy{} mi := &file_app_policy_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SystemPolicy) String() string { return protoimpl.X.MessageStringOf(x) } func (*SystemPolicy) ProtoMessage() {} func (x *SystemPolicy) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SystemPolicy.ProtoReflect.Descriptor instead. func (*SystemPolicy) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{2} } func (x *SystemPolicy) GetStats() *SystemPolicy_Stats { if x != nil { return x.Stats } return nil } func (x *SystemPolicy) GetOverrideAccessLogDest() bool { if x != nil { return x.OverrideAccessLogDest } return false } type Config struct { state protoimpl.MessageState `protogen:"open.v1"` Level map[uint32]*Policy `protobuf:"bytes,1,rep,name=level,proto3" json:"level,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` System *SystemPolicy `protobuf:"bytes,2,opt,name=system,proto3" json:"system,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} mi := &file_app_policy_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{3} } func (x *Config) GetLevel() map[uint32]*Policy { if x != nil { return x.Level } return nil } func (x *Config) GetSystem() *SystemPolicy { if x != nil { return x.System } return nil } // Timeout is a message for timeout settings in various stages, in seconds. type Policy_Timeout struct { state protoimpl.MessageState `protogen:"open.v1"` Handshake *Second `protobuf:"bytes,1,opt,name=handshake,proto3" json:"handshake,omitempty"` ConnectionIdle *Second `protobuf:"bytes,2,opt,name=connection_idle,json=connectionIdle,proto3" json:"connection_idle,omitempty"` UplinkOnly *Second `protobuf:"bytes,3,opt,name=uplink_only,json=uplinkOnly,proto3" json:"uplink_only,omitempty"` DownlinkOnly *Second `protobuf:"bytes,4,opt,name=downlink_only,json=downlinkOnly,proto3" json:"downlink_only,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Policy_Timeout) Reset() { *x = Policy_Timeout{} mi := &file_app_policy_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Policy_Timeout) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy_Timeout) ProtoMessage() {} func (x *Policy_Timeout) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy_Timeout.ProtoReflect.Descriptor instead. func (*Policy_Timeout) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{1, 0} } func (x *Policy_Timeout) GetHandshake() *Second { if x != nil { return x.Handshake } return nil } func (x *Policy_Timeout) GetConnectionIdle() *Second { if x != nil { return x.ConnectionIdle } return nil } func (x *Policy_Timeout) GetUplinkOnly() *Second { if x != nil { return x.UplinkOnly } return nil } func (x *Policy_Timeout) GetDownlinkOnly() *Second { if x != nil { return x.DownlinkOnly } return nil } type Policy_Stats struct { state protoimpl.MessageState `protogen:"open.v1"` UserUplink bool `protobuf:"varint,1,opt,name=user_uplink,json=userUplink,proto3" json:"user_uplink,omitempty"` UserDownlink bool `protobuf:"varint,2,opt,name=user_downlink,json=userDownlink,proto3" json:"user_downlink,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Policy_Stats) Reset() { *x = Policy_Stats{} mi := &file_app_policy_config_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Policy_Stats) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy_Stats) ProtoMessage() {} func (x *Policy_Stats) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy_Stats.ProtoReflect.Descriptor instead. func (*Policy_Stats) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{1, 1} } func (x *Policy_Stats) GetUserUplink() bool { if x != nil { return x.UserUplink } return false } func (x *Policy_Stats) GetUserDownlink() bool { if x != nil { return x.UserDownlink } return false } type Policy_Buffer struct { state protoimpl.MessageState `protogen:"open.v1"` // Buffer size per connection, in bytes. -1 for unlimited buffer. Connection int32 `protobuf:"varint,1,opt,name=connection,proto3" json:"connection,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Policy_Buffer) Reset() { *x = Policy_Buffer{} mi := &file_app_policy_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Policy_Buffer) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy_Buffer) ProtoMessage() {} func (x *Policy_Buffer) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy_Buffer.ProtoReflect.Descriptor instead. func (*Policy_Buffer) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{1, 2} } func (x *Policy_Buffer) GetConnection() int32 { if x != nil { return x.Connection } return 0 } type SystemPolicy_Stats struct { state protoimpl.MessageState `protogen:"open.v1"` InboundUplink bool `protobuf:"varint,1,opt,name=inbound_uplink,json=inboundUplink,proto3" json:"inbound_uplink,omitempty"` InboundDownlink bool `protobuf:"varint,2,opt,name=inbound_downlink,json=inboundDownlink,proto3" json:"inbound_downlink,omitempty"` OutboundUplink bool `protobuf:"varint,3,opt,name=outbound_uplink,json=outboundUplink,proto3" json:"outbound_uplink,omitempty"` OutboundDownlink bool `protobuf:"varint,4,opt,name=outbound_downlink,json=outboundDownlink,proto3" json:"outbound_downlink,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SystemPolicy_Stats) Reset() { *x = SystemPolicy_Stats{} mi := &file_app_policy_config_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SystemPolicy_Stats) String() string { return protoimpl.X.MessageStringOf(x) } func (*SystemPolicy_Stats) ProtoMessage() {} func (x *SystemPolicy_Stats) ProtoReflect() protoreflect.Message { mi := &file_app_policy_config_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SystemPolicy_Stats.ProtoReflect.Descriptor instead. func (*SystemPolicy_Stats) Descriptor() ([]byte, []int) { return file_app_policy_config_proto_rawDescGZIP(), []int{2, 0} } func (x *SystemPolicy_Stats) GetInboundUplink() bool { if x != nil { return x.InboundUplink } return false } func (x *SystemPolicy_Stats) GetInboundDownlink() bool { if x != nil { return x.InboundDownlink } return false } func (x *SystemPolicy_Stats) GetOutboundUplink() bool { if x != nil { return x.OutboundUplink } return false } func (x *SystemPolicy_Stats) GetOutboundDownlink() bool { if x != nil { return x.OutboundDownlink } return false } var File_app_policy_config_proto protoreflect.FileDescriptor const file_app_policy_config_proto_rawDesc = "" + "\n" + "\x17app/policy/config.proto\x12\x15v2ray.core.app.policy\x1a common/protoext/extensions.proto\"\x1e\n" + "\x06Second\x12\x14\n" + "\x05value\x18\x01 \x01(\rR\x05value\"\xd0\x04\n" + "\x06Policy\x12?\n" + "\atimeout\x18\x01 \x01(\v2%.v2ray.core.app.policy.Policy.TimeoutR\atimeout\x129\n" + "\x05stats\x18\x02 \x01(\v2#.v2ray.core.app.policy.Policy.StatsR\x05stats\x12<\n" + "\x06buffer\x18\x03 \x01(\v2$.v2ray.core.app.policy.Policy.BufferR\x06buffer\x1a\x92\x02\n" + "\aTimeout\x12;\n" + "\thandshake\x18\x01 \x01(\v2\x1d.v2ray.core.app.policy.SecondR\thandshake\x12F\n" + "\x0fconnection_idle\x18\x02 \x01(\v2\x1d.v2ray.core.app.policy.SecondR\x0econnectionIdle\x12>\n" + "\vuplink_only\x18\x03 \x01(\v2\x1d.v2ray.core.app.policy.SecondR\n" + "uplinkOnly\x12B\n" + "\rdownlink_only\x18\x04 \x01(\v2\x1d.v2ray.core.app.policy.SecondR\fdownlinkOnly\x1aM\n" + "\x05Stats\x12\x1f\n" + "\vuser_uplink\x18\x01 \x01(\bR\n" + "userUplink\x12#\n" + "\ruser_downlink\x18\x02 \x01(\bR\fuserDownlink\x1a(\n" + "\x06Buffer\x12\x1e\n" + "\n" + "connection\x18\x01 \x01(\x05R\n" + "connection\"\xba\x02\n" + "\fSystemPolicy\x12?\n" + "\x05stats\x18\x01 \x01(\v2).v2ray.core.app.policy.SystemPolicy.StatsR\x05stats\x127\n" + "\x18override_access_log_dest\x18\x02 \x01(\bR\x15overrideAccessLogDest\x1a\xaf\x01\n" + "\x05Stats\x12%\n" + "\x0einbound_uplink\x18\x01 \x01(\bR\rinboundUplink\x12)\n" + "\x10inbound_downlink\x18\x02 \x01(\bR\x0finboundDownlink\x12'\n" + "\x0foutbound_uplink\x18\x03 \x01(\bR\x0eoutboundUplink\x12+\n" + "\x11outbound_downlink\x18\x04 \x01(\bR\x10outboundDownlink\"\xf5\x01\n" + "\x06Config\x12>\n" + "\x05level\x18\x01 \x03(\v2(.v2ray.core.app.policy.Config.LevelEntryR\x05level\x12;\n" + "\x06system\x18\x02 \x01(\v2#.v2ray.core.app.policy.SystemPolicyR\x06system\x1aW\n" + "\n" + "LevelEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\rR\x03key\x123\n" + "\x05value\x18\x02 \x01(\v2\x1d.v2ray.core.app.policy.PolicyR\x05value:\x028\x01:\x15\x82\xb5\x18\x11\n" + "\aservice\x12\x06policyB`\n" + "\x19com.v2ray.core.app.policyP\x01Z)github.com/v2fly/v2ray-core/v5/app/policy\xaa\x02\x15V2Ray.Core.App.Policyb\x06proto3" var ( file_app_policy_config_proto_rawDescOnce sync.Once file_app_policy_config_proto_rawDescData []byte ) func file_app_policy_config_proto_rawDescGZIP() []byte { file_app_policy_config_proto_rawDescOnce.Do(func() { file_app_policy_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_policy_config_proto_rawDesc), len(file_app_policy_config_proto_rawDesc))) }) return file_app_policy_config_proto_rawDescData } var file_app_policy_config_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_app_policy_config_proto_goTypes = []any{ (*Second)(nil), // 0: v2ray.core.app.policy.Second (*Policy)(nil), // 1: v2ray.core.app.policy.Policy (*SystemPolicy)(nil), // 2: v2ray.core.app.policy.SystemPolicy (*Config)(nil), // 3: v2ray.core.app.policy.Config (*Policy_Timeout)(nil), // 4: v2ray.core.app.policy.Policy.Timeout (*Policy_Stats)(nil), // 5: v2ray.core.app.policy.Policy.Stats (*Policy_Buffer)(nil), // 6: v2ray.core.app.policy.Policy.Buffer (*SystemPolicy_Stats)(nil), // 7: v2ray.core.app.policy.SystemPolicy.Stats nil, // 8: v2ray.core.app.policy.Config.LevelEntry } var file_app_policy_config_proto_depIdxs = []int32{ 4, // 0: v2ray.core.app.policy.Policy.timeout:type_name -> v2ray.core.app.policy.Policy.Timeout 5, // 1: v2ray.core.app.policy.Policy.stats:type_name -> v2ray.core.app.policy.Policy.Stats 6, // 2: v2ray.core.app.policy.Policy.buffer:type_name -> v2ray.core.app.policy.Policy.Buffer 7, // 3: v2ray.core.app.policy.SystemPolicy.stats:type_name -> v2ray.core.app.policy.SystemPolicy.Stats 8, // 4: v2ray.core.app.policy.Config.level:type_name -> v2ray.core.app.policy.Config.LevelEntry 2, // 5: v2ray.core.app.policy.Config.system:type_name -> v2ray.core.app.policy.SystemPolicy 0, // 6: v2ray.core.app.policy.Policy.Timeout.handshake:type_name -> v2ray.core.app.policy.Second 0, // 7: v2ray.core.app.policy.Policy.Timeout.connection_idle:type_name -> v2ray.core.app.policy.Second 0, // 8: v2ray.core.app.policy.Policy.Timeout.uplink_only:type_name -> v2ray.core.app.policy.Second 0, // 9: v2ray.core.app.policy.Policy.Timeout.downlink_only:type_name -> v2ray.core.app.policy.Second 1, // 10: v2ray.core.app.policy.Config.LevelEntry.value:type_name -> v2ray.core.app.policy.Policy 11, // [11:11] is the sub-list for method output_type 11, // [11:11] is the sub-list for method input_type 11, // [11:11] is the sub-list for extension type_name 11, // [11:11] is the sub-list for extension extendee 0, // [0:11] is the sub-list for field type_name } func init() { file_app_policy_config_proto_init() } func file_app_policy_config_proto_init() { if File_app_policy_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_policy_config_proto_rawDesc), len(file_app_policy_config_proto_rawDesc)), NumEnums: 0, NumMessages: 9, NumExtensions: 0, NumServices: 0, }, GoTypes: file_app_policy_config_proto_goTypes, DependencyIndexes: file_app_policy_config_proto_depIdxs, MessageInfos: file_app_policy_config_proto_msgTypes, }.Build() File_app_policy_config_proto = out.File file_app_policy_config_proto_goTypes = nil file_app_policy_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/policy/manager.go
app/policy/manager.go
package policy import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/features/policy" ) // Instance is an instance of Policy manager. type Instance struct { levels map[uint32]*Policy system *SystemPolicy } // New creates new Policy manager instance. func New(ctx context.Context, config *Config) (*Instance, error) { m := &Instance{ levels: make(map[uint32]*Policy), system: config.System, } if len(config.Level) > 0 { for lv, p := range config.Level { pp := defaultPolicy() pp.overrideWith(p) m.levels[lv] = pp } } return m, nil } // Type implements common.HasType. func (*Instance) Type() interface{} { return policy.ManagerType() } // ForLevel implements policy.Manager. func (m *Instance) ForLevel(level uint32) policy.Session { if p, ok := m.levels[level]; ok { return p.ToCorePolicy() } return policy.SessionDefault() } // ForSystem implements policy.Manager. func (m *Instance) ForSystem() policy.System { if m.system == nil { return policy.System{} } return m.system.ToCorePolicy() } // Start implements common.Runnable.Start(). func (m *Instance) Start() error { return nil } // Close implements common.Closable.Close(). func (m *Instance) Close() error { return nil } func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return New(ctx, config.(*Config)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/proxy.go
proxy/proxy.go
// Package proxy contains all proxies used by V2Ray. // // To implement an inbound or outbound proxy, one needs to do the following: // 1. Implement the interface(s) below. // 2. Register a config creator through common.RegisterConfig. package proxy import ( "context" "time" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" ) // A timeout for reading the first payload from the client, used in 0-RTT optimizations. const FirstPayloadTimeout = 100 * time.Millisecond // An Inbound processes inbound connections. type Inbound interface { // Network returns a list of networks that this inbound supports. Connections with not-supported networks will not be passed into Process(). Network() []net.Network // Process processes a connection of given network. If necessary, the Inbound can dispatch the connection to an Outbound. Process(context.Context, net.Network, internet.Connection, routing.Dispatcher) error } // An Outbound process outbound connections. type Outbound interface { // Process processes the given connection. The given dialer may be used to dial a system outbound connection. Process(context.Context, *transport.Link, internet.Dialer) error } // UserManager is the interface for Inbounds and Outbounds that can manage their users. type UserManager interface { // AddUser adds a new user. AddUser(context.Context, *protocol.MemoryUser) error // RemoveUser removes a user by email. RemoveUser(context.Context, string) error } type GetInbound interface { GetInbound() Inbound } type GetOutbound interface { GetOutbound() Outbound }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/errors.generated.go
proxy/trojan/errors.generated.go
package trojan import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/client.go
proxy/trojan/client.go
package trojan import ( "context" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/retry" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/proxy" "github.com/v2fly/v2ray-core/v5/transport" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/udp" ) // Client is an inbound handler for trojan protocol type Client struct { serverPicker protocol.ServerPicker policyManager policy.Manager } // NewClient create a new trojan client. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { serverList := protocol.NewServerList() for _, rec := range config.Server { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { return nil, newError("failed to parse server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { return nil, newError("0 server") } v := core.MustFromContext(ctx) client := &Client{ serverPicker: protocol.NewRoundRobinServerPicker(serverList), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), } return client, nil } // Process implements OutboundHandler.Process(). func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbound := session.OutboundFromContext(ctx) if outbound == nil || !outbound.Target.IsValid() { return newError("target not specified") } destination := outbound.Target network := destination.Network var server *protocol.ServerSpec var conn internet.Connection err := retry.ExponentialBackoff(5, 100).On(func() error { server = c.serverPicker.PickServer() rawConn, err := dialer.Dial(ctx, server.Destination()) if err != nil { return err } conn = rawConn return nil }) if err != nil { return newError("failed to find an available destination").AtWarning().Base(err) } newError("tunneling request to ", destination, " via ", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx)) defer conn.Close() user := server.PickUser() account, ok := user.Account.(*MemoryAccount) if !ok { return newError("user account is not valid") } sessionPolicy := c.policyManager.ForLevel(user.Level) ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil { postRequest := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) var buffer [2048]byte n, addr, err := packetConn.ReadFrom(buffer[:]) if err != nil { return newError("failed to read a packet").Base(err) } dest := net.DestinationFromAddr(addr) bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) connWriter := &ConnWriter{Writer: bufferWriter, Target: dest, Account: account} packetWriter := &PacketWriter{Writer: connWriter, Target: dest} // write some request payload to buffer if _, err := packetWriter.WriteTo(buffer[:n], addr); err != nil { return newError("failed to write a request payload").Base(err) } // Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer if err = bufferWriter.SetBuffered(false); err != nil { return newError("failed to flush payload").Base(err).AtWarning() } return udp.CopyPacketConn(packetWriter, packetConn, udp.UpdateActivity(timer)) } getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) packetReader := &PacketReader{Reader: conn} packetConnectionReader := &PacketConnectionReader{reader: packetReader} return udp.CopyPacketConn(packetConn, packetConnectionReader, udp.UpdateActivity(timer)) } responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer)) if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { return newError("connection ends").Base(err) } return nil } postRequest := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) var bodyWriter buf.Writer bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) connWriter := &ConnWriter{Writer: bufferWriter, Target: destination, Account: account} if destination.Network == net.Network_UDP { bodyWriter = &PacketWriter{Writer: connWriter, Target: destination} } else { bodyWriter = connWriter } // write some request payload to buffer err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout) switch err { case buf.ErrNotTimeoutReader, buf.ErrReadTimeout: if err := connWriter.WriteHeader(); err != nil { return newError("failed to write request header").Base(err).AtWarning() } case nil: default: return newError("failed to write a request payload").Base(err).AtWarning() } // Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer if err = bufferWriter.SetBuffered(false); err != nil { return newError("failed to flush payload").Base(err).AtWarning() } if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer request payload").Base(err).AtInfo() } return nil } getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) var reader buf.Reader if network == net.Network_UDP { reader = &PacketReader{ Reader: conn, } } else { reader = buf.NewReader(conn) } return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) } responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer)) if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { return newError("connection ends").Base(err) } return nil } func init() { common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewClient(ctx, config.(*ClientConfig)) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/config.go
proxy/trojan/config.go
package trojan import ( "crypto/sha256" "encoding/hex" "fmt" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/protocol" ) // MemoryAccount is an account type converted from Account. type MemoryAccount struct { Password string Key []byte } // AsAccount implements protocol.AsAccount. func (a *Account) AsAccount() (protocol.Account, error) { password := a.GetPassword() key := hexSha224(password) return &MemoryAccount{ Password: password, Key: key, }, nil } // Equals implements protocol.Account.Equals(). func (a *MemoryAccount) Equals(another protocol.Account) bool { if account, ok := another.(*MemoryAccount); ok { return a.Password == account.Password } return false } func hexSha224(password string) []byte { buf := make([]byte, 56) hash := sha256.New224() common.Must2(hash.Write([]byte(password))) hex.Encode(buf, hash.Sum(nil)) return buf } func hexString(data []byte) string { str := "" for _, v := range data { str += fmt.Sprintf("%02x", v) } return str }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/protocol.go
proxy/trojan/protocol.go
package trojan import ( "encoding/binary" "io" gonet "net" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" ) var ( crlf = []byte{'\r', '\n'} addrParser = protocol.NewAddressParser( protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4), protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6), protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain), ) ) const ( commandTCP byte = 1 commandUDP byte = 3 ) // ConnWriter is TCP Connection Writer Wrapper for trojan protocol type ConnWriter struct { io.Writer Target net.Destination Account *MemoryAccount headerSent bool } // Write implements io.Writer func (c *ConnWriter) Write(p []byte) (n int, err error) { if !c.headerSent { if err := c.writeHeader(); err != nil { return 0, newError("failed to write request header").Base(err) } } return c.Writer.Write(p) } // WriteMultiBuffer implements buf.Writer func (c *ConnWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { defer buf.ReleaseMulti(mb) for _, b := range mb { if !b.IsEmpty() { if _, err := c.Write(b.Bytes()); err != nil { return err } } } return nil } func (c *ConnWriter) WriteHeader() error { if !c.headerSent { if err := c.writeHeader(); err != nil { return err } } return nil } func (c *ConnWriter) writeHeader() error { buffer := buf.StackNew() defer buffer.Release() command := commandTCP if c.Target.Network == net.Network_UDP { command = commandUDP } if _, err := buffer.Write(c.Account.Key); err != nil { return err } if _, err := buffer.Write(crlf); err != nil { return err } if err := buffer.WriteByte(command); err != nil { return err } if err := addrParser.WriteAddressPort(&buffer, c.Target.Address, c.Target.Port); err != nil { return err } if _, err := buffer.Write(crlf); err != nil { return err } _, err := c.Writer.Write(buffer.Bytes()) if err == nil { c.headerSent = true } return err } // PacketWriter UDP Connection Writer Wrapper for trojan protocol type PacketWriter struct { io.Writer Target net.Destination } // WriteMultiBuffer implements buf.Writer func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { for _, b := range mb { if b.IsEmpty() { continue } if _, err := w.writePacket(b.Bytes(), w.Target); err != nil { buf.ReleaseMulti(mb) return err } } return nil } // WriteMultiBufferWithMetadata writes udp packet with destination specified func (w *PacketWriter) WriteMultiBufferWithMetadata(mb buf.MultiBuffer, dest net.Destination) error { for _, b := range mb { if b.IsEmpty() { continue } if _, err := w.writePacket(b.Bytes(), dest); err != nil { buf.ReleaseMulti(mb) return err } } return nil } func (w *PacketWriter) WriteTo(payload []byte, addr gonet.Addr) (int, error) { dest := net.DestinationFromAddr(addr) return w.writePacket(payload, dest) } func (w *PacketWriter) writePacket(payload []byte, dest net.Destination) (int, error) { // nolint: unparam var addrPortLen int32 switch dest.Address.Family() { case net.AddressFamilyDomain: if protocol.IsDomainTooLong(dest.Address.Domain()) { return 0, newError("Super long domain is not supported: ", dest.Address.Domain()) } addrPortLen = 1 + 1 + int32(len(dest.Address.Domain())) + 2 case net.AddressFamilyIPv4: addrPortLen = 1 + 4 + 2 case net.AddressFamilyIPv6: addrPortLen = 1 + 16 + 2 default: panic("Unknown address type.") } length := len(payload) lengthBuf := [2]byte{} binary.BigEndian.PutUint16(lengthBuf[:], uint16(length)) buffer := buf.NewWithSize(addrPortLen + 2 + 2 + int32(length)) defer buffer.Release() if err := addrParser.WriteAddressPort(buffer, dest.Address, dest.Port); err != nil { return 0, err } if _, err := buffer.Write(lengthBuf[:]); err != nil { return 0, err } if _, err := buffer.Write(crlf); err != nil { return 0, err } if _, err := buffer.Write(payload); err != nil { return 0, err } _, err := w.Write(buffer.Bytes()) if err != nil { return 0, err } return length, nil } // ConnReader is TCP Connection Reader Wrapper for trojan protocol type ConnReader struct { io.Reader Target net.Destination headerParsed bool } // ParseHeader parses the trojan protocol header func (c *ConnReader) ParseHeader() error { var crlf [2]byte var command [1]byte var hash [56]byte if _, err := io.ReadFull(c.Reader, hash[:]); err != nil { return newError("failed to read user hash").Base(err) } if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil { return newError("failed to read crlf").Base(err) } if _, err := io.ReadFull(c.Reader, command[:]); err != nil { return newError("failed to read command").Base(err) } network := net.Network_TCP if command[0] == commandUDP { network = net.Network_UDP } addr, port, err := addrParser.ReadAddressPort(nil, c.Reader) if err != nil { return newError("failed to read address and port").Base(err) } c.Target = net.Destination{Network: network, Address: addr, Port: port} if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil { return newError("failed to read crlf").Base(err) } c.headerParsed = true return nil } // Read implements io.Reader func (c *ConnReader) Read(p []byte) (int, error) { if !c.headerParsed { if err := c.ParseHeader(); err != nil { return 0, err } } return c.Reader.Read(p) } // ReadMultiBuffer implements buf.Reader func (c *ConnReader) ReadMultiBuffer() (buf.MultiBuffer, error) { b := buf.New() _, err := b.ReadFrom(c) return buf.MultiBuffer{b}, err } // PacketPayload combines udp payload and destination type PacketPayload struct { Target net.Destination Buffer buf.MultiBuffer } // PacketReader is UDP Connection Reader Wrapper for trojan protocol type PacketReader struct { io.Reader } // ReadMultiBuffer implements buf.Reader func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { p, err := r.ReadMultiBufferWithMetadata() if p != nil { return p.Buffer, err } return nil, err } // ReadMultiBufferWithMetadata reads udp packet with destination func (r *PacketReader) ReadMultiBufferWithMetadata() (*PacketPayload, error) { addr, port, err := addrParser.ReadAddressPort(nil, r) if err != nil { return nil, newError("failed to read address and port").Base(err) } var lengthBuf [2]byte if _, err := io.ReadFull(r, lengthBuf[:]); err != nil { return nil, newError("failed to read payload length").Base(err) } length := binary.BigEndian.Uint16(lengthBuf[:]) var crlf [2]byte if _, err := io.ReadFull(r, crlf[:]); err != nil { return nil, newError("failed to read crlf").Base(err) } dest := net.UDPDestination(addr, port) b := buf.NewWithSize(int32(length)) _, err = b.ReadFullFrom(r, int32(length)) if err != nil { return nil, newError("failed to read payload").Base(err) } return &PacketPayload{Target: dest, Buffer: buf.MultiBuffer{b}}, nil } type PacketConnectionReader struct { reader *PacketReader payload *PacketPayload } func (r *PacketConnectionReader) ReadFrom(p []byte) (n int, addr gonet.Addr, err error) { if r.payload == nil || r.payload.Buffer.IsEmpty() { r.payload, err = r.reader.ReadMultiBufferWithMetadata() if err != nil { return } } addr = &gonet.UDPAddr{ IP: r.payload.Target.Address.IP(), Port: int(r.payload.Target.Port), } r.payload.Buffer, n = buf.SplitFirstBytes(r.payload.Buffer, p) return }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/validator.go
proxy/trojan/validator.go
package trojan import ( "strings" "sync" "github.com/v2fly/v2ray-core/v5/common/protocol" ) // Validator stores valid trojan users. type Validator struct { // Considering email's usage here, map + sync.Mutex/RWMutex may have better performance. email sync.Map users sync.Map } // Add a trojan user, Email must be empty or unique. func (v *Validator) Add(u *protocol.MemoryUser) error { if u.Email != "" { _, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u) if loaded { return newError("User ", u.Email, " already exists.") } } v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u) return nil } // Del a trojan user with a non-empty Email. func (v *Validator) Del(e string) error { if e == "" { return newError("Email must not be empty.") } le := strings.ToLower(e) u, _ := v.email.Load(le) if u == nil { return newError("User ", e, " not found.") } v.email.Delete(le) v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key)) return nil } // Get a trojan user with hashed key, nil if user doesn't exist. func (v *Validator) Get(hash string) *protocol.MemoryUser { u, _ := v.users.Load(hash) if u != nil { return u.(*protocol.MemoryUser) } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/protocol_test.go
proxy/trojan/protocol_test.go
package trojan_test import ( "crypto/rand" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/protocol" . "github.com/v2fly/v2ray-core/v5/proxy/trojan" ) func toAccount(a *Account) protocol.Account { account, err := a.AsAccount() common.Must(err) return account } func TestTCPRequest(t *testing.T) { user := &protocol.MemoryUser{ Email: "love@v2fly.org", Account: toAccount(&Account{ Password: "password", }), } payload := []byte("test string") data := buf.New() common.Must2(data.Write(payload)) buffer := buf.New() defer buffer.Release() destination := net.Destination{Network: net.Network_TCP, Address: net.LocalHostIP, Port: 1234} writer := &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)} common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data})) reader := &ConnReader{Reader: buffer} common.Must(reader.ParseHeader()) if r := cmp.Diff(reader.Target, destination); r != "" { t.Error("destination: ", r) } decodedData, err := reader.ReadMultiBuffer() common.Must(err) if r := cmp.Diff(decodedData[0].Bytes(), payload); r != "" { t.Error("data: ", r) } } func TestUDPRequest(t *testing.T) { user := &protocol.MemoryUser{ Email: "love@v2fly.org", Account: toAccount(&Account{ Password: "password", }), } payload := []byte("test string") data := buf.New() common.Must2(data.Write(payload)) buffer := buf.New() defer buffer.Release() destination := net.Destination{Network: net.Network_UDP, Address: net.LocalHostIP, Port: 1234} writer := &PacketWriter{Writer: &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)}, Target: destination} common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data})) connReader := &ConnReader{Reader: buffer} common.Must(connReader.ParseHeader()) packetReader := &PacketReader{Reader: connReader} p, err := packetReader.ReadMultiBufferWithMetadata() common.Must(err) if p.Buffer.IsEmpty() { t.Error("no request data") } if r := cmp.Diff(p.Target, destination); r != "" { t.Error("destination: ", r) } mb, decoded := buf.SplitFirst(p.Buffer) buf.ReleaseMulti(mb) if r := cmp.Diff(decoded.Bytes(), payload); r != "" { t.Error("data: ", r) } } func TestLargeUDPRequest(t *testing.T) { user := &protocol.MemoryUser{ Email: "love@v2fly.org", Account: toAccount(&Account{ Password: "password", }), } payload := make([]byte, 4096) common.Must2(rand.Read(payload)) data := buf.NewWithSize(int32(len(payload))) common.Must2(data.Write(payload)) buffer := buf.NewWithSize(2*data.Len() + 1) defer buffer.Release() destination := net.Destination{Network: net.Network_UDP, Address: net.LocalHostIP, Port: 1234} writer := &PacketWriter{Writer: &ConnWriter{Writer: buffer, Target: destination, Account: user.Account.(*MemoryAccount)}, Target: destination} common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data, data})) connReader := &ConnReader{Reader: buffer} common.Must(connReader.ParseHeader()) packetReader := &PacketReader{Reader: connReader} for i := 0; i < 2; i++ { p, err := packetReader.ReadMultiBufferWithMetadata() common.Must(err) if p.Buffer.IsEmpty() { t.Error("no request data") } if r := cmp.Diff(p.Target, destination); r != "" { t.Error("destination: ", r) } mb, decoded := buf.SplitFirst(p.Buffer) buf.ReleaseMulti(mb) if r := cmp.Diff(decoded.Bytes(), payload); r != "" { t.Error("data: ", r) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/server.go
proxy/trojan/server.go
package trojan import ( "context" "io" "strconv" "time" core "github.com/v2fly/v2ray-core/v5" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/log" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" "github.com/v2fly/v2ray-core/v5/common/protocol" udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp" "github.com/v2fly/v2ray-core/v5/common/retry" "github.com/v2fly/v2ray-core/v5/common/session" "github.com/v2fly/v2ray-core/v5/common/signal" "github.com/v2fly/v2ray-core/v5/common/task" "github.com/v2fly/v2ray-core/v5/features/policy" "github.com/v2fly/v2ray-core/v5/features/routing" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/v2fly/v2ray-core/v5/transport/internet/tls" "github.com/v2fly/v2ray-core/v5/transport/internet/udp" ) func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { return NewServer(ctx, config.(*ServerConfig)) })) } // Server is an inbound connection handler that handles messages in trojan protocol. type Server struct { policyManager policy.Manager validator *Validator fallbacks map[string]map[string]*Fallback // or nil packetEncoding packetaddr.PacketAddrType } // NewServer creates a new trojan inbound handler. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { validator := new(Validator) for _, user := range config.Users { u, err := user.ToMemoryUser() if err != nil { return nil, newError("failed to get trojan user").Base(err).AtError() } if err := validator.Add(u); err != nil { return nil, newError("failed to add user").Base(err).AtError() } } v := core.MustFromContext(ctx) server := &Server{ policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), validator: validator, packetEncoding: config.PacketEncoding, } if config.Fallbacks != nil { server.fallbacks = make(map[string]map[string]*Fallback) for _, fb := range config.Fallbacks { if server.fallbacks[fb.Alpn] == nil { server.fallbacks[fb.Alpn] = make(map[string]*Fallback) } server.fallbacks[fb.Alpn][fb.Path] = fb } if server.fallbacks[""] != nil { for alpn, pfb := range server.fallbacks { if alpn != "" { // && alpn != "h2" { for path, fb := range server.fallbacks[""] { if pfb[path] == nil { pfb[path] = fb } } } } } } return server, nil } // AddUser implements proxy.UserManager.AddUser(). func (s *Server) AddUser(ctx context.Context, u *protocol.MemoryUser) error { return s.validator.Add(u) } // RemoveUser implements proxy.UserManager.RemoveUser(). func (s *Server) RemoveUser(ctx context.Context, e string) error { return s.validator.Del(e) } // Network implements proxy.Inbound.Network(). func (s *Server) Network() []net.Network { return []net.Network{net.Network_TCP, net.Network_UNIX} } // Process implements proxy.Inbound.Process(). func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { sid := session.ExportIDToError(ctx) iConn := conn if statConn, ok := iConn.(*internet.StatCouterConnection); ok { iConn = statConn.Connection } sessionPolicy := s.policyManager.ForLevel(0) if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { return newError("unable to set read deadline").Base(err).AtWarning() } first := buf.New() defer first.Release() firstLen, err := first.ReadFrom(conn) if err != nil { return newError("failed to read first request").Base(err) } newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid) bufferedReader := &buf.BufferedReader{ Reader: buf.NewReader(conn), Buffer: buf.MultiBuffer{first}, } var user *protocol.MemoryUser apfb := s.fallbacks isfb := apfb != nil shouldFallback := false if firstLen < 58 || first.Byte(56) != '\r' { // invalid protocol err = newError("not trojan protocol") log.Record(&log.AccessMessage{ From: conn.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: err, }) shouldFallback = true } else { user = s.validator.Get(hexString(first.BytesTo(56))) if user == nil { // invalid user, let's fallback err = newError("not a valid user") log.Record(&log.AccessMessage{ From: conn.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: err, }) shouldFallback = true } } if isfb && shouldFallback { return s.fallback(ctx, sid, err, sessionPolicy, conn, iConn, apfb, first, firstLen, bufferedReader) } else if shouldFallback { return newError("invalid protocol or invalid user") } clientReader := &ConnReader{Reader: bufferedReader} if err := clientReader.ParseHeader(); err != nil { log.Record(&log.AccessMessage{ From: conn.RemoteAddr(), To: "", Status: log.AccessRejected, Reason: err, }) return newError("failed to create request from: ", conn.RemoteAddr()).Base(err) } destination := clientReader.Target if err := conn.SetReadDeadline(time.Time{}); err != nil { return newError("unable to set read deadline").Base(err).AtWarning() } inbound := session.InboundFromContext(ctx) if inbound == nil { panic("no inbound metadata") } inbound.User = user sessionPolicy = s.policyManager.ForLevel(user.Level) if destination.Network == net.Network_UDP { // handle udp request return s.handleUDPPayload(ctx, &PacketReader{Reader: clientReader}, &PacketWriter{Writer: conn}, dispatcher) } ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: conn.RemoteAddr(), To: destination, Status: log.AccessAccepted, Reason: "", Email: user.Email, }) newError("received request for ", destination).WriteToLog(sid) return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher) } func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReader, clientWriter *PacketWriter, dispatcher routing.Dispatcher) error { udpDispatcherConstructor := udp.NewSplitDispatcher switch s.packetEncoding { case packetaddr.PacketAddrType_None: case packetaddr.PacketAddrType_Packet: packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx) udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher } udpServer := udpDispatcherConstructor(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) { if err := clientWriter.WriteMultiBufferWithMetadata(buf.MultiBuffer{packet.Payload}, packet.Source); err != nil { newError("failed to write response").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) } }) inbound := session.InboundFromContext(ctx) user := inbound.User for { select { case <-ctx.Done(): return nil default: p, err := clientReader.ReadMultiBufferWithMetadata() if err != nil { if errors.Cause(err) != io.EOF { return newError("unexpected EOF").Base(err) } return nil } currentPacketCtx := ctx currentPacketCtx = log.ContextWithAccessMessage(currentPacketCtx, &log.AccessMessage{ From: inbound.Source, To: p.Target, Status: log.AccessAccepted, Reason: "", Email: user.Email, }) newError("tunnelling request to ", p.Target).WriteToLog(session.ExportIDToError(ctx)) for _, b := range p.Buffer { udpServer.Dispatch(currentPacketCtx, p.Target, b) } } } } func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Session, destination net.Destination, clientReader buf.Reader, clientWriter buf.Writer, dispatcher routing.Dispatcher, ) error { ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) link, err := dispatcher.Dispatch(ctx, destination) if err != nil { return newError("failed to dispatch request to ", destination).Base(err) } requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if err := buf.Copy(clientReader, link.Writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to transfer request").Base(err) } return nil } responseDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to write response").Base(err) } return nil } requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Must(common.Interrupt(link.Reader)) common.Must(common.Interrupt(link.Writer)) return newError("connection ends").Base(err) } return nil } func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err error, sessionPolicy policy.Session, connection internet.Connection, iConn internet.Connection, apfb map[string]map[string]*Fallback, first *buf.Buffer, firstLen int64, reader buf.Reader) error { if err := connection.SetReadDeadline(time.Time{}); err != nil { newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid) } newError("fallback starts").Base(err).AtInfo().WriteToLog(sid) alpn := "" if len(apfb) > 1 || apfb[""] == nil { if tlsConn, ok := iConn.(*tls.Conn); ok { alpn = tlsConn.ConnectionState().NegotiatedProtocol newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid) } if apfb[alpn] == nil { alpn = "" } } pfb := apfb[alpn] if pfb == nil { return newError(`failed to find the default "alpn" config`).AtWarning() } path := "" if len(pfb) > 1 || pfb[""] == nil { if firstLen >= 18 && first.Byte(4) != '*' { // not h2c firstBytes := first.Bytes() for i := 4; i <= 8; i++ { // 5 -> 9 if firstBytes[i] == '/' && firstBytes[i-1] == ' ' { search := len(firstBytes) if search > 64 { search = 64 // up to about 60 } for j := i + 1; j < search; j++ { k := firstBytes[j] if k == '\r' || k == '\n' { // avoid logging \r or \n break } if k == ' ' { path = string(firstBytes[i:j]) newError("realPath = " + path).AtInfo().WriteToLog(sid) if pfb[path] == nil { path = "" } break } } break } } } } fb := pfb[path] if fb == nil { return newError(`failed to find the default "path" config`).AtWarning() } ctx, cancel := context.WithCancel(ctx) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) var conn net.Conn if err := retry.ExponentialBackoff(5, 100).On(func() error { var dialer net.Dialer conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest) if err != nil { return err } return nil }); err != nil { return newError("failed to dial to " + fb.Dest).Base(err).AtWarning() } defer conn.Close() serverReader := buf.NewReader(conn) serverWriter := buf.NewWriter(conn) postRequest := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if fb.Xver != 0 { remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String()) if err != nil { return err } localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String()) if err != nil { return err } ipv4 := true for i := 0; i < len(remoteAddr); i++ { if remoteAddr[i] == ':' { ipv4 = false break } } pro := buf.New() defer pro.Release() switch fb.Xver { case 1: if ipv4 { common.Must2(pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))) } else { common.Must2(pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))) } case 2: common.Must2(pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A\x21"))) // signature + v2 + PROXY if ipv4 { common.Must2(pro.Write([]byte("\x11\x00\x0C"))) // AF_INET + STREAM + 12 bytes common.Must2(pro.Write(net.ParseIP(remoteAddr).To4())) common.Must2(pro.Write(net.ParseIP(localAddr).To4())) } else { common.Must2(pro.Write([]byte("\x21\x00\x24"))) // AF_INET6 + STREAM + 36 bytes common.Must2(pro.Write(net.ParseIP(remoteAddr).To16())) common.Must2(pro.Write(net.ParseIP(localAddr).To16())) } p1, _ := strconv.ParseUint(remotePort, 10, 16) p2, _ := strconv.ParseUint(localPort, 10, 16) common.Must2(pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})) } if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil { return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning() } } if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil { return newError("failed to fallback request payload").Base(err).AtInfo() } return nil } writer := buf.NewWriter(connection) getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil { return newError("failed to deliver response payload").Base(err).AtInfo() } return nil } if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil { common.Must(common.Interrupt(serverReader)) common.Must(common.Interrupt(serverWriter)) return newError("fallback ends").Base(err).AtInfo() } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/config.pb.go
proxy/trojan/config.pb.go
package trojan import ( packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" protocol "github.com/v2fly/v2ray-core/v5/common/protocol" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Account struct { state protoimpl.MessageState `protogen:"open.v1"` Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Account) Reset() { *x = Account{} mi := &file_proxy_trojan_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Account) String() string { return protoimpl.X.MessageStringOf(x) } func (*Account) ProtoMessage() {} func (x *Account) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Account.ProtoReflect.Descriptor instead. func (*Account) Descriptor() ([]byte, []int) { return file_proxy_trojan_config_proto_rawDescGZIP(), []int{0} } func (x *Account) GetPassword() string { if x != nil { return x.Password } return "" } type Fallback struct { state protoimpl.MessageState `protogen:"open.v1"` Alpn string `protobuf:"bytes,1,opt,name=alpn,proto3" json:"alpn,omitempty"` Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` Dest string `protobuf:"bytes,4,opt,name=dest,proto3" json:"dest,omitempty"` Xver uint64 `protobuf:"varint,5,opt,name=xver,proto3" json:"xver,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Fallback) Reset() { *x = Fallback{} mi := &file_proxy_trojan_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Fallback) String() string { return protoimpl.X.MessageStringOf(x) } func (*Fallback) ProtoMessage() {} func (x *Fallback) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Fallback.ProtoReflect.Descriptor instead. func (*Fallback) Descriptor() ([]byte, []int) { return file_proxy_trojan_config_proto_rawDescGZIP(), []int{1} } func (x *Fallback) GetAlpn() string { if x != nil { return x.Alpn } return "" } func (x *Fallback) GetPath() string { if x != nil { return x.Path } return "" } func (x *Fallback) GetType() string { if x != nil { return x.Type } return "" } func (x *Fallback) GetDest() string { if x != nil { return x.Dest } return "" } func (x *Fallback) GetXver() uint64 { if x != nil { return x.Xver } return 0 } type ClientConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ClientConfig) Reset() { *x = ClientConfig{} mi := &file_proxy_trojan_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ClientConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientConfig) ProtoMessage() {} func (x *ClientConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_config_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead. func (*ClientConfig) Descriptor() ([]byte, []int) { return file_proxy_trojan_config_proto_rawDescGZIP(), []int{2} } func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint { if x != nil { return x.Server } return nil } type ServerConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Users []*protocol.User `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"` Fallbacks []*Fallback `protobuf:"bytes,3,rep,name=fallbacks,proto3" json:"fallbacks,omitempty"` PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,4,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ServerConfig) Reset() { *x = ServerConfig{} mi := &file_proxy_trojan_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ServerConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ServerConfig) ProtoMessage() {} func (x *ServerConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_config_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead. func (*ServerConfig) Descriptor() ([]byte, []int) { return file_proxy_trojan_config_proto_rawDescGZIP(), []int{3} } func (x *ServerConfig) GetUsers() []*protocol.User { if x != nil { return x.Users } return nil } func (x *ServerConfig) GetFallbacks() []*Fallback { if x != nil { return x.Fallbacks } return nil } func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType { if x != nil { return x.PacketEncoding } return packetaddr.PacketAddrType(0) } var File_proxy_trojan_config_proto protoreflect.FileDescriptor const file_proxy_trojan_config_proto_rawDesc = "" + "\n" + "\x19proxy/trojan/config.proto\x12\x17v2ray.core.proxy.trojan\x1a\x1acommon/protocol/user.proto\x1a!common/protocol/server_spec.proto\x1a\"common/net/packetaddr/config.proto\"%\n" + "\aAccount\x12\x1a\n" + "\bpassword\x18\x01 \x01(\tR\bpassword\"n\n" + "\bFallback\x12\x12\n" + "\x04alpn\x18\x01 \x01(\tR\x04alpn\x12\x12\n" + "\x04path\x18\x02 \x01(\tR\x04path\x12\x12\n" + "\x04type\x18\x03 \x01(\tR\x04type\x12\x12\n" + "\x04dest\x18\x04 \x01(\tR\x04dest\x12\x12\n" + "\x04xver\x18\x05 \x01(\x04R\x04xver\"R\n" + "\fClientConfig\x12B\n" + "\x06server\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server\"\xdb\x01\n" + "\fServerConfig\x126\n" + "\x05users\x18\x01 \x03(\v2 .v2ray.core.common.protocol.UserR\x05users\x12?\n" + "\tfallbacks\x18\x03 \x03(\v2!.v2ray.core.proxy.trojan.FallbackR\tfallbacks\x12R\n" + "\x0fpacket_encoding\x18\x04 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncodingBf\n" + "\x1bcom.v2ray.core.proxy.trojanP\x01Z+github.com/v2fly/v2ray-core/v5/proxy/trojan\xaa\x02\x17V2Ray.Core.Proxy.Trojanb\x06proto3" var ( file_proxy_trojan_config_proto_rawDescOnce sync.Once file_proxy_trojan_config_proto_rawDescData []byte ) func file_proxy_trojan_config_proto_rawDescGZIP() []byte { file_proxy_trojan_config_proto_rawDescOnce.Do(func() { file_proxy_trojan_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_trojan_config_proto_rawDesc), len(file_proxy_trojan_config_proto_rawDesc))) }) return file_proxy_trojan_config_proto_rawDescData } var file_proxy_trojan_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_proxy_trojan_config_proto_goTypes = []any{ (*Account)(nil), // 0: v2ray.core.proxy.trojan.Account (*Fallback)(nil), // 1: v2ray.core.proxy.trojan.Fallback (*ClientConfig)(nil), // 2: v2ray.core.proxy.trojan.ClientConfig (*ServerConfig)(nil), // 3: v2ray.core.proxy.trojan.ServerConfig (*protocol.ServerEndpoint)(nil), // 4: v2ray.core.common.protocol.ServerEndpoint (*protocol.User)(nil), // 5: v2ray.core.common.protocol.User (packetaddr.PacketAddrType)(0), // 6: v2ray.core.net.packetaddr.PacketAddrType } var file_proxy_trojan_config_proto_depIdxs = []int32{ 4, // 0: v2ray.core.proxy.trojan.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint 5, // 1: v2ray.core.proxy.trojan.ServerConfig.users:type_name -> v2ray.core.common.protocol.User 1, // 2: v2ray.core.proxy.trojan.ServerConfig.fallbacks:type_name -> v2ray.core.proxy.trojan.Fallback 6, // 3: v2ray.core.proxy.trojan.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_proxy_trojan_config_proto_init() } func file_proxy_trojan_config_proto_init() { if File_proxy_trojan_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_trojan_config_proto_rawDesc), len(file_proxy_trojan_config_proto_rawDesc)), NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_trojan_config_proto_goTypes, DependencyIndexes: file_proxy_trojan_config_proto_depIdxs, MessageInfos: file_proxy_trojan_config_proto_msgTypes, }.Build() File_proxy_trojan_config_proto = out.File file_proxy_trojan_config_proto_goTypes = nil file_proxy_trojan_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/trojan.go
proxy/trojan/trojan.go
package trojan
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/simplified/config.go
proxy/trojan/simplified/config.go
package simplified import ( "context" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" "github.com/v2fly/v2ray-core/v5/proxy/trojan" ) func init() { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedServer := config.(*ServerConfig) fullServer := &trojan.ServerConfig{ Users: func() (users []*protocol.User) { for _, v := range simplifiedServer.Users { account := &trojan.Account{Password: v} users = append(users, &protocol.User{ Account: serial.ToTypedMessage(account), }) } return }(), PacketEncoding: simplifiedServer.PacketEncoding, } return common.CreateObject(ctx, fullServer) })) common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { simplifiedClient := config.(*ClientConfig) fullClient := &trojan.ClientConfig{ Server: []*protocol.ServerEndpoint{ { Address: simplifiedClient.Address, Port: simplifiedClient.Port, User: []*protocol.User{ { Account: serial.ToTypedMessage(&trojan.Account{Password: simplifiedClient.Password}), }, }, }, }, } return common.CreateObject(ctx, fullClient) })) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/trojan/simplified/config.pb.go
proxy/trojan/simplified/config.pb.go
package simplified import ( net "github.com/v2fly/v2ray-core/v5/common/net" packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr" _ "github.com/v2fly/v2ray-core/v5/common/protoext" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ServerConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Users []string `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"` PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,2,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ServerConfig) Reset() { *x = ServerConfig{} mi := &file_proxy_trojan_simplified_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ServerConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ServerConfig) ProtoMessage() {} func (x *ServerConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_simplified_config_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead. func (*ServerConfig) Descriptor() ([]byte, []int) { return file_proxy_trojan_simplified_config_proto_rawDescGZIP(), []int{0} } func (x *ServerConfig) GetUsers() []string { if x != nil { return x.Users } return nil } func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType { if x != nil { return x.PacketEncoding } return packetaddr.PacketAddrType(0) } type ClientConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ClientConfig) Reset() { *x = ClientConfig{} mi := &file_proxy_trojan_simplified_config_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ClientConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientConfig) ProtoMessage() {} func (x *ClientConfig) ProtoReflect() protoreflect.Message { mi := &file_proxy_trojan_simplified_config_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead. func (*ClientConfig) Descriptor() ([]byte, []int) { return file_proxy_trojan_simplified_config_proto_rawDescGZIP(), []int{1} } func (x *ClientConfig) GetAddress() *net.IPOrDomain { if x != nil { return x.Address } return nil } func (x *ClientConfig) GetPort() uint32 { if x != nil { return x.Port } return 0 } func (x *ClientConfig) GetPassword() string { if x != nil { return x.Password } return "" } var File_proxy_trojan_simplified_config_proto protoreflect.FileDescriptor const file_proxy_trojan_simplified_config_proto_rawDesc = "" + "\n" + "$proxy/trojan/simplified/config.proto\x12\"v2ray.core.proxy.trojan.simplified\x1a common/protoext/extensions.proto\x1a\x18common/net/address.proto\x1a\"common/net/packetaddr/config.proto\"\x8f\x01\n" + "\fServerConfig\x12\x14\n" + "\x05users\x18\x01 \x03(\tR\x05users\x12R\n" + "\x0fpacket_encoding\x18\x02 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding:\x15\x82\xb5\x18\x11\n" + "\ainbound\x12\x06trojan\"\x93\x01\n" + "\fClientConfig\x12;\n" + "\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" + "\x04port\x18\x02 \x01(\rR\x04port\x12\x1a\n" + "\bpassword\x18\x03 \x01(\tR\bpassword:\x16\x82\xb5\x18\x12\n" + "\boutbound\x12\x06trojanB\x87\x01\n" + "&com.v2ray.core.proxy.trojan.simplifiedP\x01Z6github.com/v2fly/v2ray-core/v5/proxy/trojan/simplified\xaa\x02\"V2Ray.Core.Proxy.Trojan.Simplifiedb\x06proto3" var ( file_proxy_trojan_simplified_config_proto_rawDescOnce sync.Once file_proxy_trojan_simplified_config_proto_rawDescData []byte ) func file_proxy_trojan_simplified_config_proto_rawDescGZIP() []byte { file_proxy_trojan_simplified_config_proto_rawDescOnce.Do(func() { file_proxy_trojan_simplified_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_trojan_simplified_config_proto_rawDesc), len(file_proxy_trojan_simplified_config_proto_rawDesc))) }) return file_proxy_trojan_simplified_config_proto_rawDescData } var file_proxy_trojan_simplified_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_trojan_simplified_config_proto_goTypes = []any{ (*ServerConfig)(nil), // 0: v2ray.core.proxy.trojan.simplified.ServerConfig (*ClientConfig)(nil), // 1: v2ray.core.proxy.trojan.simplified.ClientConfig (packetaddr.PacketAddrType)(0), // 2: v2ray.core.net.packetaddr.PacketAddrType (*net.IPOrDomain)(nil), // 3: v2ray.core.common.net.IPOrDomain } var file_proxy_trojan_simplified_config_proto_depIdxs = []int32{ 2, // 0: v2ray.core.proxy.trojan.simplified.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType 3, // 1: v2ray.core.proxy.trojan.simplified.ClientConfig.address:type_name -> v2ray.core.common.net.IPOrDomain 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_proxy_trojan_simplified_config_proto_init() } func file_proxy_trojan_simplified_config_proto_init() { if File_proxy_trojan_simplified_config_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_trojan_simplified_config_proto_rawDesc), len(file_proxy_trojan_simplified_config_proto_rawDesc)), NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proxy_trojan_simplified_config_proto_goTypes, DependencyIndexes: file_proxy_trojan_simplified_config_proto_depIdxs, MessageInfos: file_proxy_trojan_simplified_config_proto_msgTypes, }.Build() File_proxy_trojan_simplified_config_proto = out.File file_proxy_trojan_simplified_config_proto_goTypes = nil file_proxy_trojan_simplified_config_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/eih_aes.go
proxy/shadowsocks2022/eih_aes.go
package shadowsocks2022 import ( "crypto/subtle" "io" "github.com/v2fly/struc" "github.com/v2fly/v2ray-core/v5/common/buf" "lukechampine.com/blake3" ) func newAESEIH(size int) *aesEIH { return &aesEIH{length: size} } func newAESEIHWithData(size int, eih [][aesEIHSize]byte) *aesEIH { return &aesEIH{length: size, eih: eih} } const aesEIHSize = 16 type aesEIH struct { eih [][aesEIHSize]byte length int } func (a *aesEIH) Pack(p []byte, opt *struc.Options) (int, error) { var totalCopy int for i := 0; i < a.length; i++ { n := copy(p[aesEIHSize*i:aesEIHSize*(i+1)], a.eih[i][:]) if n != 16 { return 0, newError("failed to pack aesEIH") } totalCopy += n } return totalCopy, nil } func (a *aesEIH) Unpack(r io.Reader, length int, opt *struc.Options) error { a.eih = make([][aesEIHSize]byte, a.length) for i := 0; i < a.length; i++ { n, err := r.Read(a.eih[i][:]) if err != nil { return newError("failed to unpack aesEIH").Base(err) } if n != aesEIHSize { return newError("failed to unpack aesEIH") } } return nil } func (a *aesEIH) Size(opt *struc.Options) int { return a.length * aesEIHSize } func (a *aesEIH) String() string { return "" } const aesEIHPskHashSize = 16 type aesEIHGenerator struct { ipsk [][]byte ipskHash [][aesEIHPskHashSize]byte psk []byte pskHash [aesEIHPskHashSize]byte length int } func newAESEIHGeneratorContainer(size int, effectivePsk []byte, ipsk [][]byte) *aesEIHGenerator { var ipskHash [][aesEIHPskHashSize]byte for _, v := range ipsk { hash := blake3.Sum512(v) ipskHash = append(ipskHash, [aesEIHPskHashSize]byte(hash[:16])) } pskHashFull := blake3.Sum512(effectivePsk) pskHash := [aesEIHPskHashSize]byte(pskHashFull[:16]) return &aesEIHGenerator{length: size, ipsk: ipsk, ipskHash: ipskHash, psk: effectivePsk, pskHash: pskHash} } func (a *aesEIHGenerator) GenerateEIH(derivation KeyDerivation, method Method, salt []byte) (ExtensibleIdentityHeaders, error) { return a.generateEIHWithMask(derivation, method, salt, nil) } func (a *aesEIHGenerator) GenerateEIHUDP(derivation KeyDerivation, method Method, mask []byte) (ExtensibleIdentityHeaders, error) { return a.generateEIHWithMask(derivation, method, nil, mask) } func (a *aesEIHGenerator) generateEIHWithMask(derivation KeyDerivation, method Method, salt, mask []byte) (ExtensibleIdentityHeaders, error) { eih := make([][16]byte, a.length) current := a.length - 1 currentPskHash := a.pskHash for { identityKeyBuf := buf.New() identityKey := identityKeyBuf.Extend(int32(method.GetSessionSubKeyAndSaltLength())) if mask == nil { err := derivation.GetIdentitySubKey(a.ipsk[current], salt, identityKey) if err != nil { return nil, newError("failed to get identity sub key").Base(err) } } else { copy(identityKey, a.ipsk[current]) } eih[current] = [16]byte{} if mask != nil { subtle.XORBytes(currentPskHash[:], mask, currentPskHash[:]) } err := method.GenerateEIH(identityKey, currentPskHash[:], eih[current][:]) if err != nil { return nil, newError("failed to generate EIH").Base(err) } current-- if current < 0 { break } currentPskHash = a.ipskHash[current] identityKeyBuf.Release() } return newAESEIHWithData(a.length, eih), nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/client_session.go
proxy/shadowsocks2022/client_session.go
package shadowsocks2022 import ( "context" "crypto/rand" "io" gonet "net" "sync" "time" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/transport/internet" "github.com/pion/transport/v2/replaydetector" ) func NewClientUDPSession(ctx context.Context, conn io.ReadWriteCloser, packetProcessor UDPClientPacketProcessor) *ClientUDPSession { session := &ClientUDPSession{ locker: &sync.RWMutex{}, conn: conn, packetProcessor: packetProcessor, sessionMap: make(map[string]*ClientUDPSessionConn), sessionMapAlias: make(map[string]string), } session.ctx, session.finish = context.WithCancel(ctx) go session.KeepReading() return session } type ClientUDPSession struct { locker *sync.RWMutex conn io.ReadWriteCloser packetProcessor UDPClientPacketProcessor sessionMap map[string]*ClientUDPSessionConn sessionMapAlias map[string]string ctx context.Context finish func() } func (c *ClientUDPSession) GetCachedState(sessionID string) UDPClientPacketProcessorCachedState { c.locker.RLock() defer c.locker.RUnlock() state, ok := c.sessionMap[sessionID] if !ok { return nil } return state.cachedProcessorState } func (c *ClientUDPSession) GetCachedServerState(serverSessionID string) UDPClientPacketProcessorCachedState { c.locker.RLock() defer c.locker.RUnlock() clientSessionID := c.getCachedStateAlias(serverSessionID) if clientSessionID == "" { return nil } state, ok := c.sessionMap[clientSessionID] if !ok { return nil } if serverState, ok := state.trackedServerSessionID[serverSessionID]; !ok { return nil } else { return serverState.cachedRecvProcessorState } } func (c *ClientUDPSession) getCachedStateAlias(serverSessionID string) string { state, ok := c.sessionMapAlias[serverSessionID] if !ok { return "" } return state } func (c *ClientUDPSession) PutCachedState(sessionID string, cache UDPClientPacketProcessorCachedState) { c.locker.RLock() defer c.locker.RUnlock() state, ok := c.sessionMap[sessionID] if !ok { return } state.cachedProcessorState = cache } func (c *ClientUDPSession) PutCachedServerState(serverSessionID string, cache UDPClientPacketProcessorCachedState) { c.locker.RLock() defer c.locker.RUnlock() clientSessionID := c.getCachedStateAlias(serverSessionID) if clientSessionID == "" { return } state, ok := c.sessionMap[clientSessionID] if !ok { return } if serverState, ok := state.trackedServerSessionID[serverSessionID]; ok { serverState.cachedRecvProcessorState = cache return } } func (c *ClientUDPSession) Close() error { c.finish() return c.conn.Close() } func (c *ClientUDPSession) WriteUDPRequest(request *UDPRequest) error { buffer := buf.New() defer buffer.Release() err := c.packetProcessor.EncodeUDPRequest(request, buffer, c) if request.Payload != nil { request.Payload.Release() } if err != nil { return newError("unable to encode udp request").Base(err) } _, err = c.conn.Write(buffer.Bytes()) if err != nil { return newError("unable to write to conn").Base(err) } return nil } func (c *ClientUDPSession) KeepReading() { for c.ctx.Err() == nil { udpResp := &UDPResponse{} buffer := make([]byte, 1600) n, err := c.conn.Read(buffer) if err != nil { newError("unable to read from conn").Base(err).WriteToLog() return } if n != 0 { err := c.packetProcessor.DecodeUDPResp(buffer[:n], udpResp, c) if err != nil { newError("unable to decode udp response").Base(err).WriteToLog() continue } { timeDifference := int64(udpResp.TimeStamp) - time.Now().Unix() if timeDifference < -30 || timeDifference > 30 { newError("udp packet timestamp difference too large, packet discarded, time diff = ", timeDifference).WriteToLog() continue } } c.locker.RLock() session, ok := c.sessionMap[string(udpResp.ClientSessionID[:])] c.locker.RUnlock() if ok { select { case session.readChan <- udpResp: default: } } else { newError("misbehaving server: unknown client session ID").Base(err).WriteToLog() } } } } func (c *ClientUDPSession) NewSessionConn() (internet.AbstractPacketConn, error) { sessionID := make([]byte, 8) _, err := rand.Read(sessionID) if err != nil { return nil, newError("unable to generate session id").Base(err) } connctx, connfinish := context.WithCancel(c.ctx) sessionConn := &ClientUDPSessionConn{ sessionID: string(sessionID), readChan: make(chan *UDPResponse, 128), parent: c, ctx: connctx, finish: connfinish, nextWritePacketID: 0, trackedServerSessionID: make(map[string]*ClientUDPSessionServerTracker), } c.locker.Lock() c.sessionMap[sessionConn.sessionID] = sessionConn c.locker.Unlock() return sessionConn, nil } type ClientUDPSessionServerTracker struct { cachedRecvProcessorState UDPClientPacketProcessorCachedState rxReplayDetector replaydetector.ReplayDetector lastSeen time.Time } type ClientUDPSessionConn struct { sessionID string readChan chan *UDPResponse parent *ClientUDPSession nextWritePacketID uint64 trackedServerSessionID map[string]*ClientUDPSessionServerTracker cachedProcessorState UDPClientPacketProcessorCachedState ctx context.Context finish func() } func (c *ClientUDPSessionConn) Close() error { c.parent.locker.Lock() delete(c.parent.sessionMap, c.sessionID) for k := range c.trackedServerSessionID { delete(c.parent.sessionMapAlias, k) } c.parent.locker.Unlock() c.finish() return nil } func (c *ClientUDPSessionConn) WriteTo(p []byte, addr gonet.Addr) (n int, err error) { thisPacketID := c.nextWritePacketID c.nextWritePacketID += 1 req := &UDPRequest{ SessionID: [8]byte{}, PacketID: thisPacketID, TimeStamp: uint64(time.Now().Unix()), Address: net.IPAddress(addr.(*gonet.UDPAddr).IP), Port: addr.(*net.UDPAddr).Port, Payload: nil, } copy(req.SessionID[:], c.sessionID) req.Payload = buf.New() req.Payload.Write(p) err = c.parent.WriteUDPRequest(req) if err != nil { return 0, newError("unable to write to parent session").Base(err) } return len(p), nil } func (c *ClientUDPSessionConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { for { select { case <-c.ctx.Done(): return 0, nil, io.EOF case resp := <-c.readChan: n = copy(p, resp.Payload.Bytes()) resp.Payload.Release() var trackedState *ClientUDPSessionServerTracker if trackedStateReceived, ok := c.trackedServerSessionID[string(resp.SessionID[:])]; !ok { for key, value := range c.trackedServerSessionID { if time.Since(value.lastSeen) > 65*time.Second { delete(c.trackedServerSessionID, key) } } state := &ClientUDPSessionServerTracker{ rxReplayDetector: replaydetector.New(1024, ^uint64(0)), } c.trackedServerSessionID[string(resp.SessionID[:])] = state c.parent.locker.RLock() c.parent.sessionMapAlias[string(resp.SessionID[:])] = string(resp.ClientSessionID[:]) c.parent.locker.RUnlock() trackedState = state } else { trackedState = trackedStateReceived } if accept, ok := trackedState.rxReplayDetector.Check(resp.PacketID); ok { accept() } else { newError("misbehaving server: replayed packet").Base(err).WriteToLog() continue } trackedState.lastSeen = time.Now() addr = &net.UDPAddr{IP: resp.Address.IP(), Port: resp.Port} } return n, addr, nil } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/kdf_blake3.go
proxy/shadowsocks2022/kdf_blake3.go
package shadowsocks2022 import ( "lukechampine.com/blake3" "github.com/v2fly/v2ray-core/v5/common/buf" ) func newBLAKE3KeyDerivation() *BLAKE3KeyDerivation { return &BLAKE3KeyDerivation{} } type BLAKE3KeyDerivation struct{} func (b BLAKE3KeyDerivation) GetSessionSubKey(effectivePsk, salt []byte, outKey []byte) error { keyingMaterialBuffer := buf.New() keyingMaterialBuffer.Write(effectivePsk) keyingMaterialBuffer.Write(salt) blake3.DeriveKey(outKey, "shadowsocks 2022 session subkey", keyingMaterialBuffer.Bytes()) keyingMaterialBuffer.Release() return nil } func (b BLAKE3KeyDerivation) GetIdentitySubKey(effectivePsk, salt []byte, outKey []byte) error { keyingMaterialBuffer := buf.New() keyingMaterialBuffer.Write(effectivePsk) keyingMaterialBuffer.Write(salt) blake3.DeriveKey(outKey, "shadowsocks 2022 identity subkey", keyingMaterialBuffer.Bytes()) keyingMaterialBuffer.Release() return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/errors.generated.go
proxy/shadowsocks2022/errors.generated.go
package shadowsocks2022 import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false