2023-07-27 21:13:11 -04:00
|
|
|
package sing
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2023-07-29 06:47:47 -04:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/Yuzuki616/V2bX/common/rate"
|
|
|
|
|
|
|
|
"github.com/Yuzuki616/V2bX/limiter"
|
2023-07-27 21:13:11 -04:00
|
|
|
|
|
|
|
"github.com/Yuzuki616/V2bX/common/counter"
|
|
|
|
"github.com/inazumav/sing-box/adapter"
|
|
|
|
"github.com/inazumav/sing-box/log"
|
|
|
|
N "github.com/sagernet/sing/common/network"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HookServer struct {
|
|
|
|
hooker *Hooker
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHookServer(logger log.Logger) *HookServer {
|
|
|
|
return &HookServer{
|
|
|
|
hooker: &Hooker{
|
|
|
|
logger: logger,
|
2023-07-29 06:47:47 -04:00
|
|
|
counter: sync.Map{},
|
2023-07-27 21:13:11 -04:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HookServer) Start() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HookServer) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HookServer) StatsService() adapter.V2RayStatsService {
|
|
|
|
return h.hooker
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HookServer) Hooker() *Hooker {
|
|
|
|
return h.hooker
|
|
|
|
}
|
|
|
|
|
|
|
|
type Hooker struct {
|
|
|
|
logger log.Logger
|
2023-07-29 06:47:47 -04:00
|
|
|
counter sync.Map
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Hooker) RoutedConnection(inbound string, outbound string, user string, conn net.Conn) net.Conn {
|
2023-07-29 06:47:47 -04:00
|
|
|
l, err := limiter.GetLimiter(inbound)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("get limiter for ", inbound, " error: ", err)
|
|
|
|
}
|
|
|
|
ip, _, _ := strings.Cut(conn.RemoteAddr().String(), ":")
|
|
|
|
if b, r := l.CheckLimit(user, ip, true); r {
|
|
|
|
conn.Close()
|
|
|
|
h.logger.Error("[", inbound, "] ", "Limited ", user, " by ip or conn")
|
|
|
|
return conn
|
|
|
|
} else if b != nil {
|
|
|
|
conn = rate.NewConnRateLimiter(conn, b)
|
|
|
|
}
|
|
|
|
if c, ok := h.counter.Load(inbound); ok {
|
|
|
|
return counter.NewConnCounter(conn, c.(*counter.TrafficCounter).GetCounter(user))
|
|
|
|
} else {
|
|
|
|
c := counter.NewTrafficCounter()
|
|
|
|
h.counter.Store(inbound, c)
|
2023-07-27 21:13:11 -04:00
|
|
|
return counter.NewConnCounter(conn, c.GetCounter(user))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Hooker) RoutedPacketConnection(inbound string, outbound string, user string, conn N.PacketConn) N.PacketConn {
|
2023-07-29 06:47:47 -04:00
|
|
|
if c, ok := h.counter.Load(inbound); ok {
|
|
|
|
return counter.NewPacketConnCounter(conn, c.(*counter.TrafficCounter).GetCounter(user))
|
|
|
|
} else {
|
|
|
|
c := counter.NewTrafficCounter()
|
|
|
|
h.counter.Store(inbound, c)
|
2023-07-27 21:13:11 -04:00
|
|
|
return counter.NewPacketConnCounter(conn, c.GetCounter(user))
|
|
|
|
}
|
|
|
|
}
|