2023-12-08 10:48:21 +01:00
|
|
|
package iptables
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
import "encoding/json"
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
type ipList struct {
|
|
|
|
ips map[string]struct{}
|
|
|
|
}
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
func newIpList(ip string) *ipList {
|
2023-12-08 10:48:21 +01:00
|
|
|
ips := make(map[string]struct{})
|
|
|
|
ips[ip] = struct{}{}
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
return &ipList{
|
2023-12-08 10:48:21 +01:00
|
|
|
ips: ips,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *ipList) addIP(ip string) {
|
|
|
|
s.ips[ip] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
// MarshalJSON implements json.Marshaler
|
|
|
|
func (s *ipList) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(struct {
|
|
|
|
IPs map[string]struct{} `json:"ips"`
|
|
|
|
}{
|
|
|
|
IPs: s.ips,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalJSON implements json.Unmarshaler
|
|
|
|
func (s *ipList) UnmarshalJSON(data []byte) error {
|
|
|
|
temp := struct {
|
|
|
|
IPs map[string]struct{} `json:"ips"`
|
|
|
|
}{}
|
|
|
|
if err := json.Unmarshal(data, &temp); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
s.ips = temp.IPs
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
type ipsetStore struct {
|
2024-10-24 14:46:24 +02:00
|
|
|
ipsets map[string]*ipList
|
2023-12-08 10:48:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func newIpsetStore() *ipsetStore {
|
|
|
|
return &ipsetStore{
|
2024-10-24 14:46:24 +02:00
|
|
|
ipsets: make(map[string]*ipList),
|
2023-12-08 10:48:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
func (s *ipsetStore) ipset(ipsetName string) (*ipList, bool) {
|
2023-12-08 10:48:21 +01:00
|
|
|
r, ok := s.ipsets[ipsetName]
|
|
|
|
return r, ok
|
|
|
|
}
|
|
|
|
|
2024-10-24 14:46:24 +02:00
|
|
|
func (s *ipsetStore) addIpList(ipsetName string, list *ipList) {
|
2023-12-08 10:48:21 +01:00
|
|
|
s.ipsets[ipsetName] = list
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *ipsetStore) deleteIpset(ipsetName string) {
|
|
|
|
delete(s.ipsets, ipsetName)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *ipsetStore) ipsetNames() []string {
|
|
|
|
names := make([]string, 0, len(s.ipsets))
|
|
|
|
for name := range s.ipsets {
|
|
|
|
names = append(names, name)
|
|
|
|
}
|
|
|
|
return names
|
|
|
|
}
|
2024-10-24 14:46:24 +02:00
|
|
|
|
|
|
|
// MarshalJSON implements json.Marshaler
|
|
|
|
func (s *ipsetStore) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(struct {
|
|
|
|
IPSets map[string]*ipList `json:"ipsets"`
|
|
|
|
}{
|
|
|
|
IPSets: s.ipsets,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalJSON implements json.Unmarshaler
|
|
|
|
func (s *ipsetStore) UnmarshalJSON(data []byte) error {
|
|
|
|
temp := struct {
|
|
|
|
IPSets map[string]*ipList `json:"ipsets"`
|
|
|
|
}{}
|
|
|
|
if err := json.Unmarshal(data, &temp); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
s.ipsets = temp.IPSets
|
|
|
|
return nil
|
|
|
|
}
|