netmaker/netclient/ncutils/netclientutils_windows.go

94 lines
2.2 KiB
Go
Raw Normal View History

2021-11-17 09:10:11 +08:00
package ncutils
import (
"embed"
2021-11-18 10:57:27 +08:00
"fmt"
2021-11-17 09:10:11 +08:00
"log"
2021-11-18 10:57:27 +08:00
"os"
2021-11-17 09:10:11 +08:00
"os/exec"
2021-11-18 10:57:27 +08:00
"strconv"
2021-11-17 09:10:11 +08:00
"strings"
2021-11-18 10:57:27 +08:00
"syscall"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2021-11-17 09:10:11 +08:00
)
//go:embed windowsdaemon/winsw.exe
var winswContent embed.FS
2021-11-17 09:10:11 +08:00
// RunCmd - runs a local command
func RunCmd(command string, printerr bool) (string, error) {
args := strings.Fields(command)
cmd := exec.Command(args[0], args[1:]...)
cmd.Wait()
2021-11-18 10:57:27 +08:00
//cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: "/C \"" + command + "\""}
2021-11-17 09:10:11 +08:00
out, err := cmd.CombinedOutput()
if err != nil && printerr {
log.Println("error running command:", command)
log.Println(strings.TrimSuffix(string(out), "\n"))
}
return string(out), err
}
2021-11-18 10:57:27 +08:00
// RunCmd - runs a local command
func RunCmdFormatted(command string, printerr bool) (string, error) {
var comSpec = os.Getenv("COMSPEC")
if comSpec == "" {
comSpec = os.Getenv("SystemRoot") + "\\System32\\cmd.exe"
}
cmd := exec.Command(comSpec)
cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: "/C \"" + command + "\""}
cmd.Wait()
out, err := cmd.CombinedOutput()
if err != nil && printerr {
log.Println("error running command:", command)
log.Println(strings.TrimSuffix(string(out), "\n"))
}
return string(out), err
}
// CreateUserSpaceConf - creates a user space WireGuard conf
func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
2021-11-18 10:57:27 +08:00
peersString, err := parsePeers(perskeepalive, peers)
var listenPortString string
if mtu <= 0 {
mtu = 1280
}
if listenPort != "" {
listenPortString += "ListenPort = " + listenPort
}
if err != nil {
return "", err
}
config := fmt.Sprintf(`[Interface]
Address = %s
PrivateKey = %s
MTU = %s
%s
%s
`,
address+"/32",
privatekey,
strconv.Itoa(int(mtu)),
listenPortString,
peersString)
return config, nil
}
// GetEmbedded - Gets the Windows daemon creator
func GetEmbedded() error {
data, err := winswContent.ReadFile("windowsdaemon/winsw.exe")
if err != nil {
return err
}
fileName := fmt.Sprintf("%swinsw.exe", GetNetclientPathSpecific())
err = os.WriteFile(fileName, data, 0700)
if err != nil {
Log("could not mount winsw.exe")
return err
}
return nil
}