2023-03-03 19:26:54 +08:00
|
|
|
package conntrack
|
|
|
|
|
|
|
|
import (
|
2023-03-16 10:55:06 +08:00
|
|
|
"io"
|
2023-03-03 19:26:54 +08:00
|
|
|
"net"
|
|
|
|
|
2023-04-26 04:53:25 +08:00
|
|
|
"github.com/sagernet/sing/common/bufio"
|
2023-03-03 19:26:54 +08:00
|
|
|
"github.com/sagernet/sing/common/x/list"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PacketConn struct {
|
|
|
|
net.PacketConn
|
2023-03-16 10:55:06 +08:00
|
|
|
element *list.Element[io.Closer]
|
2023-03-03 19:26:54 +08:00
|
|
|
}
|
|
|
|
|
2023-04-13 11:20:19 +08:00
|
|
|
func NewPacketConn(conn net.PacketConn) (net.PacketConn, error) {
|
2023-03-03 19:26:54 +08:00
|
|
|
connAccess.Lock()
|
2023-03-16 10:55:06 +08:00
|
|
|
element := openConnection.PushBack(conn)
|
2023-03-03 19:26:54 +08:00
|
|
|
connAccess.Unlock()
|
2023-03-16 10:55:06 +08:00
|
|
|
if KillerEnabled {
|
|
|
|
err := killerCheck()
|
|
|
|
if err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2023-03-03 19:26:54 +08:00
|
|
|
return &PacketConn{
|
|
|
|
PacketConn: conn,
|
|
|
|
element: element,
|
2023-03-16 10:55:06 +08:00
|
|
|
}, nil
|
2023-03-03 19:26:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) Close() error {
|
|
|
|
if c.element.Value != nil {
|
|
|
|
connAccess.Lock()
|
|
|
|
if c.element.Value != nil {
|
|
|
|
openConnection.Remove(c.element)
|
|
|
|
c.element.Value = nil
|
|
|
|
}
|
|
|
|
connAccess.Unlock()
|
|
|
|
}
|
|
|
|
return c.PacketConn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) Upstream() any {
|
2023-04-26 04:53:25 +08:00
|
|
|
return bufio.NewPacketConn(c.PacketConn)
|
2023-03-03 19:26:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) ReaderReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) WriterReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|