mirror of
https://github.com/qdm12/gluetun.git
synced 2025-12-10 20:07:32 -06:00
63 lines
1.9 KiB
Go
63 lines
1.9 KiB
Go
package firewall
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
|
|
"github.com/qdm12/gluetun/internal/subnet"
|
|
)
|
|
|
|
type OutboundSubnetsSetter interface {
|
|
SetOutboundSubnets(ctx context.Context, subnets []net.IPNet) (err error)
|
|
}
|
|
|
|
func (c *Config) SetOutboundSubnets(ctx context.Context, subnets []net.IPNet) (err error) {
|
|
c.stateMutex.Lock()
|
|
defer c.stateMutex.Unlock()
|
|
|
|
if !c.enabled {
|
|
c.logger.Info("firewall disabled, only updating allowed subnets internal list")
|
|
c.outboundSubnets = make([]net.IPNet, len(subnets))
|
|
copy(c.outboundSubnets, subnets)
|
|
return nil
|
|
}
|
|
|
|
c.logger.Info("setting allowed subnets through firewall...")
|
|
|
|
subnetsToAdd := subnet.FindSubnetsToAdd(c.outboundSubnets, subnets)
|
|
subnetsToRemove := subnet.FindSubnetsToRemove(c.outboundSubnets, subnets)
|
|
if len(subnetsToAdd) == 0 && len(subnetsToRemove) == 0 {
|
|
return nil
|
|
}
|
|
|
|
c.removeOutboundSubnets(ctx, subnetsToRemove)
|
|
if err := c.addOutboundSubnets(ctx, subnetsToAdd); err != nil {
|
|
return fmt.Errorf("cannot set allowed subnets through firewall: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *Config) removeOutboundSubnets(ctx context.Context, subnets []net.IPNet) {
|
|
const remove = true
|
|
for _, subNet := range subnets {
|
|
if err := c.acceptOutputFromIPToSubnet(ctx, c.defaultInterface, c.localIP, subNet, remove); err != nil {
|
|
c.logger.Error("cannot remove outdated outbound subnet through firewall: " + err.Error())
|
|
continue
|
|
}
|
|
c.outboundSubnets = subnet.RemoveSubnetFromSubnets(c.outboundSubnets, subNet)
|
|
}
|
|
}
|
|
|
|
func (c *Config) addOutboundSubnets(ctx context.Context, subnets []net.IPNet) error {
|
|
const remove = false
|
|
for _, subnet := range subnets {
|
|
if err := c.acceptOutputFromIPToSubnet(ctx, c.defaultInterface, c.localIP, subnet, remove); err != nil {
|
|
return fmt.Errorf("cannot add allowed subnet through firewall: %w", err)
|
|
}
|
|
c.outboundSubnets = append(c.outboundSubnets, subnet)
|
|
}
|
|
return nil
|
|
}
|