repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/readv_test.go
common/buf/readv_test.go
// +build !wasm package buf_test import ( "crypto/rand" "net" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/sync/errgroup" "v2ray.com/core/common" . "v2ray.com/core/common/buf" "v2ray.com/core/testing/servers/tcp" ) func TestReadvReader(t *testing.T) { tcpServer := &tcp.Server{ MsgProcessor: func(b []byte) []byte { return b }, } dest, err := tcpServer.Start() common.Must(err) defer tcpServer.Close() // nolint: errcheck conn, err := net.Dial("tcp", dest.NetAddr()) common.Must(err) defer conn.Close() // nolint: errcheck const size = 8192 data := make([]byte, 8192) common.Must2(rand.Read(data)) var errg errgroup.Group errg.Go(func() error { writer := NewWriter(conn) mb := MergeBytes(nil, data) return writer.WriteMultiBuffer(mb) }) defer func() { if err := errg.Wait(); err != nil { t.Error(err) } }() rawConn, err := conn.(*net.TCPConn).SyscallConn() common.Must(err) reader := NewReadVReader(conn, rawConn) var rmb MultiBuffer for { mb, err := reader.ReadMultiBuffer() if err != nil { t.Fatal("unexpected error: ", err) } rmb, _ = MergeMulti(rmb, mb) if rmb.Len() == size { break } } rdata := make([]byte, size) SplitBytes(rmb, rdata) if r := cmp.Diff(data, rdata); r != "" { t.Fatal(r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/readv_unix.go
common/buf/readv_unix.go
// +build illumos package buf import "golang.org/x/sys/unix" type unixReader struct { iovs [][]byte } func (r *unixReader) Init(bs []*Buffer) { iovs := r.iovs if iovs == nil { iovs = make([][]byte, 0, len(bs)) } for _, b := range bs { iovs = append(iovs, b.v) } r.iovs = iovs } func (r *unixReader) Read(fd uintptr) int32 { n, e := unix.Readv(int(fd), r.iovs) if e != nil { return -1 } return int32(n) } func (r *unixReader) Clear() { r.iovs = r.iovs[:0] } func newMultiReader() multiReader { return &unixReader{} }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/readv_reader.go
common/buf/readv_reader.go
// +build !wasm package buf import ( "io" "runtime" "syscall" "v2ray.com/core/common/platform" ) type allocStrategy struct { current uint32 } func (s *allocStrategy) Current() uint32 { return s.current } func (s *allocStrategy) Adjust(n uint32) { if n >= s.current { s.current *= 4 } else { s.current = n } if s.current > 32 { s.current = 32 } if s.current == 0 { s.current = 1 } } func (s *allocStrategy) Alloc() []*Buffer { bs := make([]*Buffer, s.current) for i := range bs { bs[i] = New() } return bs } type multiReader interface { Init([]*Buffer) Read(fd uintptr) int32 Clear() } // ReadVReader is a Reader that uses readv(2) syscall to read data. type ReadVReader struct { io.Reader rawConn syscall.RawConn mr multiReader alloc allocStrategy } // NewReadVReader creates a new ReadVReader. func NewReadVReader(reader io.Reader, rawConn syscall.RawConn) *ReadVReader { return &ReadVReader{ Reader: reader, rawConn: rawConn, alloc: allocStrategy{ current: 1, }, mr: newMultiReader(), } } func (r *ReadVReader) readMulti() (MultiBuffer, error) { bs := r.alloc.Alloc() r.mr.Init(bs) var nBytes int32 err := r.rawConn.Read(func(fd uintptr) bool { n := r.mr.Read(fd) if n < 0 { return false } nBytes = n return true }) r.mr.Clear() if err != nil { ReleaseMulti(MultiBuffer(bs)) return nil, err } if nBytes == 0 { ReleaseMulti(MultiBuffer(bs)) return nil, io.EOF } nBuf := 0 for nBuf < len(bs) { if nBytes <= 0 { break } end := nBytes if end > Size { end = Size } bs[nBuf].end = end nBytes -= end nBuf++ } for i := nBuf; i < len(bs); i++ { bs[i].Release() bs[i] = nil } return MultiBuffer(bs[:nBuf]), nil } // ReadMultiBuffer implements Reader. func (r *ReadVReader) ReadMultiBuffer() (MultiBuffer, error) { if r.alloc.Current() == 1 { b, err := ReadBuffer(r.Reader) if b.IsFull() { r.alloc.Adjust(1) } return MultiBuffer{b}, err } mb, err := r.readMulti() if err != nil { return nil, err } r.alloc.Adjust(uint32(len(mb))) return mb, nil } var useReadv = false func init() { const defaultFlagValue = "NOT_DEFINED_AT_ALL" value := platform.NewEnvFlag("v2ray.buf.readv").GetValue(func() string { return defaultFlagValue }) switch value { case defaultFlagValue, "auto": if (runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "s390x") && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") { useReadv = true } case "enable": useReadv = true } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/multi_buffer_test.go
common/buf/multi_buffer_test.go
package buf_test import ( "bytes" "crypto/rand" "io" "testing" "github.com/google/go-cmp/cmp" "io/ioutil" "os" "v2ray.com/core/common" . "v2ray.com/core/common/buf" ) func TestMultiBufferRead(t *testing.T) { b1 := New() common.Must2(b1.WriteString("ab")) b2 := New() common.Must2(b2.WriteString("cd")) mb := MultiBuffer{b1, b2} bs := make([]byte, 32) _, nBytes := SplitBytes(mb, bs) if nBytes != 4 { t.Error("expect 4 bytes split, but got ", nBytes) } if r := cmp.Diff(bs[:nBytes], []byte("abcd")); r != "" { t.Error(r) } } func TestMultiBufferAppend(t *testing.T) { var mb MultiBuffer b := New() common.Must2(b.WriteString("ab")) mb = append(mb, b) if mb.Len() != 2 { t.Error("expected length 2, but got ", mb.Len()) } } func TestMultiBufferSliceBySizeLarge(t *testing.T) { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) mb := MergeBytes(nil, lb) mb, mb2 := SplitSize(mb, 1024) if mb2.Len() != 1024 { t.Error("expect length 1024, but got ", mb2.Len()) } if mb.Len() != 7*1024 { t.Error("expect length 7*1024, but got ", mb.Len()) } mb, mb3 := SplitSize(mb, 7*1024) if mb3.Len() != 7*1024 { t.Error("expect length 7*1024, but got", mb.Len()) } if !mb.IsEmpty() { t.Error("expect empty buffer, but got ", mb.Len()) } } func TestMultiBufferSplitFirst(t *testing.T) { b1 := New() b1.WriteString("b1") b2 := New() b2.WriteString("b2") b3 := New() b3.WriteString("b3") var mb MultiBuffer mb = append(mb, b1, b2, b3) mb, c1 := SplitFirst(mb) if diff := cmp.Diff(b1.String(), c1.String()); diff != "" { t.Error(diff) } mb, c2 := SplitFirst(mb) if diff := cmp.Diff(b2.String(), c2.String()); diff != "" { t.Error(diff) } mb, c3 := SplitFirst(mb) if diff := cmp.Diff(b3.String(), c3.String()); diff != "" { t.Error(diff) } if !mb.IsEmpty() { t.Error("expect empty buffer, but got ", mb.String()) } } func TestMultiBufferReadAllToByte(t *testing.T) { { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) rd := bytes.NewBuffer(lb) b, err := ReadAllToBytes(rd) common.Must(err) if l := len(b); l != 8*1024 { t.Error("unexpceted length from ReadAllToBytes", l) } } { const dat = "data/test_MultiBufferReadAllToByte.dat" f, err := os.Open(dat) common.Must(err) buf2, err := ReadAllToBytes(f) common.Must(err) f.Close() cnt, err := ioutil.ReadFile(dat) common.Must(err) if d := cmp.Diff(buf2, cnt); d != "" { t.Error("fail to read from file: ", d) } } } func TestMultiBufferCopy(t *testing.T) { lb := make([]byte, 8*1024) common.Must2(io.ReadFull(rand.Reader, lb)) reader := bytes.NewBuffer(lb) mb, err := ReadFrom(reader) common.Must(err) lbdst := make([]byte, 8*1024) mb.Copy(lbdst) if d := cmp.Diff(lb, lbdst); d != "" { t.Error("unexpceted different from MultiBufferCopy ", d) } } func TestSplitFirstBytes(t *testing.T) { a := New() common.Must2(a.WriteString("ab")) b := New() common.Must2(b.WriteString("bc")) mb := MultiBuffer{a, b} o := make([]byte, 2) _, cnt := SplitFirstBytes(mb, o) if cnt != 2 { t.Error("unexpected cnt from SplitFirstBytes ", cnt) } if d := cmp.Diff(string(o), "ab"); d != "" { t.Error("unexpected splited result from SplitFirstBytes ", d) } } func TestCompact(t *testing.T) { a := New() common.Must2(a.WriteString("ab")) b := New() common.Must2(b.WriteString("bc")) mb := MultiBuffer{a, b} cmb := Compact(mb) if w := cmb.String(); w != "abbc" { t.Error("unexpected Compact result ", w) } } func BenchmarkSplitBytes(b *testing.B) { var mb MultiBuffer raw := make([]byte, Size) b.ResetTimer() for i := 0; i < b.N; i++ { buffer := StackNew() buffer.Extend(Size) mb = append(mb, &buffer) mb, _ = SplitBytes(mb, raw) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/buf/copy_test.go
common/buf/copy_test.go
package buf_test import ( "crypto/rand" "io" "testing" "github.com/golang/mock/gomock" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/testing/mocks" ) func TestReadError(t *testing.T) { mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockReader := mocks.NewReader(mockCtl) mockReader.EXPECT().Read(gomock.Any()).Return(0, errors.New("error")) err := buf.Copy(buf.NewReader(mockReader), buf.Discard) if err == nil { t.Fatal("expected error, but nil") } if !buf.IsReadError(err) { t.Error("expected to be ReadError, but not") } if err.Error() != "error" { t.Fatal("unexpected error message: ", err.Error()) } } func TestWriteError(t *testing.T) { mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockWriter := mocks.NewWriter(mockCtl) mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("error")) err := buf.Copy(buf.NewReader(rand.Reader), buf.NewWriter(mockWriter)) if err == nil { t.Fatal("expected error, but nil") } if !buf.IsWriteError(err) { t.Error("expected to be WriteError, but not") } if err.Error() != "error" { t.Fatal("unexpected error message: ", err.Error()) } } type TestReader struct{} func (TestReader) Read(b []byte) (int, error) { return len(b), nil } func BenchmarkCopy(b *testing.B) { reader := buf.NewReader(io.LimitReader(TestReader{}, 10240)) writer := buf.Discard b.ResetTimer() for i := 0; i < b.N; i++ { _ = buf.Copy(reader, writer) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/session_test.go
common/mux/session_test.go
package mux_test import ( "testing" . "v2ray.com/core/common/mux" ) func TestSessionManagerAdd(t *testing.T) { m := NewSessionManager() s := m.Allocate() if s.ID != 1 { t.Error("id: ", s.ID) } if m.Size() != 1 { t.Error("size: ", m.Size()) } s = m.Allocate() if s.ID != 2 { t.Error("id: ", s.ID) } if m.Size() != 2 { t.Error("size: ", m.Size()) } s = &Session{ ID: 4, } m.Add(s) if s.ID != 4 { t.Error("id: ", s.ID) } if m.Size() != 3 { t.Error("size: ", m.Size()) } } func TestSessionManagerClose(t *testing.T) { m := NewSessionManager() s := m.Allocate() if m.CloseIfNoSession() { t.Error("able to close") } m.Remove(s.ID) if !m.CloseIfNoSession() { t.Error("not able to close") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/errors.generated.go
common/mux/errors.generated.go
package mux import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/client.go
common/mux/client.go
package mux import ( "context" "io" "sync" "time" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/session" "v2ray.com/core/common/signal/done" "v2ray.com/core/common/task" "v2ray.com/core/proxy" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" "v2ray.com/core/transport/pipe" ) type ClientManager struct { Enabled bool // wheather mux is enabled from user config Picker WorkerPicker } func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) error { for i := 0; i < 16; i++ { worker, err := m.Picker.PickAvailable() if err != nil { return err } if worker.Dispatch(ctx, link) { return nil } } return newError("unable to find an available mux client").AtWarning() } type WorkerPicker interface { PickAvailable() (*ClientWorker, error) } type IncrementalWorkerPicker struct { Factory ClientWorkerFactory access sync.Mutex workers []*ClientWorker cleanupTask *task.Periodic } func (p *IncrementalWorkerPicker) cleanupFunc() error { p.access.Lock() defer p.access.Unlock() if len(p.workers) == 0 { return newError("no worker") } p.cleanup() return nil } func (p *IncrementalWorkerPicker) cleanup() { var activeWorkers []*ClientWorker for _, w := range p.workers { if !w.Closed() { activeWorkers = append(activeWorkers, w) } } p.workers = activeWorkers } func (p *IncrementalWorkerPicker) findAvailable() int { for idx, w := range p.workers { if !w.IsFull() { return idx } } return -1 } func (p *IncrementalWorkerPicker) pickInternal() (*ClientWorker, bool, error) { p.access.Lock() defer p.access.Unlock() idx := p.findAvailable() if idx >= 0 { n := len(p.workers) if n > 1 && idx != n-1 { p.workers[n-1], p.workers[idx] = p.workers[idx], p.workers[n-1] } return p.workers[idx], false, nil } p.cleanup() worker, err := p.Factory.Create() if err != nil { return nil, false, err } p.workers = append(p.workers, worker) if p.cleanupTask == nil { p.cleanupTask = &task.Periodic{ Interval: time.Second * 30, Execute: p.cleanupFunc, } } return worker, true, nil } func (p *IncrementalWorkerPicker) PickAvailable() (*ClientWorker, error) { worker, start, err := p.pickInternal() if start { common.Must(p.cleanupTask.Start()) } return worker, err } type ClientWorkerFactory interface { Create() (*ClientWorker, error) } type DialingWorkerFactory struct { Proxy proxy.Outbound Dialer internet.Dialer Strategy ClientStrategy } func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)} uplinkReader, upLinkWriter := pipe.New(opts...) downlinkReader, downlinkWriter := pipe.New(opts...) c, err := NewClientWorker(transport.Link{ Reader: downlinkReader, Writer: upLinkWriter, }, f.Strategy) if err != nil { return nil, err } go func(p proxy.Outbound, d internet.Dialer, c common.Closable) { ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{ Target: net.TCPDestination(muxCoolAddress, muxCoolPort), }) ctx, cancel := context.WithCancel(ctx) if err := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); err != nil { errors.New("failed to handler mux client connection").Base(err).WriteToLog() } common.Must(c.Close()) cancel() }(f.Proxy, f.Dialer, c.done) return c, nil } type ClientStrategy struct { MaxConcurrency uint32 MaxConnection uint32 } type ClientWorker struct { sessionManager *SessionManager link transport.Link done *done.Instance strategy ClientStrategy } var muxCoolAddress = net.DomainAddress("v1.mux.cool") var muxCoolPort = net.Port(9527) // NewClientWorker creates a new mux.Client. func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) { c := &ClientWorker{ sessionManager: NewSessionManager(), link: stream, done: done.New(), strategy: s, } go c.fetchOutput() go c.monitor() return c, nil } func (m *ClientWorker) TotalConnections() uint32 { return uint32(m.sessionManager.Count()) } func (m *ClientWorker) ActiveConnections() uint32 { return uint32(m.sessionManager.Size()) } // Closed returns true if this Client is closed. func (m *ClientWorker) Closed() bool { return m.done.Done() } func (m *ClientWorker) monitor() { timer := time.NewTicker(time.Second * 16) defer timer.Stop() for { select { case <-m.done.Wait(): m.sessionManager.Close() common.Close(m.link.Writer) // nolint: errcheck common.Interrupt(m.link.Reader) // nolint: errcheck return case <-timer.C: size := m.sessionManager.Size() if size == 0 && m.sessionManager.CloseIfNoSession() { common.Must(m.done.Close()) } } } } func writeFirstPayload(reader buf.Reader, writer *Writer) error { err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100) if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout { return writer.WriteMultiBuffer(buf.MultiBuffer{}) } if err != nil { return err } return nil } func fetchInput(ctx context.Context, s *Session, output buf.Writer) { dest := session.OutboundFromContext(ctx).Target transferType := protocol.TransferTypeStream if dest.Network == net.Network_UDP { transferType = protocol.TransferTypePacket } s.transferType = transferType writer := NewWriter(s.ID, dest, output, transferType) defer s.Close() // nolint: errcheck defer writer.Close() // nolint: errcheck newError("dispatching request to ", dest).WriteToLog(session.ExportIDToError(ctx)) if err := writeFirstPayload(s.input, writer); err != nil { newError("failed to write first payload").Base(err).WriteToLog(session.ExportIDToError(ctx)) writer.hasError = true common.Interrupt(s.input) return } if err := buf.Copy(s.input, writer); err != nil { newError("failed to fetch all input").Base(err).WriteToLog(session.ExportIDToError(ctx)) writer.hasError = true common.Interrupt(s.input) return } } func (m *ClientWorker) IsClosing() bool { sm := m.sessionManager if m.strategy.MaxConnection > 0 && sm.Count() >= int(m.strategy.MaxConnection) { return true } return false } func (m *ClientWorker) IsFull() bool { if m.IsClosing() || m.Closed() { return true } sm := m.sessionManager if m.strategy.MaxConcurrency > 0 && sm.Size() >= int(m.strategy.MaxConcurrency) { return true } return false } func (m *ClientWorker) Dispatch(ctx context.Context, link *transport.Link) bool { if m.IsFull() || m.Closed() { return false } sm := m.sessionManager s := sm.Allocate() if s == nil { return false } s.input = link.Reader s.output = link.Writer go fetchInput(ctx, s, m.link.Writer) return true } func (m *ClientWorker) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error { if meta.Option.Has(OptionData) { return buf.Copy(NewStreamReader(reader), buf.Discard) } return nil } func (m *ClientWorker) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error { if meta.Option.Has(OptionData) { return buf.Copy(NewStreamReader(reader), buf.Discard) } return nil } func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error { if !meta.Option.Has(OptionData) { return nil } s, found := m.sessionManager.Get(meta.SessionID) if !found { // Notify remote peer to close this session. closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream) closingWriter.Close() return buf.Copy(NewStreamReader(reader), buf.Discard) } rr := s.NewReader(reader) err := buf.Copy(rr, s.output) if err != nil && buf.IsWriteError(err) { newError("failed to write to downstream. closing session ", s.ID).Base(err).WriteToLog() // Notify remote peer to close this session. closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream) closingWriter.Close() drainErr := buf.Copy(rr, buf.Discard) common.Interrupt(s.input) s.Close() return drainErr } return err } func (m *ClientWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error { if s, found := m.sessionManager.Get(meta.SessionID); found { if meta.Option.Has(OptionError) { common.Interrupt(s.input) common.Interrupt(s.output) } s.Close() } if meta.Option.Has(OptionData) { return buf.Copy(NewStreamReader(reader), buf.Discard) } return nil } func (m *ClientWorker) fetchOutput() { defer func() { common.Must(m.done.Close()) }() reader := &buf.BufferedReader{Reader: m.link.Reader} var meta FrameMetadata for { err := meta.Unmarshal(reader) if err != nil { if errors.Cause(err) != io.EOF { newError("failed to read metadata").Base(err).WriteToLog() } break } switch meta.SessionStatus { case SessionStatusKeepAlive: err = m.handleStatueKeepAlive(&meta, reader) case SessionStatusEnd: err = m.handleStatusEnd(&meta, reader) case SessionStatusNew: err = m.handleStatusNew(&meta, reader) case SessionStatusKeep: err = m.handleStatusKeep(&meta, reader) default: status := meta.SessionStatus newError("unknown status: ", status).AtError().WriteToLog() return } if err != nil { newError("failed to process data").Base(err).WriteToLog() return } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/frame_test.go
common/mux/frame_test.go
package mux_test import ( "testing" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/mux" "v2ray.com/core/common/net" ) func BenchmarkFrameWrite(b *testing.B) { frame := mux.FrameMetadata{ Target: net.TCPDestination(net.DomainAddress("www.v2ray.com"), net.Port(80)), SessionID: 1, SessionStatus: mux.SessionStatusNew, } writer := buf.New() defer writer.Release() for i := 0; i < b.N; i++ { common.Must(frame.WriteTo(writer)) writer.Clear() } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/writer.go
common/mux/writer.go
package mux import ( "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" ) type Writer struct { dest net.Destination writer buf.Writer id uint16 followup bool hasError bool transferType protocol.TransferType } func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType) *Writer { return &Writer{ id: id, dest: dest, writer: writer, followup: false, transferType: transferType, } } func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer { return &Writer{ id: id, writer: writer, followup: true, transferType: transferType, } } func (w *Writer) getNextFrameMeta() FrameMetadata { meta := FrameMetadata{ SessionID: w.id, Target: w.dest, } if w.followup { meta.SessionStatus = SessionStatusKeep } else { w.followup = true meta.SessionStatus = SessionStatusNew } return meta } func (w *Writer) writeMetaOnly() error { meta := w.getNextFrameMeta() b := buf.New() if err := meta.WriteTo(b); err != nil { return err } return w.writer.WriteMultiBuffer(buf.MultiBuffer{b}) } func writeMetaWithFrame(writer buf.Writer, meta FrameMetadata, data buf.MultiBuffer) error { frame := buf.New() if err := meta.WriteTo(frame); err != nil { return err } if _, err := serial.WriteUint16(frame, uint16(data.Len())); err != nil { return err } mb2 := make(buf.MultiBuffer, 0, len(data)+1) mb2 = append(mb2, frame) mb2 = append(mb2, data...) return writer.WriteMultiBuffer(mb2) } func (w *Writer) writeData(mb buf.MultiBuffer) error { meta := w.getNextFrameMeta() meta.Option.Set(OptionData) return writeMetaWithFrame(w.writer, meta, mb) } // WriteMultiBuffer implements buf.Writer. func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error { defer buf.ReleaseMulti(mb) if mb.IsEmpty() { return w.writeMetaOnly() } for !mb.IsEmpty() { var chunk buf.MultiBuffer if w.transferType == protocol.TransferTypeStream { mb, chunk = buf.SplitSize(mb, 8*1024) } else { mb2, b := buf.SplitFirst(mb) mb = mb2 chunk = buf.MultiBuffer{b} } if err := w.writeData(chunk); err != nil { return err } } return nil } // Close implements common.Closable. func (w *Writer) Close() error { meta := FrameMetadata{ SessionID: w.id, SessionStatus: SessionStatusEnd, } if w.hasError { meta.Option.Set(OptionError) } frame := buf.New() common.Must(meta.WriteTo(frame)) w.writer.WriteMultiBuffer(buf.MultiBuffer{frame}) // nolint: errcheck return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/reader.go
common/mux/reader.go
package mux import ( "io" "v2ray.com/core/common/buf" "v2ray.com/core/common/crypto" "v2ray.com/core/common/serial" ) // PacketReader is an io.Reader that reads whole chunk of Mux frames every time. type PacketReader struct { reader io.Reader eof bool } // NewPacketReader creates a new PacketReader. func NewPacketReader(reader io.Reader) *PacketReader { return &PacketReader{ reader: reader, eof: false, } } // ReadMultiBuffer implements buf.Reader. func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { if r.eof { return nil, io.EOF } size, err := serial.ReadUint16(r.reader) if err != nil { return nil, err } if size > buf.Size { return nil, newError("packet size too large: ", size) } b := buf.New() if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil { b.Release() return nil, err } r.eof = true return buf.MultiBuffer{b}, nil } // NewStreamReader creates a new StreamReader. func NewStreamReader(reader *buf.BufferedReader) buf.Reader { return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/client_test.go
common/mux/client_test.go
package mux_test import ( "context" "testing" "time" "github.com/golang/mock/gomock" "v2ray.com/core/common" "v2ray.com/core/common/errors" "v2ray.com/core/common/mux" "v2ray.com/core/common/net" "v2ray.com/core/common/session" "v2ray.com/core/testing/mocks" "v2ray.com/core/transport" "v2ray.com/core/transport/pipe" ) func TestIncrementalPickerFailure(t *testing.T) { mockCtl := gomock.NewController(t) defer mockCtl.Finish() mockWorkerFactory := mocks.NewMuxClientWorkerFactory(mockCtl) mockWorkerFactory.EXPECT().Create().Return(nil, errors.New("test")) picker := mux.IncrementalWorkerPicker{ Factory: mockWorkerFactory, } _, err := picker.PickAvailable() if err == nil { t.Error("expected error, but nil") } } func TestClientWorkerEOF(t *testing.T) { reader, writer := pipe.New(pipe.WithoutSizeLimit()) common.Must(writer.Close()) worker, err := mux.NewClientWorker(transport.Link{Reader: reader, Writer: writer}, mux.ClientStrategy{}) common.Must(err) time.Sleep(time.Millisecond * 500) f := worker.Dispatch(context.Background(), nil) if f { t.Error("expected failed dispatching, but actually not") } } func TestClientWorkerClose(t *testing.T) { mockCtl := gomock.NewController(t) defer mockCtl.Finish() r1, w1 := pipe.New(pipe.WithoutSizeLimit()) worker1, err := mux.NewClientWorker(transport.Link{ Reader: r1, Writer: w1, }, mux.ClientStrategy{ MaxConcurrency: 4, MaxConnection: 4, }) common.Must(err) r2, w2 := pipe.New(pipe.WithoutSizeLimit()) worker2, err := mux.NewClientWorker(transport.Link{ Reader: r2, Writer: w2, }, mux.ClientStrategy{ MaxConcurrency: 4, MaxConnection: 4, }) common.Must(err) factory := mocks.NewMuxClientWorkerFactory(mockCtl) gomock.InOrder( factory.EXPECT().Create().Return(worker1, nil), factory.EXPECT().Create().Return(worker2, nil), ) picker := &mux.IncrementalWorkerPicker{ Factory: factory, } manager := &mux.ClientManager{ Picker: picker, } tr1, tw1 := pipe.New(pipe.WithoutSizeLimit()) ctx1 := session.ContextWithOutbound(context.Background(), &session.Outbound{ Target: net.TCPDestination(net.DomainAddress("www.v2ray.com"), 80), }) common.Must(manager.Dispatch(ctx1, &transport.Link{ Reader: tr1, Writer: tw1, })) defer tw1.Close() common.Must(w1.Close()) time.Sleep(time.Millisecond * 500) if !worker1.Closed() { t.Error("worker1 is not finished") } tr2, tw2 := pipe.New(pipe.WithoutSizeLimit()) ctx2 := session.ContextWithOutbound(context.Background(), &session.Outbound{ Target: net.TCPDestination(net.DomainAddress("www.v2ray.com"), 80), }) common.Must(manager.Dispatch(ctx2, &transport.Link{ Reader: tr2, Writer: tw2, })) defer tw2.Close() common.Must(w2.Close()) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/mux_test.go
common/mux/mux_test.go
package mux_test import ( "io" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" . "v2ray.com/core/common/mux" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/transport/pipe" ) func readAll(reader buf.Reader) (buf.MultiBuffer, error) { var mb buf.MultiBuffer for { b, err := reader.ReadMultiBuffer() if err == io.EOF { break } if err != nil { return nil, err } mb = append(mb, b...) } return mb, nil } func TestReaderWriter(t *testing.T) { pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024)) dest := net.TCPDestination(net.DomainAddress("v2ray.com"), 80) writer := NewWriter(1, dest, pWriter, protocol.TransferTypeStream) dest2 := net.TCPDestination(net.LocalHostIP, 443) writer2 := NewWriter(2, dest2, pWriter, protocol.TransferTypeStream) dest3 := net.TCPDestination(net.LocalHostIPv6, 18374) writer3 := NewWriter(3, dest3, pWriter, protocol.TransferTypeStream) writePayload := func(writer *Writer, payload ...byte) error { b := buf.New() b.Write(payload) return writer.WriteMultiBuffer(buf.MultiBuffer{b}) } common.Must(writePayload(writer, 'a', 'b', 'c', 'd')) common.Must(writePayload(writer2)) common.Must(writePayload(writer, 'e', 'f', 'g', 'h')) common.Must(writePayload(writer3, 'x')) writer.Close() writer3.Close() common.Must(writePayload(writer2, 'y')) writer2.Close() bytesReader := &buf.BufferedReader{Reader: pReader} { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 1, SessionStatus: SessionStatusNew, Target: dest, Option: OptionData, }); r != "" { t.Error("metadata: ", r) } data, err := readAll(NewStreamReader(bytesReader)) common.Must(err) if s := data.String(); s != "abcd" { t.Error("data: ", s) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionStatus: SessionStatusNew, SessionID: 2, Option: 0, Target: dest2, }); r != "" { t.Error("meta: ", r) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 1, SessionStatus: SessionStatusKeep, Option: 1, }); r != "" { t.Error("meta: ", r) } data, err := readAll(NewStreamReader(bytesReader)) common.Must(err) if s := data.String(); s != "efgh" { t.Error("data: ", s) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 3, SessionStatus: SessionStatusNew, Option: 1, Target: dest3, }); r != "" { t.Error("meta: ", r) } data, err := readAll(NewStreamReader(bytesReader)) common.Must(err) if s := data.String(); s != "x" { t.Error("data: ", s) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 1, SessionStatus: SessionStatusEnd, Option: 0, }); r != "" { t.Error("meta: ", r) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 3, SessionStatus: SessionStatusEnd, Option: 0, }); r != "" { t.Error("meta: ", r) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 2, SessionStatus: SessionStatusKeep, Option: 1, }); r != "" { t.Error("meta: ", r) } data, err := readAll(NewStreamReader(bytesReader)) common.Must(err) if s := data.String(); s != "y" { t.Error("data: ", s) } } { var meta FrameMetadata common.Must(meta.Unmarshal(bytesReader)) if r := cmp.Diff(meta, FrameMetadata{ SessionID: 2, SessionStatus: SessionStatusEnd, Option: 0, }); r != "" { t.Error("meta: ", r) } } pWriter.Close() { var meta FrameMetadata err := meta.Unmarshal(bytesReader) if err == nil { t.Error("nil error") } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/session.go
common/mux/session.go
package mux import ( "sync" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/protocol" ) type SessionManager struct { sync.RWMutex sessions map[uint16]*Session count uint16 closed bool } func NewSessionManager() *SessionManager { return &SessionManager{ count: 0, sessions: make(map[uint16]*Session, 16), } } func (m *SessionManager) Closed() bool { m.RLock() defer m.RUnlock() return m.closed } func (m *SessionManager) Size() int { m.RLock() defer m.RUnlock() return len(m.sessions) } func (m *SessionManager) Count() int { m.RLock() defer m.RUnlock() return int(m.count) } func (m *SessionManager) Allocate() *Session { m.Lock() defer m.Unlock() if m.closed { return nil } m.count++ s := &Session{ ID: m.count, parent: m, } m.sessions[s.ID] = s return s } func (m *SessionManager) Add(s *Session) { m.Lock() defer m.Unlock() if m.closed { return } m.count++ m.sessions[s.ID] = s } func (m *SessionManager) Remove(id uint16) { m.Lock() defer m.Unlock() if m.closed { return } delete(m.sessions, id) if len(m.sessions) == 0 { m.sessions = make(map[uint16]*Session, 16) } } func (m *SessionManager) Get(id uint16) (*Session, bool) { m.RLock() defer m.RUnlock() if m.closed { return nil, false } s, found := m.sessions[id] return s, found } func (m *SessionManager) CloseIfNoSession() bool { m.Lock() defer m.Unlock() if m.closed { return true } if len(m.sessions) != 0 { return false } m.closed = true return true } func (m *SessionManager) Close() error { m.Lock() defer m.Unlock() if m.closed { return nil } m.closed = true for _, s := range m.sessions { common.Close(s.input) // nolint: errcheck common.Close(s.output) // nolint: errcheck } m.sessions = nil return nil } // Session represents a client connection in a Mux connection. type Session struct { input buf.Reader output buf.Writer parent *SessionManager ID uint16 transferType protocol.TransferType } // Close closes all resources associated with this session. func (s *Session) Close() error { common.Close(s.output) // nolint: errcheck common.Close(s.input) // nolint: errcheck s.parent.Remove(s.ID) return nil } // NewReader creates a buf.Reader based on the transfer type of this Session. func (s *Session) NewReader(reader *buf.BufferedReader) buf.Reader { if s.transferType == protocol.TransferTypeStream { return NewStreamReader(reader) } return NewPacketReader(reader) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/server.go
common/mux/server.go
package mux import ( "context" "io" "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/errors" "v2ray.com/core/common/log" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/session" "v2ray.com/core/features/routing" "v2ray.com/core/transport" "v2ray.com/core/transport/pipe" ) type Server struct { dispatcher routing.Dispatcher } // NewServer creates a new mux.Server. func NewServer(ctx context.Context) *Server { s := &Server{} core.RequireFeatures(ctx, func(d routing.Dispatcher) { s.dispatcher = d }) return s } // Type implements common.HasType. func (s *Server) Type() interface{} { return s.dispatcher.Type() } // Dispatch implements routing.Dispatcher func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) { if dest.Address != muxCoolAddress { return s.dispatcher.Dispatch(ctx, dest) } opts := pipe.OptionsFromContext(ctx) uplinkReader, uplinkWriter := pipe.New(opts...) downlinkReader, downlinkWriter := pipe.New(opts...) _, err := NewServerWorker(ctx, s.dispatcher, &transport.Link{ Reader: uplinkReader, Writer: downlinkWriter, }) if err != nil { return nil, err } return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil } // Start implements common.Runnable. func (s *Server) Start() error { return nil } // Close implements common.Closable. func (s *Server) Close() error { return nil } type ServerWorker struct { dispatcher routing.Dispatcher link *transport.Link sessionManager *SessionManager } func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) { worker := &ServerWorker{ dispatcher: d, link: link, sessionManager: NewSessionManager(), } go worker.run(ctx) return worker, nil } func handle(ctx context.Context, s *Session, output buf.Writer) { writer := NewResponseWriter(s.ID, output, s.transferType) if err := buf.Copy(s.input, writer); err != nil { newError("session ", s.ID, " ends.").Base(err).WriteToLog(session.ExportIDToError(ctx)) writer.hasError = true } writer.Close() s.Close() } func (w *ServerWorker) ActiveConnections() uint32 { return uint32(w.sessionManager.Size()) } func (w *ServerWorker) Closed() bool { return w.sessionManager.Closed() } func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error { if meta.Option.Has(OptionData) { return buf.Copy(NewStreamReader(reader), buf.Discard) } return nil } func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error { newError("received request for ", meta.Target).WriteToLog(session.ExportIDToError(ctx)) { msg := &log.AccessMessage{ To: meta.Target, Status: log.AccessAccepted, Reason: "", } if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() { msg.From = inbound.Source msg.Email = inbound.User.Email } ctx = log.ContextWithAccessMessage(ctx, msg) } link, err := w.dispatcher.Dispatch(ctx, meta.Target) if err != nil { if meta.Option.Has(OptionData) { buf.Copy(NewStreamReader(reader), buf.Discard) } return newError("failed to dispatch request.").Base(err) } s := &Session{ input: link.Reader, output: link.Writer, parent: w.sessionManager, ID: meta.SessionID, transferType: protocol.TransferTypeStream, } if meta.Target.Network == net.Network_UDP { s.transferType = protocol.TransferTypePacket } w.sessionManager.Add(s) go handle(ctx, s, w.link.Writer) if !meta.Option.Has(OptionData) { return nil } rr := s.NewReader(reader) if err := buf.Copy(rr, s.output); err != nil { buf.Copy(rr, buf.Discard) common.Interrupt(s.input) return s.Close() } return nil } func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error { if !meta.Option.Has(OptionData) { return nil } s, found := w.sessionManager.Get(meta.SessionID) if !found { // Notify remote peer to close this session. closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream) closingWriter.Close() return buf.Copy(NewStreamReader(reader), buf.Discard) } rr := s.NewReader(reader) err := buf.Copy(rr, s.output) if err != nil && buf.IsWriteError(err) { newError("failed to write to downstream writer. closing session ", s.ID).Base(err).WriteToLog() // Notify remote peer to close this session. closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream) closingWriter.Close() drainErr := buf.Copy(rr, buf.Discard) common.Interrupt(s.input) s.Close() return drainErr } return err } func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error { if s, found := w.sessionManager.Get(meta.SessionID); found { if meta.Option.Has(OptionError) { common.Interrupt(s.input) common.Interrupt(s.output) } s.Close() } if meta.Option.Has(OptionData) { return buf.Copy(NewStreamReader(reader), buf.Discard) } return nil } func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error { var meta FrameMetadata err := meta.Unmarshal(reader) if err != nil { return newError("failed to read metadata").Base(err) } switch meta.SessionStatus { case SessionStatusKeepAlive: err = w.handleStatusKeepAlive(&meta, reader) case SessionStatusEnd: err = w.handleStatusEnd(&meta, reader) case SessionStatusNew: err = w.handleStatusNew(ctx, &meta, reader) case SessionStatusKeep: err = w.handleStatusKeep(&meta, reader) default: status := meta.SessionStatus return newError("unknown status: ", status).AtError() } if err != nil { return newError("failed to process data").Base(err) } return nil } func (w *ServerWorker) run(ctx context.Context) { input := w.link.Reader reader := &buf.BufferedReader{Reader: input} defer w.sessionManager.Close() // nolint: errcheck for { select { case <-ctx.Done(): return default: err := w.handleFrame(ctx, reader) if err != nil { if errors.Cause(err) != io.EOF { newError("unexpected EOF").Base(err).WriteToLog(session.ExportIDToError(ctx)) common.Interrupt(input) } return } } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/frame.go
common/mux/frame.go
package mux import ( "encoding/binary" "io" "v2ray.com/core/common" "v2ray.com/core/common/bitmask" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" "v2ray.com/core/common/serial" ) type SessionStatus byte const ( SessionStatusNew SessionStatus = 0x01 SessionStatusKeep SessionStatus = 0x02 SessionStatusEnd SessionStatus = 0x03 SessionStatusKeepAlive SessionStatus = 0x04 ) const ( OptionData bitmask.Byte = 0x01 OptionError bitmask.Byte = 0x02 ) type TargetNetwork byte const ( TargetNetworkTCP TargetNetwork = 0x01 TargetNetworkUDP TargetNetwork = 0x02 ) var addrParser = protocol.NewAddressParser( protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4), protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain), protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6), protocol.PortThenAddress(), ) /* Frame format 2 bytes - length 2 bytes - session id 1 bytes - status 1 bytes - option 1 byte - network 2 bytes - port n bytes - address */ type FrameMetadata struct { Target net.Destination SessionID uint16 Option bitmask.Byte SessionStatus SessionStatus } func (f FrameMetadata) WriteTo(b *buf.Buffer) error { lenBytes := b.Extend(2) len0 := b.Len() sessionBytes := b.Extend(2) binary.BigEndian.PutUint16(sessionBytes, f.SessionID) common.Must(b.WriteByte(byte(f.SessionStatus))) common.Must(b.WriteByte(byte(f.Option))) if f.SessionStatus == SessionStatusNew { switch f.Target.Network { case net.Network_TCP: common.Must(b.WriteByte(byte(TargetNetworkTCP))) case net.Network_UDP: common.Must(b.WriteByte(byte(TargetNetworkUDP))) } if err := addrParser.WriteAddressPort(b, f.Target.Address, f.Target.Port); err != nil { return err } } len1 := b.Len() binary.BigEndian.PutUint16(lenBytes, uint16(len1-len0)) return nil } // Unmarshal reads FrameMetadata from the given reader. func (f *FrameMetadata) Unmarshal(reader io.Reader) error { metaLen, err := serial.ReadUint16(reader) if err != nil { return err } if metaLen > 512 { return newError("invalid metalen ", metaLen).AtError() } b := buf.New() defer b.Release() if _, err := b.ReadFullFrom(reader, int32(metaLen)); err != nil { return err } return f.UnmarshalFromBuffer(b) } // UnmarshalFromBuffer reads a FrameMetadata from the given buffer. // Visible for testing only. func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer) error { if b.Len() < 4 { return newError("insufficient buffer: ", b.Len()) } f.SessionID = binary.BigEndian.Uint16(b.BytesTo(2)) f.SessionStatus = SessionStatus(b.Byte(2)) f.Option = bitmask.Byte(b.Byte(3)) f.Target.Network = net.Network_Unknown if f.SessionStatus == SessionStatusNew { if b.Len() < 8 { return newError("insufficient buffer: ", b.Len()) } network := TargetNetwork(b.Byte(4)) b.Advance(5) addr, port, err := addrParser.ReadAddressPort(nil, b) if err != nil { return newError("failed to parse address and port").Base(err) } switch network { case TargetNetworkTCP: f.Target = net.TCPDestination(addr, port) case TargetNetworkUDP: f.Target = net.UDPDestination(addr, port) default: return newError("unknown network type: ", network) } } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/mux/mux.go
common/mux/mux.go
package mux //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/retry/errors.generated.go
common/retry/errors.generated.go
package retry import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/retry/retry_test.go
common/retry/retry_test.go
package retry_test import ( "testing" "time" "v2ray.com/core/common" "v2ray.com/core/common/errors" . "v2ray.com/core/common/retry" ) var ( errorTestOnly = errors.New("This is a fake error.") ) func TestNoRetry(t *testing.T) { startTime := time.Now().Unix() err := Timed(10, 100000).On(func() error { return nil }) endTime := time.Now().Unix() common.Must(err) if endTime < startTime { t.Error("endTime < startTime: ", startTime, " -> ", endTime) } } func TestRetryOnce(t *testing.T) { startTime := time.Now() called := 0 err := Timed(10, 1000).On(func() error { if called == 0 { called++ return errorTestOnly } return nil }) duration := time.Since(startTime) common.Must(err) if v := int64(duration / time.Millisecond); v < 900 { t.Error("duration: ", v) } } func TestRetryMultiple(t *testing.T) { startTime := time.Now() called := 0 err := Timed(10, 1000).On(func() error { if called < 5 { called++ return errorTestOnly } return nil }) duration := time.Since(startTime) common.Must(err) if v := int64(duration / time.Millisecond); v < 4900 { t.Error("duration: ", v) } } func TestRetryExhausted(t *testing.T) { startTime := time.Now() called := 0 err := Timed(2, 1000).On(func() error { called++ return errorTestOnly }) duration := time.Since(startTime) if errors.Cause(err) != ErrRetryFailed { t.Error("cause: ", err) } if v := int64(duration / time.Millisecond); v < 1900 { t.Error("duration: ", v) } } func TestExponentialBackoff(t *testing.T) { startTime := time.Now() called := 0 err := ExponentialBackoff(10, 100).On(func() error { called++ return errorTestOnly }) duration := time.Since(startTime) if errors.Cause(err) != ErrRetryFailed { t.Error("cause: ", err) } if v := int64(duration / time.Millisecond); v < 4000 { t.Error("duration: ", v) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/retry/retry.go
common/retry/retry.go
package retry // import "v2ray.com/core/common/retry" //go:generate go run v2ray.com/core/common/errors/errorgen import ( "time" ) var ( ErrRetryFailed = newError("all retry attempts failed") ) // Strategy is a way to retry on a specific function. type Strategy interface { // On performs a retry on a specific function, until it doesn't return any error. On(func() error) error } type retryer struct { totalAttempt int nextDelay func() uint32 } // On implements Strategy.On. func (r *retryer) On(method func() error) error { attempt := 0 accumulatedError := make([]error, 0, r.totalAttempt) for attempt < r.totalAttempt { err := method() if err == nil { return nil } numErrors := len(accumulatedError) if numErrors == 0 || err.Error() != accumulatedError[numErrors-1].Error() { accumulatedError = append(accumulatedError, err) } delay := r.nextDelay() time.Sleep(time.Duration(delay) * time.Millisecond) attempt++ } return newError(accumulatedError).Base(ErrRetryFailed) } // Timed returns a retry strategy with fixed interval. func Timed(attempts int, delay uint32) Strategy { return &retryer{ totalAttempt: attempts, nextDelay: func() uint32 { return delay }, } } func ExponentialBackoff(attempts int, delay uint32) Strategy { nextDelay := uint32(0) return &retryer{ totalAttempt: attempts, nextDelay: func() uint32 { r := nextDelay nextDelay += delay return r }, } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/network.go
common/net/network.go
package net func (n Network) SystemString() string { switch n { case Network_TCP: return "tcp" case Network_UDP: return "udp" default: return "unknown" } } // HasNetwork returns true if the network list has a certain network. func HasNetwork(list []Network, network Network) bool { for _, value := range list { if value == network { return true } } return false }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/destination.pb.go
common/net/destination.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/net/destination.proto package net import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Endpoint of a network connection. type Endpoint struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Network Network `protobuf:"varint,1,opt,name=network,proto3,enum=v2ray.core.common.net.Network" json:"network,omitempty"` Address *IPOrDomain `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` Port uint32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` } func (x *Endpoint) Reset() { *x = Endpoint{} if protoimpl.UnsafeEnabled { mi := &file_common_net_destination_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Endpoint) String() string { return protoimpl.X.MessageStringOf(x) } func (*Endpoint) ProtoMessage() {} func (x *Endpoint) ProtoReflect() protoreflect.Message { mi := &file_common_net_destination_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Endpoint.ProtoReflect.Descriptor instead. func (*Endpoint) Descriptor() ([]byte, []int) { return file_common_net_destination_proto_rawDescGZIP(), []int{0} } func (x *Endpoint) GetNetwork() Network { if x != nil { return x.Network } return Network_Unknown } func (x *Endpoint) GetAddress() *IPOrDomain { if x != nil { return x.Address } return nil } func (x *Endpoint) GetPort() uint32 { if x != nil { return x.Port } return 0 } var File_common_net_destination_proto protoreflect.FileDescriptor var file_common_net_destination_proto_rawDesc = []byte{ 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x1a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x95, 0x01, 0x0a, 0x08, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x38, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x52, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x12, 0x3b, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x49, 0x50, 0x4f, 0x72, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x4e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_net_destination_proto_rawDescOnce sync.Once file_common_net_destination_proto_rawDescData = file_common_net_destination_proto_rawDesc ) func file_common_net_destination_proto_rawDescGZIP() []byte { file_common_net_destination_proto_rawDescOnce.Do(func() { file_common_net_destination_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_net_destination_proto_rawDescData) }) return file_common_net_destination_proto_rawDescData } var file_common_net_destination_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_net_destination_proto_goTypes = []interface{}{ (*Endpoint)(nil), // 0: v2ray.core.common.net.Endpoint (Network)(0), // 1: v2ray.core.common.net.Network (*IPOrDomain)(nil), // 2: v2ray.core.common.net.IPOrDomain } var file_common_net_destination_proto_depIdxs = []int32{ 1, // 0: v2ray.core.common.net.Endpoint.network:type_name -> v2ray.core.common.net.Network 2, // 1: v2ray.core.common.net.Endpoint.address:type_name -> v2ray.core.common.net.IPOrDomain 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_common_net_destination_proto_init() } func file_common_net_destination_proto_init() { if File_common_net_destination_proto != nil { return } file_common_net_network_proto_init() file_common_net_address_proto_init() if !protoimpl.UnsafeEnabled { file_common_net_destination_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Endpoint); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_net_destination_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_net_destination_proto_goTypes, DependencyIndexes: file_common_net_destination_proto_depIdxs, MessageInfos: file_common_net_destination_proto_msgTypes, }.Build() File_common_net_destination_proto = out.File file_common_net_destination_proto_rawDesc = nil file_common_net_destination_proto_goTypes = nil file_common_net_destination_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/port.pb.go
common/net/port.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/net/port.proto package net import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // PortRange represents a range of ports. type PortRange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The port that this range starts from. From uint32 `protobuf:"varint,1,opt,name=From,proto3" json:"From,omitempty"` // The port that this range ends with (inclusive). To uint32 `protobuf:"varint,2,opt,name=To,proto3" json:"To,omitempty"` } func (x *PortRange) Reset() { *x = PortRange{} if protoimpl.UnsafeEnabled { mi := &file_common_net_port_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PortRange) String() string { return protoimpl.X.MessageStringOf(x) } func (*PortRange) ProtoMessage() {} func (x *PortRange) ProtoReflect() protoreflect.Message { mi := &file_common_net_port_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PortRange.ProtoReflect.Descriptor instead. func (*PortRange) Descriptor() ([]byte, []int) { return file_common_net_port_proto_rawDescGZIP(), []int{0} } func (x *PortRange) GetFrom() uint32 { if x != nil { return x.From } return 0 } func (x *PortRange) GetTo() uint32 { if x != nil { return x.To } return 0 } // PortList is a list of ports. type PortList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Range []*PortRange `protobuf:"bytes,1,rep,name=range,proto3" json:"range,omitempty"` } func (x *PortList) Reset() { *x = PortList{} if protoimpl.UnsafeEnabled { mi := &file_common_net_port_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PortList) String() string { return protoimpl.X.MessageStringOf(x) } func (*PortList) ProtoMessage() {} func (x *PortList) ProtoReflect() protoreflect.Message { mi := &file_common_net_port_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PortList.ProtoReflect.Descriptor instead. func (*PortList) Descriptor() ([]byte, []int) { return file_common_net_port_proto_rawDescGZIP(), []int{1} } func (x *PortList) GetRange() []*PortRange { if x != nil { return x.Range } return nil } var File_common_net_port_proto protoreflect.FileDescriptor var file_common_net_port_proto_rawDesc = []byte{ 0x0a, 0x15, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x22, 0x2f, 0x0a, 0x09, 0x50, 0x6f, 0x72, 0x74, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x46, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x46, 0x72, 0x6f, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x54, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x02, 0x54, 0x6f, 0x22, 0x42, 0x0a, 0x08, 0x50, 0x6f, 0x72, 0x74, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x36, 0x0a, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x50, 0x6f, 0x72, 0x74, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x4e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_net_port_proto_rawDescOnce sync.Once file_common_net_port_proto_rawDescData = file_common_net_port_proto_rawDesc ) func file_common_net_port_proto_rawDescGZIP() []byte { file_common_net_port_proto_rawDescOnce.Do(func() { file_common_net_port_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_net_port_proto_rawDescData) }) return file_common_net_port_proto_rawDescData } var file_common_net_port_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_common_net_port_proto_goTypes = []interface{}{ (*PortRange)(nil), // 0: v2ray.core.common.net.PortRange (*PortList)(nil), // 1: v2ray.core.common.net.PortList } var file_common_net_port_proto_depIdxs = []int32{ 0, // 0: v2ray.core.common.net.PortList.range:type_name -> v2ray.core.common.net.PortRange 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_net_port_proto_init() } func file_common_net_port_proto_init() { if File_common_net_port_proto != nil { return } if !protoimpl.UnsafeEnabled { file_common_net_port_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PortRange); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_common_net_port_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PortList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_net_port_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_net_port_proto_goTypes, DependencyIndexes: file_common_net_port_proto_depIdxs, MessageInfos: file_common_net_port_proto_msgTypes, }.Build() File_common_net_port_proto = out.File file_common_net_port_proto_rawDesc = nil file_common_net_port_proto_goTypes = nil file_common_net_port_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/errors.generated.go
common/net/errors.generated.go
package net import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/port_test.go
common/net/port_test.go
package net_test import ( "testing" . "v2ray.com/core/common/net" ) func TestPortRangeContains(t *testing.T) { portRange := &PortRange{ From: 53, To: 53, } if !portRange.Contains(Port(53)) { t.Error("expected port range containing 53, but actually not") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/connection.go
common/net/connection.go
// +build !confonly package net import ( "io" "net" "time" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/signal/done" ) type ConnectionOption func(*connection) func ConnectionLocalAddr(a net.Addr) ConnectionOption { return func(c *connection) { c.local = a } } func ConnectionRemoteAddr(a net.Addr) ConnectionOption { return func(c *connection) { c.remote = a } } func ConnectionInput(writer io.Writer) ConnectionOption { return func(c *connection) { c.writer = buf.NewWriter(writer) } } func ConnectionInputMulti(writer buf.Writer) ConnectionOption { return func(c *connection) { c.writer = writer } } func ConnectionOutput(reader io.Reader) ConnectionOption { return func(c *connection) { c.reader = &buf.BufferedReader{Reader: buf.NewReader(reader)} } } func ConnectionOutputMulti(reader buf.Reader) ConnectionOption { return func(c *connection) { c.reader = &buf.BufferedReader{Reader: reader} } } func ConnectionOutputMultiUDP(reader buf.Reader) ConnectionOption { return func(c *connection) { c.reader = &buf.BufferedReader{ Reader: reader, Spliter: buf.SplitFirstBytes, } } } func ConnectionOnClose(n io.Closer) ConnectionOption { return func(c *connection) { c.onClose = n } } func NewConnection(opts ...ConnectionOption) net.Conn { c := &connection{ done: done.New(), local: &net.TCPAddr{ IP: []byte{0, 0, 0, 0}, Port: 0, }, remote: &net.TCPAddr{ IP: []byte{0, 0, 0, 0}, Port: 0, }, } for _, opt := range opts { opt(c) } return c } type connection struct { reader *buf.BufferedReader writer buf.Writer done *done.Instance onClose io.Closer local Addr remote Addr } func (c *connection) Read(b []byte) (int, error) { return c.reader.Read(b) } // ReadMultiBuffer implements buf.Reader. func (c *connection) ReadMultiBuffer() (buf.MultiBuffer, error) { return c.reader.ReadMultiBuffer() } // Write implements net.Conn.Write(). func (c *connection) Write(b []byte) (int, error) { if c.done.Done() { return 0, io.ErrClosedPipe } l := len(b) mb := make(buf.MultiBuffer, 0, l/buf.Size+1) mb = buf.MergeBytes(mb, b) return l, c.writer.WriteMultiBuffer(mb) } func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error { if c.done.Done() { buf.ReleaseMulti(mb) return io.ErrClosedPipe } return c.writer.WriteMultiBuffer(mb) } // Close implements net.Conn.Close(). func (c *connection) Close() error { common.Must(c.done.Close()) common.Interrupt(c.reader) common.Close(c.writer) if c.onClose != nil { return c.onClose.Close() } return nil } // LocalAddr implements net.Conn.LocalAddr(). func (c *connection) LocalAddr() net.Addr { return c.local } // RemoteAddr implements net.Conn.RemoteAddr(). func (c *connection) RemoteAddr() net.Addr { return c.remote } // SetDeadline implements net.Conn.SetDeadline(). func (c *connection) SetDeadline(t time.Time) error { return nil } // SetReadDeadline implements net.Conn.SetReadDeadline(). func (c *connection) SetReadDeadline(t time.Time) error { return nil } // SetWriteDeadline implements net.Conn.SetWriteDeadline(). func (c *connection) SetWriteDeadline(t time.Time) error { return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/net.go
common/net/net.go
// Package net is a drop-in replacement to Golang's net package, with some more functionalities. package net // import "v2ray.com/core/common/net" //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/port.go
common/net/port.go
package net import ( "encoding/binary" "strconv" ) // Port represents a network port in TCP and UDP protocol. type Port uint16 // PortFromBytes converts a byte array to a Port, assuming bytes are in big endian order. // @unsafe Caller must ensure that the byte array has at least 2 elements. func PortFromBytes(port []byte) Port { return Port(binary.BigEndian.Uint16(port)) } // PortFromInt converts an integer to a Port. // @error when the integer is not positive or larger then 65535 func PortFromInt(val uint32) (Port, error) { if val > 65535 { return Port(0), newError("invalid port range: ", val) } return Port(val), nil } // PortFromString converts a string to a Port. // @error when the string is not an integer or the integral value is a not a valid Port. func PortFromString(s string) (Port, error) { val, err := strconv.ParseUint(s, 10, 32) if err != nil { return Port(0), newError("invalid port range: ", s) } return PortFromInt(uint32(val)) } // Value return the corresponding uint16 value of a Port. func (p Port) Value() uint16 { return uint16(p) } // String returns the string presentation of a Port. func (p Port) String() string { return strconv.Itoa(int(p)) } // FromPort returns the beginning port of this PortRange. func (p *PortRange) FromPort() Port { return Port(p.From) } // ToPort returns the end port of this PortRange. func (p *PortRange) ToPort() Port { return Port(p.To) } // Contains returns true if the given port is within the range of a PortRange. func (p *PortRange) Contains(port Port) bool { return p.FromPort() <= port && port <= p.ToPort() } // SinglePortRange returns a PortRange contains a single port. func SinglePortRange(p Port) *PortRange { return &PortRange{ From: uint32(p), To: uint32(p), } } type MemoryPortRange struct { From Port To Port } func (r MemoryPortRange) Contains(port Port) bool { return r.From <= port && port <= r.To } type MemoryPortList []MemoryPortRange func PortListFromProto(l *PortList) MemoryPortList { mpl := make(MemoryPortList, 0, len(l.Range)) for _, r := range l.Range { mpl = append(mpl, MemoryPortRange{From: Port(r.From), To: Port(r.To)}) } return mpl } func (mpl MemoryPortList) Contains(port Port) bool { for _, pr := range mpl { if pr.Contains(port) { return true } } return false }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/system.go
common/net/system.go
package net import "net" // DialTCP is an alias of net.DialTCP. var DialTCP = net.DialTCP var DialUDP = net.DialUDP var DialUnix = net.DialUnix var Dial = net.Dial type ListenConfig = net.ListenConfig var Listen = net.Listen var ListenTCP = net.ListenTCP var ListenUDP = net.ListenUDP var ListenUnix = net.ListenUnix var LookupIP = net.LookupIP var FileConn = net.FileConn // ParseIP is an alias of net.ParseIP var ParseIP = net.ParseIP var SplitHostPort = net.SplitHostPort var CIDRMask = net.CIDRMask type Addr = net.Addr type Conn = net.Conn type PacketConn = net.PacketConn type TCPAddr = net.TCPAddr type TCPConn = net.TCPConn type UDPAddr = net.UDPAddr type UDPConn = net.UDPConn type UnixAddr = net.UnixAddr type UnixConn = net.UnixConn // IP is an alias for net.IP. type IP = net.IP type IPMask = net.IPMask type IPNet = net.IPNet const IPv4len = net.IPv4len const IPv6len = net.IPv6len type Error = net.Error type AddrError = net.AddrError type Dialer = net.Dialer type Listener = net.Listener type TCPListener = net.TCPListener type UnixListener = net.UnixListener var ResolveUnixAddr = net.ResolveUnixAddr var ResolveUDPAddr = net.ResolveUDPAddr type Resolver = net.Resolver
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/destination.go
common/net/destination.go
package net import ( "net" "strings" ) // Destination represents a network destination including address and protocol (tcp / udp). type Destination struct { Address Address Port Port Network Network } // DestinationFromAddr generates a Destination from a net address. func DestinationFromAddr(addr net.Addr) Destination { switch addr := addr.(type) { case *net.TCPAddr: return TCPDestination(IPAddress(addr.IP), Port(addr.Port)) case *net.UDPAddr: return UDPDestination(IPAddress(addr.IP), Port(addr.Port)) case *net.UnixAddr: // TODO: deal with Unix domain socket return TCPDestination(LocalHostIP, Port(9)) default: panic("Net: Unknown address type.") } } // ParseDestination converts a destination from its string presentation. func ParseDestination(dest string) (Destination, error) { d := Destination{ Address: AnyIP, Port: Port(0), } if strings.HasPrefix(dest, "tcp:") { d.Network = Network_TCP dest = dest[4:] } else if strings.HasPrefix(dest, "udp:") { d.Network = Network_UDP dest = dest[4:] } hstr, pstr, err := SplitHostPort(dest) if err != nil { return d, err } if len(hstr) > 0 { d.Address = ParseAddress(hstr) } if len(pstr) > 0 { port, err := PortFromString(pstr) if err != nil { return d, err } d.Port = port } return d, nil } // TCPDestination creates a TCP destination with given address func TCPDestination(address Address, port Port) Destination { return Destination{ Network: Network_TCP, Address: address, Port: port, } } // UDPDestination creates a UDP destination with given address func UDPDestination(address Address, port Port) Destination { return Destination{ Network: Network_UDP, Address: address, Port: port, } } // NetAddr returns the network address in this Destination in string form. func (d Destination) NetAddr() string { return d.Address.String() + ":" + d.Port.String() } // String returns the strings form of this Destination. func (d Destination) String() string { prefix := "unknown:" switch d.Network { case Network_TCP: prefix = "tcp:" case Network_UDP: prefix = "udp:" } return prefix + d.NetAddr() } // IsValid returns true if this Destination is valid. func (d Destination) IsValid() bool { return d.Network != Network_Unknown } // AsDestination converts current Endpoint into Destination. func (p *Endpoint) AsDestination() Destination { return Destination{ Network: p.Network, Address: p.Address.AsAddress(), Port: Port(p.Port), } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/network.pb.go
common/net/network.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/net/network.proto package net import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type Network int32 const ( Network_Unknown Network = 0 // Deprecated: Do not use. Network_RawTCP Network = 1 Network_TCP Network = 2 Network_UDP Network = 3 ) // Enum value maps for Network. var ( Network_name = map[int32]string{ 0: "Unknown", 1: "RawTCP", 2: "TCP", 3: "UDP", } Network_value = map[string]int32{ "Unknown": 0, "RawTCP": 1, "TCP": 2, "UDP": 3, } ) func (x Network) Enum() *Network { p := new(Network) *p = x return p } func (x Network) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Network) Descriptor() protoreflect.EnumDescriptor { return file_common_net_network_proto_enumTypes[0].Descriptor() } func (Network) Type() protoreflect.EnumType { return &file_common_net_network_proto_enumTypes[0] } func (x Network) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Network.Descriptor instead. func (Network) EnumDescriptor() ([]byte, []int) { return file_common_net_network_proto_rawDescGZIP(), []int{0} } // NetworkList is a list of Networks. type NetworkList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Network []Network `protobuf:"varint,1,rep,packed,name=network,proto3,enum=v2ray.core.common.net.Network" json:"network,omitempty"` } func (x *NetworkList) Reset() { *x = NetworkList{} if protoimpl.UnsafeEnabled { mi := &file_common_net_network_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NetworkList) String() string { return protoimpl.X.MessageStringOf(x) } func (*NetworkList) ProtoMessage() {} func (x *NetworkList) ProtoReflect() protoreflect.Message { mi := &file_common_net_network_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NetworkList.ProtoReflect.Descriptor instead. func (*NetworkList) Descriptor() ([]byte, []int) { return file_common_net_network_proto_rawDescGZIP(), []int{0} } func (x *NetworkList) GetNetwork() []Network { if x != nil { return x.Network } return nil } var File_common_net_network_proto protoreflect.FileDescriptor var file_common_net_network_proto_rawDesc = []byte{ 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x22, 0x47, 0x0a, 0x0b, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x38, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x52, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2a, 0x38, 0x0a, 0x07, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x06, 0x52, 0x61, 0x77, 0x54, 0x43, 0x50, 0x10, 0x01, 0x1a, 0x02, 0x08, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x43, 0x50, 0x10, 0x02, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x44, 0x50, 0x10, 0x03, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x4e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_net_network_proto_rawDescOnce sync.Once file_common_net_network_proto_rawDescData = file_common_net_network_proto_rawDesc ) func file_common_net_network_proto_rawDescGZIP() []byte { file_common_net_network_proto_rawDescOnce.Do(func() { file_common_net_network_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_net_network_proto_rawDescData) }) return file_common_net_network_proto_rawDescData } var file_common_net_network_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_common_net_network_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_net_network_proto_goTypes = []interface{}{ (Network)(0), // 0: v2ray.core.common.net.Network (*NetworkList)(nil), // 1: v2ray.core.common.net.NetworkList } var file_common_net_network_proto_depIdxs = []int32{ 0, // 0: v2ray.core.common.net.NetworkList.network:type_name -> v2ray.core.common.net.Network 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_net_network_proto_init() } func file_common_net_network_proto_init() { if File_common_net_network_proto != nil { return } if !protoimpl.UnsafeEnabled { file_common_net_network_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NetworkList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_net_network_proto_rawDesc, NumEnums: 1, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_net_network_proto_goTypes, DependencyIndexes: file_common_net_network_proto_depIdxs, EnumInfos: file_common_net_network_proto_enumTypes, MessageInfos: file_common_net_network_proto_msgTypes, }.Build() File_common_net_network_proto = out.File file_common_net_network_proto_rawDesc = nil file_common_net_network_proto_goTypes = nil file_common_net_network_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/address_test.go
common/net/address_test.go
package net_test import ( "net" "testing" "github.com/google/go-cmp/cmp" . "v2ray.com/core/common/net" ) func TestAddressProperty(t *testing.T) { type addrProprty struct { IP []byte Domain string Family AddressFamily String string } testCases := []struct { Input Address Output addrProprty }{ { Input: IPAddress([]byte{byte(1), byte(2), byte(3), byte(4)}), Output: addrProprty{ IP: []byte{byte(1), byte(2), byte(3), byte(4)}, Family: AddressFamilyIPv4, String: "1.2.3.4", }, }, { Input: IPAddress([]byte{ byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), }), Output: addrProprty{ IP: []byte{ byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), byte(1), byte(2), byte(3), byte(4), }, Family: AddressFamilyIPv6, String: "[102:304:102:304:102:304:102:304]", }, }, { Input: IPAddress([]byte{ byte(0), byte(0), byte(0), byte(0), byte(0), byte(0), byte(0), byte(0), byte(0), byte(0), byte(255), byte(255), byte(1), byte(2), byte(3), byte(4), }), Output: addrProprty{ IP: []byte{byte(1), byte(2), byte(3), byte(4)}, Family: AddressFamilyIPv4, String: "1.2.3.4", }, }, { Input: DomainAddress("v2ray.com"), Output: addrProprty{ Domain: "v2ray.com", Family: AddressFamilyDomain, String: "v2ray.com", }, }, { Input: IPAddress(net.IPv4(1, 2, 3, 4)), Output: addrProprty{ IP: []byte{byte(1), byte(2), byte(3), byte(4)}, Family: AddressFamilyIPv4, String: "1.2.3.4", }, }, { Input: ParseAddress("[2001:4860:0:2001::68]"), Output: addrProprty{ IP: []byte{0x20, 0x01, 0x48, 0x60, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68}, Family: AddressFamilyIPv6, String: "[2001:4860:0:2001::68]", }, }, { Input: ParseAddress("::0"), Output: addrProprty{ IP: AnyIPv6.IP(), Family: AddressFamilyIPv6, String: "[::]", }, }, { Input: ParseAddress("[::ffff:123.151.71.143]"), Output: addrProprty{ IP: []byte{123, 151, 71, 143}, Family: AddressFamilyIPv4, String: "123.151.71.143", }, }, { Input: NewIPOrDomain(ParseAddress("v2ray.com")).AsAddress(), Output: addrProprty{ Domain: "v2ray.com", Family: AddressFamilyDomain, String: "v2ray.com", }, }, { Input: NewIPOrDomain(ParseAddress("8.8.8.8")).AsAddress(), Output: addrProprty{ IP: []byte{8, 8, 8, 8}, Family: AddressFamilyIPv4, String: "8.8.8.8", }, }, { Input: NewIPOrDomain(ParseAddress("[2001:4860:0:2001::68]")).AsAddress(), Output: addrProprty{ IP: []byte{0x20, 0x01, 0x48, 0x60, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68}, Family: AddressFamilyIPv6, String: "[2001:4860:0:2001::68]", }, }, } for _, testCase := range testCases { actual := addrProprty{ Family: testCase.Input.Family(), String: testCase.Input.String(), } if testCase.Input.Family().IsIP() { actual.IP = testCase.Input.IP() } else { actual.Domain = testCase.Input.Domain() } if r := cmp.Diff(actual, testCase.Output); r != "" { t.Error("for input: ", testCase.Input, ":", r) } } } func TestInvalidAddressConvertion(t *testing.T) { panics := func(f func()) (ret bool) { defer func() { if r := recover(); r != nil { ret = true } }() f() return false } testCases := []func(){ func() { ParseAddress("8.8.8.8").Domain() }, func() { ParseAddress("2001:4860:0:2001::68").Domain() }, func() { ParseAddress("v2ray.com").IP() }, } for idx, testCase := range testCases { if !panics(testCase) { t.Error("case ", idx, " failed") } } } func BenchmarkParseAddressIPv4(b *testing.B) { for i := 0; i < b.N; i++ { addr := ParseAddress("8.8.8.8") if addr.Family() != AddressFamilyIPv4 { panic("not ipv4") } } } func BenchmarkParseAddressIPv6(b *testing.B) { for i := 0; i < b.N; i++ { addr := ParseAddress("2001:4860:0:2001::68") if addr.Family() != AddressFamilyIPv6 { panic("not ipv6") } } } func BenchmarkParseAddressDomain(b *testing.B) { for i := 0; i < b.N; i++ { addr := ParseAddress("v2ray.com") if addr.Family() != AddressFamilyDomain { panic("not domain") } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/destination_test.go
common/net/destination_test.go
package net_test import ( "testing" "github.com/google/go-cmp/cmp" . "v2ray.com/core/common/net" ) func TestDestinationProperty(t *testing.T) { testCases := []struct { Input Destination Network Network String string NetString string }{ { Input: TCPDestination(IPAddress([]byte{1, 2, 3, 4}), 80), Network: Network_TCP, String: "tcp:1.2.3.4:80", NetString: "1.2.3.4:80", }, { Input: UDPDestination(IPAddress([]byte{0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88}), 53), Network: Network_UDP, String: "udp:[2001:4860:4860::8888]:53", NetString: "[2001:4860:4860::8888]:53", }, } for _, testCase := range testCases { dest := testCase.Input if r := cmp.Diff(dest.Network, testCase.Network); r != "" { t.Error("unexpected Network in ", dest.String(), ": ", r) } if r := cmp.Diff(dest.String(), testCase.String); r != "" { t.Error(r) } if r := cmp.Diff(dest.NetAddr(), testCase.NetString); r != "" { t.Error(r) } } } func TestDestinationParse(t *testing.T) { cases := []struct { Input string Output Destination Error bool }{ { Input: "tcp:127.0.0.1:80", Output: TCPDestination(LocalHostIP, Port(80)), }, { Input: "udp:8.8.8.8:53", Output: UDPDestination(IPAddress([]byte{8, 8, 8, 8}), Port(53)), }, { Input: "8.8.8.8:53", Output: Destination{ Address: IPAddress([]byte{8, 8, 8, 8}), Port: Port(53), }, }, { Input: ":53", Output: Destination{ Address: AnyIP, Port: Port(53), }, }, { Input: "8.8.8.8", Error: true, }, { Input: "8.8.8.8:http", Error: true, }, } for _, testcase := range cases { d, err := ParseDestination(testcase.Input) if !testcase.Error { if err != nil { t.Error("for test case: ", testcase.Input, " expected no error, but got ", err) } if d != testcase.Output { t.Error("for test case: ", testcase.Input, " expected output: ", testcase.Output.String(), " but got ", d.String()) } } else { if err == nil { t.Error("for test case: ", testcase.Input, " expected error, but got nil") } } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/address.pb.go
common/net/address.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/net/address.proto package net import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Address of a network host. It may be either an IP address or a domain // address. type IPOrDomain struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Address: // *IPOrDomain_Ip // *IPOrDomain_Domain Address isIPOrDomain_Address `protobuf_oneof:"address"` } func (x *IPOrDomain) Reset() { *x = IPOrDomain{} if protoimpl.UnsafeEnabled { mi := &file_common_net_address_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *IPOrDomain) String() string { return protoimpl.X.MessageStringOf(x) } func (*IPOrDomain) ProtoMessage() {} func (x *IPOrDomain) ProtoReflect() protoreflect.Message { mi := &file_common_net_address_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use IPOrDomain.ProtoReflect.Descriptor instead. func (*IPOrDomain) Descriptor() ([]byte, []int) { return file_common_net_address_proto_rawDescGZIP(), []int{0} } func (m *IPOrDomain) GetAddress() isIPOrDomain_Address { if m != nil { return m.Address } return nil } func (x *IPOrDomain) GetIp() []byte { if x, ok := x.GetAddress().(*IPOrDomain_Ip); ok { return x.Ip } return nil } func (x *IPOrDomain) GetDomain() string { if x, ok := x.GetAddress().(*IPOrDomain_Domain); ok { return x.Domain } return "" } type isIPOrDomain_Address interface { isIPOrDomain_Address() } type IPOrDomain_Ip struct { // IP address. Must by either 4 or 16 bytes. Ip []byte `protobuf:"bytes,1,opt,name=ip,proto3,oneof"` } type IPOrDomain_Domain struct { // Domain address. Domain string `protobuf:"bytes,2,opt,name=domain,proto3,oneof"` } func (*IPOrDomain_Ip) isIPOrDomain_Address() {} func (*IPOrDomain_Domain) isIPOrDomain_Address() {} var File_common_net_address_proto protoreflect.FileDescriptor var file_common_net_address_proto_rawDesc = []byte{ 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x22, 0x43, 0x0a, 0x0a, 0x49, 0x50, 0x4f, 0x72, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12, 0x10, 0x0a, 0x02, 0x69, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x02, 0x69, 0x70, 0x12, 0x18, 0x0a, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x42, 0x09, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x4e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_net_address_proto_rawDescOnce sync.Once file_common_net_address_proto_rawDescData = file_common_net_address_proto_rawDesc ) func file_common_net_address_proto_rawDescGZIP() []byte { file_common_net_address_proto_rawDescOnce.Do(func() { file_common_net_address_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_net_address_proto_rawDescData) }) return file_common_net_address_proto_rawDescData } var file_common_net_address_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_net_address_proto_goTypes = []interface{}{ (*IPOrDomain)(nil), // 0: v2ray.core.common.net.IPOrDomain } var file_common_net_address_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_common_net_address_proto_init() } func file_common_net_address_proto_init() { if File_common_net_address_proto != nil { return } if !protoimpl.UnsafeEnabled { file_common_net_address_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*IPOrDomain); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_common_net_address_proto_msgTypes[0].OneofWrappers = []interface{}{ (*IPOrDomain_Ip)(nil), (*IPOrDomain_Domain)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_net_address_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_net_address_proto_goTypes, DependencyIndexes: file_common_net_address_proto_depIdxs, MessageInfos: file_common_net_address_proto_msgTypes, }.Build() File_common_net_address_proto = out.File file_common_net_address_proto_rawDesc = nil file_common_net_address_proto_goTypes = nil file_common_net_address_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/net/address.go
common/net/address.go
package net import ( "bytes" "net" "strings" ) var ( // LocalHostIP is a constant value for localhost IP in IPv4. LocalHostIP = IPAddress([]byte{127, 0, 0, 1}) // AnyIP is a constant value for any IP in IPv4. AnyIP = IPAddress([]byte{0, 0, 0, 0}) // LocalHostDomain is a constant value for localhost domain. LocalHostDomain = DomainAddress("localhost") // LocalHostIPv6 is a constant value for localhost IP in IPv6. LocalHostIPv6 = IPAddress([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}) // AnyIPv6 is a constant value for any IP in IPv6. AnyIPv6 = IPAddress([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) ) // AddressFamily is the type of address. type AddressFamily byte const ( // AddressFamilyIPv4 represents address as IPv4 AddressFamilyIPv4 = AddressFamily(0) // AddressFamilyIPv6 represents address as IPv6 AddressFamilyIPv6 = AddressFamily(1) // AddressFamilyDomain represents address as Domain AddressFamilyDomain = AddressFamily(2) ) // IsIPv4 returns true if current AddressFamily is IPv4. func (af AddressFamily) IsIPv4() bool { return af == AddressFamilyIPv4 } // IsIPv6 returns true if current AddressFamily is IPv6. func (af AddressFamily) IsIPv6() bool { return af == AddressFamilyIPv6 } // IsIP returns true if current AddressFamily is IPv6 or IPv4. func (af AddressFamily) IsIP() bool { return af == AddressFamilyIPv4 || af == AddressFamilyIPv6 } // IsDomain returns true if current AddressFamily is Domain. func (af AddressFamily) IsDomain() bool { return af == AddressFamilyDomain } // Address represents a network address to be communicated with. It may be an IP address or domain // address, not both. This interface doesn't resolve IP address for a given domain. type Address interface { IP() net.IP // IP of this Address Domain() string // Domain of this Address Family() AddressFamily String() string // String representation of this Address } func isAlphaNum(c byte) bool { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } // ParseAddress parses a string into an Address. The return value will be an IPAddress when // the string is in the form of IPv4 or IPv6 address, or a DomainAddress otherwise. func ParseAddress(addr string) Address { // Handle IPv6 address in form as "[2001:4860:0:2001::68]" lenAddr := len(addr) if lenAddr > 0 && addr[0] == '[' && addr[lenAddr-1] == ']' { addr = addr[1 : lenAddr-1] lenAddr -= 2 } if lenAddr > 0 && (!isAlphaNum(addr[0]) || !isAlphaNum(addr[len(addr)-1])) { addr = strings.TrimSpace(addr) } ip := net.ParseIP(addr) if ip != nil { return IPAddress(ip) } return DomainAddress(addr) } var bytes0 = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // IPAddress creates an Address with given IP. func IPAddress(ip []byte) Address { switch len(ip) { case net.IPv4len: var addr ipv4Address = [4]byte{ip[0], ip[1], ip[2], ip[3]} return addr case net.IPv6len: if bytes.Equal(ip[:10], bytes0) && ip[10] == 0xff && ip[11] == 0xff { return IPAddress(ip[12:16]) } var addr ipv6Address = [16]byte{ ip[0], ip[1], ip[2], ip[3], ip[4], ip[5], ip[6], ip[7], ip[8], ip[9], ip[10], ip[11], ip[12], ip[13], ip[14], ip[15], } return addr default: newError("invalid IP format: ", ip).AtError().WriteToLog() return nil } } // DomainAddress creates an Address with given domain. func DomainAddress(domain string) Address { return domainAddress(domain) } type ipv4Address [4]byte func (a ipv4Address) IP() net.IP { return net.IP(a[:]) } func (ipv4Address) Domain() string { panic("Calling Domain() on an IPv4Address.") } func (ipv4Address) Family() AddressFamily { return AddressFamilyIPv4 } func (a ipv4Address) String() string { return a.IP().String() } type ipv6Address [16]byte func (a ipv6Address) IP() net.IP { return net.IP(a[:]) } func (ipv6Address) Domain() string { panic("Calling Domain() on an IPv6Address.") } func (ipv6Address) Family() AddressFamily { return AddressFamilyIPv6 } func (a ipv6Address) String() string { return "[" + a.IP().String() + "]" } type domainAddress string func (domainAddress) IP() net.IP { panic("Calling IP() on a DomainAddress.") } func (a domainAddress) Domain() string { return string(a) } func (domainAddress) Family() AddressFamily { return AddressFamilyDomain } func (a domainAddress) String() string { return a.Domain() } // AsAddress translates IPOrDomain to Address. func (d *IPOrDomain) AsAddress() Address { if d == nil { return nil } switch addr := d.Address.(type) { case *IPOrDomain_Ip: return IPAddress(addr.Ip) case *IPOrDomain_Domain: return DomainAddress(addr.Domain) } panic("Common|Net: Invalid address.") } // NewIPOrDomain translates Address to IPOrDomain func NewIPOrDomain(addr Address) *IPOrDomain { switch addr.Family() { case AddressFamilyDomain: return &IPOrDomain{ Address: &IPOrDomain_Domain{ Domain: addr.Domain(), }, } case AddressFamilyIPv4, AddressFamilyIPv6: return &IPOrDomain{ Address: &IPOrDomain_Ip{ Ip: addr.IP(), }, } default: panic("Unknown Address type.") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/uuid/uuid.go
common/uuid/uuid.go
package uuid // import "v2ray.com/core/common/uuid" import ( "bytes" "crypto/rand" "encoding/hex" "v2ray.com/core/common" "v2ray.com/core/common/errors" ) var ( byteGroups = []int{8, 4, 4, 4, 12} ) type UUID [16]byte // String returns the string representation of this UUID. func (u *UUID) String() string { bytes := u.Bytes() result := hex.EncodeToString(bytes[0 : byteGroups[0]/2]) start := byteGroups[0] / 2 for i := 1; i < len(byteGroups); i++ { nBytes := byteGroups[i] / 2 result += "-" result += hex.EncodeToString(bytes[start : start+nBytes]) start += nBytes } return result } // Bytes returns the bytes representation of this UUID. func (u *UUID) Bytes() []byte { return u[:] } // Equals returns true if this UUID equals another UUID by value. func (u *UUID) Equals(another *UUID) bool { if u == nil && another == nil { return true } if u == nil || another == nil { return false } return bytes.Equal(u.Bytes(), another.Bytes()) } // New creates a UUID with random value. func New() UUID { var uuid UUID common.Must2(rand.Read(uuid.Bytes())) return uuid } // ParseBytes converts a UUID in byte form to object. func ParseBytes(b []byte) (UUID, error) { var uuid UUID if len(b) != 16 { return uuid, errors.New("invalid UUID: ", b) } copy(uuid[:], b) return uuid, nil } // ParseString converts a UUID in string form to object. func ParseString(str string) (UUID, error) { var uuid UUID text := []byte(str) if len(text) < 32 { return uuid, errors.New("invalid UUID: ", str) } b := uuid.Bytes() for _, byteGroup := range byteGroups { if text[0] == '-' { text = text[1:] } if _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup]); err != nil { return uuid, err } text = text[byteGroup:] b = b[byteGroup/2:] } return uuid, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/uuid/uuid_test.go
common/uuid/uuid_test.go
package uuid_test import ( "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" . "v2ray.com/core/common/uuid" ) func TestParseBytes(t *testing.T) { str := "2418d087-648d-4990-86e8-19dca1d006d3" bytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3} uuid, err := ParseBytes(bytes) common.Must(err) if diff := cmp.Diff(uuid.String(), str); diff != "" { t.Error(diff) } _, err = ParseBytes([]byte{1, 3, 2, 4}) if err == nil { t.Fatal("Expect error but nil") } } func TestParseString(t *testing.T) { str := "2418d087-648d-4990-86e8-19dca1d006d3" expectedBytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3} uuid, err := ParseString(str) common.Must(err) if r := cmp.Diff(expectedBytes, uuid.Bytes()); r != "" { t.Fatal(r) } _, err = ParseString("2418d087") if err == nil { t.Fatal("Expect error but nil") } _, err = ParseString("2418d087-648k-4990-86e8-19dca1d006d3") if err == nil { t.Fatal("Expect error but nil") } } func TestNewUUID(t *testing.T) { uuid := New() uuid2, err := ParseString(uuid.String()) common.Must(err) if uuid.String() != uuid2.String() { t.Error("uuid string: ", uuid.String(), " != ", uuid2.String()) } if r := cmp.Diff(uuid.Bytes(), uuid2.Bytes()); r != "" { t.Error(r) } } func TestRandom(t *testing.T) { uuid := New() uuid2 := New() if uuid.String() == uuid2.String() { t.Error("duplicated uuid") } } func TestEquals(t *testing.T) { var uuid *UUID var uuid2 *UUID if !uuid.Equals(uuid2) { t.Error("empty uuid should equal") } uuid3 := New() if uuid.Equals(&uuid3) { t.Error("nil uuid equals non-nil uuid") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/stack/bytes.go
common/stack/bytes.go
package stack // TwoBytes is a [2]byte which is always allocated on stack. // //go:notinheap type TwoBytes [2]byte // EightBytes is a [8]byte which is always allocated on stack. // //go:notinheap type EightBytes [8]byte
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/session/session.go
common/session/session.go
// Package session provides functions for sessions of incoming requests. package session // import "v2ray.com/core/common/session" import ( "context" "math/rand" "v2ray.com/core/common/errors" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" ) // ID of a session. type ID uint32 // NewID generates a new ID. The generated ID is high likely to be unique, but not cryptographically secure. // The generated ID will never be 0. func NewID() ID { for { id := ID(rand.Uint32()) if id != 0 { return id } } } // ExportIDToError transfers session.ID into an error object, for logging purpose. // This can be used with error.WriteToLog(). func ExportIDToError(ctx context.Context) errors.ExportOption { id := IDFromContext(ctx) return func(h *errors.ExportOptionHolder) { h.SessionID = uint32(id) } } // Inbound is the metadata of an inbound connection. type Inbound struct { // Source address of the inbound connection. Source net.Destination // Getaway address Gateway net.Destination // Tag of the inbound proxy that handles the connection. Tag string // User is the user that authencates for the inbound. May be nil if the protocol allows anounymous traffic. User *protocol.MemoryUser } // Outbound is the metadata of an outbound connection. type Outbound struct { // Target address of the outbound connection. Target net.Destination // Gateway address Gateway net.Address } // SniffingRequest controls the behavior of content sniffing. type SniffingRequest struct { OverrideDestinationForProtocol []string Enabled bool } // Content is the metadata of the connection content. type Content struct { // Protocol of current content. Protocol string SniffingRequest SniffingRequest Attributes map[string]string SkipRoutePick bool } // Sockopt is the settings for socket connection. type Sockopt struct { // Mark of the socket connection. Mark int32 } // SetAttribute attachs additional string attributes to content. func (c *Content) SetAttribute(name string, value string) { if c.Attributes == nil { c.Attributes = make(map[string]string) } c.Attributes[name] = value } // Attribute retrieves additional string attributes from content. func (c *Content) Attribute(name string) string { if c.Attributes == nil { return "" } return c.Attributes[name] }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/session/context.go
common/session/context.go
package session import "context" type sessionKey int const ( idSessionKey sessionKey = iota inboundSessionKey outboundSessionKey contentSessionKey muxPreferedSessionKey sockoptSessionKey ) // ContextWithID returns a new context with the given ID. func ContextWithID(ctx context.Context, id ID) context.Context { return context.WithValue(ctx, idSessionKey, id) } // IDFromContext returns ID in this context, or 0 if not contained. func IDFromContext(ctx context.Context) ID { if id, ok := ctx.Value(idSessionKey).(ID); ok { return id } return 0 } func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context { return context.WithValue(ctx, inboundSessionKey, inbound) } func InboundFromContext(ctx context.Context) *Inbound { if inbound, ok := ctx.Value(inboundSessionKey).(*Inbound); ok { return inbound } return nil } func ContextWithOutbound(ctx context.Context, outbound *Outbound) context.Context { return context.WithValue(ctx, outboundSessionKey, outbound) } func OutboundFromContext(ctx context.Context) *Outbound { if outbound, ok := ctx.Value(outboundSessionKey).(*Outbound); ok { return outbound } return nil } func ContextWithContent(ctx context.Context, content *Content) context.Context { return context.WithValue(ctx, contentSessionKey, content) } func ContentFromContext(ctx context.Context) *Content { if content, ok := ctx.Value(contentSessionKey).(*Content); ok { return content } return nil } // ContextWithMuxPrefered returns a new context with the given bool func ContextWithMuxPrefered(ctx context.Context, forced bool) context.Context { return context.WithValue(ctx, muxPreferedSessionKey, forced) } // MuxPreferedFromContext returns value in this context, or false if not contained. func MuxPreferedFromContext(ctx context.Context) bool { if val, ok := ctx.Value(muxPreferedSessionKey).(bool); ok { return val } return false } // ContextWithSockopt returns a new context with Socket configs included func ContextWithSockopt(ctx context.Context, s *Sockopt) context.Context { return context.WithValue(ctx, sockoptSessionKey, s) } // SockoptFromContext returns Socket configs in this context, or nil if not contained. func SockoptFromContext(ctx context.Context) *Sockopt { if sockopt, ok := ctx.Value(sockoptSessionKey).(*Sockopt); ok { return sockopt } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/typed_message.pb.go
common/serial/typed_message.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/serial/typed_message.proto package serial import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // TypedMessage is a serialized proto message along with its type name. type TypedMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The name of the message type, retrieved from protobuf API. Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // Serialized proto message. Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (x *TypedMessage) Reset() { *x = TypedMessage{} if protoimpl.UnsafeEnabled { mi := &file_common_serial_typed_message_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TypedMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*TypedMessage) ProtoMessage() {} func (x *TypedMessage) ProtoReflect() protoreflect.Message { mi := &file_common_serial_typed_message_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TypedMessage.ProtoReflect.Descriptor instead. func (*TypedMessage) Descriptor() ([]byte, []int) { return file_common_serial_typed_message_proto_rawDescGZIP(), []int{0} } func (x *TypedMessage) GetType() string { if x != nil { return x.Type } return "" } func (x *TypedMessage) GetValue() []byte { if x != nil { return x.Value } return nil } var File_common_serial_typed_message_proto protoreflect.FileDescriptor var file_common_serial_typed_message_proto_rawDesc = []byte{ 0x0a, 0x21, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x64, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x22, 0x38, 0x0a, 0x0c, 0x54, 0x79, 0x70, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x59, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x50, 0x01, 0x5a, 0x1c, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0xaa, 0x02, 0x18, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x53, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_serial_typed_message_proto_rawDescOnce sync.Once file_common_serial_typed_message_proto_rawDescData = file_common_serial_typed_message_proto_rawDesc ) func file_common_serial_typed_message_proto_rawDescGZIP() []byte { file_common_serial_typed_message_proto_rawDescOnce.Do(func() { file_common_serial_typed_message_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_serial_typed_message_proto_rawDescData) }) return file_common_serial_typed_message_proto_rawDescData } var file_common_serial_typed_message_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_common_serial_typed_message_proto_goTypes = []interface{}{ (*TypedMessage)(nil), // 0: v2ray.core.common.serial.TypedMessage } var file_common_serial_typed_message_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_common_serial_typed_message_proto_init() } func file_common_serial_typed_message_proto_init() { if File_common_serial_typed_message_proto != nil { return } if !protoimpl.UnsafeEnabled { file_common_serial_typed_message_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TypedMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_serial_typed_message_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_serial_typed_message_proto_goTypes, DependencyIndexes: file_common_serial_typed_message_proto_depIdxs, MessageInfos: file_common_serial_typed_message_proto_msgTypes, }.Build() File_common_serial_typed_message_proto = out.File file_common_serial_typed_message_proto_rawDesc = nil file_common_serial_typed_message_proto_goTypes = nil file_common_serial_typed_message_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/typed_message.go
common/serial/typed_message.go
package serial import ( "errors" "reflect" "github.com/golang/protobuf/proto" ) // ToTypedMessage converts a proto Message into TypedMessage. func ToTypedMessage(message proto.Message) *TypedMessage { if message == nil { return nil } settings, _ := proto.Marshal(message) return &TypedMessage{ Type: GetMessageType(message), Value: settings, } } // GetMessageType returns the name of this proto Message. func GetMessageType(message proto.Message) string { return proto.MessageName(message) } // GetInstance creates a new instance of the message with messageType. func GetInstance(messageType string) (interface{}, error) { mType := proto.MessageType(messageType) if mType == nil || mType.Elem() == nil { return nil, errors.New("Serial: Unknown type: " + messageType) } return reflect.New(mType.Elem()).Interface(), nil } // GetInstance converts current TypedMessage into a proto Message. func (v *TypedMessage) GetInstance() (proto.Message, error) { instance, err := GetInstance(v.Type) if err != nil { return nil, err } protoMessage := instance.(proto.Message) if err := proto.Unmarshal(v.Value, protoMessage); err != nil { return nil, err } return protoMessage, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/serial.go
common/serial/serial.go
package serial import ( "encoding/binary" "io" ) // ReadUint16 reads first two bytes from the reader, and then coverts them to an uint16 value. func ReadUint16(reader io.Reader) (uint16, error) { var b [2]byte if _, err := io.ReadFull(reader, b[:]); err != nil { return 0, err } return binary.BigEndian.Uint16(b[:]), nil } // WriteUint16 writes an uint16 value into writer. func WriteUint16(writer io.Writer, value uint16) (int, error) { var b [2]byte binary.BigEndian.PutUint16(b[:], value) return writer.Write(b[:]) } // WriteUint64 writes an uint64 value into writer. func WriteUint64(writer io.Writer, value uint64) (int, error) { var b [8]byte binary.BigEndian.PutUint64(b[:], value) return writer.Write(b[:]) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/string.go
common/serial/string.go
package serial import ( "fmt" "strings" ) // ToString serialize an arbitrary value into string. func ToString(v interface{}) string { if v == nil { return " " } switch value := v.(type) { case string: return value case *string: return *value case fmt.Stringer: return value.String() case error: return value.Error() default: return fmt.Sprintf("%+v", value) } } // Concat concatenates all input into a single string. func Concat(v ...interface{}) string { builder := strings.Builder{} for _, value := range v { builder.WriteString(ToString(value)) } return builder.String() }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/typed_message_test.go
common/serial/typed_message_test.go
package serial_test import ( "testing" . "v2ray.com/core/common/serial" ) func TestGetInstance(t *testing.T) { p, err := GetInstance("") if p != nil { t.Error("expected nil instance, but got ", p) } if err == nil { t.Error("expect non-nil error, but got nil") } } func TestConvertingNilMessage(t *testing.T) { x := ToTypedMessage(nil) if x != nil { t.Error("expect nil, but actually not") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/serial_test.go
common/serial/serial_test.go
package serial_test import ( "bytes" "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/serial" ) func TestUint16Serial(t *testing.T) { b := buf.New() defer b.Release() n, err := serial.WriteUint16(b, 10) common.Must(err) if n != 2 { t.Error("expect 2 bytes writtng, but actually ", n) } if diff := cmp.Diff(b.Bytes(), []byte{0, 10}); diff != "" { t.Error(diff) } } func TestUint64Serial(t *testing.T) { b := buf.New() defer b.Release() n, err := serial.WriteUint64(b, 10) common.Must(err) if n != 8 { t.Error("expect 8 bytes writtng, but actually ", n) } if diff := cmp.Diff(b.Bytes(), []byte{0, 0, 0, 0, 0, 0, 0, 10}); diff != "" { t.Error(diff) } } func TestReadUint16(t *testing.T) { testCases := []struct { Input []byte Output uint16 }{ { Input: []byte{0, 1}, Output: 1, }, } for _, testCase := range testCases { v, err := serial.ReadUint16(bytes.NewReader(testCase.Input)) common.Must(err) if v != testCase.Output { t.Error("for input ", testCase.Input, " expect output ", testCase.Output, " but got ", v) } } } func BenchmarkReadUint16(b *testing.B) { reader := buf.New() defer reader.Release() common.Must2(reader.Write([]byte{0, 1})) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := serial.ReadUint16(reader) common.Must(err) reader.Clear() reader.Extend(2) } } func BenchmarkWriteUint64(b *testing.B) { writer := buf.New() defer writer.Release() b.ResetTimer() for i := 0; i < b.N; i++ { _, err := serial.WriteUint64(writer, 8) common.Must(err) writer.Clear() } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/serial/string_test.go
common/serial/string_test.go
package serial_test import ( "errors" "testing" "github.com/google/go-cmp/cmp" . "v2ray.com/core/common/serial" ) func TestToString(t *testing.T) { s := "a" data := []struct { Value interface{} String string }{ {Value: s, String: s}, {Value: &s, String: s}, {Value: errors.New("t"), String: "t"}, {Value: []byte{'b', 'c'}, String: "[98 99]"}, } for _, c := range data { if r := cmp.Diff(ToString(c.Value), c.String); r != "" { t.Error(r) } } } func TestConcat(t *testing.T) { testCases := []struct { Input []interface{} Output string }{ { Input: []interface{}{ "a", "b", }, Output: "ab", }, } for _, testCase := range testCases { actual := Concat(testCase.Input...) if actual != testCase.Output { t.Error("Unexpected output: ", actual, " but want: ", testCase.Output) } } } func BenchmarkConcat(b *testing.B) { input := []interface{}{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"} b.ReportAllocs() for i := 0; i < b.N; i++ { _ = Concat(input...) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/log_test.go
common/log/log_test.go
package log_test import ( "testing" "github.com/google/go-cmp/cmp" "v2ray.com/core/common/log" "v2ray.com/core/common/net" ) type testLogger struct { value string } func (l *testLogger) Handle(msg log.Message) { l.value = msg.String() } func TestLogRecord(t *testing.T) { var logger testLogger log.RegisterHandler(&logger) ip := "8.8.8.8" log.Record(&log.GeneralMessage{ Severity: log.Severity_Error, Content: net.ParseAddress(ip), }) if diff := cmp.Diff("[Error] "+ip, logger.value); diff != "" { t.Error(diff) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/logger_test.go
common/log/logger_test.go
package log_test import ( "io/ioutil" "os" "strings" "testing" "time" "v2ray.com/core/common" "v2ray.com/core/common/buf" . "v2ray.com/core/common/log" ) func TestFileLogger(t *testing.T) { f, err := ioutil.TempFile("", "vtest") common.Must(err) path := f.Name() common.Must(f.Close()) creator, err := CreateFileLogWriter(path) common.Must(err) handler := NewLogger(creator) handler.Handle(&GeneralMessage{Content: "Test Log"}) time.Sleep(2 * time.Second) common.Must(common.Close(handler)) f, err = os.Open(path) common.Must(err) defer f.Close() // nolint: errcheck b, err := buf.ReadAllToBytes(f) common.Must(err) if !strings.Contains(string(b), "Test Log") { t.Fatal("Expect log text contains 'Test Log', but actually: ", string(b)) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/log.go
common/log/log.go
package log // import "v2ray.com/core/common/log" import ( "sync" "v2ray.com/core/common/serial" ) // Message is the interface for all log messages. type Message interface { String() string } // Handler is the interface for log handler. type Handler interface { Handle(msg Message) } // GeneralMessage is a general log message that can contain all kind of content. type GeneralMessage struct { Severity Severity Content interface{} } // String implements Message. func (m *GeneralMessage) String() string { return serial.Concat("[", m.Severity, "] ", m.Content) } // Record writes a message into log stream. func Record(msg Message) { logHandler.Handle(msg) } var ( logHandler syncHandler ) // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded. func RegisterHandler(handler Handler) { if handler == nil { panic("Log handler is nil") } logHandler.Set(handler) } type syncHandler struct { sync.RWMutex Handler } func (h *syncHandler) Handle(msg Message) { h.RLock() defer h.RUnlock() if h.Handler != nil { h.Handler.Handle(msg) } } func (h *syncHandler) Set(handler Handler) { h.Lock() defer h.Unlock() h.Handler = handler }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/access.go
common/log/access.go
package log import ( "context" "strings" "v2ray.com/core/common/serial" ) type logKey int const ( accessMessageKey logKey = iota ) type AccessStatus string const ( AccessAccepted = AccessStatus("accepted") AccessRejected = AccessStatus("rejected") ) type AccessMessage struct { From interface{} To interface{} Status AccessStatus Reason interface{} Email string Detour string } func (m *AccessMessage) String() string { builder := strings.Builder{} builder.WriteString(serial.ToString(m.From)) builder.WriteByte(' ') builder.WriteString(string(m.Status)) builder.WriteByte(' ') builder.WriteString(serial.ToString(m.To)) builder.WriteByte(' ') if len(m.Detour) > 0 { builder.WriteByte('[') builder.WriteString(m.Detour) builder.WriteString("] ") } builder.WriteString(serial.ToString(m.Reason)) if len(m.Email) > 0 { builder.WriteString("email:") builder.WriteString(m.Email) builder.WriteByte(' ') } return builder.String() } func ContextWithAccessMessage(ctx context.Context, accessMessage *AccessMessage) context.Context { return context.WithValue(ctx, accessMessageKey, accessMessage) } func AccessMessageFromContext(ctx context.Context) *AccessMessage { if accessMessage, ok := ctx.Value(accessMessageKey).(*AccessMessage); ok { return accessMessage } return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/log.pb.go
common/log/log.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: common/log/log.proto package log import ( proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type Severity int32 const ( Severity_Unknown Severity = 0 Severity_Error Severity = 1 Severity_Warning Severity = 2 Severity_Info Severity = 3 Severity_Debug Severity = 4 ) // Enum value maps for Severity. var ( Severity_name = map[int32]string{ 0: "Unknown", 1: "Error", 2: "Warning", 3: "Info", 4: "Debug", } Severity_value = map[string]int32{ "Unknown": 0, "Error": 1, "Warning": 2, "Info": 3, "Debug": 4, } ) func (x Severity) Enum() *Severity { p := new(Severity) *p = x return p } func (x Severity) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Severity) Descriptor() protoreflect.EnumDescriptor { return file_common_log_log_proto_enumTypes[0].Descriptor() } func (Severity) Type() protoreflect.EnumType { return &file_common_log_log_proto_enumTypes[0] } func (x Severity) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Severity.Descriptor instead. func (Severity) EnumDescriptor() ([]byte, []int) { return file_common_log_log_proto_rawDescGZIP(), []int{0} } var File_common_log_log_proto protoreflect.FileDescriptor var file_common_log_log_proto_rawDesc = []byte{ 0x0a, 0x14, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6c, 0x6f, 0x67, 0x2f, 0x6c, 0x6f, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x67, 0x2a, 0x44, 0x0a, 0x08, 0x53, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x57, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x49, 0x6e, 0x66, 0x6f, 0x10, 0x03, 0x12, 0x09, 0x0a, 0x05, 0x44, 0x65, 0x62, 0x75, 0x67, 0x10, 0x04, 0x42, 0x50, 0x0a, 0x19, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x67, 0x50, 0x01, 0x5a, 0x19, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6c, 0x6f, 0x67, 0xaa, 0x02, 0x15, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x4c, 0x6f, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_common_log_log_proto_rawDescOnce sync.Once file_common_log_log_proto_rawDescData = file_common_log_log_proto_rawDesc ) func file_common_log_log_proto_rawDescGZIP() []byte { file_common_log_log_proto_rawDescOnce.Do(func() { file_common_log_log_proto_rawDescData = protoimpl.X.CompressGZIP(file_common_log_log_proto_rawDescData) }) return file_common_log_log_proto_rawDescData } var file_common_log_log_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_common_log_log_proto_goTypes = []interface{}{ (Severity)(0), // 0: v2ray.core.common.log.Severity } var file_common_log_log_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_common_log_log_proto_init() } func file_common_log_log_proto_init() { if File_common_log_log_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_common_log_log_proto_rawDesc, NumEnums: 1, NumMessages: 0, NumExtensions: 0, NumServices: 0, }, GoTypes: file_common_log_log_proto_goTypes, DependencyIndexes: file_common_log_log_proto_depIdxs, EnumInfos: file_common_log_log_proto_enumTypes, }.Build() File_common_log_log_proto = out.File file_common_log_log_proto_rawDesc = nil file_common_log_log_proto_goTypes = nil file_common_log_log_proto_depIdxs = nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/log/logger.go
common/log/logger.go
package log import ( "io" "log" "os" "time" "v2ray.com/core/common/platform" "v2ray.com/core/common/signal/done" "v2ray.com/core/common/signal/semaphore" ) // Writer is the interface for writing logs. type Writer interface { Write(string) error io.Closer } // WriterCreator is a function to create LogWriters. type WriterCreator func() Writer type generalLogger struct { creator WriterCreator buffer chan Message access *semaphore.Instance done *done.Instance } // NewLogger returns a generic log handler that can handle all type of messages. func NewLogger(logWriterCreator WriterCreator) Handler { return &generalLogger{ creator: logWriterCreator, buffer: make(chan Message, 16), access: semaphore.New(1), done: done.New(), } } func (l *generalLogger) run() { defer l.access.Signal() dataWritten := false ticker := time.NewTicker(time.Minute) defer ticker.Stop() logger := l.creator() if logger == nil { return } defer logger.Close() // nolint: errcheck for { select { case <-l.done.Wait(): return case msg := <-l.buffer: logger.Write(msg.String() + platform.LineSeparator()) // nolint: errcheck dataWritten = true case <-ticker.C: if !dataWritten { return } dataWritten = false } } } func (l *generalLogger) Handle(msg Message) { select { case l.buffer <- msg: default: } select { case <-l.access.Wait(): go l.run() default: } } func (l *generalLogger) Close() error { return l.done.Close() } type consoleLogWriter struct { logger *log.Logger } func (w *consoleLogWriter) Write(s string) error { w.logger.Print(s) return nil } func (w *consoleLogWriter) Close() error { return nil } type fileLogWriter struct { file *os.File logger *log.Logger } func (w *fileLogWriter) Write(s string) error { w.logger.Print(s) return nil } func (w *fileLogWriter) Close() error { return w.file.Close() } // CreateStdoutLogWriter returns a LogWriterCreator that creates LogWriter for stdout. func CreateStdoutLogWriter() WriterCreator { return func() Writer { return &consoleLogWriter{ logger: log.New(os.Stdout, "", log.Ldate|log.Ltime), } } } // CreateStderrLogWriter returns a LogWriterCreator that creates LogWriter for stderr. func CreateStderrLogWriter() WriterCreator { return func() Writer { return &consoleLogWriter{ logger: log.New(os.Stderr, "", log.Ldate|log.Ltime), } } } // CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file. func CreateFileLogWriter(path string) (WriterCreator, error) { file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return nil, err } file.Close() return func() Writer { file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return nil } return &fileLogWriter{ file: file, logger: log.New(file, "", log.Ldate|log.Ltime), } }, nil } func init() { RegisterHandler(NewLogger(CreateStdoutLogWriter())) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/signal/timer.go
common/signal/timer.go
package signal import ( "context" "sync" "time" "v2ray.com/core/common" "v2ray.com/core/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() // nolint: errcheck 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() // nolint: errcheck } 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/signal/timer_test.go
common/signal/timer_test.go
package signal_test import ( "context" "runtime" "testing" "time" . "v2ray.com/core/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("expcted 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/signal/notifier_test.go
common/signal/notifier_test.go
package signal_test import ( "testing" . "v2ray.com/core/common/signal" ) func TestNotifierSignal(t *testing.T) { n := NewNotifier() w := n.Wait() n.Signal() select { case <-w: default: t.Fail() } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/signal/pubsub/pubsub.go
common/signal/pubsub/pubsub.go
package pubsub import ( "errors" "sync" "time" "v2ray.com/core/common" "v2ray.com/core/common/signal/done" "v2ray.com/core/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() subs := append(s.subs[name], sub) s.subs[name] = subs 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/signal/pubsub/pubsub_test.go
common/signal/pubsub/pubsub_test.go
package pubsub_test import ( "testing" . "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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() // nolint: errcheck }) 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/task/periodic_test.go
common/task/periodic_test.go
package task_test import ( "testing" "time" "v2ray.com/core/common" . "v2ray.com/core/common/task" ) func TestPeriodicTaskStop(t *testing.T) { value := 0 task := &Periodic{ Interval: time.Second * 2, Execute: func() error { value++ return nil }, } common.Must(task.Start()) time.Sleep(time.Second * 5) common.Must(task.Close()) if value != 3 { t.Fatal("expected 3, but got ", value) } time.Sleep(time.Second * 4) if value != 3 { t.Fatal("expected 3, but got ", value) } common.Must(task.Start()) time.Sleep(time.Second * 3) if value != 5 { t.Fatal("Expected 5, but ", value) } common.Must(task.Close()) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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" "v2ray.com/core/common" . "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/task/task.go
common/task/task.go
package task import ( "context" "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/task/common.go
common/task/common.go
package task import "v2ray.com/core/common" // Close returns a func() that closes v. func Close(v interface{}) func() error { return func() error { return common.Close(v) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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 "v2ray.com/core/common/dice" import ( "math/rand" "time" ) // 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) } // 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.Intn(65536)) } 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/dice/dice_test.go
common/dice/dice_test.go
package dice_test import ( "math/rand" "testing" . "v2ray.com/core/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) } } func BenchmarkIntn20(b *testing.B) { for i := 0; i < b.N; i++ { rand.Intn(20) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/windows.go
common/platform/windows.go
// +build windows package platform import "path/filepath" func ExpandEnv(s string) string { // TODO return s } func LineSeparator() string { return "\r\n" } func GetToolLocation(file string) string { const name = "v2ray.location.tool" toolPath := EnvFlag{Name: name, AltName: NormalizeEnvName(name)}.GetValue(getExecutableDir) return filepath.Join(toolPath, file+".exe") } // 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/platform_test.go
common/platform/platform_test.go
package platform_test import ( "os" "path/filepath" "runtime" "testing" "v2ray.com/core/common" . "v2ray.com/core/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 := NormalizeEnvName(test.input); v != test.output { t.Error("unexpected output: ", v, " want ", test.output) } } } func TestEnvFlag(t *testing.T) { if v := (EnvFlag{ Name: "xxxxx.y", }.GetValueAsInt(10)); v != 10 { t.Error("env value: ", v) } } func TestGetAssetLocation(t *testing.T) { exec, err := os.Executable() common.Must(err) loc := 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 := GetAssetLocation("t"); v != "\\v2ray\\t" { t.Error("asset loc: ", v) } } else { if v := GetAssetLocation("t"); v != "/v2ray/t" { t.Error("asset loc: ", v) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/others.go
common/platform/others.go
// +build !windows package platform import ( "os" "path/filepath" ) func ExpandEnv(s string) string { return os.ExpandEnv(s) } func LineSeparator() string { return "\n" } func GetToolLocation(file string) string { const name = "v2ray.location.tool" toolPath := EnvFlag{Name: name, AltName: NormalizeEnvName(name)}.GetValue(getExecutableDir) return filepath.Join(toolPath, file) } // 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) for _, p := range []string{ defPath, filepath.Join("/usr/local/share/v2ray/", file), filepath.Join("/usr/share/v2ray/", file), } { if _, err := os.Stat(p); os.IsNotExist(err) { continue } // asset found return p } // asset not found, let the caller throw out the error return defPath }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/platform.go
common/platform/platform.go
package platform // import "v2ray.com/core/common/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.Replace(strings.ToUpper(strings.TrimSpace(name)), ".", "_", -1) } 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/filesystem/file.go
common/platform/filesystem/file.go
package filesystem import ( "io" "os" "v2ray.com/core/common/buf" "v2ray.com/core/common/platform" ) type FileReaderFunc func(path string) (io.ReadCloser, error) var NewFileReader FileReaderFunc = func(path string) (io.ReadCloser, error) { return os.Open(path) } func ReadFile(path string) ([]byte, error) { reader, err := NewFileReader(path) if err != nil { return nil, err } defer reader.Close() return buf.ReadAllToBytes(reader) } func ReadAsset(file string) ([]byte, error) { return ReadFile(platform.GetAssetLocation(file)) } func CopyFile(dst string, src string) error { bytes, err := ReadFile(src) if err != nil { return err } f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() _, err = f.Write(bytes) return err }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/ctlcmd/errors.generated.go
common/platform/ctlcmd/errors.generated.go
package ctlcmd import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/ctlcmd/attr_windows.go
common/platform/ctlcmd/attr_windows.go
// +build windows package ctlcmd import "syscall" func getSysProcAttr() *syscall.SysProcAttr { return &syscall.SysProcAttr{ HideWindow: true, } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/ctlcmd/ctlcmd.go
common/platform/ctlcmd/ctlcmd.go
package ctlcmd import ( "io" "os" "os/exec" "strings" "v2ray.com/core/common/buf" "v2ray.com/core/common/platform" ) //go:generate go run v2ray.com/core/common/errors/errorgen func Run(args []string, input io.Reader) (buf.MultiBuffer, error) { v2ctl := platform.GetToolLocation("v2ctl") if _, err := os.Stat(v2ctl); err != nil { return nil, newError("v2ctl doesn't exist").Base(err) } var errBuffer buf.MultiBufferContainer var outBuffer buf.MultiBufferContainer cmd := exec.Command(v2ctl, args...) cmd.Stderr = &errBuffer cmd.Stdout = &outBuffer cmd.SysProcAttr = getSysProcAttr() if input != nil { cmd.Stdin = input } if err := cmd.Start(); err != nil { return nil, newError("failed to start v2ctl").Base(err) } if err := cmd.Wait(); err != nil { msg := "failed to execute v2ctl" if errBuffer.Len() > 0 { msg += ": \n" + strings.TrimSpace(errBuffer.MultiBuffer.String()) } return nil, newError(msg).Base(err) } // log stderr, info message if !errBuffer.IsEmpty() { newError("<v2ctl message> \n", strings.TrimSpace(errBuffer.MultiBuffer.String())).AtInfo().WriteToLog() } return outBuffer.MultiBuffer, nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/platform/ctlcmd/attr_other.go
common/platform/ctlcmd/attr_other.go
// +build !windows package ctlcmd import "syscall" func getSysProcAttr() *syscall.SysProcAttr { return nil }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/chunk_test.go
common/crypto/chunk_test.go
package crypto_test import ( "bytes" "io" "testing" "v2ray.com/core/common" "v2ray.com/core/common/buf" . "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/aes.go
common/crypto/aes.go
package crypto import ( "crypto/aes" "crypto/cipher" "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/errors.generated.go
common/crypto/errors.generated.go
package crypto import "v2ray.com/core/common/errors" type errPathObjHolder struct{} func newError(values ...interface{}) *errors.Error { return errors.New(values...).WithPathObj(errPathObjHolder{}) }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/chacha20.go
common/crypto/chacha20.go
package crypto import ( "crypto/cipher" "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/io.go
common/crypto/io.go
package crypto import ( "crypto/cipher" "io" "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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" "v2ray.com/core/common" . "v2ray.com/core/common/crypto" ) func mustDecodeHex(s string) []byte { b, err := hex.DecodeString(s) common.Must(err) return b } func TestChaCha20Stream(t *testing.T) { var 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)) actualOutout := make([]byte, len(c.output)) s.XORKeyStream(actualOutout, input) if r := cmp.Diff(c.output, actualOutout); 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/crypto.go
common/crypto/crypto.go
// Package crypto provides common crypto libraries for V2Ray. package crypto // import "v2ray.com/core/common/crypto" //go:generate go run v2ray.com/core/common/errors/errorgen
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/benchmark_test.go
common/crypto/benchmark_test.go
package crypto_test import ( "crypto/cipher" "testing" . "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/auth.go
common/crypto/auth.go
package crypto import ( "crypto/cipher" "io" "math/rand" "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/bytespool" "v2ray.com/core/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 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 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 == uint16(r.auth.Overhead())+padding { r.done = true return io.EOF } if soft && int32(size) > r.reader.BufferedBytes() { r.size = size r.paddingLen = padding r.hasSize = true return errSoft } if size <= buf.Size { b, err := r.readBuffer(int32(size), int32(padding)) if err != nil { return nil } *mb = append(*mb, b) return nil } payload := bytespool.Alloc(int32(size)) defer bytespool.Free(payload) if _, err := io.ReadFull(r.reader, payload[:size]); err != nil { return err } size -= padding rb, err := r.auth.Open(payload[:0], payload[:size]) 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 { // With size of the chunk and padding length encrypted, the content of padding doesn't matter much. 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 mb2Write := make(buf.MultiBuffer, 0, len(mb)+10) 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) mb2Write := make(buf.MultiBuffer, 0, len(mb)+1) 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/chunk.go
common/crypto/chunk.go
package crypto import ( "encoding/binary" "io" "v2ray.com/core/common" "v2ray.com/core/common/buf" ) // ChunkSizeDecoder is a utility class to decode size value from bytes. type ChunkSizeDecoder interface { SizeBytes() int32 Decode([]byte) (uint16, error) } // 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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" "v2ray.com/core/common" "v2ray.com/core/common/buf" . "v2ray.com/core/common/crypto" "v2ray.com/core/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/crypto/internal/chacha_core_gen.go
common/crypto/internal/chacha_core_gen.go
// +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, 0644) 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/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) { 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 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/matchers_test.go
common/strmatcher/matchers_test.go
package strmatcher_test import ( "testing" "v2ray.com/core/common" . "v2ray.com/core/common/strmatcher" ) func TestMatcher(t *testing.T) { cases := []struct { pattern string mType Type input string output bool }{ { pattern: "v2ray.com", mType: Domain, input: "www.v2ray.com", output: true, }, { pattern: "v2ray.com", mType: Domain, input: "v2ray.com", output: true, }, { pattern: "v2ray.com", mType: Domain, input: "www.v3ray.com", output: false, }, { pattern: "v2ray.com", mType: Domain, input: "2ray.com", output: false, }, { pattern: "v2ray.com", mType: Domain, input: "xv2ray.com", output: false, }, { pattern: "v2ray.com", mType: Full, input: "v2ray.com", output: true, }, { pattern: "v2ray.com", mType: Full, input: "xv2ray.com", output: false, }, { pattern: "v2ray.com", mType: Regex, input: "v2rayxcom", 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) } } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/domain_matcher_test.go
common/strmatcher/domain_matcher_test.go
package strmatcher_test import ( "reflect" "testing" . "v2ray.com/core/common/strmatcher" ) func TestDomainMatcherGroup(t *testing.T) { g := new(DomainMatcherGroup) g.Add("v2ray.com", 1) g.Add("google.com", 2) g.Add("x.a.com", 3) g.Add("a.b.com", 4) g.Add("c.a.b.com", 5) g.Add("x.y.com", 4) g.Add("x.y.com", 6) testCases := []struct { Domain string Result []uint32 }{ { Domain: "x.v2ray.com", 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}, }, } 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 := new(DomainMatcherGroup) r := g.Match("v2ray.com") if len(r) != 0 { t.Error("Expect [], but ", r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/matchers.go
common/strmatcher/matchers.go
package strmatcher import ( "regexp" "strings" ) type fullMatcher string func (m fullMatcher) Match(s string) bool { return string(m) == s } func (m fullMatcher) String() string { return "full:" + string(m) } type substrMatcher string func (m substrMatcher) Match(s string) bool { return strings.Contains(s, string(m)) } func (m substrMatcher) String() string { return "keyword:" + string(m) } type domainMatcher string func (m domainMatcher) Match(s string) bool { pattern := string(m) if !strings.HasSuffix(s, pattern) { return false } return len(s) == len(pattern) || s[len(s)-len(pattern)-1] == '.' } func (m domainMatcher) String() string { return "domain:" + string(m) } type regexMatcher struct { pattern *regexp.Regexp } func (m *regexMatcher) Match(s string) bool { return m.pattern.MatchString(s) } func (m *regexMatcher) String() string { return "regexp:" + m.pattern.String() }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/full_matcher.go
common/strmatcher/full_matcher.go
package strmatcher type FullMatcherGroup struct { matchers map[string][]uint32 } func (g *FullMatcherGroup) Add(domain string, value uint32) { if g.matchers == nil { g.matchers = make(map[string][]uint32) } g.matchers[domain] = append(g.matchers[domain], value) } func (g *FullMatcherGroup) addMatcher(m fullMatcher, value uint32) { g.Add(string(m), value) } func (g *FullMatcherGroup) Match(str string) []uint32 { if g.matchers == nil { return nil } return g.matchers[str] }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/domain_matcher.go
common/strmatcher/domain_matcher.go
package strmatcher import "strings" func breakDomain(domain string) []string { return strings.Split(domain, ".") } type node struct { values []uint32 sub map[string]*node } // DomainMatcherGroup is a IndexMatcher for a large set of Domain matchers. // Visible for testing only. type DomainMatcherGroup struct { root *node } func (g *DomainMatcherGroup) Add(domain string, value uint32) { if g.root == nil { g.root = new(node) } current := g.root parts := breakDomain(domain) for i := len(parts) - 1; i >= 0; i-- { part := parts[i] if current.sub == nil { current.sub = make(map[string]*node) } next := current.sub[part] if next == nil { next = new(node) current.sub[part] = next } current = next } current.values = append(current.values, value) } func (g *DomainMatcherGroup) addMatcher(m domainMatcher, value uint32) { g.Add(string(m), value) } func (g *DomainMatcherGroup) Match(domain string) []uint32 { if domain == "" { return nil } current := g.root if current == nil { return nil } nextPart := func(idx int) int { for i := idx - 1; i >= 0; i-- { if domain[i] == '.' { return i } } return -1 } matches := [][]uint32{} idx := len(domain) for { if idx == -1 || current.sub == nil { break } nidx := nextPart(idx) part := domain[nidx+1 : idx] next := current.sub[part] if next == nil { break } current = next idx = nidx if len(current.values) > 0 { matches = append(matches, current.values) } } switch len(matches) { case 0: return nil case 1: return matches[0] default: result := []uint32{} for idx := range matches { // Insert reversely, the subdomain that matches further ranks higher result = append(result, matches[len(matches)-1-idx]...) } return result } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/strmatcher_test.go
common/strmatcher/strmatcher_test.go
package strmatcher_test import ( "reflect" "testing" "v2ray.com/core/common" . "v2ray.com/core/common/strmatcher" ) // See https://github.com/v2fly/v2ray-core/issues/92#issuecomment-673238489 func TestMatcherGroup(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{1, 2, 6}, }, { Input: "example.com", Output: []uint32{10, 4}, }, } matcherGroup := &MatcherGroup{} for _, rule := range rules { matcher, err := rule.Type.New(rule.Domain) common.Must(err) matcherGroup.Add(matcher) } 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
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/strmatcher.go
common/strmatcher/strmatcher.go
package strmatcher import ( "regexp" ) // Matcher is the interface to determine a string matches a pattern. type Matcher interface { // Match returns true if the given string matches a predefined pattern. Match(string) bool String() string } // 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 = iota // Substr is the type of matcher that the input string must contain the pattern as a sub-string. Substr // Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern. Domain // Regex is the type of matcher that the input string must matches the regular-expression pattern. Regex ) // 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: return domainMatcher(pattern), nil case Regex: r, err := regexp.Compile(pattern) if err != nil { return nil, err } return &regexMatcher{ pattern: r, }, nil default: panic("Unknown type") } } // IndexMatcher is the interface for matching with a group of matchers. type IndexMatcher interface { // Match returns the index of a matcher that matches the input. It returns empty array if no such matcher exists. Match(input string) []uint32 } type matcherEntry struct { m Matcher id uint32 } // MatcherGroup is an implementation of IndexMatcher. // Empty initialization works. type MatcherGroup struct { count uint32 fullMatcher FullMatcherGroup domainMatcher DomainMatcherGroup otherMatchers []matcherEntry } // Add adds a new Matcher into the MatcherGroup, and returns its index. The index will never be 0. func (g *MatcherGroup) Add(m Matcher) uint32 { g.count++ c := g.count switch tm := m.(type) { case fullMatcher: g.fullMatcher.addMatcher(tm, c) case domainMatcher: g.domainMatcher.addMatcher(tm, c) default: g.otherMatchers = append(g.otherMatchers, matcherEntry{ m: m, id: c, }) } return c } // Match implements IndexMatcher.Match. func (g *MatcherGroup) Match(pattern string) []uint32 { result := []uint32{} result = append(result, g.fullMatcher.Match(pattern)...) result = append(result, g.domainMatcher.Match(pattern)...) for _, e := range g.otherMatchers { if e.m.Match(pattern) { result = append(result, e.id) } } return result } // Size returns the number of matchers in the MatcherGroup. func (g *MatcherGroup) Size() uint32 { return g.count }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/benchmark_test.go
common/strmatcher/benchmark_test.go
package strmatcher_test import ( "strconv" "testing" "v2ray.com/core/common" . "v2ray.com/core/common/strmatcher" ) func BenchmarkDomainMatcherGroup(b *testing.B) { g := new(DomainMatcherGroup) for i := 1; i <= 1024; i++ { g.Add(strconv.Itoa(i)+".v2ray.com", uint32(i)) } b.ResetTimer() for i := 0; i < b.N; i++ { _ = g.Match("0.v2ray.com") } } func BenchmarkFullMatcherGroup(b *testing.B) { g := new(FullMatcherGroup) for i := 1; i <= 1024; i++ { g.Add(strconv.Itoa(i)+".v2ray.com", uint32(i)) } b.ResetTimer() for i := 0; i < b.N; i++ { _ = g.Match("0.v2ray.com") } } func BenchmarkMarchGroup(b *testing.B) { g := new(MatcherGroup) for i := 1; i <= 1024; i++ { m, err := Domain.New(strconv.Itoa(i) + ".v2ray.com") common.Must(err) g.Add(m) } b.ResetTimer() for i := 0; i < b.N; i++ { _ = g.Match("0.v2ray.com") } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false
v2ray/v2ray-core
https://github.com/v2ray/v2ray-core/blob/d80440f3d57b45c829dbf513306f7adf9a0f3f76/common/strmatcher/full_matcher_test.go
common/strmatcher/full_matcher_test.go
package strmatcher_test import ( "reflect" "testing" . "v2ray.com/core/common/strmatcher" ) func TestFullMatcherGroup(t *testing.T) { g := new(FullMatcherGroup) g.Add("v2ray.com", 1) g.Add("google.com", 2) g.Add("x.a.com", 3) g.Add("x.y.com", 4) g.Add("x.y.com", 6) testCases := []struct { Domain string Result []uint32 }{ { Domain: "v2ray.com", Result: []uint32{1}, }, { Domain: "y.com", Result: nil, }, { Domain: "x.y.com", Result: []uint32{4, 6}, }, } 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 := new(FullMatcherGroup) r := g.Match("v2ray.com") if len(r) != 0 { t.Error("Expect [], but ", r) } }
go
MIT
d80440f3d57b45c829dbf513306f7adf9a0f3f76
2026-01-07T08:35:44.381088Z
false