Add hostname, hostid and version initialisation with NewJailHost()

This commit is contained in:
yo 2022-06-19 13:51:57 +02:00
parent a7aaa11de6
commit 1bc248fdcc

View File

@ -2,10 +2,12 @@ package cmd
import (
"fmt"
"golang.org/x/net/route"
"net"
"regexp"
"strconv"
"strings"
"io/ioutil"
"golang.org/x/net/route"
)
var defaultRoute4 = [4]byte{0, 0, 0, 0}
@ -113,7 +115,7 @@ func getHostInUseIPv4() ([]string, error) {
out, err := executeCommand("/sbin/ifconfig")
if err != nil {
return ips, fmt.Errorf("ERROR executing \"/sbin/ifconfig\": %s", err)
return ips, fmt.Errorf("Error executing \"/sbin/ifconfig\": %s", err)
}
for _, line := range strings.Split(out, "\n") {
@ -124,3 +126,75 @@ func getHostInUseIPv4() ([]string, error) {
return ips, nil
}
func getHostname() (string, error) {
out, err := executeCommand("/bin/hostname")
if err != nil {
return "", fmt.Errorf("Error executing \"/bin/hostname\": %v", err)
}
return strings.Split(out, "\n")[0], nil
}
func getHostId() (string, error) {
var content []byte
var err error
// return empty string if file does not exist
if content, err = ioutil.ReadFile("/etc/hostid"); err != nil {
if strings.HasSuffix(err.Error(), "no such file or directory") {
return "", nil
}
return "", err
}
return strings.Split(string(content), "\n")[0], nil
}
func getFreeBSDVersion() (FreeBSDVersion, error) {
var version FreeBSDVersion
regex := `([0-9]{1,2})(\.)?([0-9]{1,2})?\-([^\-]*)(\-)?(p[0-9]{1,2})?`
re := regexp.MustCompile(regex)
out, err := executeCommand("/bin/freebsd-version")
if err != nil {
return version, fmt.Errorf("Error executing \"/bin/freebsd-version\": %v", err)
}
if re.MatchString(out) {
version.major, err = strconv.Atoi(re.FindStringSubmatch(out)[1])
if err != nil {
return version, err
}
version.minor, err = strconv.Atoi(re.FindStringSubmatch(out)[3])
if err != nil {
return version, err
}
version.flavor = re.FindStringSubmatch(out)[4]
// Skip the 'p' starting patch level
if len(re.FindStringSubmatch(out)[6]) > 0 {
version.patchLevel, err = strconv.Atoi(re.FindStringSubmatch(out)[6][1:])
if err != nil {
return version, err
}
}
}
return version, nil
}
func NewJailHost() (JailHost, error) {
var jh JailHost
var err error
if jh.hostname, err = getHostname(); err != nil {
return jh, err
}
if jh.hostid, err = getHostId(); err != nil {
return jh, err
}
if jh.version, err = getFreeBSDVersion(); err != nil {
return jh, err
}
return jh, nil
}