Code maintenance: rework ovpn host extraction

This commit is contained in:
Quentin McGaw
2020-12-31 20:35:49 +00:00
parent 8c769812ae
commit a56471fe73
4 changed files with 65 additions and 64 deletions

View File

@@ -1,26 +1,50 @@
package updater
import (
"errors"
"fmt"
"net"
"strings"
)
func extractRemoteLinesFromOpenvpn(content []byte) (remoteLines []string) {
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "remote ") {
remoteLines = append(remoteLines, line)
}
var (
errRemoteHostNotFound = errors.New("remote host not found")
)
func extractHostFromOVPN(b []byte) (host, warning string, err error) {
const (
rejectIP = true
rejectDomain = false
)
hosts := extractRemoteHostsFromOpenvpn(b, rejectIP, rejectDomain)
if len(hosts) == 0 {
return "", "", errRemoteHostNotFound
} else if len(hosts) > 1 {
warning = fmt.Sprintf(
"only using the first host %q and discarding %d other hosts",
hosts[0], len(hosts)-1)
}
return remoteLines
return hosts[0], warning, nil
}
func extractHostnamesFromRemoteLines(remoteLines []string) (hostnames []string) {
for _, remoteLine := range remoteLines {
fields := strings.Fields(remoteLine)
if len(fields[1]) == 0 {
func extractRemoteHostsFromOpenvpn(content []byte,
rejectIP, rejectDomain bool) (hosts []string) {
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if !strings.HasPrefix(line, "remote ") {
continue
}
hostnames = append(hostnames, fields[1])
fields := strings.Fields(line)
if len(fields) == 1 || len(fields[1]) == 0 {
continue
}
host := fields[1]
parsedIP := net.ParseIP(host)
if (rejectIP && parsedIP != nil) ||
(rejectDomain && parsedIP == nil) {
continue
}
hosts = append(hosts, host)
}
return hostnames
return hosts
}