2024-08-27 03:07:58 +03:00
|
|
|
package main
|
|
|
|
|
2024-08-30 04:30:33 +03:00
|
|
|
import (
|
2024-08-30 05:27:52 +03:00
|
|
|
"net"
|
|
|
|
"time"
|
2024-08-30 04:30:33 +03:00
|
|
|
|
|
|
|
"kvas2-go/models"
|
2024-09-06 17:06:17 +03:00
|
|
|
"kvas2-go/netfilter-helper"
|
|
|
|
|
|
|
|
"github.com/coreos/go-iptables/iptables"
|
2024-08-30 04:30:33 +03:00
|
|
|
)
|
2024-08-27 03:07:58 +03:00
|
|
|
|
|
|
|
type Group struct {
|
|
|
|
*models.Group
|
2024-09-06 14:24:55 +03:00
|
|
|
|
|
|
|
Enabled bool
|
|
|
|
|
2024-09-06 17:06:17 +03:00
|
|
|
iptables *iptables.IPTables
|
2024-09-06 14:24:55 +03:00
|
|
|
ipset *netfilterHelper.IPSet
|
|
|
|
ifaceToIPSet *netfilterHelper.IfaceToIPSet
|
2024-08-27 03:07:58 +03:00
|
|
|
}
|
2024-08-30 04:30:33 +03:00
|
|
|
|
2024-09-14 18:20:44 +03:00
|
|
|
func (g *Group) AddIPv4(address net.IP, ttl time.Duration) error {
|
|
|
|
ttlSeconds := uint32(ttl.Seconds())
|
2024-10-21 00:18:42 +03:00
|
|
|
return g.ipset.AddIP(address, &ttlSeconds)
|
2024-09-14 18:20:44 +03:00
|
|
|
}
|
2024-08-30 05:27:52 +03:00
|
|
|
|
2024-09-14 18:20:44 +03:00
|
|
|
func (g *Group) DelIPv4(address net.IP) error {
|
|
|
|
return g.ipset.Del(address)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Group) ListIPv4() (map[string]*uint32, error) {
|
|
|
|
return g.ipset.List()
|
2024-08-30 05:27:52 +03:00
|
|
|
}
|
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
func (g *Group) Enable() error {
|
|
|
|
if g.Enabled {
|
2024-08-30 04:30:33 +03:00
|
|
|
return nil
|
|
|
|
}
|
2024-09-06 14:24:55 +03:00
|
|
|
defer func() {
|
|
|
|
if !g.Enabled {
|
|
|
|
_ = g.Disable()
|
2024-09-05 03:53:10 +03:00
|
|
|
}
|
2024-09-06 14:24:55 +03:00
|
|
|
}()
|
2024-09-05 03:53:10 +03:00
|
|
|
|
2024-09-06 17:06:17 +03:00
|
|
|
if g.FixProtect {
|
|
|
|
g.iptables.AppendUnique("filter", "_NDM_SL_FORWARD", "-o", g.Interface, "-m", "state", "--state", "NEW", "-j", "_NDM_SL_PROTECT")
|
|
|
|
}
|
|
|
|
|
2024-09-14 18:20:44 +03:00
|
|
|
err := g.ifaceToIPSet.Enable()
|
2024-09-04 10:59:52 +03:00
|
|
|
if err != nil {
|
2024-09-06 14:24:55 +03:00
|
|
|
return err
|
2024-09-04 10:59:52 +03:00
|
|
|
}
|
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
g.Enabled = true
|
2024-09-04 10:59:52 +03:00
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
return nil
|
|
|
|
}
|
2024-09-05 05:42:10 +03:00
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
func (g *Group) Disable() []error {
|
|
|
|
var errs []error
|
2024-09-05 06:21:26 +03:00
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
if !g.Enabled {
|
|
|
|
return nil
|
2024-09-05 05:42:10 +03:00
|
|
|
}
|
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
errs2 := g.ifaceToIPSet.Disable()
|
|
|
|
if errs2 != nil {
|
|
|
|
errs = append(errs, errs2...)
|
2024-09-05 05:42:10 +03:00
|
|
|
}
|
|
|
|
|
2024-09-06 14:24:55 +03:00
|
|
|
g.Enabled = false
|
2024-08-30 04:30:33 +03:00
|
|
|
|
2024-09-06 14:52:42 +03:00
|
|
|
return errs
|
2024-08-30 04:30:33 +03:00
|
|
|
}
|