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/common/signal/timer.go
common/signal/timer.go
package signal import ( "context" "sync" "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/task" ) type ActivityUpdater interface { Update() } type ActivityTimer struct { sync.RWMutex updated chan struct{} checkTask *task.Periodic onTimeout func() } func (t *ActivityTimer) Update() { select { case t.updated <- struct{}{}: default: } } func (t *ActivityTimer) check() error { select { case <-t.updated: default: t.finish() } return nil } func (t *ActivityTimer) finish() { t.Lock() defer t.Unlock() if t.onTimeout != nil { t.onTimeout() t.onTimeout = nil } if t.checkTask != nil { t.checkTask.Close() t.checkTask = nil } } func (t *ActivityTimer) SetTimeout(timeout time.Duration) { if timeout == 0 { t.finish() return } checkTask := &task.Periodic{ Interval: timeout, Execute: t.check, } t.Lock() if t.checkTask != nil { t.checkTask.Close() } t.checkTask = checkTask t.Unlock() t.Update() common.Must(checkTask.Start()) } func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer { timer := &ActivityTimer{ updated: make(chan struct{}, 1), onTimeout: cancel, } timer.SetTimeout(timeout) return timer }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/notifier.go
common/signal/notifier.go
package signal // Notifier is a utility for notifying changes. The change producer may notify changes multiple time, and the consumer may get notified asynchronously. type Notifier struct { c chan struct{} } // NewNotifier creates a new Notifier. func NewNotifier() *Notifier { return &Notifier{ c: make(chan struct{}, 1), } } // Signal signals a change, usually by producer. This method never blocks. func (n *Notifier) Signal() { select { case n.c <- struct{}{}: default: } } // Wait returns a channel for waiting for changes. The returned channel never gets closed. func (n *Notifier) Wait() <-chan struct{} { return n.c }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/timer_test.go
common/signal/timer_test.go
package signal_test import ( "context" "runtime" "testing" "time" . "github.com/v2fly/v2ray-core/v5/common/signal" ) func TestActivityTimer(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) timer := CancelAfterInactivity(ctx, cancel, time.Second*4) time.Sleep(time.Second * 6) if ctx.Err() == nil { t.Error("expected some error, but got nil") } runtime.KeepAlive(timer) } func TestActivityTimerUpdate(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) timer := CancelAfterInactivity(ctx, cancel, time.Second*10) time.Sleep(time.Second * 3) if ctx.Err() != nil { t.Error("expected nil, but got ", ctx.Err().Error()) } timer.SetTimeout(time.Second * 1) time.Sleep(time.Second * 2) if ctx.Err() == nil { t.Error("expected some error, but got nil") } runtime.KeepAlive(timer) } func TestActivityTimerNonBlocking(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) timer := CancelAfterInactivity(ctx, cancel, 0) time.Sleep(time.Second * 1) select { case <-ctx.Done(): default: t.Error("context not done") } timer.SetTimeout(0) timer.SetTimeout(1) timer.SetTimeout(2) } func TestActivityTimerZeroTimeout(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) timer := CancelAfterInactivity(ctx, cancel, 0) select { case <-ctx.Done(): default: t.Error("context not done") } runtime.KeepAlive(timer) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/notifier_test.go
common/signal/notifier_test.go
package signal_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/signal" ) func TestNotifierSignal(t *testing.T) { n := NewNotifier() w := n.Wait() n.Signal() select { case <-w: default: t.Fail() } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/pubsub/pubsub.go
common/signal/pubsub/pubsub.go
package pubsub import ( "errors" "sync" "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/signal/done" "github.com/v2fly/v2ray-core/v5/common/task" ) type Subscriber struct { buffer chan interface{} done *done.Instance } func (s *Subscriber) push(msg interface{}) { select { case s.buffer <- msg: default: } } func (s *Subscriber) Wait() <-chan interface{} { return s.buffer } func (s *Subscriber) Close() error { return s.done.Close() } func (s *Subscriber) IsClosed() bool { return s.done.Done() } type Service struct { sync.RWMutex subs map[string][]*Subscriber ctask *task.Periodic } func NewService() *Service { s := &Service{ subs: make(map[string][]*Subscriber), } s.ctask = &task.Periodic{ Execute: s.Cleanup, Interval: time.Second * 30, } return s } // Cleanup cleans up internal caches of subscribers. // Visible for testing only. func (s *Service) Cleanup() error { s.Lock() defer s.Unlock() if len(s.subs) == 0 { return errors.New("nothing to do") } for name, subs := range s.subs { newSub := make([]*Subscriber, 0, len(s.subs)) for _, sub := range subs { if !sub.IsClosed() { newSub = append(newSub, sub) } } if len(newSub) == 0 { delete(s.subs, name) } else { s.subs[name] = newSub } } if len(s.subs) == 0 { s.subs = make(map[string][]*Subscriber) } return nil } func (s *Service) Subscribe(name string) *Subscriber { sub := &Subscriber{ buffer: make(chan interface{}, 16), done: done.New(), } s.Lock() s.subs[name] = append(s.subs[name], sub) s.Unlock() common.Must(s.ctask.Start()) return sub } func (s *Service) Publish(name string, message interface{}) { s.RLock() defer s.RUnlock() for _, sub := range s.subs[name] { if !sub.IsClosed() { sub.push(message) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/pubsub/pubsub_test.go
common/signal/pubsub/pubsub_test.go
package pubsub_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/signal/pubsub" ) func TestPubsub(t *testing.T) { service := NewService() sub := service.Subscribe("a") service.Publish("a", 1) select { case v := <-sub.Wait(): if v != 1 { t.Error("expected subscribed value 1, but got ", v) } default: t.Fail() } sub.Close() service.Publish("a", 2) select { case <-sub.Wait(): t.Fail() default: } service.Cleanup() }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/semaphore/semaphore.go
common/signal/semaphore/semaphore.go
package semaphore // Instance is an implementation of semaphore. type Instance struct { token chan struct{} } // New create a new Semaphore with n permits. func New(n int) *Instance { s := &Instance{ token: make(chan struct{}, n), } for i := 0; i < n; i++ { s.token <- struct{}{} } return s } // Wait returns a channel for acquiring a permit. func (s *Instance) Wait() <-chan struct{} { return s.token } // Signal releases a permit into the semaphore. func (s *Instance) Signal() { s.token <- struct{}{} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/signal/done/done.go
common/signal/done/done.go
package done import ( "sync" ) // Instance is a utility for notifications of something being done. type Instance struct { access sync.Mutex c chan struct{} closed bool } // New returns a new Done. func New() *Instance { return &Instance{ c: make(chan struct{}), } } // Done returns true if Close() is called. func (d *Instance) Done() bool { select { case <-d.Wait(): return true default: return false } } // Wait returns a channel for waiting for done. func (d *Instance) Wait() <-chan struct{} { return d.c } // Close marks this Done 'done'. This method may be called multiple times. All calls after first call will have no effect on its status. func (d *Instance) Close() error { d.access.Lock() defer d.access.Unlock() if d.closed { return nil } d.closed = true close(d.c) return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/task/periodic.go
common/task/periodic.go
package task import ( "sync" "time" ) // Periodic is a task that runs periodically. type Periodic struct { // Interval of the task being run Interval time.Duration // Execute is the task function Execute func() error access sync.Mutex timer *time.Timer running bool } func (t *Periodic) hasClosed() bool { t.access.Lock() defer t.access.Unlock() return !t.running } func (t *Periodic) checkedExecute() error { if t.hasClosed() { return nil } if err := t.Execute(); err != nil { t.access.Lock() t.running = false t.access.Unlock() return err } t.access.Lock() defer t.access.Unlock() if !t.running { return nil } t.timer = time.AfterFunc(t.Interval, func() { t.checkedExecute() }) return nil } // Start implements common.Runnable. func (t *Periodic) Start() error { t.access.Lock() if t.running { t.access.Unlock() return nil } t.running = true t.access.Unlock() if err := t.checkedExecute(); err != nil { t.access.Lock() t.running = false t.access.Unlock() return err } return nil } // Close implements common.Closable. func (t *Periodic) Close() error { t.access.Lock() defer t.access.Unlock() t.running = false if t.timer != nil { t.timer.Stop() t.timer = nil } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/task/periodic_test.go
common/task/periodic_test.go
package task_test import ( "sync/atomic" "testing" "time" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/task" ) func TestPeriodicTaskStop(t *testing.T) { var value uint64 task := &Periodic{ Interval: time.Second * 2, Execute: func() error { atomic.AddUint64(&value, 1) return nil }, } common.Must(task.Start()) time.Sleep(time.Second * 5) common.Must(task.Close()) value1 := atomic.LoadUint64(&value) if value1 != 3 { t.Fatal("expected 3, but got ", value1) } time.Sleep(time.Second * 4) value2 := atomic.LoadUint64(&value) if value2 != 3 { t.Fatal("expected 3, but got ", value2) } common.Must(task.Start()) time.Sleep(time.Second * 3) value3 := atomic.LoadUint64(&value) if value3 != 5 { t.Fatal("Expected 5, but ", value3) } common.Must(task.Close()) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/task/task_test.go
common/task/task_test.go
package task_test import ( "context" "errors" "strings" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/task" ) func TestExecuteParallel(t *testing.T) { err := Run(context.Background(), func() error { time.Sleep(time.Millisecond * 200) return errors.New("test") }, func() error { time.Sleep(time.Millisecond * 500) return errors.New("test2") }) if r := cmp.Diff(err.Error(), "test"); r != "" { t.Error(r) } } func TestExecuteParallelContextCancel(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) err := Run(ctx, func() error { time.Sleep(time.Millisecond * 2000) return errors.New("test") }, func() error { time.Sleep(time.Millisecond * 5000) return errors.New("test2") }, func() error { cancel() return nil }) errStr := err.Error() if !strings.Contains(errStr, "canceled") { t.Error("expected error string to contain 'canceled', but actually not: ", errStr) } } func BenchmarkExecuteOne(b *testing.B) { noop := func() error { return nil } for i := 0; i < b.N; i++ { common.Must(Run(context.Background(), noop)) } } func BenchmarkExecuteTwo(b *testing.B) { noop := func() error { return nil } for i := 0; i < b.N; i++ { common.Must(Run(context.Background(), noop, noop)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/task/task.go
common/task/task.go
package task import ( "context" "github.com/v2fly/v2ray-core/v5/common/signal/semaphore" ) // OnSuccess executes g() after f() returns nil. func OnSuccess(f func() error, g func() error) func() error { return func() error { if err := f(); err != nil { return err } return g() } } // Run executes a list of tasks in parallel, returns the first error encountered or nil if all tasks pass. func Run(ctx context.Context, tasks ...func() error) error { n := len(tasks) s := semaphore.New(n) done := make(chan error, 1) for _, task := range tasks { <-s.Wait() go func(f func() error) { err := f() if err == nil { s.Signal() return } select { case done <- err: default: } }(task) } for i := 0; i < n; i++ { select { case err := <-done: return err case <-ctx.Done(): return ctx.Err() case <-s.Wait(): } } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/task/common.go
common/task/common.go
package task import "github.com/v2fly/v2ray-core/v5/common" // Close returns a func() that closes v. func Close(v interface{}) func() error { return func() error { return common.Close(v) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/dice/dice.go
common/dice/dice.go
// Package dice contains common functions to generate random number. // It also initialize math/rand with the time in seconds at launch time. package dice import ( crand "crypto/rand" "io" "math/big" "math/rand" "time" "github.com/v2fly/v2ray-core/v5/common" ) // Roll returns a non-negative number between 0 (inclusive) and n (exclusive). func Roll(n int) int { if n == 1 { return 0 } return rand.Intn(n) } // RollWith returns a non-negative number between 0 (inclusive) and n (exclusive). // Use random as the random source, if read fails, it panics. func RollWith(n int, random io.Reader) int { if n == 1 { return 0 } mrand, err := crand.Int(random, big.NewInt(int64(n))) common.Must(err) return int(mrand.Int64()) } // Roll returns a non-negative number between 0 (inclusive) and n (exclusive). func RollDeterministic(n int, seed int64) int { if n == 1 { return 0 } return rand.New(rand.NewSource(seed)).Intn(n) } // RollUint16 returns a random uint16 value. func RollUint16() uint16 { return uint16(rand.Int63() >> 47) } func RollUint64() uint64 { return rand.Uint64() } func NewDeterministicDice(seed int64) *DeterministicDice { return &DeterministicDice{rand.New(rand.NewSource(seed))} } type DeterministicDice struct { *rand.Rand } func (dd *DeterministicDice) Roll(n int) int { if n == 1 { return 0 } return dd.Intn(n) } func init() { rand.Seed(time.Now().Unix()) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/dice/dice_test.go
common/dice/dice_test.go
package dice_test import ( "math/rand" "testing" . "github.com/v2fly/v2ray-core/v5/common/dice" ) func BenchmarkRoll1(b *testing.B) { for i := 0; i < b.N; i++ { Roll(1) } } func BenchmarkRoll20(b *testing.B) { for i := 0; i < b.N; i++ { Roll(20) } } func BenchmarkIntn1(b *testing.B) { for i := 0; i < b.N; i++ { rand.Intn(1) //nolint:staticcheck } } func BenchmarkIntn20(b *testing.B) { for i := 0; i < b.N; i++ { rand.Intn(20) } } func BenchmarkInt63(b *testing.B) { for i := 0; i < b.N; i++ { _ = uint16(rand.Int63() >> 47) } } func BenchmarkInt31(b *testing.B) { for i := 0; i < b.N; i++ { _ = uint16(rand.Int31() >> 15) } } func BenchmarkIntn(b *testing.B) { for i := 0; i < b.N; i++ { _ = uint16(rand.Intn(65536)) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/registry/implementation_set.go
common/registry/implementation_set.go
package registry import ( "github.com/golang/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protoext" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type implementationSet struct { AliasLookup map[string]*implementation } type CustomLoader func(data []byte, loader LoadByAlias) (proto.Message, error) type implementation struct { FullName string Alias []string Loader CustomLoader } func (i *implementationSet) RegisterImplementation(name string, opt *protoext.MessageOpt, loader CustomLoader) { alias := opt.GetShortName() impl := &implementation{ FullName: name, Alias: alias, } for _, aliasName := range alias { i.AliasLookup[aliasName] = impl } } func (i *implementationSet) findImplementationByAlias(alias string) (string, CustomLoader, error) { impl, found := i.AliasLookup[alias] if found { return impl.FullName, impl.Loader, nil } return "", nil, newError("cannot find implementation by alias: ", alias) } func newImplementationSet() *implementationSet { return &implementationSet{AliasLookup: map[string]*implementation{}} }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/registry/registry.go
common/registry/registry.go
package registry import ( "bytes" "context" "reflect" "strings" "sync" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" protov2 "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protoext" "github.com/v2fly/v2ray-core/v5/common/protofilter" "github.com/v2fly/v2ray-core/v5/common/serial" ) type implementationRegistry struct { implSet map[string]*implementationSet } func (i *implementationRegistry) RegisterImplementation(name string, opt *protoext.MessageOpt, loader CustomLoader) { interfaceType := opt.GetType() for _, v := range interfaceType { i.registerSingleImplementation(v, name, opt, loader) } } func (i *implementationRegistry) registerSingleImplementation(interfaceType, name string, opt *protoext.MessageOpt, loader CustomLoader) { implSet, found := i.implSet[interfaceType] if !found { implSet = newImplementationSet() i.implSet[interfaceType] = implSet } implSet.RegisterImplementation(name, opt, loader) } func (i *implementationRegistry) findImplementationByAlias(interfaceType, alias string) (string, CustomLoader, error) { implSet, found := i.implSet[interfaceType] if !found { return "", nil, newError("cannot find implemention unknown interface type") } return implSet.findImplementationByAlias(alias) } func (i *implementationRegistry) LoadImplementationByAlias(ctx context.Context, interfaceType, alias string, data []byte) (proto.Message, error) { var implementationFullName string if strings.HasPrefix(alias, "#") { // skip resolution for full name implementationFullName, _ = strings.CutPrefix(alias, "#") } else { registryResult, customLoader, err := i.findImplementationByAlias(interfaceType, alias) if err != nil { return nil, newError("unable to find implementation").Base(err) } if customLoader != nil { return customLoader(data, i) } implementationFullName = registryResult } implementationConfigInstance, err := serial.GetInstance(implementationFullName) if err != nil { return nil, newError("unable to create implementation config instance").Base(err) } unmarshaler := jsonpb.Unmarshaler{AllowUnknownFields: false} err = unmarshaler.Unmarshal(bytes.NewReader(data), implementationConfigInstance.(proto.Message)) if err != nil { return nil, newError("unable to parse json content").Base(err) } implementationConfigInstancev2 := proto.MessageV2(implementationConfigInstance) if isRestrictedModeContext(ctx) { if err := enforceRestriction(implementationConfigInstancev2); err != nil { return nil, err } } if err := protofilter.FilterProtoConfig(ctx, implementationConfigInstancev2); err != nil { return nil, err } return implementationConfigInstance.(proto.Message), nil } func newImplementationRegistry() *implementationRegistry { return &implementationRegistry{implSet: map[string]*implementationSet{}} } var globalImplementationRegistry = newImplementationRegistry() var initialized = &sync.Once{} type registerRequest struct { proto interface{} loader CustomLoader } var registerRequests []registerRequest // RegisterImplementation register an implementation of a type of interface // loader(CustomLoader) is a private API, its interface is subject to breaking changes func RegisterImplementation(proto interface{}, loader CustomLoader) error { registerRequests = append(registerRequests, registerRequest{ proto: proto, loader: loader, }) return nil } func registerImplementation(proto interface{}, loader CustomLoader) error { protoReflect := reflect.New(reflect.TypeOf(proto).Elem()) proto2 := protoReflect.Interface().(protov2.Message) msgDesc := proto2.ProtoReflect().Descriptor() fullName := string(msgDesc.FullName()) msgOpts, err := protoext.GetMessageOptions(msgDesc) if err != nil { return newError("unable to find message options").Base(err) } globalImplementationRegistry.RegisterImplementation(fullName, msgOpts, loader) return nil } type LoadByAlias interface { LoadImplementationByAlias(ctx context.Context, interfaceType, alias string, data []byte) (proto.Message, error) } func LoadImplementationByAlias(ctx context.Context, interfaceType, alias string, data []byte) (proto.Message, error) { initialized.Do(func() { for _, v := range registerRequests { registerImplementation(v.proto, v.loader) } }) return globalImplementationRegistry.LoadImplementationByAlias(ctx, interfaceType, alias, data) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/registry/errors.generated.go
common/registry/errors.generated.go
package registry import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/registry/restrict.go
common/registry/restrict.go
package registry import ( "context" "google.golang.org/protobuf/proto" "github.com/v2fly/v2ray-core/v5/common/protoext" ) const restrictedLoadModeCtx = "restrictedLoadModeCtx" func CreateRestrictedModeContext(ctx context.Context) context.Context { return context.WithValue(ctx, restrictedLoadModeCtx, true) //nolint: staticcheck } func isRestrictedModeContext(ctx context.Context) bool { v := ctx.Value(restrictedLoadModeCtx) if v == nil { return false } return v.(bool) } func enforceRestriction(config proto.Message) error { configDescriptor := config.ProtoReflect().Descriptor() msgOpts, err := protoext.GetMessageOptions(configDescriptor) if err != nil { return newError("unable to find message options").Base(err) } if !msgOpts.AllowRestrictedModeLoad { return newError("component has not opted in for load in restricted mode") } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/windows.go
common/platform/windows.go
//go:build windows // +build windows package platform import "path/filepath" func LineSeparator() string { return "\r\n" } // GetAssetLocation search for `file` in the excutable dir func GetAssetLocation(file string) string { const name = "v2ray.location.asset" assetPath := NewEnvFlag(name).GetValue(getExecutableDir) return filepath.Join(assetPath, file) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/platform_test.go
common/platform/platform_test.go
package platform_test import ( "errors" "io/fs" "os" "path/filepath" "runtime" "testing" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/platform" ) func TestNormalizeEnvName(t *testing.T) { cases := []struct { input string output string }{ { input: "a", output: "A", }, { input: "a.a", output: "A_A", }, { input: "A.A.B", output: "A_A_B", }, } for _, test := range cases { if v := platform.NormalizeEnvName(test.input); v != test.output { t.Error("unexpected output: ", v, " want ", test.output) } } } func TestEnvFlag(t *testing.T) { if v := (platform.EnvFlag{ Name: "xxxxx.y", }.GetValueAsInt(10)); v != 10 { t.Error("env value: ", v) } } // TestWrongErrorCheckOnOSStat is a test to detect the misuse of error handling // in os.Stat, which will lead to failure to find & read geoip & geosite files. func TestWrongErrorCheckOnOSStat(t *testing.T) { theExpectedDir := filepath.Join("usr", "local", "share", "v2ray") getAssetLocation := func(file string) string { for _, p := range []string{ filepath.Join(theExpectedDir, file), } { // errors.Is(fs.ErrNotExist, err) is a mistake supposed Not to // be discovered by the Go runtime, which will lead to failure to // find & read geoip & geosite files. // The correct code is `errors.Is(err, fs.ErrNotExist)` if _, err := os.Stat(p); err != nil && errors.Is(fs.ErrNotExist, err) { //nolint: staticcheck continue } // asset found return p } return filepath.Join("the", "wrong", "path", "not-exist.txt") } notExist := getAssetLocation("not-exist.txt") if filepath.Dir(notExist) != theExpectedDir { t.Error("asset dir:", notExist, "not in", theExpectedDir) } } func TestGetAssetLocation(t *testing.T) { exec, err := os.Executable() common.Must(err) loc := platform.GetAssetLocation("t") if filepath.Dir(loc) != filepath.Dir(exec) { t.Error("asset dir: ", loc, " not in ", exec) } os.Setenv("v2ray.location.asset", "/v2ray") if runtime.GOOS == "windows" { if v := platform.GetAssetLocation("t"); v != "\\v2ray\\t" { t.Error("asset loc: ", v) } } else { if v := platform.GetAssetLocation("t"); v != "/v2ray/t" { t.Error("asset loc: ", v) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/others.go
common/platform/others.go
//go:build !windows // +build !windows package platform import ( "path/filepath" "github.com/adrg/xdg" ) func LineSeparator() string { return "\n" } // GetAssetLocation search for `file` in certain locations func GetAssetLocation(file string) string { const name = "v2ray.location.asset" assetPath := NewEnvFlag(name).GetValue(getExecutableDir) defPath := filepath.Join(assetPath, file) relPath := filepath.Join("v2ray", file) fullPath, err := xdg.SearchDataFile(relPath) if err != nil { return defPath } return fullPath }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/platform.go
common/platform/platform.go
package platform import ( "os" "path/filepath" "strconv" "strings" ) type EnvFlag struct { Name string AltName string } func NewEnvFlag(name string) EnvFlag { return EnvFlag{ Name: name, AltName: NormalizeEnvName(name), } } func (f EnvFlag) GetValue(defaultValue func() string) string { if v, found := os.LookupEnv(f.Name); found { return v } if len(f.AltName) > 0 { if v, found := os.LookupEnv(f.AltName); found { return v } } return defaultValue() } func (f EnvFlag) GetValueAsInt(defaultValue int) int { useDefaultValue := false s := f.GetValue(func() string { useDefaultValue = true return "" }) if useDefaultValue { return defaultValue } v, err := strconv.ParseInt(s, 10, 32) if err != nil { return defaultValue } return int(v) } func NormalizeEnvName(name string) string { return strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(name)), ".", "_") } func getExecutableDir() string { exec, err := os.Executable() if err != nil { return "" } return filepath.Dir(exec) } func getExecutableSubDir(dir string) func() string { return func() string { return filepath.Join(getExecutableDir(), dir) } } func GetPluginDirectory() string { const name = "v2ray.location.plugin" pluginDir := NewEnvFlag(name).GetValue(getExecutableSubDir("plugins")) return pluginDir } func GetConfigurationPath() string { const name = "v2ray.location.config" configPath := NewEnvFlag(name).GetValue(getExecutableDir) return filepath.Join(configPath, "config.json") } // GetConfDirPath reads "v2ray.location.confdir" func GetConfDirPath() string { const name = "v2ray.location.confdir" configPath := NewEnvFlag(name).GetValue(func() string { return "" }) return configPath }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/filesystem/file.go
common/platform/filesystem/file.go
package filesystem import ( "io" "os" "path/filepath" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem/fsifce" ) var NewFileSeeker fsifce.FileSeekerFunc = func(path string) (io.ReadSeekCloser, error) { return os.Open(path) } var NewFileReader fsifce.FileReaderFunc = func(path string) (io.ReadCloser, error) { return os.Open(path) } var NewFileWriter fsifce.FileWriterFunc = func(path string) (io.WriteCloser, error) { basePath := filepath.Dir(path) if err := os.MkdirAll(basePath, 0o700); err != nil { return nil, err } return os.Create(path) } var NewFileRemover fsifce.FileRemoveFunc = os.Remove var NewFileReadDir fsifce.FileReadDirFunc = os.ReadDir func ReadFile(path string) ([]byte, error) { reader, err := NewFileReader(path) if err != nil { return nil, err } defer reader.Close() return buf.ReadAllToBytes(reader) } func WriteFile(path string, payload []byte) error { writer, err := NewFileWriter(path) if err != nil { return err } defer writer.Close() return buf.WriteAllBytes(writer, payload) } func ReadAsset(file string) ([]byte, error) { return ReadFile(platform.GetAssetLocation(file)) } func CopyFile(dst string, src string, perm os.FileMode) error { bytes, err := ReadFile(src) if err != nil { return err } f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, perm) if err != nil { return err } defer f.Close() _, err = f.Write(bytes) return err }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/filesystem/fsifce/ifce.go
common/platform/filesystem/fsifce/ifce.go
package fsifce import ( "io" "io/fs" ) type FileSeekerFunc func(path string) (io.ReadSeekCloser, error) type FileReaderFunc func(path string) (io.ReadCloser, error) type FileWriterFunc func(path string) (io.WriteCloser, error) type FileReadDirFunc func(path string) ([]fs.DirEntry, error) type FileRemoveFunc func(path string) error
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/ctlcmd/attr_other.go
common/platform/ctlcmd/attr_other.go
//go:build !windows // +build !windows package ctlcmd import "syscall" func getSysProcAttr() *syscall.SysProcAttr { return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/securedload/verify.go
common/platform/securedload/verify.go
package securedload type ProtectedLoader interface { VerifyAndLoad(filename string) ([]byte, error) } var knownProtectedLoader map[string]ProtectedLoader func RegisterProtectedLoader(name string, sv ProtectedLoader) { if knownProtectedLoader == nil { knownProtectedLoader = map[string]ProtectedLoader{} } knownProtectedLoader[name] = sv }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/securedload/file.go
common/platform/securedload/file.go
package securedload func GetAssetSecured(name string) ([]byte, error) { var err error for k, v := range knownProtectedLoader { loadedData, errLoad := v.VerifyAndLoad(name) if errLoad == nil { return loadedData, nil } err = newError(k, " is not loading executable file").Base(errLoad) } return nil, err }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/securedload/errors.generated.go
common/platform/securedload/errors.generated.go
package securedload import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/securedload/embedded.go
common/platform/securedload/embedded.go
package securedload const allowedHashes = `SHA256 (!#project==v2fly) = ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff SHA256 (!#version==embedded) = ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff SHA256 (subscriptions/subscriptionsDefinition.v2flyTemplate) = 3f165dba7de0d7c506fbdff3275ea64b76f307df435316a3ea0914ee957793ab SHA256 (browserforwarder/index.html) = 34f2c573724256421ade769bda18eeac85172bf0aaed00d7b90e41e843a2caef SHA256 (browserforwarder/index.js) = cb587a075bb0addcdc0d22c9222a48d2c7004b54935b5021379d3d35dc1f2927 `
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/platform/securedload/securedload.go
common/platform/securedload/securedload.go
package securedload //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/common/platform/securedload/embeddedhash.go
common/platform/securedload/embeddedhash.go
package securedload import ( "bytes" "crypto/sha256" "encoding/hex" "path/filepath" "strings" "github.com/v2fly/VSign/insmgr" "github.com/v2fly/VSign/signerVerify" "github.com/v2fly/v2ray-core/v5/common/platform" "github.com/v2fly/v2ray-core/v5/common/platform/filesystem" ) type EmbeddedHashProtectedLoader struct { checkedFile map[string]string } func (e EmbeddedHashProtectedLoader) VerifyAndLoad(filename string) ([]byte, error) { platformFileName := filepath.FromSlash(filename) fileContent, err := filesystem.ReadFile(platform.GetAssetLocation(platformFileName)) if err != nil { return nil, newError("Cannot find file", filename).Base(err) } fileHash := sha256.Sum256(fileContent) fileHashAsString := hex.EncodeToString(fileHash[:]) if fileNameVerified, ok := e.checkedFile[fileHashAsString]; ok { for _, filenameVerifiedIndividual := range strings.Split(fileNameVerified, ";") { if strings.HasSuffix(filenameVerifiedIndividual, filename) { return fileContent, nil } } } return nil, newError("Unrecognized file at ", filename, " can not be loaded for execution") } func NewEmbeddedHashProtectedLoader() *EmbeddedHashProtectedLoader { instructions := insmgr.ReadAllIns(bytes.NewReader([]byte(allowedHashes))) checkedFile, _, ok := signerVerify.CheckAsClient(instructions, "v2fly", true) if !ok { panic("Embedded Hash data is invalid") } return &EmbeddedHashProtectedLoader{checkedFile: checkedFile} } func init() { RegisterProtectedLoader("embedded", NewEmbeddedHashProtectedLoader()) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/chunk_test.go
common/crypto/chunk_test.go
package crypto_test import ( "bytes" "io" "testing" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" . "github.com/v2fly/v2ray-core/v5/common/crypto" ) func TestChunkStreamIO(t *testing.T) { cache := bytes.NewBuffer(make([]byte, 0, 8192)) writer := NewChunkStreamWriter(PlainChunkSizeParser{}, cache) reader := NewChunkStreamReader(PlainChunkSizeParser{}, cache) b := buf.New() b.WriteString("abcd") common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b})) b = buf.New() b.WriteString("efg") common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b})) common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{})) if cache.Len() != 13 { t.Fatalf("Cache length is %d, want 13", cache.Len()) } mb, err := reader.ReadMultiBuffer() common.Must(err) if s := mb.String(); s != "abcd" { t.Error("content: ", s) } mb, err = reader.ReadMultiBuffer() common.Must(err) if s := mb.String(); s != "efg" { t.Error("content: ", s) } _, err = reader.ReadMultiBuffer() if err != io.EOF { t.Error("error: ", err) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/aes.go
common/crypto/aes.go
package crypto import ( "crypto/aes" "crypto/cipher" "github.com/v2fly/v2ray-core/v5/common" ) // NewAesDecryptionStream creates a new AES encryption stream based on given key and IV. // Caller must ensure the length of key and IV is either 16, 24 or 32 bytes. func NewAesDecryptionStream(key []byte, iv []byte) cipher.Stream { return NewAesStreamMethod(key, iv, cipher.NewCFBDecrypter) } // NewAesEncryptionStream creates a new AES description stream based on given key and IV. // Caller must ensure the length of key and IV is either 16, 24 or 32 bytes. func NewAesEncryptionStream(key []byte, iv []byte) cipher.Stream { return NewAesStreamMethod(key, iv, cipher.NewCFBEncrypter) } func NewAesStreamMethod(key []byte, iv []byte, f func(cipher.Block, []byte) cipher.Stream) cipher.Stream { aesBlock, err := aes.NewCipher(key) common.Must(err) return f(aesBlock, iv) } // NewAesCTRStream creates a stream cipher based on AES-CTR. func NewAesCTRStream(key []byte, iv []byte) cipher.Stream { return NewAesStreamMethod(key, iv, cipher.NewCTR) } // NewAesGcm creates a AEAD cipher based on AES-GCM. func NewAesGcm(key []byte) cipher.AEAD { block, err := aes.NewCipher(key) common.Must(err) aead, err := cipher.NewGCM(block) common.Must(err) return aead }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/errors.generated.go
common/crypto/errors.generated.go
package crypto import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/chacha20.go
common/crypto/chacha20.go
package crypto import ( "crypto/cipher" "github.com/v2fly/v2ray-core/v5/common/crypto/internal" ) // NewChaCha20Stream creates a new Chacha20 encryption/descryption stream based on give key and IV. // Caller must ensure the length of key is 32 bytes, and length of IV is either 8 or 12 bytes. func NewChaCha20Stream(key []byte, iv []byte) cipher.Stream { return internal.NewChaCha20Stream(key, iv, 20) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/io.go
common/crypto/io.go
package crypto import ( "crypto/cipher" "io" "github.com/v2fly/v2ray-core/v5/common/buf" ) type CryptionReader struct { stream cipher.Stream reader io.Reader } func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader { return &CryptionReader{ stream: stream, reader: reader, } } func (r *CryptionReader) Read(data []byte) (int, error) { nBytes, err := r.reader.Read(data) if nBytes > 0 { r.stream.XORKeyStream(data[:nBytes], data[:nBytes]) } return nBytes, err } var _ buf.Writer = (*CryptionWriter)(nil) type CryptionWriter struct { stream cipher.Stream writer io.Writer bufWriter buf.Writer } // NewCryptionWriter creates a new CryptionWriter. func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter { return &CryptionWriter{ stream: stream, writer: writer, bufWriter: buf.NewWriter(writer), } } // Write implements io.Writer.Write(). func (w *CryptionWriter) Write(data []byte) (int, error) { w.stream.XORKeyStream(data, data) if err := buf.WriteAllBytes(w.writer, data); err != nil { return 0, err } return len(data), nil } // WriteMultiBuffer implements buf.Writer. func (w *CryptionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { for _, b := range mb { w.stream.XORKeyStream(b.Bytes(), b.Bytes()) } return w.bufWriter.WriteMultiBuffer(mb) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/chacha20_test.go
common/crypto/chacha20_test.go
package crypto_test import ( "crypto/rand" "encoding/hex" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/crypto" ) func mustDecodeHex(s string) []byte { b, err := hex.DecodeString(s) common.Must(err) return b } func TestChaCha20Stream(t *testing.T) { cases := []struct { key []byte iv []byte output []byte }{ { key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"), iv: mustDecodeHex("0000000000000000"), output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" + "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586" + "9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed" + "29b721769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f"), }, { key: mustDecodeHex("5555555555555555555555555555555555555555555555555555555555555555"), iv: mustDecodeHex("5555555555555555"), output: mustDecodeHex("bea9411aa453c5434a5ae8c92862f564396855a9ea6e22d6d3b50ae1b3663311" + "a4a3606c671d605ce16c3aece8e61ea145c59775017bee2fa6f88afc758069f7" + "e0b8f676e644216f4d2a3422d7fa36c6c4931aca950e9da42788e6d0b6d1cd83" + "8ef652e97b145b14871eae6c6804c7004db5ac2fce4c68c726d004b10fcaba86"), }, { key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"), iv: mustDecodeHex("000000000000000000000000"), output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"), }, } for _, c := range cases { s := NewChaCha20Stream(c.key, c.iv) input := make([]byte, len(c.output)) actualOutput := make([]byte, len(c.output)) s.XORKeyStream(actualOutput, input) if r := cmp.Diff(c.output, actualOutput); r != "" { t.Fatal(r) } } } func TestChaCha20Decoding(t *testing.T) { key := make([]byte, 32) common.Must2(rand.Read(key)) iv := make([]byte, 8) common.Must2(rand.Read(iv)) stream := NewChaCha20Stream(key, iv) payload := make([]byte, 1024) common.Must2(rand.Read(payload)) x := make([]byte, len(payload)) stream.XORKeyStream(x, payload) stream2 := NewChaCha20Stream(key, iv) stream2.XORKeyStream(x, x) if r := cmp.Diff(x, payload); 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/common/crypto/crypto.go
common/crypto/crypto.go
// Package crypto provides common crypto libraries for V2Ray. package crypto //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/common/crypto/benchmark_test.go
common/crypto/benchmark_test.go
package crypto_test import ( "crypto/cipher" "testing" . "github.com/v2fly/v2ray-core/v5/common/crypto" ) const benchSize = 1024 * 1024 func benchmarkStream(b *testing.B, c cipher.Stream) { b.SetBytes(benchSize) input := make([]byte, benchSize) output := make([]byte, benchSize) b.ResetTimer() for i := 0; i < b.N; i++ { c.XORKeyStream(output, input) } } func BenchmarkChaCha20(b *testing.B) { key := make([]byte, 32) nonce := make([]byte, 8) c := NewChaCha20Stream(key, nonce) benchmarkStream(b, c) } func BenchmarkChaCha20IETF(b *testing.B) { key := make([]byte, 32) nonce := make([]byte, 12) c := NewChaCha20Stream(key, nonce) benchmarkStream(b, c) } func BenchmarkAESEncryption(b *testing.B) { key := make([]byte, 32) iv := make([]byte, 16) c := NewAesEncryptionStream(key, iv) benchmarkStream(b, c) } func BenchmarkAESDecryption(b *testing.B) { key := make([]byte, 32) iv := make([]byte, 16) c := NewAesDecryptionStream(key, iv) benchmarkStream(b, c) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/auth.go
common/crypto/auth.go
package crypto import ( "crypto/cipher" "crypto/rand" "io" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/bytespool" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/protocol" ) type BytesGenerator func() []byte func GenerateEmptyBytes() BytesGenerator { var b [1]byte return func() []byte { return b[:0] } } func GenerateStaticBytes(content []byte) BytesGenerator { return func() []byte { return content } } func GenerateIncreasingNonce(nonce []byte) BytesGenerator { c := append([]byte(nil), nonce...) return func() []byte { for i := range c { c[i]++ if c[i] != 0 { break } } return c } } func GenerateInitialAEADNonce() BytesGenerator { return GenerateIncreasingNonce([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}) } type Authenticator interface { NonceSize() int Overhead() int Open(dst, cipherText []byte) ([]byte, error) Seal(dst, plainText []byte) ([]byte, error) } type AEADAuthenticator struct { cipher.AEAD NonceGenerator BytesGenerator AdditionalDataGenerator BytesGenerator } func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) { iv := v.NonceGenerator() if len(iv) != v.AEAD.NonceSize() { return nil, newError("invalid AEAD nonce size: ", len(iv)) } var additionalData []byte if v.AdditionalDataGenerator != nil { additionalData = v.AdditionalDataGenerator() } return v.AEAD.Open(dst, iv, cipherText, additionalData) } func (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) { iv := v.NonceGenerator() if len(iv) != v.AEAD.NonceSize() { return nil, newError("invalid AEAD nonce size: ", len(iv)) } var additionalData []byte if v.AdditionalDataGenerator != nil { additionalData = v.AdditionalDataGenerator() } return v.AEAD.Seal(dst, iv, plainText, additionalData), nil } type AuthenticationReader struct { auth Authenticator reader *buf.BufferedReader sizeParser ChunkSizeDecoder sizeBytes []byte transferType protocol.TransferType padding PaddingLengthGenerator size uint16 sizeOffset uint16 paddingLen uint16 hasSize bool done bool } func NewAuthenticationReader(auth Authenticator, sizeParser ChunkSizeDecoder, reader io.Reader, transferType protocol.TransferType, paddingLen PaddingLengthGenerator) *AuthenticationReader { r := &AuthenticationReader{ auth: auth, sizeParser: sizeParser, transferType: transferType, padding: paddingLen, sizeBytes: make([]byte, sizeParser.SizeBytes()), } if chunkSizeDecoderWithOffset, ok := sizeParser.(ChunkSizeDecoderWithOffset); ok { r.sizeOffset = chunkSizeDecoderWithOffset.HasConstantOffset() } if breader, ok := reader.(*buf.BufferedReader); ok { r.reader = breader } else { r.reader = &buf.BufferedReader{Reader: buf.NewReader(reader)} } return r } func (r *AuthenticationReader) readSize() (uint16, uint16, error) { if r.hasSize { r.hasSize = false return r.size, r.paddingLen, nil } if _, err := io.ReadFull(r.reader, r.sizeBytes); err != nil { return 0, 0, err } var padding uint16 if r.padding != nil { padding = r.padding.NextPaddingLen() } size, err := r.sizeParser.Decode(r.sizeBytes) return size, padding, err } var errSoft = newError("waiting for more data") func (r *AuthenticationReader) readBuffer(size int32, padding int32) (*buf.Buffer, error) { b := buf.New() if _, err := b.ReadFullFrom(r.reader, size); err != nil { b.Release() return nil, err } size -= padding rb, err := r.auth.Open(b.BytesTo(0), b.BytesTo(size)) if err != nil { b.Release() return nil, err } b.Resize(0, int32(len(rb))) return b, nil } func (r *AuthenticationReader) readInternal(soft bool, mb *buf.MultiBuffer) error { if soft && r.reader.BufferedBytes() < r.sizeParser.SizeBytes() { return errSoft } if r.done { return io.EOF } size, padding, err := r.readSize() if err != nil { return err } if size+r.sizeOffset == uint16(r.auth.Overhead())+padding { r.done = true return io.EOF } effectiveSize := int32(size) + int32(r.sizeOffset) if soft && effectiveSize > r.reader.BufferedBytes() { r.size = size r.paddingLen = padding r.hasSize = true return errSoft } if effectiveSize <= buf.Size { b, err := r.readBuffer(effectiveSize, int32(padding)) if err != nil { return err } *mb = append(*mb, b) return nil } payload := bytespool.Alloc(effectiveSize) defer bytespool.Free(payload) if _, err := io.ReadFull(r.reader, payload[:effectiveSize]); err != nil { return err } effectiveSize -= int32(padding) rb, err := r.auth.Open(payload[:0], payload[:effectiveSize]) if err != nil { return err } *mb = buf.MergeBytes(*mb, rb) return nil } func (r *AuthenticationReader) ReadMultiBuffer() (buf.MultiBuffer, error) { const readSize = 16 mb := make(buf.MultiBuffer, 0, readSize) if err := r.readInternal(false, &mb); err != nil { buf.ReleaseMulti(mb) return nil, err } for i := 1; i < readSize; i++ { err := r.readInternal(true, &mb) if err == errSoft || err == io.EOF { break } if err != nil { buf.ReleaseMulti(mb) return nil, err } } return mb, nil } type AuthenticationWriter struct { auth Authenticator writer buf.Writer sizeParser ChunkSizeEncoder transferType protocol.TransferType padding PaddingLengthGenerator } func NewAuthenticationWriter(auth Authenticator, sizeParser ChunkSizeEncoder, writer io.Writer, transferType protocol.TransferType, padding PaddingLengthGenerator) *AuthenticationWriter { w := &AuthenticationWriter{ auth: auth, writer: buf.NewWriter(writer), sizeParser: sizeParser, transferType: transferType, } if padding != nil { w.padding = padding } return w } func (w *AuthenticationWriter) seal(b []byte) (*buf.Buffer, error) { encryptedSize := int32(len(b) + w.auth.Overhead()) var paddingSize int32 if w.padding != nil { paddingSize = int32(w.padding.NextPaddingLen()) } sizeBytes := w.sizeParser.SizeBytes() totalSize := sizeBytes + encryptedSize + paddingSize if totalSize > buf.Size { return nil, newError("size too large: ", totalSize) } eb := buf.New() w.sizeParser.Encode(uint16(encryptedSize+paddingSize), eb.Extend(sizeBytes)) if _, err := w.auth.Seal(eb.Extend(encryptedSize)[:0], b); err != nil { eb.Release() return nil, err } if paddingSize > 0 { // These paddings will send in clear text. // To avoid leakage of PRNG internal state, a cryptographically secure PRNG should be used. paddingBytes := eb.Extend(paddingSize) common.Must2(rand.Read(paddingBytes)) } return eb, nil } func (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error { defer buf.ReleaseMulti(mb) var maxPadding int32 if w.padding != nil { maxPadding = int32(w.padding.MaxPaddingLen()) } payloadSize := buf.Size - int32(w.auth.Overhead()) - w.sizeParser.SizeBytes() - maxPadding if len(mb)+10 > 64*1024*1024 { return errors.New("value too large") } sliceSize := len(mb) + 10 mb2Write := make(buf.MultiBuffer, 0, sliceSize) temp := buf.New() defer temp.Release() rawBytes := temp.Extend(payloadSize) for { nb, nBytes := buf.SplitBytes(mb, rawBytes) mb = nb eb, err := w.seal(rawBytes[:nBytes]) if err != nil { buf.ReleaseMulti(mb2Write) return err } mb2Write = append(mb2Write, eb) if mb.IsEmpty() { break } } return w.writer.WriteMultiBuffer(mb2Write) } func (w *AuthenticationWriter) writePacket(mb buf.MultiBuffer) error { defer buf.ReleaseMulti(mb) if len(mb)+1 > 64*1024*1024 { return errors.New("value too large") } sliceSize := len(mb) + 1 mb2Write := make(buf.MultiBuffer, 0, sliceSize) for _, b := range mb { if b.IsEmpty() { continue } eb, err := w.seal(b.Bytes()) if err != nil { continue } mb2Write = append(mb2Write, eb) } if mb2Write.IsEmpty() { return nil } return w.writer.WriteMultiBuffer(mb2Write) } // WriteMultiBuffer implements buf.Writer. func (w *AuthenticationWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { if mb.IsEmpty() { eb, err := w.seal([]byte{}) common.Must(err) return w.writer.WriteMultiBuffer(buf.MultiBuffer{eb}) } if w.transferType == protocol.TransferTypeStream { return w.writeStream(mb) } return w.writePacket(mb) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/chunk.go
common/crypto/chunk.go
package crypto import ( "encoding/binary" "io" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" ) // ChunkSizeDecoder is a utility class to decode size value from bytes. type ChunkSizeDecoder interface { // SizeBytes must be stable, return the same value across all calls SizeBytes() int32 Decode([]byte) (uint16, error) } type ChunkSizeDecoderWithOffset interface { ChunkSizeDecoder // HasConstantOffset set the constant offset of Decode // The effective size should be HasConstantOffset() + Decode(_).[0](uint64) HasConstantOffset() uint16 } // ChunkSizeEncoder is a utility class to encode size value into bytes. type ChunkSizeEncoder interface { SizeBytes() int32 Encode(uint16, []byte) []byte } type PaddingLengthGenerator interface { MaxPaddingLen() uint16 NextPaddingLen() uint16 } type PlainChunkSizeParser struct{} func (PlainChunkSizeParser) SizeBytes() int32 { return 2 } func (PlainChunkSizeParser) Encode(size uint16, b []byte) []byte { binary.BigEndian.PutUint16(b, size) return b[:2] } func (PlainChunkSizeParser) Decode(b []byte) (uint16, error) { return binary.BigEndian.Uint16(b), nil } type AEADChunkSizeParser struct { Auth *AEADAuthenticator } func (p *AEADChunkSizeParser) SizeBytes() int32 { return 2 + int32(p.Auth.Overhead()) } func (p *AEADChunkSizeParser) Encode(size uint16, b []byte) []byte { binary.BigEndian.PutUint16(b, size-uint16(p.Auth.Overhead())) b, err := p.Auth.Seal(b[:0], b[:2]) common.Must(err) return b } func (p *AEADChunkSizeParser) Decode(b []byte) (uint16, error) { b, err := p.Auth.Open(b[:0], b) if err != nil { return 0, err } return binary.BigEndian.Uint16(b) + uint16(p.Auth.Overhead()), nil } type ChunkStreamReader struct { sizeDecoder ChunkSizeDecoder reader *buf.BufferedReader buffer []byte leftOverSize int32 maxNumChunk uint32 numChunk uint32 } func NewChunkStreamReader(sizeDecoder ChunkSizeDecoder, reader io.Reader) *ChunkStreamReader { return NewChunkStreamReaderWithChunkCount(sizeDecoder, reader, 0) } func NewChunkStreamReaderWithChunkCount(sizeDecoder ChunkSizeDecoder, reader io.Reader, maxNumChunk uint32) *ChunkStreamReader { r := &ChunkStreamReader{ sizeDecoder: sizeDecoder, buffer: make([]byte, sizeDecoder.SizeBytes()), maxNumChunk: maxNumChunk, } if breader, ok := reader.(*buf.BufferedReader); ok { r.reader = breader } else { r.reader = &buf.BufferedReader{Reader: buf.NewReader(reader)} } return r } func (r *ChunkStreamReader) readSize() (uint16, error) { if _, err := io.ReadFull(r.reader, r.buffer); err != nil { return 0, err } return r.sizeDecoder.Decode(r.buffer) } func (r *ChunkStreamReader) ReadMultiBuffer() (buf.MultiBuffer, error) { size := r.leftOverSize if size == 0 { r.numChunk++ if r.maxNumChunk > 0 && r.numChunk > r.maxNumChunk { return nil, io.EOF } nextSize, err := r.readSize() if err != nil { return nil, err } if nextSize == 0 { return nil, io.EOF } size = int32(nextSize) } r.leftOverSize = size mb, err := r.reader.ReadAtMost(size) if !mb.IsEmpty() { r.leftOverSize -= mb.Len() return mb, nil } return nil, err } type ChunkStreamWriter struct { sizeEncoder ChunkSizeEncoder writer buf.Writer } func NewChunkStreamWriter(sizeEncoder ChunkSizeEncoder, writer io.Writer) *ChunkStreamWriter { return &ChunkStreamWriter{ sizeEncoder: sizeEncoder, writer: buf.NewWriter(writer), } } func (w *ChunkStreamWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { const sliceSize = 8192 mbLen := mb.Len() mb2Write := make(buf.MultiBuffer, 0, mbLen/buf.Size+mbLen/sliceSize+2) for { mb2, slice := buf.SplitSize(mb, sliceSize) mb = mb2 b := buf.New() w.sizeEncoder.Encode(uint16(slice.Len()), b.Extend(w.sizeEncoder.SizeBytes())) mb2Write = append(mb2Write, b) mb2Write = append(mb2Write, slice...) if mb.IsEmpty() { break } } return w.writer.WriteMultiBuffer(mb2Write) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/auth_test.go
common/crypto/auth_test.go
package crypto_test import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "io" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" . "github.com/v2fly/v2ray-core/v5/common/crypto" "github.com/v2fly/v2ray-core/v5/common/protocol" ) func TestAuthenticationReaderWriter(t *testing.T) { key := make([]byte, 16) rand.Read(key) block, err := aes.NewCipher(key) common.Must(err) aead, err := cipher.NewGCM(block) common.Must(err) const payloadSize = 1024 * 80 rawPayload := make([]byte, payloadSize) rand.Read(rawPayload) payload := buf.MergeBytes(nil, rawPayload) cache := bytes.NewBuffer(nil) iv := make([]byte, 12) rand.Read(iv) writer := NewAuthenticationWriter(&AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateStaticBytes(iv), AdditionalDataGenerator: GenerateEmptyBytes(), }, PlainChunkSizeParser{}, cache, protocol.TransferTypeStream, nil) common.Must(writer.WriteMultiBuffer(payload)) if cache.Len() <= 1024*80 { t.Error("cache len: ", cache.Len()) } common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{})) reader := NewAuthenticationReader(&AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateStaticBytes(iv), AdditionalDataGenerator: GenerateEmptyBytes(), }, PlainChunkSizeParser{}, cache, protocol.TransferTypeStream, nil) var mb buf.MultiBuffer for mb.Len() < payloadSize { mb2, err := reader.ReadMultiBuffer() common.Must(err) mb, _ = buf.MergeMulti(mb, mb2) } if mb.Len() != payloadSize { t.Error("mb len: ", mb.Len()) } mbContent := make([]byte, payloadSize) buf.SplitBytes(mb, mbContent) if r := cmp.Diff(mbContent, rawPayload); r != "" { t.Error(r) } _, err = reader.ReadMultiBuffer() if err != io.EOF { t.Error("error: ", err) } } func TestAuthenticationReaderWriterPacket(t *testing.T) { key := make([]byte, 16) common.Must2(rand.Read(key)) block, err := aes.NewCipher(key) common.Must(err) aead, err := cipher.NewGCM(block) common.Must(err) cache := buf.New() iv := make([]byte, 12) rand.Read(iv) writer := NewAuthenticationWriter(&AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateStaticBytes(iv), AdditionalDataGenerator: GenerateEmptyBytes(), }, PlainChunkSizeParser{}, cache, protocol.TransferTypePacket, nil) var payload buf.MultiBuffer pb1 := buf.New() pb1.Write([]byte("abcd")) payload = append(payload, pb1) pb2 := buf.New() pb2.Write([]byte("efgh")) payload = append(payload, pb2) common.Must(writer.WriteMultiBuffer(payload)) if cache.Len() == 0 { t.Error("cache len: ", cache.Len()) } common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{})) reader := NewAuthenticationReader(&AEADAuthenticator{ AEAD: aead, NonceGenerator: GenerateStaticBytes(iv), AdditionalDataGenerator: GenerateEmptyBytes(), }, PlainChunkSizeParser{}, cache, protocol.TransferTypePacket, nil) mb, err := reader.ReadMultiBuffer() common.Must(err) mb, b1 := buf.SplitFirst(mb) if b1.String() != "abcd" { t.Error("b1: ", b1.String()) } mb, b2 := buf.SplitFirst(mb) if b2.String() != "efgh" { t.Error("b2: ", b2.String()) } if !mb.IsEmpty() { t.Error("not empty") } _, err = reader.ReadMultiBuffer() if err != io.EOF { t.Error("error: ", err) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/internal/chacha_core_gen.go
common/crypto/internal/chacha_core_gen.go
//go:build generate // +build generate package main import ( "fmt" "log" "os" ) func writeQuarterRound(file *os.File, a, b, c, d int) { add := "x%d+=x%d\n" xor := "x=x%d^x%d\n" rotate := "x%d=(x << %d) | (x >> (32 - %d))\n" fmt.Fprintf(file, add, a, b) fmt.Fprintf(file, xor, d, a) fmt.Fprintf(file, rotate, d, 16, 16) fmt.Fprintf(file, add, c, d) fmt.Fprintf(file, xor, b, c) fmt.Fprintf(file, rotate, b, 12, 12) fmt.Fprintf(file, add, a, b) fmt.Fprintf(file, xor, d, a) fmt.Fprintf(file, rotate, d, 8, 8) fmt.Fprintf(file, add, c, d) fmt.Fprintf(file, xor, b, c) fmt.Fprintf(file, rotate, b, 7, 7) } func writeChacha20Block(file *os.File) { fmt.Fprintln(file, ` func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { var x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15 = s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],s[12],s[13],s[14],s[15] for i := 0; i < rounds; i+=2 { var x uint32 `) writeQuarterRound(file, 0, 4, 8, 12) writeQuarterRound(file, 1, 5, 9, 13) writeQuarterRound(file, 2, 6, 10, 14) writeQuarterRound(file, 3, 7, 11, 15) writeQuarterRound(file, 0, 5, 10, 15) writeQuarterRound(file, 1, 6, 11, 12) writeQuarterRound(file, 2, 7, 8, 13) writeQuarterRound(file, 3, 4, 9, 14) fmt.Fprintln(file, "}") for i := 0; i < 16; i++ { fmt.Fprintf(file, "binary.LittleEndian.PutUint32(out[%d:%d], s[%d]+x%d)\n", i*4, i*4+4, i, i) } fmt.Fprintln(file, "}") fmt.Fprintln(file) } func main() { file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644) if err != nil { log.Fatalf("Failed to generate chacha_core.go: %v", err) } defer file.Close() fmt.Fprintln(file, "package internal") fmt.Fprintln(file) fmt.Fprintln(file, "import \"encoding/binary\"") fmt.Fprintln(file) writeChacha20Block(file) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/internal/chacha.go
common/crypto/internal/chacha.go
package internal //go:generate go run chacha_core_gen.go import ( "encoding/binary" ) const ( wordSize = 4 // the size of ChaCha20's words stateSize = 16 // the size of ChaCha20's state, in words blockSize = stateSize * wordSize // the size of ChaCha20's block, in bytes ) type ChaCha20Stream struct { state [stateSize]uint32 // the state as an array of 16 32-bit words block [blockSize]byte // the keystream as an array of 64 bytes offset int // the offset of used bytes in block rounds int } func NewChaCha20Stream(key []byte, nonce []byte, rounds int) *ChaCha20Stream { s := new(ChaCha20Stream) // the magic constants for 256-bit keys s.state[0] = 0x61707865 s.state[1] = 0x3320646e s.state[2] = 0x79622d32 s.state[3] = 0x6b206574 for i := 0; i < 8; i++ { s.state[i+4] = binary.LittleEndian.Uint32(key[i*4 : i*4+4]) } switch len(nonce) { case 8: s.state[14] = binary.LittleEndian.Uint32(nonce[0:]) s.state[15] = binary.LittleEndian.Uint32(nonce[4:]) case 12: s.state[13] = binary.LittleEndian.Uint32(nonce[0:4]) s.state[14] = binary.LittleEndian.Uint32(nonce[4:8]) s.state[15] = binary.LittleEndian.Uint32(nonce[8:12]) default: panic("bad nonce length") } s.rounds = rounds ChaCha20Block(&s.state, s.block[:], s.rounds) return s } func (s *ChaCha20Stream) XORKeyStream(dst, src []byte) { // Stride over the input in 64-byte blocks, minus the amount of keystream // previously used. This will produce best results when processing blocks // of a size evenly divisible by 64. i := 0 max := len(src) for i < max { gap := blockSize - s.offset limit := i + gap if limit > max { limit = max } o := s.offset for j := i; j < limit; j++ { dst[j] = src[j] ^ s.block[o] o++ } i += gap s.offset = o if o == blockSize { s.offset = 0 s.state[12]++ ChaCha20Block(&s.state, s.block[:], s.rounds) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/crypto/internal/chacha_core.generated.go
common/crypto/internal/chacha_core.generated.go
package internal import "encoding/binary" func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 := s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15] for i := 0; i < rounds; i += 2 { var x uint32 x0 += x4 x = x12 ^ x0 x12 = (x << 16) | (x >> (32 - 16)) x8 += x12 x = x4 ^ x8 x4 = (x << 12) | (x >> (32 - 12)) x0 += x4 x = x12 ^ x0 x12 = (x << 8) | (x >> (32 - 8)) x8 += x12 x = x4 ^ x8 x4 = (x << 7) | (x >> (32 - 7)) x1 += x5 x = x13 ^ x1 x13 = (x << 16) | (x >> (32 - 16)) x9 += x13 x = x5 ^ x9 x5 = (x << 12) | (x >> (32 - 12)) x1 += x5 x = x13 ^ x1 x13 = (x << 8) | (x >> (32 - 8)) x9 += x13 x = x5 ^ x9 x5 = (x << 7) | (x >> (32 - 7)) x2 += x6 x = x14 ^ x2 x14 = (x << 16) | (x >> (32 - 16)) x10 += x14 x = x6 ^ x10 x6 = (x << 12) | (x >> (32 - 12)) x2 += x6 x = x14 ^ x2 x14 = (x << 8) | (x >> (32 - 8)) x10 += x14 x = x6 ^ x10 x6 = (x << 7) | (x >> (32 - 7)) x3 += x7 x = x15 ^ x3 x15 = (x << 16) | (x >> (32 - 16)) x11 += x15 x = x7 ^ x11 x7 = (x << 12) | (x >> (32 - 12)) x3 += x7 x = x15 ^ x3 x15 = (x << 8) | (x >> (32 - 8)) x11 += x15 x = x7 ^ x11 x7 = (x << 7) | (x >> (32 - 7)) x0 += x5 x = x15 ^ x0 x15 = (x << 16) | (x >> (32 - 16)) x10 += x15 x = x5 ^ x10 x5 = (x << 12) | (x >> (32 - 12)) x0 += x5 x = x15 ^ x0 x15 = (x << 8) | (x >> (32 - 8)) x10 += x15 x = x5 ^ x10 x5 = (x << 7) | (x >> (32 - 7)) x1 += x6 x = x12 ^ x1 x12 = (x << 16) | (x >> (32 - 16)) x11 += x12 x = x6 ^ x11 x6 = (x << 12) | (x >> (32 - 12)) x1 += x6 x = x12 ^ x1 x12 = (x << 8) | (x >> (32 - 8)) x11 += x12 x = x6 ^ x11 x6 = (x << 7) | (x >> (32 - 7)) x2 += x7 x = x13 ^ x2 x13 = (x << 16) | (x >> (32 - 16)) x8 += x13 x = x7 ^ x8 x7 = (x << 12) | (x >> (32 - 12)) x2 += x7 x = x13 ^ x2 x13 = (x << 8) | (x >> (32 - 8)) x8 += x13 x = x7 ^ x8 x7 = (x << 7) | (x >> (32 - 7)) x3 += x4 x = x14 ^ x3 x14 = (x << 16) | (x >> (32 - 16)) x9 += x14 x = x4 ^ x9 x4 = (x << 12) | (x >> (32 - 12)) x3 += x4 x = x14 ^ x3 x14 = (x << 8) | (x >> (32 - 8)) x9 += x14 x = x4 ^ x9 x4 = (x << 7) | (x >> (32 - 7)) } binary.LittleEndian.PutUint32(out[0:4], s[0]+x0) binary.LittleEndian.PutUint32(out[4:8], s[1]+x1) binary.LittleEndian.PutUint32(out[8:12], s[2]+x2) binary.LittleEndian.PutUint32(out[12:16], s[3]+x3) binary.LittleEndian.PutUint32(out[16:20], s[4]+x4) binary.LittleEndian.PutUint32(out[20:24], s[5]+x5) binary.LittleEndian.PutUint32(out[24:28], s[6]+x6) binary.LittleEndian.PutUint32(out[28:32], s[7]+x7) binary.LittleEndian.PutUint32(out[32:36], s[8]+x8) binary.LittleEndian.PutUint32(out[36:40], s[9]+x9) binary.LittleEndian.PutUint32(out[40:44], s[10]+x10) binary.LittleEndian.PutUint32(out[44:48], s[11]+x11) binary.LittleEndian.PutUint32(out[48:52], s[12]+x12) binary.LittleEndian.PutUint32(out[52:56], s[13]+x13) binary.LittleEndian.PutUint32(out[56:60], s[14]+x14) binary.LittleEndian.PutUint32(out[60:64], s[15]+x15) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_mph.go
common/strmatcher/matchergroup_mph.go
package strmatcher import ( "math/bits" "sort" "strings" "unsafe" ) // PrimeRK is the prime base used in Rabin-Karp algorithm. const PrimeRK = 16777619 // RollingHash calculates the rolling murmurHash of given string based on a provided suffix hash. func RollingHash(hash uint32, input string) uint32 { for i := len(input) - 1; i >= 0; i-- { hash = hash*PrimeRK + uint32(input[i]) } return hash } // MemHash is the hash function used by go map, it utilizes available hardware instructions(behaves // as aeshash if aes instruction is available). // With different seed, each MemHash<seed> performs as distinct hash functions. func MemHash(seed uint32, input string) uint32 { return uint32(strhash(unsafe.Pointer(&input), uintptr(seed))) // nosemgrep } const ( mphMatchTypeCount = 2 // Full and Domain ) type mphRuleInfo struct { rollingHash uint32 matchers [mphMatchTypeCount][]uint32 } // MphMatcherGroup is an implementation of MatcherGroup. // It implements Rabin-Karp algorithm and minimal perfect hash table for Full and Domain matcher. type MphMatcherGroup struct { rules []string // RuleIdx -> pattern string, index 0 reserved for failed lookup values [][]uint32 // RuleIdx -> registered matcher values for the pattern (Full Matcher takes precedence) level0 []uint32 // RollingHash & Mask -> seed for Memhash level0Mask uint32 // Mask restricting RollingHash to 0 ~ len(level0) level1 []uint32 // Memhash<seed> & Mask -> stored index for rules level1Mask uint32 // Mask for restricting Memhash<seed> to 0 ~ len(level1) ruleInfos *map[string]mphRuleInfo } func NewMphMatcherGroup() *MphMatcherGroup { return &MphMatcherGroup{ rules: []string{""}, values: [][]uint32{nil}, level0: nil, level0Mask: 0, level1: nil, level1Mask: 0, ruleInfos: &map[string]mphRuleInfo{}, // Only used for building, destroyed after build complete } } // AddFullMatcher implements MatcherGroupForFull. func (g *MphMatcherGroup) AddFullMatcher(matcher FullMatcher, value uint32) { pattern := strings.ToLower(matcher.Pattern()) g.addPattern(0, "", pattern, matcher.Type(), value) } // AddDomainMatcher implements MatcherGroupForDomain. func (g *MphMatcherGroup) AddDomainMatcher(matcher DomainMatcher, value uint32) { pattern := strings.ToLower(matcher.Pattern()) hash := g.addPattern(0, "", pattern, matcher.Type(), value) // For full domain match g.addPattern(hash, pattern, ".", matcher.Type(), value) // For partial domain match } func (g *MphMatcherGroup) addPattern(suffixHash uint32, suffixPattern string, pattern string, matcherType Type, value uint32) uint32 { fullPattern := pattern + suffixPattern info, found := (*g.ruleInfos)[fullPattern] if !found { info = mphRuleInfo{rollingHash: RollingHash(suffixHash, pattern)} g.rules = append(g.rules, fullPattern) g.values = append(g.values, nil) } info.matchers[matcherType] = append(info.matchers[matcherType], value) (*g.ruleInfos)[fullPattern] = info return info.rollingHash } // Build builds a minimal perfect hash table for insert rules. // Algorithm used: Hash, displace, and compress. See http://cmph.sourceforge.net/papers/esa09.pdf func (g *MphMatcherGroup) Build() error { ruleCount := len(*g.ruleInfos) g.level0 = make([]uint32, nextPow2(ruleCount/4)) g.level0Mask = uint32(len(g.level0) - 1) g.level1 = make([]uint32, nextPow2(ruleCount)) g.level1Mask = uint32(len(g.level1) - 1) // Create buckets based on all rule's rolling hash buckets := make([][]uint32, len(g.level0)) for ruleIdx := 1; ruleIdx < len(g.rules); ruleIdx++ { // Traverse rules starting from index 1 (0 reserved for failed lookup) ruleInfo := (*g.ruleInfos)[g.rules[ruleIdx]] bucketIdx := ruleInfo.rollingHash & g.level0Mask buckets[bucketIdx] = append(buckets[bucketIdx], uint32(ruleIdx)) g.values[ruleIdx] = append(ruleInfo.matchers[Full], ruleInfo.matchers[Domain]...) // nolint:gocritic } g.ruleInfos = nil // Set ruleInfos nil to release memory // Sort buckets in descending order with respect to each bucket's size bucketIdxs := make([]int, len(buckets)) for bucketIdx := range buckets { bucketIdxs[bucketIdx] = bucketIdx } sort.Slice(bucketIdxs, func(i, j int) bool { return len(buckets[bucketIdxs[i]]) > len(buckets[bucketIdxs[j]]) }) // Exercise Hash, Displace, and Compress algorithm to construct minimal perfect hash table occupied := make([]bool, len(g.level1)) // Whether a second-level hash has been already used hashedBucket := make([]uint32, 0, 4) // Second-level hashes for each rule in a specific bucket for _, bucketIdx := range bucketIdxs { bucket := buckets[bucketIdx] hashedBucket = hashedBucket[:0] seed := uint32(0) for len(hashedBucket) != len(bucket) { for _, ruleIdx := range bucket { memHash := MemHash(seed, g.rules[ruleIdx]) & g.level1Mask if occupied[memHash] { // Collision occurred with this seed for _, hash := range hashedBucket { // Revert all values in this hashed bucket occupied[hash] = false g.level1[hash] = 0 } hashedBucket = hashedBucket[:0] seed++ // Try next seed break } occupied[memHash] = true g.level1[memHash] = ruleIdx // The final value in the hash table hashedBucket = append(hashedBucket, memHash) } } g.level0[bucketIdx] = seed // Displacement value for this bucket } return nil } // Lookup searches for input in minimal perfect hash table and returns its index. 0 indicates not found. func (g *MphMatcherGroup) Lookup(rollingHash uint32, input string) uint32 { i0 := rollingHash & g.level0Mask seed := g.level0[i0] i1 := MemHash(seed, input) & g.level1Mask if n := g.level1[i1]; g.rules[n] == input { return n } return 0 } // Match implements MatcherGroup.Match. func (g *MphMatcherGroup) Match(input string) []uint32 { matches := make([][]uint32, 0, 5) hash := uint32(0) for i := len(input) - 1; i >= 0; i-- { hash = hash*PrimeRK + uint32(input[i]) if input[i] == '.' { if mphIdx := g.Lookup(hash, input[i:]); mphIdx != 0 { matches = append(matches, g.values[mphIdx]) } } } if mphIdx := g.Lookup(hash, input); mphIdx != 0 { matches = append(matches, g.values[mphIdx]) } return CompositeMatchesReverse(matches) } // MatchAny implements MatcherGroup.MatchAny. func (g *MphMatcherGroup) MatchAny(input string) bool { hash := uint32(0) for i := len(input) - 1; i >= 0; i-- { hash = hash*PrimeRK + uint32(input[i]) if input[i] == '.' { if g.Lookup(hash, input[i:]) != 0 { return true } } } return g.Lookup(hash, input) != 0 } func nextPow2(v int) int { if v <= 1 { return 1 } const MaxUInt = ^uint(0) n := (MaxUInt >> bits.LeadingZeros(uint(v))) + 1 return int(n) } //go:noescape //go:linkname strhash runtime.strhash func strhash(p unsafe.Pointer, h uintptr) uintptr
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/indexmatcher_mph_test.go
common/strmatcher/indexmatcher_mph_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestMphIndexMatcher(t *testing.T) { rules := []struct { Type Type Domain string }{ { Type: Regex, Domain: "apis\\.us$", }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Domain, Domain: "com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Full, Domain: "fonts.googleapis.com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Domain, Domain: "example.com", }, } cases := []struct { Input string Output []uint32 }{ { Input: "www.baidu.com", Output: []uint32{5, 9, 4}, }, { Input: "fonts.googleapis.com", Output: []uint32{8, 3, 7, 4, 2, 6}, }, { Input: "example.googleapis.com", Output: []uint32{3, 7, 4, 2, 6}, }, { Input: "testapis.us", Output: []uint32{2, 6, 1}, }, { Input: "example.com", Output: []uint32{10, 4}, }, } matcherGroup := NewMphIndexMatcher() for _, rule := range rules { matcher, err := rule.Type.New(rule.Domain) common.Must(err) matcherGroup.Add(matcher) } matcherGroup.Build() for _, test := range cases { if m := matcherGroup.Match(test.Input); !reflect.DeepEqual(m, test.Output) { t.Error("unexpected output: ", m, " for test case ", test) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchers_test.go
common/strmatcher/matchers_test.go
package strmatcher_test import ( "reflect" "testing" "unsafe" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestMatcher(t *testing.T) { cases := []struct { pattern string mType Type input string output bool }{ { pattern: "v2fly.org", mType: Domain, input: "www.v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "www.v3fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "2fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "xv2fly.org", output: false, }, { pattern: "v2fly.org", mType: Full, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Full, input: "xv2fly.org", output: false, }, { pattern: "v2fly.org", mType: Regex, input: "v2flyxorg", output: true, }, } for _, test := range cases { matcher, err := test.mType.New(test.pattern) common.Must(err) if m := matcher.Match(test.input); m != test.output { t.Error("unexpected output: ", m, " for test case ", test) } } } func TestToDomain(t *testing.T) { { // Test normal ASCII domain, which should not trigger new string data allocation input := "v2fly.org" domain, err := ToDomain(input) if err != nil { t.Error("unexpected error: ", err) } if domain != input { t.Error("unexpected output: ", domain, " for test case ", input) } if (*reflect.StringHeader)(unsafe.Pointer(&input)).Data != (*reflect.StringHeader)(unsafe.Pointer(&domain)).Data { t.Error("different string data of output: ", domain, " and test case ", input) } } { // Test ASCII domain containing upper case letter, which should be converted to lower case input := "v2FLY.oRg" domain, err := ToDomain(input) if err != nil { t.Error("unexpected error: ", err) } if domain != "v2fly.org" { t.Error("unexpected output: ", domain, " for test case ", input) } } { // Test internationalized domain, which should be translated to ASCII punycode input := "v2fly.公益" domain, err := ToDomain(input) if err != nil { t.Error("unexpected error: ", err) } if domain != "v2fly.xn--55qw42g" { t.Error("unexpected output: ", domain, " for test case ", input) } } { // Test internationalized domain containing upper case letter input := "v2FLY.公益" domain, err := ToDomain(input) if err != nil { t.Error("unexpected error: ", err) } if domain != "v2fly.xn--55qw42g" { t.Error("unexpected output: ", domain, " for test case ", input) } } { // Test domain name of invalid character, which should return with error input := "{" _, err := ToDomain(input) if err == nil { t.Error("unexpected non error for test case ", input) } } { // Test domain name containing a space, which should return with error input := "Mijia Cloud" _, err := ToDomain(input) if err == nil { t.Error("unexpected non error for test case ", input) } } { // Test domain name containing an underscore, which should return with error input := "Mijia_Cloud.com" _, err := ToDomain(input) if err == nil { t.Error("unexpected non error for test case ", input) } } { // Test internationalized domain containing invalid character input := "Mijia Cloud.公司" _, err := ToDomain(input) if err == nil { t.Error("unexpected non error for test case ", input) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_simple_test.go
common/strmatcher/matchergroup_simple_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestSimpleMatcherGroup(t *testing.T) { patterns := []struct { pattern string mType Type }{ { pattern: "v2fly.org", mType: Domain, }, { pattern: "v2fly.org", mType: Full, }, { pattern: "v2fly.org", mType: Regex, }, } cases := []struct { input string output []uint32 }{ { input: "www.v2fly.org", output: []uint32{0, 2}, }, { input: "v2fly.org", output: []uint32{0, 1, 2}, }, { input: "www.v3fly.org", output: []uint32{}, }, { input: "2fly.org", output: []uint32{}, }, { input: "xv2fly.org", output: []uint32{2}, }, { input: "v2flyxorg", output: []uint32{2}, }, } matcherGroup := &SimpleMatcherGroup{} for id, entry := range patterns { matcher, err := entry.mType.New(entry.pattern) common.Must(err) common.Must(AddMatcherToGroup(matcherGroup, matcher, uint32(id))) } for _, test := range cases { if r := matcherGroup.Match(test.input); !reflect.DeepEqual(r, test.output) { t.Error("unexpected output: ", r, " for test case ", test) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_substr_test.go
common/strmatcher/matchergroup_substr_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestSubstrMatcherGroup(t *testing.T) { patterns := []struct { pattern string mType Type }{ { pattern: "apis", mType: Substr, }, { pattern: "google", mType: Substr, }, { pattern: "apis", mType: Substr, }, } cases := []struct { input string output []uint32 }{ { input: "google.com", output: []uint32{1}, }, { input: "apis.com", output: []uint32{0, 2}, }, { input: "googleapis.com", output: []uint32{1, 0, 2}, }, { input: "fonts.googleapis.com", output: []uint32{1, 0, 2}, }, { input: "apis.googleapis.com", output: []uint32{0, 2, 1, 0, 2}, }, } matcherGroup := &SubstrMatcherGroup{} for id, entry := range patterns { matcher, err := entry.mType.New(entry.pattern) common.Must(err) common.Must(AddMatcherToGroup(matcherGroup, matcher, uint32(id))) } for _, test := range cases { if r := matcherGroup.Match(test.input); !reflect.DeepEqual(r, test.output) { t.Error("unexpected output: ", r, " for test case ", test) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_domain_test.go
common/strmatcher/matchergroup_domain_test.go
package strmatcher_test import ( "reflect" "testing" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestDomainMatcherGroup(t *testing.T) { patterns := []struct { Pattern string Value uint32 }{ { Pattern: "v2fly.org", Value: 1, }, { Pattern: "google.com", Value: 2, }, { Pattern: "x.a.com", Value: 3, }, { Pattern: "a.b.com", Value: 4, }, { Pattern: "c.a.b.com", Value: 5, }, { Pattern: "x.y.com", Value: 4, }, { Pattern: "x.y.com", Value: 6, }, } testCases := []struct { Domain string Result []uint32 }{ { Domain: "x.v2fly.org", Result: []uint32{1}, }, { Domain: "y.com", Result: nil, }, { Domain: "a.b.com", Result: []uint32{4}, }, { // Matches [c.a.b.com, a.b.com] Domain: "c.a.b.com", Result: []uint32{5, 4}, }, { Domain: "c.a..b.com", Result: nil, }, { Domain: ".com", Result: nil, }, { Domain: "com", Result: nil, }, { Domain: "", Result: nil, }, { Domain: "x.y.com", Result: []uint32{4, 6}, }, } g := NewDomainMatcherGroup() for _, pattern := range patterns { AddMatcherToGroup(g, DomainMatcher(pattern.Pattern), pattern.Value) } for _, testCase := range testCases { r := g.Match(testCase.Domain) if !reflect.DeepEqual(r, testCase.Result) { t.Error("Failed to match domain: ", testCase.Domain, ", expect ", testCase.Result, ", but got ", r) } } } func TestEmptyDomainMatcherGroup(t *testing.T) { g := NewDomainMatcherGroup() r := g.Match("v2fly.org") if len(r) != 0 { t.Error("Expect [], but ", r) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchers.go
common/strmatcher/matchers.go
package strmatcher import ( "errors" "regexp" "strings" "unicode/utf8" "golang.org/x/net/idna" ) // FullMatcher is an implementation of Matcher. type FullMatcher string func (FullMatcher) Type() Type { return Full } func (m FullMatcher) Pattern() string { return string(m) } func (m FullMatcher) String() string { return "full:" + m.Pattern() } func (m FullMatcher) Match(s string) bool { return string(m) == s } // DomainMatcher is an implementation of Matcher. type DomainMatcher string func (DomainMatcher) Type() Type { return Domain } func (m DomainMatcher) Pattern() string { return string(m) } func (m DomainMatcher) String() string { return "domain:" + m.Pattern() } func (m DomainMatcher) Match(s string) bool { pattern := m.Pattern() if !strings.HasSuffix(s, pattern) { return false } return len(s) == len(pattern) || s[len(s)-len(pattern)-1] == '.' } // SubstrMatcher is an implementation of Matcher. type SubstrMatcher string func (SubstrMatcher) Type() Type { return Substr } func (m SubstrMatcher) Pattern() string { return string(m) } func (m SubstrMatcher) String() string { return "keyword:" + m.Pattern() } func (m SubstrMatcher) Match(s string) bool { return strings.Contains(s, m.Pattern()) } // RegexMatcher is an implementation of Matcher. type RegexMatcher struct { pattern *regexp.Regexp } func (*RegexMatcher) Type() Type { return Regex } func (m *RegexMatcher) Pattern() string { return m.pattern.String() } func (m *RegexMatcher) String() string { return "regexp:" + m.Pattern() } func (m *RegexMatcher) Match(s string) bool { return m.pattern.MatchString(s) } // New creates a new Matcher based on the given pattern. func (t Type) New(pattern string) (Matcher, error) { switch t { case Full: return FullMatcher(pattern), nil case Substr: return SubstrMatcher(pattern), nil case Domain: pattern, err := ToDomain(pattern) if err != nil { return nil, err } return DomainMatcher(pattern), nil case Regex: // 1. regex matching is case-sensitive regex, err := regexp.Compile(pattern) if err != nil { return nil, err } return &RegexMatcher{pattern: regex}, nil default: return nil, errors.New("unknown matcher type") } } // NewDomainPattern creates a new Matcher based on the given domain pattern. // It works like `Type.New`, but will do validation and conversion to ensure it's a valid domain pattern. func (t Type) NewDomainPattern(pattern string) (Matcher, error) { switch t { case Full: pattern, err := ToDomain(pattern) if err != nil { return nil, err } return FullMatcher(pattern), nil case Substr: pattern, err := ToDomain(pattern) if err != nil { return nil, err } return SubstrMatcher(pattern), nil case Domain: pattern, err := ToDomain(pattern) if err != nil { return nil, err } return DomainMatcher(pattern), nil case Regex: // Regex's charset not in LDH subset regex, err := regexp.Compile(pattern) if err != nil { return nil, err } return &RegexMatcher{pattern: regex}, nil default: return nil, errors.New("unknown matcher type") } } // ToDomain converts input pattern to a domain string, and return error if such a conversion cannot be made. // 1. Conforms to Letter-Digit-Hyphen (LDH) subset (https://tools.ietf.org/html/rfc952): // * Letters A to Z (no distinction between uppercase and lowercase, we convert to lowers) // * Digits 0 to 9 // * Hyphens(-) and Periods(.) // 2. If any non-ASCII characters, domain are converted from Internationalized domain name to Punycode. func ToDomain(pattern string) (string, error) { for { isASCII, hasUpper := true, false for i := 0; i < len(pattern); i++ { c := pattern[i] if c >= utf8.RuneSelf { isASCII = false break } switch { case 'A' <= c && c <= 'Z': hasUpper = true case 'a' <= c && c <= 'z': case '0' <= c && c <= '9': case c == '-': case c == '.': default: return "", errors.New("pattern string does not conform to Letter-Digit-Hyphen (LDH) subset") } } if !isASCII { var err error pattern, err = idna.Punycode.ToASCII(pattern) if err != nil { return "", err } continue } if hasUpper { pattern = strings.ToLower(pattern) } break } return pattern, nil } // MatcherGroupForAll is an interface indicating a MatcherGroup could accept all types of matchers. type MatcherGroupForAll interface { AddMatcher(matcher Matcher, value uint32) } // MatcherGroupForFull is an interface indicating a MatcherGroup could accept FullMatchers. type MatcherGroupForFull interface { AddFullMatcher(matcher FullMatcher, value uint32) } // MatcherGroupForDomain is an interface indicating a MatcherGroup could accept DomainMatchers. type MatcherGroupForDomain interface { AddDomainMatcher(matcher DomainMatcher, value uint32) } // MatcherGroupForSubstr is an interface indicating a MatcherGroup could accept SubstrMatchers. type MatcherGroupForSubstr interface { AddSubstrMatcher(matcher SubstrMatcher, value uint32) } // MatcherGroupForRegex is an interface indicating a MatcherGroup could accept RegexMatchers. type MatcherGroupForRegex interface { AddRegexMatcher(matcher *RegexMatcher, value uint32) } // AddMatcherToGroup is a helper function to try to add a Matcher to any kind of MatcherGroup. // It returns error if the MatcherGroup does not accept the provided Matcher's type. // This function is provided to help writing code to test a MatcherGroup. func AddMatcherToGroup(g MatcherGroup, matcher Matcher, value uint32) error { if g, ok := g.(IndexMatcher); ok { g.Add(matcher) return nil } if g, ok := g.(MatcherGroupForAll); ok { g.AddMatcher(matcher, value) return nil } switch matcher := matcher.(type) { case FullMatcher: if g, ok := g.(MatcherGroupForFull); ok { g.AddFullMatcher(matcher, value) return nil } case DomainMatcher: if g, ok := g.(MatcherGroupForDomain); ok { g.AddDomainMatcher(matcher, value) return nil } case SubstrMatcher: if g, ok := g.(MatcherGroupForSubstr); ok { g.AddSubstrMatcher(matcher, value) return nil } case *RegexMatcher: if g, ok := g.(MatcherGroupForRegex); ok { g.AddRegexMatcher(matcher, value) return nil } } return errors.New("cannot add matcher to matcher group") } // CompositeMatches flattens the matches slice to produce a single matched indices slice. // It is designed to avoid new memory allocation as possible. func CompositeMatches(matches [][]uint32) []uint32 { switch len(matches) { case 0: return nil case 1: return matches[0] default: result := make([]uint32, 0, 5) for i := 0; i < len(matches); i++ { result = append(result, matches[i]...) } return result } } // CompositeMatches flattens the matches slice to produce a single matched indices slice. // It is designed that: // 1. All matchers are concatenated in reverse order, so the matcher that matches further ranks higher. // 2. Indices in the same matcher keeps their original order. // 3. Avoid new memory allocation as possible. func CompositeMatchesReverse(matches [][]uint32) []uint32 { switch len(matches) { case 0: return nil case 1: return matches[0] default: result := make([]uint32, 0, 5) for i := len(matches) - 1; i >= 0; i-- { result = append(result, matches[i]...) } return result } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_domain.go
common/strmatcher/matchergroup_domain.go
package strmatcher type trieNode struct { values []uint32 children map[string]*trieNode } // DomainMatcherGroup is an implementation of MatcherGroup. // It uses trie to optimize both memory consumption and lookup speed. Trie node is domain label based. type DomainMatcherGroup struct { root *trieNode } func NewDomainMatcherGroup() *DomainMatcherGroup { return &DomainMatcherGroup{ root: new(trieNode), } } // AddDomainMatcher implements MatcherGroupForDomain.AddDomainMatcher. func (g *DomainMatcherGroup) AddDomainMatcher(matcher DomainMatcher, value uint32) { node := g.root pattern := matcher.Pattern() for i := len(pattern); i > 0; { var part string for j := i - 1; ; j-- { if pattern[j] == '.' { part = pattern[j+1 : i] i = j break } if j == 0 { part = pattern[j:i] i = j break } } if node.children == nil { node.children = make(map[string]*trieNode) } next := node.children[part] if next == nil { next = new(trieNode) node.children[part] = next } node = next } node.values = append(node.values, value) } // Match implements MatcherGroup.Match. func (g *DomainMatcherGroup) Match(input string) []uint32 { matches := make([][]uint32, 0, 5) node := g.root for i := len(input); i > 0; { for j := i - 1; ; j-- { if input[j] == '.' { // Domain label found node = node.children[input[j+1:i]] i = j break } if j == 0 { // The last part of domain label node = node.children[input[j:i]] i = j break } } if node == nil { // No more match if no trie edge transition break } if len(node.values) > 0 { // Found matched matchers matches = append(matches, node.values) } if node.children == nil { // No more match if leaf node reached break } } return CompositeMatchesReverse(matches) } // MatchAny implements MatcherGroup.MatchAny. func (g *DomainMatcherGroup) MatchAny(input string) bool { node := g.root for i := len(input); i > 0; { for j := i - 1; ; j-- { if input[j] == '.' { node = node.children[input[j+1:i]] i = j break } if j == 0 { node = node.children[input[j:i]] i = j break } } if node == nil { return false } if len(node.values) > 0 { return true } if node.children == nil { return false } } return false }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_ac_automation_test.go
common/strmatcher/matchergroup_ac_automation_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestACAutomatonMatcherGroup(t *testing.T) { cases1 := []struct { pattern string mType Type input string output bool }{ { pattern: "v2fly.org", mType: Domain, input: "www.v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "www.v3fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "2fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "xv2fly.org", output: false, }, { pattern: "v2fly.org", mType: Full, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Full, input: "xv2fly.org", output: false, }, } for _, test := range cases1 { ac := NewACAutomatonMatcherGroup() matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(ac, matcher, 0)) ac.Build() if m := ac.MatchAny(test.input); m != test.output { t.Error("unexpected output: ", m, " for test case ", test) } } { cases2Input := []struct { pattern string mType Type }{ { pattern: "163.com", mType: Domain, }, { pattern: "m.126.com", mType: Full, }, { pattern: "3.com", mType: Full, }, { pattern: "google.com", mType: Substr, }, { pattern: "vgoogle.com", mType: Substr, }, } ac := NewACAutomatonMatcherGroup() for _, test := range cases2Input { matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(ac, matcher, 0)) } ac.Build() cases2Output := []struct { pattern string res bool }{ { pattern: "126.com", res: false, }, { pattern: "m.163.com", res: true, }, { pattern: "mm163.com", res: false, }, { pattern: "m.126.com", res: true, }, { pattern: "163.com", res: true, }, { pattern: "63.com", res: false, }, { pattern: "oogle.com", res: false, }, { pattern: "vvgoogle.com", res: true, }, } for _, test := range cases2Output { if m := ac.MatchAny(test.pattern); m != test.res { t.Error("unexpected output: ", m, " for test case ", test) } } } { cases3Input := []struct { pattern string mType Type }{ { pattern: "video.google.com", mType: Domain, }, { pattern: "gle.com", mType: Domain, }, } ac := NewACAutomatonMatcherGroup() for _, test := range cases3Input { matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(ac, matcher, 0)) } ac.Build() cases3Output := []struct { pattern string res bool }{ { pattern: "google.com", res: false, }, } for _, test := range cases3Output { if m := ac.MatchAny(test.pattern); m != test.res { t.Error("unexpected output: ", m, " for test case ", test) } } } { cases4Input := []struct { pattern string mType Type }{ { pattern: "apis", mType: Substr, }, { pattern: "googleapis.com", mType: Domain, }, } ac := NewACAutomatonMatcherGroup() for _, test := range cases4Input { matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(ac, matcher, 0)) } ac.Build() cases4Output := []struct { pattern string res bool }{ { pattern: "gapis.com", res: true, }, } for _, test := range cases4Output { if m := ac.MatchAny(test.pattern); m != test.res { t.Error("unexpected output: ", m, " for test case ", test) } } } } func TestACAutomatonMatcherGroupSubstr(t *testing.T) { patterns := []struct { pattern string mType Type }{ { pattern: "apis", mType: Substr, }, { pattern: "google", mType: Substr, }, { pattern: "apis", mType: Substr, }, } cases := []struct { input string output []uint32 }{ { input: "google.com", output: []uint32{1}, }, { input: "apis.com", output: []uint32{0, 2}, }, { input: "googleapis.com", output: []uint32{1, 0, 2}, }, { input: "fonts.googleapis.com", output: []uint32{1, 0, 2}, }, { input: "apis.googleapis.com", output: []uint32{0, 2, 1, 0, 2}, }, } matcherGroup := NewACAutomatonMatcherGroup() for id, entry := range patterns { matcher, err := entry.mType.New(entry.pattern) common.Must(err) common.Must(AddMatcherToGroup(matcherGroup, matcher, uint32(id))) } matcherGroup.Build() for _, test := range cases { if r := matcherGroup.Match(test.input); !reflect.DeepEqual(r, test.output) { t.Error("unexpected output: ", r, " for test case ", test) } } } // See https://github.com/v2fly/v2ray-core/issues/92#issuecomment-673238489 func TestACAutomatonMatcherGroupAsIndexMatcher(t *testing.T) { rules := []struct { Type Type Domain string }{ // Regex not supported by ACAutomationMatcherGroup // { // Type: Regex, // Domain: "apis\\.us$", // }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Domain, Domain: "com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Full, Domain: "fonts.googleapis.com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Domain, Domain: "example.com", }, } cases := []struct { Input string Output []uint32 }{ { Input: "www.baidu.com", Output: []uint32{5, 9, 4}, }, { Input: "fonts.googleapis.com", Output: []uint32{8, 3, 7, 4, 2, 6}, }, { Input: "example.googleapis.com", Output: []uint32{3, 7, 4, 2, 6}, }, { Input: "testapis.us", Output: []uint32{2, 6 /*, 1*/}, }, { Input: "example.com", Output: []uint32{10, 4}, }, } matcherGroup := NewACAutomatonMatcherGroup() for i, rule := range rules { matcher, err := rule.Type.New(rule.Domain) common.Must(err) common.Must(AddMatcherToGroup(matcherGroup, matcher, uint32(i+2))) } matcherGroup.Build() for _, test := range cases { if m := matcherGroup.Match(test.Input); !reflect.DeepEqual(m, test.Output) { t.Error("unexpected output: ", m, " for test case ", test) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/indexmatcher_linear_test.go
common/strmatcher/indexmatcher_linear_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) // See https://github.com/v2fly/v2ray-core/issues/92#issuecomment-673238489 func TestLinearIndexMatcher(t *testing.T) { rules := []struct { Type Type Domain string }{ { Type: Regex, Domain: "apis\\.us$", }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Domain, Domain: "com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Substr, Domain: "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Full, Domain: "fonts.googleapis.com", }, { Type: Full, Domain: "www.baidu.com", }, { Type: Domain, Domain: "example.com", }, } cases := []struct { Input string Output []uint32 }{ { Input: "www.baidu.com", Output: []uint32{5, 9, 4}, }, { Input: "fonts.googleapis.com", Output: []uint32{8, 3, 7, 4, 2, 6}, }, { Input: "example.googleapis.com", Output: []uint32{3, 7, 4, 2, 6}, }, { Input: "testapis.us", Output: []uint32{2, 6, 1}, }, { Input: "example.com", Output: []uint32{10, 4}, }, } matcherGroup := NewLinearIndexMatcher() for _, rule := range rules { matcher, err := rule.Type.New(rule.Domain) common.Must(err) matcherGroup.Add(matcher) } matcherGroup.Build() for _, test := range cases { if m := matcherGroup.Match(test.Input); !reflect.DeepEqual(m, test.Output) { t.Error("unexpected output: ", m, " for test case ", test) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/benchmark_indexmatcher_test.go
common/strmatcher/benchmark_indexmatcher_test.go
package strmatcher_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func BenchmarkLinearIndexMatcher(b *testing.B) { benchmarkIndexMatcher(b, func() IndexMatcher { return NewLinearIndexMatcher() }) } func BenchmarkMphIndexMatcher(b *testing.B) { benchmarkIndexMatcher(b, func() IndexMatcher { return NewMphIndexMatcher() }) } func benchmarkIndexMatcher(b *testing.B, ctor func() IndexMatcher) { b.Run("Match", func(b *testing.B) { b.Run("Domain------------", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: true}) }) b.Run("Domain+Full-------", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: true, Full: true}) }) b.Run("Domain+Full+Substr", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: true, Full: true, Substr: true}) }) b.Run("All-Fail----------", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: false, Full: false, Substr: false}) }) }) b.Run("Match/Dotless", func(b *testing.B) { // Dotless domain matcher automatically inserted in DNS app when "localhost" DNS is used. b.Run("All-Succ", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: true, Full: true, Substr: true, Regex: true}) }) b.Run("All-Fail", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{Domain: false, Full: false, Substr: false, Regex: false}) }) }) b.Run("MatchAny", func(b *testing.B) { b.Run("First-Full--", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{Full: true, Domain: true, Substr: true}) }) b.Run("First-Domain", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{Full: false, Domain: true, Substr: true}) }) b.Run("First-Substr", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{Full: false, Domain: false, Substr: true}) }) b.Run("All-Fail----", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{Full: false, Domain: false, Substr: false}) }) }) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_mph_test.go
common/strmatcher/matchergroup_mph_test.go
package strmatcher_test import ( "reflect" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestMphMatcherGroup(t *testing.T) { cases1 := []struct { pattern string mType Type input string output bool }{ { pattern: "v2fly.org", mType: Domain, input: "www.v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Domain, input: "www.v3fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "2fly.org", output: false, }, { pattern: "v2fly.org", mType: Domain, input: "xv2fly.org", output: false, }, { pattern: "v2fly.org", mType: Full, input: "v2fly.org", output: true, }, { pattern: "v2fly.org", mType: Full, input: "xv2fly.org", output: false, }, } for _, test := range cases1 { mph := NewMphMatcherGroup() matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(mph, matcher, 0)) mph.Build() if m := mph.MatchAny(test.input); m != test.output { t.Error("unexpected output: ", m, " for test case ", test) } } { cases2Input := []struct { pattern string mType Type }{ { pattern: "163.com", mType: Domain, }, { pattern: "m.126.com", mType: Full, }, { pattern: "3.com", mType: Full, }, } mph := NewMphMatcherGroup() for _, test := range cases2Input { matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(mph, matcher, 0)) } mph.Build() cases2Output := []struct { pattern string res bool }{ { pattern: "126.com", res: false, }, { pattern: "m.163.com", res: true, }, { pattern: "mm163.com", res: false, }, { pattern: "m.126.com", res: true, }, { pattern: "163.com", res: true, }, { pattern: "63.com", res: false, }, { pattern: "oogle.com", res: false, }, { pattern: "vvgoogle.com", res: false, }, } for _, test := range cases2Output { if m := mph.MatchAny(test.pattern); m != test.res { t.Error("unexpected output: ", m, " for test case ", test) } } } { cases3Input := []struct { pattern string mType Type }{ { pattern: "video.google.com", mType: Domain, }, { pattern: "gle.com", mType: Domain, }, } mph := NewMphMatcherGroup() for _, test := range cases3Input { matcher, err := test.mType.New(test.pattern) common.Must(err) common.Must(AddMatcherToGroup(mph, matcher, 0)) } mph.Build() cases3Output := []struct { pattern string res bool }{ { pattern: "google.com", res: false, }, } for _, test := range cases3Output { if m := mph.MatchAny(test.pattern); m != test.res { t.Error("unexpected output: ", m, " for test case ", test) } } } } // See https://github.com/v2fly/v2ray-core/issues/92#issuecomment-673238489 func TestMphMatcherGroupAsIndexMatcher(t *testing.T) { rules := []struct { Type Type Domain string }{ // Regex not supported by MphMatcherGroup // { // Type: Regex, // Domain: "apis\\.us$", // }, // Substr not supported by MphMatcherGroup // { // Type: Substr, // Domain: "apis", // }, { Type: Domain, Domain: "googleapis.com", }, { Type: Domain, Domain: "com", }, { Type: Full, Domain: "www.baidu.com", }, // Substr not supported by MphMatcherGroup, We add another matcher to preserve index { Type: Domain, // Substr, Domain: "example.com", // "apis", }, { Type: Domain, Domain: "googleapis.com", }, { Type: Full, Domain: "fonts.googleapis.com", }, { Type: Full, Domain: "www.baidu.com", }, { // This matcher (index 10) is swapped with matcher (index 6) to test that full matcher takes high priority. Type: Full, Domain: "example.com", }, { Type: Domain, Domain: "example.com", }, } cases := []struct { Input string Output []uint32 }{ { Input: "www.baidu.com", Output: []uint32{5, 9, 4}, }, { Input: "fonts.googleapis.com", Output: []uint32{8, 3, 7, 4 /*2, 6*/}, }, { Input: "example.googleapis.com", Output: []uint32{3, 7, 4 /*2, 6*/}, }, { Input: "testapis.us", // Output: []uint32{ /*2, 6*/ /*1,*/ }, Output: nil, }, { Input: "example.com", Output: []uint32{10, 6, 11, 4}, }, } matcherGroup := NewMphMatcherGroup() for i, rule := range rules { matcher, err := rule.Type.New(rule.Domain) common.Must(err) common.Must(AddMatcherToGroup(matcherGroup, matcher, uint32(i+3))) } matcherGroup.Build() for _, test := range cases { if m := matcherGroup.Match(test.Input); !reflect.DeepEqual(m, test.Output) { t.Error("unexpected output: ", m, " for test case ", test) } } } func TestEmptyMphMatcherGroup(t *testing.T) { g := NewMphMatcherGroup() g.Build() r := g.Match("v2fly.org") if len(r) != 0 { t.Error("Expect [], but ", r) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/benchmark_matchers_test.go
common/strmatcher/benchmark_matchers_test.go
package strmatcher_test import ( "strconv" "testing" "github.com/v2fly/v2ray-core/v5/common" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func BenchmarkFullMatcher(b *testing.B) { b.Run("SimpleMatcherGroup------", func(b *testing.B) { benchmarkMatcherType(b, Full, func() MatcherGroup { return new(SimpleMatcherGroup) }) }) b.Run("FullMatcherGroup--------", func(b *testing.B) { benchmarkMatcherType(b, Full, func() MatcherGroup { return NewFullMatcherGroup() }) }) b.Run("ACAutomationMatcherGroup", func(b *testing.B) { benchmarkMatcherType(b, Full, func() MatcherGroup { return NewACAutomatonMatcherGroup() }) }) b.Run("MphMatcherGroup---------", func(b *testing.B) { benchmarkMatcherType(b, Full, func() MatcherGroup { return NewMphMatcherGroup() }) }) } func BenchmarkDomainMatcher(b *testing.B) { b.Run("SimpleMatcherGroup------", func(b *testing.B) { benchmarkMatcherType(b, Domain, func() MatcherGroup { return new(SimpleMatcherGroup) }) }) b.Run("DomainMatcherGroup------", func(b *testing.B) { benchmarkMatcherType(b, Domain, func() MatcherGroup { return NewDomainMatcherGroup() }) }) b.Run("ACAutomationMatcherGroup", func(b *testing.B) { benchmarkMatcherType(b, Domain, func() MatcherGroup { return NewACAutomatonMatcherGroup() }) }) b.Run("MphMatcherGroup---------", func(b *testing.B) { benchmarkMatcherType(b, Domain, func() MatcherGroup { return NewMphMatcherGroup() }) }) } func BenchmarkSubstrMatcher(b *testing.B) { b.Run("SimpleMatcherGroup------", func(b *testing.B) { benchmarkMatcherType(b, Substr, func() MatcherGroup { return new(SimpleMatcherGroup) }) }) b.Run("SubstrMatcherGroup------", func(b *testing.B) { benchmarkMatcherType(b, Substr, func() MatcherGroup { return new(SubstrMatcherGroup) }) }) b.Run("ACAutomationMatcherGroup", func(b *testing.B) { benchmarkMatcherType(b, Substr, func() MatcherGroup { return NewACAutomatonMatcherGroup() }) }) } // Utility functions for benchmark func benchmarkMatcherType(b *testing.B, t Type, ctor func() MatcherGroup) { b.Run("Match", func(b *testing.B) { b.Run("Succ", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{t: true}) }) b.Run("Fail", func(b *testing.B) { benchmarkMatch(b, ctor(), map[Type]bool{t: false}) }) }) b.Run("MatchAny", func(b *testing.B) { b.Run("Succ", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{t: true}) }) b.Run("Fail", func(b *testing.B) { benchmarkMatchAny(b, ctor(), map[Type]bool{t: false}) }) }) } func benchmarkMatch(b *testing.B, g MatcherGroup, enabledTypes map[Type]bool) { prepareMatchers(g, enabledTypes) b.ResetTimer() for i := 0; i < b.N; i++ { _ = g.Match("0.v2fly.org") } } func benchmarkMatchAny(b *testing.B, g MatcherGroup, enabledTypes map[Type]bool) { prepareMatchers(g, enabledTypes) b.ResetTimer() for i := 0; i < b.N; i++ { _ = g.MatchAny("0.v2fly.org") } } func prepareMatchers(g MatcherGroup, enabledTypes map[Type]bool) { for matcherType, hasMatch := range enabledTypes { switch matcherType { case Domain: if hasMatch { AddMatcherToGroup(g, DomainMatcher("v2fly.org"), 0) } for i := 1; i < 1024; i++ { AddMatcherToGroup(g, DomainMatcher(strconv.Itoa(i)+".v2fly.org"), uint32(i)) } case Full: if hasMatch { AddMatcherToGroup(g, FullMatcher("0.v2fly.org"), 0) } for i := 1; i < 64; i++ { AddMatcherToGroup(g, FullMatcher(strconv.Itoa(i)+".v2fly.org"), uint32(i)) } case Substr: if hasMatch { AddMatcherToGroup(g, SubstrMatcher("v2fly.org"), 0) } for i := 1; i < 4; i++ { AddMatcherToGroup(g, SubstrMatcher(strconv.Itoa(i)+".v2fly.org"), uint32(i)) } case Regex: matcher, err := Regex.New("^[^.]*$") // Dotless domain matcher automatically inserted in DNS app when "localhost" DNS is used. common.Must(err) AddMatcherToGroup(g, matcher, 0) } } if g, ok := g.(buildable); ok { common.Must(g.Build()) } } type buildable interface { Build() error }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/strmatcher.go
common/strmatcher/strmatcher.go
package strmatcher // Type is the type of the matcher. type Type byte const ( // Full is the type of matcher that the input string must exactly equal to the pattern. Full Type = 0 // Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern. Domain Type = 1 // Substr is the type of matcher that the input string must contain the pattern as a sub-string. Substr Type = 2 // Regex is the type of matcher that the input string must matches the regular-expression pattern. Regex Type = 3 ) // Matcher is the interface to determine a string matches a pattern. // - This is a basic matcher to represent a certain kind of match semantic(full, substr, domain or regex). type Matcher interface { // Type returns the matcher's type. Type() Type // Pattern returns the matcher's raw string representation. Pattern() string // String returns a string representation of the matcher containing its type and pattern. String() string // Match returns true if the given string matches a predefined pattern. // * This method is seldom used for performance reason // and is generally taken over by their corresponding MatcherGroup. Match(input string) bool } // MatcherGroup is an advanced type of matcher to accept a bunch of basic Matchers (of certain type, not all matcher types). // For example: // - FullMatcherGroup accepts FullMatcher and uses a hash table to facilitate lookup. // - DomainMatcherGroup accepts DomainMatcher and uses a trie to optimize both memory consumption and lookup speed. type MatcherGroup interface { // Match returns all matched matchers with their corresponding values. Match(input string) []uint32 // MatchAny returns true as soon as one matching matcher is found. MatchAny(input string) bool } // IndexMatcher is a general type of matcher thats accepts all kinds of basic matchers. // It should: // - Accept all Matcher types with no exception. // - Optimize string matching with a combination of MatcherGroups. // - Obey certain priority order specification when returning matched Matchers. type IndexMatcher interface { // Size returns number of matchers added to IndexMatcher. Size() uint32 // Add adds a new Matcher to IndexMatcher, and returns its index. The index will never be 0. Add(matcher Matcher) uint32 // Build builds the IndexMatcher to be ready for matching. Build() error // Match returns the indices of all matchers that matches the input. // * Empty array is returned if no such matcher exists. // * The order of returned matchers should follow priority specification. // Priority specification: // 1. Priority between matcher types: full > domain > substr > regex. // 2. Priority of same-priority matchers matching at same position: the early added takes precedence. // 3. Priority of domain matchers matching at different levels: the further matched domain takes precedence. // 4. Priority of substr matchers matching at different positions: the further matched substr takes precedence. Match(input string) []uint32 // MatchAny returns true as soon as one matching matcher is found. MatchAny(input string) bool }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/indexmatcher_mph.go
common/strmatcher/indexmatcher_mph.go
package strmatcher // A MphIndexMatcher is divided into three parts: // 1. `full` and `domain` patterns are matched by Rabin-Karp algorithm and minimal perfect hash table; // 2. `substr` patterns are matched by ac automaton; // 3. `regex` patterns are matched with the regex library. type MphIndexMatcher struct { count uint32 mph *MphMatcherGroup ac *ACAutomatonMatcherGroup regex *SimpleMatcherGroup } func NewMphIndexMatcher() *MphIndexMatcher { return new(MphIndexMatcher) } // Add implements IndexMatcher.Add. func (g *MphIndexMatcher) Add(matcher Matcher) uint32 { g.count++ index := g.count switch matcher := matcher.(type) { case FullMatcher: if g.mph == nil { g.mph = NewMphMatcherGroup() } g.mph.AddFullMatcher(matcher, index) case DomainMatcher: if g.mph == nil { g.mph = NewMphMatcherGroup() } g.mph.AddDomainMatcher(matcher, index) case SubstrMatcher: if g.ac == nil { g.ac = NewACAutomatonMatcherGroup() } g.ac.AddSubstrMatcher(matcher, index) case *RegexMatcher: if g.regex == nil { g.regex = &SimpleMatcherGroup{} } g.regex.AddMatcher(matcher, index) } return index } // Build implements IndexMatcher.Build. func (g *MphIndexMatcher) Build() error { if g.mph != nil { g.mph.Build() } if g.ac != nil { g.ac.Build() } return nil } // Match implements IndexMatcher.Match. func (g *MphIndexMatcher) Match(input string) []uint32 { result := make([][]uint32, 0, 5) if g.mph != nil { if matches := g.mph.Match(input); len(matches) > 0 { result = append(result, matches) } } if g.ac != nil { if matches := g.ac.Match(input); len(matches) > 0 { result = append(result, matches) } } if g.regex != nil { if matches := g.regex.Match(input); len(matches) > 0 { result = append(result, matches) } } return CompositeMatches(result) } // MatchAny implements IndexMatcher.MatchAny. func (g *MphIndexMatcher) MatchAny(input string) bool { if g.mph != nil && g.mph.MatchAny(input) { return true } if g.ac != nil && g.ac.MatchAny(input) { return true } return g.regex != nil && g.regex.MatchAny(input) } // Size implements IndexMatcher.Size. func (g *MphIndexMatcher) Size() uint32 { return g.count }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_full.go
common/strmatcher/matchergroup_full.go
package strmatcher // FullMatcherGroup is an implementation of MatcherGroup. // It uses a hash table to facilitate exact match lookup. type FullMatcherGroup struct { matchers map[string][]uint32 } func NewFullMatcherGroup() *FullMatcherGroup { return &FullMatcherGroup{ matchers: make(map[string][]uint32), } } // AddFullMatcher implements MatcherGroupForFull.AddFullMatcher. func (g *FullMatcherGroup) AddFullMatcher(matcher FullMatcher, value uint32) { domain := matcher.Pattern() g.matchers[domain] = append(g.matchers[domain], value) } // Match implements MatcherGroup.Match. func (g *FullMatcherGroup) Match(input string) []uint32 { return g.matchers[input] } // MatchAny implements MatcherGroup.Any. func (g *FullMatcherGroup) MatchAny(input string) bool { _, found := g.matchers[input] return found }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_substr.go
common/strmatcher/matchergroup_substr.go
package strmatcher import ( "sort" "strings" ) // SubstrMatcherGroup is implementation of MatcherGroup, // It is simply implmeneted to comply with the priority specification of Substr matchers. type SubstrMatcherGroup struct { patterns []string values []uint32 } // AddSubstrMatcher implements MatcherGroupForSubstr.AddSubstrMatcher. func (g *SubstrMatcherGroup) AddSubstrMatcher(matcher SubstrMatcher, value uint32) { g.patterns = append(g.patterns, matcher.Pattern()) g.values = append(g.values, value) } // Match implements MatcherGroup.Match. func (g *SubstrMatcherGroup) Match(input string) []uint32 { var result []uint32 for i, pattern := range g.patterns { for j := strings.LastIndex(input, pattern); j != -1; j = strings.LastIndex(input[:j], pattern) { result = append(result, uint32(j)<<16|uint32(i)&0xffff) // uint32: position (higher 16 bit) | patternIdx (lower 16 bit) } } // sort.Slice will trigger allocation no matter what input is. See https://github.com/golang/go/issues/17332 // We optimize the sorting by length to prevent memory allocation as possible. switch len(result) { case 0: return nil case 1: // No need to sort case 2: // Do a simple swap if unsorted if result[0] > result[1] { result[0], result[1] = result[1], result[0] } default: // Sort the match results in dictionary order, so that: // 1. Pattern matched at smaller position (meaning matched further) takes precedence. // 2. When patterns matched at same position, pattern with smaller index (meaning inserted early) takes precedence. sort.Slice(result, func(i, j int) bool { return result[i] < result[j] }) } for i, entry := range result { result[i] = g.values[entry&0xffff] // Get pattern value from its index (the lower 16 bit) } return result } // MatchAny implements MatcherGroup.MatchAny. func (g *SubstrMatcherGroup) MatchAny(input string) bool { for _, pattern := range g.patterns { if strings.Contains(input, pattern) { return true } } return false }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/indexmatcher_linear.go
common/strmatcher/indexmatcher_linear.go
package strmatcher // LinearIndexMatcher is an implementation of IndexMatcher. type LinearIndexMatcher struct { count uint32 full *FullMatcherGroup domain *DomainMatcherGroup substr *SubstrMatcherGroup regex *SimpleMatcherGroup } func NewLinearIndexMatcher() *LinearIndexMatcher { return new(LinearIndexMatcher) } // Add implements IndexMatcher.Add. func (g *LinearIndexMatcher) Add(matcher Matcher) uint32 { g.count++ index := g.count switch matcher := matcher.(type) { case FullMatcher: if g.full == nil { g.full = NewFullMatcherGroup() } g.full.AddFullMatcher(matcher, index) case DomainMatcher: if g.domain == nil { g.domain = NewDomainMatcherGroup() } g.domain.AddDomainMatcher(matcher, index) case SubstrMatcher: if g.substr == nil { g.substr = new(SubstrMatcherGroup) } g.substr.AddSubstrMatcher(matcher, index) default: if g.regex == nil { g.regex = new(SimpleMatcherGroup) } g.regex.AddMatcher(matcher, index) } return index } // Build implements IndexMatcher.Build. func (*LinearIndexMatcher) Build() error { return nil } // Match implements IndexMatcher.Match. func (g *LinearIndexMatcher) Match(input string) []uint32 { // Allocate capacity to prevent matches escaping to heap result := make([][]uint32, 0, 5) if g.full != nil { if matches := g.full.Match(input); len(matches) > 0 { result = append(result, matches) } } if g.domain != nil { if matches := g.domain.Match(input); len(matches) > 0 { result = append(result, matches) } } if g.substr != nil { if matches := g.substr.Match(input); len(matches) > 0 { result = append(result, matches) } } if g.regex != nil { if matches := g.regex.Match(input); len(matches) > 0 { result = append(result, matches) } } return CompositeMatches(result) } // MatchAny implements IndexMatcher.MatchAny. func (g *LinearIndexMatcher) MatchAny(input string) bool { if g.full != nil && g.full.MatchAny(input) { return true } if g.domain != nil && g.domain.MatchAny(input) { return true } if g.substr != nil && g.substr.MatchAny(input) { return true } return g.regex != nil && g.regex.MatchAny(input) } // Size implements IndexMatcher.Size. func (g *LinearIndexMatcher) Size() uint32 { return g.count }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_ac_automation.go
common/strmatcher/matchergroup_ac_automation.go
package strmatcher import ( "container/list" ) const ( acValidCharCount = 39 // aA-zZ (26), 0-9 (10), - (1), . (1), invalid(1) acMatchTypeCount = 3 // Full, Domain and Substr ) type acEdge byte const ( acTrieEdge acEdge = 1 acFailEdge acEdge = 0 ) type acNode struct { next [acValidCharCount]uint32 // EdgeIdx -> Next NodeIdx (Next trie node or fail node) edge [acValidCharCount]acEdge // EdgeIdx -> Trie Edge / Fail Edge fail uint32 // NodeIdx of *next matched* Substr Pattern on its fail path match uint32 // MatchIdx of matchers registered on this node, 0 indicates no match } // Sizeof acNode: (4+1)*acValidCharCount + <padding> + 4 + 4 type acValue [acMatchTypeCount][]uint32 // MatcherType -> Registered Matcher Values // ACAutoMationMatcherGroup is an implementation of MatcherGroup. // It uses an AC Automata to provide support for Full, Domain and Substr matcher. Trie node is char based. // // NOTICE: ACAutomatonMatcherGroup currently uses a restricted charset (LDH Subset), // upstream should manually in a way to ensure all patterns and inputs passed to it to be in this charset. type ACAutomatonMatcherGroup struct { nodes []acNode // NodeIdx -> acNode values []acValue // MatchIdx -> acValue } func NewACAutomatonMatcherGroup() *ACAutomatonMatcherGroup { ac := new(ACAutomatonMatcherGroup) ac.addNode() // Create root node (NodeIdx 0) ac.addMatchEntry() // Create sentinel match entry (MatchIdx 0) return ac } // AddFullMatcher implements MatcherGroupForFull.AddFullMatcher. func (ac *ACAutomatonMatcherGroup) AddFullMatcher(matcher FullMatcher, value uint32) { ac.addPattern(0, matcher.Pattern(), matcher.Type(), value) } // AddDomainMatcher implements MatcherGroupForDomain.AddDomainMatcher. func (ac *ACAutomatonMatcherGroup) AddDomainMatcher(matcher DomainMatcher, value uint32) { node := ac.addPattern(0, matcher.Pattern(), matcher.Type(), value) // For full domain match ac.addPattern(node, ".", matcher.Type(), value) // For partial domain match } // AddSubstrMatcher implements MatcherGroupForSubstr.AddSubstrMatcher. func (ac *ACAutomatonMatcherGroup) AddSubstrMatcher(matcher SubstrMatcher, value uint32) { ac.addPattern(0, matcher.Pattern(), matcher.Type(), value) } func (ac *ACAutomatonMatcherGroup) addPattern(nodeIdx uint32, pattern string, matcherType Type, value uint32) uint32 { node := &ac.nodes[nodeIdx] for i := len(pattern) - 1; i >= 0; i-- { edgeIdx := acCharset[pattern[i]] nextIdx := node.next[edgeIdx] if nextIdx == 0 { // Add new Trie Edge nextIdx = ac.addNode() ac.nodes[nodeIdx].next[edgeIdx] = nextIdx ac.nodes[nodeIdx].edge[edgeIdx] = acTrieEdge } nodeIdx = nextIdx node = &ac.nodes[nodeIdx] } if node.match == 0 { // Add new match entry node.match = ac.addMatchEntry() } ac.values[node.match][matcherType] = append(ac.values[node.match][matcherType], value) return nodeIdx } func (ac *ACAutomatonMatcherGroup) addNode() uint32 { ac.nodes = append(ac.nodes, acNode{}) return uint32(len(ac.nodes) - 1) } func (ac *ACAutomatonMatcherGroup) addMatchEntry() uint32 { ac.values = append(ac.values, acValue{}) return uint32(len(ac.values) - 1) } func (ac *ACAutomatonMatcherGroup) Build() error { fail := make([]uint32, len(ac.nodes)) queue := list.New() for edgeIdx := 0; edgeIdx < acValidCharCount; edgeIdx++ { if nextIdx := ac.nodes[0].next[edgeIdx]; nextIdx != 0 { queue.PushBack(nextIdx) } } for { front := queue.Front() if front == nil { break } queue.Remove(front) nodeIdx := front.Value.(uint32) node := &ac.nodes[nodeIdx] // Current node failNode := &ac.nodes[fail[nodeIdx]] // Fail node of currrent node for edgeIdx := 0; edgeIdx < acValidCharCount; edgeIdx++ { nodeIdx := node.next[edgeIdx] // Next node through trie edge failIdx := failNode.next[edgeIdx] // Next node through fail edge if nodeIdx != 0 { queue.PushBack(nodeIdx) fail[nodeIdx] = failIdx if match := ac.nodes[failIdx].match; match != 0 && len(ac.values[match][Substr]) > 0 { // Fail node is a Substr match node ac.nodes[nodeIdx].fail = failIdx } else { // Use path compression to reduce fail path to only contain match nodes ac.nodes[nodeIdx].fail = ac.nodes[failIdx].fail } } else { // Add new fail edge node.next[edgeIdx] = failIdx node.edge[edgeIdx] = acFailEdge } } } return nil } // Match implements MatcherGroup.Match. func (ac *ACAutomatonMatcherGroup) Match(input string) []uint32 { suffixMatches := make([][]uint32, 0, 5) substrMatches := make([][]uint32, 0, 5) fullMatch := true // fullMatch indicates no fail edge traversed so far. node := &ac.nodes[0] // start from root node. // 1. the match string is all through trie edge. FULL MATCH or DOMAIN // 2. the match string is through a fail edge. NOT FULL MATCH // 2.1 Through a fail edge, but there exists a valid node. SUBSTR for i := len(input) - 1; i >= 0; i-- { edge := acCharset[input[i]] fullMatch = fullMatch && (node.edge[edge] == acTrieEdge) node = &ac.nodes[node.next[edge]] // Advance to next node // When entering a new node, traverse the fail path to find all possible Substr patterns: // 1. The fail path is compressed to only contains match nodes and root node (for terminate condition). // 2. node.fail != 0 is added here for better performance (as shown by benchmark), possibly it helps branch prediction. if node.fail != 0 { for failIdx, failNode := node.fail, &ac.nodes[node.fail]; failIdx != 0; failIdx, failNode = failNode.fail, &ac.nodes[failIdx] { substrMatches = append(substrMatches, ac.values[failNode.match][Substr]) } } // When entering a new node, check whether this node is a match. // For Substr matchers: // 1. Matched in any situation, whether a failNode edge is traversed or not. // For Domain matchers: // 1. Should not traverse any fail edge (fullMatch). // 2. Only check on dot separator (input[i] == '.'). if node.match != 0 { values := ac.values[node.match] if len(values[Substr]) > 0 { substrMatches = append(substrMatches, values[Substr]) } if fullMatch && input[i] == '.' && len(values[Domain]) > 0 { suffixMatches = append(suffixMatches, values[Domain]) } } } // At the end of input, check if the whole string matches a pattern. // For Domain matchers: // 1. Exact match on Domain Matcher works like Full Match. e.g. foo.com is a full match for domain:foo.com. // For Full matchers: // 1. Only when no fail edge is traversed (fullMatch). // 2. Takes the highest priority (added at last). if fullMatch && node.match != 0 { values := ac.values[node.match] if len(values[Domain]) > 0 { suffixMatches = append(suffixMatches, values[Domain]) } if len(values[Full]) > 0 { suffixMatches = append(suffixMatches, values[Full]) } } if len(substrMatches) == 0 { return CompositeMatchesReverse(suffixMatches) } return CompositeMatchesReverse(append(substrMatches, suffixMatches...)) } // MatchAny implements MatcherGroup.MatchAny. func (ac *ACAutomatonMatcherGroup) MatchAny(input string) bool { fullMatch := true node := &ac.nodes[0] for i := len(input) - 1; i >= 0; i-- { edge := acCharset[input[i]] fullMatch = fullMatch && (node.edge[edge] == acTrieEdge) node = &ac.nodes[node.next[edge]] if node.fail != 0 { // There is a match on this node's fail path return true } if node.match != 0 { // There is a match on this node values := ac.values[node.match] if len(values[Substr]) > 0 { // Substr match succeeds unconditionally return true } if fullMatch && input[i] == '.' && len(values[Domain]) > 0 { // Domain match only succeeds with dot separator on trie path return true } } } return fullMatch && node.match != 0 // At the end of input, Domain and Full match will succeed if no fail edge is traversed } // Letter-Digit-Hyphen (LDH) subset (https://tools.ietf.org/html/rfc952): // - Letters A to Z (no distinction is made between uppercase and lowercase) // - Digits 0 to 9 // - Hyphens(-) and Periods(.) // // If for future the strmatcher are used for other scenarios than domain, // we could add a new Charset interface to represent variable charsets. var acCharset = [256]int{ 'A': 1, 'a': 1, 'B': 2, 'b': 2, 'C': 3, 'c': 3, 'D': 4, 'd': 4, 'E': 5, 'e': 5, 'F': 6, 'f': 6, 'G': 7, 'g': 7, 'H': 8, 'h': 8, 'I': 9, 'i': 9, 'J': 10, 'j': 10, 'K': 11, 'k': 11, 'L': 12, 'l': 12, 'M': 13, 'm': 13, 'N': 14, 'n': 14, 'O': 15, 'o': 15, 'P': 16, 'p': 16, 'Q': 17, 'q': 17, 'R': 18, 'r': 18, 'S': 19, 's': 19, 'T': 20, 't': 20, 'U': 21, 'u': 21, 'V': 22, 'v': 22, 'W': 23, 'w': 23, 'X': 24, 'x': 24, 'Y': 25, 'y': 25, 'Z': 26, 'z': 26, '-': 27, '.': 28, '0': 29, '1': 30, '2': 31, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38, }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_full_test.go
common/strmatcher/matchergroup_full_test.go
package strmatcher_test import ( "reflect" "testing" . "github.com/v2fly/v2ray-core/v5/common/strmatcher" ) func TestFullMatcherGroup(t *testing.T) { patterns := []struct { Pattern string Value uint32 }{ { Pattern: "v2fly.org", Value: 1, }, { Pattern: "google.com", Value: 2, }, { Pattern: "x.a.com", Value: 3, }, { Pattern: "x.y.com", Value: 4, }, { Pattern: "x.y.com", Value: 6, }, } testCases := []struct { Domain string Result []uint32 }{ { Domain: "v2fly.org", Result: []uint32{1}, }, { Domain: "y.com", Result: nil, }, { Domain: "x.y.com", Result: []uint32{4, 6}, }, } g := NewFullMatcherGroup() for _, pattern := range patterns { AddMatcherToGroup(g, FullMatcher(pattern.Pattern), pattern.Value) } for _, testCase := range testCases { r := g.Match(testCase.Domain) if !reflect.DeepEqual(r, testCase.Result) { t.Error("Failed to match domain: ", testCase.Domain, ", expect ", testCase.Result, ", but got ", r) } } } func TestEmptyFullMatcherGroup(t *testing.T) { g := NewFullMatcherGroup() r := g.Match("v2fly.org") if len(r) != 0 { t.Error("Expect [], but ", r) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/strmatcher/matchergroup_simple.go
common/strmatcher/matchergroup_simple.go
package strmatcher type matcherEntry struct { matcher Matcher value uint32 } // SimpleMatcherGroup is an implementation of MatcherGroup. // It simply stores all matchers in an array and sequentially matches them. type SimpleMatcherGroup struct { matchers []matcherEntry } // AddMatcher implements MatcherGroupForAll.AddMatcher. func (g *SimpleMatcherGroup) AddMatcher(matcher Matcher, value uint32) { g.matchers = append(g.matchers, matcherEntry{ matcher: matcher, value: value, }) } // Match implements MatcherGroup.Match. func (g *SimpleMatcherGroup) Match(input string) []uint32 { result := []uint32{} for _, e := range g.matchers { if e.matcher.Match(input) { result = append(result, e.value) } } return result } // MatchAny implements MatcherGroup.MatchAny. func (g *SimpleMatcherGroup) MatchAny(input string) bool { for _, e := range g.matchers { if e.matcher.Match(input) { return true } } return false }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/peer/latency.go
common/peer/latency.go
package peer import ( "sync" ) type Latency interface { Value() uint64 } type HasLatency interface { ConnectionLatency() Latency HandshakeLatency() Latency } type AverageLatency struct { access sync.Mutex value uint64 } func (al *AverageLatency) Update(newValue uint64) { al.access.Lock() defer al.access.Unlock() al.value = (al.value + newValue*2) / 3 } func (al *AverageLatency) Value() uint64 { return al.value }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/peer/peer.go
common/peer/peer.go
package peer
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/bytespool/pool.go
common/bytespool/pool.go
package bytespool import "sync" func createAllocFunc(size int32) func() interface{} { return func() interface{} { return make([]byte, size) } } // The following parameters controls the size of buffer pools. // There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one. // Package buf is guaranteed to not use buffers larger than the largest pool. // Other packets may use larger buffers. const ( numPools = 4 sizeMulti = 4 ) var ( pool [numPools]sync.Pool poolSize [numPools]int32 ) func init() { size := int32(2048) for i := 0; i < numPools; i++ { pool[i] = sync.Pool{ New: createAllocFunc(size), } poolSize[i] = size size *= sizeMulti } } // GetPool returns a sync.Pool that generates bytes array with at least the given size. // It may return nil if no such pool exists. // // v2ray:api:stable func GetPool(size int32) *sync.Pool { for idx, ps := range poolSize { if size <= ps { return &pool[idx] } } return nil } // Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048. // // v2ray:api:stable func Alloc(size int32) []byte { pool := GetPool(size) if pool != nil { return pool.Get().([]byte) } return make([]byte, size) } // Free puts a byte slice into the internal pool. // // v2ray:api:stable func Free(b []byte) { size := int32(cap(b)) b = b[0:cap(b)] for i := numPools - 1; i >= 0; i-- { if size >= poolSize[i] { pool[i].Put(b) // nolint: staticcheck return } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/time.go
common/protocol/time.go
package protocol import ( "time" "github.com/v2fly/v2ray-core/v5/common/dice" ) type Timestamp int64 type TimestampGenerator func() Timestamp func NowTime() Timestamp { return Timestamp(time.Now().Unix()) } func NewTimestampGenerator(base Timestamp, delta int) TimestampGenerator { return func() Timestamp { rangeInDelta := dice.Roll(delta*2) - delta return base + Timestamp(rangeInDelta) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/time_test.go
common/protocol/time_test.go
package protocol_test import ( "testing" "time" . "github.com/v2fly/v2ray-core/v5/common/protocol" ) func TestGenerateRandomInt64InRange(t *testing.T) { base := time.Now().Unix() delta := 100 generator := NewTimestampGenerator(Timestamp(base), delta) for i := 0; i < 100; i++ { val := int64(generator()) if val > base+int64(delta) || val < base-int64(delta) { t.Error(val, " not between ", base-int64(delta), " and ", base+int64(delta)) } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/user.pb.go
common/protocol/user.pb.go
package protocol 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) ) // User is a generic user for all procotols. type User struct { state protoimpl.MessageState `protogen:"open.v1"` Level uint32 `protobuf:"varint,1,opt,name=level,proto3" json:"level,omitempty"` Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` // Protocol specific account information. Must be the account proto in one of // the proxies. Account *anypb.Any `protobuf:"bytes,3,opt,name=account,proto3" json:"account,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *User) Reset() { *x = User{} mi := &file_common_protocol_user_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *User) String() string { return protoimpl.X.MessageStringOf(x) } func (*User) ProtoMessage() {} func (x *User) ProtoReflect() protoreflect.Message { mi := &file_common_protocol_user_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 User.ProtoReflect.Descriptor instead. func (*User) Descriptor() ([]byte, []int) { return file_common_protocol_user_proto_rawDescGZIP(), []int{0} } func (x *User) GetLevel() uint32 { if x != nil { return x.Level } return 0 } func (x *User) GetEmail() string { if x != nil { return x.Email } return "" } func (x *User) GetAccount() *anypb.Any { if x != nil { return x.Account } return nil } var File_common_protocol_user_proto protoreflect.FileDescriptor const file_common_protocol_user_proto_rawDesc = "" + "\n" + "\x1acommon/protocol/user.proto\x12\x1av2ray.core.common.protocol\x1a\x19google/protobuf/any.proto\"b\n" + "\x04User\x12\x14\n" + "\x05level\x18\x01 \x01(\rR\x05level\x12\x14\n" + "\x05email\x18\x02 \x01(\tR\x05email\x12.\n" + "\aaccount\x18\x03 \x01(\v2\x14.google.protobuf.AnyR\aaccountBo\n" + "\x1ecom.v2ray.core.common.protocolP\x01Z.github.com/v2fly/v2ray-core/v5/common/protocol\xaa\x02\x1aV2Ray.Core.Common.Protocolb\x06proto3" var ( file_common_protocol_user_proto_rawDescOnce sync.Once file_common_protocol_user_proto_rawDescData []byte ) func file_common_protocol_user_proto_rawDescGZIP() []byte { file_common_protocol_user_proto_rawDescOnce.Do(func() { file_common_protocol_user_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_common_protocol_user_proto_rawDesc), len(file_common_protocol_user_proto_rawDesc))) }) return file_common_protocol_user_proto_rawDescData } var file_common_protocol_user_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_protocol_user_proto_goTypes = []any{ (*User)(nil), // 0: v2ray.core.common.protocol.User (*anypb.Any)(nil), // 1: google.protobuf.Any } var file_common_protocol_user_proto_depIdxs = []int32{ 1, // 0: v2ray.core.common.protocol.User.account:type_name -> google.protobuf.Any 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_common_protocol_user_proto_init() } func file_common_protocol_user_proto_init() { if File_common_protocol_user_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_protocol_user_proto_rawDesc), len(file_common_protocol_user_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_protocol_user_proto_goTypes, DependencyIndexes: file_common_protocol_user_proto_depIdxs, MessageInfos: file_common_protocol_user_proto_msgTypes, }.Build() File_common_protocol_user_proto = out.File file_common_protocol_user_proto_goTypes = nil file_common_protocol_user_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/server_picker_test.go
common/protocol/server_picker_test.go
package protocol_test import ( "testing" "time" "github.com/v2fly/v2ray-core/v5/common/net" . "github.com/v2fly/v2ray-core/v5/common/protocol" ) func TestServerList(t *testing.T) { list := NewServerList() list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid())) if list.Size() != 1 { t.Error("list size: ", list.Size()) } list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second)))) if list.Size() != 2 { t.Error("list.size: ", list.Size()) } server := list.GetServer(1) if server.Destination().Port != 2 { t.Error("server: ", server.Destination()) } time.Sleep(2 * time.Second) server = list.GetServer(1) if server != nil { t.Error("server: ", server) } server = list.GetServer(0) if server.Destination().Port != 1 { t.Error("server: ", server.Destination()) } } func TestServerPicker(t *testing.T) { list := NewServerList() list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid())) list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second)))) list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(3)), BeforeTime(time.Now().Add(time.Second)))) picker := NewRoundRobinServerPicker(list) server := picker.PickServer() if server.Destination().Port != 1 { t.Error("server: ", server.Destination()) } server = picker.PickServer() if server.Destination().Port != 2 { t.Error("server: ", server.Destination()) } server = picker.PickServer() if server.Destination().Port != 3 { t.Error("server: ", server.Destination()) } server = picker.PickServer() if server.Destination().Port != 1 { t.Error("server: ", server.Destination()) } time.Sleep(2 * time.Second) server = picker.PickServer() if server.Destination().Port != 1 { t.Error("server: ", server.Destination()) } server = picker.PickServer() if server.Destination().Port != 1 { t.Error("server: ", server.Destination()) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/headers.pb.go
common/protocol/headers.pb.go
package protocol 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 SecurityType int32 const ( SecurityType_UNKNOWN SecurityType = 0 SecurityType_LEGACY SecurityType = 1 SecurityType_AUTO SecurityType = 2 SecurityType_AES128_GCM SecurityType = 3 SecurityType_CHACHA20_POLY1305 SecurityType = 4 SecurityType_NONE SecurityType = 5 SecurityType_ZERO SecurityType = 6 ) // Enum value maps for SecurityType. var ( SecurityType_name = map[int32]string{ 0: "UNKNOWN", 1: "LEGACY", 2: "AUTO", 3: "AES128_GCM", 4: "CHACHA20_POLY1305", 5: "NONE", 6: "ZERO", } SecurityType_value = map[string]int32{ "UNKNOWN": 0, "LEGACY": 1, "AUTO": 2, "AES128_GCM": 3, "CHACHA20_POLY1305": 4, "NONE": 5, "ZERO": 6, } ) func (x SecurityType) Enum() *SecurityType { p := new(SecurityType) *p = x return p } func (x SecurityType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SecurityType) Descriptor() protoreflect.EnumDescriptor { return file_common_protocol_headers_proto_enumTypes[0].Descriptor() } func (SecurityType) Type() protoreflect.EnumType { return &file_common_protocol_headers_proto_enumTypes[0] } func (x SecurityType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SecurityType.Descriptor instead. func (SecurityType) EnumDescriptor() ([]byte, []int) { return file_common_protocol_headers_proto_rawDescGZIP(), []int{0} } type SecurityConfig struct { state protoimpl.MessageState `protogen:"open.v1"` Type SecurityType `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.common.protocol.SecurityType" json:"type,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SecurityConfig) Reset() { *x = SecurityConfig{} mi := &file_common_protocol_headers_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *SecurityConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SecurityConfig) ProtoMessage() {} func (x *SecurityConfig) ProtoReflect() protoreflect.Message { mi := &file_common_protocol_headers_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 SecurityConfig.ProtoReflect.Descriptor instead. func (*SecurityConfig) Descriptor() ([]byte, []int) { return file_common_protocol_headers_proto_rawDescGZIP(), []int{0} } func (x *SecurityConfig) GetType() SecurityType { if x != nil { return x.Type } return SecurityType_UNKNOWN } var File_common_protocol_headers_proto protoreflect.FileDescriptor const file_common_protocol_headers_proto_rawDesc = "" + "\n" + "\x1dcommon/protocol/headers.proto\x12\x1av2ray.core.common.protocol\"N\n" + "\x0eSecurityConfig\x12<\n" + "\x04type\x18\x01 \x01(\x0e2(.v2ray.core.common.protocol.SecurityTypeR\x04type*l\n" + "\fSecurityType\x12\v\n" + "\aUNKNOWN\x10\x00\x12\n" + "\n" + "\x06LEGACY\x10\x01\x12\b\n" + "\x04AUTO\x10\x02\x12\x0e\n" + "\n" + "AES128_GCM\x10\x03\x12\x15\n" + "\x11CHACHA20_POLY1305\x10\x04\x12\b\n" + "\x04NONE\x10\x05\x12\b\n" + "\x04ZERO\x10\x06Bo\n" + "\x1ecom.v2ray.core.common.protocolP\x01Z.github.com/v2fly/v2ray-core/v5/common/protocol\xaa\x02\x1aV2Ray.Core.Common.Protocolb\x06proto3" var ( file_common_protocol_headers_proto_rawDescOnce sync.Once file_common_protocol_headers_proto_rawDescData []byte ) func file_common_protocol_headers_proto_rawDescGZIP() []byte { file_common_protocol_headers_proto_rawDescOnce.Do(func() { file_common_protocol_headers_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_common_protocol_headers_proto_rawDesc), len(file_common_protocol_headers_proto_rawDesc))) }) return file_common_protocol_headers_proto_rawDescData } var file_common_protocol_headers_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_common_protocol_headers_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_protocol_headers_proto_goTypes = []any{ (SecurityType)(0), // 0: v2ray.core.common.protocol.SecurityType (*SecurityConfig)(nil), // 1: v2ray.core.common.protocol.SecurityConfig } var file_common_protocol_headers_proto_depIdxs = []int32{ 0, // 0: v2ray.core.common.protocol.SecurityConfig.type:type_name -> v2ray.core.common.protocol.SecurityType 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_common_protocol_headers_proto_init() } func file_common_protocol_headers_proto_init() { if File_common_protocol_headers_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_protocol_headers_proto_rawDesc), len(file_common_protocol_headers_proto_rawDesc)), NumEnums: 1, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_protocol_headers_proto_goTypes, DependencyIndexes: file_common_protocol_headers_proto_depIdxs, EnumInfos: file_common_protocol_headers_proto_enumTypes, MessageInfos: file_common_protocol_headers_proto_msgTypes, }.Build() File_common_protocol_headers_proto = out.File file_common_protocol_headers_proto_goTypes = nil file_common_protocol_headers_proto_depIdxs = nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/errors.generated.go
common/protocol/errors.generated.go
package protocol import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/server_picker.go
common/protocol/server_picker.go
package protocol import ( "sync" ) type ServerList struct { sync.RWMutex servers []*ServerSpec } func NewServerList() *ServerList { return &ServerList{} } func (sl *ServerList) AddServer(server *ServerSpec) { sl.Lock() defer sl.Unlock() sl.servers = append(sl.servers, server) } func (sl *ServerList) Size() uint32 { sl.RLock() defer sl.RUnlock() return uint32(len(sl.servers)) } func (sl *ServerList) GetServer(idx uint32) *ServerSpec { sl.Lock() defer sl.Unlock() for { if idx >= uint32(len(sl.servers)) { return nil } server := sl.servers[idx] if !server.IsValid() { sl.removeServer(idx) continue } return server } } func (sl *ServerList) removeServer(idx uint32) { n := len(sl.servers) sl.servers[idx] = sl.servers[n-1] sl.servers = sl.servers[:n-1] } type ServerPicker interface { PickServer() *ServerSpec } type RoundRobinServerPicker struct { sync.Mutex serverlist *ServerList nextIndex uint32 } func NewRoundRobinServerPicker(serverlist *ServerList) *RoundRobinServerPicker { return &RoundRobinServerPicker{ serverlist: serverlist, nextIndex: 0, } } func (p *RoundRobinServerPicker) PickServer() *ServerSpec { p.Lock() defer p.Unlock() next := p.nextIndex server := p.serverlist.GetServer(next) if server == nil { next = 0 server = p.serverlist.GetServer(0) } next++ if next >= p.serverlist.Size() { next = 0 } p.nextIndex = next return server }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/id_test.go
common/protocol/id_test.go
package protocol_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/uuid" ) func TestIdEquals(t *testing.T) { id1 := NewID(uuid.New()) id2 := NewID(id1.UUID()) if !id1.Equals(id2) { t.Error("expected id1 to equal id2, but actually not") } if id1.String() != id2.String() { t.Error(id1.String(), " != ", id2.String()) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/protocol.go
common/protocol/protocol.go
package protocol import ( "errors" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen var ErrProtoNeedMoreData = errors.New("protocol matches, but need more data to complete sniffing")
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/server_spec.go
common/protocol/server_spec.go
package protocol import ( "sync" "time" "github.com/v2fly/v2ray-core/v5/common/dice" "github.com/v2fly/v2ray-core/v5/common/net" ) type ValidationStrategy interface { IsValid() bool Invalidate() } type alwaysValidStrategy struct{} func AlwaysValid() ValidationStrategy { return alwaysValidStrategy{} } func (alwaysValidStrategy) IsValid() bool { return true } func (alwaysValidStrategy) Invalidate() {} type timeoutValidStrategy struct { until time.Time } func BeforeTime(t time.Time) ValidationStrategy { return &timeoutValidStrategy{ until: t, } } func (s *timeoutValidStrategy) IsValid() bool { return s.until.After(time.Now()) } func (s *timeoutValidStrategy) Invalidate() { s.until = time.Time{} } type ServerSpec struct { sync.RWMutex dest net.Destination users []*MemoryUser valid ValidationStrategy } func NewServerSpec(dest net.Destination, valid ValidationStrategy, users ...*MemoryUser) *ServerSpec { return &ServerSpec{ dest: dest, users: users, valid: valid, } } func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) { dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port)) mUsers := make([]*MemoryUser, len(spec.User)) for idx, u := range spec.User { mUser, err := u.ToMemoryUser() if err != nil { return nil, err } mUsers[idx] = mUser } return NewServerSpec(dest, AlwaysValid(), mUsers...), nil } func (s *ServerSpec) Destination() net.Destination { return s.dest } func (s *ServerSpec) HasUser(user *MemoryUser) bool { s.RLock() defer s.RUnlock() for _, u := range s.users { if u.Account.Equals(user.Account) { return true } } return false } func (s *ServerSpec) AddUser(user *MemoryUser) { if s.HasUser(user) { return } s.Lock() defer s.Unlock() s.users = append(s.users, user) } func (s *ServerSpec) PickUser() *MemoryUser { s.RLock() defer s.RUnlock() userCount := len(s.users) switch userCount { case 0: return nil case 1: return s.users[0] default: return s.users[dice.Roll(userCount)] } } func (s *ServerSpec) IsValid() bool { return s.valid.IsValid() } func (s *ServerSpec) Invalidate() { s.valid.Invalidate() }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/id.go
common/protocol/id.go
package protocol import ( "crypto/hmac" "crypto/md5" "hash" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/uuid" ) const ( IDBytesLen = 16 ) type IDHash func(key []byte) hash.Hash func DefaultIDHash(key []byte) hash.Hash { return hmac.New(md5.New, key) } // The ID of en entity, in the form of a UUID. type ID struct { uuid uuid.UUID cmdKey [IDBytesLen]byte } // Equals returns true if this ID equals to the other one. func (id *ID) Equals(another *ID) bool { return id.uuid.Equals(&(another.uuid)) } func (id *ID) Bytes() []byte { return id.uuid.Bytes() } func (id *ID) String() string { return id.uuid.String() } func (id *ID) UUID() uuid.UUID { return id.uuid } func (id ID) CmdKey() []byte { return id.cmdKey[:] } // NewID returns an ID with given UUID. func NewID(uuid uuid.UUID) *ID { id := &ID{uuid: uuid} md5hash := md5.New() common.Must2(md5hash.Write(uuid.Bytes())) common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))) md5hash.Sum(id.cmdKey[:0]) return id } func nextID(u *uuid.UUID) uuid.UUID { md5hash := md5.New() common.Must2(md5hash.Write(u.Bytes())) common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))) var newid uuid.UUID for { md5hash.Sum(newid[:0]) if !newid.Equals(u) { return newid } common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))) } } func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID { alterIDs := make([]*ID, alterIDCount) prevID := primary.UUID() for idx := range alterIDs { newid := nextID(&prevID) alterIDs[idx] = NewID(newid) prevID = newid } return alterIDs }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/server_spec_test.go
common/protocol/server_spec_test.go
package protocol_test import ( "strings" "testing" "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" . "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/uuid" "github.com/v2fly/v2ray-core/v5/proxy/vmess" ) func TestAlwaysValidStrategy(t *testing.T) { strategy := AlwaysValid() if !strategy.IsValid() { t.Error("strategy not valid") } strategy.Invalidate() if !strategy.IsValid() { t.Error("strategy not valid") } } func TestTimeoutValidStrategy(t *testing.T) { strategy := BeforeTime(time.Now().Add(2 * time.Second)) if !strategy.IsValid() { t.Error("strategy not valid") } time.Sleep(3 * time.Second) if strategy.IsValid() { t.Error("strategy is valid") } strategy = BeforeTime(time.Now().Add(2 * time.Second)) strategy.Invalidate() if strategy.IsValid() { t.Error("strategy is valid") } } func TestUserInServerSpec(t *testing.T) { uuid1 := uuid.New() uuid2 := uuid.New() toAccount := func(a *vmess.Account) Account { account, err := a.AsAccount() common.Must(err) return account } spec := NewServerSpec(net.Destination{}, AlwaysValid(), &MemoryUser{ Email: "test1@v2fly.org", Account: toAccount(&vmess.Account{Id: uuid1.String()}), }) if spec.HasUser(&MemoryUser{ Email: "test1@v2fly.org", Account: toAccount(&vmess.Account{Id: uuid2.String()}), }) { t.Error("has user: ", uuid2) } spec.AddUser(&MemoryUser{Email: "test2@v2fly.org"}) if !spec.HasUser(&MemoryUser{ Email: "test1@v2fly.org", Account: toAccount(&vmess.Account{Id: uuid1.String()}), }) { t.Error("not having user: ", uuid1) } } func TestPickUser(t *testing.T) { spec := NewServerSpec(net.Destination{}, AlwaysValid(), &MemoryUser{Email: "test1@v2fly.org"}, &MemoryUser{Email: "test2@v2fly.org"}, &MemoryUser{Email: "test3@v2fly.org"}) user := spec.PickUser() if !strings.HasSuffix(user.Email, "@v2fly.org") { t.Error("user: ", user.Email) } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/payload.go
common/protocol/payload.go
package protocol type TransferType byte const ( TransferTypeStream TransferType = 0 TransferTypePacket TransferType = 1 ) type AddressType byte const ( AddressTypeIPv4 AddressType = 1 AddressTypeDomain AddressType = 2 AddressTypeIPv6 AddressType = 3 )
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/address_test.go
common/protocol/address_test.go
package protocol_test import ( "bytes" "testing" "github.com/google/go-cmp/cmp" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" . "github.com/v2fly/v2ray-core/v5/common/protocol" ) func TestAddressReading(t *testing.T) { data := []struct { Options []AddressOption Input []byte Address net.Address Port net.Port Error bool }{ { Options: []AddressOption{}, Input: []byte{}, Error: true, }, { Options: []AddressOption{}, Input: []byte{0, 0, 0, 0, 0}, Error: true, }, { Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)}, Input: []byte{1, 0, 0, 0, 0, 0, 53}, Address: net.IPAddress([]byte{0, 0, 0, 0}), Port: net.Port(53), }, { Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4), PortThenAddress()}, Input: []byte{0, 53, 1, 0, 0, 0, 0}, Address: net.IPAddress([]byte{0, 0, 0, 0}), Port: net.Port(53), }, { Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)}, Input: []byte{1, 0, 0, 0, 0}, Error: true, }, { Options: []AddressOption{AddressFamilyByte(0x04, net.AddressFamilyIPv6)}, Input: []byte{4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 80}, Address: net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}), Port: net.Port(80), }, { Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, Input: []byte{3, 9, 118, 50, 102, 108, 121, 46, 111, 114, 103, 0, 80}, Address: net.DomainAddress("v2fly.org"), Port: net.Port(80), }, { Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, Input: []byte{3, 9, 118, 50, 102, 108, 121, 46, 111, 114, 103, 0}, Error: true, }, { Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, Input: []byte{3, 7, 56, 46, 56, 46, 56, 46, 56, 0, 80}, Address: net.ParseAddress("8.8.8.8"), Port: net.Port(80), }, { Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, Input: []byte{3, 7, 10, 46, 56, 46, 56, 46, 56, 0, 80}, Error: true, }, { Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, Input: append(append([]byte{3, 24}, []byte("2a00:1450:4007:816::200e")...), 0, 80), Address: net.ParseAddress("2a00:1450:4007:816::200e"), Port: net.Port(80), }, } for _, tc := range data { b := buf.New() parser := NewAddressParser(tc.Options...) addr, port, err := parser.ReadAddressPort(b, bytes.NewReader(tc.Input)) b.Release() if tc.Error { if err == nil { t.Errorf("Expect error but not: %v", tc) } } else { if err != nil { t.Errorf("Expect no error but: %s %v", err.Error(), tc) } if addr != tc.Address { t.Error("Got address ", addr.String(), " want ", tc.Address.String()) } if tc.Port != port { t.Error("Got port ", port, " want ", tc.Port) } } } } func TestAddressWriting(t *testing.T) { data := []struct { Options []AddressOption Address net.Address Port net.Port Bytes []byte Error bool }{ { Options: []AddressOption{AddressFamilyByte(0x01, net.AddressFamilyIPv4)}, Address: net.LocalHostIP, Port: net.Port(80), Bytes: []byte{1, 127, 0, 0, 1, 0, 80}, }, } for _, tc := range data { parser := NewAddressParser(tc.Options...) b := buf.New() err := parser.WriteAddressPort(b, tc.Address, tc.Port) if tc.Error { if err == nil { t.Error("Expect error but nil") } } else { common.Must(err) if diff := cmp.Diff(tc.Bytes, b.Bytes()); diff != "" { t.Error(err) } } } } func BenchmarkAddressReadingIPv4(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x01, net.AddressFamilyIPv4)) cache := buf.New() defer cache.Release() payload := buf.New() defer payload.Release() raw := []byte{1, 0, 0, 0, 0, 0, 53} payload.Write(raw) b.ResetTimer() for i := 0; i < b.N; i++ { _, _, err := parser.ReadAddressPort(cache, payload) common.Must(err) cache.Clear() payload.Clear() payload.Extend(int32(len(raw))) } } func BenchmarkAddressReadingIPv6(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x04, net.AddressFamilyIPv6)) cache := buf.New() defer cache.Release() payload := buf.New() defer payload.Release() raw := []byte{4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 80} payload.Write(raw) b.ResetTimer() for i := 0; i < b.N; i++ { _, _, err := parser.ReadAddressPort(cache, payload) common.Must(err) cache.Clear() payload.Clear() payload.Extend(int32(len(raw))) } } func BenchmarkAddressReadingDomain(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x03, net.AddressFamilyDomain)) cache := buf.New() defer cache.Release() payload := buf.New() defer payload.Release() raw := []byte{3, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0, 80} payload.Write(raw) b.ResetTimer() for i := 0; i < b.N; i++ { _, _, err := parser.ReadAddressPort(cache, payload) common.Must(err) cache.Clear() payload.Clear() payload.Extend(int32(len(raw))) } } func BenchmarkAddressWritingIPv4(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x01, net.AddressFamilyIPv4)) writer := buf.New() defer writer.Release() b.ResetTimer() for i := 0; i < b.N; i++ { common.Must(parser.WriteAddressPort(writer, net.LocalHostIP, net.Port(80))) writer.Clear() } } func BenchmarkAddressWritingIPv6(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x04, net.AddressFamilyIPv6)) writer := buf.New() defer writer.Release() b.ResetTimer() for i := 0; i < b.N; i++ { common.Must(parser.WriteAddressPort(writer, net.LocalHostIPv6, net.Port(80))) writer.Clear() } } func BenchmarkAddressWritingDomain(b *testing.B) { parser := NewAddressParser(AddressFamilyByte(0x02, net.AddressFamilyDomain)) writer := buf.New() defer writer.Release() b.ResetTimer() for i := 0; i < b.N; i++ { common.Must(parser.WriteAddressPort(writer, net.DomainAddress("www.v2fly.org"), net.Port(80))) writer.Clear() } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/context.go
common/protocol/context.go
package protocol import ( "context" ) type key int const ( requestKey key = iota ) func ContextWithRequestHeader(ctx context.Context, request *RequestHeader) context.Context { return context.WithValue(ctx, requestKey, request) } func RequestHeaderFromContext(ctx context.Context) *RequestHeader { request := ctx.Value(requestKey) if request == nil { return nil } return request.(*RequestHeader) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/user.go
common/protocol/user.go
package protocol import "github.com/v2fly/v2ray-core/v5/common/serial" func (u *User) GetTypedAccount() (Account, error) { if u.GetAccount() == nil { return nil, newError("Account missing").AtWarning() } rawAccount, err := serial.GetInstanceOf(u.Account) if err != nil { return nil, err } if asAccount, ok := rawAccount.(AsAccount); ok { return asAccount.AsAccount() } if account, ok := rawAccount.(Account); ok { return account, nil } return nil, newError("Unknown account type: ", serial.V2Type(u.Account)) } func (u *User) ToMemoryUser() (*MemoryUser, error) { account, err := u.GetTypedAccount() if err != nil { return nil, err } return &MemoryUser{ Account: account, Email: u.Email, Level: u.Level, }, nil } // MemoryUser is a parsed form of User, to reduce number of parsing of Account proto. type MemoryUser struct { // Account is the parsed account of the protocol. Account Account Email string Level uint32 }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/server_spec.pb.go
common/protocol/server_spec.pb.go
package protocol import ( net "github.com/v2fly/v2ray-core/v5/common/net" 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 ServerEndpoint struct { state protoimpl.MessageState `protogen:"open.v1"` Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` User []*User `protobuf:"bytes,3,rep,name=user,proto3" json:"user,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ServerEndpoint) Reset() { *x = ServerEndpoint{} mi := &file_common_protocol_server_spec_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ServerEndpoint) String() string { return protoimpl.X.MessageStringOf(x) } func (*ServerEndpoint) ProtoMessage() {} func (x *ServerEndpoint) ProtoReflect() protoreflect.Message { mi := &file_common_protocol_server_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 ServerEndpoint.ProtoReflect.Descriptor instead. func (*ServerEndpoint) Descriptor() ([]byte, []int) { return file_common_protocol_server_spec_proto_rawDescGZIP(), []int{0} } func (x *ServerEndpoint) GetAddress() *net.IPOrDomain { if x != nil { return x.Address } return nil } func (x *ServerEndpoint) GetPort() uint32 { if x != nil { return x.Port } return 0 } func (x *ServerEndpoint) GetUser() []*User { if x != nil { return x.User } return nil } var File_common_protocol_server_spec_proto protoreflect.FileDescriptor const file_common_protocol_server_spec_proto_rawDesc = "" + "\n" + "!common/protocol/server_spec.proto\x12\x1av2ray.core.common.protocol\x1a\x18common/net/address.proto\x1a\x1acommon/protocol/user.proto\"\x97\x01\n" + "\x0eServerEndpoint\x12;\n" + "\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" + "\x04port\x18\x02 \x01(\rR\x04port\x124\n" + "\x04user\x18\x03 \x03(\v2 .v2ray.core.common.protocol.UserR\x04userBo\n" + "\x1ecom.v2ray.core.common.protocolP\x01Z.github.com/v2fly/v2ray-core/v5/common/protocol\xaa\x02\x1aV2Ray.Core.Common.Protocolb\x06proto3" var ( file_common_protocol_server_spec_proto_rawDescOnce sync.Once file_common_protocol_server_spec_proto_rawDescData []byte ) func file_common_protocol_server_spec_proto_rawDescGZIP() []byte { file_common_protocol_server_spec_proto_rawDescOnce.Do(func() { file_common_protocol_server_spec_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_common_protocol_server_spec_proto_rawDesc), len(file_common_protocol_server_spec_proto_rawDesc))) }) return file_common_protocol_server_spec_proto_rawDescData } var file_common_protocol_server_spec_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_protocol_server_spec_proto_goTypes = []any{ (*ServerEndpoint)(nil), // 0: v2ray.core.common.protocol.ServerEndpoint (*net.IPOrDomain)(nil), // 1: v2ray.core.common.net.IPOrDomain (*User)(nil), // 2: v2ray.core.common.protocol.User } var file_common_protocol_server_spec_proto_depIdxs = []int32{ 1, // 0: v2ray.core.common.protocol.ServerEndpoint.address:type_name -> v2ray.core.common.net.IPOrDomain 2, // 1: v2ray.core.common.protocol.ServerEndpoint.user:type_name -> v2ray.core.common.protocol.User 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_common_protocol_server_spec_proto_init() } func file_common_protocol_server_spec_proto_init() { if File_common_protocol_server_spec_proto != nil { return } file_common_protocol_user_proto_init() type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_protocol_server_spec_proto_rawDesc), len(file_common_protocol_server_spec_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_protocol_server_spec_proto_goTypes, DependencyIndexes: file_common_protocol_server_spec_proto_depIdxs, MessageInfos: file_common_protocol_server_spec_proto_msgTypes, }.Build() File_common_protocol_server_spec_proto = out.File file_common_protocol_server_spec_proto_goTypes = nil file_common_protocol_server_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/common/protocol/address.go
common/protocol/address.go
package protocol import ( "io" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/serial" ) type AddressOption func(*option) func PortThenAddress() AddressOption { return func(p *option) { p.portFirst = true } } func AddressFamilyByte(b byte, f net.AddressFamily) AddressOption { if b >= 16 { panic("address family byte too big") } return func(p *option) { p.addrTypeMap[b] = f p.addrByteMap[f] = b } } type AddressTypeParser func(byte) byte func WithAddressTypeParser(atp AddressTypeParser) AddressOption { return func(p *option) { p.typeParser = atp } } type AddressSerializer interface { ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error) WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error } const afInvalid = 255 type option struct { addrTypeMap [16]net.AddressFamily addrByteMap [16]byte portFirst bool typeParser AddressTypeParser } // NewAddressParser creates a new AddressParser func NewAddressParser(options ...AddressOption) AddressSerializer { var o option for i := range o.addrByteMap { o.addrByteMap[i] = afInvalid } for i := range o.addrTypeMap { o.addrTypeMap[i] = net.AddressFamily(afInvalid) } for _, opt := range options { opt(&o) } ap := &addressParser{ addrByteMap: o.addrByteMap, addrTypeMap: o.addrTypeMap, } if o.typeParser != nil { ap.typeParser = o.typeParser } if o.portFirst { return portFirstAddressParser{ap: ap} } return portLastAddressParser{ap: ap} } type portFirstAddressParser struct { ap *addressParser } func (p portFirstAddressParser) ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error) { if buffer == nil { buffer = buf.New() defer buffer.Release() } port, err := readPort(buffer, input) if err != nil { return nil, 0, err } addr, err := p.ap.readAddress(buffer, input) if err != nil { return nil, 0, err } return addr, port, nil } func (p portFirstAddressParser) WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error { if err := writePort(writer, port); err != nil { return err } return p.ap.writeAddress(writer, addr) } type portLastAddressParser struct { ap *addressParser } func (p portLastAddressParser) ReadAddressPort(buffer *buf.Buffer, input io.Reader) (net.Address, net.Port, error) { if buffer == nil { buffer = buf.New() defer buffer.Release() } addr, err := p.ap.readAddress(buffer, input) if err != nil { return nil, 0, err } port, err := readPort(buffer, input) if err != nil { return nil, 0, err } return addr, port, nil } func (p portLastAddressParser) WriteAddressPort(writer io.Writer, addr net.Address, port net.Port) error { if err := p.ap.writeAddress(writer, addr); err != nil { return err } return writePort(writer, port) } func readPort(b *buf.Buffer, reader io.Reader) (net.Port, error) { if _, err := b.ReadFullFrom(reader, 2); err != nil { return 0, err } return net.PortFromBytes(b.BytesFrom(-2)), nil } func writePort(writer io.Writer, port net.Port) error { return common.Error2(serial.WriteUint16(writer, port.Value())) } func maybeIPPrefix(b byte) bool { return b == '[' || (b >= '0' && b <= '9') } func isValidDomain(d string) bool { for _, c := range d { if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '.' || c == '_') { return false } } return true } type addressParser struct { addrTypeMap [16]net.AddressFamily addrByteMap [16]byte typeParser AddressTypeParser } func (p *addressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Address, error) { if _, err := b.ReadFullFrom(reader, 1); err != nil { return nil, err } addrType := b.Byte(b.Len() - 1) if p.typeParser != nil { addrType = p.typeParser(addrType) } if addrType >= 16 { return nil, newError("unknown address type: ", addrType) } addrFamily := p.addrTypeMap[addrType] if addrFamily == net.AddressFamily(afInvalid) { return nil, newError("unknown address type: ", addrType) } switch addrFamily { case net.AddressFamilyIPv4: if _, err := b.ReadFullFrom(reader, 4); err != nil { return nil, err } return net.IPAddress(b.BytesFrom(-4)), nil case net.AddressFamilyIPv6: if _, err := b.ReadFullFrom(reader, 16); err != nil { return nil, err } return net.IPAddress(b.BytesFrom(-16)), nil case net.AddressFamilyDomain: if _, err := b.ReadFullFrom(reader, 1); err != nil { return nil, err } domainLength := int32(b.Byte(b.Len() - 1)) if _, err := b.ReadFullFrom(reader, domainLength); err != nil { return nil, err } domain := string(b.BytesFrom(-domainLength)) if maybeIPPrefix(domain[0]) { addr := net.ParseAddress(domain) if addr.Family().IsIP() { return addr, nil } } if !isValidDomain(domain) { return nil, newError("invalid domain name: ", domain) } return net.DomainAddress(domain), nil default: panic("impossible case") } } func (p *addressParser) writeAddress(writer io.Writer, address net.Address) error { tb := p.addrByteMap[address.Family()] if tb == afInvalid { return newError("unknown address family", address.Family()) } switch address.Family() { case net.AddressFamilyIPv4, net.AddressFamilyIPv6: if _, err := writer.Write([]byte{tb}); err != nil { return err } if _, err := writer.Write(address.IP()); err != nil { return err } case net.AddressFamilyDomain: domain := address.Domain() if IsDomainTooLong(domain) { return newError("Super long domain is not supported: ", domain) } if _, err := writer.Write([]byte{tb, byte(len(domain))}); err != nil { return err } if _, err := writer.Write([]byte(domain)); err != nil { return err } default: panic("Unknown family type.") } return nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/account.go
common/protocol/account.go
package protocol // Account is a user identity used for authentication. type Account interface { Equals(Account) bool } // AsAccount is an object can be converted into account. type AsAccount interface { AsAccount() (Account, error) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/headers.go
common/protocol/headers.go
package protocol import ( "runtime" "golang.org/x/sys/cpu" "github.com/v2fly/v2ray-core/v5/common/bitmask" "github.com/v2fly/v2ray-core/v5/common/net" "github.com/v2fly/v2ray-core/v5/common/uuid" ) // RequestCommand is a custom command in a proxy request. type RequestCommand byte const ( RequestCommandTCP = RequestCommand(0x01) RequestCommandUDP = RequestCommand(0x02) RequestCommandMux = RequestCommand(0x03) ) func (c RequestCommand) TransferType() TransferType { switch c { case RequestCommandTCP, RequestCommandMux: return TransferTypeStream case RequestCommandUDP: return TransferTypePacket default: return TransferTypeStream } } const ( // RequestOptionChunkStream indicates request payload is chunked. Each chunk consists of length, authentication and payload. RequestOptionChunkStream bitmask.Byte = 0x01 // RequestOptionConnectionReuse indicates client side expects to reuse the connection. RequestOptionConnectionReuse bitmask.Byte = 0x02 RequestOptionChunkMasking bitmask.Byte = 0x04 RequestOptionGlobalPadding bitmask.Byte = 0x08 RequestOptionAuthenticatedLength bitmask.Byte = 0x10 ) type RequestHeader struct { Version byte Command RequestCommand Option bitmask.Byte Security SecurityType Port net.Port Address net.Address User *MemoryUser } func (h *RequestHeader) Destination() net.Destination { if h.Command == RequestCommandUDP { return net.UDPDestination(h.Address, h.Port) } return net.TCPDestination(h.Address, h.Port) } const ( ResponseOptionConnectionReuse bitmask.Byte = 0x01 ) type ResponseCommand interface{} type ResponseHeader struct { Option bitmask.Byte Command ResponseCommand } type CommandSwitchAccount struct { Host net.Address Port net.Port ID uuid.UUID Level uint32 AlterIds uint16 ValidMin byte } var ( hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL // Keep in sync with crypto/aes/cipher_s390x.go. hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 || runtime.GOARCH == "arm64" && hasGCMAsmARM64 || runtime.GOARCH == "s390x" && hasGCMAsmS390X ) func (sc *SecurityConfig) GetSecurityType() SecurityType { if sc == nil || sc.Type == SecurityType_AUTO { if hasAESGCMHardwareSupport { return SecurityType_AES128_GCM } return SecurityType_CHACHA20_POLY1305 } return sc.Type } func IsDomainTooLong(domain string) bool { return len(domain) > 255 }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/quic/sniff.go
common/protocol/quic/sniff.go
package quic import ( "crypto" "crypto/aes" "crypto/tls" "encoding/binary" "io" "github.com/quic-go/quic-go/quicvarint" "golang.org/x/crypto/hkdf" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/errors" "github.com/v2fly/v2ray-core/v5/common/protocol" ptls "github.com/v2fly/v2ray-core/v5/common/protocol/tls" ) type SniffHeader struct { domain string } func (s SniffHeader) Protocol() string { return "quic" } func (s SniffHeader) Domain() string { return s.domain } const ( versionDraft29 uint32 = 0xff00001d version1 uint32 = 0x1 ) var ( quicSaltOld = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99} quicSalt = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a} initialSuite = &cipherSuiteTLS13{ ID: tls.TLS_AES_128_GCM_SHA256, KeyLen: 16, AEAD: aeadAESGCMTLS13, Hash: crypto.SHA256, } errNotQuic = errors.New("not quic") errNotQuicInitial = errors.New("not initial packet") ) func SniffQUIC(b []byte) (*SniffHeader, error) { if len(b) == 0 { return nil, common.ErrNoClue } // Crypto data separated across packets cryptoLen := 0 cryptoDataBuf := buf.NewWithSize(32767) defer cryptoDataBuf.Release() cache := buf.New() defer cache.Release() // Parse QUIC packets for len(b) > 0 { buffer := buf.FromBytes(b) typeByte, err := buffer.ReadByte() if err != nil { return nil, errNotQuic } isLongHeader := typeByte&0x80 > 0 if !isLongHeader || typeByte&0x40 == 0 { return nil, errNotQuicInitial } vb, err := buffer.ReadBytes(4) if err != nil { return nil, errNotQuic } versionNumber := binary.BigEndian.Uint32(vb) if versionNumber != 0 && typeByte&0x40 == 0 { return nil, errNotQuic } else if versionNumber != versionDraft29 && versionNumber != version1 { return nil, errNotQuic } packetType := (typeByte & 0x30) >> 4 isQuicInitial := packetType == 0x0 var destConnID []byte if l, err := buffer.ReadByte(); err != nil { return nil, errNotQuic } else if destConnID, err = buffer.ReadBytes(int32(l)); err != nil { return nil, errNotQuic } if l, err := buffer.ReadByte(); err != nil { return nil, errNotQuic } else if common.Error2(buffer.ReadBytes(int32(l))) != nil { return nil, errNotQuic } if isQuicInitial { // Only initial packets have token, see https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.2 tokenLen, err := quicvarint.Read(buffer) if err != nil || tokenLen > uint64(len(b)) { return nil, errNotQuic } if _, err = buffer.ReadBytes(int32(tokenLen)); err != nil { return nil, errNotQuic } } packetLen, err := quicvarint.Read(buffer) if err != nil { return nil, errNotQuic } // packet is impossible to shorter than this if packetLen < 4 { return nil, errNotQuic } hdrLen := len(b) - int(buffer.Len()) if len(b) < hdrLen+int(packetLen) { return nil, common.ErrNoClue // Not enough data to read as a QUIC packet. QUIC is UDP-based, so this is unlikely to happen. } restPayload := b[hdrLen+int(packetLen):] if !isQuicInitial { // Skip this packet if it's not initial packet b = restPayload continue } origPNBytes := make([]byte, 4) copy(origPNBytes, b[hdrLen:hdrLen+4]) var salt []byte if versionNumber == version1 { salt = quicSalt } else { salt = quicSaltOld } initialSecret := hkdf.Extract(crypto.SHA256.New, destConnID, salt) secret := hkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size()) hpKey := hkdfExpandLabel(initialSuite.Hash, secret, []byte{}, "quic hp", initialSuite.KeyLen) block, err := aes.NewCipher(hpKey) if err != nil { return nil, err } cache.Clear() mask := cache.Extend(int32(block.BlockSize())) block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16]) b[0] ^= mask[0] & 0xf for i := range b[hdrLen : hdrLen+4] { b[hdrLen+i] ^= mask[i+1] } packetNumberLength := b[0]&0x3 + 1 if packetNumberLength != 1 { return nil, errNotQuicInitial } var packetNumber uint32 { n, err := buffer.ReadByte() if err != nil { return nil, err } packetNumber = uint32(n) } extHdrLen := hdrLen + int(packetNumberLength) copy(b[extHdrLen:hdrLen+4], origPNBytes[packetNumberLength:]) data := b[extHdrLen : int(packetLen)+hdrLen] key := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16) iv := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12) cipher := aeadAESGCMTLS13(key, iv) nonce := cache.Extend(int32(cipher.NonceSize())) binary.BigEndian.PutUint64(nonce[len(nonce)-8:], uint64(packetNumber)) decrypted, err := cipher.Open(b[extHdrLen:extHdrLen], nonce, data, b[:extHdrLen]) if err != nil { return nil, err } buffer = buf.FromBytes(decrypted) for i := 0; !buffer.IsEmpty(); i++ { frameType := byte(0x0) // Default to PADDING frame for frameType == 0x0 && !buffer.IsEmpty() { frameType, _ = buffer.ReadByte() } switch frameType { case 0x00: // PADDING frame case 0x01: // PING frame case 0x02, 0x03: // ACK frame if _, err = quicvarint.Read(buffer); err != nil { // Field: Largest Acknowledged return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Delay return nil, io.ErrUnexpectedEOF } ackRangeCount, err := quicvarint.Read(buffer) // Field: ACK Range Count if err != nil { return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { // Field: First ACK Range return nil, io.ErrUnexpectedEOF } for i := 0; i < int(ackRangeCount); i++ { // Field: ACK Range if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> Gap return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> ACK Range Length return nil, io.ErrUnexpectedEOF } } if frameType == 0x03 { if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT0 Count return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT1 Count return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { //nolint:misspell // Field: ECN Counts -> ECT-CE Count return nil, io.ErrUnexpectedEOF } } case 0x06: // CRYPTO frame, we will use this frame offset, err := quicvarint.Read(buffer) // Field: Offset if err != nil { return nil, io.ErrUnexpectedEOF } length, err := quicvarint.Read(buffer) // Field: Length if err != nil || length > uint64(buffer.Len()) { return nil, io.ErrUnexpectedEOF } if cryptoLen < int(offset+length) { cryptoLen = int(offset + length) if cryptoDataBuf.Cap() < int32(cryptoLen) { return nil, io.ErrShortBuffer } if cryptoDataBuf.Len() != int32(cryptoLen) { cryptoDataBuf.Extend(int32(cryptoLen) - cryptoDataBuf.Len()) } } if _, err := buffer.Read(cryptoDataBuf.BytesRange(int32(offset), int32(offset+length))); err != nil { // Field: Crypto Data return nil, io.ErrUnexpectedEOF } case 0x1c: // CONNECTION_CLOSE frame, only 0x1c is permitted in initial packet if _, err = quicvarint.Read(buffer); err != nil { // Field: Error Code return nil, io.ErrUnexpectedEOF } if _, err = quicvarint.Read(buffer); err != nil { // Field: Frame Type return nil, io.ErrUnexpectedEOF } length, err := quicvarint.Read(buffer) // Field: Reason Phrase Length if err != nil { return nil, io.ErrUnexpectedEOF } if _, err := buffer.ReadBytes(int32(length)); err != nil { // Field: Reason Phrase return nil, io.ErrUnexpectedEOF } default: // Only above frame types are permitted in initial packet. // See https://www.rfc-editor.org/rfc/rfc9000.html#section-17.2.2-8 return nil, errNotQuicInitial } } tlsHdr := &ptls.SniffHeader{} err = ptls.ReadClientHello(cryptoDataBuf.BytesRange(0, int32(cryptoLen)), tlsHdr) if err != nil { // The crypto data may have not been fully recovered in current packets, // So we continue to sniff rest packets. b = restPayload continue } return &SniffHeader{domain: tlsHdr.Domain()}, nil } // All payload is parsed as valid QUIC packets, but we need more packets for crypto data to read client hello. return nil, protocol.ErrProtoNeedMoreData } func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte { b := make([]byte, 3, 3+6+len(label)+1+len(context)) binary.BigEndian.PutUint16(b, uint16(length)) b[2] = uint8(6 + len(label)) b = append(b, []byte("tls13 ")...) b = append(b, []byte(label)...) b = b[:3+6+len(label)+1] b[3+6+len(label)] = uint8(len(context)) b = append(b, context...) out := make([]byte, length) n, err := hkdf.Expand(hash.New, secret, b).Read(out) if err != nil || n != length { panic("quic: HKDF-Expand-Label invocation failed unexpectedly") } return out }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/quic/cipher_suite.go
common/protocol/quic/cipher_suite.go
package quic import ( "crypto" "crypto/cipher" _ "crypto/tls" _ "unsafe" ) // copied from github.com/quic-go/quic-go/internal/qtls/cipher_suite_go121.go type cipherSuiteTLS13 struct { ID uint16 KeyLen int AEAD func(key, fixedNonce []byte) cipher.AEAD Hash crypto.Hash } // github.com/quic-go/quic-go/internal/handshake/cipher_suite.go describes these cipher suite implementations are copied from the standard library crypto/tls package. // So we can user go:linkname to implement the same feature. //go:linkname aeadAESGCMTLS13 crypto/tls.aeadAESGCMTLS13 func aeadAESGCMTLS13(key, nonceMask []byte) cipher.AEAD
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/quic/sniff_test.go
common/protocol/quic/sniff_test.go
package quic_test import ( "encoding/hex" "errors" "testing" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/protocol/quic" ) func TestSniffQUIC(t *testing.T) { pkt, err := hex.DecodeString("cd0000000108f1fb7bcc78aa5e7203a8f86400421531fe825b19541876db6c55c38890cd73149d267a084afee6087304095417a3033df6a81bbb71d8512e7a3e16df1e277cae5df3182cb214b8fe982ba3fdffbaa9ffec474547d55945f0fddbeadfb0b5243890b2fa3da45169e2bd34ec04b2e29382f48d612b28432a559757504d158e9e505407a77dd34f4b60b8d3b555ee85aacd6648686802f4de25e7216b19e54c5f78e8a5963380c742d861306db4c16e4f7fc94957aa50b9578a0b61f1e406b2ad5f0cd3cd271c4d99476409797b0c3cb3efec256118912d4b7e4fd79d9cb9016b6e5eaa4f5e57b637b217755daf8968a4092bed0ed5413f5d04904b3a61e4064f9211b2629e5b52a89c7b19f37a713e41e27743ea6dfa736dfa1bb0a4b2bc8c8dc632c6ce963493a20c550e6fdb2475213665e9a85cfc394da9cec0cf41f0c8abed3fc83be5245b2b5aa5e825d29349f721d30774ef5bf965b540f3d8d98febe20956b1fc8fa047e10e7d2f921c9c6622389e02322e80621a1cf5264e245b7276966eb02932584e3f7038bd36aa908766ad3fb98344025dec18670d6db43a1c5daac00937fce7b7c7d61ff4e6efd01a2bdee0ee183108b926393df4f3d74bbcbb015f240e7e346b7d01c41111a401225ce3b095ab4623a5836169bf9599eeca79d1d2e9b2202b5960a09211e978058d6fc0484eff3e91ce4649a5e3ba15b906d334cf66e28d9ff575406e1ae1ac2febafd72870b6f5d58fc5fb949cb1f40feb7c1d9ce5e71b") common.Must(err) quicHdr, err := quic.SniffQUIC(pkt) if err != nil || quicHdr.Domain() != "www.google.com" { t.Error("failed") } } func TestSniffQUICComplex(t *testing.T) { tests := []struct { name string hexData string domain string wantErr bool needsMoreData bool }{ { name: "EmptyPacket", hexData: "0000000000000000000000000000000000000000000000000000000000000000", domain: "", wantErr: true, needsMoreData: false, }, { name: "NTP Packet Client", hexData: "23000000000000000000000000000000000000000000000000000000000000000000000000000000acb84a797d4044c9", domain: "", wantErr: true, needsMoreData: false, }, { name: "NTP Packet Server", hexData: "240106ec000000000000000e47505373ea4dcaef2f4b4c31acb84a797d4044c9eb58b8693dd70c27eb58b8693dd7dde2", domain: "", wantErr: true, needsMoreData: false, }, { name: "DNS Packet Client", hexData: "4500004a8e2d40003f1146392a2a2d03080808081eea00350036a8175ad4010000010000000000000675706461746504636f64650c76697375616c73747564696f03636f6d0000010001", domain: "", wantErr: true, needsMoreData: false, }, { name: "DNS Packet Client", hexData: "4500004a667a40003f116dec2a2a2d030808080866980035003605d9b524010000010000000000000675706461746504636f64650c76697375616c73747564696f03636f6d0000410001", domain: "", wantErr: true, needsMoreData: false, }, { name: "DNS Packet Server", hexData: "b524818000010006000100000675706461746504636f64650c76697375616c73747564696f03636f6d0000410001c00c00050001000000ec00301e7673636f64652d7570646174652d67366763623667676474686b63746439037a303107617a7572656664036e657400c03a000500010000000b002311737461722d617a75726566642d70726f640e747261666669636d616e61676572c065c076000500010000003c002c0473686564086475616c2d6c6f770b732d706172742d3030313706742d3030303908742d6d7365646765c065c0a5000500010000006c001411617a75726566642d742d66622d70726f64c088c0dd000500010000003c0026046475616c0b732d706172742d3030313706742d303030390b66622d742d6d7365646765c065c0fd00050001000000300002c102c1150006000100000030002d036e7331c115066d736e687374096d6963726f736f6674c0257848b78d00000708000003840024ea000000003c", domain: "", wantErr: true, needsMoreData: false, }, { name: "DNS Packet Server", hexData: "5ad4818000010007000000000675706461746504636f64650c76697375616c73747564696f03636f6d0000010001c00c000500010000008400301e7673636f64652d7570646174652d67366763623667676474686b63746439037a303107617a7572656664036e657400c03a000500010000001e002311737461722d617a75726566642d70726f640e747261666669636d616e61676572c065c076000500010000003c002c0473686564086475616c2d6c6f770b732d706172742d3030313706742d3030303908742d6d7365646765c065c0a50005000100000010001411617a75726566642d742d66622d70726f64c088c0dd000500010000003c0026046475616c0b732d706172742d3030313706742d303030390b66622d742d6d7365646765c065c0fd00050001000000100002c102c102000100010000001000040d6bfd2d", domain: "", wantErr: true, needsMoreData: false, }, { name: "QUIC, NonHandshake Packet", hexData: "548439ba3a0cffd27dabe08ebf9e603dd4801781e133b1a0276d29a047c3b8856adcced0067c4b11a08985bf93c05863305bd4b43ee9168cd5fdae0c392ff74ae06ce13e8d97dabec81ee927a844fa840f781edf9deb22f3162bf77009b3f5800c5e45539ac104368e7df8ba", domain: "", wantErr: true, needsMoreData: false, }, { name: "QUIC, NonHandshake Packet", hexData: "53f4144825dab3ba251b83d0089e910210bec1a6507cca92ad9ff539cc21f6c75e3551ca44003d9a", domain: "", wantErr: true, needsMoreData: false, }, { name: "QUIC, NonHandshake Packet", hexData: "528dc5524c03e7517949422cc3f6ffbfff74b2ec30a87654a71a", domain: "", wantErr: true, needsMoreData: false, }, { name: "QUIC Chromebook Handshake[1]; packet 1", hexData: "cb00000001088ca3be26059ca269000044d088950f316207d551c91c88d791557c440a19184322536d2c900034358c1b3964f2d2935337b8d044d35bf62b4eea9ceaac64121aa634c7cd28630722d169fa0f215b940d47d7996ca56f0d463dbf97a4a1b5818c5297a26fe58f5553dfb513ad589750a61682f229996555c7121c8bf48b06b68ab06427b01af485d832f9894099a20d3baadcff7b1cf07e2c059d3e7ba88d4ad35ef0ffea1fdc6ac3db271dfcca892a41ab25284936225c9bc593ce242b11b8abed4a8df902987eef0c6d90669e3606f47dd6ad05f44ba3a0cd356854261bbb1e2d8f6b83cc57cfa57eda3e5d7181b6ec418f6eeca81c259a33e4b0a913de720f2f8782764766ac9602a7f52a1082ec3da30dbefcf38c781a3e033810c4f2babf9b72adf7164159d98142181492e4468c0e10ab29013bf238e7360e09767ca49d59a9eb18f06a372bad711fefa90295f8e0839b1080570648212b321e5bd6f614bf0d3dc2817628b0c052a32820c16cb7f531c49244c48eb1429625246f9c164ae4ee1e83eaa8ff0eef1acf5a3d8ca88f1e4597db5ba5c0cb23d6100dd53da4f439ae64c4d3d43d1fbb5677f4fdc3bd2c2948dfc7e0be1a33c842033da15529cfd3cae00da68343d835db867f746854804410ba68f0dd7711b0fe55817b83f6ce1a12ad38acf2a3156f819f0dc68ea799c05583d9728f2856577811b260dba40d6c5e82c9e558c5b8f3f4599caf05ea591118e0b80ad621e0a76e4926047593a896752cb168420cb1b02d4211de5e5b7c891f319b5c0cf687e1d261a01f2acbade6bd73cd1ade0a02e240e9351384e1a6868c21a4878f39f0fa94ee1e36c5a46449241a3fe0147ff50176787eca7f3a936c901aeef56770bff74feecb985e6670d20dfd8ed17952dca5a5292213345c61db09bb5bcf5bf74565f61f9dccab51a289c3160ffe4a9b29cc76ea46778d9317a890efea2ad905f4219463a3baca3c02f5c3682634be7c2e86e366272a8263fec8e871644a79299d4aa74f1b1414b2f963cce6e059978faf813625af7869c1dec92035478c0e46dc66d938d4131aca27a59b2103b8cefa8e08aeb44b53b205b932902aea8d519faaaa12e354a6f532b4f716d7929e655dc2e98b494a99153854af5732a2659f2c21e4069896a1835ad05c5e53781cab16599cf4af47c196deeff9115c80d13f93aeb28b08023e6a1d3cf7da2a4457a9e443176bcdfef8f8de630c02bd0efdc5ddda56ad8f6b47edbda6353205e6e655f690092a48deb7f8a5254a7d778e07216cd97dfefcf740c1acd2977ef0fa17f798ea9752bae46e3aa3ec9b13f4c95c20a7839b8409000fa1f17e8dc46cc05c41bff696ee03c0371cae8638e8018ff4ebedd9f27d56443e534a72dd3d18a64790b676ddd060376759fa4a12ffc17f4be83492126ec1dc0fcd4aefef73a0b9c443ec3532b9a66b1a60daacf45e6557115edc0cc4d08758754a44beffedaa0d1265e50beed1a01752904ee3f7e706ed290b1a79071b142105b7c02e692ff318710e3ce9c3b9ec557cdecef173796417341ada414faa06b52adf645db454b56468ccf0da50a942ebc09487797cb45a085ec1e2e06fcd1f5b72eac291955a62e5aa379a374aea3a0dec3e4e0ba1dde350a94c72dbea7505922e26e99d62f751c2b301413a73fb6b20a36052151473ebecd04d0a771ec326957bc28c2020fdf6f01d9abed69b3c3e73168b404a1748b15310b167396da01c7d", domain: "", wantErr: true, needsMoreData: true, }, { name: "QUIC Chromebook Handshake[1]; packet 1 - 2", hexData: "cb00000001088ca3be26059ca269000044d088950f316207d551c91c88d791557c440a19184322536d2c900034358c1b3964f2d2935337b8d044d35bf62b4eea9ceaac64121aa634c7cd28630722d169fa0f215b940d47d7996ca56f0d463dbf97a4a1b5818c5297a26fe58f5553dfb513ad589750a61682f229996555c7121c8bf48b06b68ab06427b01af485d832f9894099a20d3baadcff7b1cf07e2c059d3e7ba88d4ad35ef0ffea1fdc6ac3db271dfcca892a41ab25284936225c9bc593ce242b11b8abed4a8df902987eef0c6d90669e3606f47dd6ad05f44ba3a0cd356854261bbb1e2d8f6b83cc57cfa57eda3e5d7181b6ec418f6eeca81c259a33e4b0a913de720f2f8782764766ac9602a7f52a1082ec3da30dbefcf38c781a3e033810c4f2babf9b72adf7164159d98142181492e4468c0e10ab29013bf238e7360e09767ca49d59a9eb18f06a372bad711fefa90295f8e0839b1080570648212b321e5bd6f614bf0d3dc2817628b0c052a32820c16cb7f531c49244c48eb1429625246f9c164ae4ee1e83eaa8ff0eef1acf5a3d8ca88f1e4597db5ba5c0cb23d6100dd53da4f439ae64c4d3d43d1fbb5677f4fdc3bd2c2948dfc7e0be1a33c842033da15529cfd3cae00da68343d835db867f746854804410ba68f0dd7711b0fe55817b83f6ce1a12ad38acf2a3156f819f0dc68ea799c05583d9728f2856577811b260dba40d6c5e82c9e558c5b8f3f4599caf05ea591118e0b80ad621e0a76e4926047593a896752cb168420cb1b02d4211de5e5b7c891f319b5c0cf687e1d261a01f2acbade6bd73cd1ade0a02e240e9351384e1a6868c21a4878f39f0fa94ee1e36c5a46449241a3fe0147ff50176787eca7f3a936c901aeef56770bff74feecb985e6670d20dfd8ed17952dca5a5292213345c61db09bb5bcf5bf74565f61f9dccab51a289c3160ffe4a9b29cc76ea46778d9317a890efea2ad905f4219463a3baca3c02f5c3682634be7c2e86e366272a8263fec8e871644a79299d4aa74f1b1414b2f963cce6e059978faf813625af7869c1dec92035478c0e46dc66d938d4131aca27a59b2103b8cefa8e08aeb44b53b205b932902aea8d519faaaa12e354a6f532b4f716d7929e655dc2e98b494a99153854af5732a2659f2c21e4069896a1835ad05c5e53781cab16599cf4af47c196deeff9115c80d13f93aeb28b08023e6a1d3cf7da2a4457a9e443176bcdfef8f8de630c02bd0efdc5ddda56ad8f6b47edbda6353205e6e655f690092a48deb7f8a5254a7d778e07216cd97dfefcf740c1acd2977ef0fa17f798ea9752bae46e3aa3ec9b13f4c95c20a7839b8409000fa1f17e8dc46cc05c41bff696ee03c0371cae8638e8018ff4ebedd9f27d56443e534a72dd3d18a64790b676ddd060376759fa4a12ffc17f4be83492126ec1dc0fcd4aefef73a0b9c443ec3532b9a66b1a60daacf45e6557115edc0cc4d08758754a44beffedaa0d1265e50beed1a01752904ee3f7e706ed290b1a79071b142105b7c02e692ff318710e3ce9c3b9ec557cdecef173796417341ada414faa06b52adf645db454b56468ccf0da50a942ebc09487797cb45a085ec1e2e06fcd1f5b72eac291955a62e5aa379a374aea3a0dec3e4e0ba1dde350a94c72dbea7505922e26e99d62f751c2b301413a73fb6b20a36052151473ebecd04d0a771ec326957bc28c2020fdf6f01d9abed69b3c3e73168b404a1748b15310b167396da01c7dc700000001088ca3be26059ca269000044d00a7e7a252620d0fdfb63c0c193d6a9fe6a36aa9ce1b29dfa5f11f2567850b88384a2cc682eca2e292749365b833e5f7540019cd4f3143ed078aec07990b0d6ece18310403e73e1fe2975a8f9cb05796fa6196faaba3ee12a22b63a28a624cf4f7bedd44de000dc5ea698c65664df995b7d5fade0aab1cf0ecc5afd5ecb8fb80deecae3a8c97c20171f00ac3b5dc9a9027ca9c25571c72bb32070f6e3fb583560b0da6041b72e0a9601b8ad17d3c45e9dcc059f9f4758e8c35a839a9f6f4c501cb64e32e886fc733bc51069fbe4406f04d908285974c387d5b3e5f0f674941d05993bf8bda0d5ffd8c4fb528e150ff4bf37e38bd9c6346816fe360d4a206da81e815c1f7905184b6146b33427c6e38f1179981c18b82a3544442dd997c182d956037ae8f106eaf67ba133e7f15f1550b257d431f01ba0472659c6a5c2e6ff5e4ce9e692f4ef9fb169a75df4eb13f0b20e1994f3f8687bdca300c7e749af7b7a3b6597a6b950fe378a68c77766fdabe95248ed41d37805756b7ffa9cee0898bd661f6657cbf1af9aa8c7e437d432ca854c95307e6a7dfb6504ee3f7852fb3c246d168a03810b6c3d4e3d40bdee3def579effb66563f5bac98cfa1b071cd6f33e425e016bb3514a183b72cb3a393e9e519ba60e2177c98f530835e3b6eab78cdcb8abdbc769bc07e10c8e38bea710d5de1bdb2fa8d0d9b19e8cc31d16725a696e55342c89b667497e3d7f90e48f8503d8ead2a32a1930c3b24a4a9dcf2d8ec781705dd97d7df6e26828712fe42114419d5b8346bd86c239bd02f34e55f71400cb10c1fac7d8efa1a2ab258c17ace4288c8576ab92447b648fd15f4e038ec1c81a135e3bbb6f581a994c6a4902aeb1b5588cb1b5b53c8540296d96b6d2eccd67bae9609233f36304b5186d4698b88bb3ce8b1191a62b990436cf10718fd5759cb2281ac122f49ccbef8a3206348c1a930e7fc4bb498a11d89374e1480c7b8725b5f65e8c8d6f58da17f9134abce77eb9a6fcda514e7d3ab2e3610f86945f0dca519a3844da1b3a4b0e03c80528a2f79be478d07ff26166e30294bf0e69bf07a5bbd6d879adf6d618a1ec8365023408980bf67f0525a2fdee97fccc38fe104d4f58ed15e3671dfedf684856a27fbe286adba40ff0336def93f0174e9e35d341f5de73190d330d72227db9a866b69418e17e8e19ec884c1ffe2f0ad6deec37c9d49d536d0242fab282b0cf86cc9b15341757e0d361bddcbe5cbb062b3148d7c3c62af5c5dd5922a49920f351647030f62ed16929a404aa514fcbc38e67ba4f275e02a04c486b1a8e5b5efda197fd63e6f41fdeffa652c690dd6b00ca65df3688672ead9744f7d631e42e3b42f3ed1bff51b30f89211a7467cde65eab3659af7690cf307420a5823f31999d8f63c6c6ba0296ed4a46d5df6404f8db33e7252cc6bfcf7f55fee1f1e3b0573b6c6615793ff0691b7cfd23c195f66eb333d7efb0cfb74cf159787f87ad01fc131c6763bb1117bbfb8c2e8197ffba6b8c747565b1332bdbd6553b840939c2f98aa8eb1c549491c640e012fc549852fa7a93f81e5db152c761fc7d01bce0325619965c09f6730a162e7be53af7d9ce4b5ac0f4eb487361d2ac231d4ce92e5d9a084bc7b609ccf60056ecc82cd0c06a088cfbcf7d764b3109331c42f989da82b05cfe4c134a6784e664fa67a89c0624e3cc73ccfdea3f292db28f7c7b1b109f680f6b537f135c62f764", domain: "dns.google", wantErr: false, needsMoreData: false, }, { name: "QUIC Chromebook Handshake[2]; packet 1", hexData: "cf0000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e448967af34752fd95835e3caba1e022d6d164f3f53f1bd7f60d560a8684079e90626aa1a4d3fe728158f7e1055ff76d1566072113982b193fb932265381e4de7afb35caa4ec56f31595a33fa2eb0bc84feb9f273224050938825fd21aa7317042ad00785ffd36151aee566a5dfe17d72591af1235059171568e5af0d13fc56e7897c3d632be753d8dea184c3d96d92bc56978cc669d94dd4c5e8dc3dcba7f0a39368fb1e87981e54bba7b86fbd8e8023a94d84f0290f402a5244cb4b0eeaaa57610ea59711a43932c521f10edb4560375693cbea60240389b8cebfd94035cabe4fc96ce8a726b979775e06c3bb0e3c4c866fe82e89fb725499e711e39310b93c785b313459f22d4ba37f90b19447165c2584269d98bf47d1f7ca89585797e4d6f1a4a1db7d2b0ae91a93fb15c3bb0ab953c3656b3b2ca20833d15e95329baff6d2ade1b0921b5ed3ae96648bf123b5265e27b049e9a8674455ff5f763f039568026e4fbe9882fef761c573d8f12e342c274a8dd3ad9854a688ce57cdddb52c758161ae3a59f67fc0d5b85f12e27617e7f4366e97a61fcda084e620dde35686f01dac49ce4bd76b986e3223c215919a1b228beeb74b7fcf32827d55be8f1b3b5fed24df2db023faecbb313b18a151cc4af8199d4bb08f8127b8207a0286d52758eaca87fd476ece0e3b17bcd8afb0289e8fd33c4455d4db6f058826c301ea303bfe2c0a6651a8fb6a2e1897852d758076adb04ad907077c5d5f94089da78d8923a34f1022ed672f378fe0dd81a709b372c0a2042a42e683c051c653e42b43c4a0ea8e961074d2901d4157ac9878b13a207b05ec471cff10d922b74d05623513cd6a4ea192ad21d4089de269633d4d2d1388d98d7c8a9e29848d5558b8aa2b73b437446a640230e6adb7f4b317ee5d66681c4aae11f69b1e5f96cb32ca6331405426cb706167d86f6f8fd588a72d7b2a6906798b81f174d808e1e3fc461e598e797c41bced26b87d09282d7b6d95076c285462e0c420a6f0e171ffe2791b5d221c03520409fe36622ff77796d9b7ef82babb25313acda9c621b22bf45ed909f9365b508860645af4c3aca78e6abca2d3a65c9159fbcd577438505d3f65a57c9412c12c069ad4d6db450beb08603abef621a9e029593fb5881dbd524ea2953b4acaaf59269b584c754e88c033247bb7c032e548d34fd9b2678e62fdf953dabf2be21c3e2d7b18ec7e3aedaf2cd082e19a369c1bcd4ca67e3d464e2200ecc3df98b0aa7f349415d68bcab0441ac3366607eff024bb786aec031a4619f8a24f554fe93c8520a03affcf11e40b6d5002f98c1708cac6c56e77eccba85ea6600d1391cfd202cc7914bfbaa3303266d1a820bf2dc84d2dfcdc4cdb79e6de3fbe3c02b288dcf955652f674f3f59b50849ea7dbf755bdafa27fba3db1267fb1354d8bf25a60cacb900b4d7ba913f9ba5f6b00559ad58b2f34a658ff7ef7f7d1ceeffd9c8325f271e6b5ba44d89685b744306963aa5e05ac0e8b00ada772dd5ae5ffb7043109afea86593743564c7acb4c8e7ef0e57d081eb1b9c0916078b113ece8a6036264a9b9781183c035342d50c7b069f3a01a40230e37ed8efde073c07d0e68066541d78c2f3cbe1e603cfcaaa", domain: "", wantErr: true, needsMoreData: true, }, { name: "QUIC Chromebook Handshake[2]; packet 1-2", hexData: "cf0000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e448967af34752fd95835e3caba1e022d6d164f3f53f1bd7f60d560a8684079e90626aa1a4d3fe728158f7e1055ff76d1566072113982b193fb932265381e4de7afb35caa4ec56f31595a33fa2eb0bc84feb9f273224050938825fd21aa7317042ad00785ffd36151aee566a5dfe17d72591af1235059171568e5af0d13fc56e7897c3d632be753d8dea184c3d96d92bc56978cc669d94dd4c5e8dc3dcba7f0a39368fb1e87981e54bba7b86fbd8e8023a94d84f0290f402a5244cb4b0eeaaa57610ea59711a43932c521f10edb4560375693cbea60240389b8cebfd94035cabe4fc96ce8a726b979775e06c3bb0e3c4c866fe82e89fb725499e711e39310b93c785b313459f22d4ba37f90b19447165c2584269d98bf47d1f7ca89585797e4d6f1a4a1db7d2b0ae91a93fb15c3bb0ab953c3656b3b2ca20833d15e95329baff6d2ade1b0921b5ed3ae96648bf123b5265e27b049e9a8674455ff5f763f039568026e4fbe9882fef761c573d8f12e342c274a8dd3ad9854a688ce57cdddb52c758161ae3a59f67fc0d5b85f12e27617e7f4366e97a61fcda084e620dde35686f01dac49ce4bd76b986e3223c215919a1b228beeb74b7fcf32827d55be8f1b3b5fed24df2db023faecbb313b18a151cc4af8199d4bb08f8127b8207a0286d52758eaca87fd476ece0e3b17bcd8afb0289e8fd33c4455d4db6f058826c301ea303bfe2c0a6651a8fb6a2e1897852d758076adb04ad907077c5d5f94089da78d8923a34f1022ed672f378fe0dd81a709b372c0a2042a42e683c051c653e42b43c4a0ea8e961074d2901d4157ac9878b13a207b05ec471cff10d922b74d05623513cd6a4ea192ad21d4089de269633d4d2d1388d98d7c8a9e29848d5558b8aa2b73b437446a640230e6adb7f4b317ee5d66681c4aae11f69b1e5f96cb32ca6331405426cb706167d86f6f8fd588a72d7b2a6906798b81f174d808e1e3fc461e598e797c41bced26b87d09282d7b6d95076c285462e0c420a6f0e171ffe2791b5d221c03520409fe36622ff77796d9b7ef82babb25313acda9c621b22bf45ed909f9365b508860645af4c3aca78e6abca2d3a65c9159fbcd577438505d3f65a57c9412c12c069ad4d6db450beb08603abef621a9e029593fb5881dbd524ea2953b4acaaf59269b584c754e88c033247bb7c032e548d34fd9b2678e62fdf953dabf2be21c3e2d7b18ec7e3aedaf2cd082e19a369c1bcd4ca67e3d464e2200ecc3df98b0aa7f349415d68bcab0441ac3366607eff024bb786aec031a4619f8a24f554fe93c8520a03affcf11e40b6d5002f98c1708cac6c56e77eccba85ea6600d1391cfd202cc7914bfbaa3303266d1a820bf2dc84d2dfcdc4cdb79e6de3fbe3c02b288dcf955652f674f3f59b50849ea7dbf755bdafa27fba3db1267fb1354d8bf25a60cacb900b4d7ba913f9ba5f6b00559ad58b2f34a658ff7ef7f7d1ceeffd9c8325f271e6b5ba44d89685b744306963aa5e05ac0e8b00ada772dd5ae5ffb7043109afea86593743564c7acb4c8e7ef0e57d081eb1b9c0916078b113ece8a6036264a9b9781183c035342d50c7b069f3a01a40230e37ed8efde073c07d0e68066541d78c2f3cbe1e603cfcaaac40000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e4489522d29bb5c84749f83c8e1edfd9da8d1738164a8a9c59e37a5c9994d90bb982dcfa69b20f868960dc139618f1adc2546d34340ae13d826260c54a456bbf7469ee37b1be1d7177004468d7e92cac62a0b165d6a114ad479861dd58959e094b5a6250359301d4a614d529660760e3d1cdec9bf444a3761309bab40e4a977bc749e0dae431952f5f7e6b1ebc1383d343359a387da4301f7fa4b400475e9b82367e56278376dd1c80349f083988945a13649008109cc12a3acf569ffcc5481fbcd86b544e7dc8434e9dd42bd8e5716a844d37879568db046857389d36cc7550c75f94e314db6749aa987f0fc730fae0fcf465d01c2fb745269dfc10132ddb5404dda2f9455780f5818730834aa9db4740793359884b9927b0bd1a5ca96052b4f17397d8b78aa891401bb8bed6726ea2229d919798c50e24d5f40576ac204847be9244aadbe5c773684c37475036541d209c177d4e9c22a1253292ce4ffb886b925b6cf83cc251976a68887eda2777590f51804b790b51eee77e717b7ef0eea71634594df36e6ae9e7574d65c51ac3196f0b2a3b0f023c81f05f7807f958dda03418ed49e14b645e814b9aa55b37c809be3172ca21fe4c7a78e17e9ece8def2dd2949310ecaa41b1b477f4e85db5288aa144e333f47ef291d0e822941181c13859d9fd6d640904ee764c9276125228c932dff3fb12f564f039b52f5ba1ab4d119641df8fe13f784802b99347f0046da63f471e34b1d12d3111cffe7b5d90cf5999879f6f23e7785f09cb10df32821bb68dd8fdcfcdbedd63f2428b2292b9f0e76ff36403c9644fd43e01112ee6218d0ec1c86f6d147e4b802293e906750c7046f53bf05a144e321d3b45e08e4064fd3828fdd1b5d1ceed74081f61319dc0ad9a6e8a3b9cc802e952d24e2271712e2c2cda7daca2f835e6c804feeef8d918404cc82a1aa9534bddff68a472b208a0d0a7fd68a08fbc411132af47a6b67a32617b7b9991524c21599e8e3cb9395cdab87a3f5bf5d1833a9c7ea021b29cf428c877c6b21d62f99340ac7f85ae721acc10968e7d79f111ca40c75e14060d07cffa046d71151a0b00eab657300344b04bd1a8871650c34ceda8610d7c1ba8d37673da6aaa580400e0230c69fba8ba21927de2f5897656144694550d1df3d268804adc707e7b236501734aeabb2e61cb08012bd96eca5a486d7a55f996992c36233815abd71c30e263ba0c5d9456fe0828df16f6af7929390bb143c426d9dfeaf4bb373554479ebe609b36b4bc3dd08ce216b9cdc5726edb458c5e4036d0edc688d3e39d20f8254b5d1f174518f15b344efc27fc56572c0159aa593d5b46bc33818f986e3df8caebd4c7b702ef50dd582714a2b94ecd1c4e90af37d388445c478a32ff6e8f5852ee115966b708eed04da322b98813a69423e95f90b89ce85518e39bcef36fdd5bd312b2c6c5ee85962675274c18f39ee35155517f70fd74b31bb2de6b5108d369252e6fb289e453833132ef7960da1cc0934790c039b9a1b0c74f23eb3b61fe9b4d0ea67de757b93af451eef303b1373199af446a0fa98d5991bbd4771ee63317e6da86efbe213dfff595c41b98e0e89f4f2df110104e760feebf4cb3361171c9fceb1e1c809a268", domain: "", wantErr: true, needsMoreData: true, }, { name: "QUIC Chromebook Handshake[2]; packet 1-3", hexData: "cf0000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e448967af34752fd95835e3caba1e022d6d164f3f53f1bd7f60d560a8684079e90626aa1a4d3fe728158f7e1055ff76d1566072113982b193fb932265381e4de7afb35caa4ec56f31595a33fa2eb0bc84feb9f273224050938825fd21aa7317042ad00785ffd36151aee566a5dfe17d72591af1235059171568e5af0d13fc56e7897c3d632be753d8dea184c3d96d92bc56978cc669d94dd4c5e8dc3dcba7f0a39368fb1e87981e54bba7b86fbd8e8023a94d84f0290f402a5244cb4b0eeaaa57610ea59711a43932c521f10edb4560375693cbea60240389b8cebfd94035cabe4fc96ce8a726b979775e06c3bb0e3c4c866fe82e89fb725499e711e39310b93c785b313459f22d4ba37f90b19447165c2584269d98bf47d1f7ca89585797e4d6f1a4a1db7d2b0ae91a93fb15c3bb0ab953c3656b3b2ca20833d15e95329baff6d2ade1b0921b5ed3ae96648bf123b5265e27b049e9a8674455ff5f763f039568026e4fbe9882fef761c573d8f12e342c274a8dd3ad9854a688ce57cdddb52c758161ae3a59f67fc0d5b85f12e27617e7f4366e97a61fcda084e620dde35686f01dac49ce4bd76b986e3223c215919a1b228beeb74b7fcf32827d55be8f1b3b5fed24df2db023faecbb313b18a151cc4af8199d4bb08f8127b8207a0286d52758eaca87fd476ece0e3b17bcd8afb0289e8fd33c4455d4db6f058826c301ea303bfe2c0a6651a8fb6a2e1897852d758076adb04ad907077c5d5f94089da78d8923a34f1022ed672f378fe0dd81a709b372c0a2042a42e683c051c653e42b43c4a0ea8e961074d2901d4157ac9878b13a207b05ec471cff10d922b74d05623513cd6a4ea192ad21d4089de269633d4d2d1388d98d7c8a9e29848d5558b8aa2b73b437446a640230e6adb7f4b317ee5d66681c4aae11f69b1e5f96cb32ca6331405426cb706167d86f6f8fd588a72d7b2a6906798b81f174d808e1e3fc461e598e797c41bced26b87d09282d7b6d95076c285462e0c420a6f0e171ffe2791b5d221c03520409fe36622ff77796d9b7ef82babb25313acda9c621b22bf45ed909f9365b508860645af4c3aca78e6abca2d3a65c9159fbcd577438505d3f65a57c9412c12c069ad4d6db450beb08603abef621a9e029593fb5881dbd524ea2953b4acaaf59269b584c754e88c033247bb7c032e548d34fd9b2678e62fdf953dabf2be21c3e2d7b18ec7e3aedaf2cd082e19a369c1bcd4ca67e3d464e2200ecc3df98b0aa7f349415d68bcab0441ac3366607eff024bb786aec031a4619f8a24f554fe93c8520a03affcf11e40b6d5002f98c1708cac6c56e77eccba85ea6600d1391cfd202cc7914bfbaa3303266d1a820bf2dc84d2dfcdc4cdb79e6de3fbe3c02b288dcf955652f674f3f59b50849ea7dbf755bdafa27fba3db1267fb1354d8bf25a60cacb900b4d7ba913f9ba5f6b00559ad58b2f34a658ff7ef7f7d1ceeffd9c8325f271e6b5ba44d89685b744306963aa5e05ac0e8b00ada772dd5ae5ffb7043109afea86593743564c7acb4c8e7ef0e57d081eb1b9c0916078b113ece8a6036264a9b9781183c035342d50c7b069f3a01a40230e37ed8efde073c07d0e68066541d78c2f3cbe1e603cfcaaac40000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e4489522d29bb5c84749f83c8e1edfd9da8d1738164a8a9c59e37a5c9994d90bb982dcfa69b20f868960dc139618f1adc2546d34340ae13d826260c54a456bbf7469ee37b1be1d7177004468d7e92cac62a0b165d6a114ad479861dd58959e094b5a6250359301d4a614d529660760e3d1cdec9bf444a3761309bab40e4a977bc749e0dae431952f5f7e6b1ebc1383d343359a387da4301f7fa4b400475e9b82367e56278376dd1c80349f083988945a13649008109cc12a3acf569ffcc5481fbcd86b544e7dc8434e9dd42bd8e5716a844d37879568db046857389d36cc7550c75f94e314db6749aa987f0fc730fae0fcf465d01c2fb745269dfc10132ddb5404dda2f9455780f5818730834aa9db4740793359884b9927b0bd1a5ca96052b4f17397d8b78aa891401bb8bed6726ea2229d919798c50e24d5f40576ac204847be9244aadbe5c773684c37475036541d209c177d4e9c22a1253292ce4ffb886b925b6cf83cc251976a68887eda2777590f51804b790b51eee77e717b7ef0eea71634594df36e6ae9e7574d65c51ac3196f0b2a3b0f023c81f05f7807f958dda03418ed49e14b645e814b9aa55b37c809be3172ca21fe4c7a78e17e9ece8def2dd2949310ecaa41b1b477f4e85db5288aa144e333f47ef291d0e822941181c13859d9fd6d640904ee764c9276125228c932dff3fb12f564f039b52f5ba1ab4d119641df8fe13f784802b99347f0046da63f471e34b1d12d3111cffe7b5d90cf5999879f6f23e7785f09cb10df32821bb68dd8fdcfcdbedd63f2428b2292b9f0e76ff36403c9644fd43e01112ee6218d0ec1c86f6d147e4b802293e906750c7046f53bf05a144e321d3b45e08e4064fd3828fdd1b5d1ceed74081f61319dc0ad9a6e8a3b9cc802e952d24e2271712e2c2cda7daca2f835e6c804feeef8d918404cc82a1aa9534bddff68a472b208a0d0a7fd68a08fbc411132af47a6b67a32617b7b9991524c21599e8e3cb9395cdab87a3f5bf5d1833a9c7ea021b29cf428c877c6b21d62f99340ac7f85ae721acc10968e7d79f111ca40c75e14060d07cffa046d71151a0b00eab657300344b04bd1a8871650c34ceda8610d7c1ba8d37673da6aaa580400e0230c69fba8ba21927de2f5897656144694550d1df3d268804adc707e7b236501734aeabb2e61cb08012bd96eca5a486d7a55f996992c36233815abd71c30e263ba0c5d9456fe0828df16f6af7929390bb143c426d9dfeaf4bb373554479ebe609b36b4bc3dd08ce216b9cdc5726edb458c5e4036d0edc688d3e39d20f8254b5d1f174518f15b344efc27fc56572c0159aa593d5b46bc33818f986e3df8caebd4c7b702ef50dd582714a2b94ecd1c4e90af37d388445c478a32ff6e8f5852ee115966b708eed04da322b98813a69423e95f90b89ce85518e39bcef36fdd5bd312b2c6c5ee85962675274c18f39ee35155517f70fd74b31bb2de6b5108d369252e6fb289e453833132ef7960da1cc0934790c039b9a1b0c74f23eb3b61fe9b4d0ea67de757b93af451eef303b1373199af446a0fa98d5991bbd4771ee63317e6da86efbe213dfff595c41b98e0e89f4f2df110104e760feebf4cb3361171c9fceb1e1c809a268c60000000108452af27900a1723300404600ca8530029a6bc59ff3e85beb5fc838ac3147ba5c2f6421ddcffdd85167d8de70eff2b1fa016dad4918337dec0feb660edb98e078dea51fa914055984b7957bd732fa4c831e44892ff5e6b16d8a259a9128c2c0c3c525462781a344c3df7f19a747e0e79ca8714995c867fc697a3cb87b35e769465a8e966bcb35b7e897ad036aa23a6c021e2445a0eb79962151cd20dbb43ae1231847de01caf4e5589dfebf026e95f7d1d742e140d9dda849396a70cc0798f1eef06fd5f4cfbc9a190ddf04cc332c5b7b15e53af311190ced92a1291c12b8799f2b50e076539a8370ee667e1791a78f38e565a48acbaa1c78ba941dba8b0d040f8fb8bbcc9f6bf5705efa613a24b12d6ac9cebb4f3fac1b09a07b49d8a3a62808eb0a324629f13a012e6ad0feb11ad97c1572983c713b62f27584809ba43e64e4af9845af807c0783104838f4e2ac33fa848866f3cc64a7b6203a5c09e8ad231f0f06ae2fb7b39a64cedd823b0ff297ad9be1ccac436777ccb3e22ef6b9c12e6d5e34926f50e8ca8c8c0532c810b074d001c11791a01bf25786b57a5da54065dcee4962822e929f47ee44d3b8c83d45a8b7a936dc2a6fa396e4194fa032d1627eca59f69857fc40dab5835d3613dade1c74b09c345bd32c509e9545d2330b157a7acb76409f3ac8eaa22802414f38c5422fe4c5189caaf5c1b93ce7c0892f0cfc477490d335aa78961d632a973cf106bd974c2714176fb0f98cf12f2887a0d7bd491756dd374331eb3e6adb9f2bd0d6b273403fd14b314eb27ebbb6f6e78ce310437004b757c048149cf04429ae4a6d6e65c9b3e0b9c9c4d4ef52007eaaad9670320f10cd5317b3d3edc374d45c98b217dd28fb3c2c2fb6e74a3aced143e3242084b192ba6df24e69fdb883e850714fe27a45f43883486a986574fd1fc10f259fe90786441554514c8dade1f3b86fdaf5f54ab655e2d803c98aa56073b00c32148a1ed367dff3a2bd934ecba55141389990b661bbd9ce1ef1def13747d45500daf92cec9e60908274703e761cd46affd46622f2a2192a79425ebf51c875fc7ba3598e15e0ba2465fc3e87c8a5da1915d3b8abe4b16d21259f311183eee1e7d2b808a91a7c89b284df0eb6a2a79c610bbe47722b3e04d5a6c0e574816a94d97349b6976010eb8c7debf42210982f78de482b7cd068051bf57908dbf46b5ceaf64f5fb33ede4412c1ce81eb1dfb4e99e10dd9b57ebc6e62ecbf4ee2db04d9e48c62bd45f8fa51704d414296a2d51d25ced6a192034a44c67e09d8985b573f98e03fa36dd8dcce2c04b4d5b1f276b6a642aadbdcafcf09de1d234bf8bbbf64aeadf01519ddafb419b3e62d204e04c3d7ebaf54b09e387ac3e9c4781c11625a2f44fddb7a1886f21929bd01c283f64903b6ccbb463984dfadc00f6af2a421517da023fd319f528195cac5fe907624b70c0172479d07d78e266dbf20ab8fc302228f279ffdba7395a839c4a9d7a4e001a260e1702393968f1e9722f023b204cf09cfee9a7bba045e4a2a449ee9fbb5c36e93028cfc87a2e34914b1b4f01beeded175ac0fa73fea9292f2bc3b1247164d8e05cddc3981bdc24e5f596571c418f6fa00fd9d4d0898cbf0d2f5413bed5f100f1854903017b6bc88bd7e303b5e0e2417bbcc984731128eda550d31f9af0e6e743eb6916466bbd435617d56fa60b05cd7dca66a9f6f4be23d3c5ff5d900822c6d1d8d71b0bab24f57d9682381a87c", domain: "signaler-pa.clients6.google.com", wantErr: false, needsMoreData: false, }, { name: "QUIC Chromebook Handshake[3]; packet 1", hexData: "cb0000000108676ef9ec3514fd5f004046001ae0c831dde6ac72f1337c9ca111f5b32afdf102d75c017d3bccb6fa89902b750b00c51bb226afa517754b72e962ff007c1c8c8749a21be1d8d94f7bf73437c010cd60e0bd4489d0a84868f32ecd4bd0d4c95a8a08d60d8303ef02323bdbcd96a33940824d25b9594bd8ae5716b9d043ab27ba03a2593c4d149b923711dd98e45456db19c8ea71e982562ae787c1b6cbe3ca1b03df2df62aa8e3127c5f68bdf80ed90588e7ec1f41f5a6281b87a12348cb17a04e9eaa461fef2e0e3ae70ebdc7bffa15c6b61ab270173e46dec0fd081f935a5fe6338d3b9cd38fcb52cb159edb66d2927238294313990da25c22f40d40e3cd72e76bbd066de731cf8fb6b4b7bc7639efb788c0b108dbf8280845a2cc62fbaf5fb8e1ecbe5ba7791aab94786c1c71c9058d0153b34a3f5bc8903e0d120f353defbe973cd33568bd03609dcdab8af1e8563897f5dd0251c6e6514bf40bd447d376fed21b2c54ebf74680df241bdc2ea5579bc0736cf3257c20d275746e8e6853aa89dcda8c2dbe523438ab92ca1ed1ab4f109e4ea84de57dfb6c544d695a5b710fe2d432f2b58644f8aeb965752d3a1d1a3057c2229192f89b254f5d292c22f1060642729df3667ef39e27691c82da9be847a59a17ba7345d23a37e31ec135633cc5ea84c752f56d4ec75878a2920b93e9b4e091e0114552712e1e50ade42e26ac0266b84043a493e1ce2e80cd57422de16a88deceaa55385dc2a977ffc9063e7c427200b6d8511ef9004f89412587bd6d0057898f5ae284db78b0ec861fed36dfb7c7a9679ad0480eefe71985ba6f731bd0e816a901e0c017dd0cb7fc8a4606dec2091a51aab16d6f9bbdecf3fea177671e68250a84fe19de8df78d711e22b81372bc22ae21ac7208ed41201f6e26cd6748e9d6e2f4884f5acba736b2432536718891638d43991bd97c232829e26be6e6bb303d44849b245ef758eb2813bc87cf21a30f132360111e3015de5d1e4f0c5a98aff159c29f6debed7c2f18f455dfc7f33995a90b7625688507ecef1e7db48e7030ea6c4fa835bbc1dfbea6c0a6c704d658d4866a42b9860b1c8b5b64cb669e102c81e369b5f07b8fa08816a566a99f4d2910f6e8d751d52f1e2889f0ec9acfcb4627e0da5c35452be05c7766eddf3c42ceb6a312044075a4231b4203718c886498a313f3ba12e44e368b04ec3ea6e72d6fed9b6b334cbc0ba89f0aa9a129b1bad5b0ad8690291a344967f58e52415859852c6ca3ea24bc93ec1041fd1dc8a6a181326d3026098db0cddec90b3cd6df1e7638a3703f70c9a3baff8f005b90f362459a275a8b39daa78ff24613434594f96b8023a41a17d815e5c0319a39e07d32841339f14f404030b4a22551b86ba94832a1c49053d63140b503f2f64354ce10abe6c08f6cdaf6d8dc361c3c9d1a8077ad34dccc699b6fe07c16f8f7743d04003d672f82e643b3f1d5e263495504e11e6b2e676c11b3d0033d5f837e6bfd01602584ff181e3cb86f081015a9311eed546b42a8280680aa538353949f89674c554b43241e36536430ae9e0190729ce902e8f06a952d23b62816deb3b62b45375033ede2d8065a8e7b38f5aee0a5c66eb2f21f33fa6795d4b086e6f6ac941ba0c883ccf6e54e52164384045e0b0d74a9361f224303c841ec907be250725ab06cf79dd8bff8f46c08963a409b9b71b5c634c987c5e163f73fc32553be1231c72444c5e2a91189824034a784948f", domain: "", wantErr: true, needsMoreData: true, }, { name: "QUIC Chromebook Handshake[3]; packet 1-2",
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
true
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/sniff.go
common/protocol/tls/sniff.go
package tls import ( "encoding/binary" "errors" "strings" "github.com/v2fly/v2ray-core/v5/common" ) type SniffHeader struct { domain string } func (h *SniffHeader) Protocol() string { return "tls" } func (h *SniffHeader) Domain() string { return h.domain } var ( errNotTLS = errors.New("not TLS header") errNotClientHello = errors.New("not client hello") ) func IsValidTLSVersion(major, minor byte) bool { return major == 3 } // ReadClientHello returns server name (if any) from TLS client hello message. // https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300 func ReadClientHello(data []byte, h *SniffHeader) error { if len(data) < 42 { return common.ErrNoClue } sessionIDLen := int(data[38]) if sessionIDLen > 32 || len(data) < 39+sessionIDLen { return common.ErrNoClue } data = data[39+sessionIDLen:] if len(data) < 2 { return common.ErrNoClue } // cipherSuiteLen is the number of bytes of cipher suite numbers. Since // they are uint16s, the number must be even. cipherSuiteLen := int(data[0])<<8 | int(data[1]) if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen { return errNotClientHello } data = data[2+cipherSuiteLen:] if len(data) < 1 { return common.ErrNoClue } compressionMethodsLen := int(data[0]) if len(data) < 1+compressionMethodsLen { return common.ErrNoClue } data = data[1+compressionMethodsLen:] if len(data) == 0 { return errNotClientHello } if len(data) < 2 { return errNotClientHello } extensionsLength := int(data[0])<<8 | int(data[1]) data = data[2:] if extensionsLength != len(data) { return errNotClientHello } for len(data) != 0 { if len(data) < 4 { return errNotClientHello } extension := uint16(data[0])<<8 | uint16(data[1]) length := int(data[2])<<8 | int(data[3]) data = data[4:] if len(data) < length { return errNotClientHello } if extension == 0x00 { /* extensionServerName */ d := data[:length] if len(d) < 2 { return errNotClientHello } namesLen := int(d[0])<<8 | int(d[1]) d = d[2:] if len(d) != namesLen { return errNotClientHello } for len(d) > 0 { if len(d) < 3 { return errNotClientHello } nameType := d[0] nameLen := int(d[1])<<8 | int(d[2]) d = d[3:] if len(d) < nameLen { return errNotClientHello } if nameType == 0 { serverName := string(d[:nameLen]) // An SNI value may not include a // trailing dot. See // https://tools.ietf.org/html/rfc6066#section-3. if strings.HasSuffix(serverName, ".") { return errNotClientHello } h.domain = serverName return nil } d = d[nameLen:] } } data = data[length:] } return errNotTLS } func SniffTLS(b []byte) (*SniffHeader, error) { if len(b) < 5 { return nil, common.ErrNoClue } if b[0] != 0x16 /* TLS Handshake */ { return nil, errNotTLS } if !IsValidTLSVersion(b[1], b[2]) { return nil, errNotTLS } headerLen := int(binary.BigEndian.Uint16(b[3:5])) if 5+headerLen > len(b) { return nil, common.ErrNoClue } h := &SniffHeader{} err := ReadClientHello(b[5:5+headerLen], h) if err == nil { return h, nil } return nil, err }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/sniff_test.go
common/protocol/tls/sniff_test.go
package tls_test import ( "testing" . "github.com/v2fly/v2ray-core/v5/common/protocol/tls" ) func TestTLSHeaders(t *testing.T) { cases := []struct { input []byte domain string err bool }{ { input: []byte{ 0x16, 0x03, 0x01, 0x00, 0xc8, 0x01, 0x00, 0x00, 0xc4, 0x03, 0x03, 0x1a, 0xac, 0xb2, 0xa8, 0xfe, 0xb4, 0x96, 0x04, 0x5b, 0xca, 0xf7, 0xc1, 0xf4, 0x2e, 0x53, 0x24, 0x6e, 0x34, 0x0c, 0x58, 0x36, 0x71, 0x97, 0x59, 0xe9, 0x41, 0x66, 0xe2, 0x43, 0xa0, 0x13, 0xb6, 0x00, 0x00, 0x20, 0x1a, 0x1a, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13, 0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x7b, 0xba, 0xba, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x14, 0x00, 0x00, 0x11, 0x63, 0x2e, 0x73, 0x2d, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66, 0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x17, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01, 0x05, 0x03, 0x08, 0x05, 0x05, 0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0xaa, 0xaa, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0xaa, 0xaa, 0x00, 0x01, 0x00, }, domain: "c.s-microsoft.com", err: false, }, { input: []byte{ 0x16, 0x03, 0x01, 0x00, 0xee, 0x01, 0x00, 0x00, 0xea, 0x03, 0x03, 0xe7, 0x91, 0x9e, 0x93, 0xca, 0x78, 0x1b, 0x3c, 0xe0, 0x65, 0x25, 0x58, 0xb5, 0x93, 0xe1, 0x0f, 0x85, 0xec, 0x9a, 0x66, 0x8e, 0x61, 0x82, 0x88, 0xc8, 0xfc, 0xae, 0x1e, 0xca, 0xd7, 0xa5, 0x63, 0x20, 0xbd, 0x1c, 0x00, 0x00, 0x8b, 0xee, 0x09, 0xe3, 0x47, 0x6a, 0x0e, 0x74, 0xb0, 0xbc, 0xa3, 0x02, 0xa7, 0x35, 0xe8, 0x85, 0x70, 0x7c, 0x7a, 0xf0, 0x00, 0xdf, 0x4a, 0xea, 0x87, 0x01, 0x14, 0x91, 0x00, 0x20, 0xea, 0xea, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13, 0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x81, 0x9a, 0x9a, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x16, 0x00, 0x00, 0x13, 0x77, 0x77, 0x77, 0x30, 0x37, 0x2e, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x74, 0x61, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x00, 0x17, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01, 0x05, 0x03, 0x08, 0x05, 0x05, 0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x75, 0x50, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x9a, 0x9a, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x8a, 0x8a, 0x00, 0x01, 0x00, }, domain: "www07.clicktale.net", err: false, }, { input: []byte{ 0x16, 0x03, 0x01, 0x00, 0xe6, 0x01, 0x00, 0x00, 0xe2, 0x03, 0x03, 0x81, 0x47, 0xc1, 0x66, 0xd5, 0x1b, 0xfa, 0x4b, 0xb5, 0xe0, 0x2a, 0xe1, 0xa7, 0x87, 0x13, 0x1d, 0x11, 0xaa, 0xc6, 0xce, 0xfc, 0x7f, 0xab, 0x94, 0xc8, 0x62, 0xad, 0xc8, 0xab, 0x0c, 0xdd, 0xcb, 0x20, 0x6f, 0x9d, 0x07, 0xf1, 0x95, 0x3e, 0x99, 0xd8, 0xf3, 0x6d, 0x97, 0xee, 0x19, 0x0b, 0x06, 0x1b, 0xf4, 0x84, 0x0b, 0xb6, 0x8f, 0xcc, 0xde, 0xe2, 0xd0, 0x2d, 0x6b, 0x0c, 0x1f, 0x52, 0x53, 0x13, 0x00, 0x08, 0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0x00, 0xff, 0x01, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x00, 0x07, 0x64, 0x6f, 0x67, 0x66, 0x69, 0x73, 0x68, 0x00, 0x0b, 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x1e, 0x00, 0x19, 0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x1e, 0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x07, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x00, 0x2b, 0x00, 0x07, 0x06, 0x7f, 0x1c, 0x7f, 0x1b, 0x7f, 0x1a, 0x00, 0x2d, 0x00, 0x02, 0x01, 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x2f, 0x35, 0x0c, 0xb6, 0x90, 0x0a, 0xb7, 0xd5, 0xc4, 0x1b, 0x2f, 0x60, 0xaa, 0x56, 0x7b, 0x3f, 0x71, 0xc8, 0x01, 0x7e, 0x86, 0xd3, 0xb7, 0x0c, 0x29, 0x1a, 0x9e, 0x5b, 0x38, 0x3f, 0x01, 0x72, }, domain: "dogfish", err: false, }, { input: []byte{ 0x16, 0x03, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00, 0xff, 0x03, 0x03, 0x3d, 0x89, 0x52, 0x9e, 0xee, 0xbe, 0x17, 0x63, 0x75, 0xef, 0x29, 0xbd, 0x14, 0x6a, 0x49, 0xe0, 0x2c, 0x37, 0x57, 0x71, 0x62, 0x82, 0x44, 0x94, 0x8f, 0x6e, 0x94, 0x08, 0x45, 0x7f, 0xdb, 0xc1, 0x00, 0x00, 0x3e, 0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff, 0x01, 0x00, 0x00, 0x98, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x0b, 0x31, 0x30, 0x2e, 0x34, 0x32, 0x2e, 0x30, 0x2e, 0x32, 0x34, 0x33, 0x00, 0x0b, 0x00, 0x04, 0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x03, 0x02, 0x01, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02, 0x06, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x09, 0x08, 0x7f, 0x14, 0x03, 0x03, 0x03, 0x02, 0x03, 0x01, 0x00, 0x2d, 0x00, 0x03, 0x02, 0x01, 0x00, 0x00, 0x28, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x13, 0x7c, 0x6e, 0x97, 0xc4, 0xfd, 0x09, 0x2e, 0x70, 0x2f, 0x73, 0x5a, 0x9b, 0x57, 0x4d, 0x5f, 0x2b, 0x73, 0x2c, 0xa5, 0x4a, 0x98, 0x40, 0x3d, 0x75, 0x6e, 0xb4, 0x76, 0xf9, 0x48, 0x8f, 0x36, }, domain: "10.42.0.243", err: false, }, } for _, test := range cases { header, err := SniffTLS(test.input) if test.err { if err == nil { t.Errorf("Exepct error but nil in test %v", test) } } else { if err != nil { t.Errorf("Expect no error but actually %s in test %v", err.Error(), test) } if header.Domain() != test.domain { t.Error("expect domain ", test.domain, " but got ", header.Domain()) } } } }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/cert/cert_test.go
common/protocol/tls/cert/cert_test.go
package cert import ( "context" "crypto/x509" "encoding/json" "os" "strings" "testing" "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/task" ) func TestGenerate(t *testing.T) { err := generate(nil, true, true, "ca") if err != nil { t.Fatal(err) } } func generate(domainNames []string, isCA bool, jsonOutput bool, fileOutput string) error { commonName := "V2Ray Root CA" organization := "V2Ray Inc" expire := time.Hour * 3 var opts []Option if isCA { opts = append(opts, Authority(isCA)) opts = append(opts, KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature)) } opts = append(opts, NotAfter(time.Now().Add(expire))) opts = append(opts, CommonName(commonName)) if len(domainNames) > 0 { opts = append(opts, DNSNames(domainNames...)) } opts = append(opts, Organization(organization)) cert, err := Generate(nil, opts...) if err != nil { return newError("failed to generate TLS certificate").Base(err) } if jsonOutput { printJSON(cert) } if len(fileOutput) > 0 { if err := printFile(cert, fileOutput); err != nil { return err } } return nil } type jsonCert struct { Certificate []string `json:"certificate"` Key []string `json:"key"` } func printJSON(certificate *Certificate) { certPEM, keyPEM := certificate.ToPEM() jCert := &jsonCert{ Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"), Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"), } content, err := json.MarshalIndent(jCert, "", " ") common.Must(err) os.Stdout.Write(content) os.Stdout.WriteString("\n") } func printFile(certificate *Certificate, name string) error { certPEM, keyPEM := certificate.ToPEM() return task.Run(context.Background(), func() error { return writeFile(certPEM, name+"_cert.pem") }, func() error { return writeFile(keyPEM, name+"_key.pem") }) } func writeFile(content []byte, name string) error { f, err := os.Create(name) if err != nil { return err } defer f.Close() return common.Error2(f.Write(content)) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/cert/errors.generated.go
common/protocol/tls/cert/errors.generated.go
package cert import "github.com/v2fly/v2ray-core/v5/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/cert/privateKey.go
common/protocol/tls/cert/privateKey.go
package cert import ( "crypto/x509/pkix" "encoding/asn1" "math/big" ) type ecPrivateKey struct { Version int PrivateKey []byte NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"` PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"` } type pkcs8 struct { Version int Algo pkix.AlgorithmIdentifier PrivateKey []byte // optional attributes omitted. } type pkcs1AdditionalRSAPrime struct { Prime *big.Int // We ignore these values because rsa will calculate them. Exp *big.Int Coeff *big.Int } type pkcs1PrivateKey struct { Version int N *big.Int E int D *big.Int P *big.Int Q *big.Int // We ignore these values, if present, because rsa will calculate them. Dp *big.Int `asn1:"optional"` Dq *big.Int `asn1:"optional"` Qinv *big.Int `asn1:"optional"` AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"` }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/tls/cert/cert.go
common/protocol/tls/cert/cert.go
package cert import ( "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/asn1" "encoding/pem" "math/big" "time" "github.com/v2fly/v2ray-core/v5/common" "github.com/v2fly/v2ray-core/v5/common/net" ) //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen type Certificate struct { // Certificate in ASN.1 DER format Certificate []byte // Private key in ASN.1 DER format PrivateKey []byte } func ParseCertificate(certPEM []byte, keyPEM []byte) (*Certificate, error) { certBlock, _ := pem.Decode(certPEM) if certBlock == nil { return nil, newError("failed to decode certificate") } keyBlock, _ := pem.Decode(keyPEM) if keyBlock == nil { return nil, newError("failed to decode key") } return &Certificate{ Certificate: certBlock.Bytes, PrivateKey: keyBlock.Bytes, }, nil } func (c *Certificate) ToPEM() ([]byte, []byte) { return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate}), pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: c.PrivateKey}) } type Option func(*x509.Certificate) func Authority(isCA bool) Option { return func(cert *x509.Certificate) { cert.IsCA = isCA } } func NotBefore(t time.Time) Option { return func(c *x509.Certificate) { c.NotBefore = t } } func NotAfter(t time.Time) Option { return func(c *x509.Certificate) { c.NotAfter = t } } func DNSNames(names ...string) Option { return func(c *x509.Certificate) { c.DNSNames = names } } func CommonName(name string) Option { return func(c *x509.Certificate) { c.Subject.CommonName = name } } func IPAddresses(ip ...net.IP) Option { return func(c *x509.Certificate) { c.IPAddresses = ip } } func KeyUsage(usage x509.KeyUsage) Option { return func(c *x509.Certificate) { c.KeyUsage = usage } } func Organization(org string) Option { return func(c *x509.Certificate) { c.Subject.Organization = []string{org} } } func MustGenerate(parent *Certificate, opts ...Option) *Certificate { cert, err := Generate(parent, opts...) common.Must(err) return cert } func publicKey(priv interface{}) interface{} { switch k := priv.(type) { case *rsa.PrivateKey: return &k.PublicKey case *ecdsa.PrivateKey: return &k.PublicKey case ed25519.PrivateKey: return k.Public().(ed25519.PublicKey) default: return nil } } func Generate(parent *Certificate, opts ...Option) (*Certificate, error) { var ( pKey interface{} parentKey interface{} err error ) // higher signing performance than RSA2048 selfKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, newError("failed to generate self private key").Base(err) } parentKey = selfKey if parent != nil { if _, e := asn1.Unmarshal(parent.PrivateKey, &ecPrivateKey{}); e == nil { pKey, err = x509.ParseECPrivateKey(parent.PrivateKey) } else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs8{}); e == nil { pKey, err = x509.ParsePKCS8PrivateKey(parent.PrivateKey) } else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs1PrivateKey{}); e == nil { pKey, err = x509.ParsePKCS1PrivateKey(parent.PrivateKey) } if err != nil { return nil, newError("failed to parse parent private key").Base(err) } parentKey = pKey } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, newError("failed to generate serial number").Base(err) } template := &x509.Certificate{ SerialNumber: serialNumber, NotBefore: time.Now().Add(time.Hour * -1), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } for _, opt := range opts { opt(template) } parentCert := template if parent != nil { pCert, err := x509.ParseCertificate(parent.Certificate) if err != nil { return nil, newError("failed to parse parent certificate").Base(err) } parentCert = pCert } derBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, publicKey(selfKey), parentKey) if err != nil { return nil, newError("failed to create certificate").Base(err) } privateKey, err := x509.MarshalPKCS8PrivateKey(selfKey) if err != nil { return nil, newError("Unable to marshal private key").Base(err) } return &Certificate{ Certificate: derBytes, PrivateKey: privateKey, }, nil }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false
v2fly/v2ray-core
https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/udp/packet.go
common/protocol/udp/packet.go
package udp import ( "github.com/v2fly/v2ray-core/v5/common/buf" "github.com/v2fly/v2ray-core/v5/common/net" ) // Packet is a UDP packet together with its source and destination address. type Packet struct { Payload *buf.Buffer Source net.Destination Target net.Destination }
go
MIT
b2c3b2506695d872162baeed95c9525fbfdbfda0
2026-01-07T08:36:12.135351Z
false