group.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package interrupt
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "github.com/sagernet/sing/common/x/list"
  7. )
  8. type Group struct {
  9. access sync.Mutex
  10. connections list.List[*groupConnItem]
  11. }
  12. type groupConnItem struct {
  13. conn io.Closer
  14. isExternal bool
  15. }
  16. func NewGroup() *Group {
  17. return &Group{}
  18. }
  19. func (g *Group) NewConn(conn net.Conn, isExternal bool) net.Conn {
  20. g.access.Lock()
  21. defer g.access.Unlock()
  22. item := g.connections.PushBack(&groupConnItem{conn, isExternal})
  23. return &Conn{Conn: conn, group: g, element: item}
  24. }
  25. func (g *Group) NewPacketConn(conn net.PacketConn, isExternal bool) net.PacketConn {
  26. g.access.Lock()
  27. defer g.access.Unlock()
  28. item := g.connections.PushBack(&groupConnItem{conn, isExternal})
  29. return &PacketConn{PacketConn: conn, group: g, element: item}
  30. }
  31. func (g *Group) Interrupt(interruptExternalConnections bool) {
  32. g.access.Lock()
  33. defer g.access.Unlock()
  34. var toDelete []*list.Element[*groupConnItem]
  35. for element := g.connections.Front(); element != nil; element = element.Next() {
  36. if !element.Value.isExternal || interruptExternalConnections {
  37. element.Value.conn.Close()
  38. toDelete = append(toDelete, element)
  39. }
  40. }
  41. for _, element := range toDelete {
  42. g.connections.Remove(element)
  43. }
  44. }