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/observatory/command/command_grpc.pb.go | app/observatory/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 (
ObservatoryService_GetOutboundStatus_FullMethodName = "/v2ray.core.app.observatory.command.ObservatoryService/GetOutboundStatus"
)
// ObservatoryServiceClient is the client API for ObservatoryService 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 ObservatoryServiceClient interface {
GetOutboundStatus(ctx context.Context, in *GetOutboundStatusRequest, opts ...grpc.CallOption) (*GetOutboundStatusResponse, error)
}
type observatoryServiceClient struct {
cc grpc.ClientConnInterface
}
func NewObservatoryServiceClient(cc grpc.ClientConnInterface) ObservatoryServiceClient {
return &observatoryServiceClient{cc}
}
func (c *observatoryServiceClient) GetOutboundStatus(ctx context.Context, in *GetOutboundStatusRequest, opts ...grpc.CallOption) (*GetOutboundStatusResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetOutboundStatusResponse)
err := c.cc.Invoke(ctx, ObservatoryService_GetOutboundStatus_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// ObservatoryServiceServer is the server API for ObservatoryService service.
// All implementations must embed UnimplementedObservatoryServiceServer
// for forward compatibility.
type ObservatoryServiceServer interface {
GetOutboundStatus(context.Context, *GetOutboundStatusRequest) (*GetOutboundStatusResponse, error)
mustEmbedUnimplementedObservatoryServiceServer()
}
// UnimplementedObservatoryServiceServer 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 UnimplementedObservatoryServiceServer struct{}
func (UnimplementedObservatoryServiceServer) GetOutboundStatus(context.Context, *GetOutboundStatusRequest) (*GetOutboundStatusResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetOutboundStatus not implemented")
}
func (UnimplementedObservatoryServiceServer) mustEmbedUnimplementedObservatoryServiceServer() {}
func (UnimplementedObservatoryServiceServer) testEmbeddedByValue() {}
// UnsafeObservatoryServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ObservatoryServiceServer will
// result in compilation errors.
type UnsafeObservatoryServiceServer interface {
mustEmbedUnimplementedObservatoryServiceServer()
}
func RegisterObservatoryServiceServer(s grpc.ServiceRegistrar, srv ObservatoryServiceServer) {
// If the following call pancis, it indicates UnimplementedObservatoryServiceServer 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(&ObservatoryService_ServiceDesc, srv)
}
func _ObservatoryService_GetOutboundStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetOutboundStatusRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ObservatoryServiceServer).GetOutboundStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ObservatoryService_GetOutboundStatus_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ObservatoryServiceServer).GetOutboundStatus(ctx, req.(*GetOutboundStatusRequest))
}
return interceptor(ctx, in, info, handler)
}
// ObservatoryService_ServiceDesc is the grpc.ServiceDesc for ObservatoryService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ObservatoryService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v2ray.core.app.observatory.command.ObservatoryService",
HandlerType: (*ObservatoryServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetOutboundStatus",
Handler: _ObservatoryService_GetOutboundStatus_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/observatory/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/observatory/command/command.go | app/observatory/command/command.go | //go:build !confonly
// +build !confonly
package command
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"github.com/golang/protobuf/proto"
"google.golang.org/grpc"
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 service struct {
UnimplementedObservatoryServiceServer
v *core.Instance
observatory extension.Observatory
}
func (s *service) GetOutboundStatus(ctx context.Context, request *GetOutboundStatusRequest) (*GetOutboundStatusResponse, error) {
var result proto.Message
if request.Tag == "" {
observeResult, err := s.observatory.GetObservation(ctx)
if err != nil {
return nil, newError("cannot get observation").Base(err)
}
result = observeResult
} else {
if _, ok := s.observatory.(features.TaggedFeatures); !ok {
return nil, newError("observatory does not support tagged features")
}
fet, err := s.observatory.(features.TaggedFeatures).GetFeaturesByTag(request.Tag)
if err != nil {
return nil, newError("cannot get tagged observatory").Base(err)
}
observeResult, err := fet.(extension.Observatory).GetObservation(ctx)
if err != nil {
return nil, newError("cannot get observation").Base(err)
}
result = observeResult
}
retdata := result.(*observatory.ObservationResult)
return &GetOutboundStatusResponse{
Status: retdata,
}, nil
}
func (s *service) Register(server *grpc.Server) {
RegisterObservatoryServiceServer(server, s)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
s := core.MustFromContext(ctx)
sv := &service{v: s}
err := s.RequireFeatures(func(Observatory extension.Observatory) {
sv.observatory = Observatory
})
if err != nil {
return nil, err
}
return sv, nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/burst/healthping_result_test.go | app/observatory/burst/healthping_result_test.go | package burst_test
import (
"math"
reflect "reflect"
"testing"
"time"
"github.com/v2fly/v2ray-core/v5/app/observatory/burst"
)
func TestHealthPingResults(t *testing.T) {
rtts := []int64{60, 140, 60, 140, 60, 60, 140, 60, 140}
hr := burst.NewHealthPingResult(4, time.Hour)
for _, rtt := range rtts {
hr.Put(time.Duration(rtt))
}
rttFailed := time.Duration(math.MaxInt64)
expected := &burst.HealthPingStats{
All: 4,
Fail: 0,
Deviation: 40,
Average: 100,
Max: 140,
Min: 60,
}
actual := hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
hr.Put(rttFailed)
hr.Put(rttFailed)
expected.Fail = 2
actual = hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("failed half-failures test, expected: %v, actual: %v", expected, actual)
}
hr.Put(rttFailed)
hr.Put(rttFailed)
expected = &burst.HealthPingStats{
All: 4,
Fail: 4,
Deviation: 0,
Average: 0,
Max: 0,
Min: 0,
}
actual = hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("failed all-failures test, expected: %v, actual: %v", expected, actual)
}
}
func TestHealthPingResultsIgnoreOutdated(t *testing.T) {
rtts := []int64{60, 140, 60, 140}
hr := burst.NewHealthPingResult(4, time.Duration(10)*time.Millisecond)
for i, rtt := range rtts {
if i == 2 {
// wait for previous 2 outdated
time.Sleep(time.Duration(10) * time.Millisecond)
}
hr.Put(time.Duration(rtt))
}
hr.Get()
expected := &burst.HealthPingStats{
All: 2,
Fail: 0,
Deviation: 40,
Average: 100,
Max: 140,
Min: 60,
}
actual := hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("failed 'half-outdated' test, expected: %v, actual: %v", expected, actual)
}
// wait for all outdated
time.Sleep(time.Duration(10) * time.Millisecond)
expected = &burst.HealthPingStats{
All: 0,
Fail: 0,
Deviation: 0,
Average: 0,
Max: 0,
Min: 0,
}
actual = hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("failed 'outdated / not-tested' test, expected: %v, actual: %v", expected, actual)
}
hr.Put(time.Duration(60))
expected = &burst.HealthPingStats{
All: 1,
Fail: 0,
// 1 sample, std=0.5rtt
Deviation: 30,
Average: 60,
Max: 60,
Min: 60,
}
actual = hr.Get()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %v, actual: %v", expected, actual)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/burst/healthping.go | app/observatory/burst/healthping.go | package burst
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/v2fly/v2ray-core/v5/common/dice"
)
// HealthPingSettings holds settings for health Checker
type HealthPingSettings struct {
Destination string `json:"destination"`
Connectivity string `json:"connectivity"`
Interval time.Duration `json:"interval"`
SamplingCount int `json:"sampling"`
Timeout time.Duration `json:"timeout"`
}
// HealthPing is the health checker for balancers
type HealthPing struct {
ctx context.Context
access sync.Mutex
ticker *time.Ticker
tickerClose chan struct{}
Settings *HealthPingSettings
Results map[string]*HealthPingRTTS
}
// NewHealthPing creates a new HealthPing with settings
func NewHealthPing(ctx context.Context, config *HealthPingConfig) *HealthPing {
settings := &HealthPingSettings{}
if config != nil {
settings = &HealthPingSettings{
Connectivity: strings.TrimSpace(config.Connectivity),
Destination: strings.TrimSpace(config.Destination),
Interval: time.Duration(config.Interval),
SamplingCount: int(config.SamplingCount),
Timeout: time.Duration(config.Timeout),
}
}
if settings.Destination == "" {
// Destination URL, need 204 for success return default to chromium
// https://github.com/chromium/chromium/blob/main/components/safety_check/url_constants.cc#L10
// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/safety_check/url_constants.cc#10
settings.Destination = "https://connectivitycheck.gstatic.com/generate_204"
}
if settings.Interval == 0 {
settings.Interval = time.Duration(1) * time.Minute
} else if settings.Interval < 10 {
newError("health check interval is too small, 10s is applied").AtWarning().WriteToLog()
settings.Interval = time.Duration(10) * time.Second
}
if settings.SamplingCount <= 0 {
settings.SamplingCount = 10
}
if settings.Timeout <= 0 {
// results are saved after all health pings finish,
// a larger timeout could possibly makes checks run longer
settings.Timeout = time.Duration(5) * time.Second
}
return &HealthPing{
ctx: ctx,
Settings: settings,
Results: nil,
}
}
// StartScheduler implements the HealthChecker
func (h *HealthPing) StartScheduler(selector func() ([]string, error)) {
if h.ticker != nil {
return
}
interval := h.Settings.Interval * time.Duration(h.Settings.SamplingCount)
ticker := time.NewTicker(interval)
tickerClose := make(chan struct{})
h.ticker = ticker
h.tickerClose = tickerClose
go func() {
for {
go func() {
tags, err := selector()
if err != nil {
newError("error select outbounds for scheduled health check: ", err).AtWarning().WriteToLog()
return
}
h.doCheck(tags, interval, h.Settings.SamplingCount)
h.Cleanup(tags)
}()
select {
case <-ticker.C:
continue
case <-tickerClose:
return
}
}
}()
}
// StopScheduler implements the HealthChecker
func (h *HealthPing) StopScheduler() {
if h.ticker == nil {
return
}
h.ticker.Stop()
h.ticker = nil
close(h.tickerClose)
h.tickerClose = nil
}
// Check implements the HealthChecker
func (h *HealthPing) Check(tags []string) error {
if len(tags) == 0 {
return nil
}
newError("perform one-time health check for tags ", tags).AtInfo().WriteToLog()
h.doCheck(tags, 0, 1)
return nil
}
type rtt struct {
handler string
value time.Duration
}
// doCheck performs the 'rounds' amount checks in given 'duration'. You should make
// sure all tags are valid for current balancer
func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int) {
count := len(tags) * rounds
if count == 0 {
return
}
ch := make(chan *rtt, count)
for _, tag := range tags {
handler := tag
client := newPingClient(
h.ctx,
h.Settings.Destination,
h.Settings.Timeout,
handler,
)
for i := 0; i < rounds; i++ {
delay := time.Duration(0)
if duration > 0 {
delay = time.Duration(dice.Roll(int(duration)))
}
time.AfterFunc(delay, func() {
newError("checking ", handler).AtDebug().WriteToLog()
delay, err := client.MeasureDelay()
if err == nil {
ch <- &rtt{
handler: handler,
value: delay,
}
return
}
if !h.checkConnectivity() {
newError("network is down").AtWarning().WriteToLog()
ch <- &rtt{
handler: handler,
value: 0,
}
return
}
newError(fmt.Sprintf(
"error ping %s with %s: %s",
h.Settings.Destination,
handler,
err,
)).AtWarning().WriteToLog()
ch <- &rtt{
handler: handler,
value: rttFailed,
}
})
}
}
for i := 0; i < count; i++ {
rtt := <-ch
if rtt.value > 0 {
// should not put results when network is down
h.PutResult(rtt.handler, rtt.value)
}
}
}
// PutResult puts a ping rtt to results
func (h *HealthPing) PutResult(tag string, rtt time.Duration) {
h.access.Lock()
defer h.access.Unlock()
if h.Results == nil {
h.Results = make(map[string]*HealthPingRTTS)
}
r, ok := h.Results[tag]
if !ok {
// validity is 2 times to sampling period, since the check are
// distributed in the time line randomly, in extreme cases,
// previous checks are distributed on the left, and latters
// on the right
validity := h.Settings.Interval * time.Duration(h.Settings.SamplingCount) * 2
r = NewHealthPingResult(h.Settings.SamplingCount, validity)
h.Results[tag] = r
}
r.Put(rtt)
}
// Cleanup removes results of removed handlers,
// tags should be all valid tags of the Balancer now
func (h *HealthPing) Cleanup(tags []string) {
h.access.Lock()
defer h.access.Unlock()
for tag := range h.Results {
found := false
for _, v := range tags {
if tag == v {
found = true
break
}
}
if !found {
delete(h.Results, tag)
}
}
}
// checkConnectivity checks the network connectivity, it returns
// true if network is good or "connectivity check url" not set
func (h *HealthPing) checkConnectivity() bool {
if h.Settings.Connectivity == "" {
return true
}
tester := newDirectPingClient(
h.Settings.Connectivity,
h.Settings.Timeout,
)
if _, err := tester.MeasureDelay(); err != nil {
return false
}
return true
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/burst/errors.generated.go | app/observatory/burst/errors.generated.go | package burst
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/observatory/burst/ping.go | app/observatory/burst/ping.go | package burst
import (
"context"
"net/http"
"time"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/transport/internet/tagged"
)
type pingClient struct {
destination string
httpClient *http.Client
}
func newPingClient(ctx context.Context, destination string, timeout time.Duration, handler string) *pingClient {
return &pingClient{
destination: destination,
httpClient: newHTTPClient(ctx, handler, timeout),
}
}
func newDirectPingClient(destination string, timeout time.Duration) *pingClient {
return &pingClient{
destination: destination,
httpClient: &http.Client{Timeout: timeout},
}
}
func newHTTPClient(ctxv context.Context, handler string, timeout time.Duration) *http.Client {
tr := &http.Transport{
DisableKeepAlives: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
return tagged.Dialer(ctxv, dest, handler)
},
}
return &http.Client{
Transport: tr,
Timeout: timeout,
// don't follow redirect
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// MeasureDelay returns the delay time of the request to dest
func (s *pingClient) MeasureDelay() (time.Duration, error) {
if s.httpClient == nil {
panic("pingClient no initialized")
}
req, err := http.NewRequest(http.MethodHead, s.destination, nil)
if err != nil {
return rttFailed, err
}
start := time.Now()
resp, err := s.httpClient.Do(req)
if err != nil {
return rttFailed, err
}
// don't wait for body
resp.Body.Close()
return time.Since(start), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/burst/healthping_result.go | app/observatory/burst/healthping_result.go | package burst
import (
"math"
"time"
)
// HealthPingStats is the statistics of HealthPingRTTS
type HealthPingStats struct {
All int
Fail int
Deviation time.Duration
Average time.Duration
Max time.Duration
Min time.Duration
}
// HealthPingRTTS holds ping rtts for health Checker
type HealthPingRTTS struct {
idx int
cap int
validity time.Duration
rtts []*pingRTT
lastUpdateAt time.Time
stats *HealthPingStats
}
type pingRTT struct {
time time.Time
value time.Duration
}
// NewHealthPingResult returns a *HealthPingResult with specified capacity
func NewHealthPingResult(cap int, validity time.Duration) *HealthPingRTTS {
return &HealthPingRTTS{cap: cap, validity: validity}
}
// Get gets statistics of the HealthPingRTTS
func (h *HealthPingRTTS) Get() *HealthPingStats {
return h.getStatistics()
}
// GetWithCache get statistics and write cache for next call
// Make sure use Mutex.Lock() before calling it, RWMutex.RLock()
// is not an option since it writes cache
func (h *HealthPingRTTS) GetWithCache() *HealthPingStats {
lastPutAt := h.rtts[h.idx].time
now := time.Now()
if h.stats == nil || h.lastUpdateAt.Before(lastPutAt) || h.findOutdated(now) >= 0 {
h.stats = h.getStatistics()
h.lastUpdateAt = now
}
return h.stats
}
// Put puts a new rtt to the HealthPingResult
func (h *HealthPingRTTS) Put(d time.Duration) {
if h.rtts == nil {
h.rtts = make([]*pingRTT, h.cap)
for i := 0; i < h.cap; i++ {
h.rtts[i] = &pingRTT{}
}
h.idx = -1
}
h.idx = h.calcIndex(1)
now := time.Now()
h.rtts[h.idx].time = now
h.rtts[h.idx].value = d
}
func (h *HealthPingRTTS) calcIndex(step int) int {
idx := h.idx
idx += step
if idx >= h.cap {
idx %= h.cap
}
return idx
}
func (h *HealthPingRTTS) getStatistics() *HealthPingStats {
stats := &HealthPingStats{}
stats.Fail = 0
stats.Max = 0
stats.Min = rttFailed
sum := time.Duration(0)
cnt := 0
validRTTs := make([]time.Duration, 0)
for _, rtt := range h.rtts {
switch {
case rtt.value == 0 || time.Since(rtt.time) > h.validity:
continue
case rtt.value == rttFailed:
stats.Fail++
continue
}
cnt++
sum += rtt.value
validRTTs = append(validRTTs, rtt.value)
if stats.Max < rtt.value {
stats.Max = rtt.value
}
if stats.Min > rtt.value {
stats.Min = rtt.value
}
}
stats.All = cnt + stats.Fail
if cnt == 0 {
stats.Min = 0
return stats
}
stats.Average = time.Duration(int(sum) / cnt)
var std float64
if cnt < 2 {
// no enough data for standard deviation, we assume it's half of the average rtt
// if we don't do this, standard deviation of 1 round tested nodes is 0, will always
// selected before 2 or more rounds tested nodes
std = float64(stats.Average / 2)
} else {
variance := float64(0)
for _, rtt := range validRTTs {
variance += math.Pow(float64(rtt-stats.Average), 2)
}
std = math.Sqrt(variance / float64(cnt))
}
stats.Deviation = time.Duration(std)
return stats
}
func (h *HealthPingRTTS) findOutdated(now time.Time) int {
for i := h.cap - 1; i < 2*h.cap; i++ {
// from oldest to latest
idx := h.calcIndex(i)
validity := h.rtts[idx].time.Add(h.validity)
if h.lastUpdateAt.After(validity) {
return idx
}
if validity.Before(now) {
return idx
}
}
return -1
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/burst/burstobserver.go | app/observatory/burst/burstobserver.go | package burst
import (
"context"
"sync"
"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/signal/done"
"github.com/v2fly/v2ray-core/v5/features/extension"
"github.com/v2fly/v2ray-core/v5/features/outbound"
)
type Observer struct {
config *Config
ctx context.Context
statusLock sync.Mutex // nolint: structcheck
hp *HealthPing
finished *done.Instance
ohm outbound.Manager
}
func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
return &observatory.ObservationResult{Status: o.createResult()}, nil
}
func (o *Observer) createResult() []*observatory.OutboundStatus {
var result []*observatory.OutboundStatus
o.hp.access.Lock()
defer o.hp.access.Unlock()
for name, value := range o.hp.Results {
status := observatory.OutboundStatus{
Alive: value.getStatistics().All != value.getStatistics().Fail,
Delay: value.getStatistics().Average.Milliseconds(),
LastErrorReason: "",
OutboundTag: name,
LastSeenTime: 0,
LastTryTime: 0,
HealthPing: &observatory.HealthPingMeasurementResult{
All: int64(value.getStatistics().All),
Fail: int64(value.getStatistics().Fail),
Deviation: int64(value.getStatistics().Deviation),
Average: int64(value.getStatistics().Average),
Max: int64(value.getStatistics().Max),
Min: int64(value.getStatistics().Min),
},
}
result = append(result, &status)
}
return result
}
func (o *Observer) Type() interface{} {
return extension.ObservatoryType()
}
func (o *Observer) Start() error {
if o.config != nil && len(o.config.SubjectSelector) != 0 {
o.finished = done.New()
o.hp.StartScheduler(func() ([]string, error) {
hs, ok := o.ohm.(outbound.HandlerSelector)
if !ok {
return nil, newError("outbound.Manager is not a HandlerSelector")
}
outbounds := hs.Select(o.config.SubjectSelector)
return outbounds, nil
})
}
return nil
}
func (o *Observer) Close() error {
if o.finished != nil {
o.hp.StopScheduler()
return o.finished.Close()
}
return nil
}
func New(ctx context.Context, config *Config) (*Observer, error) {
var outboundManager outbound.Manager
err := core.RequireFeatures(ctx, func(om outbound.Manager) {
outboundManager = om
})
if err != nil {
return nil, newError("Cannot get depended features").Base(err)
}
hp := NewHealthPing(ctx, config.PingConfig)
return &Observer{
config: config,
ctx: ctx,
ohm: outboundManager,
hp: hp,
}, 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/observatory/burst/config.pb.go | app/observatory/burst/config.pb.go | package burst
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"`
// @Document The selectors for outbound under observation
SubjectSelector []string `protobuf:"bytes,2,rep,name=subject_selector,json=subjectSelector,proto3" json:"subject_selector,omitempty"`
PingConfig *HealthPingConfig `protobuf:"bytes,3,opt,name=ping_config,json=pingConfig,proto3" json:"ping_config,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_observatory_burst_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_observatory_burst_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_observatory_burst_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetSubjectSelector() []string {
if x != nil {
return x.SubjectSelector
}
return nil
}
func (x *Config) GetPingConfig() *HealthPingConfig {
if x != nil {
return x.PingConfig
}
return nil
}
type HealthPingConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// destination url, need 204 for success return
// default https://connectivitycheck.gstatic.com/generate_204
Destination string `protobuf:"bytes,1,opt,name=destination,proto3" json:"destination,omitempty"`
// connectivity check url
Connectivity string `protobuf:"bytes,2,opt,name=connectivity,proto3" json:"connectivity,omitempty"`
// health check interval, int64 values of time.Duration
Interval int64 `protobuf:"varint,3,opt,name=interval,proto3" json:"interval,omitempty"`
// sampling count is the amount of recent ping results which are kept for calculation
SamplingCount int32 `protobuf:"varint,4,opt,name=samplingCount,proto3" json:"samplingCount,omitempty"`
// ping timeout, int64 values of time.Duration
Timeout int64 `protobuf:"varint,5,opt,name=timeout,proto3" json:"timeout,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *HealthPingConfig) Reset() {
*x = HealthPingConfig{}
mi := &file_app_observatory_burst_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *HealthPingConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HealthPingConfig) ProtoMessage() {}
func (x *HealthPingConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_burst_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 HealthPingConfig.ProtoReflect.Descriptor instead.
func (*HealthPingConfig) Descriptor() ([]byte, []int) {
return file_app_observatory_burst_config_proto_rawDescGZIP(), []int{1}
}
func (x *HealthPingConfig) GetDestination() string {
if x != nil {
return x.Destination
}
return ""
}
func (x *HealthPingConfig) GetConnectivity() string {
if x != nil {
return x.Connectivity
}
return ""
}
func (x *HealthPingConfig) GetInterval() int64 {
if x != nil {
return x.Interval
}
return 0
}
func (x *HealthPingConfig) GetSamplingCount() int32 {
if x != nil {
return x.SamplingCount
}
return 0
}
func (x *HealthPingConfig) GetTimeout() int64 {
if x != nil {
return x.Timeout
}
return 0
}
var File_app_observatory_burst_config_proto protoreflect.FileDescriptor
const file_app_observatory_burst_config_proto_rawDesc = "" +
"\n" +
"\"app/observatory/burst/config.proto\x12 v2ray.core.app.observatory.burst\x1a common/protoext/extensions.proto\"\xa9\x01\n" +
"\x06Config\x12)\n" +
"\x10subject_selector\x18\x02 \x03(\tR\x0fsubjectSelector\x12S\n" +
"\vping_config\x18\x03 \x01(\v22.v2ray.core.app.observatory.burst.HealthPingConfigR\n" +
"pingConfig:\x1f\x82\xb5\x18\x1b\n" +
"\aservice\x12\x10burstObservatory\"\xb4\x01\n" +
"\x10HealthPingConfig\x12 \n" +
"\vdestination\x18\x01 \x01(\tR\vdestination\x12\"\n" +
"\fconnectivity\x18\x02 \x01(\tR\fconnectivity\x12\x1a\n" +
"\binterval\x18\x03 \x01(\x03R\binterval\x12$\n" +
"\rsamplingCount\x18\x04 \x01(\x05R\rsamplingCount\x12\x18\n" +
"\atimeout\x18\x05 \x01(\x03R\atimeoutB\x81\x01\n" +
"$com.v2ray.core.app.observatory.burstP\x01Z4github.com/v2fly/v2ray-core/v5/app/observatory/burst\xaa\x02 V2Ray.Core.App.Observatory.Burstb\x06proto3"
var (
file_app_observatory_burst_config_proto_rawDescOnce sync.Once
file_app_observatory_burst_config_proto_rawDescData []byte
)
func file_app_observatory_burst_config_proto_rawDescGZIP() []byte {
file_app_observatory_burst_config_proto_rawDescOnce.Do(func() {
file_app_observatory_burst_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_observatory_burst_config_proto_rawDesc), len(file_app_observatory_burst_config_proto_rawDesc)))
})
return file_app_observatory_burst_config_proto_rawDescData
}
var file_app_observatory_burst_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_app_observatory_burst_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.app.observatory.burst.Config
(*HealthPingConfig)(nil), // 1: v2ray.core.app.observatory.burst.HealthPingConfig
}
var file_app_observatory_burst_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.app.observatory.burst.Config.ping_config:type_name -> v2ray.core.app.observatory.burst.HealthPingConfig
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_observatory_burst_config_proto_init() }
func file_app_observatory_burst_config_proto_init() {
if File_app_observatory_burst_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_observatory_burst_config_proto_rawDesc), len(file_app_observatory_burst_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_observatory_burst_config_proto_goTypes,
DependencyIndexes: file_app_observatory_burst_config_proto_depIdxs,
MessageInfos: file_app_observatory_burst_config_proto_msgTypes,
}.Build()
File_app_observatory_burst_config_proto = out.File
file_app_observatory_burst_config_proto_goTypes = nil
file_app_observatory_burst_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/observatory/burst/burst.go | app/observatory/burst/burst.go | package burst
import (
"math"
"time"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
const (
rttFailed = time.Duration(math.MaxInt64 - iota)
rttUntested // nolint: varcheck
rttUnqualified // nolint: varcheck
)
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/reverse.go | app/reverse/reverse.go | package reverse
//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/errors"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/features/outbound"
"github.com/v2fly/v2ray-core/v5/features/routing"
)
const (
internalDomain = "reverse.internal.v2fly.org"
)
func isDomain(dest net.Destination, domain string) bool {
return dest.Address.Family().IsDomain() && dest.Address.Domain() == domain
}
func isInternalDomain(dest net.Destination) bool {
return isDomain(dest, internalDomain)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
r := new(Reverse)
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher, om outbound.Manager) error {
return r.Init(ctx, config.(*Config), d, om)
}); err != nil {
return nil, err
}
return r, nil
}))
}
type Reverse struct {
bridges []*Bridge
portals []*Portal
}
func (r *Reverse) Init(ctx context.Context, config *Config, d routing.Dispatcher, ohm outbound.Manager) error {
for _, bConfig := range config.BridgeConfig {
b, err := NewBridge(ctx, bConfig, d)
if err != nil {
return err
}
r.bridges = append(r.bridges, b)
}
for _, pConfig := range config.PortalConfig {
p, err := NewPortal(ctx, pConfig, ohm)
if err != nil {
return err
}
r.portals = append(r.portals, p)
}
return nil
}
func (r *Reverse) Type() interface{} {
return (*Reverse)(nil)
}
func (r *Reverse) Start() error {
for _, b := range r.bridges {
if err := b.Start(); err != nil {
return err
}
}
for _, p := range r.portals {
if err := p.Start(); err != nil {
return err
}
}
return nil
}
func (r *Reverse) Close() error {
var errs []error
for _, b := range r.bridges {
errs = append(errs, b.Close())
}
for _, p := range r.portals {
errs = append(errs, p.Close())
}
return errors.Combine(errs...)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/errors.generated.go | app/reverse/errors.generated.go | package reverse
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/reverse/portal.go | app/reverse/portal.go | package reverse
import (
"context"
"sync"
"time"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/mux"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/outbound"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/pipe"
)
type Portal struct {
ctx context.Context
ohm outbound.Manager
tag string
domain string
picker *StaticMuxPicker
client *mux.ClientManager
}
func NewPortal(ctx context.Context, config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
if config.Tag == "" {
return nil, newError("portal tag is empty")
}
if config.Domain == "" {
return nil, newError("portal domain is empty")
}
picker, err := NewStaticMuxPicker()
if err != nil {
return nil, err
}
return &Portal{
ctx: ctx,
ohm: ohm,
tag: config.Tag,
domain: config.Domain,
picker: picker,
client: &mux.ClientManager{
Picker: picker,
},
}, nil
}
func (p *Portal) Start() error {
return p.ohm.AddHandler(p.ctx, &Outbound{
portal: p,
tag: p.tag,
})
}
func (p *Portal) Close() error {
return p.ohm.RemoveHandler(p.ctx, p.tag)
}
func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
outboundMeta := session.OutboundFromContext(ctx)
if outboundMeta == nil {
return newError("outbound metadata not found").AtError()
}
if isDomain(outboundMeta.Target, p.domain) {
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
if err != nil {
return newError("failed to create mux client worker").Base(err).AtWarning()
}
worker, err := NewPortalWorker(ctx, muxClient)
if err != nil {
return newError("failed to create portal worker").Base(err)
}
p.picker.AddWorker(worker)
return nil
}
return p.client.Dispatch(ctx, link)
}
type Outbound struct {
portal *Portal
tag string
}
func (o *Outbound) Tag() string {
return o.tag
}
func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
if err := o.portal.HandleConnection(ctx, link); err != nil {
newError("failed to process reverse connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
common.Interrupt(link.Writer)
}
}
func (o *Outbound) Start() error {
return nil
}
func (o *Outbound) Close() error {
return nil
}
type StaticMuxPicker struct {
access sync.Mutex
workers []*PortalWorker
cTask *task.Periodic
}
func NewStaticMuxPicker() (*StaticMuxPicker, error) {
p := &StaticMuxPicker{}
p.cTask = &task.Periodic{
Execute: p.cleanup,
Interval: time.Second * 30,
}
p.cTask.Start()
return p, nil
}
func (p *StaticMuxPicker) cleanup() error {
p.access.Lock()
defer p.access.Unlock()
var activeWorkers []*PortalWorker
for _, w := range p.workers {
if !w.Closed() {
activeWorkers = append(activeWorkers, w)
}
}
if len(activeWorkers) != len(p.workers) {
p.workers = activeWorkers
}
return nil
}
func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
p.access.Lock()
defer p.access.Unlock()
if len(p.workers) == 0 {
return nil, newError("empty worker list")
}
minIdx := -1
var minConn uint32 = 9999
for i, w := range p.workers {
if w.draining {
continue
}
if w.client.Closed() {
continue
}
if w.client.ActiveConnections() < minConn {
minConn = w.client.ActiveConnections()
minIdx = i
}
}
if minIdx == -1 {
for i, w := range p.workers {
if w.IsFull() {
continue
}
if w.client.ActiveConnections() < minConn {
minConn = w.client.ActiveConnections()
minIdx = i
}
}
}
if minIdx != -1 {
return p.workers[minIdx].client, nil
}
return nil, newError("no mux client worker available")
}
func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
p.access.Lock()
defer p.access.Unlock()
p.workers = append(p.workers, worker)
}
type PortalWorker struct {
client *mux.ClientWorker
control *task.Periodic
writer buf.Writer
reader buf.Reader
draining bool
}
func NewPortalWorker(ctx context.Context, client *mux.ClientWorker) (*PortalWorker, error) {
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
uplinkReader, uplinkWriter := pipe.New(opt...)
downlinkReader, downlinkWriter := pipe.New(opt...)
ctx = session.ContextWithOutbound(ctx, &session.Outbound{
Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
})
f := client.Dispatch(ctx, &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
})
if !f {
return nil, newError("unable to dispatch control connection")
}
w := &PortalWorker{
client: client,
reader: downlinkReader,
writer: uplinkWriter,
}
w.control = &task.Periodic{
Execute: w.heartbeat,
Interval: time.Second * 2,
}
w.control.Start()
return w, nil
}
func (w *PortalWorker) heartbeat() error {
if w.client.Closed() {
return newError("client worker stopped")
}
if w.draining || w.writer == nil {
return newError("already disposed")
}
msg := &Control{}
msg.FillInRandom()
if w.client.TotalConnections() > 256 {
w.draining = true
msg.State = Control_DRAIN
defer func() {
common.Close(w.writer)
common.Interrupt(w.reader)
w.writer = nil
}()
}
b, err := proto.Marshal(msg)
common.Must(err)
mb := buf.MergeBytes(nil, b)
return w.writer.WriteMultiBuffer(mb)
}
func (w *PortalWorker) IsFull() bool {
return w.client.IsFull()
}
func (w *PortalWorker) Closed() bool {
return w.client.Closed()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/config.go | app/reverse/config.go | package reverse
import (
"crypto/rand"
"io"
"github.com/v2fly/v2ray-core/v5/common/dice"
)
func (c *Control) FillInRandom() {
randomLength := dice.Roll(64)
c.Random = make([]byte, randomLength)
io.ReadFull(rand.Reader, c.Random)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/bridge.go | app/reverse/bridge.go | package reverse
import (
"context"
"time"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common/mux"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/pipe"
)
// Bridge is a component in reverse proxy, that relays connections from Portal to local address.
type Bridge struct {
ctx context.Context
dispatcher routing.Dispatcher
tag string
domain string
workers []*BridgeWorker
monitorTask *task.Periodic
}
// NewBridge creates a new Bridge instance.
func NewBridge(ctx context.Context, config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
if config.Tag == "" {
return nil, newError("bridge tag is empty")
}
if config.Domain == "" {
return nil, newError("bridge domain is empty")
}
b := &Bridge{
ctx: ctx,
dispatcher: dispatcher,
tag: config.Tag,
domain: config.Domain,
}
b.monitorTask = &task.Periodic{
Execute: b.monitor,
Interval: time.Second * 2,
}
return b, nil
}
func (b *Bridge) cleanup() {
var activeWorkers []*BridgeWorker
for _, w := range b.workers {
if w.IsActive() {
activeWorkers = append(activeWorkers, w)
}
}
if len(activeWorkers) != len(b.workers) {
b.workers = activeWorkers
}
}
func (b *Bridge) monitor() error {
b.cleanup()
var numConnections uint32
var numWorker uint32
for _, w := range b.workers {
if w.IsActive() {
numConnections += w.Connections()
numWorker++
}
}
if numWorker == 0 || numConnections/numWorker > 16 {
worker, err := NewBridgeWorker(b.ctx, b.domain, b.tag, b.dispatcher)
if err != nil {
newError("failed to create bridge worker").Base(err).AtWarning().WriteToLog()
return nil
}
b.workers = append(b.workers, worker)
}
return nil
}
func (b *Bridge) Start() error {
return b.monitorTask.Start()
}
func (b *Bridge) Close() error {
return b.monitorTask.Close()
}
type BridgeWorker struct {
tag string
worker *mux.ServerWorker
dispatcher routing.Dispatcher
state Control_State
}
func NewBridgeWorker(ctx context.Context, domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
bridgeCtx := session.ContextWithInbound(ctx, &session.Inbound{
Tag: tag,
})
link, err := d.Dispatch(bridgeCtx, net.Destination{
Network: net.Network_TCP,
Address: net.DomainAddress(domain),
Port: 0,
})
if err != nil {
return nil, err
}
w := &BridgeWorker{
dispatcher: d,
tag: tag,
}
worker, err := mux.NewServerWorker(ctx, w, link)
if err != nil {
return nil, err
}
w.worker = worker
return w, nil
}
func (w *BridgeWorker) Type() interface{} {
return routing.DispatcherType()
}
func (w *BridgeWorker) Start() error {
return nil
}
func (w *BridgeWorker) Close() error {
return nil
}
func (w *BridgeWorker) IsActive() bool {
return w.state == Control_ACTIVE && !w.worker.Closed()
}
func (w *BridgeWorker) Connections() uint32 {
return w.worker.ActiveConnections()
}
func (w *BridgeWorker) handleInternalConn(link transport.Link) {
go func() {
reader := link.Reader
for {
mb, err := reader.ReadMultiBuffer()
if err != nil {
break
}
for _, b := range mb {
var ctl Control
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
newError("failed to parse proto message").Base(err).WriteToLog()
break
}
if ctl.State != w.state {
w.state = ctl.State
}
}
}
}()
}
func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
if !isInternalDomain(dest) {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: w.tag,
})
return w.dispatcher.Dispatch(ctx, dest)
}
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
uplinkReader, uplinkWriter := pipe.New(opt...)
downlinkReader, downlinkWriter := pipe.New(opt...)
w.handleInternalConn(transport.Link{
Reader: downlinkReader,
Writer: uplinkWriter,
})
return &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
}, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/portal_test.go | app/reverse/portal_test.go | package reverse_test
import (
"testing"
"github.com/v2fly/v2ray-core/v5/app/reverse"
"github.com/v2fly/v2ray-core/v5/common"
)
func TestStaticPickerEmpty(t *testing.T) {
picker, err := reverse.NewStaticMuxPicker()
common.Must(err)
worker, err := picker.PickAvailable()
if err == nil {
t.Error("expected error, but nil")
}
if worker != nil {
t.Error("expected nil worker, but not nil")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/reverse/config.pb.go | app/reverse/config.pb.go | package reverse
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 Control_State int32
const (
Control_ACTIVE Control_State = 0
Control_DRAIN Control_State = 1
)
// Enum value maps for Control_State.
var (
Control_State_name = map[int32]string{
0: "ACTIVE",
1: "DRAIN",
}
Control_State_value = map[string]int32{
"ACTIVE": 0,
"DRAIN": 1,
}
)
func (x Control_State) Enum() *Control_State {
p := new(Control_State)
*p = x
return p
}
func (x Control_State) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
return file_app_reverse_config_proto_enumTypes[0].Descriptor()
}
func (Control_State) Type() protoreflect.EnumType {
return &file_app_reverse_config_proto_enumTypes[0]
}
func (x Control_State) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Control_State.Descriptor instead.
func (Control_State) EnumDescriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{0, 0}
}
type Control struct {
state protoimpl.MessageState `protogen:"open.v1"`
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=v2ray.core.app.reverse.Control_State" json:"state,omitempty"`
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Control) Reset() {
*x = Control{}
mi := &file_app_reverse_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Control) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Control) ProtoMessage() {}
func (x *Control) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_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 Control.ProtoReflect.Descriptor instead.
func (*Control) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{0}
}
func (x *Control) GetState() Control_State {
if x != nil {
return x.State
}
return Control_ACTIVE
}
func (x *Control) GetRandom() []byte {
if x != nil {
return x.Random
}
return nil
}
type BridgeConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *BridgeConfig) Reset() {
*x = BridgeConfig{}
mi := &file_app_reverse_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *BridgeConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*BridgeConfig) ProtoMessage() {}
func (x *BridgeConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_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 BridgeConfig.ProtoReflect.Descriptor instead.
func (*BridgeConfig) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{1}
}
func (x *BridgeConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *BridgeConfig) GetDomain() string {
if x != nil {
return x.Domain
}
return ""
}
type PortalConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PortalConfig) Reset() {
*x = PortalConfig{}
mi := &file_app_reverse_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PortalConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PortalConfig) ProtoMessage() {}
func (x *PortalConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_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 PortalConfig.ProtoReflect.Descriptor instead.
func (*PortalConfig) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{2}
}
func (x *PortalConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *PortalConfig) GetDomain() string {
if x != nil {
return x.Domain
}
return ""
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
BridgeConfig []*BridgeConfig `protobuf:"bytes,1,rep,name=bridge_config,json=bridgeConfig,proto3" json:"bridge_config,omitempty"`
PortalConfig []*PortalConfig `protobuf:"bytes,2,rep,name=portal_config,json=portalConfig,proto3" json:"portal_config,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_reverse_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_reverse_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_reverse_config_proto_rawDescGZIP(), []int{3}
}
func (x *Config) GetBridgeConfig() []*BridgeConfig {
if x != nil {
return x.BridgeConfig
}
return nil
}
func (x *Config) GetPortalConfig() []*PortalConfig {
if x != nil {
return x.PortalConfig
}
return nil
}
var File_app_reverse_config_proto protoreflect.FileDescriptor
const file_app_reverse_config_proto_rawDesc = "" +
"\n" +
"\x18app/reverse/config.proto\x12\x16v2ray.core.app.reverse\x1a common/protoext/extensions.proto\"~\n" +
"\aControl\x12;\n" +
"\x05state\x18\x01 \x01(\x0e2%.v2ray.core.app.reverse.Control.StateR\x05state\x12\x16\n" +
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
"\x05State\x12\n" +
"\n" +
"\x06ACTIVE\x10\x00\x12\t\n" +
"\x05DRAIN\x10\x01\"8\n" +
"\fBridgeConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
"\x06domain\x18\x02 \x01(\tR\x06domain\"8\n" +
"\fPortalConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
"\x06domain\x18\x02 \x01(\tR\x06domain\"\xb6\x01\n" +
"\x06Config\x12I\n" +
"\rbridge_config\x18\x01 \x03(\v2$.v2ray.core.app.reverse.BridgeConfigR\fbridgeConfig\x12I\n" +
"\rportal_config\x18\x02 \x03(\v2$.v2ray.core.app.reverse.PortalConfigR\fportalConfig:\x16\x82\xb5\x18\x12\n" +
"\aservice\x12\areverseBg\n" +
"\x1ccom.v2ray.core.proxy.reverseP\x01Z*github.com/v2fly/v2ray-core/v5/app/reverse\xaa\x02\x18V2Ray.Core.Proxy.Reverseb\x06proto3"
var (
file_app_reverse_config_proto_rawDescOnce sync.Once
file_app_reverse_config_proto_rawDescData []byte
)
func file_app_reverse_config_proto_rawDescGZIP() []byte {
file_app_reverse_config_proto_rawDescOnce.Do(func() {
file_app_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)))
})
return file_app_reverse_config_proto_rawDescData
}
var file_app_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_app_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_app_reverse_config_proto_goTypes = []any{
(Control_State)(0), // 0: v2ray.core.app.reverse.Control.State
(*Control)(nil), // 1: v2ray.core.app.reverse.Control
(*BridgeConfig)(nil), // 2: v2ray.core.app.reverse.BridgeConfig
(*PortalConfig)(nil), // 3: v2ray.core.app.reverse.PortalConfig
(*Config)(nil), // 4: v2ray.core.app.reverse.Config
}
var file_app_reverse_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.reverse.Control.state:type_name -> v2ray.core.app.reverse.Control.State
2, // 1: v2ray.core.app.reverse.Config.bridge_config:type_name -> v2ray.core.app.reverse.BridgeConfig
3, // 2: v2ray.core.app.reverse.Config.portal_config:type_name -> v2ray.core.app.reverse.PortalConfig
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_app_reverse_config_proto_init() }
func file_app_reverse_config_proto_init() {
if File_app_reverse_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_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)),
NumEnums: 1,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_reverse_config_proto_goTypes,
DependencyIndexes: file_app_reverse_config_proto_depIdxs,
EnumInfos: file_app_reverse_config_proto_enumTypes,
MessageInfos: file_app_reverse_config_proto_msgTypes,
}.Build()
File_app_reverse_config_proto = out.File
file_app_reverse_config_proto_goTypes = nil
file_app_reverse_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/persistentstorage/storage.go | app/persistentstorage/storage.go | package persistentstorage
import "github.com/v2fly/v2ray-core/v5/features/extension/storage"
type ScopedPersistentStorage = storage.ScopedPersistentStorage
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/persistentstorage/protostorage/protokv.go | app/persistentstorage/protostorage/protokv.go | package protostorage
import (
"context"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/features/extension/storage"
)
type ProtoPersistentStorage interface {
PutProto(ctx context.Context, key string, pb proto.Message) error
GetProto(ctx context.Context, key string, pb proto.Message) error
}
type protoStorage struct {
storage storage.ScopedPersistentStorage
textFormat bool
}
func (p *protoStorage) PutProto(ctx context.Context, key string, pb proto.Message) error {
if !p.textFormat {
data, err := proto.Marshal(pb)
if err != nil {
return err
}
return p.storage.Put(ctx, []byte(key), data)
} else {
protojsonStr := protojson.Format(pb)
return p.storage.Put(ctx, []byte(key), []byte(protojsonStr))
}
}
func (p *protoStorage) GetProto(ctx context.Context, key string, pb proto.Message) error {
data, err := p.storage.Get(ctx, []byte(key))
if err != nil {
return err
}
if !p.textFormat {
return proto.Unmarshal(data, pb)
}
return protojson.Unmarshal(data, pb)
}
func NewProtoStorage(storage storage.ScopedPersistentStorage, textFormat bool) ProtoPersistentStorage {
return &protoStorage{
storage: storage,
textFormat: textFormat,
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/persistentstorage/filesystemstorage/config.pb.go | app/persistentstorage/filesystemstorage/config.pb.go | package filesystemstorage
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 StateStorageRoot int32
const (
StateStorageRoot_WorkDir StateStorageRoot = 0
)
// Enum value maps for StateStorageRoot.
var (
StateStorageRoot_name = map[int32]string{
0: "WorkDir",
}
StateStorageRoot_value = map[string]int32{
"WorkDir": 0,
}
)
func (x StateStorageRoot) Enum() *StateStorageRoot {
p := new(StateStorageRoot)
*p = x
return p
}
func (x StateStorageRoot) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (StateStorageRoot) Descriptor() protoreflect.EnumDescriptor {
return file_app_persistentstorage_filesystemstorage_config_proto_enumTypes[0].Descriptor()
}
func (StateStorageRoot) Type() protoreflect.EnumType {
return &file_app_persistentstorage_filesystemstorage_config_proto_enumTypes[0]
}
func (x StateStorageRoot) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use StateStorageRoot.Descriptor instead.
func (StateStorageRoot) EnumDescriptor() ([]byte, []int) {
return file_app_persistentstorage_filesystemstorage_config_proto_rawDescGZIP(), []int{0}
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
StateStorageRoot StateStorageRoot `protobuf:"varint,1,opt,name=state_storage_root,json=stateStorageRoot,proto3,enum=v2ray.core.app.persistentstorage.filesystemstorage.StateStorageRoot" json:"state_storage_root,omitempty"`
InstanceName string `protobuf:"bytes,4,opt,name=instance_name,json=instanceName,proto3" json:"instance_name,omitempty"`
Protojson bool `protobuf:"varint,5,opt,name=protojson,proto3" json:"protojson,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_persistentstorage_filesystemstorage_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_persistentstorage_filesystemstorage_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_persistentstorage_filesystemstorage_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetStateStorageRoot() StateStorageRoot {
if x != nil {
return x.StateStorageRoot
}
return StateStorageRoot_WorkDir
}
func (x *Config) GetInstanceName() string {
if x != nil {
return x.InstanceName
}
return ""
}
func (x *Config) GetProtojson() bool {
if x != nil {
return x.Protojson
}
return false
}
var File_app_persistentstorage_filesystemstorage_config_proto protoreflect.FileDescriptor
const file_app_persistentstorage_filesystemstorage_config_proto_rawDesc = "" +
"\n" +
"4app/persistentstorage/filesystemstorage/config.proto\x122v2ray.core.app.persistentstorage.filesystemstorage\x1a common/protoext/extensions.proto\"\xe1\x01\n" +
"\x06Config\x12r\n" +
"\x12state_storage_root\x18\x01 \x01(\x0e2D.v2ray.core.app.persistentstorage.filesystemstorage.StateStorageRootR\x10stateStorageRoot\x12#\n" +
"\rinstance_name\x18\x04 \x01(\tR\finstanceName\x12\x1c\n" +
"\tprotojson\x18\x05 \x01(\bR\tprotojson: \x82\xb5\x18\x1c\n" +
"\aservice\x12\x11filesystemstorage*\x1f\n" +
"\x10StateStorageRoot\x12\v\n" +
"\aWorkDir\x10\x00B\xb3\x01\n" +
"2com.v2ray.core.persistentstorage.filesystemstorageP\x01ZFgithub.com/v2fly/v2ray-core/v5/app/persistentstorage/filesystemstorage\xaa\x022V2Ray.Core.App.Persistentstorage.Filesystemstorageb\x06proto3"
var (
file_app_persistentstorage_filesystemstorage_config_proto_rawDescOnce sync.Once
file_app_persistentstorage_filesystemstorage_config_proto_rawDescData []byte
)
func file_app_persistentstorage_filesystemstorage_config_proto_rawDescGZIP() []byte {
file_app_persistentstorage_filesystemstorage_config_proto_rawDescOnce.Do(func() {
file_app_persistentstorage_filesystemstorage_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_persistentstorage_filesystemstorage_config_proto_rawDesc), len(file_app_persistentstorage_filesystemstorage_config_proto_rawDesc)))
})
return file_app_persistentstorage_filesystemstorage_config_proto_rawDescData
}
var file_app_persistentstorage_filesystemstorage_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_app_persistentstorage_filesystemstorage_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_app_persistentstorage_filesystemstorage_config_proto_goTypes = []any{
(StateStorageRoot)(0), // 0: v2ray.core.app.persistentstorage.filesystemstorage.StateStorageRoot
(*Config)(nil), // 1: v2ray.core.app.persistentstorage.filesystemstorage.Config
}
var file_app_persistentstorage_filesystemstorage_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.persistentstorage.filesystemstorage.Config.state_storage_root:type_name -> v2ray.core.app.persistentstorage.filesystemstorage.StateStorageRoot
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_persistentstorage_filesystemstorage_config_proto_init() }
func file_app_persistentstorage_filesystemstorage_config_proto_init() {
if File_app_persistentstorage_filesystemstorage_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_persistentstorage_filesystemstorage_config_proto_rawDesc), len(file_app_persistentstorage_filesystemstorage_config_proto_rawDesc)),
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_persistentstorage_filesystemstorage_config_proto_goTypes,
DependencyIndexes: file_app_persistentstorage_filesystemstorage_config_proto_depIdxs,
EnumInfos: file_app_persistentstorage_filesystemstorage_config_proto_enumTypes,
MessageInfos: file_app_persistentstorage_filesystemstorage_config_proto_msgTypes,
}.Build()
File_app_persistentstorage_filesystemstorage_config_proto = out.File
file_app_persistentstorage_filesystemstorage_config_proto_goTypes = nil
file_app_persistentstorage_filesystemstorage_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/persistentstorage/filesystemstorage/fs.go | app/persistentstorage/filesystemstorage/fs.go | package filesystemstorage
import (
"bytes"
"context"
"io"
"path/filepath"
"strings"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/app/persistentstorage/protostorage"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/features/extension/storage"
)
func newFileSystemStorage(ctx context.Context, config *Config) storage.ScopedPersistentStorageService {
appEnvironment := envctx.EnvironmentFromContext(ctx).(environment.AppEnvironment)
fss := &fileSystemStorage{
fs: appEnvironment,
pathRoot: config.InstanceName,
currentLocation: nil,
config: config,
}
protoStorageInst := protostorage.NewProtoStorage(fss, config.Protojson)
fss.proto = protoStorageInst
return fss
}
type fileSystemStorage struct {
fs environment.FileSystemCapabilitySet
proto protostorage.ProtoPersistentStorage
pathRoot string
currentLocation []string
config *Config
}
func (f *fileSystemStorage) Type() interface{} {
return storage.ScopedPersistentStorageServiceType
}
func (f *fileSystemStorage) Start() error {
return nil
}
func (f *fileSystemStorage) Close() error {
return nil
}
func (f *fileSystemStorage) PutProto(ctx context.Context, key string, pb proto.Message) error {
return f.proto.PutProto(ctx, key, pb)
}
func (f *fileSystemStorage) GetProto(ctx context.Context, key string, pb proto.Message) error {
return f.proto.GetProto(ctx, key, pb)
}
func (f *fileSystemStorage) ScopedPersistentStorageEngine() {
}
func (f *fileSystemStorage) Put(ctx context.Context, key []byte, value []byte) error {
finalPath := filepath.Join(f.pathRoot, filepath.Join(f.currentLocation...), string(key))
if value == nil {
return f.fs.RemoveFile()(finalPath)
}
writer, err := f.fs.OpenFileForWrite()(finalPath)
if err != nil {
return err
}
defer writer.Close()
_, err = io.Copy(writer, io.NopCloser(bytes.NewReader(value)))
return err
}
func (f *fileSystemStorage) Get(ctx context.Context, key []byte) ([]byte, error) {
finalPath := filepath.Join(f.pathRoot, filepath.Join(f.currentLocation...), string(key))
reader, err := f.fs.OpenFileForRead()(finalPath)
if err != nil {
return nil, err
}
defer reader.Close()
return io.ReadAll(reader)
}
func (f *fileSystemStorage) List(ctx context.Context, keyPrefix []byte) ([][]byte, error) {
res, err := f.fs.ReadDir()(filepath.Join(f.pathRoot, filepath.Join(f.currentLocation...)))
if err != nil {
return nil, err
}
var result [][]byte
for _, entry := range res {
if !entry.IsDir() && bytes.HasPrefix([]byte(entry.Name()), keyPrefix) {
result = append(result, []byte(entry.Name()))
}
}
return result, nil
}
func (f *fileSystemStorage) Clear(ctx context.Context) {
allFile, err := f.List(ctx, []byte{})
if err != nil {
return
}
for _, file := range allFile {
_ = f.Put(ctx, file, nil)
}
}
func (f *fileSystemStorage) NarrowScope(ctx context.Context, key []byte) (storage.ScopedPersistentStorage, error) {
escapedKey := strings.ReplaceAll(string(key), "/", "_")
fss := &fileSystemStorage{
fs: f.fs,
pathRoot: f.pathRoot,
currentLocation: append(f.currentLocation, escapedKey),
config: f.config,
}
fss.proto = protostorage.NewProtoStorage(fss, f.config.Protojson)
return fss, nil
}
func (f *fileSystemStorage) DropScope(ctx context.Context, key []byte) error {
panic("unimplemented")
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return newFileSystemStorage(ctx, config.(*Config)), nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/stats.go | app/stats/stats.go | package stats
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"sync"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
// Manager is an implementation of stats.Manager.
type Manager struct {
access sync.RWMutex
counters map[string]*Counter
channels map[string]*Channel
running bool
}
// NewManager creates an instance of Statistics Manager.
func NewManager(ctx context.Context, config *Config) (*Manager, error) {
m := &Manager{
counters: make(map[string]*Counter),
channels: make(map[string]*Channel),
}
return m, nil
}
// Type implements common.HasType.
func (*Manager) Type() interface{} {
return stats.ManagerType()
}
// RegisterCounter implements stats.Manager.
func (m *Manager) RegisterCounter(name string) (stats.Counter, error) {
m.access.Lock()
defer m.access.Unlock()
if _, found := m.counters[name]; found {
return nil, newError("Counter ", name, " already registered.")
}
newError("create new counter ", name).AtDebug().WriteToLog()
c := new(Counter)
m.counters[name] = c
return c, nil
}
// UnregisterCounter implements stats.Manager.
func (m *Manager) UnregisterCounter(name string) error {
m.access.Lock()
defer m.access.Unlock()
if _, found := m.counters[name]; found {
newError("remove counter ", name).AtDebug().WriteToLog()
delete(m.counters, name)
}
return nil
}
// GetCounter implements stats.Manager.
func (m *Manager) GetCounter(name string) stats.Counter {
m.access.RLock()
defer m.access.RUnlock()
if c, found := m.counters[name]; found {
return c
}
return nil
}
// VisitCounters calls visitor function on all managed counters.
func (m *Manager) VisitCounters(visitor func(string, stats.Counter) bool) {
m.access.RLock()
defer m.access.RUnlock()
for name, c := range m.counters {
if !visitor(name, c) {
break
}
}
}
// RegisterChannel implements stats.Manager.
func (m *Manager) RegisterChannel(name string) (stats.Channel, error) {
m.access.Lock()
defer m.access.Unlock()
if _, found := m.channels[name]; found {
return nil, newError("Channel ", name, " already registered.")
}
newError("create new channel ", name).AtDebug().WriteToLog()
c := NewChannel(&ChannelConfig{BufferSize: 64, Blocking: false})
m.channels[name] = c
if m.running {
return c, c.Start()
}
return c, nil
}
// UnregisterChannel implements stats.Manager.
func (m *Manager) UnregisterChannel(name string) error {
m.access.Lock()
defer m.access.Unlock()
if c, found := m.channels[name]; found {
newError("remove channel ", name).AtDebug().WriteToLog()
delete(m.channels, name)
return c.Close()
}
return nil
}
// GetChannel implements stats.Manager.
func (m *Manager) GetChannel(name string) stats.Channel {
m.access.RLock()
defer m.access.RUnlock()
if c, found := m.channels[name]; found {
return c
}
return nil
}
// Start implements common.Runnable.
func (m *Manager) Start() error {
m.access.Lock()
defer m.access.Unlock()
m.running = true
errs := []error{}
for _, channel := range m.channels {
if err := channel.Start(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Combine(errs...)
}
return nil
}
// Close implement common.Closable.
func (m *Manager) Close() error {
m.access.Lock()
defer m.access.Unlock()
m.running = false
errs := []error{}
for name, channel := range m.channels {
newError("remove channel ", name).AtDebug().WriteToLog()
delete(m.channels, name)
if err := channel.Close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Combine(errs...)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewManager(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/stats/errors.generated.go | app/stats/errors.generated.go | package stats
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/counter_test.go | app/stats/counter_test.go | package stats_test
import (
"context"
"testing"
. "github.com/v2fly/v2ray-core/v5/app/stats"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
func TestStatsCounter(t *testing.T) {
raw, err := common.CreateObject(context.Background(), &Config{})
common.Must(err)
m := raw.(stats.Manager)
c, err := m.RegisterCounter("test.counter")
common.Must(err)
if v := c.Add(1); v != 1 {
t.Fatal("unpexcted Add(1) return: ", v, ", wanted ", 1)
}
if v := c.Set(0); v != 1 {
t.Fatal("unexpected Set(0) return: ", v, ", wanted ", 1)
}
if v := c.Value(); v != 0 {
t.Fatal("unexpected Value() return: ", v, ", wanted ", 0)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/stats_test.go | app/stats/stats_test.go | package stats_test
import (
"context"
"testing"
"time"
. "github.com/v2fly/v2ray-core/v5/app/stats"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
func TestInterface(t *testing.T) {
_ = (stats.Manager)(new(Manager))
}
func TestStatsChannelRunnable(t *testing.T) {
raw, err := common.CreateObject(context.Background(), &Config{})
common.Must(err)
m := raw.(stats.Manager)
ch1, err := m.RegisterChannel("test.channel.1")
c1 := ch1.(*Channel)
common.Must(err)
if c1.Running() {
t.Fatalf("unexpected running channel: test.channel.%d", 1)
}
common.Must(m.Start())
if !c1.Running() {
t.Fatalf("unexpected non-running channel: test.channel.%d", 1)
}
ch2, err := m.RegisterChannel("test.channel.2")
c2 := ch2.(*Channel)
common.Must(err)
if !c2.Running() {
t.Fatalf("unexpected non-running channel: test.channel.%d", 2)
}
s1, err := c1.Subscribe()
common.Must(err)
common.Must(c1.Close())
if c1.Running() {
t.Fatalf("unexpected running channel: test.channel.%d", 1)
}
select { // Check all subscribers in closed channel are closed
case _, ok := <-s1:
if ok {
t.Fatalf("unexpected non-closed subscriber in channel: test.channel.%d", 1)
}
case <-time.After(500 * time.Millisecond):
t.Fatalf("unexpected non-closed subscriber in channel: test.channel.%d", 1)
}
if len(c1.Subscribers()) != 0 { // Check subscribers in closed channel are emptied
t.Fatalf("unexpected non-empty subscribers in channel: test.channel.%d", 1)
}
common.Must(m.Close())
if c2.Running() {
t.Fatalf("unexpected running channel: test.channel.%d", 2)
}
ch3, err := m.RegisterChannel("test.channel.3")
c3 := ch3.(*Channel)
common.Must(err)
if c3.Running() {
t.Fatalf("unexpected running channel: test.channel.%d", 3)
}
common.Must(c3.Start())
common.Must(m.UnregisterChannel("test.channel.3"))
if c3.Running() { // Test that unregistering will close the channel.
t.Fatalf("unexpected running channel: test.channel.%d", 3)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/counter.go | app/stats/counter.go | package stats
import "sync/atomic"
// Counter is an implementation of stats.Counter.
type Counter struct {
value int64
}
// Value implements stats.Counter.
func (c *Counter) Value() int64 {
return atomic.LoadInt64(&c.value)
}
// Set implements stats.Counter.
func (c *Counter) Set(newValue int64) int64 {
return atomic.SwapInt64(&c.value, newValue)
}
// Add implements stats.Counter.
func (c *Counter) Add(delta int64) int64 {
return atomic.AddInt64(&c.value, delta)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/config.pb.go | app/stats/config.pb.go | package stats
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"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_stats_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_stats_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_stats_config_proto_rawDescGZIP(), []int{0}
}
type ChannelConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Blocking bool `protobuf:"varint,1,opt,name=Blocking,proto3" json:"Blocking,omitempty"`
SubscriberLimit int32 `protobuf:"varint,2,opt,name=SubscriberLimit,proto3" json:"SubscriberLimit,omitempty"`
BufferSize int32 `protobuf:"varint,3,opt,name=BufferSize,proto3" json:"BufferSize,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChannelConfig) Reset() {
*x = ChannelConfig{}
mi := &file_app_stats_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChannelConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChannelConfig) ProtoMessage() {}
func (x *ChannelConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 ChannelConfig.ProtoReflect.Descriptor instead.
func (*ChannelConfig) Descriptor() ([]byte, []int) {
return file_app_stats_config_proto_rawDescGZIP(), []int{1}
}
func (x *ChannelConfig) GetBlocking() bool {
if x != nil {
return x.Blocking
}
return false
}
func (x *ChannelConfig) GetSubscriberLimit() int32 {
if x != nil {
return x.SubscriberLimit
}
return 0
}
func (x *ChannelConfig) GetBufferSize() int32 {
if x != nil {
return x.BufferSize
}
return 0
}
var File_app_stats_config_proto protoreflect.FileDescriptor
const file_app_stats_config_proto_rawDesc = "" +
"\n" +
"\x16app/stats/config.proto\x12\x14v2ray.core.app.stats\x1a common/protoext/extensions.proto\"\x1e\n" +
"\x06Config:\x14\x82\xb5\x18\x10\n" +
"\aservice\x12\x05stats\"u\n" +
"\rChannelConfig\x12\x1a\n" +
"\bBlocking\x18\x01 \x01(\bR\bBlocking\x12(\n" +
"\x0fSubscriberLimit\x18\x02 \x01(\x05R\x0fSubscriberLimit\x12\x1e\n" +
"\n" +
"BufferSize\x18\x03 \x01(\x05R\n" +
"BufferSizeB]\n" +
"\x18com.v2ray.core.app.statsP\x01Z(github.com/v2fly/v2ray-core/v5/app/stats\xaa\x02\x14V2Ray.Core.App.Statsb\x06proto3"
var (
file_app_stats_config_proto_rawDescOnce sync.Once
file_app_stats_config_proto_rawDescData []byte
)
func file_app_stats_config_proto_rawDescGZIP() []byte {
file_app_stats_config_proto_rawDescOnce.Do(func() {
file_app_stats_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_stats_config_proto_rawDesc), len(file_app_stats_config_proto_rawDesc)))
})
return file_app_stats_config_proto_rawDescData
}
var file_app_stats_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_app_stats_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.app.stats.Config
(*ChannelConfig)(nil), // 1: v2ray.core.app.stats.ChannelConfig
}
var file_app_stats_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_stats_config_proto_init() }
func file_app_stats_config_proto_init() {
if File_app_stats_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_stats_config_proto_rawDesc), len(file_app_stats_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_stats_config_proto_goTypes,
DependencyIndexes: file_app_stats_config_proto_depIdxs,
MessageInfos: file_app_stats_config_proto_msgTypes,
}.Build()
File_app_stats_config_proto = out.File
file_app_stats_config_proto_goTypes = nil
file_app_stats_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/stats/channel.go | app/stats/channel.go | package stats
import (
"context"
"sync"
"github.com/v2fly/v2ray-core/v5/common"
)
// Channel is an implementation of stats.Channel.
type Channel struct {
channel chan channelMessage
subscribers []chan interface{}
// Synchronization components
access sync.RWMutex
closed chan struct{}
// Channel options
blocking bool // Set blocking state if channel buffer reaches limit
bufferSize int // Set to 0 as no buffering
subsLimit int // Set to 0 as no subscriber limit
}
// NewChannel creates an instance of Statistics Channel.
func NewChannel(config *ChannelConfig) *Channel {
return &Channel{
channel: make(chan channelMessage, config.BufferSize),
subsLimit: int(config.SubscriberLimit),
bufferSize: int(config.BufferSize),
blocking: config.Blocking,
}
}
// Subscribers implements stats.Channel.
func (c *Channel) Subscribers() []chan interface{} {
c.access.RLock()
defer c.access.RUnlock()
return c.subscribers
}
// Subscribe implements stats.Channel.
func (c *Channel) Subscribe() (chan interface{}, error) {
c.access.Lock()
defer c.access.Unlock()
if c.subsLimit > 0 && len(c.subscribers) >= c.subsLimit {
return nil, newError("Number of subscribers has reached limit")
}
subscriber := make(chan interface{}, c.bufferSize)
c.subscribers = append(c.subscribers, subscriber)
return subscriber, nil
}
// Unsubscribe implements stats.Channel.
func (c *Channel) Unsubscribe(subscriber chan interface{}) error {
c.access.Lock()
defer c.access.Unlock()
for i, s := range c.subscribers {
if s == subscriber {
// Copy to new memory block to prevent modifying original data
subscribers := make([]chan interface{}, len(c.subscribers)-1)
copy(subscribers[:i], c.subscribers[:i])
copy(subscribers[i:], c.subscribers[i+1:])
c.subscribers = subscribers
}
}
return nil
}
// Publish implements stats.Channel.
func (c *Channel) Publish(ctx context.Context, msg interface{}) {
select { // Early exit if channel closed
case <-c.closed:
return
default:
pub := channelMessage{context: ctx, message: msg}
if c.blocking {
pub.publish(c.channel)
} else {
pub.publishNonBlocking(c.channel)
}
}
}
// Running returns whether the channel is running.
func (c *Channel) Running() bool {
select {
case <-c.closed: // Channel closed
default: // Channel running or not initialized
if c.closed != nil { // Channel initialized
return true
}
}
return false
}
// Start implements common.Runnable.
func (c *Channel) Start() error {
c.access.Lock()
defer c.access.Unlock()
if !c.Running() {
c.closed = make(chan struct{}) // Reset close signal
go func() {
for {
select {
case pub := <-c.channel: // Published message received
for _, sub := range c.Subscribers() { // Concurrency-safe subscribers retrievement
if c.blocking {
pub.broadcast(sub)
} else {
pub.broadcastNonBlocking(sub)
}
}
case <-c.closed: // Channel closed
for _, sub := range c.Subscribers() { // Remove all subscribers
common.Must(c.Unsubscribe(sub))
close(sub)
}
return
}
}
}()
}
return nil
}
// Close implements common.Closable.
func (c *Channel) Close() error {
c.access.Lock()
defer c.access.Unlock()
if c.Running() {
close(c.closed) // Send closed signal
}
return nil
}
// channelMessage is the published message with guaranteed delivery.
// message is discarded only when the context is early cancelled.
type channelMessage struct {
context context.Context
message interface{}
}
func (c channelMessage) publish(publisher chan channelMessage) {
select {
case publisher <- c:
case <-c.context.Done():
}
}
func (c channelMessage) publishNonBlocking(publisher chan channelMessage) {
select {
case publisher <- c:
default: // Create another goroutine to keep sending message
go c.publish(publisher)
}
}
func (c channelMessage) broadcast(subscriber chan interface{}) {
select {
case subscriber <- c.message:
case <-c.context.Done():
}
}
func (c channelMessage) broadcastNonBlocking(subscriber chan interface{}) {
select {
case subscriber <- c.message:
default: // Create another goroutine to keep sending message
go c.broadcast(subscriber)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/channel_test.go | app/stats/channel_test.go | package stats_test
import (
"context"
"fmt"
"testing"
"time"
. "github.com/v2fly/v2ray-core/v5/app/stats"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
func TestStatsChannel(t *testing.T) {
// At most 2 subscribers could be registered
c := NewChannel(&ChannelConfig{SubscriberLimit: 2, Blocking: true})
a, err := stats.SubscribeRunnableChannel(c)
common.Must(err)
if !c.Running() {
t.Fatal("unexpected failure in running channel after first subscription")
}
b, err := c.Subscribe()
common.Must(err)
// Test that third subscriber is forbidden
_, err = c.Subscribe()
if err == nil {
t.Fatal("unexpected successful subscription")
}
t.Log("expected error: ", err)
stopCh := make(chan struct{})
errCh := make(chan string)
go func() {
c.Publish(context.Background(), 1)
c.Publish(context.Background(), 2)
c.Publish(context.Background(), "3")
c.Publish(context.Background(), []int{4})
stopCh <- struct{}{}
}()
go func() {
if v, ok := (<-a).(int); !ok || v != 1 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 1)
}
if v, ok := (<-a).(int); !ok || v != 2 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 2)
}
if v, ok := (<-a).(string); !ok || v != "3" {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", "3")
}
if v, ok := (<-a).([]int); !ok || v[0] != 4 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", []int{4})
}
stopCh <- struct{}{}
}()
go func() {
if v, ok := (<-b).(int); !ok || v != 1 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 1)
}
if v, ok := (<-b).(int); !ok || v != 2 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 2)
}
if v, ok := (<-b).(string); !ok || v != "3" {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", "3")
}
if v, ok := (<-b).([]int); !ok || v[0] != 4 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", []int{4})
}
stopCh <- struct{}{}
}()
timeout := time.After(2 * time.Second)
for i := 0; i < 3; i++ {
select {
case <-timeout:
t.Fatal("Test timeout after 2s")
case e := <-errCh:
t.Fatal(e)
case <-stopCh:
}
}
// Test the unsubscription of channel
common.Must(c.Unsubscribe(b))
// Test the last subscriber will close channel with `UnsubscribeClosableChannel`
common.Must(stats.UnsubscribeClosableChannel(c, a))
if c.Running() {
t.Fatal("unexpected running channel after unsubscribing the last subscriber")
}
}
func TestStatsChannelUnsubcribe(t *testing.T) {
c := NewChannel(&ChannelConfig{Blocking: true})
common.Must(c.Start())
defer c.Close()
a, err := c.Subscribe()
common.Must(err)
defer c.Unsubscribe(a)
b, err := c.Subscribe()
common.Must(err)
pauseCh := make(chan struct{})
stopCh := make(chan struct{})
errCh := make(chan string)
{
var aSet, bSet bool
for _, s := range c.Subscribers() {
if s == a {
aSet = true
}
if s == b {
bSet = true
}
}
if !(aSet && bSet) {
t.Fatal("unexpected subscribers: ", c.Subscribers())
}
}
go func() { // Blocking publish
c.Publish(context.Background(), 1)
<-pauseCh // Wait for `b` goroutine to resume sending message
c.Publish(context.Background(), 2)
}()
go func() {
if v, ok := (<-a).(int); !ok || v != 1 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 1)
}
if v, ok := (<-a).(int); !ok || v != 2 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 2)
}
}()
go func() {
if v, ok := (<-b).(int); !ok || v != 1 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 1)
}
// Unsubscribe `b` while publishing is paused
c.Unsubscribe(b)
{ // Test `b` is not in subscribers
var aSet, bSet bool
for _, s := range c.Subscribers() {
if s == a {
aSet = true
}
if s == b {
bSet = true
}
}
if !(aSet && !bSet) {
errCh <- fmt.Sprint("unexpected subscribers: ", c.Subscribers())
}
}
// Resume publishing progress
close(pauseCh)
// Test `b` is neither closed nor able to receive any data
select {
case v, ok := <-b:
if ok {
errCh <- fmt.Sprint("unexpected data received: ", v)
} else {
errCh <- fmt.Sprint("unexpected closed channel: ", b)
}
default:
}
close(stopCh)
}()
select {
case <-time.After(2 * time.Second):
t.Fatal("Test timeout after 2s")
case e := <-errCh:
t.Fatal(e)
case <-stopCh:
}
}
func TestStatsChannelBlocking(t *testing.T) {
// Do not use buffer so as to create blocking scenario
c := NewChannel(&ChannelConfig{BufferSize: 0, Blocking: true})
common.Must(c.Start())
defer c.Close()
a, err := c.Subscribe()
common.Must(err)
defer c.Unsubscribe(a)
pauseCh := make(chan struct{})
stopCh := make(chan struct{})
errCh := make(chan string)
ctx, cancel := context.WithCancel(context.Background())
// Test blocking channel publishing
go func() {
// Dummy message with no subscriber receiving, will block broadcasting goroutine
c.Publish(context.Background(), nil)
<-pauseCh
// Publishing should be blocked here, for last message was not cleared and buffer was full
c.Publish(context.Background(), nil)
pauseCh <- struct{}{}
// Publishing should still be blocked here
c.Publish(ctx, nil)
// Check publishing is done because context is canceled
select {
case <-ctx.Done():
if ctx.Err() != context.Canceled {
errCh <- fmt.Sprint("unexpected error: ", ctx.Err())
}
default:
errCh <- "unexpected non-blocked publishing"
}
close(stopCh)
}()
go func() {
pauseCh <- struct{}{}
select {
case <-pauseCh:
errCh <- "unexpected non-blocked publishing"
case <-time.After(100 * time.Millisecond):
}
// Receive first published message
<-a
select {
case <-pauseCh:
case <-time.After(100 * time.Millisecond):
errCh <- "unexpected blocking publishing"
}
// Manually cancel the context to end publishing
cancel()
}()
select {
case <-time.After(2 * time.Second):
t.Fatal("Test timeout after 2s")
case e := <-errCh:
t.Fatal(e)
case <-stopCh:
}
}
func TestStatsChannelNonBlocking(t *testing.T) {
// Do not use buffer so as to create blocking scenario
c := NewChannel(&ChannelConfig{BufferSize: 0, Blocking: false})
common.Must(c.Start())
defer c.Close()
a, err := c.Subscribe()
common.Must(err)
defer c.Unsubscribe(a)
pauseCh := make(chan struct{})
stopCh := make(chan struct{})
errCh := make(chan string)
ctx, cancel := context.WithCancel(context.Background())
// Test blocking channel publishing
go func() {
c.Publish(context.Background(), nil)
c.Publish(context.Background(), nil)
pauseCh <- struct{}{}
<-pauseCh
c.Publish(ctx, nil)
c.Publish(ctx, nil)
// Check publishing is done because context is canceled
select {
case <-ctx.Done():
if ctx.Err() != context.Canceled {
errCh <- fmt.Sprint("unexpected error: ", ctx.Err())
}
case <-time.After(100 * time.Millisecond):
errCh <- "unexpected non-cancelled publishing"
}
}()
go func() {
// Check publishing won't block even if there is no subscriber receiving message
select {
case <-pauseCh:
case <-time.After(100 * time.Millisecond):
errCh <- "unexpected blocking publishing"
}
// Receive first and second published message
<-a
<-a
pauseCh <- struct{}{}
// Manually cancel the context to end publishing
cancel()
// Check third and forth published message is cancelled and cannot receive
<-time.After(100 * time.Millisecond)
select {
case <-a:
errCh <- "unexpected non-cancelled publishing"
default:
}
select {
case <-a:
errCh <- "unexpected non-cancelled publishing"
default:
}
close(stopCh)
}()
select {
case <-time.After(2 * time.Second):
t.Fatal("Test timeout after 2s")
case e := <-errCh:
t.Fatal(e)
case <-stopCh:
}
}
func TestStatsChannelConcurrency(t *testing.T) {
// Do not use buffer so as to create blocking scenario
c := NewChannel(&ChannelConfig{BufferSize: 0, Blocking: true})
common.Must(c.Start())
defer c.Close()
a, err := c.Subscribe()
common.Must(err)
defer c.Unsubscribe(a)
b, err := c.Subscribe()
common.Must(err)
defer c.Unsubscribe(b)
stopCh := make(chan struct{})
errCh := make(chan string)
go func() { // Blocking publish
c.Publish(context.Background(), 1)
c.Publish(context.Background(), 2)
}()
go func() {
if v, ok := (<-a).(int); !ok || v != 1 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 1)
}
if v, ok := (<-a).(int); !ok || v != 2 {
errCh <- fmt.Sprint("unexpected receiving: ", v, ", wanted ", 2)
}
}()
go func() {
// Block `b` for a time so as to ensure source channel is trying to send message to `b`.
<-time.After(25 * time.Millisecond)
// This causes concurrency scenario: unsubscribe `b` while trying to send message to it
c.Unsubscribe(b)
// Test `b` is not closed and can still receive data 1:
// Because unsubscribe won't affect the ongoing process of sending message.
select {
case v, ok := <-b:
if v1, ok1 := v.(int); !(ok && ok1 && v1 == 1) {
errCh <- fmt.Sprint("unexpected failure in receiving data: ", 1)
}
default:
errCh <- fmt.Sprint("unexpected block from receiving data: ", 1)
}
// Test `b` is not closed but cannot receive data 2:
// Because in a new round of messaging, `b` has been unsubscribed.
select {
case v, ok := <-b:
if ok {
errCh <- fmt.Sprint("unexpected receiving: ", v)
} else {
errCh <- "unexpected closing of channel"
}
default:
}
close(stopCh)
}()
select {
case <-time.After(2 * time.Second):
t.Fatal("Test timeout after 2s")
case e := <-errCh:
t.Fatal(e)
case <-stopCh:
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/command/command_test.go | app/stats/command/command_test.go | package command_test
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/v2fly/v2ray-core/v5/app/stats"
. "github.com/v2fly/v2ray-core/v5/app/stats/command"
"github.com/v2fly/v2ray-core/v5/common"
)
func TestGetStats(t *testing.T) {
m, err := stats.NewManager(context.Background(), &stats.Config{})
common.Must(err)
sc, err := m.RegisterCounter("test_counter")
common.Must(err)
sc.Set(1)
s := NewStatsServer(m)
testCases := []struct {
name string
reset bool
value int64
err bool
}{
{
name: "counterNotExist",
err: true,
},
{
name: "test_counter",
reset: true,
value: 1,
},
{
name: "test_counter",
value: 0,
},
}
for _, tc := range testCases {
resp, err := s.GetStats(context.Background(), &GetStatsRequest{
Name: tc.name,
Reset_: tc.reset,
})
if tc.err {
if err == nil {
t.Error("nil error: ", tc.name)
}
} else {
common.Must(err)
if r := cmp.Diff(resp.Stat, &Stat{Name: tc.name, Value: tc.value}, cmpopts.IgnoreUnexported(Stat{})); r != "" {
t.Error(r)
}
}
}
}
func TestQueryStats(t *testing.T) {
m, err := stats.NewManager(context.Background(), &stats.Config{})
common.Must(err)
sc1, err := m.RegisterCounter("test_counter")
common.Must(err)
sc1.Set(1)
sc2, err := m.RegisterCounter("test_counter_2")
common.Must(err)
sc2.Set(2)
sc3, err := m.RegisterCounter("test_counter_3")
common.Must(err)
sc3.Set(3)
s := NewStatsServer(m)
resp, err := s.QueryStats(context.Background(), &QueryStatsRequest{
Pattern: "counter_",
})
common.Must(err)
if r := cmp.Diff(resp.Stat, []*Stat{
{Name: "test_counter_2", Value: 2},
{Name: "test_counter_3", Value: 3},
}, cmpopts.SortSlices(func(s1, s2 *Stat) bool { return s1.Name < s2.Name }),
cmpopts.IgnoreUnexported(Stat{})); r != "" {
t.Error(r)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/stats/command/command.pb.go | app/stats/command/command.pb.go | package command
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 GetStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Name of the stat counter.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// Whether or not to reset the counter to fetching its value.
Reset_ bool `protobuf:"varint,2,opt,name=reset,proto3" json:"reset,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetStatsRequest) Reset() {
*x = GetStatsRequest{}
mi := &file_app_stats_command_command_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetStatsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetStatsRequest) ProtoMessage() {}
func (x *GetStatsRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 GetStatsRequest.ProtoReflect.Descriptor instead.
func (*GetStatsRequest) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{0}
}
func (x *GetStatsRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *GetStatsRequest) GetReset_() bool {
if x != nil {
return x.Reset_
}
return false
}
type Stat struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Stat) Reset() {
*x = Stat{}
mi := &file_app_stats_command_command_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Stat) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Stat) ProtoMessage() {}
func (x *Stat) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 Stat.ProtoReflect.Descriptor instead.
func (*Stat) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{1}
}
func (x *Stat) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Stat) GetValue() int64 {
if x != nil {
return x.Value
}
return 0
}
type GetStatsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Stat *Stat `protobuf:"bytes,1,opt,name=stat,proto3" json:"stat,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetStatsResponse) Reset() {
*x = GetStatsResponse{}
mi := &file_app_stats_command_command_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetStatsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetStatsResponse) ProtoMessage() {}
func (x *GetStatsResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 GetStatsResponse.ProtoReflect.Descriptor instead.
func (*GetStatsResponse) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{2}
}
func (x *GetStatsResponse) GetStat() *Stat {
if x != nil {
return x.Stat
}
return nil
}
type QueryStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Deprecated, use Patterns instead
Pattern string `protobuf:"bytes,1,opt,name=pattern,proto3" json:"pattern,omitempty"`
Reset_ bool `protobuf:"varint,2,opt,name=reset,proto3" json:"reset,omitempty"`
Patterns []string `protobuf:"bytes,3,rep,name=patterns,proto3" json:"patterns,omitempty"`
Regexp bool `protobuf:"varint,4,opt,name=regexp,proto3" json:"regexp,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *QueryStatsRequest) Reset() {
*x = QueryStatsRequest{}
mi := &file_app_stats_command_command_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *QueryStatsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*QueryStatsRequest) ProtoMessage() {}
func (x *QueryStatsRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 QueryStatsRequest.ProtoReflect.Descriptor instead.
func (*QueryStatsRequest) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{3}
}
func (x *QueryStatsRequest) GetPattern() string {
if x != nil {
return x.Pattern
}
return ""
}
func (x *QueryStatsRequest) GetReset_() bool {
if x != nil {
return x.Reset_
}
return false
}
func (x *QueryStatsRequest) GetPatterns() []string {
if x != nil {
return x.Patterns
}
return nil
}
func (x *QueryStatsRequest) GetRegexp() bool {
if x != nil {
return x.Regexp
}
return false
}
type QueryStatsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Stat []*Stat `protobuf:"bytes,1,rep,name=stat,proto3" json:"stat,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *QueryStatsResponse) Reset() {
*x = QueryStatsResponse{}
mi := &file_app_stats_command_command_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *QueryStatsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*QueryStatsResponse) ProtoMessage() {}
func (x *QueryStatsResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 QueryStatsResponse.ProtoReflect.Descriptor instead.
func (*QueryStatsResponse) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{4}
}
func (x *QueryStatsResponse) GetStat() []*Stat {
if x != nil {
return x.Stat
}
return nil
}
type SysStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SysStatsRequest) Reset() {
*x = SysStatsRequest{}
mi := &file_app_stats_command_command_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SysStatsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SysStatsRequest) ProtoMessage() {}
func (x *SysStatsRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 SysStatsRequest.ProtoReflect.Descriptor instead.
func (*SysStatsRequest) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{5}
}
type SysStatsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
NumGoroutine uint32 `protobuf:"varint,1,opt,name=NumGoroutine,proto3" json:"NumGoroutine,omitempty"`
NumGC uint32 `protobuf:"varint,2,opt,name=NumGC,proto3" json:"NumGC,omitempty"`
Alloc uint64 `protobuf:"varint,3,opt,name=Alloc,proto3" json:"Alloc,omitempty"`
TotalAlloc uint64 `protobuf:"varint,4,opt,name=TotalAlloc,proto3" json:"TotalAlloc,omitempty"`
Sys uint64 `protobuf:"varint,5,opt,name=Sys,proto3" json:"Sys,omitempty"`
Mallocs uint64 `protobuf:"varint,6,opt,name=Mallocs,proto3" json:"Mallocs,omitempty"`
Frees uint64 `protobuf:"varint,7,opt,name=Frees,proto3" json:"Frees,omitempty"`
LiveObjects uint64 `protobuf:"varint,8,opt,name=LiveObjects,proto3" json:"LiveObjects,omitempty"`
PauseTotalNs uint64 `protobuf:"varint,9,opt,name=PauseTotalNs,proto3" json:"PauseTotalNs,omitempty"`
Uptime uint32 `protobuf:"varint,10,opt,name=Uptime,proto3" json:"Uptime,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SysStatsResponse) Reset() {
*x = SysStatsResponse{}
mi := &file_app_stats_command_command_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SysStatsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SysStatsResponse) ProtoMessage() {}
func (x *SysStatsResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_stats_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 SysStatsResponse.ProtoReflect.Descriptor instead.
func (*SysStatsResponse) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{6}
}
func (x *SysStatsResponse) GetNumGoroutine() uint32 {
if x != nil {
return x.NumGoroutine
}
return 0
}
func (x *SysStatsResponse) GetNumGC() uint32 {
if x != nil {
return x.NumGC
}
return 0
}
func (x *SysStatsResponse) GetAlloc() uint64 {
if x != nil {
return x.Alloc
}
return 0
}
func (x *SysStatsResponse) GetTotalAlloc() uint64 {
if x != nil {
return x.TotalAlloc
}
return 0
}
func (x *SysStatsResponse) GetSys() uint64 {
if x != nil {
return x.Sys
}
return 0
}
func (x *SysStatsResponse) GetMallocs() uint64 {
if x != nil {
return x.Mallocs
}
return 0
}
func (x *SysStatsResponse) GetFrees() uint64 {
if x != nil {
return x.Frees
}
return 0
}
func (x *SysStatsResponse) GetLiveObjects() uint64 {
if x != nil {
return x.LiveObjects
}
return 0
}
func (x *SysStatsResponse) GetPauseTotalNs() uint64 {
if x != nil {
return x.PauseTotalNs
}
return 0
}
func (x *SysStatsResponse) GetUptime() uint32 {
if x != nil {
return x.Uptime
}
return 0
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_stats_command_command_proto_msgTypes[7]
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_stats_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 Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_stats_command_command_proto_rawDescGZIP(), []int{7}
}
var File_app_stats_command_command_proto protoreflect.FileDescriptor
const file_app_stats_command_command_proto_rawDesc = "" +
"\n" +
"\x1fapp/stats/command/command.proto\x12\x1cv2ray.core.app.stats.command\x1a common/protoext/extensions.proto\";\n" +
"\x0fGetStatsRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
"\x05reset\x18\x02 \x01(\bR\x05reset\"0\n" +
"\x04Stat\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
"\x05value\x18\x02 \x01(\x03R\x05value\"J\n" +
"\x10GetStatsResponse\x126\n" +
"\x04stat\x18\x01 \x01(\v2\".v2ray.core.app.stats.command.StatR\x04stat\"w\n" +
"\x11QueryStatsRequest\x12\x18\n" +
"\apattern\x18\x01 \x01(\tR\apattern\x12\x14\n" +
"\x05reset\x18\x02 \x01(\bR\x05reset\x12\x1a\n" +
"\bpatterns\x18\x03 \x03(\tR\bpatterns\x12\x16\n" +
"\x06regexp\x18\x04 \x01(\bR\x06regexp\"L\n" +
"\x12QueryStatsResponse\x126\n" +
"\x04stat\x18\x01 \x03(\v2\".v2ray.core.app.stats.command.StatR\x04stat\"\x11\n" +
"\x0fSysStatsRequest\"\xa2\x02\n" +
"\x10SysStatsResponse\x12\"\n" +
"\fNumGoroutine\x18\x01 \x01(\rR\fNumGoroutine\x12\x14\n" +
"\x05NumGC\x18\x02 \x01(\rR\x05NumGC\x12\x14\n" +
"\x05Alloc\x18\x03 \x01(\x04R\x05Alloc\x12\x1e\n" +
"\n" +
"TotalAlloc\x18\x04 \x01(\x04R\n" +
"TotalAlloc\x12\x10\n" +
"\x03Sys\x18\x05 \x01(\x04R\x03Sys\x12\x18\n" +
"\aMallocs\x18\x06 \x01(\x04R\aMallocs\x12\x14\n" +
"\x05Frees\x18\a \x01(\x04R\x05Frees\x12 \n" +
"\vLiveObjects\x18\b \x01(\x04R\vLiveObjects\x12\"\n" +
"\fPauseTotalNs\x18\t \x01(\x04R\fPauseTotalNs\x12\x16\n" +
"\x06Uptime\x18\n" +
" \x01(\rR\x06Uptime\"\"\n" +
"\x06Config:\x18\x82\xb5\x18\x14\n" +
"\vgrpcservice\x12\x05stats2\xde\x02\n" +
"\fStatsService\x12k\n" +
"\bGetStats\x12-.v2ray.core.app.stats.command.GetStatsRequest\x1a..v2ray.core.app.stats.command.GetStatsResponse\"\x00\x12q\n" +
"\n" +
"QueryStats\x12/.v2ray.core.app.stats.command.QueryStatsRequest\x1a0.v2ray.core.app.stats.command.QueryStatsResponse\"\x00\x12n\n" +
"\vGetSysStats\x12-.v2ray.core.app.stats.command.SysStatsRequest\x1a..v2ray.core.app.stats.command.SysStatsResponse\"\x00Bu\n" +
" com.v2ray.core.app.stats.commandP\x01Z0github.com/v2fly/v2ray-core/v5/app/stats/command\xaa\x02\x1cV2Ray.Core.App.Stats.Commandb\x06proto3"
var (
file_app_stats_command_command_proto_rawDescOnce sync.Once
file_app_stats_command_command_proto_rawDescData []byte
)
func file_app_stats_command_command_proto_rawDescGZIP() []byte {
file_app_stats_command_command_proto_rawDescOnce.Do(func() {
file_app_stats_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_stats_command_command_proto_rawDesc), len(file_app_stats_command_command_proto_rawDesc)))
})
return file_app_stats_command_command_proto_rawDescData
}
var file_app_stats_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_app_stats_command_command_proto_goTypes = []any{
(*GetStatsRequest)(nil), // 0: v2ray.core.app.stats.command.GetStatsRequest
(*Stat)(nil), // 1: v2ray.core.app.stats.command.Stat
(*GetStatsResponse)(nil), // 2: v2ray.core.app.stats.command.GetStatsResponse
(*QueryStatsRequest)(nil), // 3: v2ray.core.app.stats.command.QueryStatsRequest
(*QueryStatsResponse)(nil), // 4: v2ray.core.app.stats.command.QueryStatsResponse
(*SysStatsRequest)(nil), // 5: v2ray.core.app.stats.command.SysStatsRequest
(*SysStatsResponse)(nil), // 6: v2ray.core.app.stats.command.SysStatsResponse
(*Config)(nil), // 7: v2ray.core.app.stats.command.Config
}
var file_app_stats_command_command_proto_depIdxs = []int32{
1, // 0: v2ray.core.app.stats.command.GetStatsResponse.stat:type_name -> v2ray.core.app.stats.command.Stat
1, // 1: v2ray.core.app.stats.command.QueryStatsResponse.stat:type_name -> v2ray.core.app.stats.command.Stat
0, // 2: v2ray.core.app.stats.command.StatsService.GetStats:input_type -> v2ray.core.app.stats.command.GetStatsRequest
3, // 3: v2ray.core.app.stats.command.StatsService.QueryStats:input_type -> v2ray.core.app.stats.command.QueryStatsRequest
5, // 4: v2ray.core.app.stats.command.StatsService.GetSysStats:input_type -> v2ray.core.app.stats.command.SysStatsRequest
2, // 5: v2ray.core.app.stats.command.StatsService.GetStats:output_type -> v2ray.core.app.stats.command.GetStatsResponse
4, // 6: v2ray.core.app.stats.command.StatsService.QueryStats:output_type -> v2ray.core.app.stats.command.QueryStatsResponse
6, // 7: v2ray.core.app.stats.command.StatsService.GetSysStats:output_type -> v2ray.core.app.stats.command.SysStatsResponse
5, // [5:8] is the sub-list for method output_type
2, // [2:5] 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_app_stats_command_command_proto_init() }
func file_app_stats_command_command_proto_init() {
if File_app_stats_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_stats_command_command_proto_rawDesc), len(file_app_stats_command_command_proto_rawDesc)),
NumEnums: 0,
NumMessages: 8,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_app_stats_command_command_proto_goTypes,
DependencyIndexes: file_app_stats_command_command_proto_depIdxs,
MessageInfos: file_app_stats_command_command_proto_msgTypes,
}.Build()
File_app_stats_command_command_proto = out.File
file_app_stats_command_command_proto_goTypes = nil
file_app_stats_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/stats/command/errors.generated.go | app/stats/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/stats/command/command_grpc.pb.go | app/stats/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 (
StatsService_GetStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/GetStats"
StatsService_QueryStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/QueryStats"
StatsService_GetSysStats_FullMethodName = "/v2ray.core.app.stats.command.StatsService/GetSysStats"
)
// StatsServiceClient is the client API for StatsService 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 StatsServiceClient interface {
GetStats(ctx context.Context, in *GetStatsRequest, opts ...grpc.CallOption) (*GetStatsResponse, error)
QueryStats(ctx context.Context, in *QueryStatsRequest, opts ...grpc.CallOption) (*QueryStatsResponse, error)
GetSysStats(ctx context.Context, in *SysStatsRequest, opts ...grpc.CallOption) (*SysStatsResponse, error)
}
type statsServiceClient struct {
cc grpc.ClientConnInterface
}
func NewStatsServiceClient(cc grpc.ClientConnInterface) StatsServiceClient {
return &statsServiceClient{cc}
}
func (c *statsServiceClient) GetStats(ctx context.Context, in *GetStatsRequest, opts ...grpc.CallOption) (*GetStatsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetStatsResponse)
err := c.cc.Invoke(ctx, StatsService_GetStats_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *statsServiceClient) QueryStats(ctx context.Context, in *QueryStatsRequest, opts ...grpc.CallOption) (*QueryStatsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(QueryStatsResponse)
err := c.cc.Invoke(ctx, StatsService_QueryStats_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *statsServiceClient) GetSysStats(ctx context.Context, in *SysStatsRequest, opts ...grpc.CallOption) (*SysStatsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SysStatsResponse)
err := c.cc.Invoke(ctx, StatsService_GetSysStats_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// StatsServiceServer is the server API for StatsService service.
// All implementations must embed UnimplementedStatsServiceServer
// for forward compatibility.
type StatsServiceServer interface {
GetStats(context.Context, *GetStatsRequest) (*GetStatsResponse, error)
QueryStats(context.Context, *QueryStatsRequest) (*QueryStatsResponse, error)
GetSysStats(context.Context, *SysStatsRequest) (*SysStatsResponse, error)
mustEmbedUnimplementedStatsServiceServer()
}
// UnimplementedStatsServiceServer 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 UnimplementedStatsServiceServer struct{}
func (UnimplementedStatsServiceServer) GetStats(context.Context, *GetStatsRequest) (*GetStatsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetStats not implemented")
}
func (UnimplementedStatsServiceServer) QueryStats(context.Context, *QueryStatsRequest) (*QueryStatsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method QueryStats not implemented")
}
func (UnimplementedStatsServiceServer) GetSysStats(context.Context, *SysStatsRequest) (*SysStatsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetSysStats not implemented")
}
func (UnimplementedStatsServiceServer) mustEmbedUnimplementedStatsServiceServer() {}
func (UnimplementedStatsServiceServer) testEmbeddedByValue() {}
// UnsafeStatsServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to StatsServiceServer will
// result in compilation errors.
type UnsafeStatsServiceServer interface {
mustEmbedUnimplementedStatsServiceServer()
}
func RegisterStatsServiceServer(s grpc.ServiceRegistrar, srv StatsServiceServer) {
// If the following call pancis, it indicates UnimplementedStatsServiceServer 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(&StatsService_ServiceDesc, srv)
}
func _StatsService_GetStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetStatsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StatsServiceServer).GetStats(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StatsService_GetStats_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StatsServiceServer).GetStats(ctx, req.(*GetStatsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StatsService_QueryStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryStatsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StatsServiceServer).QueryStats(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StatsService_QueryStats_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StatsServiceServer).QueryStats(ctx, req.(*QueryStatsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StatsService_GetSysStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SysStatsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StatsServiceServer).GetSysStats(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StatsService_GetSysStats_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StatsServiceServer).GetSysStats(ctx, req.(*SysStatsRequest))
}
return interceptor(ctx, in, info, handler)
}
// StatsService_ServiceDesc is the grpc.ServiceDesc for StatsService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var StatsService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v2ray.core.app.stats.command.StatsService",
HandlerType: (*StatsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetStats",
Handler: _StatsService_GetStats_Handler,
},
{
MethodName: "QueryStats",
Handler: _StatsService_QueryStats_Handler,
},
{
MethodName: "GetSysStats",
Handler: _StatsService_GetSysStats_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/stats/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/stats/command/command.go | app/stats/command/command.go | package command
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"runtime"
"time"
grpc "google.golang.org/grpc"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/stats"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
feature_stats "github.com/v2fly/v2ray-core/v5/features/stats"
)
// statsServer is an implementation of StatsService.
type statsServer struct {
stats feature_stats.Manager
startTime time.Time
}
func NewStatsServer(manager feature_stats.Manager) StatsServiceServer {
return &statsServer{
stats: manager,
startTime: time.Now(),
}
}
func (s *statsServer) GetStats(ctx context.Context, request *GetStatsRequest) (*GetStatsResponse, error) {
c := s.stats.GetCounter(request.Name)
if c == nil {
return nil, newError(request.Name, " not found.")
}
var value int64
if request.Reset_ {
value = c.Set(0)
} else {
value = c.Value()
}
return &GetStatsResponse{
Stat: &Stat{
Name: request.Name,
Value: value,
},
}, nil
}
func (s *statsServer) QueryStats(ctx context.Context, request *QueryStatsRequest) (*QueryStatsResponse, error) {
mgroup := &strmatcher.LinearIndexMatcher{}
if request.Pattern != "" {
request.Patterns = append(request.Patterns, request.Pattern)
}
t := strmatcher.Substr
if request.Regexp {
t = strmatcher.Regex
}
for _, p := range request.Patterns {
m, err := t.New(p)
if err != nil {
return nil, err
}
mgroup.Add(m)
}
response := &QueryStatsResponse{}
manager, ok := s.stats.(*stats.Manager)
if !ok {
return nil, newError("QueryStats only works its own stats.Manager.")
}
manager.VisitCounters(func(name string, c feature_stats.Counter) bool {
if mgroup.Size() == 0 || len(mgroup.Match(name)) > 0 {
var value int64
if request.Reset_ {
value = c.Set(0)
} else {
value = c.Value()
}
response.Stat = append(response.Stat, &Stat{
Name: name,
Value: value,
})
}
return true
})
return response, nil
}
func (s *statsServer) GetSysStats(ctx context.Context, request *SysStatsRequest) (*SysStatsResponse, error) {
var rtm runtime.MemStats
runtime.ReadMemStats(&rtm)
uptime := time.Since(s.startTime)
response := &SysStatsResponse{
Uptime: uint32(uptime.Seconds()),
NumGoroutine: uint32(runtime.NumGoroutine()),
Alloc: rtm.Alloc,
TotalAlloc: rtm.TotalAlloc,
Sys: rtm.Sys,
Mallocs: rtm.Mallocs,
Frees: rtm.Frees,
LiveObjects: rtm.Mallocs - rtm.Frees,
NumGC: rtm.NumGC,
PauseTotalNs: rtm.PauseTotalNs,
}
return response, nil
}
func (s *statsServer) mustEmbedUnimplementedStatsServiceServer() {}
type service struct {
statsManager feature_stats.Manager
}
func (s *service) Register(server *grpc.Server) {
RegisterStatsServiceServer(server, NewStatsServer(s.statsManager))
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
s := new(service)
core.RequireFeatures(ctx, func(sm feature_stats.Manager) {
s.statsManager = sm
})
return s, nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/errors.generated.go | app/subscription/errors.generated.go | package subscription
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/subscription/subscription_rpc.pb.go | app/subscription/subscription_rpc.pb.go | package subscription
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 SubscriptionServer struct {
state protoimpl.MessageState `protogen:"open.v1"`
ServerMetadata map[string]string `protobuf:"bytes,2,rep,name=serverMetadata,proto3" json:"serverMetadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
Tag string `protobuf:"bytes,3,opt,name=tag,proto3" json:"tag,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SubscriptionServer) Reset() {
*x = SubscriptionServer{}
mi := &file_app_subscription_subscription_rpc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SubscriptionServer) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SubscriptionServer) ProtoMessage() {}
func (x *SubscriptionServer) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscription_rpc_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 SubscriptionServer.ProtoReflect.Descriptor instead.
func (*SubscriptionServer) Descriptor() ([]byte, []int) {
return file_app_subscription_subscription_rpc_proto_rawDescGZIP(), []int{0}
}
func (x *SubscriptionServer) GetServerMetadata() map[string]string {
if x != nil {
return x.ServerMetadata
}
return nil
}
func (x *SubscriptionServer) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
type TrackedSubscriptionStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Servers map[string]*SubscriptionServer `protobuf:"bytes,1,rep,name=servers,proto3" json:"servers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
DocumentMetadata map[string]string `protobuf:"bytes,2,rep,name=documentMetadata,proto3" json:"documentMetadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
ImportSource *ImportSource `protobuf:"bytes,3,opt,name=importSource,proto3" json:"importSource,omitempty"`
AddedByApi bool `protobuf:"varint,4,opt,name=added_by_api,json=addedByApi,proto3" json:"added_by_api,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *TrackedSubscriptionStatus) Reset() {
*x = TrackedSubscriptionStatus{}
mi := &file_app_subscription_subscription_rpc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *TrackedSubscriptionStatus) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TrackedSubscriptionStatus) ProtoMessage() {}
func (x *TrackedSubscriptionStatus) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscription_rpc_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 TrackedSubscriptionStatus.ProtoReflect.Descriptor instead.
func (*TrackedSubscriptionStatus) Descriptor() ([]byte, []int) {
return file_app_subscription_subscription_rpc_proto_rawDescGZIP(), []int{1}
}
func (x *TrackedSubscriptionStatus) GetServers() map[string]*SubscriptionServer {
if x != nil {
return x.Servers
}
return nil
}
func (x *TrackedSubscriptionStatus) GetDocumentMetadata() map[string]string {
if x != nil {
return x.DocumentMetadata
}
return nil
}
func (x *TrackedSubscriptionStatus) GetImportSource() *ImportSource {
if x != nil {
return x.ImportSource
}
return nil
}
func (x *TrackedSubscriptionStatus) GetAddedByApi() bool {
if x != nil {
return x.AddedByApi
}
return false
}
var File_app_subscription_subscription_rpc_proto protoreflect.FileDescriptor
const file_app_subscription_subscription_rpc_proto_rawDesc = "" +
"\n" +
"'app/subscription/subscription_rpc.proto\x12\x1bv2ray.core.app.subscription\x1a\x1dapp/subscription/config.proto\"\xd6\x01\n" +
"\x12SubscriptionServer\x12k\n" +
"\x0eserverMetadata\x18\x02 \x03(\v2C.v2ray.core.app.subscription.SubscriptionServer.ServerMetadataEntryR\x0eserverMetadata\x12\x10\n" +
"\x03tag\x18\x03 \x01(\tR\x03tag\x1aA\n" +
"\x13ServerMetadataEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x97\x04\n" +
"\x19TrackedSubscriptionStatus\x12]\n" +
"\aservers\x18\x01 \x03(\v2C.v2ray.core.app.subscription.TrackedSubscriptionStatus.ServersEntryR\aservers\x12x\n" +
"\x10documentMetadata\x18\x02 \x03(\v2L.v2ray.core.app.subscription.TrackedSubscriptionStatus.DocumentMetadataEntryR\x10documentMetadata\x12M\n" +
"\fimportSource\x18\x03 \x01(\v2).v2ray.core.app.subscription.ImportSourceR\fimportSource\x12 \n" +
"\fadded_by_api\x18\x04 \x01(\bR\n" +
"addedByApi\x1ak\n" +
"\fServersEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12E\n" +
"\x05value\x18\x02 \x01(\v2/.v2ray.core.app.subscription.SubscriptionServerR\x05value:\x028\x01\x1aC\n" +
"\x15DocumentMetadataEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01Br\n" +
"\x1fcom.v2ray.core.app.subscriptionP\x01Z/github.com/v2fly/v2ray-core/v5/app/subscription\xaa\x02\x1bV2Ray.Core.App.Subscriptionb\x06proto3"
var (
file_app_subscription_subscription_rpc_proto_rawDescOnce sync.Once
file_app_subscription_subscription_rpc_proto_rawDescData []byte
)
func file_app_subscription_subscription_rpc_proto_rawDescGZIP() []byte {
file_app_subscription_subscription_rpc_proto_rawDescOnce.Do(func() {
file_app_subscription_subscription_rpc_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_subscription_subscription_rpc_proto_rawDesc), len(file_app_subscription_subscription_rpc_proto_rawDesc)))
})
return file_app_subscription_subscription_rpc_proto_rawDescData
}
var file_app_subscription_subscription_rpc_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_app_subscription_subscription_rpc_proto_goTypes = []any{
(*SubscriptionServer)(nil), // 0: v2ray.core.app.subscription.SubscriptionServer
(*TrackedSubscriptionStatus)(nil), // 1: v2ray.core.app.subscription.TrackedSubscriptionStatus
nil, // 2: v2ray.core.app.subscription.SubscriptionServer.ServerMetadataEntry
nil, // 3: v2ray.core.app.subscription.TrackedSubscriptionStatus.ServersEntry
nil, // 4: v2ray.core.app.subscription.TrackedSubscriptionStatus.DocumentMetadataEntry
(*ImportSource)(nil), // 5: v2ray.core.app.subscription.ImportSource
}
var file_app_subscription_subscription_rpc_proto_depIdxs = []int32{
2, // 0: v2ray.core.app.subscription.SubscriptionServer.serverMetadata:type_name -> v2ray.core.app.subscription.SubscriptionServer.ServerMetadataEntry
3, // 1: v2ray.core.app.subscription.TrackedSubscriptionStatus.servers:type_name -> v2ray.core.app.subscription.TrackedSubscriptionStatus.ServersEntry
4, // 2: v2ray.core.app.subscription.TrackedSubscriptionStatus.documentMetadata:type_name -> v2ray.core.app.subscription.TrackedSubscriptionStatus.DocumentMetadataEntry
5, // 3: v2ray.core.app.subscription.TrackedSubscriptionStatus.importSource:type_name -> v2ray.core.app.subscription.ImportSource
0, // 4: v2ray.core.app.subscription.TrackedSubscriptionStatus.ServersEntry.value:type_name -> v2ray.core.app.subscription.SubscriptionServer
5, // [5:5] is the sub-list for method output_type
5, // [5:5] 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_subscription_subscription_rpc_proto_init() }
func file_app_subscription_subscription_rpc_proto_init() {
if File_app_subscription_subscription_rpc_proto != nil {
return
}
file_app_subscription_config_proto_init()
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_subscription_subscription_rpc_proto_rawDesc), len(file_app_subscription_subscription_rpc_proto_rawDesc)),
NumEnums: 0,
NumMessages: 5,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_subscription_subscription_rpc_proto_goTypes,
DependencyIndexes: file_app_subscription_subscription_rpc_proto_depIdxs,
MessageInfos: file_app_subscription_subscription_rpc_proto_msgTypes,
}.Build()
File_app_subscription_subscription_rpc_proto = out.File
file_app_subscription_subscription_rpc_proto_goTypes = nil
file_app_subscription_subscription_rpc_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/subscription/subscription.go | app/subscription/subscription.go | package subscription
import "github.com/v2fly/v2ray-core/v5/features"
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type SubscriptionManager interface {
features.Feature
AddTrackedSubscriptionFromImportSource(importSource *ImportSource) error
RemoveTrackedSubscription(name string) error
ListTrackedSubscriptions() []string
GetTrackedSubscriptionStatus(name string) (*TrackedSubscriptionStatus, error)
UpdateTrackedSubscription(name string) error
}
func SubscriptionManagerType() interface{} {
return (*SubscriptionManager)(nil)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/config.pb.go | app/subscription/config.pb.go | package subscription
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 ImportSource struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"`
TagPrefix string `protobuf:"bytes,3,opt,name=tag_prefix,json=tagPrefix,proto3" json:"tag_prefix,omitempty"`
ImportUsingTag string `protobuf:"bytes,4,opt,name=import_using_tag,json=importUsingTag,proto3" json:"import_using_tag,omitempty"`
DefaultExpireSeconds uint64 `protobuf:"varint,5,opt,name=default_expire_seconds,json=defaultExpireSeconds,proto3" json:"default_expire_seconds,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ImportSource) Reset() {
*x = ImportSource{}
mi := &file_app_subscription_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ImportSource) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ImportSource) ProtoMessage() {}
func (x *ImportSource) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_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 ImportSource.ProtoReflect.Descriptor instead.
func (*ImportSource) Descriptor() ([]byte, []int) {
return file_app_subscription_config_proto_rawDescGZIP(), []int{0}
}
func (x *ImportSource) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *ImportSource) GetUrl() string {
if x != nil {
return x.Url
}
return ""
}
func (x *ImportSource) GetTagPrefix() string {
if x != nil {
return x.TagPrefix
}
return ""
}
func (x *ImportSource) GetImportUsingTag() string {
if x != nil {
return x.ImportUsingTag
}
return ""
}
func (x *ImportSource) GetDefaultExpireSeconds() uint64 {
if x != nil {
return x.DefaultExpireSeconds
}
return 0
}
// Config is the settings for Subscription Manager.
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Imports []*ImportSource `protobuf:"bytes,1,rep,name=imports,proto3" json:"imports,omitempty"`
NonnativeConverterOverlay []byte `protobuf:"bytes,2,opt,name=nonnative_converter_overlay,json=nonnativeConverterOverlay,proto3" json:"nonnative_converter_overlay,omitempty"`
NonnativeConverterOverlayFile string `protobuf:"bytes,96002,opt,name=nonnative_converter_overlay_file,json=nonnativeConverterOverlayFile,proto3" json:"nonnative_converter_overlay_file,omitempty"`
Persistence bool `protobuf:"varint,3,opt,name=persistence,proto3" json:"persistence,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_subscription_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_subscription_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_subscription_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetImports() []*ImportSource {
if x != nil {
return x.Imports
}
return nil
}
func (x *Config) GetNonnativeConverterOverlay() []byte {
if x != nil {
return x.NonnativeConverterOverlay
}
return nil
}
func (x *Config) GetNonnativeConverterOverlayFile() string {
if x != nil {
return x.NonnativeConverterOverlayFile
}
return ""
}
func (x *Config) GetPersistence() bool {
if x != nil {
return x.Persistence
}
return false
}
var File_app_subscription_config_proto protoreflect.FileDescriptor
const file_app_subscription_config_proto_rawDesc = "" +
"\n" +
"\x1dapp/subscription/config.proto\x12\x1bv2ray.core.app.subscription\x1a common/protoext/extensions.proto\"\xb3\x01\n" +
"\fImportSource\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" +
"\x03url\x18\x02 \x01(\tR\x03url\x12\x1d\n" +
"\n" +
"tag_prefix\x18\x03 \x01(\tR\ttagPrefix\x12(\n" +
"\x10import_using_tag\x18\x04 \x01(\tR\x0eimportUsingTag\x124\n" +
"\x16default_expire_seconds\x18\x05 \x01(\x04R\x14defaultExpireSeconds\"\xba\x02\n" +
"\x06Config\x12C\n" +
"\aimports\x18\x01 \x03(\v2).v2ray.core.app.subscription.ImportSourceR\aimports\x12>\n" +
"\x1bnonnative_converter_overlay\x18\x02 \x01(\fR\x19nonnativeConverterOverlay\x12l\n" +
" nonnative_converter_overlay_file\x18\x82\xee\x05 \x01(\tB!\x82\xb5\x18\x1d\"\x1bnonnative_converter_overlayR\x1dnonnativeConverterOverlayFile\x12 \n" +
"\vpersistence\x18\x03 \x01(\bR\vpersistence:\x1b\x82\xb5\x18\x17\n" +
"\aservice\x12\fsubscriptionBr\n" +
"\x1fcom.v2ray.core.app.subscriptionP\x01Z/github.com/v2fly/v2ray-core/v5/app/subscription\xaa\x02\x1bV2Ray.Core.App.Subscriptionb\x06proto3"
var (
file_app_subscription_config_proto_rawDescOnce sync.Once
file_app_subscription_config_proto_rawDescData []byte
)
func file_app_subscription_config_proto_rawDescGZIP() []byte {
file_app_subscription_config_proto_rawDescOnce.Do(func() {
file_app_subscription_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_subscription_config_proto_rawDesc), len(file_app_subscription_config_proto_rawDesc)))
})
return file_app_subscription_config_proto_rawDescData
}
var file_app_subscription_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_app_subscription_config_proto_goTypes = []any{
(*ImportSource)(nil), // 0: v2ray.core.app.subscription.ImportSource
(*Config)(nil), // 1: v2ray.core.app.subscription.Config
}
var file_app_subscription_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.subscription.Config.imports:type_name -> v2ray.core.app.subscription.ImportSource
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_subscription_config_proto_init() }
func file_app_subscription_config_proto_init() {
if File_app_subscription_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_subscription_config_proto_rawDesc), len(file_app_subscription_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_subscription_config_proto_goTypes,
DependencyIndexes: file_app_subscription_config_proto_depIdxs,
MessageInfos: file_app_subscription_config_proto_msgTypes,
}.Build()
File_app_subscription_config_proto = out.File
file_app_subscription_config_proto_goTypes = nil
file_app_subscription_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/subscription/subscriptionmanager/manager_rpc.go | app/subscription/subscriptionmanager/manager_rpc.go | package subscriptionmanager
import "github.com/v2fly/v2ray-core/v5/app/subscription"
func (s *SubscriptionManagerImpl) AddTrackedSubscriptionFromImportSource(importSource *subscription.ImportSource) error {
s.Lock()
defer s.Unlock()
return s.addTrackedSubscriptionFromImportSource(importSource, true)
}
func (s *SubscriptionManagerImpl) RemoveTrackedSubscription(name string) error {
s.Lock()
defer s.Unlock()
return s.removeTrackedSubscription(name)
}
func (s *SubscriptionManagerImpl) UpdateTrackedSubscription(name string) error {
s.Lock()
defer s.Unlock()
return s.updateSubscription(name)
}
func (s *SubscriptionManagerImpl) ListTrackedSubscriptions() []string {
s.Lock()
defer s.Unlock()
var names []string
for name := range s.trackedSubscriptions {
names = append(names, name)
}
return names
}
func (s *SubscriptionManagerImpl) GetTrackedSubscriptionStatus(name string) (*subscription.TrackedSubscriptionStatus, error) {
s.Lock()
defer s.Unlock()
if trackedSubscriptionItem, ok := s.trackedSubscriptions[name]; ok {
result := &subscription.TrackedSubscriptionStatus{}
if err := trackedSubscriptionItem.fillStatus(result); err != nil {
return nil, newError("failed to fill status").Base(err)
}
result.ImportSource = trackedSubscriptionItem.importSource
return result, nil
} else {
return nil, newError("unable to locate")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/errors.generated.go | app/subscription/subscriptionmanager/errors.generated.go | package subscriptionmanager
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/subscription/subscriptionmanager/delta.go | app/subscription/subscriptionmanager/delta.go | package subscriptionmanager
type changedDocument struct {
removed []string
added []string
modified []string
unchanged []string
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/subdocchecker.go | app/subscription/subscriptionmanager/subdocchecker.go | package subscriptionmanager
import "time"
func (s *SubscriptionManagerImpl) checkupSubscription(subscriptionName string) error {
var trackedSub *trackedSubscription
if trackedSubFound, found := s.trackedSubscriptions[subscriptionName]; !found {
return newError("not found")
} else {
trackedSub = trackedSubFound
}
shouldUpdate := false
if trackedSub.currentDocumentExpireTime.Before(time.Now()) {
shouldUpdate = true
}
if shouldUpdate {
if err := s.updateSubscription(subscriptionName); err != nil {
return newError("failed to update subscription: ", 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/subscription/subscriptionmanager/known_metadata.go | app/subscription/subscriptionmanager/known_metadata.go | package subscriptionmanager
const (
ServerMetadataID = "ID"
ServerMetadataTagName = "TagName"
ServerMetadataFullyQualifiedName = "FullyQualifiedName"
)
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/subdocapplier.go | app/subscription/subscriptionmanager/subdocapplier.go | package subscriptionmanager
import (
"fmt"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
)
func (s *SubscriptionManagerImpl) applySubscriptionTo(name string, document *specs.SubscriptionDocument) error {
var trackedSub *trackedSubscription
if trackedSubFound, found := s.trackedSubscriptions[name]; !found {
return newError("not found")
} else {
trackedSub = trackedSubFound
}
delta, err := trackedSub.diff(document)
if err != nil {
return err
}
nameToServerConfig := make(map[string]*specs.SubscriptionServerConfig)
for _, server := range document.Server {
nameToServerConfig[server.Id] = server
}
for _, serverName := range delta.removed {
if err := s.removeManagedServer(name, serverName); err != nil {
newError("failed to remove managed server: ", err).AtWarning().WriteToLog()
continue
}
trackedSub.recordRemovedServer(serverName)
}
for _, serverName := range delta.modified {
serverConfig := nameToServerConfig[serverName]
if err := s.updateManagedServer(name, serverName, serverConfig); err != nil {
newError("failed to update managed server: ", err).AtWarning().WriteToLog()
continue
}
trackedSub.recordUpdatedServer(serverName, serverConfig.Metadata[ServerMetadataTagName], serverConfig)
}
for _, serverName := range delta.added {
serverConfig := nameToServerConfig[serverName]
if err := s.addManagedServer(name, serverName, serverConfig); err != nil {
newError("failed to add managed server: ", err).AtWarning().WriteToLog()
continue
}
trackedSub.recordUpdatedServer(serverName, serverConfig.Metadata[ServerMetadataTagName], serverConfig)
}
newError("finished applying subscription, ", name, "; ", fmt.Sprintf(
"%v updated, %v added, %v removed, %v unchanged",
len(delta.modified), len(delta.added), len(delta.removed), len(delta.unchanged))).AtInfo().WriteToLog()
return nil
}
func (s *SubscriptionManagerImpl) removeManagedServer(subscriptionName, serverName string) error {
var trackedSub *trackedSubscription
if trackedSubFound, found := s.trackedSubscriptions[subscriptionName]; !found {
return newError("not found")
} else {
trackedSub = trackedSubFound
}
var trackedServer *materializedServer
if trackedServerFound, err := trackedSub.getCurrentServer(serverName); err != nil {
return err
} else {
trackedServer = trackedServerFound
}
tagName := fmt.Sprintf("%s_%s", trackedSub.importSource.TagPrefix, trackedServer.tagPostfix)
if err := core.RemoveOutboundHandler(s.s, tagName); err != nil {
return newError("failed to remove handler: ", err)
}
trackedSub.recordRemovedServer(serverName)
return nil
}
func (s *SubscriptionManagerImpl) addManagedServer(subscriptionName, serverName string,
serverSpec *specs.SubscriptionServerConfig,
) error {
var trackedSub *trackedSubscription
if trackedSubFound, found := s.trackedSubscriptions[subscriptionName]; !found {
return newError("not found")
} else {
trackedSub = trackedSubFound
}
tagPostfix := serverSpec.Metadata[ServerMetadataTagName]
tagName := fmt.Sprintf("%s_%s", trackedSub.importSource.TagPrefix, tagPostfix)
materialized, err := s.materialize(subscriptionName, tagName, serverSpec)
if err != nil {
return newError("failed to materialize server: ", err)
}
if err := core.AddOutboundHandler(s.s, materialized); err != nil {
return newError("failed to add handler: ", err)
}
trackedSub.recordUpdatedServer(serverName, tagPostfix, serverSpec)
return nil
}
func (s *SubscriptionManagerImpl) updateManagedServer(subscriptionName, serverName string,
serverSpec *specs.SubscriptionServerConfig,
) error {
if err := s.removeManagedServer(subscriptionName, serverName); err != nil {
return newError("failed to update managed server: ", err).AtWarning()
}
if err := s.addManagedServer(subscriptionName, serverName, serverSpec); err != nil {
return newError("failed to update managed server : ", err).AtWarning()
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/subdocupdater.go | app/subscription/subscriptionmanager/subdocupdater.go | package subscriptionmanager
import (
"fmt"
"strings"
"time"
"unicode"
"golang.org/x/crypto/sha3"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/app/subscription/documentfetcher"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
)
func (s *SubscriptionManagerImpl) updateSubscription(subscriptionName string) error {
var trackedSub *trackedSubscription
if trackedSubFound, found := s.trackedSubscriptions[subscriptionName]; !found {
return newError("not found")
} else {
trackedSub = trackedSubFound
}
importSource := trackedSub.importSource
docFetcher, err := documentfetcher.GetFetcher("http")
if err != nil {
return newError("failed to get fetcher: ", err)
}
if strings.HasPrefix(importSource.Url, "data:") {
docFetcher, err = documentfetcher.GetFetcher("dataurl")
if err != nil {
return newError("failed to get fetcher: ", err)
}
}
downloadedDocument, err := docFetcher.DownloadDocument(s.ctx, importSource)
if err != nil {
return newError("failed to download document: ", err)
}
trackedSub.originalDocument = downloadedDocument
container, err := containers.TryAllParsers(trackedSub.originalDocument, "")
if err != nil {
return newError("failed to parse document: ", err)
}
trackedSub.originalContainer = container
parsedDocument := &specs.SubscriptionDocument{}
parsedDocument.Metadata = container.Metadata
trackedSub.originalServerConfig = make(map[string]*originalServerConfig)
for _, server := range trackedSub.originalContainer.ServerSpecs {
documentHash := sha3.Sum256(server.Content)
serverConfigHashName := fmt.Sprintf("%x", documentHash)
parsed, err := s.converter.TryAllConverters(server.Content, "outbound", server.KindHint)
if err != nil {
trackedSub.originalServerConfig["!!!"+serverConfigHashName] = &originalServerConfig{data: server.Content}
continue
}
s.polyfillServerConfig(parsed, serverConfigHashName)
parsedDocument.Server = append(parsedDocument.Server, parsed)
trackedSub.originalServerConfig[parsed.Id] = &originalServerConfig{data: server.Content}
}
newError("new subscription document fetched and parsed from ", subscriptionName).AtInfo().WriteToLog()
if err := s.applySubscriptionTo(subscriptionName, parsedDocument); err != nil {
return newError("failed to apply subscription: ", err)
}
trackedSub.currentDocument = parsedDocument
trackedSub.currentDocumentExpireTime = time.Now().Add(time.Second * time.Duration(importSource.DefaultExpireSeconds))
return nil
}
func (s *SubscriptionManagerImpl) polyfillServerConfig(document *specs.SubscriptionServerConfig, hash string) {
document.Id = hash
if document.Metadata == nil {
document.Metadata = make(map[string]string)
}
if id, ok := document.Metadata[ServerMetadataID]; !ok || id == "" {
document.Metadata[ServerMetadataID] = document.Id
} else {
document.Id = document.Metadata[ServerMetadataID]
}
if fqn, ok := document.Metadata[ServerMetadataFullyQualifiedName]; !ok || fqn == "" {
document.Metadata[ServerMetadataFullyQualifiedName] = hash
}
if tagName, ok := document.Metadata[ServerMetadataTagName]; !ok || tagName == "" {
document.Metadata[ServerMetadataTagName] = document.Metadata[ServerMetadataID]
}
document.Metadata[ServerMetadataTagName] = s.restrictTagName(document.Metadata[ServerMetadataTagName])
}
func (s *SubscriptionManagerImpl) restrictTagName(tagName string) string {
newTagName := &strings.Builder{}
somethingRemoved := false
for _, c := range tagName {
if (unicode.IsLetter(c) || unicode.IsNumber(c)) && c < 128 {
newTagName.WriteRune(c)
} else {
somethingRemoved = true
}
}
newTagNameString := newTagName.String()
if len(newTagNameString) > 24 {
newTagNameString = newTagNameString[:15]
somethingRemoved = true
}
if somethingRemoved {
hashedTagName := sha3.Sum256([]byte(tagName))
hashedTagNameString := fmt.Sprintf("%x", hashedTagName)
newTagNameString = newTagNameString + "_" + hashedTagNameString[:8]
}
return newTagNameString
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/serverspec_materialize.go | app/subscription/subscriptionmanager/serverspec_materialize.go | package subscriptionmanager
import (
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func (s *SubscriptionManagerImpl) materialize(subscriptionName, tagName string, serverSpec *specs.SubscriptionServerConfig) (*core.OutboundHandlerConfig, error) {
outboundConf, err := s.getOutboundTemplateForSubscriptionName(subscriptionName)
if err != nil {
return nil, newError("failed to get outbound template for subscription name: ", err)
}
senderSettingsIfcd, err := serial.GetInstanceOf(outboundConf.SenderSettings)
if err != nil {
return nil, newError("failed to get sender settings: ", err)
}
senderSettings := senderSettingsIfcd.(*proxyman.SenderConfig)
if serverSpec.Configuration.Transport != "" {
senderSettings.StreamSettings.ProtocolName = serverSpec.Configuration.Transport
senderSettings.StreamSettings.TransportSettings = append(senderSettings.StreamSettings.TransportSettings,
&internet.TransportConfig{ProtocolName: serverSpec.Configuration.Transport, Settings: serverSpec.Configuration.TransportSettings})
}
if serverSpec.Configuration.Security != "" {
senderSettings.StreamSettings.SecurityType = serverSpec.Configuration.Security
senderSettings.StreamSettings.SecuritySettings = append(senderSettings.StreamSettings.SecuritySettings,
serverSpec.Configuration.SecuritySettings)
}
outboundConf.SenderSettings = serial.ToTypedMessage(senderSettings)
outboundConf.ProxySettings = serverSpec.Configuration.ProtocolSettings
outboundConf.Tag = tagName
return outboundConf, nil
}
func (s *SubscriptionManagerImpl) getOutboundTemplateForSubscriptionName(subscriptionName string) (*core.OutboundHandlerConfig, error) { //nolint: unparam
senderSetting := &proxyman.SenderConfig{
DomainStrategy: proxyman.SenderConfig_AS_IS, StreamSettings: &internet.StreamConfig{},
}
return &core.OutboundHandlerConfig{SenderSettings: serial.ToTypedMessage(senderSetting)}, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/manager.go | app/subscription/subscriptionmanager/manager.go | package subscriptionmanager
import (
"archive/zip"
"bytes"
"context"
"sync"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/persistentstorage"
"github.com/v2fly/v2ray-core/v5/app/persistentstorage/protostorage"
"github.com/v2fly/v2ray-core/v5/app/subscription"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative/nonnativeifce"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/common/task"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type SubscriptionManagerImpl struct {
sync.Mutex
config *subscription.Config
ctx context.Context
s *core.Instance
converter *entries.ConverterRegistry
trackedSubscriptions map[string]*trackedSubscription
refreshTask *task.Periodic
persistentStorage persistentstorage.ScopedPersistentStorage
persistImportStorage persistentstorage.ScopedPersistentStorage
persistImportSourceProtoStorage protostorage.ProtoPersistentStorage
}
func (s *SubscriptionManagerImpl) Type() interface{} {
return subscription.SubscriptionManagerType()
}
func (s *SubscriptionManagerImpl) housekeeping() error {
for subscriptionName := range s.trackedSubscriptions {
s.Lock()
if err := s.checkupSubscription(subscriptionName); err != nil {
newError("failed to checkup subscription: ", err).AtWarning().WriteToLog()
}
s.Unlock()
}
return nil
}
func (s *SubscriptionManagerImpl) Start() error {
if s.config.Persistence {
appEnvironment := envctx.EnvironmentFromContext(s.ctx).(environment.AppEnvironment)
s.persistentStorage = appEnvironment.PersistentStorage()
importsStorage, err := s.persistentStorage.NarrowScope(s.ctx, []byte("imports"))
if err != nil {
return newError("failed to get persistent storage for imports").Base(err)
}
s.persistImportStorage = importsStorage
s.persistImportSourceProtoStorage = importsStorage.(protostorage.ProtoPersistentStorage)
if err = s.loadAllFromPersistentStorage(); err != nil {
newError("failed to load all from persistent storage: ", err).WriteToLog()
}
}
go func() {
if err := s.refreshTask.Start(); err != nil {
return
}
}()
return nil
}
func (s *SubscriptionManagerImpl) Close() error {
if err := s.refreshTask.Close(); err != nil {
return err
}
return nil
}
func (s *SubscriptionManagerImpl) addTrackedSubscriptionFromImportSource(importSource *subscription.ImportSource,
addedByAPI bool,
) error {
if s.config.Persistence && addedByAPI {
err := s.persistImportSourceProtoStorage.PutProto(s.ctx, importSource.Name, importSource)
if err != nil {
return newError("failed to persist import source: ", err)
}
}
tracked, err := newTrackedSubscription(importSource)
if err != nil {
return newError("failed to init subscription ", importSource.Name, ": ", err)
}
tracked.addedByAPI = addedByAPI
s.trackedSubscriptions[importSource.Name] = tracked
return nil
}
func (s *SubscriptionManagerImpl) removeTrackedSubscription(subscriptionName string) error {
if s.config.Persistence {
err := s.persistImportStorage.Put(s.ctx, []byte(subscriptionName), nil)
if err != nil {
return newError("failed to delete import source: ", err)
}
}
if _, ok := s.trackedSubscriptions[subscriptionName]; ok {
err := s.applySubscriptionTo(subscriptionName, &specs.SubscriptionDocument{Server: make([]*specs.SubscriptionServerConfig, 0)})
if err != nil {
return newError("failed to apply empty subscription: ", err)
}
delete(s.trackedSubscriptions, subscriptionName)
}
return nil
}
func (s *SubscriptionManagerImpl) init() error {
s.refreshTask = &task.Periodic{
Interval: time.Duration(60) * time.Second,
Execute: s.housekeeping,
}
s.trackedSubscriptions = make(map[string]*trackedSubscription)
s.converter = entries.GetOverlayConverterRegistry()
if s.config.NonnativeConverterOverlay != nil {
zipReader, err := zip.NewReader(bytes.NewReader(s.config.NonnativeConverterOverlay), int64(len(s.config.NonnativeConverterOverlay)))
if err != nil {
return newError("failed to read nonnative converter overlay: ", err)
}
converter, err := nonnativeifce.NewNonNativeConverterConstructor(zipReader)
if err != nil {
return newError("failed to construct nonnative converter: ", err)
}
if err := s.converter.RegisterConverter("user_nonnative", converter); err != nil {
return newError("failed to register user nonnative converter: ", err)
}
}
for _, v := range s.config.Imports {
if err := s.addTrackedSubscriptionFromImportSource(v, false); err != nil {
return newError("failed to add tracked subscription: ", err)
}
}
return nil
}
func (s *SubscriptionManagerImpl) loadAllFromPersistentStorage() error {
if !s.config.Persistence {
return nil
}
protoImportSources, err := s.persistImportStorage.List(s.ctx, []byte(""))
if err != nil {
return newError("failed to list import sources: ", err)
}
for _, protoImportSource := range protoImportSources {
var importSource subscription.ImportSource
err := s.persistImportSourceProtoStorage.GetProto(s.ctx, string(protoImportSource), &importSource)
if err != nil {
return newError("failed to get import source: ", err)
}
if err := s.addTrackedSubscriptionFromImportSource(&importSource, false); err != nil {
return newError("failed to add tracked subscription: ", err)
}
}
return nil
}
func NewSubscriptionManager(ctx context.Context, config *subscription.Config) (*SubscriptionManagerImpl, error) {
instance := core.MustFromContext(ctx)
impl := &SubscriptionManagerImpl{ctx: ctx, s: instance, config: config}
if err := impl.init(); err != nil {
return nil, newError("failed to init subscription manager: ", err)
}
return impl, nil
}
func init() {
common.Must(common.RegisterConfig((*subscription.Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewSubscriptionManager(ctx, config.(*subscription.Config))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/tracked_subscription.go | app/subscription/subscriptionmanager/tracked_subscription.go | package subscriptionmanager
import (
"time"
"github.com/v2fly/v2ray-core/v5/app/subscription"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
)
func newTrackedSubscription(importSource *subscription.ImportSource) (*trackedSubscription, error) { //nolint: unparam
return &trackedSubscription{importSource: importSource, materialized: map[string]*materializedServer{}}, nil
}
type trackedSubscription struct {
importSource *subscription.ImportSource
currentDocumentExpireTime time.Time
currentDocument *specs.SubscriptionDocument
materialized map[string]*materializedServer
originalDocument []byte
originalContainer *containers.Container
originalServerConfig map[string]*originalServerConfig
addedByAPI bool
}
type originalServerConfig struct {
data []byte
}
func (s *trackedSubscription) diff(newDocument *specs.SubscriptionDocument) (changedDocument, error) { //nolint: unparam
delta := changedDocument{}
seen := make(map[string]bool)
for _, server := range newDocument.Server {
if currentMaterialized, found := s.materialized[server.Id]; found {
if currentMaterialized.serverConfig.Metadata[ServerMetadataFullyQualifiedName] == server.Metadata[ServerMetadataFullyQualifiedName] {
delta.unchanged = append(delta.unchanged, server.Id)
} else {
delta.modified = append(delta.modified, server.Id)
}
seen[server.Id] = true
} else {
delta.added = append(delta.added, server.Id)
}
}
for name := range s.materialized {
if _, ok := seen[name]; !ok {
delta.removed = append(delta.removed, name)
}
}
return delta, nil
}
func (s *trackedSubscription) recordRemovedServer(name string) {
delete(s.materialized, name)
}
func (s *trackedSubscription) recordUpdatedServer(name, tagPostfix string, serverConfig *specs.SubscriptionServerConfig) {
s.materialized[name] = &materializedServer{tagPostfix: tagPostfix, serverConfig: serverConfig}
}
func (s *trackedSubscription) getCurrentServer(name string) (*materializedServer, error) {
if materialized, found := s.materialized[name]; found {
return materialized, nil
} else {
return nil, newError("not found")
}
}
type materializedServer struct {
tagPostfix string
serverConfig *specs.SubscriptionServerConfig
}
func (s *trackedSubscription) fillStatus(status *subscription.TrackedSubscriptionStatus) error { //nolint: unparam
status.ImportSource = s.importSource
if s.currentDocument == nil {
return nil
}
status.DocumentMetadata = s.currentDocument.Metadata
status.Servers = make(map[string]*subscription.SubscriptionServer)
for _, v := range s.currentDocument.Server {
status.Servers[v.Id] = &subscription.SubscriptionServer{
ServerMetadata: v.Metadata,
}
if materializedInstance, ok := s.materialized[v.Id]; ok {
status.Servers[v.Id].Tag = materializedInstance.tagPostfix
}
}
status.AddedByApi = s.addedByAPI
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/subscriptionmanager/command/command.pb.go | app/subscription/subscriptionmanager/command/command.pb.go | package command
import (
subscription "github.com/v2fly/v2ray-core/v5/app/subscription"
_ "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 ListTrackedSubscriptionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListTrackedSubscriptionRequest) Reset() {
*x = ListTrackedSubscriptionRequest{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListTrackedSubscriptionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListTrackedSubscriptionRequest) ProtoMessage() {}
func (x *ListTrackedSubscriptionRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 ListTrackedSubscriptionRequest.ProtoReflect.Descriptor instead.
func (*ListTrackedSubscriptionRequest) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{0}
}
type ListTrackedSubscriptionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Names []string `protobuf:"bytes,1,rep,name=names,proto3" json:"names,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListTrackedSubscriptionResponse) Reset() {
*x = ListTrackedSubscriptionResponse{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListTrackedSubscriptionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListTrackedSubscriptionResponse) ProtoMessage() {}
func (x *ListTrackedSubscriptionResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 ListTrackedSubscriptionResponse.ProtoReflect.Descriptor instead.
func (*ListTrackedSubscriptionResponse) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{1}
}
func (x *ListTrackedSubscriptionResponse) GetNames() []string {
if x != nil {
return x.Names
}
return nil
}
type AddTrackedSubscriptionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Source *subscription.ImportSource `protobuf:"bytes,1,opt,name=source,proto3" json:"source,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddTrackedSubscriptionRequest) Reset() {
*x = AddTrackedSubscriptionRequest{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddTrackedSubscriptionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTrackedSubscriptionRequest) ProtoMessage() {}
func (x *AddTrackedSubscriptionRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 AddTrackedSubscriptionRequest.ProtoReflect.Descriptor instead.
func (*AddTrackedSubscriptionRequest) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{2}
}
func (x *AddTrackedSubscriptionRequest) GetSource() *subscription.ImportSource {
if x != nil {
return x.Source
}
return nil
}
type AddTrackedSubscriptionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddTrackedSubscriptionResponse) Reset() {
*x = AddTrackedSubscriptionResponse{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddTrackedSubscriptionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTrackedSubscriptionResponse) ProtoMessage() {}
func (x *AddTrackedSubscriptionResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 AddTrackedSubscriptionResponse.ProtoReflect.Descriptor instead.
func (*AddTrackedSubscriptionResponse) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{3}
}
type RemoveTrackedSubscriptionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RemoveTrackedSubscriptionRequest) Reset() {
*x = RemoveTrackedSubscriptionRequest{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RemoveTrackedSubscriptionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTrackedSubscriptionRequest) ProtoMessage() {}
func (x *RemoveTrackedSubscriptionRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 RemoveTrackedSubscriptionRequest.ProtoReflect.Descriptor instead.
func (*RemoveTrackedSubscriptionRequest) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{4}
}
func (x *RemoveTrackedSubscriptionRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
type RemoveTrackedSubscriptionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RemoveTrackedSubscriptionResponse) Reset() {
*x = RemoveTrackedSubscriptionResponse{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RemoveTrackedSubscriptionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTrackedSubscriptionResponse) ProtoMessage() {}
func (x *RemoveTrackedSubscriptionResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 RemoveTrackedSubscriptionResponse.ProtoReflect.Descriptor instead.
func (*RemoveTrackedSubscriptionResponse) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{5}
}
type UpdateTrackedSubscriptionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateTrackedSubscriptionRequest) Reset() {
*x = UpdateTrackedSubscriptionRequest{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateTrackedSubscriptionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateTrackedSubscriptionRequest) ProtoMessage() {}
func (x *UpdateTrackedSubscriptionRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 UpdateTrackedSubscriptionRequest.ProtoReflect.Descriptor instead.
func (*UpdateTrackedSubscriptionRequest) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{6}
}
func (x *UpdateTrackedSubscriptionRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
type UpdateTrackedSubscriptionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateTrackedSubscriptionResponse) Reset() {
*x = UpdateTrackedSubscriptionResponse{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateTrackedSubscriptionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateTrackedSubscriptionResponse) ProtoMessage() {}
func (x *UpdateTrackedSubscriptionResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 UpdateTrackedSubscriptionResponse.ProtoReflect.Descriptor instead.
func (*UpdateTrackedSubscriptionResponse) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{7}
}
type GetTrackedSubscriptionStatusRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetTrackedSubscriptionStatusRequest) Reset() {
*x = GetTrackedSubscriptionStatusRequest{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetTrackedSubscriptionStatusRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTrackedSubscriptionStatusRequest) ProtoMessage() {}
func (x *GetTrackedSubscriptionStatusRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 GetTrackedSubscriptionStatusRequest.ProtoReflect.Descriptor instead.
func (*GetTrackedSubscriptionStatusRequest) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{8}
}
func (x *GetTrackedSubscriptionStatusRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
type GetTrackedSubscriptionStatusResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status *subscription.TrackedSubscriptionStatus `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetTrackedSubscriptionStatusResponse) Reset() {
*x = GetTrackedSubscriptionStatusResponse{}
mi := &file_app_subscription_subscriptionmanager_command_command_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetTrackedSubscriptionStatusResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTrackedSubscriptionStatusResponse) ProtoMessage() {}
func (x *GetTrackedSubscriptionStatusResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_subscriptionmanager_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 GetTrackedSubscriptionStatusResponse.ProtoReflect.Descriptor instead.
func (*GetTrackedSubscriptionStatusResponse) Descriptor() ([]byte, []int) {
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{9}
}
func (x *GetTrackedSubscriptionStatusResponse) GetStatus() *subscription.TrackedSubscriptionStatus {
if x != nil {
return x.Status
}
return nil
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_subscription_subscriptionmanager_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_subscription_subscriptionmanager_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_subscription_subscriptionmanager_command_command_proto_rawDescGZIP(), []int{10}
}
var File_app_subscription_subscriptionmanager_command_command_proto protoreflect.FileDescriptor
const file_app_subscription_subscriptionmanager_command_command_proto_rawDesc = "" +
"\n" +
":app/subscription/subscriptionmanager/command/command.proto\x127v2ray.core.app.subscription.subscriptionmanager.command\x1a common/protoext/extensions.proto\x1a\x1dapp/subscription/config.proto\x1a'app/subscription/subscription_rpc.proto\" \n" +
"\x1eListTrackedSubscriptionRequest\"7\n" +
"\x1fListTrackedSubscriptionResponse\x12\x14\n" +
"\x05names\x18\x01 \x03(\tR\x05names\"b\n" +
"\x1dAddTrackedSubscriptionRequest\x12A\n" +
"\x06source\x18\x01 \x01(\v2).v2ray.core.app.subscription.ImportSourceR\x06source\" \n" +
"\x1eAddTrackedSubscriptionResponse\"6\n" +
" RemoveTrackedSubscriptionRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"#\n" +
"!RemoveTrackedSubscriptionResponse\"6\n" +
" UpdateTrackedSubscriptionRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"#\n" +
"!UpdateTrackedSubscriptionResponse\"9\n" +
"#GetTrackedSubscriptionStatusRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"v\n" +
"$GetTrackedSubscriptionStatusResponse\x12N\n" +
"\x06status\x18\x01 \x01(\v26.v2ray.core.app.subscription.TrackedSubscriptionStatusR\x06status\"0\n" +
"\x06Config:&\x82\xb5\x18\"\n" +
"\vgrpcservice\x12\x13subscriptionmanager2\xc9\b\n" +
"\x1aSubscriptionManagerService\x12\xce\x01\n" +
"\x17ListTrackedSubscription\x12W.v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionRequest\x1aX.v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionResponse\"\x00\x12\xcb\x01\n" +
"\x16AddTrackedSubscription\x12V.v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionRequest\x1aW.v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionResponse\"\x00\x12\xd4\x01\n" +
"\x19RemoveTrackedSubscription\x12Y.v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionRequest\x1aZ.v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionResponse\"\x00\x12\xdd\x01\n" +
"\x1cGetTrackedSubscriptionStatus\x12\\.v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusRequest\x1a].v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusResponse\"\x00\x12\xd4\x01\n" +
"\x19UpdateTrackedSubscription\x12Y.v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionRequest\x1aZ.v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionResponse\"\x00B\xc2\x01\n" +
"7com.v2ray.core.subscription.subscriptionmanager.commandP\x01ZKgithub.com/v2fly/v2ray-core/v5/app/subscription/subscriptionmanager/command\xaa\x027V2Ray.Core.App.Subscription.Subscriptionmanager.Commandb\x06proto3"
var (
file_app_subscription_subscriptionmanager_command_command_proto_rawDescOnce sync.Once
file_app_subscription_subscriptionmanager_command_command_proto_rawDescData []byte
)
func file_app_subscription_subscriptionmanager_command_command_proto_rawDescGZIP() []byte {
file_app_subscription_subscriptionmanager_command_command_proto_rawDescOnce.Do(func() {
file_app_subscription_subscriptionmanager_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_subscription_subscriptionmanager_command_command_proto_rawDesc), len(file_app_subscription_subscriptionmanager_command_command_proto_rawDesc)))
})
return file_app_subscription_subscriptionmanager_command_command_proto_rawDescData
}
var file_app_subscription_subscriptionmanager_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
var file_app_subscription_subscriptionmanager_command_command_proto_goTypes = []any{
(*ListTrackedSubscriptionRequest)(nil), // 0: v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionRequest
(*ListTrackedSubscriptionResponse)(nil), // 1: v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionResponse
(*AddTrackedSubscriptionRequest)(nil), // 2: v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionRequest
(*AddTrackedSubscriptionResponse)(nil), // 3: v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionResponse
(*RemoveTrackedSubscriptionRequest)(nil), // 4: v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionRequest
(*RemoveTrackedSubscriptionResponse)(nil), // 5: v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionResponse
(*UpdateTrackedSubscriptionRequest)(nil), // 6: v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionRequest
(*UpdateTrackedSubscriptionResponse)(nil), // 7: v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionResponse
(*GetTrackedSubscriptionStatusRequest)(nil), // 8: v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusRequest
(*GetTrackedSubscriptionStatusResponse)(nil), // 9: v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusResponse
(*Config)(nil), // 10: v2ray.core.app.subscription.subscriptionmanager.command.Config
(*subscription.ImportSource)(nil), // 11: v2ray.core.app.subscription.ImportSource
(*subscription.TrackedSubscriptionStatus)(nil), // 12: v2ray.core.app.subscription.TrackedSubscriptionStatus
}
var file_app_subscription_subscriptionmanager_command_command_proto_depIdxs = []int32{
11, // 0: v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionRequest.source:type_name -> v2ray.core.app.subscription.ImportSource
12, // 1: v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusResponse.status:type_name -> v2ray.core.app.subscription.TrackedSubscriptionStatus
0, // 2: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.ListTrackedSubscription:input_type -> v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionRequest
2, // 3: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.AddTrackedSubscription:input_type -> v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionRequest
4, // 4: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.RemoveTrackedSubscription:input_type -> v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionRequest
8, // 5: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.GetTrackedSubscriptionStatus:input_type -> v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusRequest
6, // 6: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.UpdateTrackedSubscription:input_type -> v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionRequest
1, // 7: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.ListTrackedSubscription:output_type -> v2ray.core.app.subscription.subscriptionmanager.command.ListTrackedSubscriptionResponse
3, // 8: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.AddTrackedSubscription:output_type -> v2ray.core.app.subscription.subscriptionmanager.command.AddTrackedSubscriptionResponse
5, // 9: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.RemoveTrackedSubscription:output_type -> v2ray.core.app.subscription.subscriptionmanager.command.RemoveTrackedSubscriptionResponse
9, // 10: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.GetTrackedSubscriptionStatus:output_type -> v2ray.core.app.subscription.subscriptionmanager.command.GetTrackedSubscriptionStatusResponse
7, // 11: v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService.UpdateTrackedSubscription:output_type -> v2ray.core.app.subscription.subscriptionmanager.command.UpdateTrackedSubscriptionResponse
7, // [7:12] is the sub-list for method output_type
2, // [2:7] 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_app_subscription_subscriptionmanager_command_command_proto_init() }
func file_app_subscription_subscriptionmanager_command_command_proto_init() {
if File_app_subscription_subscriptionmanager_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_subscription_subscriptionmanager_command_command_proto_rawDesc), len(file_app_subscription_subscriptionmanager_command_command_proto_rawDesc)),
NumEnums: 0,
NumMessages: 11,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_app_subscription_subscriptionmanager_command_command_proto_goTypes,
DependencyIndexes: file_app_subscription_subscriptionmanager_command_command_proto_depIdxs,
MessageInfos: file_app_subscription_subscriptionmanager_command_command_proto_msgTypes,
}.Build()
File_app_subscription_subscriptionmanager_command_command_proto = out.File
file_app_subscription_subscriptionmanager_command_command_proto_goTypes = nil
file_app_subscription_subscriptionmanager_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/subscription/subscriptionmanager/command/errors.generated.go | app/subscription/subscriptionmanager/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/subscription/subscriptionmanager/command/command_grpc.pb.go | app/subscription/subscriptionmanager/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 (
SubscriptionManagerService_ListTrackedSubscription_FullMethodName = "/v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService/ListTrackedSubscription"
SubscriptionManagerService_AddTrackedSubscription_FullMethodName = "/v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService/AddTrackedSubscription"
SubscriptionManagerService_RemoveTrackedSubscription_FullMethodName = "/v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService/RemoveTrackedSubscription"
SubscriptionManagerService_GetTrackedSubscriptionStatus_FullMethodName = "/v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService/GetTrackedSubscriptionStatus"
SubscriptionManagerService_UpdateTrackedSubscription_FullMethodName = "/v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService/UpdateTrackedSubscription"
)
// SubscriptionManagerServiceClient is the client API for SubscriptionManagerService 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 SubscriptionManagerServiceClient interface {
ListTrackedSubscription(ctx context.Context, in *ListTrackedSubscriptionRequest, opts ...grpc.CallOption) (*ListTrackedSubscriptionResponse, error)
AddTrackedSubscription(ctx context.Context, in *AddTrackedSubscriptionRequest, opts ...grpc.CallOption) (*AddTrackedSubscriptionResponse, error)
RemoveTrackedSubscription(ctx context.Context, in *RemoveTrackedSubscriptionRequest, opts ...grpc.CallOption) (*RemoveTrackedSubscriptionResponse, error)
GetTrackedSubscriptionStatus(ctx context.Context, in *GetTrackedSubscriptionStatusRequest, opts ...grpc.CallOption) (*GetTrackedSubscriptionStatusResponse, error)
UpdateTrackedSubscription(ctx context.Context, in *UpdateTrackedSubscriptionRequest, opts ...grpc.CallOption) (*UpdateTrackedSubscriptionResponse, error)
}
type subscriptionManagerServiceClient struct {
cc grpc.ClientConnInterface
}
func NewSubscriptionManagerServiceClient(cc grpc.ClientConnInterface) SubscriptionManagerServiceClient {
return &subscriptionManagerServiceClient{cc}
}
func (c *subscriptionManagerServiceClient) ListTrackedSubscription(ctx context.Context, in *ListTrackedSubscriptionRequest, opts ...grpc.CallOption) (*ListTrackedSubscriptionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListTrackedSubscriptionResponse)
err := c.cc.Invoke(ctx, SubscriptionManagerService_ListTrackedSubscription_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *subscriptionManagerServiceClient) AddTrackedSubscription(ctx context.Context, in *AddTrackedSubscriptionRequest, opts ...grpc.CallOption) (*AddTrackedSubscriptionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddTrackedSubscriptionResponse)
err := c.cc.Invoke(ctx, SubscriptionManagerService_AddTrackedSubscription_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *subscriptionManagerServiceClient) RemoveTrackedSubscription(ctx context.Context, in *RemoveTrackedSubscriptionRequest, opts ...grpc.CallOption) (*RemoveTrackedSubscriptionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RemoveTrackedSubscriptionResponse)
err := c.cc.Invoke(ctx, SubscriptionManagerService_RemoveTrackedSubscription_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *subscriptionManagerServiceClient) GetTrackedSubscriptionStatus(ctx context.Context, in *GetTrackedSubscriptionStatusRequest, opts ...grpc.CallOption) (*GetTrackedSubscriptionStatusResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetTrackedSubscriptionStatusResponse)
err := c.cc.Invoke(ctx, SubscriptionManagerService_GetTrackedSubscriptionStatus_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *subscriptionManagerServiceClient) UpdateTrackedSubscription(ctx context.Context, in *UpdateTrackedSubscriptionRequest, opts ...grpc.CallOption) (*UpdateTrackedSubscriptionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateTrackedSubscriptionResponse)
err := c.cc.Invoke(ctx, SubscriptionManagerService_UpdateTrackedSubscription_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// SubscriptionManagerServiceServer is the server API for SubscriptionManagerService service.
// All implementations must embed UnimplementedSubscriptionManagerServiceServer
// for forward compatibility.
type SubscriptionManagerServiceServer interface {
ListTrackedSubscription(context.Context, *ListTrackedSubscriptionRequest) (*ListTrackedSubscriptionResponse, error)
AddTrackedSubscription(context.Context, *AddTrackedSubscriptionRequest) (*AddTrackedSubscriptionResponse, error)
RemoveTrackedSubscription(context.Context, *RemoveTrackedSubscriptionRequest) (*RemoveTrackedSubscriptionResponse, error)
GetTrackedSubscriptionStatus(context.Context, *GetTrackedSubscriptionStatusRequest) (*GetTrackedSubscriptionStatusResponse, error)
UpdateTrackedSubscription(context.Context, *UpdateTrackedSubscriptionRequest) (*UpdateTrackedSubscriptionResponse, error)
mustEmbedUnimplementedSubscriptionManagerServiceServer()
}
// UnimplementedSubscriptionManagerServiceServer 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 UnimplementedSubscriptionManagerServiceServer struct{}
func (UnimplementedSubscriptionManagerServiceServer) ListTrackedSubscription(context.Context, *ListTrackedSubscriptionRequest) (*ListTrackedSubscriptionResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListTrackedSubscription not implemented")
}
func (UnimplementedSubscriptionManagerServiceServer) AddTrackedSubscription(context.Context, *AddTrackedSubscriptionRequest) (*AddTrackedSubscriptionResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddTrackedSubscription not implemented")
}
func (UnimplementedSubscriptionManagerServiceServer) RemoveTrackedSubscription(context.Context, *RemoveTrackedSubscriptionRequest) (*RemoveTrackedSubscriptionResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RemoveTrackedSubscription not implemented")
}
func (UnimplementedSubscriptionManagerServiceServer) GetTrackedSubscriptionStatus(context.Context, *GetTrackedSubscriptionStatusRequest) (*GetTrackedSubscriptionStatusResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetTrackedSubscriptionStatus not implemented")
}
func (UnimplementedSubscriptionManagerServiceServer) UpdateTrackedSubscription(context.Context, *UpdateTrackedSubscriptionRequest) (*UpdateTrackedSubscriptionResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateTrackedSubscription not implemented")
}
func (UnimplementedSubscriptionManagerServiceServer) mustEmbedUnimplementedSubscriptionManagerServiceServer() {
}
func (UnimplementedSubscriptionManagerServiceServer) testEmbeddedByValue() {}
// UnsafeSubscriptionManagerServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to SubscriptionManagerServiceServer will
// result in compilation errors.
type UnsafeSubscriptionManagerServiceServer interface {
mustEmbedUnimplementedSubscriptionManagerServiceServer()
}
func RegisterSubscriptionManagerServiceServer(s grpc.ServiceRegistrar, srv SubscriptionManagerServiceServer) {
// If the following call pancis, it indicates UnimplementedSubscriptionManagerServiceServer 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(&SubscriptionManagerService_ServiceDesc, srv)
}
func _SubscriptionManagerService_ListTrackedSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListTrackedSubscriptionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SubscriptionManagerServiceServer).ListTrackedSubscription(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SubscriptionManagerService_ListTrackedSubscription_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SubscriptionManagerServiceServer).ListTrackedSubscription(ctx, req.(*ListTrackedSubscriptionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SubscriptionManagerService_AddTrackedSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddTrackedSubscriptionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SubscriptionManagerServiceServer).AddTrackedSubscription(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SubscriptionManagerService_AddTrackedSubscription_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SubscriptionManagerServiceServer).AddTrackedSubscription(ctx, req.(*AddTrackedSubscriptionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SubscriptionManagerService_RemoveTrackedSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RemoveTrackedSubscriptionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SubscriptionManagerServiceServer).RemoveTrackedSubscription(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SubscriptionManagerService_RemoveTrackedSubscription_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SubscriptionManagerServiceServer).RemoveTrackedSubscription(ctx, req.(*RemoveTrackedSubscriptionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SubscriptionManagerService_GetTrackedSubscriptionStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTrackedSubscriptionStatusRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SubscriptionManagerServiceServer).GetTrackedSubscriptionStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SubscriptionManagerService_GetTrackedSubscriptionStatus_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SubscriptionManagerServiceServer).GetTrackedSubscriptionStatus(ctx, req.(*GetTrackedSubscriptionStatusRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SubscriptionManagerService_UpdateTrackedSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateTrackedSubscriptionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SubscriptionManagerServiceServer).UpdateTrackedSubscription(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SubscriptionManagerService_UpdateTrackedSubscription_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SubscriptionManagerServiceServer).UpdateTrackedSubscription(ctx, req.(*UpdateTrackedSubscriptionRequest))
}
return interceptor(ctx, in, info, handler)
}
// SubscriptionManagerService_ServiceDesc is the grpc.ServiceDesc for SubscriptionManagerService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var SubscriptionManagerService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v2ray.core.app.subscription.subscriptionmanager.command.SubscriptionManagerService",
HandlerType: (*SubscriptionManagerServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListTrackedSubscription",
Handler: _SubscriptionManagerService_ListTrackedSubscription_Handler,
},
{
MethodName: "AddTrackedSubscription",
Handler: _SubscriptionManagerService_AddTrackedSubscription_Handler,
},
{
MethodName: "RemoveTrackedSubscription",
Handler: _SubscriptionManagerService_RemoveTrackedSubscription_Handler,
},
{
MethodName: "GetTrackedSubscriptionStatus",
Handler: _SubscriptionManagerService_GetTrackedSubscriptionStatus_Handler,
},
{
MethodName: "UpdateTrackedSubscription",
Handler: _SubscriptionManagerService_UpdateTrackedSubscription_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/subscription/subscriptionmanager/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/subscription/subscriptionmanager/command/command.go | app/subscription/subscriptionmanager/command/command.go | package command
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/subscription"
"github.com/v2fly/v2ray-core/v5/common"
"google.golang.org/grpc"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type SubscriptionManagerService struct {
UnimplementedSubscriptionManagerServiceServer
manager subscription.SubscriptionManager
}
func (s *SubscriptionManagerService) UpdateTrackedSubscription(ctx context.Context, request *UpdateTrackedSubscriptionRequest) (*UpdateTrackedSubscriptionResponse, error) {
if s.manager == nil {
return nil, newError("subscription manager is not available")
}
err := s.manager.UpdateTrackedSubscription(request.Name)
if err != nil {
return nil, err
}
return &UpdateTrackedSubscriptionResponse{}, nil
}
func NewSubscriptionManagerService(manager subscription.SubscriptionManager) *SubscriptionManagerService {
return &SubscriptionManagerService{manager: manager}
}
func (s *SubscriptionManagerService) ListTrackedSubscription(ctx context.Context, req *ListTrackedSubscriptionRequest) (*ListTrackedSubscriptionResponse, error) {
if s.manager == nil {
return nil, newError("subscription manager is not available")
}
names := s.manager.ListTrackedSubscriptions()
return &ListTrackedSubscriptionResponse{Names: names}, nil
}
func (s *SubscriptionManagerService) AddTrackedSubscription(ctx context.Context, req *AddTrackedSubscriptionRequest) (*AddTrackedSubscriptionResponse, error) {
if s.manager == nil {
return nil, newError("subscription manager is not available")
}
err := s.manager.AddTrackedSubscriptionFromImportSource(req.Source)
if err != nil {
return nil, err
}
return &AddTrackedSubscriptionResponse{}, nil
}
func (s *SubscriptionManagerService) RemoveTrackedSubscription(ctx context.Context, req *RemoveTrackedSubscriptionRequest) (*RemoveTrackedSubscriptionResponse, error) {
if s.manager == nil {
return nil, newError("subscription manager is not available")
}
err := s.manager.RemoveTrackedSubscription(req.Name)
if err != nil {
return nil, err
}
return &RemoveTrackedSubscriptionResponse{}, nil
}
func (s *SubscriptionManagerService) GetTrackedSubscriptionStatus(ctx context.Context, req *GetTrackedSubscriptionStatusRequest) (*GetTrackedSubscriptionStatusResponse, error) {
if s.manager == nil {
return nil, newError("subscription manager is not available")
}
status, err := s.manager.GetTrackedSubscriptionStatus(req.Name)
if err != nil {
return nil, err
}
return &GetTrackedSubscriptionStatusResponse{Status: status}, nil
}
func (s *SubscriptionManagerService) Register(server *grpc.Server) {
RegisterSubscriptionManagerServiceServer(server, s)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
var manager subscription.SubscriptionManager
common.Must(core.RequireFeatures(ctx, func(m subscription.SubscriptionManager) {
manager = m
}))
service := NewSubscriptionManagerService(manager)
return service, nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/documentfetcher/errors.generated.go | app/subscription/documentfetcher/errors.generated.go | package documentfetcher
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/subscription/documentfetcher/fetcher.go | app/subscription/documentfetcher/fetcher.go | package documentfetcher
import (
"context"
"github.com/v2fly/v2ray-core/v5/app/subscription"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type FetcherOptions interface{}
type Fetcher interface {
DownloadDocument(ctx context.Context, source *subscription.ImportSource, opts ...FetcherOptions) ([]byte, error)
}
var knownFetcher = make(map[string]Fetcher)
func RegisterFetcher(name string, fetcher Fetcher) error {
if _, found := knownFetcher[name]; found {
return newError("fetcher ", name, " already registered")
}
knownFetcher[name] = fetcher
return nil
}
func GetFetcher(name string) (Fetcher, error) {
if fetcher, found := knownFetcher[name]; found {
return fetcher, nil
}
return nil, newError("fetcher ", name, " not found")
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/documentfetcher/dataurlfetcher/errors.generated.go | app/subscription/documentfetcher/dataurlfetcher/errors.generated.go | package dataurlfetcher
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/subscription/documentfetcher/dataurlfetcher/dataurl.go | app/subscription/documentfetcher/dataurlfetcher/dataurl.go | package dataurlfetcher
import (
"context"
"strings"
"github.com/vincent-petithory/dataurl"
"github.com/v2fly/v2ray-core/v5/app/subscription"
"github.com/v2fly/v2ray-core/v5/app/subscription/documentfetcher"
"github.com/v2fly/v2ray-core/v5/common"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func newDataURLFetcher() *dataURLFetcher {
return &dataURLFetcher{}
}
func init() {
common.Must(documentfetcher.RegisterFetcher("dataurl", newDataURLFetcher()))
}
type dataURLFetcher struct{}
func (d *dataURLFetcher) DownloadDocument(ctx context.Context, source *subscription.ImportSource, opts ...documentfetcher.FetcherOptions) ([]byte, error) {
dataURL, err := dataurl.DecodeString(source.Url)
if err != nil {
return nil, newError("unable to decode dataURL").Base(err)
}
if dataURL.MediaType.Type != "application" {
return nil, newError("unsupported media type: ", dataURL.MediaType.Type)
}
if !strings.HasPrefix(dataURL.MediaType.Subtype, "vnd.v2ray.subscription") {
return nil, newError("unsupported media subtype: ", dataURL.MediaType.Subtype)
}
return []byte(source.Url), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/documentfetcher/httpfetcher/errors.generated.go | app/subscription/documentfetcher/httpfetcher/errors.generated.go | package httpfetcher
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/subscription/documentfetcher/httpfetcher/http.go | app/subscription/documentfetcher/httpfetcher/http.go | package httpfetcher
import (
"context"
"io"
gonet "net"
"net/http"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/app/subscription"
"github.com/v2fly/v2ray-core/v5/app/subscription/documentfetcher"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func newHTTPFetcher() *httpFetcher {
return &httpFetcher{}
}
func init() {
common.Must(documentfetcher.RegisterFetcher("http", newHTTPFetcher()))
}
type httpFetcher struct{}
func (h *httpFetcher) DownloadDocument(ctx context.Context, source *subscription.ImportSource, opts ...documentfetcher.FetcherOptions) ([]byte, error) {
instanceNetwork := envctx.EnvironmentFromContext(ctx).(environment.InstanceNetworkCapabilitySet)
outboundDialer := instanceNetwork.OutboundDialer()
var httpRoundTripper http.RoundTripper //nolint: gosimple
httpRoundTripper = &http.Transport{
DialContext: func(ctx_ context.Context, network string, addr string) (gonet.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, newError("unable to parse destination")
}
return outboundDialer(ctx, dest, source.ImportUsingTag)
},
}
request, err := http.NewRequest("GET", source.Url, nil)
if err != nil {
return nil, newError("unable to generate request").Base(err)
}
resp, err := httpRoundTripper.RoundTrip(request)
if err != nil {
return nil, newError("unable to send request").Base(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, newError("unexpected http status ", resp.StatusCode, "=", resp.Status)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, newError("unable to read response").Base(err)
}
return data, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/errors.generated.go | app/subscription/containers/errors.generated.go | package containers
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/subscription/containers/tryall.go | app/subscription/containers/tryall.go | package containers
func TryAllParsers(rawConfig []byte, prioritizedParser string) (*Container, error) {
if prioritizedParser != "" {
if parser, found := knownParsers[prioritizedParser]; found {
container, err := parser.ParseSubscriptionContainerDocument(rawConfig)
if err == nil {
return container, nil
}
}
}
for _, parser := range knownParsers {
container, err := parser.ParseSubscriptionContainerDocument(rawConfig)
if err == nil {
return container, nil
}
}
return nil, newError("no parser found for config")
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/containers.go | app/subscription/containers/containers.go | package containers
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type UnparsedServerConf struct {
KindHint string
Content []byte
}
type Container struct {
Kind string
Metadata map[string]string
ServerSpecs []UnparsedServerConf
}
type SubscriptionContainerDocumentParser interface {
ParseSubscriptionContainerDocument(rawConfig []byte) (*Container, error)
}
var knownParsers = make(map[string]SubscriptionContainerDocumentParser)
func RegisterParser(kind string, parser SubscriptionContainerDocumentParser) error {
if _, found := knownParsers[kind]; found {
return newError("parser already registered for kind ", kind)
}
knownParsers[kind] = parser
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/base64urlline/parser.go | app/subscription/containers/base64urlline/parser.go | package base64urlline
import (
"bufio"
"bytes"
"encoding/base64"
"io"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/common"
)
func newBase64URLLineParser() containers.SubscriptionContainerDocumentParser {
return &parser{}
}
type parser struct{}
func (p parser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
result := &containers.Container{}
result.Kind = "Base64URLLine"
result.Metadata = make(map[string]string)
bodyDecoder := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(rawConfig))
decoded, err := io.ReadAll(bodyDecoder)
if err != nil {
return nil, newError("failed to decode base64url body base64").Base(err)
}
scanner := bufio.NewScanner(bytes.NewReader(decoded))
const maxCapacity int = 1024 * 256
buf := make([]byte, maxCapacity)
scanner.Buffer(buf, maxCapacity)
for scanner.Scan() {
result.ServerSpecs = append(result.ServerSpecs, containers.UnparsedServerConf{
KindHint: "URL",
Content: scanner.Bytes(),
})
}
return result, nil
}
func init() {
common.Must(containers.RegisterParser("Base64URLLine", newBase64URLLineParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/base64urlline/errors.generated.go | app/subscription/containers/base64urlline/errors.generated.go | package base64urlline
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/subscription/containers/base64urlline/base64urlline.go | app/subscription/containers/base64urlline/base64urlline.go | package base64urlline
//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/subscription/containers/dataurlsingle/errors.generated.go | app/subscription/containers/dataurlsingle/errors.generated.go | package dataurlsingle
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/subscription/containers/dataurlsingle/dataurl.go | app/subscription/containers/dataurlsingle/dataurl.go | package dataurlsingle
import (
"bytes"
"strings"
"github.com/vincent-petithory/dataurl"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/common"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func newSingularDataURLParser() containers.SubscriptionContainerDocumentParser {
return &parser{}
}
type parser struct{}
func (p parser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
dataURL, err := dataurl.Decode(bytes.NewReader(rawConfig))
if err != nil {
return nil, newError("unable to decode dataURL").Base(err)
}
if dataURL.MediaType.Type != "application" {
return nil, newError("unsupported media type: ", dataURL.MediaType.Type)
}
if !strings.HasPrefix(dataURL.MediaType.Subtype, "vnd.v2ray.subscription-singular") {
return nil, newError("unsupported media subtype: ", dataURL.MediaType.Subtype)
}
result := &containers.Container{}
result.Kind = "DataURLSingle"
result.Metadata = make(map[string]string)
result.ServerSpecs = append(result.ServerSpecs, containers.UnparsedServerConf{
KindHint: "",
Content: dataURL.Data,
})
return result, nil
}
func init() {
common.Must(containers.RegisterParser("DataURLSingle", newSingularDataURLParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/urlline/parser.go | app/subscription/containers/urlline/parser.go | package urlline
import (
"bufio"
"bytes"
"net/url"
"strings"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/common"
)
func newURLLineParser() containers.SubscriptionContainerDocumentParser {
return &parser{}
}
type parser struct{}
func (p parser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
result := &containers.Container{}
result.Kind = "URLLine"
result.Metadata = make(map[string]string)
scanner := bufio.NewScanner(bytes.NewReader(rawConfig))
const maxCapacity int = 1024 * 256
buf := make([]byte, maxCapacity)
scanner.Buffer(buf, maxCapacity)
parsedLine := 0
failedLine := 0
for scanner.Scan() {
content := scanner.Text()
content = strings.TrimSpace(content)
if strings.HasPrefix(content, "#") {
continue
}
if strings.HasPrefix(content, "//") {
continue
}
_, err := url.Parse(content)
if err != nil {
failedLine++
continue
} else {
parsedLine++
}
result.ServerSpecs = append(result.ServerSpecs, containers.UnparsedServerConf{
KindHint: "URL",
Content: scanner.Bytes(),
})
}
if failedLine > parsedLine || parsedLine == 0 {
return nil, newError("failed to parse as URLLine").Base(newError("too many failed lines"))
}
return result, nil
}
func init() {
common.Must(containers.RegisterParser("URLLine", newURLLineParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/urlline/errors.generated.go | app/subscription/containers/urlline/errors.generated.go | package urlline
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/subscription/containers/urlline/urlline.go | app/subscription/containers/urlline/urlline.go | package urlline
//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/subscription/containers/jsonfieldarray/parser.go | app/subscription/containers/jsonfieldarray/parser.go | package jsonfieldarray
import (
"encoding/json"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/common"
)
// NewJSONFieldArrayParser internal api
func NewJSONFieldArrayParser() containers.SubscriptionContainerDocumentParser {
return newJSONFieldArrayParser()
}
func newJSONFieldArrayParser() containers.SubscriptionContainerDocumentParser {
return &parser{}
}
type parser struct{}
type jsonDocument map[string]json.RawMessage
func (p parser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
result := &containers.Container{}
result.Kind = "JsonFieldArray"
result.Metadata = make(map[string]string)
var doc jsonDocument
if err := json.Unmarshal(rawConfig, &doc); err != nil {
return nil, newError("failed to parse as json").Base(err)
}
for key, value := range doc {
switch value[0] {
case '[':
parsedArray, err := p.parseArray(value, "JsonFieldArray+"+key)
if err != nil {
return nil, newError("failed to parse as json array").Base(err)
}
result.ServerSpecs = append(result.ServerSpecs, parsedArray...)
case '{':
fallthrough
default:
result.Metadata[key] = string(value)
}
}
return result, nil
}
func (p parser) parseArray(rawConfig []byte, kindHint string) ([]containers.UnparsedServerConf, error) {
var result []json.RawMessage
if err := json.Unmarshal(rawConfig, &result); err != nil {
return nil, newError("failed to parse as json array").Base(err)
}
var ret []containers.UnparsedServerConf
for _, value := range result {
ret = append(ret, containers.UnparsedServerConf{
KindHint: kindHint,
Content: []byte(value),
})
}
return ret, nil
}
func init() {
common.Must(containers.RegisterParser("JsonFieldArray", newJSONFieldArrayParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/jsonfieldarray/jsonfieldarray.go | app/subscription/containers/jsonfieldarray/jsonfieldarray.go | package jsonfieldarray
//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/subscription/containers/jsonfieldarray/errors.generated.go | app/subscription/containers/jsonfieldarray/errors.generated.go | package jsonfieldarray
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/subscription/containers/jsonfieldarray/jsonified/jsonified.go | app/subscription/containers/jsonfieldarray/jsonified/jsonified.go | package jsonified
//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/subscription/containers/jsonfieldarray/jsonified/parser.go | app/subscription/containers/jsonfieldarray/jsonified/parser.go | package jsonified
import (
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers/jsonfieldarray"
"github.com/v2fly/v2ray-core/v5/common"
jsonConf "github.com/v2fly/v2ray-core/v5/infra/conf/json"
)
func newJsonifiedYamlParser() containers.SubscriptionContainerDocumentParser {
return &jsonifiedYAMLParser{}
}
type jsonifiedYAMLParser struct{}
func (j jsonifiedYAMLParser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
parser := jsonfieldarray.NewJSONFieldArrayParser()
jsonified, err := jsonConf.FromYAML(rawConfig)
if err != nil {
return nil, newError("failed to parse as yaml").Base(err)
}
container, err := parser.ParseSubscriptionContainerDocument(jsonified)
if err != nil {
return nil, newError("failed to parse as jsonfieldarray").Base(err)
}
container.Kind = "Yaml2Json+" + container.Kind
for _, value := range container.ServerSpecs {
value.KindHint = "Yaml2Json+" + value.KindHint
}
return container, nil
}
func init() {
common.Must(containers.RegisterParser("Yaml2Json", newJsonifiedYamlParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/containers/jsonfieldarray/jsonified/errors.generated.go | app/subscription/containers/jsonfieldarray/jsonified/errors.generated.go | package jsonified
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/subscription/entries/errors.generated.go | app/subscription/entries/errors.generated.go | package entries
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/subscription/entries/register.go | app/subscription/entries/register.go | package entries
import "github.com/v2fly/v2ray-core/v5/app/subscription/specs"
type ConverterRegistry struct {
knownConverters map[string]Converter
parent *ConverterRegistry
}
var globalConverterRegistry = &ConverterRegistry{knownConverters: map[string]Converter{}}
func RegisterConverter(kind string, converter Converter) error {
return globalConverterRegistry.RegisterConverter(kind, converter)
}
func GetOverlayConverterRegistry() *ConverterRegistry {
return globalConverterRegistry.GetOverlayConverterRegistry()
}
func (c *ConverterRegistry) RegisterConverter(kind string, converter Converter) error {
if _, found := c.knownConverters[kind]; found {
return newError("converter already registered for kind ", kind)
}
c.knownConverters[kind] = converter
return nil
}
func (c *ConverterRegistry) TryAllConverters(rawConfig []byte, prioritizedConverter, kindHint string) (*specs.SubscriptionServerConfig, error) {
if prioritizedConverter != "" {
if converter, found := c.knownConverters[prioritizedConverter]; found {
serverConfig, err := converter.ConvertToAbstractServerConfig(rawConfig, kindHint)
if err == nil {
return serverConfig, nil
}
}
}
for _, converter := range c.knownConverters {
serverConfig, err := converter.ConvertToAbstractServerConfig(rawConfig, kindHint)
if err == nil {
return serverConfig, nil
}
}
if c.parent != nil {
if serverConfig, err := c.parent.TryAllConverters(rawConfig, prioritizedConverter, kindHint); err == nil {
return serverConfig, nil
}
}
return nil, newError("no converter found for config")
}
func (c *ConverterRegistry) GetOverlayConverterRegistry() *ConverterRegistry {
return &ConverterRegistry{knownConverters: map[string]Converter{}, parent: c}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/entries.go | app/subscription/entries/entries.go | package entries
import "github.com/v2fly/v2ray-core/v5/app/subscription/specs"
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type Converter interface {
ConvertToAbstractServerConfig(rawConfig []byte, kindHint string) (*specs.SubscriptionServerConfig, error)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/outbound/errors.generated.go | app/subscription/entries/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/subscription/entries/outbound/outbound.go | app/subscription/entries/outbound/outbound.go | package outbound
import (
"github.com/v2fly/v2ray-core/v5/app/subscription/entries"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
"github.com/v2fly/v2ray-core/v5/common"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
// NewOutboundEntriesParser internal api
func NewOutboundEntriesParser() entries.Converter {
return newOutboundEntriesParser()
}
func newOutboundEntriesParser() entries.Converter {
return &outboundEntriesParser{}
}
type outboundEntriesParser struct{}
func (o *outboundEntriesParser) ConvertToAbstractServerConfig(rawConfig []byte, kindHint string) (*specs.SubscriptionServerConfig, error) {
parser := specs.NewOutboundParser()
outbound, err := parser.ParseOutboundConfig(rawConfig)
if err != nil {
return nil, newError("failed to parse outbound config").Base(err).AtWarning()
}
return parser.ToSubscriptionServerConfig(outbound)
}
func init() {
common.Must(entries.RegisterConverter("outbound", newOutboundEntriesParser()))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/nonnative/matchdef.go | app/subscription/entries/nonnative/matchdef.go | package nonnative
import (
"bytes"
"embed"
"encoding/json"
"io/fs"
"strings"
"text/template"
)
//go:embed definitions/*
var embeddedDefinitions embed.FS
func NewDefMatcher() *DefMatcher {
d := &DefMatcher{}
d.init()
return d
}
type DefMatcher struct {
templates *template.Template
}
type ExecutionEnvironment struct {
link AbstractNonNativeLink
}
func (d *DefMatcher) createFuncMap() template.FuncMap {
return map[string]any{
"assertExists": func(env *ExecutionEnvironment, names ...string) (bool, error) {
link := env.link
for _, v := range names {
_, ok := link.Values[v]
if !ok {
return false, newError("failed assertExists of ", v)
}
}
return true, nil
},
"assertIsOneOf": func(env *ExecutionEnvironment, name string, values ...string) (bool, error) {
link := env.link
actualValue, ok := link.Values[name]
if !ok {
return false, newError("failed assertIs of non-exist ", name)
}
found := false
for _, currentValue := range values {
if currentValue == actualValue {
found = true
break
}
}
if !found {
return false, newError("failed assertIsOneOf name = ", actualValue, "is not one of ", values)
}
return true, nil
},
"assertValueIsOneOf": func(value string, values ...string) (bool, error) {
actualValue := value
found := false
for _, currentValue := range values {
if currentValue == actualValue {
found = true
break
}
}
if !found {
return false, newError("failed assertIsOneOf name = ", actualValue, "is not one of ", values)
}
return true, nil
},
"tryGet": func(env *ExecutionEnvironment, names ...string) (string, error) {
link := env.link
for _, currentName := range names {
value, ok := link.Values[currentName]
if ok {
return value, nil
} else if currentName == "<default>" {
return "", nil
}
}
return "", newError("failed tryGet exists none of ", names)
},
"splitAndGetNth": func(sep string, n int, content string) (string, error) {
result := strings.Split(content, sep)
if n > len(result)-1 {
return "", newError("failed splitAndGetNth exists too short content:", content, "n = ", n, "sep =", sep)
}
if n < 0 {
n = len(result) + n
if n < 0 {
return "", newError("failed splitAndGetNth exists too short content:", content, "n = ", n, "sep =", sep)
}
}
return result[n], nil
},
"splitAndGetAfterNth": func(sep string, n int, content string) ([]string, error) {
result := strings.Split(content, sep)
if n < 0 {
n = len(result) + n
}
if n > len(result)-1 {
return []string{}, newError("failed splitAndGetNth exists too short content:", content)
}
return result[n:], nil
},
"splitAndGetBeforeNth": func(sep string, n int, content string) ([]string, error) {
result := strings.Split(content, sep)
if n < 0 {
n = len(result) + n
}
if n > len(result)-1 {
return []string{}, newError("failed splitAndGetNth exists too short content:", content)
}
return result[:n], nil
},
"jsonEncode": func(content any) (string, error) {
buf := bytes.NewBuffer(nil)
err := json.NewEncoder(buf).Encode(content)
if err != nil {
return "", newError("unable to jsonQuote ", content).Base(err)
}
return buf.String(), nil
},
"stringCutSuffix": func(suffix, content string) (string, error) {
remaining, found := strings.CutSuffix(content, suffix)
if !found {
return "", newError("suffix not found in content =", suffix, " suffix =", suffix)
}
return remaining, nil
},
"unalias": func(standardName string, names ...string) (string, error) {
if len(names) == 0 {
return "", newError("no input value specified")
}
actualInput := names[len(names)-1]
alias := names[:len(names)-1]
for _, v := range alias {
if v == actualInput {
return standardName, nil
}
}
return actualInput, nil
},
}
}
func (d *DefMatcher) init() {
d.templates = template.New("root").Funcs(d.createFuncMap())
}
func (d *DefMatcher) LoadEmbeddedDefinitions() error {
return d.LoadDefinitions(embeddedDefinitions)
}
func (d *DefMatcher) LoadDefinitions(fs fs.FS) error {
var err error
d.templates, err = d.templates.ParseFS(fs, "definitions/*.jsont")
if err != nil {
return err
}
return nil
}
func (d *DefMatcher) ExecuteNamed(link AbstractNonNativeLink, name string) ([]byte, error) {
outputBuffer := bytes.NewBuffer(nil)
env := &ExecutionEnvironment{link: link}
err := d.templates.ExecuteTemplate(outputBuffer, name, env)
if err != nil {
return nil, newError("failed to execute template").Base(err)
}
return outputBuffer.Bytes(), nil
}
func (d *DefMatcher) ExecuteAll(link AbstractNonNativeLink) ([]byte, error) {
outputBuffer := bytes.NewBuffer(nil)
for _, loadedTemplates := range d.templates.Templates() {
env := &ExecutionEnvironment{link: link}
err := loadedTemplates.Execute(outputBuffer, env)
if err != nil {
outputBuffer.Reset()
} else {
break
}
}
if outputBuffer.Len() == 0 {
return nil, newError("failed to find a working template")
}
return outputBuffer.Bytes(), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/nonnative/errors.generated.go | app/subscription/entries/nonnative/errors.generated.go | package nonnative
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/subscription/entries/nonnative/nonnative.go | app/subscription/entries/nonnative/nonnative.go | package nonnative
import (
"encoding/base64"
"encoding/json"
"net/url"
"regexp"
"strings"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func ExtractAllValuesFromBytes(bytes []byte) AbstractNonNativeLink {
link := AbstractNonNativeLink{}
link.fromBytes(bytes)
return link
}
type jsonDocument map[string]json.RawMessage
type AbstractNonNativeLink struct {
Values map[string]string
}
func (a *AbstractNonNativeLink) fromBytes(bytes []byte) {
a.Values = make(map[string]string)
content := string(bytes)
content = strings.Trim(content, " \n\t\r")
a.extractValue(content, "root")
}
func (a *AbstractNonNativeLink) extractValue(content, prefix string) {
if content == "" {
return
}
{
// check if the content is a link
match, err := regexp.Match("[a-zA-Z0-9]+:((\\/\\/)|\\?)", []byte(content))
if err != nil {
panic(err)
}
if match {
// if so, parse as link
parsedURL, err := url.Parse(content)
// if process is successful, then continue to parse every element of the link
if err == nil {
a.Values[prefix+"_!kind"] = "link"
a.extractLink(parsedURL, prefix)
return
}
}
}
{
// check if it is base64
content = strings.Trim(content, "=")
decoded, err := base64.RawStdEncoding.DecodeString(content)
if err == nil {
a.Values[prefix+"_!kind"] = "base64"
a.Values[prefix+"_!rawContent"] = string(decoded)
a.extractValue(string(decoded), prefix+"_!base64")
return
}
}
{
// check if it is base64url
content = strings.Trim(content, "=")
decoded, err := base64.RawURLEncoding.DecodeString(content)
if err == nil {
a.Values[prefix+"_!kind"] = "base64url"
a.Values[prefix+"_!rawContent"] = string(decoded)
a.extractValue(string(decoded), prefix+"_!base64")
return
}
}
{
// check if it is json
var doc jsonDocument
if err := json.Unmarshal([]byte(content), &doc); err == nil {
a.Values[prefix+"_!kind"] = "json"
a.extractJSON(&doc, prefix)
return
}
}
}
func (a *AbstractNonNativeLink) extractLink(content *url.URL, prefix string) {
a.Values[prefix+"_!link"] = content.String()
a.Values[prefix+"_!link_protocol"] = content.Scheme
a.Values[prefix+"_!link_host"] = content.Host
a.extractValue(content.Host, prefix+"_!link_host")
a.Values[prefix+"_!link_path"] = content.Path
a.Values[prefix+"_!link_query"] = content.RawQuery
a.Values[prefix+"_!link_fragment"] = content.Fragment
a.Values[prefix+"_!link_userinfo"] = content.User.String()
a.extractValue(content.User.String(), prefix+"_!link_userinfo_!value")
a.Values[prefix+"_!link_opaque"] = content.Opaque
}
func (a *AbstractNonNativeLink) extractJSON(content *jsonDocument, prefix string) {
for key, value := range *content {
switch value[0] {
case '{':
a.extractValue(string(value), prefix+"_!json_"+key)
case '"':
var unquoted string
if err := json.Unmarshal(value, &unquoted); err == nil {
a.Values[prefix+"_!json_"+key+"_!unquoted"] = unquoted
}
fallthrough
default:
a.Values[prefix+"_!json_"+key] = string(value)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/nonnative/converter.go | app/subscription/entries/nonnative/converter.go | package nonnative
import (
"io/fs"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative/nonnativeifce"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries/outbound"
"github.com/v2fly/v2ray-core/v5/app/subscription/specs"
"github.com/v2fly/v2ray-core/v5/common"
)
type nonNativeConverter struct {
matcher *DefMatcher
}
func (n *nonNativeConverter) ConvertToAbstractServerConfig(rawConfig []byte, kindHint string) (*specs.SubscriptionServerConfig, error) {
nonNativeLink := ExtractAllValuesFromBytes(rawConfig)
nonNativeLink.Values["_kind"] = kindHint
result, err := n.matcher.ExecuteAll(nonNativeLink)
if err != nil {
return nil, newError("failed to find working converting template").Base(err)
}
outboundParser := outbound.NewOutboundEntriesParser()
outboundEntries, err := outboundParser.ConvertToAbstractServerConfig(result, "")
if err != nil {
return nil, newError("failed to parse template output as outbound entries").Base(err)
}
return outboundEntries, nil
}
func NewNonNativeConverter(fs fs.FS) (entries.Converter, error) {
matcher := NewDefMatcher()
if fs == nil {
err := matcher.LoadEmbeddedDefinitions()
if err != nil {
return nil, newError("failed to load embedded definitions").Base(err)
}
} else {
err := matcher.LoadDefinitions(fs)
if err != nil {
return nil, newError("failed to load provided definitions").Base(err)
}
}
return &nonNativeConverter{matcher: matcher}, nil
}
func init() {
common.Must(entries.RegisterConverter("nonnative", common.Must2(NewNonNativeConverter(nil)).(entries.Converter)))
nonnativeifce.NewNonNativeConverterConstructor = NewNonNativeConverter
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/entries/nonnative/nonnativeifce/nonnativeifce.go | app/subscription/entries/nonnative/nonnativeifce/nonnativeifce.go | package nonnativeifce
import (
"io/fs"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries"
)
type NonNativeConverterConstructorT func(fs fs.FS) (entries.Converter, error)
var NewNonNativeConverterConstructor NonNativeConverterConstructorT
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/specs/errors.generated.go | app/subscription/specs/errors.generated.go | package specs
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/subscription/specs/abstract_spec.pb.go | app/subscription/specs/abstract_spec.pb.go | package specs
import (
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 ServerConfiguration struct {
state protoimpl.MessageState `protogen:"open.v1"`
Protocol string `protobuf:"bytes,1,opt,name=protocol,proto3" json:"protocol,omitempty"`
ProtocolSettings *anypb.Any `protobuf:"bytes,2,opt,name=protocol_settings,json=protocolSettings,proto3" json:"protocol_settings,omitempty"`
Transport string `protobuf:"bytes,3,opt,name=transport,proto3" json:"transport,omitempty"`
TransportSettings *anypb.Any `protobuf:"bytes,4,opt,name=transport_settings,json=transportSettings,proto3" json:"transport_settings,omitempty"`
Security string `protobuf:"bytes,5,opt,name=security,proto3" json:"security,omitempty"`
SecuritySettings *anypb.Any `protobuf:"bytes,6,opt,name=security_settings,json=securitySettings,proto3" json:"security_settings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfiguration) Reset() {
*x = ServerConfiguration{}
mi := &file_app_subscription_specs_abstract_spec_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfiguration) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfiguration) ProtoMessage() {}
func (x *ServerConfiguration) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_specs_abstract_spec_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 ServerConfiguration.ProtoReflect.Descriptor instead.
func (*ServerConfiguration) Descriptor() ([]byte, []int) {
return file_app_subscription_specs_abstract_spec_proto_rawDescGZIP(), []int{0}
}
func (x *ServerConfiguration) GetProtocol() string {
if x != nil {
return x.Protocol
}
return ""
}
func (x *ServerConfiguration) GetProtocolSettings() *anypb.Any {
if x != nil {
return x.ProtocolSettings
}
return nil
}
func (x *ServerConfiguration) GetTransport() string {
if x != nil {
return x.Transport
}
return ""
}
func (x *ServerConfiguration) GetTransportSettings() *anypb.Any {
if x != nil {
return x.TransportSettings
}
return nil
}
func (x *ServerConfiguration) GetSecurity() string {
if x != nil {
return x.Security
}
return ""
}
func (x *ServerConfiguration) GetSecuritySettings() *anypb.Any {
if x != nil {
return x.SecuritySettings
}
return nil
}
type SubscriptionServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Metadata map[string]string `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
Configuration *ServerConfiguration `protobuf:"bytes,3,opt,name=configuration,proto3" json:"configuration,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SubscriptionServerConfig) Reset() {
*x = SubscriptionServerConfig{}
mi := &file_app_subscription_specs_abstract_spec_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SubscriptionServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SubscriptionServerConfig) ProtoMessage() {}
func (x *SubscriptionServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_specs_abstract_spec_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 SubscriptionServerConfig.ProtoReflect.Descriptor instead.
func (*SubscriptionServerConfig) Descriptor() ([]byte, []int) {
return file_app_subscription_specs_abstract_spec_proto_rawDescGZIP(), []int{1}
}
func (x *SubscriptionServerConfig) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *SubscriptionServerConfig) GetMetadata() map[string]string {
if x != nil {
return x.Metadata
}
return nil
}
func (x *SubscriptionServerConfig) GetConfiguration() *ServerConfiguration {
if x != nil {
return x.Configuration
}
return nil
}
type SubscriptionDocument struct {
state protoimpl.MessageState `protogen:"open.v1"`
Metadata map[string]string `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
Server []*SubscriptionServerConfig `protobuf:"bytes,3,rep,name=server,proto3" json:"server,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SubscriptionDocument) Reset() {
*x = SubscriptionDocument{}
mi := &file_app_subscription_specs_abstract_spec_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SubscriptionDocument) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SubscriptionDocument) ProtoMessage() {}
func (x *SubscriptionDocument) ProtoReflect() protoreflect.Message {
mi := &file_app_subscription_specs_abstract_spec_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 SubscriptionDocument.ProtoReflect.Descriptor instead.
func (*SubscriptionDocument) Descriptor() ([]byte, []int) {
return file_app_subscription_specs_abstract_spec_proto_rawDescGZIP(), []int{2}
}
func (x *SubscriptionDocument) GetMetadata() map[string]string {
if x != nil {
return x.Metadata
}
return nil
}
func (x *SubscriptionDocument) GetServer() []*SubscriptionServerConfig {
if x != nil {
return x.Server
}
return nil
}
var File_app_subscription_specs_abstract_spec_proto protoreflect.FileDescriptor
const file_app_subscription_specs_abstract_spec_proto_rawDesc = "" +
"\n" +
"*app/subscription/specs/abstract_spec.proto\x12!v2ray.core.app.subscription.specs\x1a\x19google/protobuf/any.proto\"\xb6\x02\n" +
"\x13ServerConfiguration\x12\x1a\n" +
"\bprotocol\x18\x01 \x01(\tR\bprotocol\x12A\n" +
"\x11protocol_settings\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\x10protocolSettings\x12\x1c\n" +
"\ttransport\x18\x03 \x01(\tR\ttransport\x12C\n" +
"\x12transport_settings\x18\x04 \x01(\v2\x14.google.protobuf.AnyR\x11transportSettings\x12\x1a\n" +
"\bsecurity\x18\x05 \x01(\tR\bsecurity\x12A\n" +
"\x11security_settings\x18\x06 \x01(\v2\x14.google.protobuf.AnyR\x10securitySettings\"\xac\x02\n" +
"\x18SubscriptionServerConfig\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12e\n" +
"\bmetadata\x18\x02 \x03(\v2I.v2ray.core.app.subscription.specs.SubscriptionServerConfig.MetadataEntryR\bmetadata\x12\\\n" +
"\rconfiguration\x18\x03 \x01(\v26.v2ray.core.app.subscription.specs.ServerConfigurationR\rconfiguration\x1a;\n" +
"\rMetadataEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x8b\x02\n" +
"\x14SubscriptionDocument\x12a\n" +
"\bmetadata\x18\x02 \x03(\v2E.v2ray.core.app.subscription.specs.SubscriptionDocument.MetadataEntryR\bmetadata\x12S\n" +
"\x06server\x18\x03 \x03(\v2;.v2ray.core.app.subscription.specs.SubscriptionServerConfigR\x06server\x1a;\n" +
"\rMetadataEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x84\x01\n" +
"%com.v2ray.core.app.subscription.specsP\x01Z5github.com/v2fly/v2ray-core/v5/app/subscription/specs\xaa\x02!V2Ray.Core.App.Subscription.Specsb\x06proto3"
var (
file_app_subscription_specs_abstract_spec_proto_rawDescOnce sync.Once
file_app_subscription_specs_abstract_spec_proto_rawDescData []byte
)
func file_app_subscription_specs_abstract_spec_proto_rawDescGZIP() []byte {
file_app_subscription_specs_abstract_spec_proto_rawDescOnce.Do(func() {
file_app_subscription_specs_abstract_spec_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_subscription_specs_abstract_spec_proto_rawDesc), len(file_app_subscription_specs_abstract_spec_proto_rawDesc)))
})
return file_app_subscription_specs_abstract_spec_proto_rawDescData
}
var file_app_subscription_specs_abstract_spec_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_app_subscription_specs_abstract_spec_proto_goTypes = []any{
(*ServerConfiguration)(nil), // 0: v2ray.core.app.subscription.specs.ServerConfiguration
(*SubscriptionServerConfig)(nil), // 1: v2ray.core.app.subscription.specs.SubscriptionServerConfig
(*SubscriptionDocument)(nil), // 2: v2ray.core.app.subscription.specs.SubscriptionDocument
nil, // 3: v2ray.core.app.subscription.specs.SubscriptionServerConfig.MetadataEntry
nil, // 4: v2ray.core.app.subscription.specs.SubscriptionDocument.MetadataEntry
(*anypb.Any)(nil), // 5: google.protobuf.Any
}
var file_app_subscription_specs_abstract_spec_proto_depIdxs = []int32{
5, // 0: v2ray.core.app.subscription.specs.ServerConfiguration.protocol_settings:type_name -> google.protobuf.Any
5, // 1: v2ray.core.app.subscription.specs.ServerConfiguration.transport_settings:type_name -> google.protobuf.Any
5, // 2: v2ray.core.app.subscription.specs.ServerConfiguration.security_settings:type_name -> google.protobuf.Any
3, // 3: v2ray.core.app.subscription.specs.SubscriptionServerConfig.metadata:type_name -> v2ray.core.app.subscription.specs.SubscriptionServerConfig.MetadataEntry
0, // 4: v2ray.core.app.subscription.specs.SubscriptionServerConfig.configuration:type_name -> v2ray.core.app.subscription.specs.ServerConfiguration
4, // 5: v2ray.core.app.subscription.specs.SubscriptionDocument.metadata:type_name -> v2ray.core.app.subscription.specs.SubscriptionDocument.MetadataEntry
1, // 6: v2ray.core.app.subscription.specs.SubscriptionDocument.server:type_name -> v2ray.core.app.subscription.specs.SubscriptionServerConfig
7, // [7:7] is the sub-list for method output_type
7, // [7:7] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
}
func init() { file_app_subscription_specs_abstract_spec_proto_init() }
func file_app_subscription_specs_abstract_spec_proto_init() {
if File_app_subscription_specs_abstract_spec_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_subscription_specs_abstract_spec_proto_rawDesc), len(file_app_subscription_specs_abstract_spec_proto_rawDesc)),
NumEnums: 0,
NumMessages: 5,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_subscription_specs_abstract_spec_proto_goTypes,
DependencyIndexes: file_app_subscription_specs_abstract_spec_proto_depIdxs,
MessageInfos: file_app_subscription_specs_abstract_spec_proto_msgTypes,
}.Build()
File_app_subscription_specs_abstract_spec_proto = out.File
file_app_subscription_specs_abstract_spec_proto_goTypes = nil
file_app_subscription_specs_abstract_spec_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/subscription/specs/outbound_parser.go | app/subscription/specs/outbound_parser.go | package specs
import (
"bytes"
"context"
"encoding/json"
"github.com/golang/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common/registry"
"github.com/v2fly/v2ray-core/v5/common/serial"
)
func NewOutboundParser() *OutboundParser {
return &OutboundParser{}
}
type OutboundParser struct{}
func (p *OutboundParser) ParseOutboundConfig(rawConfig []byte) (*OutboundConfig, error) {
skeleton := &OutboundConfig{}
decoder := json.NewDecoder(bytes.NewReader(rawConfig))
decoder.DisallowUnknownFields()
err := decoder.Decode(skeleton)
if err != nil {
return nil, newError("failed to parse outbound config skeleton").Base(err)
}
return skeleton, nil
}
func (p *OutboundParser) toAbstractServerSpec(config *OutboundConfig) (*ServerConfiguration, error) {
serverConfig := &ServerConfiguration{}
serverConfig.Protocol = config.Protocol
{
protocolSettings, err := loadHeterogeneousConfigFromRawJSONRestricted("outbound", config.Protocol, config.Settings)
if err != nil {
return nil, newError("failed to parse protocol settings").Base(err)
}
serverConfig.ProtocolSettings = serial.ToTypedMessage(protocolSettings)
}
if config.StreamSetting != nil {
if config.StreamSetting.Transport == "" {
config.StreamSetting.Transport = "tcp"
}
if config.StreamSetting.Security == "" {
config.StreamSetting.Security = "none"
}
{
serverConfig.Transport = config.StreamSetting.Transport
transportSettings, err := loadHeterogeneousConfigFromRawJSONRestricted(
"transport", config.StreamSetting.Transport, config.StreamSetting.TransportSettings)
if err != nil {
return nil, newError("failed to parse transport settings").Base(err)
}
serverConfig.TransportSettings = serial.ToTypedMessage(transportSettings)
}
if config.StreamSetting.Security != "none" {
securitySettings, err := loadHeterogeneousConfigFromRawJSONRestricted(
"security", config.StreamSetting.Security, config.StreamSetting.SecuritySettings)
if err != nil {
return nil, newError("failed to parse security settings").Base(err)
}
serverConfig.SecuritySettings = serial.ToTypedMessage(securitySettings)
serverConfig.Security = serial.V2Type(serverConfig.SecuritySettings)
}
}
return serverConfig, nil
}
func (p *OutboundParser) ToSubscriptionServerConfig(config *OutboundConfig) (*SubscriptionServerConfig, error) {
serverSpec, err := p.toAbstractServerSpec(config)
if err != nil {
return nil, newError("unable to parse server specification").Base(err)
}
return &SubscriptionServerConfig{
Configuration: serverSpec,
Metadata: config.Metadata,
}, nil
}
func loadHeterogeneousConfigFromRawJSONRestricted(interfaceType, name string, rawJSON json.RawMessage) (proto.Message, error) {
ctx := context.TODO()
ctx = registry.CreateRestrictedModeContext(ctx)
if len(rawJSON) == 0 {
rawJSON = []byte("{}")
}
return registry.LoadImplementationByAlias(ctx, interfaceType, name, []byte(rawJSON))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/subscription/specs/specs.go | app/subscription/specs/specs.go | package specs
//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/subscription/specs/skeleton.go | app/subscription/specs/skeleton.go | package specs
import (
"encoding/json"
)
type OutboundConfig struct {
Protocol string `json:"protocol"`
Settings json.RawMessage `json:"settings"`
StreamSetting *StreamConfig `json:"streamSettings"`
Metadata map[string]string `json:"metadata"`
}
type StreamConfig struct {
Transport string `json:"transport"`
TransportSettings json.RawMessage `json:"transportSettings"`
Security string `json:"security"`
SecuritySettings json.RawMessage `json:"securitySettings"`
}
| 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.go | app/dns/nameserver_doh.go | //go:build !confonly
// +build !confonly
package dns
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/dns/dnsmessage"
"github.com/v2fly/v2ray-core/v5/common"
"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"
)
// DoHNameServer implemented DNS over HTTPS (RFC8484) Wire Format,
// which is compatible with traditional dns over udp(RFC1035),
// thus most of the DOH implementation is copied from udpns.go
type DoHNameServer struct {
sync.RWMutex
ips map[string]record
pub *pubsub.Service
cleanup *task.Periodic
httpClient *http.Client
dohURL string
name string
}
// NewDoHNameServer creates DOH server object for remote resolving.
func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher) (*DoHNameServer, error) {
newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
s := baseDOHNameServer(url, "DOH")
// Dispatched connection will be closed (interrupted) after each request
// This makes DOH inefficient without a keep-alived connection
// See: core/app/proxyman/outbound/handler.go:113
// Using mux (https request wrapped in a stream layer) improves the situation.
// Recommend to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
// a normal network eg. the server side of v2ray
tr := &http.Transport{
MaxIdleConns: 30,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 30 * time.Second,
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return nil, err
}
return net.NewConnection(
net.ConnectionInputMulti(link.Writer),
net.ConnectionOutputMulti(link.Reader),
), nil
},
}
dispatchedClient := &http.Client{
Transport: tr,
Timeout: 60 * time.Second,
}
s.httpClient = dispatchedClient
return s, nil
}
// NewDoHLocalNameServer creates DOH client object for local resolving
func NewDoHLocalNameServer(url *url.URL) *DoHNameServer {
url.Scheme = "https"
s := baseDOHNameServer(url, "DOHL")
tr := &http.Transport{
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
conn, err := internet.DialSystem(ctx, dest, nil)
if err != nil {
return nil, err
}
return conn, nil
},
}
s.httpClient = &http.Client{
Timeout: time.Second * 180,
Transport: tr,
}
newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog()
return s
}
func baseDOHNameServer(url *url.URL, prefix string) *DoHNameServer {
s := &DoHNameServer{
ips: make(map[string]record),
pub: pubsub.NewService(),
name: prefix + "//" + url.Host,
dohURL: url.String(),
}
s.cleanup = &task.Periodic{
Interval: time.Minute,
Execute: s.Cleanup,
}
return s
}
// Name implements Server.
func (s *DoHNameServer) Name() string {
return s.name
}
// Cleanup clears expired items from cache
func (s *DoHNameServer) 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 *DoHNameServer) 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 *DoHNameServer) newReqID() uint16 {
return 0
}
func (s *DoHNameServer) 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: "tls",
SkipDNSResolve: true,
})
// forced to use mux for DOH
dnsCtx = session.ContextWithMuxPrefered(dnsCtx, 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
}
resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
if err != nil {
newError("failed to retrieve response").Base(err).AtError().WriteToLog()
return
}
rec, err := parseResponse(resp)
if err != nil {
newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
return
}
s.updateIP(r, rec)
}(req)
}
}
func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
body := bytes.NewBuffer(b)
req, err := http.NewRequest("POST", s.dohURL, body)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/dns-message")
req.Header.Add("Content-Type", "application/dns-message")
resp, err := s.httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(io.Discard, resp.Body) // flush resp.Body so that the conn is reusable
return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
func (s *DoHNameServer) 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 *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { // nolint: dupl
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/dns_test.go | app/dns/dns_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/policy"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/outbound"
"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/serial"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
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"
)
type staticHandler struct{}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg)
ans.Id = r.Id
var clientIP net.IP
opt := r.IsEdns0()
if opt != nil {
for _, o := range opt.Option {
if o.Option() == dns.EDNS0SUBNET {
subnet := o.(*dns.EDNS0_SUBNET)
clientIP = subnet.Address
}
}
}
for _, q := range r.Question {
switch {
case q.Name == "google.com." && q.Qtype == dns.TypeA:
if clientIP == nil {
rr, _ := dns.NewRR("google.com. IN A 8.8.8.8")
ans.Answer = append(ans.Answer, rr)
} else {
rr, _ := dns.NewRR("google.com. IN A 8.8.4.4")
ans.Answer = append(ans.Answer, rr)
}
case q.Name == "api.google.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("api.google.com. IN A 8.8.7.7")
ans.Answer = append(ans.Answer, rr)
case q.Name == "v2.api.google.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("v2.api.google.com. IN A 8.8.7.8")
ans.Answer = append(ans.Answer, rr)
case q.Name == "facebook.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("facebook.com. IN A 9.9.9.9")
ans.Answer = append(ans.Answer, rr)
case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeA:
rr, err := dns.NewRR("ipv6.google.com. IN A 8.8.8.7")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeAAAA:
rr, err := dns.NewRR("ipv6.google.com. IN AAAA 2001:4860:4860::8888")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
case q.Name == "notexist.google.com." && q.Qtype == dns.TypeAAAA:
ans.MsgHdr.Rcode = dns.RcodeNameError
case q.Name == "hostname." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
case q.Name == "hostname.local." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname.local. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
case q.Name == "hostname.localdomain." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname.localdomain. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
case q.Name == "localhost." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost. IN A 127.0.0.2")
ans.Answer = append(ans.Answer, rr)
case q.Name == "localhost-a." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost-a. IN A 127.0.0.3")
ans.Answer = append(ans.Answer, rr)
case q.Name == "localhost-b." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost-b. IN A 127.0.0.4")
ans.Answer = append(ans.Answer, rr)
case q.Name == "Mijia\\ Cloud." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("Mijia\\ Cloud. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
case q.Name == "xn--vi8h.ws." /* 🍕.ws */ && q.Qtype == dns.TypeA:
rr, err := dns.NewRR("xn--vi8h.ws. IN A 208.100.42.200")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
case q.Name == "xn--l8jaaa.com." /* ああああ.com */ && q.Qtype == dns.TypeA:
rr, err := dns.NewRR("xn--l8jaaa.com. IN AAAA a:a:a:a::aaaa")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
}
}
w.WriteMsg(ans)
}
func TestUDPServerSubnet(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
ClientIp: []byte{7, 8, 9, 10},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
ips, err := client.LookupIP("google.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{8, 8, 4, 4}}); r != "" {
t.Fatal(r)
}
}
func TestUDPServer(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&policy.Config{}),
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
v, err := core.New(config)
common.Must(err)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
{
ips, err := client.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(r)
}
}
{
ips, err := client.LookupIP("facebook.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{9, 9, 9, 9}}); r != "" {
t.Fatal(r)
}
}
{
_, err := client.LookupIP("notexist.google.com")
if err == nil {
t.Fatal("nil error")
}
if r := feature_dns.RCodeFromError(err); r != uint16(dns.RcodeNameError) {
t.Fatal("expected NameError, but got ", r)
}
}
{
clientv6 := client.(feature_dns.IPv6Lookup)
ips, err := clientv6.LookupIPv6("ipv4only.google.com")
if err != feature_dns.ErrEmptyResponse {
t.Fatal("error: ", err)
}
if len(ips) != 0 {
t.Fatal("ips: ", ips)
}
}
{
ips, err := client.LookupIP(common.Must2(strmatcher.ToDomain("🍕.ws")).(string))
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{208, 100, 42, 200}}); r != "" {
t.Fatal(r)
}
}
{
ips, err := client.LookupIP(common.Must2(strmatcher.ToDomain("ああああ.com")).(string))
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{0, 0xa, 0, 0xa, 0, 0xa, 0, 0xa, 0, 0, 0, 0, 0, 0, 0xaa, 0xaa}}); r != "" {
t.Fatal(r)
}
}
dnsServer.Shutdown()
{
ips, err := client.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(r)
}
}
}
func TestPrioritizedDomain(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 9999, /* unreachable */
},
},
NameServer: []*NameServer{
{
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_Full,
Domain: "google.com",
},
},
},
},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
startTime := time.Now()
{
ips, err := client.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(r)
}
}
endTime := time.Now()
if startTime.After(endTime.Add(time.Second * 2)) {
t.Error("DNS query doesn't finish in 2 seconds.")
}
}
func TestUDPServerIPv6(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&policy.Config{}),
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
v, err := core.New(config)
common.Must(err)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
client6 := client.(feature_dns.IPv6Lookup)
{
ips, err := client6.LookupIPv6("ipv6.google.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{32, 1, 72, 96, 72, 96, 0, 0, 0, 0, 0, 0, 0, 0, 136, 136}}); r != "" {
t.Fatal(r)
}
}
}
func TestStaticHostDomain(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
StaticHosts: []*HostMapping{
{
Type: DomainMatchingType_Full,
Domain: "example.com",
ProxiedDomain: "google.com",
},
},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
{
ips, err := client.LookupIP("example.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{8, 8, 8, 8}}); r != "" {
t.Fatal(r)
}
}
dnsServer.Shutdown()
}
func TestIPMatch(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{
// private dns, not match
{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
Geoip: []*routercommon.GeoIP{
{
CountryCode: "local",
Cidr: []*routercommon.CIDR{
{
// inner ip, will not match
Ip: []byte{192, 168, 11, 1},
Prefix: 32,
},
},
},
},
},
// second dns, match ip
{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
Geoip: []*routercommon.GeoIP{
{
CountryCode: "test",
Cidr: []*routercommon.CIDR{
{
Ip: []byte{8, 8, 8, 8},
Prefix: 32,
},
},
},
{
CountryCode: "test",
Cidr: []*routercommon.CIDR{
{
Ip: []byte{8, 8, 8, 4},
Prefix: 32,
},
},
},
},
},
},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
startTime := time.Now()
{
ips, err := client.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(r)
}
}
endTime := time.Now()
if startTime.After(endTime.Add(time.Second * 2)) {
t.Error("DNS query doesn't finish in 2 seconds.")
}
}
func TestLocalDomain(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 9999, /* unreachable */
},
},
NameServer: []*NameServer{
{
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{
// Equivalent of dotless:localhost
{Type: DomainMatchingType_Regex, Domain: "^[^.]*localhost[^.]*$"},
},
Geoip: []*routercommon.GeoIP{
{ // Will match localhost, localhost-a and localhost-b,
CountryCode: "local",
Cidr: []*routercommon.CIDR{
{Ip: []byte{127, 0, 0, 2}, Prefix: 32},
{Ip: []byte{127, 0, 0, 3}, Prefix: 32},
{Ip: []byte{127, 0, 0, 4}, Prefix: 32},
},
},
},
},
{
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{
// Equivalent of dotless: and domain:local
{Type: DomainMatchingType_Regex, Domain: "^[^.]*$"},
{Type: DomainMatchingType_Subdomain, Domain: "local"},
{Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
},
},
},
StaticHosts: []*HostMapping{
{
Type: DomainMatchingType_Full,
Domain: "hostnamestatic",
Ip: [][]byte{{127, 0, 0, 53}},
},
{
Type: DomainMatchingType_Full,
Domain: "hostnamealias",
ProxiedDomain: "hostname.localdomain",
},
},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
startTime := time.Now()
{ // Will match dotless:
ips, err := client.LookupIP("hostname")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 1}}); r != "" {
t.Fatal(r)
}
}
{ // Will match domain:local
ips, err := client.LookupIP("hostname.local")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 1}}); r != "" {
t.Fatal(r)
}
}
{ // Will match static ip
ips, err := client.LookupIP("hostnamestatic")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 53}}); r != "" {
t.Fatal(r)
}
}
{ // Will match domain replacing
ips, err := client.LookupIP("hostnamealias")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 1}}); r != "" {
t.Fatal(r)
}
}
{ // Will match dotless:localhost, but not expectIPs: 127.0.0.2, 127.0.0.3, then matches at dotless:
ips, err := client.LookupIP("localhost")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 2}}); r != "" {
t.Fatal(r)
}
}
{ // Will match dotless:localhost, and expectIPs: 127.0.0.2, 127.0.0.3
ips, err := client.LookupIP("localhost-a")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 3}}); r != "" {
t.Fatal(r)
}
}
{ // Will match dotless:localhost, and expectIPs: 127.0.0.2, 127.0.0.3
ips, err := client.LookupIP("localhost-b")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 4}}); r != "" {
t.Fatal(r)
}
}
{ // Will match dotless:
ips, err := client.LookupIP("Mijia Cloud")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{127, 0, 0, 1}}); r != "" {
t.Fatal(r)
}
}
endTime := time.Now()
if startTime.After(endTime.Add(time.Second * 2)) {
t.Error("DNS query doesn't finish in 2 seconds.")
}
}
func TestMultiMatchPrioritizedDomain(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{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 9999, /* unreachable */
},
},
NameServer: []*NameServer{
{
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",
},
},
Geoip: []*routercommon.GeoIP{
{ // Will only match 8.8.8.8 and 8.8.4.4
Cidr: []*routercommon.CIDR{
{Ip: []byte{8, 8, 8, 8}, Prefix: 32},
{Ip: []byte{8, 8, 4, 4}, Prefix: 32},
},
},
},
},
{
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",
},
},
Geoip: []*routercommon.GeoIP{
{ // Will match 8.8.8.8 and 8.8.8.7, etc
Cidr: []*routercommon.CIDR{
{Ip: []byte{8, 8, 8, 7}, Prefix: 24},
},
},
},
},
{
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: "api.google.com",
},
},
Geoip: []*routercommon.GeoIP{
{ // Will only match 8.8.7.7 (api.google.com)
Cidr: []*routercommon.CIDR{
{Ip: []byte{8, 8, 7, 7}, Prefix: 32},
},
},
},
},
{
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_Full,
Domain: "v2.api.google.com",
},
},
Geoip: []*routercommon.GeoIP{
{ // Will only match 8.8.7.8 (v2.api.google.com)
Cidr: []*routercommon.CIDR{
{Ip: []byte{8, 8, 7, 8}, Prefix: 32},
},
},
},
},
},
}),
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)
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
startTime := time.Now()
{ // Will match server 1,2 and server 1 returns expected ip
ips, err := client.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(r)
}
}
{ // Will match server 1,2 and server 1 returns unexpected ip, then server 2 returns expected one
clientv4 := client.(feature_dns.IPv4Lookup)
ips, err := clientv4.LookupIPv4("ipv6.google.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{8, 8, 8, 7}}); r != "" {
t.Fatal(r)
}
}
{ // Will match server 3,1,2 and server 3 returns expected one
ips, err := client.LookupIP("api.google.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{8, 8, 7, 7}}); r != "" {
t.Fatal(r)
}
}
{ // Will match server 4,3,1,2 and server 4 returns expected one
ips, err := client.LookupIP("v2.api.google.com")
if err != nil {
t.Fatal("unexpected error: ", err)
}
if r := cmp.Diff(ips, []net.IP{{8, 8, 7, 8}}); r != "" {
t.Fatal(r)
}
}
endTime := time.Now()
if startTime.After(endTime.Add(time.Second * 2)) {
t.Error("DNS query doesn't finish in 2 seconds.")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/dnscommon_test.go | app/dns/dnscommon_test.go | package dns
import (
"math/rand"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/miekg/dns"
"golang.org/x/net/dns/dnsmessage"
"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 Test_parseResponse(t *testing.T) {
var p [][]byte
ans := new(dns.Msg)
ans.Id = 0
p = append(p, common.Must2(ans.Pack()).([]byte))
p = append(p, []byte{})
ans = new(dns.Msg)
ans.Id = 1
ans.Answer = append(ans.Answer,
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN A 8.8.8.8")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN A 8.8.4.4")).(dns.RR),
)
p = append(p, common.Must2(ans.Pack()).([]byte))
ans = new(dns.Msg)
ans.Id = 2
ans.Answer = append(ans.Answer,
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN CNAME test.google.com")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN AAAA 2001::123:8888")).(dns.RR),
common.Must2(dns.NewRR("google.com. IN AAAA 2001::123:8844")).(dns.RR),
)
p = append(p, common.Must2(ans.Pack()).([]byte))
tests := []struct {
name string
want *IPRecord
wantErr bool
}{
{
"empty",
&IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess},
false,
},
{
"error",
nil,
true,
},
{
"a record",
&IPRecord{
1,
[]net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")},
time.Time{},
dnsmessage.RCodeSuccess,
},
false,
},
{
"aaaa record",
&IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess},
false,
},
}
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseResponse(p[i])
if (err != nil) != tt.wantErr {
t.Errorf("handleResponse() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != nil {
// reset the time
got.Expire = time.Time{}
}
if cmp.Diff(got, tt.want) != "" {
t.Errorf("%v", cmp.Diff(got, tt.want))
// t.Errorf("handleResponse() = %#v, want %#v", got, tt.want)
}
})
}
}
func Test_buildReqMsgs(t *testing.T) {
stubID := func() uint16 {
return uint16(rand.Uint32())
}
type args struct {
domain string
option dns_feature.IPOption
reqOpts *dnsmessage.Resource
}
tests := []struct {
name string
args args
want int
}{
{"dual stack", args{"test.com", dns_feature.IPOption{
IPv4Enable: true,
IPv6Enable: true,
FakeEnable: false,
}, nil}, 2},
{"ipv4 only", args{"test.com", dns_feature.IPOption{
IPv4Enable: true,
IPv6Enable: false,
FakeEnable: false,
}, nil}, 1},
{"ipv6 only", args{"test.com", dns_feature.IPOption{
IPv4Enable: false,
IPv6Enable: true,
FakeEnable: false,
}, nil}, 1},
{"none/error", args{"test.com", dns_feature.IPOption{
IPv4Enable: false,
IPv6Enable: false,
FakeEnable: false,
}, nil}, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := buildReqMsgs(tt.args.domain, tt.args.option, stubID, tt.args.reqOpts); !(len(got) == tt.want) {
t.Errorf("buildReqMsgs() = %v, want %v", got, tt.want)
}
})
}
}
func Test_genEDNS0Options(t *testing.T) {
type args struct {
clientIP net.IP
}
tests := []struct {
name string
args args
want *dnsmessage.Resource
}{
// TODO: Add test cases.
{"ipv4", args{net.ParseIP("4.3.2.1")}, nil},
{"ipv6", args{net.ParseIP("2001::4321")}, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := genEDNS0Options(tt.args.clientIP); got == nil {
t.Errorf("genEDNS0Options() = %v, want %v", got, tt.want)
}
})
}
}
func TestFqdn(t *testing.T) {
type args struct {
domain string
}
tests := []struct {
name string
args args
want string
}{
{"with fqdn", args{"www.v2fly.org."}, "www.v2fly.org."},
{"without fqdn", args{"www.v2fly.org"}, "www.v2fly.org."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Fqdn(tt.args.domain); got != tt.want {
t.Errorf("Fqdn() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/errors.generated.go | app/dns/errors.generated.go | package dns
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/nameserver.go | app/dns/nameserver.go | package dns
import (
"context"
"net/url"
"strings"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dns/fakedns"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/routing"
)
// Server is the interface for Name Server.
type Server interface {
// Name of the Client.
Name() string
// QueryIP sends IP queries to its configured server.
QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, disableCache bool) ([]net.IP, error)
}
// Client is the interface for DNS client.
type Client struct {
server Server
clientIP net.IP
tag string
queryStrategy dns.IPOption
cacheStrategy CacheStrategy
fallbackStrategy FallbackStrategy
domains []string
expectIPs []*router.GeoIPMatcher
fakeDNS Server
}
var errExpectedIPNonMatch = errors.New("expectIPs not match")
// NewServer creates a name server object according to the network destination url.
func NewServer(ctx context.Context, dest net.Destination, onCreated func(Server) error) error {
onCreatedWithError := func(server Server, err error) error {
if err != nil {
return err
}
return onCreated(server)
}
if address := dest.Address; address.Family().IsDomain() {
u, err := url.Parse(address.Domain())
if err != nil {
return err
}
switch {
case strings.EqualFold(u.String(), "localhost"):
return onCreated(NewLocalNameServer())
case strings.EqualFold(u.String(), "fakedns"):
return core.RequireFeatures(ctx, func(fakedns dns.FakeDNSEngine) error { return onCreated(NewFakeDNSServer(fakedns)) })
case strings.EqualFold(u.Scheme, "https"): // DOH Remote mode
return core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error { return onCreatedWithError(NewDoHNameServer(u, dispatcher)) })
case strings.EqualFold(u.Scheme, "https+local"): // DOH Local mode
return onCreated(NewDoHLocalNameServer(u))
case strings.EqualFold(u.Scheme, "tcp"): // DNS-over-TCP Remote mode
return core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error { return onCreatedWithError(NewTCPNameServer(u, dispatcher)) })
case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
return onCreatedWithError(NewTCPLocalNameServer(u))
case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
return onCreatedWithError(NewQUICNameServer(u))
}
}
if dest.Network == net.Network_Unknown {
dest.Network = net.Network_UDP
}
if dest.Network == net.Network_UDP { // UDP classic DNS mode
return core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error { return onCreated(NewClassicNameServer(dest, dispatcher)) })
}
return newError("No available name server could be created from ", dest).AtWarning()
}
// NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
func NewClient(ctx context.Context, ns *NameServer, dns *Config) (*Client, error) {
client := &Client{}
// Create DNS server instance
err := NewServer(ctx, ns.Address.AsDestination(), func(server Server) error {
client.server = server
return nil
})
if err != nil {
return nil, err
}
// Initialize fields with default values
if len(ns.Tag) == 0 {
ns.Tag = dns.Tag
if len(ns.Tag) == 0 {
ns.Tag = generateRandomTag()
}
}
if len(ns.ClientIp) == 0 {
ns.ClientIp = dns.ClientIp
}
if ns.QueryStrategy == nil {
ns.QueryStrategy = &dns.QueryStrategy
}
if ns.CacheStrategy == nil {
ns.CacheStrategy = new(CacheStrategy)
switch {
case dns.CacheStrategy != CacheStrategy_CacheEnabled:
*ns.CacheStrategy = dns.CacheStrategy
case dns.DisableCache:
features.PrintDeprecatedFeatureWarning("DNS disableCache settings")
*ns.CacheStrategy = CacheStrategy_CacheDisabled
}
}
if ns.FallbackStrategy == nil {
ns.FallbackStrategy = new(FallbackStrategy)
switch {
case ns.SkipFallback:
features.PrintDeprecatedFeatureWarning("DNS server skipFallback settings")
*ns.FallbackStrategy = FallbackStrategy_Disabled
case dns.FallbackStrategy != FallbackStrategy_Enabled:
*ns.FallbackStrategy = dns.FallbackStrategy
case dns.DisableFallback:
features.PrintDeprecatedFeatureWarning("DNS disableFallback settings")
*ns.FallbackStrategy = FallbackStrategy_Disabled
case dns.DisableFallbackIfMatch:
features.PrintDeprecatedFeatureWarning("DNS disableFallbackIfMatch settings")
*ns.FallbackStrategy = FallbackStrategy_DisabledIfAnyMatch
}
}
if (ns.FakeDns != nil && len(ns.FakeDns.Pools) == 0) || // Use globally configured fake ip pool if: 1. `fakedns` config is set, but empty(represents { "fakedns": true } in JSON settings);
ns.FakeDns == nil && strings.EqualFold(ns.Address.Address.GetDomain(), "fakedns") { // 2. `fakedns` config not set, but server address is `fakedns`(represents { "address": "fakedns" } in JSON settings).
if dns.FakeDns != nil {
ns.FakeDns = dns.FakeDns
} else {
ns.FakeDns = &fakedns.FakeDnsPoolMulti{}
queryStrategy := toIPOption(*ns.QueryStrategy)
if queryStrategy.IPv4Enable {
ns.FakeDns.Pools = append(ns.FakeDns.Pools, &fakedns.FakeDnsPool{
IpPool: "198.18.0.0/15",
LruSize: 65535,
})
}
if queryStrategy.IPv6Enable {
ns.FakeDns.Pools = append(ns.FakeDns.Pools, &fakedns.FakeDnsPool{
IpPool: "fc00::/18",
LruSize: 65535,
})
}
}
}
// Priotize local domains with specific TLDs or without any dot to local DNS
if strings.EqualFold(ns.Address.Address.GetDomain(), "localhost") {
ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
}
if len(ns.ClientIp) > 0 {
newError("DNS: client ", ns.Address.Address.AsAddress(), " uses clientIP ", net.IP(ns.ClientIp).String()).AtInfo().WriteToLog()
}
client.clientIP = ns.ClientIp
client.tag = ns.Tag
client.queryStrategy = toIPOption(*ns.QueryStrategy)
client.cacheStrategy = *ns.CacheStrategy
client.fallbackStrategy = *ns.FallbackStrategy
return client, nil
}
// Name returns the server name the client manages.
func (c *Client) Name() string {
return c.server.Name()
}
// QueryIP send DNS query to the name server with the client's IP and IP options.
func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption) ([]net.IP, error) {
queryOption := option.With(c.queryStrategy)
if !queryOption.IsValid() {
newError(c.server.Name(), " returns empty answer: ", domain, ". ", toReqTypes(option)).AtInfo().WriteToLog()
return nil, dns.ErrEmptyResponse
}
server := c.server
if queryOption.FakeEnable && c.fakeDNS != nil {
server = c.fakeDNS
}
disableCache := c.cacheStrategy == CacheStrategy_CacheDisabled
ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: c.tag})
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
ips, err := server.QueryIP(ctx, domain, c.clientIP, queryOption, disableCache)
cancel()
if err != nil || queryOption.FakeEnable {
return ips, err
}
return c.MatchExpectedIPs(domain, ips)
}
// MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
if len(c.expectIPs) == 0 {
return ips, nil
}
newIps := []net.IP{}
for _, ip := range ips {
for _, matcher := range c.expectIPs {
if matcher.Match(ip) {
newIps = append(newIps, ip)
break
}
}
}
if len(newIps) == 0 {
return nil, errExpectedIPNonMatch
}
newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
return newIps, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/hosts.go | app/dns/hosts.go | package dns
import (
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/dns"
)
// StaticHosts represents static domain-ip mapping in DNS server.
type StaticHosts struct {
ips [][]net.Address
matchers *strmatcher.LinearIndexMatcher
}
// NewStaticHosts creates a new StaticHosts instance.
func NewStaticHosts(hosts []*HostMapping, legacy map[string]*net.IPOrDomain) (*StaticHosts, error) {
g := new(strmatcher.LinearIndexMatcher)
sh := &StaticHosts{
ips: make([][]net.Address, len(hosts)+len(legacy)+16),
matchers: g,
}
if legacy != nil {
features.PrintDeprecatedFeatureWarning("simple host mapping")
for domain, ip := range legacy {
matcher, err := strmatcher.Full.New(domain)
common.Must(err)
id := g.Add(matcher)
address := ip.AsAddress()
if address.Family().IsDomain() {
return nil, newError("invalid domain address in static hosts: ", address.Domain()).AtWarning()
}
sh.ips[id] = []net.Address{address}
}
}
for _, mapping := range hosts {
matcher, err := toStrMatcher(mapping.Type, mapping.Domain)
if err != nil {
return nil, newError("failed to create domain matcher").Base(err)
}
id := g.Add(matcher)
ips := make([]net.Address, 0, len(mapping.Ip)+1)
switch {
case len(mapping.ProxiedDomain) > 0:
ips = append(ips, net.DomainAddress(mapping.ProxiedDomain))
case len(mapping.Ip) > 0:
for _, ip := range mapping.Ip {
addr := net.IPAddress(ip)
if addr == nil {
return nil, newError("invalid IP address in static hosts: ", ip).AtWarning()
}
ips = append(ips, addr)
}
default:
return nil, newError("neither IP address nor proxied domain specified for domain: ", mapping.Domain).AtWarning()
}
sh.ips[id] = ips
}
return sh, nil
}
func (h *StaticHosts) lookupInternal(domain string) []net.Address {
var ips []net.Address
for _, id := range h.matchers.Match(domain) {
ips = append(ips, h.ips[id]...)
}
return ips
}
func (h *StaticHosts) lookup(domain string, option dns.IPOption, maxDepth int) []net.Address {
switch addrs := h.lookupInternal(domain); {
case len(addrs) == 0: // Not recorded in static hosts, return nil
return nil
case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Try to unwrap domain
newError("found replaced domain: ", domain, " -> ", addrs[0].Domain(), ". Try to unwrap it").AtDebug().WriteToLog()
if maxDepth > 0 {
unwrapped := h.lookup(addrs[0].Domain(), option, maxDepth-1)
if unwrapped != nil {
return unwrapped
}
}
return addrs
default: // IP record found, return a non-nil IP array
return filterIP(addrs, option)
}
}
// Lookup returns IP addresses or proxied domain for the given domain, if exists in this StaticHosts.
func (h *StaticHosts) Lookup(domain string, option dns.IPOption) []net.Address {
return h.lookup(domain, option, 5)
}
| 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_test.go | app/dns/nameserver_local_test.go | package dns_test
import (
"context"
"testing"
"time"
. "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 TestLocalNameServer(t *testing.T) {
s := NewLocalNameServer()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP{}, dns.IPOption{
IPv4Enable: true,
IPv6Enable: true,
}, false)
cancel()
common.Must(err)
if len(ips) == 0 {
t.Error("expect some ips, but got 0")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dns/config.go | app/dns/config.go | //go:build !confonly
// +build !confonly
package dns
import (
"golang.org/x/net/dns/dnsmessage"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/features/dns"
)
var typeMap = map[DomainMatchingType]strmatcher.Type{
DomainMatchingType_Full: strmatcher.Full,
DomainMatchingType_Subdomain: strmatcher.Domain,
DomainMatchingType_Keyword: strmatcher.Substr,
DomainMatchingType_Regex: strmatcher.Regex,
}
// References:
// https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml
// https://unix.stackexchange.com/questions/92441/whats-the-difference-between-local-home-and-lan
var localTLDsAndDotlessDomains = []*NameServer_PriorityDomain{
{Type: DomainMatchingType_Regex, Domain: "^[^.]+$"}, // This will only match domains without any dot
{Type: DomainMatchingType_Subdomain, Domain: "local"},
{Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
{Type: DomainMatchingType_Subdomain, Domain: "localhost"},
{Type: DomainMatchingType_Subdomain, Domain: "lan"},
{Type: DomainMatchingType_Subdomain, Domain: "home.arpa"},
{Type: DomainMatchingType_Subdomain, Domain: "example"},
{Type: DomainMatchingType_Subdomain, Domain: "invalid"},
{Type: DomainMatchingType_Subdomain, Domain: "test"},
}
var localTLDsAndDotlessDomainsRule = &NameServer_OriginalRule{
Rule: "geosite:private",
Size: uint32(len(localTLDsAndDotlessDomains)),
}
func toStrMatcher(t DomainMatchingType, domain string) (strmatcher.Matcher, error) {
strMType, f := typeMap[t]
if !f {
return nil, newError("unknown mapping type", t).AtWarning()
}
matcher, err := strMType.New(domain)
if err != nil {
return nil, newError("failed to create str matcher").Base(err)
}
return matcher, nil
}
func toNetIP(addrs []net.Address) ([]net.IP, error) {
ips := make([]net.IP, 0, len(addrs))
for _, addr := range addrs {
if addr.Family().IsIP() {
ips = append(ips, addr.IP())
} else {
return nil, newError("Failed to convert address", addr, "to Net IP.").AtWarning()
}
}
return ips, nil
}
func toIPOption(s QueryStrategy) dns.IPOption {
return dns.IPOption{
IPv4Enable: s == QueryStrategy_USE_IP || s == QueryStrategy_USE_IP4,
IPv6Enable: s == QueryStrategy_USE_IP || s == QueryStrategy_USE_IP6,
FakeEnable: false,
}
}
func toReqTypes(option dns.IPOption) []dnsmessage.Type {
var reqTypes []dnsmessage.Type
if option.IPv4Enable {
reqTypes = append(reqTypes, dnsmessage.TypeA)
}
if option.IPv6Enable {
reqTypes = append(reqTypes, dnsmessage.TypeAAAA)
}
return reqTypes
}
func generateRandomTag() string {
id := uuid.New()
return "v2ray.system." + id.String()
}
| 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_test.go | app/dns/nameserver_tcp_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 TestTCPLocalNameServer(t *testing.T) {
url, err := url.Parse("tcp+local://8.8.8.8")
common.Must(err)
s, err := NewTCPLocalNameServer(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 TestTCPLocalNameServerWithCache(t *testing.T) {
url, err := url.Parse("tcp+local://8.8.8.8")
common.Must(err)
s, err := NewTCPLocalNameServer(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/dns.go | app/dns/dns.go | //go:build !confonly
// +build !confonly
// Package dns is an implementation of core.DNS feature.
package dns
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"fmt"
"strings"
"sync"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dns/fakedns"
"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/errors"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/platform"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon"
"github.com/v2fly/v2ray-core/v5/infra/conf/geodata"
)
// DNS is a DNS rely server.
type DNS struct {
sync.Mutex
hosts *StaticHosts
clients []*Client
ctx context.Context
clientTags map[string]bool
fakeDNSEngine *FakeDNSEngine
domainMatcher strmatcher.IndexMatcher
matcherInfos []DomainMatcherInfo
}
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
type DomainMatcherInfo struct {
clientIdx uint16
domainRuleIdx uint16
}
// New creates a new DNS server with given configuration.
func New(ctx context.Context, config *Config) (*DNS, error) {
// Create static hosts
hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
if err != nil {
return nil, newError("failed to create hosts").Base(err)
}
// Create name servers from legacy configs
clients := []*Client{}
for _, endpoint := range config.NameServers {
features.PrintDeprecatedFeatureWarning("simple DNS server")
client, err := NewClient(ctx, &NameServer{Address: endpoint}, config)
if err != nil {
return nil, newError("failed to create client").Base(err)
}
clients = append(clients, client)
}
// Create name servers
nsClientMap := map[int]int{}
for nsIdx, ns := range config.NameServer {
client, err := NewClient(ctx, ns, config)
if err != nil {
return nil, newError("failed to create client").Base(err)
}
nsClientMap[nsIdx] = len(clients)
clients = append(clients, client)
}
// If there is no DNS client in config, add a `localhost` DNS client
if len(clients) == 0 {
clients = append(clients, NewLocalDNSClient())
}
s := &DNS{
hosts: hosts,
clients: clients,
ctx: ctx,
}
// Establish members related to global DNS state
s.clientTags = make(map[string]bool)
for _, client := range clients {
s.clientTags[client.tag] = true
}
if err := establishDomainRules(s, config, nsClientMap); err != nil {
return nil, err
}
if err := establishExpectedIPs(s, config, nsClientMap); err != nil {
return nil, err
}
if err := establishFakeDNS(s, config, nsClientMap); err != nil {
return nil, err
}
return s, nil
}
func establishDomainRules(s *DNS, config *Config, nsClientMap map[int]int) error {
domainRuleCount := 0
for _, ns := range config.NameServer {
domainRuleCount += len(ns.PrioritizedDomain)
}
// MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
var domainMatcher strmatcher.IndexMatcher
switch config.DomainMatcher {
case "mph", "hybrid":
newError("using mph domain matcher").AtDebug().WriteToLog()
domainMatcher = strmatcher.NewMphIndexMatcher()
case "linear":
fallthrough
default:
newError("using default domain matcher").AtDebug().WriteToLog()
domainMatcher = strmatcher.NewLinearIndexMatcher()
}
for nsIdx, ns := range config.NameServer {
clientIdx := nsClientMap[nsIdx]
var rules []string
ruleCurr := 0
ruleIter := 0
for _, domain := range ns.PrioritizedDomain {
domainRule, err := toStrMatcher(domain.Type, domain.Domain)
if err != nil {
return newError("failed to create prioritized domain").Base(err).AtWarning()
}
originalRuleIdx := ruleCurr
if ruleCurr < len(ns.OriginalRules) {
rule := ns.OriginalRules[ruleCurr]
if ruleCurr >= len(rules) {
rules = append(rules, rule.Rule)
}
ruleIter++
if ruleIter >= int(rule.Size) {
ruleIter = 0
ruleCurr++
}
} else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
rules = append(rules, domainRule.String())
ruleCurr++
}
midx := domainMatcher.Add(domainRule)
matcherInfos[midx] = DomainMatcherInfo{
clientIdx: uint16(clientIdx),
domainRuleIdx: uint16(originalRuleIdx),
}
if err != nil {
return newError("failed to create prioritized domain").Base(err).AtWarning()
}
}
s.clients[clientIdx].domains = rules
}
if err := domainMatcher.Build(); err != nil {
return err
}
s.domainMatcher = domainMatcher
s.matcherInfos = matcherInfos
return nil
}
func establishExpectedIPs(s *DNS, config *Config, nsClientMap map[int]int) error {
geoipContainer := router.GeoIPMatcherContainer{}
for nsIdx, ns := range config.NameServer {
clientIdx := nsClientMap[nsIdx]
var matchers []*router.GeoIPMatcher
for _, geoip := range ns.Geoip {
matcher, err := geoipContainer.Add(geoip)
if err != nil {
return newError("failed to create ip matcher").Base(err).AtWarning()
}
matchers = append(matchers, matcher)
}
s.clients[clientIdx].expectIPs = matchers
}
return nil
}
func establishFakeDNS(s *DNS, config *Config, nsClientMap map[int]int) error {
fakeHolders := &fakedns.HolderMulti{}
fakeDefault := (*fakedns.HolderMulti)(nil)
if config.FakeDns != nil {
defaultEngine, err := fakeHolders.AddPoolMulti(config.FakeDns)
if err != nil {
return newError("fail to create fake dns").Base(err).AtWarning()
}
fakeDefault = defaultEngine
}
for nsIdx, ns := range config.NameServer {
clientIdx := nsClientMap[nsIdx]
if ns.FakeDns == nil {
continue
}
engine, err := fakeHolders.AddPoolMulti(ns.FakeDns)
if err != nil {
return newError("fail to create fake dns").Base(err).AtWarning()
}
s.clients[clientIdx].fakeDNS = NewFakeDNSServer(engine)
s.clients[clientIdx].queryStrategy.FakeEnable = true
}
// Do not create FakeDNSEngine feature if no FakeDNS server is configured
if fakeHolders.IsEmpty() {
return nil
}
// Add FakeDNSEngine feature when DNS feature is added for the first time
s.fakeDNSEngine = &FakeDNSEngine{dns: s, fakeHolders: fakeHolders, fakeDefault: fakeDefault}
return core.RequireFeatures(s.ctx, func(client dns.Client) error {
v := core.MustFromContext(s.ctx)
if v.GetFeature(dns.FakeDNSEngineType()) != nil {
return nil
}
if client, ok := client.(dns.ClientWithFakeDNS); ok {
return v.AddFeature(client.AsFakeDNSEngine())
}
return nil
})
}
// Type implements common.HasType.
func (*DNS) Type() interface{} {
return dns.ClientType()
}
// Start implements common.Runnable.
func (s *DNS) Start() error {
return nil
}
// Close implements common.Closable.
func (s *DNS) Close() error {
return nil
}
// IsOwnLink implements proxy.dns.ownLinkVerifier
func (s *DNS) IsOwnLink(ctx context.Context) bool {
inbound := session.InboundFromContext(ctx)
return inbound != nil && s.clientTags[inbound.Tag]
}
// AsFakeDNSClient implements dns.ClientWithFakeDNS.
func (s *DNS) AsFakeDNSClient() dns.Client {
return &FakeDNSClient{DNS: s}
}
// AsFakeDNSEngine implements dns.ClientWithFakeDNS.
func (s *DNS) AsFakeDNSEngine() dns.FakeDNSEngine {
return s.fakeDNSEngine
}
// LookupIP implements dns.Client.
func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, IPv6Enable: true, FakeEnable: false})
}
// LookupIPv4 implements dns.IPv4Lookup.
func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, FakeEnable: false})
}
// LookupIPv6 implements dns.IPv6Lookup.
func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, dns.IPOption{IPv6Enable: true, FakeEnable: false})
}
func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
if domain == "" {
return nil, newError("empty domain name")
}
// Normalize the FQDN form query
domain = strings.TrimSuffix(domain, ".")
// Static host lookup
switch addrs := s.hosts.Lookup(domain, option); {
case addrs == nil: // Domain not recorded in static host
break
case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
return nil, dns.ErrEmptyResponse
case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
domain = addrs[0].Domain()
default: // Successfully found ip records in static host
newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
return toNetIP(addrs)
}
// Name servers lookup
errs := []error{}
for _, client := range s.sortClients(domain, option) {
ips, err := client.QueryIP(s.ctx, domain, option)
if len(ips) > 0 {
return ips, nil
}
if err != nil {
errs = append(errs, err)
}
if err != dns.ErrEmptyResponse { // ErrEmptyResponse is not seen as failure, so no failed log
newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
}
if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
return nil, err // Only continue lookup for certain errors
}
}
if len(errs) == 0 {
return nil, dns.ErrEmptyResponse
}
return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
}
func (s *DNS) sortClients(domain string, option dns.IPOption) []*Client {
clients := make([]*Client, 0, len(s.clients))
clientUsed := make([]bool, len(s.clients))
clientIdxs := make([]int, 0, len(s.clients))
domainRules := []string{}
// Priority domain matching
for _, match := range s.domainMatcher.Match(domain) {
info := s.matcherInfos[match]
client := s.clients[info.clientIdx]
domainRule := client.domains[info.domainRuleIdx]
domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
switch {
case clientUsed[info.clientIdx]:
continue
case !option.FakeEnable && isFakeDNS(client.server):
continue
}
clientUsed[info.clientIdx] = true
clients = append(clients, client)
clientIdxs = append(clientIdxs, int(info.clientIdx))
}
// Default round-robin query
hasDomainMatch := len(clients) > 0
for idx, client := range s.clients {
switch {
case clientUsed[idx]:
continue
case !option.FakeEnable && isFakeDNS(client.server):
continue
case client.fallbackStrategy == FallbackStrategy_Disabled:
continue
case client.fallbackStrategy == FallbackStrategy_DisabledIfAnyMatch && hasDomainMatch:
continue
}
clientUsed[idx] = true
clients = append(clients, client)
clientIdxs = append(clientIdxs, idx)
}
if len(domainRules) > 0 {
newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
}
if len(clientIdxs) > 0 {
newError("domain ", domain, " will use DNS in order: ", s.formatClientNames(clientIdxs, option), " ", toReqTypes(option)).AtDebug().WriteToLog()
}
return clients
}
func (s *DNS) formatClientNames(clientIdxs []int, option dns.IPOption) []string {
clientNames := make([]string, 0, len(clientIdxs))
counter := make(map[string]uint, len(clientIdxs))
for _, clientIdx := range clientIdxs {
client := s.clients[clientIdx]
var name string
if option.With(client.queryStrategy).FakeEnable {
name = fmt.Sprintf("%s(DNS idx:%d)", client.fakeDNS.Name(), clientIdx)
} else {
name = client.Name()
}
counter[name]++
clientNames = append(clientNames, name)
}
for idx, clientIdx := range clientIdxs {
name := clientNames[idx]
if counter[name] > 1 {
clientNames[idx] = fmt.Sprintf("%s(DNS idx:%d)", name, clientIdx)
}
}
return clientNames
}
var matcherTypeMap = map[routercommon.Domain_Type]DomainMatchingType{
routercommon.Domain_Plain: DomainMatchingType_Keyword,
routercommon.Domain_Regex: DomainMatchingType_Regex,
routercommon.Domain_RootDomain: DomainMatchingType_Subdomain,
routercommon.Domain_Full: DomainMatchingType_Full,
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
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)
for _, v := range simplifiedConfig.NameServer {
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)
}
}
}
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)
}
}
for _, domain := range geo.Domain {
v.PrioritizedDomain = append(v.PrioritizedDomain, &SimplifiedNameServer_PriorityDomain{
Type: matcherTypeMap[domain.Type],
Domain: domain.Value,
})
}
}
}
var nameservers []*NameServer
for _, v := range simplifiedConfig.NameServer {
nameserver := &NameServer{
Address: v.Address,
ClientIp: net.ParseIP(v.ClientIp),
Tag: v.Tag,
QueryStrategy: v.QueryStrategy,
CacheStrategy: v.CacheStrategy,
FallbackStrategy: v.FallbackStrategy,
SkipFallback: v.SkipFallback,
Geoip: v.Geoip,
}
for _, prioritizedDomain := range v.PrioritizedDomain {
nameserver.PrioritizedDomain = append(nameserver.PrioritizedDomain, &NameServer_PriorityDomain{
Type: prioritizedDomain.Type,
Domain: prioritizedDomain.Domain,
})
}
nameservers = append(nameservers, nameserver)
}
var statichosts []*HostMapping
for _, v := range simplifiedConfig.StaticHosts {
statichost := &HostMapping{
Type: v.Type,
Domain: v.Domain,
ProxiedDomain: v.ProxiedDomain,
}
for _, ip := range v.Ip {
statichost.Ip = append(statichost.Ip, net.ParseIP(ip))
}
statichosts = append(statichosts, statichost)
}
fullConfig := &Config{
StaticHosts: statichosts,
NameServer: nameservers,
ClientIp: net.ParseIP(simplifiedConfig.ClientIp),
Tag: simplifiedConfig.Tag,
DomainMatcher: simplifiedConfig.DomainMatcher,
QueryStrategy: simplifiedConfig.QueryStrategy,
CacheStrategy: simplifiedConfig.CacheStrategy,
FallbackStrategy: simplifiedConfig.FallbackStrategy,
// Deprecated flags
DisableCache: simplifiedConfig.DisableCache,
DisableFallback: simplifiedConfig.DisableFallback,
DisableFallbackIfMatch: simplifiedConfig.DisableFallbackIfMatch,
}
return common.CreateObject(ctx, fullConfig)
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.