From 81504dc2c45da2c5adbb7de4725d4af09178fc1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Wed, 17 Aug 2022 20:34:29 +0800 Subject: [PATCH] Add conntracker api --- common/conntrack/tracker.go | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 common/conntrack/tracker.go diff --git a/common/conntrack/tracker.go b/common/conntrack/tracker.go new file mode 100644 index 0000000..b6c7662 --- /dev/null +++ b/common/conntrack/tracker.go @@ -0,0 +1,41 @@ +package conntrack + +import ( + "io" + "sync" + + "github.com/sagernet/sing/common" + "github.com/sagernet/sing/common/x/list" +) + +type Tracker struct { + access sync.Mutex + connections list.List[io.Closer] +} + +func (m *Tracker) Track(conn io.Closer) *Registration { + m.access.Lock() + element := m.connections.PushBack(conn) + m.access.Unlock() + return &Registration{m, element} +} + +func (m *Tracker) Reset() { + m.access.Lock() + defer m.access.Unlock() + for element := m.connections.Front(); element != nil; element = element.Next() { + common.Close(element.Value) + } + m.connections = list.List[io.Closer]{} +} + +type Registration struct { + manager *Tracker + element *list.Element[io.Closer] +} + +func (t *Registration) Leave() { + t.manager.access.Lock() + defer t.manager.access.Unlock() + t.manager.connections.Remove(t.element) +}