2020-07-11 21:03:55 +00:00
|
|
|
package firewall
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
|
2020-07-26 12:07:06 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
2020-07-11 21:03:55 +00:00
|
|
|
)
|
|
|
|
|
|
2021-07-23 19:12:16 +00:00
|
|
|
type VPNConnectionSetter interface {
|
2021-08-19 14:09:41 +00:00
|
|
|
SetVPNConnection(ctx context.Context, connection models.Connection) error
|
2021-07-23 19:12:16 +00:00
|
|
|
}
|
|
|
|
|
|
2021-08-19 14:09:41 +00:00
|
|
|
func (c *Config) SetVPNConnection(ctx context.Context, connection models.Connection) (err error) {
|
2020-07-11 21:03:55 +00:00
|
|
|
c.stateMutex.Lock()
|
|
|
|
|
defer c.stateMutex.Unlock()
|
|
|
|
|
|
|
|
|
|
if !c.enabled {
|
2020-10-12 15:29:58 -04:00
|
|
|
c.logger.Info("firewall disabled, only updating internal VPN connection")
|
|
|
|
|
c.vpnConnection = connection
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
c.logger.Info("setting VPN connection through firewall...")
|
2020-07-11 21:03:55 +00:00
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
if c.vpnConnection.Equal(connection) {
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
remove := true
|
|
|
|
|
if c.vpnConnection.IP != nil {
|
|
|
|
|
if err := c.acceptOutputTrafficToVPN(ctx, c.defaultInterface, c.vpnConnection, remove); err != nil {
|
2021-07-23 17:36:08 +00:00
|
|
|
c.logger.Error("cannot remove outdated VPN connection through firewall: " + err.Error())
|
2020-07-11 21:03:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
2021-08-19 14:09:41 +00:00
|
|
|
c.vpnConnection = models.Connection{}
|
2020-10-12 15:29:58 -04:00
|
|
|
remove = false
|
|
|
|
|
if err := c.acceptOutputTrafficToVPN(ctx, c.defaultInterface, connection, remove); err != nil {
|
|
|
|
|
return fmt.Errorf("cannot set VPN connection through firewall: %w", err)
|
2020-07-11 21:03:55 +00:00
|
|
|
}
|
2020-10-12 15:29:58 -04:00
|
|
|
c.vpnConnection = connection
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|