tu-wien
/
kerma
Archived
2
0
Fork 0
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
kerma/helpers/validator.go

84 lines
2.1 KiB
Go

// Package helpers provides useful helper structures for KermaGo
package helpers
import (
"net"
"os"
"regexp"
"strconv"
"strings"
)
/*
A Validator is a helper used to validate inputs based on a specified config
*/
type Validator struct {
Config Config
}
/*
Construct creates a new validator
*/
func (v *Validator) Construct() {
v.Config.Construct()
}
/*
IsValidFQDN checks if the string provided corresponds to a valid domain name
*/
func (v *Validator) IsValidFQDN(fqdn string) bool {
// see: https://www.socketloop.com/tutorials/golang-use-regular-expression-to-validate-domain-name
RegExp := regexp.MustCompile(`^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z
]{2,3})$`)
return RegExp.MatchString(fqdn)
}
/*
IsValidPeerName checks if the string provided is a valid peer name. This includes valid domain + port combinations, valid IP + port combinations as well as only domains and IPs with default port 18018
*/
func (v *Validator) IsValidPeerName(peerName string) bool {
addr := ""
port := ""
if strings.Contains(peerName, ":") {
buf := strings.Split(peerName, ":")
addr = buf[0]
port = buf[1]
} else {
addr = peerName
port = "18018"
}
if !v.IsValidIP(addr) {
return v.IsValidFQDN(addr) && v.IsValidPort(port)
}
return v.IsValidPort(port)
}
/*
IsValidPort checks if the string provided is a port in the valid port range
*/
func (v *Validator) IsValidPort(port string) bool {
portInt, err := strconv.ParseInt(port, 10, 32)
if err != nil {
return false
}
return portInt > 0 && portInt <= 65535
}
/*
IsValidIP checks if the string provided is a valid IP address. Valid IP addresses exclude 127.0.0.1 and the configured listen address
*/
func (v *Validator) IsValidIP(ip string) bool {
return net.ParseIP(ip) != nil && ip != "127.0.0.1" && ip != v.Config.IPAddress
}
/*
CheckIfFileExists checks if the path specified is an existing file
*/
func (v *Validator) CheckIfFileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}