Maintenance: remove some type aliases

This commit is contained in:
Quentin McGaw
2021-02-06 18:31:14 +00:00
parent 43e140e6cc
commit b1f1f94a76
32 changed files with 88 additions and 229 deletions

View File

@@ -316,7 +316,7 @@ func _main(ctx context.Context, buildInfo models.BuildInformation,
if allSettings.OpenVPN.Provider.PortForwarding.Enabled { if allSettings.OpenVPN.Provider.PortForwarding.Enabled {
logger.Info("Clearing forwarded port status file %s", allSettings.OpenVPN.Provider.PortForwarding.Filepath) logger.Info("Clearing forwarded port status file %s", allSettings.OpenVPN.Provider.PortForwarding.Filepath)
if err := os.Remove(string(allSettings.OpenVPN.Provider.PortForwarding.Filepath)); err != nil { if err := os.Remove(allSettings.OpenVPN.Provider.PortForwarding.Filepath); err != nil {
logger.Error(err) logger.Error(err)
} }
} }

View File

@@ -12,7 +12,7 @@ import (
func (c *cli) ClientKey(args []string, openFile os.OpenFileFunc) error { func (c *cli) ClientKey(args []string, openFile os.OpenFileFunc) error {
flagSet := flag.NewFlagSet("clientkey", flag.ExitOnError) flagSet := flag.NewFlagSet("clientkey", flag.ExitOnError)
filepath := flagSet.String("path", string(constants.ClientKey), "file path to the client.key file") filepath := flagSet.String("path", constants.ClientKey, "file path to the client.key file")
if err := flagSet.Parse(args); err != nil { if err := flagSet.Parse(args); err != nil {
return err return err
} }

View File

@@ -65,7 +65,7 @@ func (settings *Provider) readCyberghost(r reader) (err error) {
} }
func readCyberghostClientKey(r reader) (clientKey string, err error) { func readCyberghostClientKey(r reader) (clientKey string, err error) {
b, err := r.getFromFileOrSecretFile("OPENVPN_CLIENTKEY", string(constants.ClientKey)) b, err := r.getFromFileOrSecretFile("OPENVPN_CLIENTKEY", constants.ClientKey)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -86,7 +86,7 @@ func extractClientKey(b []byte) (key string, err error) {
} }
func readCyberghostClientCertificate(r reader) (clientCertificate string, err error) { func readCyberghostClientCertificate(r reader) (clientCertificate string, err error) {
b, err := r.getFromFileOrSecretFile("OPENVPN_CLIENTCRT", string(constants.ClientCertificate)) b, err := r.getFromFileOrSecretFile("OPENVPN_CLIENTCRT", constants.ClientCertificate)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -7,7 +7,6 @@ import (
"strings" "strings"
"github.com/qdm12/gluetun/internal/constants" "github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/golibs/params" "github.com/qdm12/golibs/params"
) )
@@ -67,7 +66,7 @@ func (settings *OpenVPN) read(r reader) (err error) {
vpnsp = "private internet access" vpnsp = "private internet access"
} }
settings.Provider.Name = models.VPNProvider(vpnsp) settings.Provider.Name = vpnsp
settings.User, err = r.getFromEnvOrSecretFile("OPENVPN_USER", true, []string{"USER"}) settings.User, err = r.getFromEnvOrSecretFile("OPENVPN_USER", true, []string{"USER"})
if err != nil { if err != nil {

View File

@@ -4,7 +4,6 @@ import (
"strconv" "strconv"
"github.com/qdm12/gluetun/internal/constants" "github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/golibs/params" "github.com/qdm12/golibs/params"
) )
@@ -67,12 +66,11 @@ func (settings *Provider) readPrivateInternetAccess(r reader) (err error) {
} }
if settings.PortForwarding.Enabled { if settings.PortForwarding.Enabled {
filepathStr, err := r.env.Path("PORT_FORWARDING_STATUS_FILE", settings.PortForwarding.Filepath, err = r.env.Path("PORT_FORWARDING_STATUS_FILE",
params.Default("/tmp/gluetun/forwarded_port"), params.CaseSensitiveValue()) params.Default("/tmp/gluetun/forwarded_port"), params.CaseSensitiveValue())
if err != nil { if err != nil {
return err return err
} }
settings.PortForwarding.Filepath = models.Filepath(filepathStr)
} }
return nil return nil

View File

@@ -7,29 +7,28 @@ import (
"strings" "strings"
"github.com/qdm12/gluetun/internal/constants" "github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/golibs/params" "github.com/qdm12/golibs/params"
) )
// Provider contains settings specific to a VPN provider. // Provider contains settings specific to a VPN provider.
type Provider struct { type Provider struct {
Name models.VPNProvider `json:"name"` Name string `json:"name"`
ServerSelection ServerSelection `json:"server_selection"` ServerSelection ServerSelection `json:"server_selection"`
ExtraConfigOptions ExtraConfigOptions `json:"extra_config"` ExtraConfigOptions ExtraConfigOptions `json:"extra_config"`
PortForwarding PortForwarding `json:"port_forwarding"` PortForwarding PortForwarding `json:"port_forwarding"`
} }
func (settings *Provider) lines() (lines []string) { func (settings *Provider) lines() (lines []string) {
lines = append(lines, lastIndent+strings.Title(string(settings.Name))+" settings:") lines = append(lines, lastIndent+strings.Title(settings.Name)+" settings:")
lines = append(lines, indent+lastIndent+"Network protocol: "+string(settings.ServerSelection.Protocol)) lines = append(lines, indent+lastIndent+"Network protocol: "+settings.ServerSelection.Protocol)
if settings.ServerSelection.TargetIP != nil { if settings.ServerSelection.TargetIP != nil {
lines = append(lines, indent+lastIndent+"Target IP address: "+settings.ServerSelection.TargetIP.String()) lines = append(lines, indent+lastIndent+"Target IP address: "+settings.ServerSelection.TargetIP.String())
} }
var providerLines []string var providerLines []string
switch strings.ToLower(string(settings.Name)) { switch strings.ToLower(settings.Name) {
case "cyberghost": case "cyberghost":
providerLines = settings.cyberghostLines() providerLines = settings.cyberghostLines()
case "mullvad": case "mullvad":
@@ -64,14 +63,8 @@ func commaJoin(slice []string) string {
return strings.Join(slice, ", ") return strings.Join(slice, ", ")
} }
func readProtocol(env params.Env) (protocol models.NetworkProtocol, err error) { func readProtocol(env params.Env) (protocol string, err error) {
s, err := env.Inside("PROTOCOL", return env.Inside("PROTOCOL", []string{constants.TCP, constants.UDP}, params.Default(constants.UDP))
[]string{string(constants.TCP), string(constants.UDP)},
params.Default(string(constants.UDP)))
if err != nil {
return "", err
}
return models.NetworkProtocol(s), nil
} }
func readTargetIP(env params.Env) (targetIP net.IP, err error) { func readTargetIP(env params.Env) (targetIP net.IP, err error) {
@@ -82,7 +75,7 @@ var (
ErrInvalidProtocol = errors.New("invalid network protocol") ErrInvalidProtocol = errors.New("invalid network protocol")
) )
func readCustomPort(env params.Env, protocol models.NetworkProtocol, func readCustomPort(env params.Env, protocol string,
allowedTCP, allowedUDP []uint16) (port uint16, err error) { allowedTCP, allowedUDP []uint16) (port uint16, err error) {
port, err = readPortOrZero(env, "PORT") port, err = readPortOrZero(env, "PORT")
if err != nil { if err != nil {

View File

@@ -6,7 +6,6 @@ import (
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/qdm12/gluetun/internal/constants" "github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/golibs/params/mock_params" "github.com/qdm12/golibs/params/mock_params"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@@ -108,7 +107,7 @@ func Test_Provider_lines(t *testing.T) {
}, },
PortForwarding: PortForwarding{ PortForwarding: PortForwarding{
Enabled: true, Enabled: true,
Filepath: models.Filepath("/here"), Filepath: string("/here"),
}, },
}, },
lines: []string{ lines: []string{
@@ -207,7 +206,7 @@ func Test_readProtocol(t *testing.T) {
testCases := map[string]struct { testCases := map[string]struct {
mockStr string mockStr string
mockErr error mockErr error
protocol models.NetworkProtocol protocol string
err error err error
}{ }{
"error": { "error": {

View File

@@ -4,13 +4,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/golibs/params" "github.com/qdm12/golibs/params"
) )
type PublicIP struct { type PublicIP struct {
Period time.Duration `json:"period"` Period time.Duration `json:"period"`
IPFilepath models.Filepath `json:"ip_filepath"` IPFilepath string `json:"ip_filepath"`
} }
func (settings *PublicIP) String() string { func (settings *PublicIP) String() string {
@@ -25,7 +24,7 @@ func (settings *PublicIP) lines() (lines []string) {
lines = append(lines, lastIndent+"Public IP getter:") lines = append(lines, lastIndent+"Public IP getter:")
lines = append(lines, indent+lastIndent+"Fetch period: "+settings.Period.String()) lines = append(lines, indent+lastIndent+"Fetch period: "+settings.Period.String())
lines = append(lines, indent+lastIndent+"IP file: "+string(settings.IPFilepath)) lines = append(lines, indent+lastIndent+"IP file: "+settings.IPFilepath)
return lines return lines
} }
@@ -36,13 +35,12 @@ func (settings *PublicIP) read(r reader) (err error) {
return err return err
} }
filepathStr, err := r.env.Path("PUBLICIP_FILE", params.CaseSensitiveValue(), settings.IPFilepath, err = r.env.Path("PUBLICIP_FILE", params.CaseSensitiveValue(),
params.Default("/tmp/gluetun/ip"), params.Default("/tmp/gluetun/ip"),
params.RetroKeys([]string{"IP_STATUS_FILE"}, r.onRetroActive)) params.RetroKeys([]string{"IP_STATUS_FILE"}, r.onRetroActive))
if err != nil { if err != nil {
return err return err
} }
settings.IPFilepath = models.Filepath(filepathStr)
return nil return nil
} }

View File

@@ -2,14 +2,12 @@ package configuration
import ( import (
"net" "net"
"github.com/qdm12/gluetun/internal/models"
) )
type ServerSelection struct { type ServerSelection struct {
// Common // Common
Protocol models.NetworkProtocol `json:"network_protocol"` Protocol string `json:"network_protocol"`
TargetIP net.IP `json:"target_ip,omitempty"` TargetIP net.IP `json:"target_ip,omitempty"`
// Cyberghost, PIA, Surfshark, Windscribe, Vyprvpn, NordVPN // Cyberghost, PIA, Surfshark, Windscribe, Vyprvpn, NordVPN
Regions []string `json:"regions"` Regions []string `json:"regions"`
@@ -44,12 +42,12 @@ type ExtraConfigOptions struct {
// PortForwarding contains settings for port forwarding. // PortForwarding contains settings for port forwarding.
type PortForwarding struct { type PortForwarding struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
Filepath models.Filepath `json:"filepath"` Filepath string `json:"filepath"`
} }
func (p *PortForwarding) lines() (lines []string) { func (p *PortForwarding) lines() (lines []string) {
return []string{ return []string{
lastIndent + "File path: " + string(p.Filepath), lastIndent + "File path: " + p.Filepath,
} }
} }

View File

@@ -1,10 +1,6 @@
package constants package constants
import (
"github.com/qdm12/gluetun/internal/models"
)
const ( const (
TUN models.VPNDevice = "tun0" TUN = "tun0"
TAP models.VPNDevice = "tap0" TAP = "tap0"
) )

View File

@@ -1,34 +1,30 @@
package constants package constants
import (
"github.com/qdm12/gluetun/internal/models"
)
const ( const (
// UnboundConf is the file path to the Unbound configuration file. // UnboundConf is the file path to the Unbound configuration file.
UnboundConf models.Filepath = "/etc/unbound/unbound.conf" UnboundConf string = "/etc/unbound/unbound.conf"
// ResolvConf is the file path to the system resolv.conf file. // ResolvConf is the file path to the system resolv.conf file.
ResolvConf models.Filepath = "/etc/resolv.conf" ResolvConf string = "/etc/resolv.conf"
// CACertificates is the file path to the CA certificates file. // CACertificates is the file path to the CA certificates file.
CACertificates models.Filepath = "/etc/ssl/certs/ca-certificates.crt" CACertificates string = "/etc/ssl/certs/ca-certificates.crt"
// OpenVPNAuthConf is the file path to the OpenVPN auth file. // OpenVPNAuthConf is the file path to the OpenVPN auth file.
OpenVPNAuthConf models.Filepath = "/etc/openvpn/auth.conf" OpenVPNAuthConf string = "/etc/openvpn/auth.conf"
// OpenVPNConf is the file path to the OpenVPN client configuration file. // OpenVPNConf is the file path to the OpenVPN client configuration file.
OpenVPNConf models.Filepath = "/etc/openvpn/target.ovpn" OpenVPNConf string = "/etc/openvpn/target.ovpn"
// PIAPortForward is the file path to the port forwarding JSON information for PIA servers. // PIAPortForward is the file path to the port forwarding JSON information for PIA servers.
PIAPortForward models.Filepath = "/gluetun/piaportforward.json" PIAPortForward string = "/gluetun/piaportforward.json"
// TunnelDevice is the file path to tun device. // TunnelDevice is the file path to tun device.
TunnelDevice models.Filepath = "/dev/net/tun" TunnelDevice string = "/dev/net/tun"
// NetRoute is the path to the file containing information on the network route. // NetRoute is the path to the file containing information on the network route.
NetRoute models.Filepath = "/proc/net/route" NetRoute string = "/proc/net/route"
// RootHints is the filepath to the root.hints file used by Unbound. // RootHints is the filepath to the root.hints file used by Unbound.
RootHints models.Filepath = "/etc/unbound/root.hints" RootHints string = "/etc/unbound/root.hints"
// RootKey is the filepath to the root.key file used by Unbound. // RootKey is the filepath to the root.key file used by Unbound.
RootKey models.Filepath = "/etc/unbound/root.key" RootKey string = "/etc/unbound/root.key"
// Client key filepath, used by Cyberghost. // Client key filepath, used by Cyberghost.
ClientKey models.Filepath = "/gluetun/client.key" ClientKey string = "/gluetun/client.key"
// Client certificate filepath, used by Cyberghost. // Client certificate filepath, used by Cyberghost.
ClientCertificate models.Filepath = "/gluetun/client.crt" ClientCertificate string = "/gluetun/client.crt"
// Servers information filepath. // Servers information filepath.
ServersData = "/gluetun/servers.json" ServersData = "/gluetun/servers.json"
) )

View File

@@ -1,33 +1,29 @@
package constants package constants
import (
"github.com/qdm12/gluetun/internal/models"
)
const ( const (
// PrivateInternetAccess is a VPN provider. // PrivateInternetAccess is a VPN provider.
PrivateInternetAccess models.VPNProvider = "private internet access" PrivateInternetAccess = "private internet access"
// Mullvad is a VPN provider. // Mullvad is a VPN provider.
Mullvad models.VPNProvider = "mullvad" Mullvad = "mullvad"
// Windscribe is a VPN provider. // Windscribe is a VPN provider.
Windscribe models.VPNProvider = "windscribe" Windscribe = "windscribe"
// Surfshark is a VPN provider. // Surfshark is a VPN provider.
Surfshark models.VPNProvider = "surfshark" Surfshark = "surfshark"
// Cyberghost is a VPN provider. // Cyberghost is a VPN provider.
Cyberghost models.VPNProvider = "cyberghost" Cyberghost = "cyberghost"
// Vyprvpn is a VPN provider. // Vyprvpn is a VPN provider.
Vyprvpn models.VPNProvider = "vyprvpn" Vyprvpn = "vyprvpn"
// NordVPN is a VPN provider. // NordVPN is a VPN provider.
Nordvpn models.VPNProvider = "nordvpn" Nordvpn = "nordvpn"
// PureVPN is a VPN provider. // PureVPN is a VPN provider.
Purevpn models.VPNProvider = "purevpn" Purevpn = "purevpn"
// Privado is a VPN provider. // Privado is a VPN provider.
Privado models.VPNProvider = "privado" Privado = "privado"
) )
const ( const (
// TCP is a network protocol (reliable and slower than UDP). // TCP is a network protocol (reliable and slower than UDP).
TCP models.NetworkProtocol = "tcp" TCP string = "tcp"
// UDP is a network protocol (unreliable and faster than TCP). // UDP is a network protocol (unreliable and faster than TCP).
UDP models.NetworkProtocol = "udp" UDP string = "udp"
) )

View File

@@ -1,23 +1,6 @@
package models package models
import (
"fmt"
"strings"
)
type ( type (
// VPNDevice is the device name used to tunnel using Openvpn.
VPNDevice string
// DNSHost is the DNS host to use for TLS validation.
DNSHost string
// URL is an HTTP(s) URL address.
URL string
// Filepath is a local filesytem file path.
Filepath string
// VPNProvider is the name of the VPN provider to be used.
VPNProvider string
// NetworkProtocol contains the network protocol to be used to communicate with the VPN servers.
NetworkProtocol string
// LoopStatus status such as stopped or running. // LoopStatus status such as stopped or running.
LoopStatus string LoopStatus string
) )
@@ -25,41 +8,3 @@ type (
func (ls LoopStatus) String() string { func (ls LoopStatus) String() string {
return string(ls) return string(ls)
} }
func marshalJSONString(s string) (data []byte, err error) {
return []byte(fmt.Sprintf("%q", s)), nil
}
func unmarshalJSONString(data []byte) (s string) {
s = string(data)
s = strings.TrimPrefix(s, "\"")
s = strings.TrimSuffix(s, "\"")
return s
}
func (v *VPNProvider) MarshalJSON() ([]byte, error) {
return marshalJSONString(string(*v))
}
func (v *VPNProvider) UnmarshalJSON(data []byte) error {
*v = VPNProvider(unmarshalJSONString(data))
return nil
}
func (n *NetworkProtocol) MarshalJSON() ([]byte, error) {
return marshalJSONString(string(*n))
}
func (n *NetworkProtocol) UnmarshalJSON(data []byte) error {
*n = NetworkProtocol(unmarshalJSONString(data))
return nil
}
func (f *Filepath) MarshalJSON() ([]byte, error) {
return marshalJSONString(string(*f))
}
func (f *Filepath) UnmarshalJSON(data []byte) error {
*f = Filepath(unmarshalJSONString(data))
return nil
}

View File

@@ -1,41 +0,0 @@
package models
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_VPNProvider_JSON(t *testing.T) {
t.Parallel()
v := VPNProvider("name")
data, err := v.MarshalJSON()
require.NoError(t, err)
assert.Equal(t, []byte{0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22}, data)
err = v.UnmarshalJSON(data)
require.NoError(t, err)
assert.Equal(t, VPNProvider("name"), v)
}
func Test_NetworkProtocol_JSON(t *testing.T) {
t.Parallel()
v := NetworkProtocol("name")
data, err := v.MarshalJSON()
require.NoError(t, err)
assert.Equal(t, []byte{0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22}, data)
err = v.UnmarshalJSON(data)
require.NoError(t, err)
assert.Equal(t, NetworkProtocol("name"), v)
}
func Test_Filepath_JSON(t *testing.T) {
t.Parallel()
v := Filepath("name")
data, err := v.MarshalJSON()
require.NoError(t, err)
assert.Equal(t, []byte{0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22}, data)
err = v.UnmarshalJSON(data)
require.NoError(t, err)
assert.Equal(t, Filepath("name"), v)
}

View File

@@ -1,12 +0,0 @@
package models
import "net"
// DNSProviderData contains information for a DNS provider.
type DNSProviderData struct {
IPs []net.IP
SupportsTLS bool
SupportsIPv6 bool
SupportsDNSSec bool
Host DNSHost
}

View File

@@ -5,10 +5,10 @@ import (
) )
type OpenVPNConnection struct { type OpenVPNConnection struct {
IP net.IP `json:"ip"` IP net.IP `json:"ip"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Protocol NetworkProtocol `json:"protocol"` Protocol string `json:"protocol"`
Hostname string `json:"hostname"` // Privado for tls verification Hostname string `json:"hostname"` // Privado for tls verification
} }
func (o *OpenVPNConnection) Equal(other OpenVPNConnection) bool { func (o *OpenVPNConnection) Equal(other OpenVPNConnection) bool {

View File

@@ -8,11 +8,11 @@ import (
) )
type PIAServer struct { type PIAServer struct {
Region string `json:"region"` Region string `json:"region"`
ServerName string `json:"server_name"` ServerName string `json:"server_name"`
Protocol NetworkProtocol `json:"protocol"` Protocol string `json:"protocol"`
PortForward bool `json:"port_forward"` PortForward bool `json:"port_forward"`
IP net.IP `json:"ip"` IP net.IP `json:"ip"`
} }
func (p *PIAServer) String() string { func (p *PIAServer) String() string {

View File

@@ -10,15 +10,14 @@ import (
// WriteAuthFile writes the OpenVPN auth file to disk with the right permissions. // WriteAuthFile writes the OpenVPN auth file to disk with the right permissions.
func (c *configurator) WriteAuthFile(user, password string, puid, pgid int) error { func (c *configurator) WriteAuthFile(user, password string, puid, pgid int) error {
const filepath = string(constants.OpenVPNAuthConf) file, err := c.os.OpenFile(constants.OpenVPNAuthConf, os.O_RDONLY, 0)
file, err := c.os.OpenFile(filepath, os.O_RDONLY, 0)
if err != nil && !os.IsNotExist(err) { if err != nil && !os.IsNotExist(err) {
return err return err
} }
if os.IsNotExist(err) { if os.IsNotExist(err) {
file, err = c.os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0400) file, err = c.os.OpenFile(constants.OpenVPNAuthConf, os.O_WRONLY|os.O_CREATE, 0400)
if err != nil { if err != nil {
return err return err
} }
@@ -50,7 +49,7 @@ func (c *configurator) WriteAuthFile(user, password string, puid, pgid int) erro
} }
c.logger.Info("username and password changed in %s", constants.OpenVPNAuthConf) c.logger.Info("username and password changed in %s", constants.OpenVPNAuthConf)
file, err = c.os.OpenFile(filepath, os.O_TRUNC|os.O_WRONLY, 0400) file, err = c.os.OpenFile(constants.OpenVPNAuthConf, os.O_TRUNC|os.O_WRONLY, 0400)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -11,7 +11,7 @@ import (
func (c *configurator) Start(ctx context.Context) ( func (c *configurator) Start(ctx context.Context) (
stdoutLines, stderrLines chan string, waitError chan error, err error) { stdoutLines, stderrLines chan string, waitError chan error, err error) {
c.logger.Info("starting openvpn") c.logger.Info("starting openvpn")
return c.commander.Start(ctx, "openvpn", "--config", string(constants.OpenVPNConf)) return c.commander.Start(ctx, "openvpn", "--config", constants.OpenVPNConf)
} }
func (c *configurator) Version(ctx context.Context) (string, error) { func (c *configurator) Version(ctx context.Context) (string, error) {

View File

@@ -237,7 +237,7 @@ func (l *looper) portForward(ctx context.Context, wg *sync.WaitGroup,
if !settings.Provider.PortForwarding.Enabled { if !settings.Provider.PortForwarding.Enabled {
return return
} }
syncState := func(port uint16) (pfFilepath models.Filepath) { syncState := func(port uint16) (pfFilepath string) {
l.state.portForwardedMu.Lock() l.state.portForwardedMu.Lock()
defer l.state.portForwardedMu.Unlock() defer l.state.portForwardedMu.Unlock()
l.state.portForwarded = port l.state.portForwarded = port
@@ -251,8 +251,7 @@ func (l *looper) portForward(ctx context.Context, wg *sync.WaitGroup,
} }
func writeOpenvpnConf(lines []string, openFile os.OpenFileFunc) error { func writeOpenvpnConf(lines []string, openFile os.OpenFileFunc) error {
const filepath = string(constants.OpenVPNConf) file, err := openFile(constants.OpenVPNConf, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
file, err := openFile(filepath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -11,7 +11,7 @@ import (
// CheckTUN checks the tunnel device is present and accessible. // CheckTUN checks the tunnel device is present and accessible.
func (c *configurator) CheckTUN() error { func (c *configurator) CheckTUN() error {
c.logger.Info("checking for device %s", constants.TunnelDevice) c.logger.Info("checking for device %s", constants.TunnelDevice)
f, err := c.os.OpenFile(string(constants.TunnelDevice), os.O_RDWR, 0) f, err := c.os.OpenFile(constants.TunnelDevice, os.O_RDWR, 0)
if err != nil { if err != nil {
return fmt.Errorf("TUN device is not available: %w", err) return fmt.Errorf("TUN device is not available: %w", err)
} }
@@ -32,12 +32,11 @@ func (c *configurator) CreateTUN() error {
minor = 200 minor = 200
) )
dev := c.unix.Mkdev(major, minor) dev := c.unix.Mkdev(major, minor)
if err := c.unix.Mknod(string(constants.TunnelDevice), unix.S_IFCHR, int(dev)); err != nil { if err := c.unix.Mknod(constants.TunnelDevice, unix.S_IFCHR, int(dev)); err != nil {
return err return err
} }
const filepath = string(constants.TunnelDevice) file, err := c.os.OpenFile(constants.TunnelDevice, os.O_WRONLY, 0666)
file, err := c.os.OpenFile(filepath, os.O_WRONLY, 0666)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -143,6 +143,6 @@ func (c *cyberghost) BuildConf(connection models.OpenVPNConnection,
func (c *cyberghost) PortForward(ctx context.Context, client *http.Client, func (c *cyberghost) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for cyberghost") panic("port forwarding is not supported for cyberghost")
} }

View File

@@ -137,6 +137,6 @@ func (m *mullvad) BuildConf(connection models.OpenVPNConnection,
func (m *mullvad) PortForward(ctx context.Context, client *http.Client, func (m *mullvad) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for mullvad") panic("port forwarding is not supported for mullvad")
} }

View File

@@ -28,7 +28,7 @@ func newNordvpn(servers []models.NordvpnServer, timeNow timeNowFunc) *nordvpn {
} }
} }
func (n *nordvpn) filterServers(regions []string, protocol models.NetworkProtocol, numbers []uint16) ( func (n *nordvpn) filterServers(regions []string, protocol string, numbers []uint16) (
servers []models.NordvpnServer) { servers []models.NordvpnServer) {
numbersStr := make([]string, len(numbers)) numbersStr := make([]string, len(numbers))
for i := range numbers { for i := range numbers {
@@ -151,6 +151,6 @@ func (n *nordvpn) BuildConf(connection models.OpenVPNConnection,
func (n *nordvpn) PortForward(ctx context.Context, client *http.Client, func (n *nordvpn) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for nordvpn") panic("port forwarding is not supported for nordvpn")
} }

View File

@@ -212,7 +212,7 @@ func (p *pia) BuildConf(connection models.OpenVPNConnection,
//nolint:gocognit //nolint:gocognit
func (p *pia) PortForward(ctx context.Context, client *http.Client, func (p *pia) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
commonName := p.activeServer.ServerName commonName := p.activeServer.ServerName
if !p.activeServer.PortForward { if !p.activeServer.PortForward {
pfLogger.Error("The server %s (region %s) does not support port forwarding", pfLogger.Error("The server %s (region %s) does not support port forwarding",
@@ -267,7 +267,7 @@ func (p *pia) PortForward(ctx context.Context, client *http.Client,
return return
} }
filepath := string(syncState(data.Port)) filepath := syncState(data.Port)
pfLogger.Info("Writing port to %s", filepath) pfLogger.Info("Writing port to %s", filepath)
if err := writePortForwardedToFile(openFile, filepath, data.Port); err != nil { if err := writePortForwardedToFile(openFile, filepath, data.Port); err != nil {
pfLogger.Error(err) pfLogger.Error(err)
@@ -322,7 +322,7 @@ func (p *pia) PortForward(ctx context.Context, client *http.Client,
} }
filepath := syncState(data.Port) filepath := syncState(data.Port)
pfLogger.Info("Writing port to %s", filepath) pfLogger.Info("Writing port to %s", filepath)
if err := writePortForwardedToFile(openFile, string(filepath), data.Port); err != nil { if err := writePortForwardedToFile(openFile, filepath, data.Port); err != nil {
pfLogger.Error(err) pfLogger.Error(err)
} }
if err := bindPIAPort(ctx, client, gateway, data); err != nil { if err := bindPIAPort(ctx, client, gateway, data); err != nil {
@@ -337,7 +337,7 @@ func (p *pia) PortForward(ctx context.Context, client *http.Client,
} }
} }
func filterPIAServers(servers []models.PIAServer, regions []string, protocol models.NetworkProtocol) ( func filterPIAServers(servers []models.PIAServer, regions []string, protocol string) (
filtered []models.PIAServer) { filtered []models.PIAServer) {
for _, server := range servers { for _, server := range servers {
switch { switch {
@@ -417,8 +417,7 @@ type piaPortForwardData struct {
} }
func readPIAPortForwardData(openFile os.OpenFileFunc) (data piaPortForwardData, err error) { func readPIAPortForwardData(openFile os.OpenFileFunc) (data piaPortForwardData, err error) {
const filepath = string(constants.PIAPortForward) file, err := openFile(constants.PIAPortForward, os.O_RDONLY, 0)
file, err := openFile(filepath, os.O_RDONLY, 0)
if os.IsNotExist(err) { if os.IsNotExist(err) {
return data, nil return data, nil
} else if err != nil { } else if err != nil {
@@ -435,8 +434,7 @@ func readPIAPortForwardData(openFile os.OpenFileFunc) (data piaPortForwardData,
} }
func writePIAPortForwardData(openFile os.OpenFileFunc, data piaPortForwardData) (err error) { func writePIAPortForwardData(openFile os.OpenFileFunc, data piaPortForwardData) (err error) {
const filepath = string(constants.PIAPortForward) file, err := openFile(constants.PIAPortForward,
file, err := openFile(filepath,
os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.O_CREATE|os.O_TRUNC|os.O_WRONLY,
0644) 0644)
if err != nil { if err != nil {
@@ -518,8 +516,7 @@ func fetchPIAToken(ctx context.Context, openFile os.OpenFileFunc,
} }
func getOpenvpnCredentials(openFile os.OpenFileFunc) (username, password string, err error) { func getOpenvpnCredentials(openFile os.OpenFileFunc) (username, password string, err error) {
const filepath = string(constants.OpenVPNAuthConf) file, err := openFile(constants.OpenVPNAuthConf, os.O_RDONLY, 0)
file, err := openFile(filepath, os.O_RDONLY, 0)
if err != nil { if err != nil {
return "", "", fmt.Errorf("cannot read openvpn auth file: %s", err) return "", "", fmt.Errorf("cannot read openvpn auth file: %s", err)
} }

View File

@@ -128,6 +128,6 @@ func (s *privado) BuildConf(connection models.OpenVPNConnection,
func (s *privado) PortForward(ctx context.Context, client *http.Client, func (s *privado) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for privado") panic("port forwarding is not supported for privado")
} }

View File

@@ -20,10 +20,10 @@ type Provider interface {
BuildConf(connection models.OpenVPNConnection, username string, settings configuration.OpenVPN) (lines []string) BuildConf(connection models.OpenVPNConnection, username string, settings configuration.OpenVPN) (lines []string)
PortForward(ctx context.Context, client *http.Client, PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) syncState func(port uint16) (pfFilepath string))
} }
func New(provider models.VPNProvider, allServers models.AllServers, timeNow timeNowFunc) Provider { func New(provider string, allServers models.AllServers, timeNow timeNowFunc) Provider {
switch provider { switch provider {
case constants.PrivateInternetAccess: case constants.PrivateInternetAccess:
return newPrivateInternetAccess(allServers.Pia.Servers, timeNow) return newPrivateInternetAccess(allServers.Pia.Servers, timeNow)

View File

@@ -160,6 +160,6 @@ func (p *purevpn) BuildConf(connection models.OpenVPNConnection,
func (p *purevpn) PortForward(ctx context.Context, client *http.Client, func (p *purevpn) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for purevpn") panic("port forwarding is not supported for purevpn")
} }

View File

@@ -149,6 +149,6 @@ func (s *surfshark) BuildConf(connection models.OpenVPNConnection,
func (s *surfshark) PortForward(ctx context.Context, client *http.Client, func (s *surfshark) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for surfshark") panic("port forwarding is not supported for surfshark")
} }

View File

@@ -129,6 +129,6 @@ func (v *vyprvpn) BuildConf(connection models.OpenVPNConnection,
func (v *vyprvpn) PortForward(ctx context.Context, client *http.Client, func (v *vyprvpn) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for vyprvpn") panic("port forwarding is not supported for vyprvpn")
} }

View File

@@ -143,6 +143,6 @@ func (w *windscribe) BuildConf(connection models.OpenVPNConnection,
func (w *windscribe) PortForward(ctx context.Context, client *http.Client, func (w *windscribe) PortForward(ctx context.Context, client *http.Client,
openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator, openFile os.OpenFileFunc, pfLogger logging.Logger, gateway net.IP, fw firewall.Configurator,
syncState func(port uint16) (pfFilepath models.Filepath)) { syncState func(port uint16) (pfFilepath string)) {
panic("port forwarding is not supported for windscribe") panic("port forwarding is not supported for windscribe")
} }

View File

@@ -135,7 +135,7 @@ func (l *looper) Run(ctx context.Context, wg *sync.WaitGroup) {
close(errorCh) close(errorCh)
filepath := l.GetSettings().IPFilepath filepath := l.GetSettings().IPFilepath
l.logger.Info("Removing ip file %s", filepath) l.logger.Info("Removing ip file %s", filepath)
if err := l.os.Remove(string(filepath)); err != nil { if err := l.os.Remove(filepath); err != nil {
l.logger.Error(err) l.logger.Error(err)
} }
return return
@@ -151,8 +151,8 @@ func (l *looper) Run(ctx context.Context, wg *sync.WaitGroup) {
getCancel() getCancel()
l.state.setPublicIP(ip) l.state.setPublicIP(ip)
l.logger.Info("Public IP address is %s", ip) l.logger.Info("Public IP address is %s", ip)
filepath := string(l.state.settings.IPFilepath) err := persistPublicIP(l.os.OpenFile, l.state.settings.IPFilepath,
err := persistPublicIP(l.os.OpenFile, filepath, ip.String(), l.puid, l.pgid) ip.String(), l.puid, l.pgid)
if err != nil { if err != nil {
l.logger.Error(err) l.logger.Error(err)
} }