2021-08-23 16:13:20 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
2022-04-19 14:28:57 +00:00
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
|
2022-01-06 06:40:23 -05:00
|
|
|
"github.com/qdm12/gluetun/internal/configuration/settings"
|
2022-04-19 14:28:57 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/constants"
|
2022-04-18 09:15:20 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/constants/vpn"
|
2021-08-23 16:13:20 +00:00
|
|
|
)
|
|
|
|
|
|
2022-01-06 06:40:23 -05:00
|
|
|
func GetPort(selection settings.ServerSelection,
|
2021-08-23 16:13:20 +00:00
|
|
|
defaultOpenVPNTCP, defaultOpenVPNUDP, defaultWireguard uint16) (port uint16) {
|
|
|
|
|
switch selection.VPN {
|
2022-04-18 09:15:20 +00:00
|
|
|
case vpn.Wireguard:
|
2022-01-06 06:40:23 -05:00
|
|
|
customPort := *selection.Wireguard.EndpointPort
|
2021-08-23 16:13:20 +00:00
|
|
|
if customPort > 0 {
|
|
|
|
|
return customPort
|
|
|
|
|
}
|
2022-04-19 14:28:57 +00:00
|
|
|
checkDefined("Wireguard", defaultWireguard)
|
2021-08-23 16:13:20 +00:00
|
|
|
return defaultWireguard
|
|
|
|
|
default: // OpenVPN
|
2022-01-06 06:40:23 -05:00
|
|
|
customPort := *selection.OpenVPN.CustomPort
|
2021-08-23 16:13:20 +00:00
|
|
|
if customPort > 0 {
|
|
|
|
|
return customPort
|
|
|
|
|
}
|
2022-01-06 06:40:23 -05:00
|
|
|
if *selection.OpenVPN.TCP {
|
2022-04-19 14:28:57 +00:00
|
|
|
checkDefined("OpenVPN TCP", defaultOpenVPNTCP)
|
2021-08-23 16:13:20 +00:00
|
|
|
return defaultOpenVPNTCP
|
|
|
|
|
}
|
2022-04-19 14:28:57 +00:00
|
|
|
|
|
|
|
|
checkDefined("OpenVPN UDP", defaultOpenVPNUDP)
|
2021-08-23 16:13:20 +00:00
|
|
|
return defaultOpenVPNUDP
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-04-19 14:28:57 +00:00
|
|
|
|
|
|
|
|
func checkDefined(portName string, port uint16) {
|
|
|
|
|
if port > 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
message := fmt.Sprintf("no default %s port is defined!", portName)
|
|
|
|
|
panic(message)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var ErrInvalidPort = errors.New("invalid port number")
|
|
|
|
|
|
|
|
|
|
// CheckPortAllowed for custom port used for OpenVPN.
|
|
|
|
|
func CheckPortAllowed(port uint16, tcp bool,
|
|
|
|
|
allowedTCP, allowedUDP []uint16) (err error) {
|
|
|
|
|
allowedPorts := allowedUDP
|
|
|
|
|
protocol := constants.UDP
|
|
|
|
|
if tcp {
|
|
|
|
|
allowedPorts = allowedTCP
|
|
|
|
|
protocol = constants.TCP
|
|
|
|
|
}
|
|
|
|
|
for _, allowedPort := range allowedPorts {
|
|
|
|
|
if port == allowedPort {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return fmt.Errorf("%w: %d for protocol %s",
|
|
|
|
|
ErrInvalidPort, port, protocol)
|
|
|
|
|
}
|