netmaker/netclient/wireguard/unix.go

64 lines
1.7 KiB
Go
Raw Normal View History

2021-09-20 02:03:47 +08:00
package wireguard
import (
2022-01-04 08:09:19 +08:00
"fmt"
2021-11-13 02:03:31 +08:00
"os"
2021-11-13 00:24:29 +08:00
"github.com/gravitl/netmaker/logger"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/ncutils"
)
2021-10-09 03:07:12 +08:00
// ApplyWGQuickConf - applies wg-quick commands if os supports
2022-08-20 00:08:31 +08:00
func ApplyWGQuickConf(confPath, ifacename string, isConnected bool) error {
2022-02-02 13:18:02 +08:00
if ncutils.IsWindows() {
2022-08-20 00:08:31 +08:00
return ApplyWindowsConf(confPath, isConnected)
2022-02-02 13:18:02 +08:00
} else {
_, err := os.Stat(confPath)
if err != nil {
logger.Log(0, confPath+" does not exist "+err.Error())
2022-02-02 13:18:02 +08:00
return err
}
if ncutils.IfaceExists(ifacename) {
ncutils.RunCmd("wg-quick down "+confPath, true)
}
2022-08-20 00:08:31 +08:00
if !isConnected {
return nil
}
2022-02-02 13:18:02 +08:00
_, err = ncutils.RunCmd("wg-quick up "+confPath, true)
2022-01-20 04:00:03 +08:00
return err
}
2021-11-13 00:24:29 +08:00
}
2022-01-12 07:28:41 +08:00
// ApplyMacOSConf - applies system commands similar to wg-quick using golang for MacOS
2022-08-20 00:08:31 +08:00
func ApplyMacOSConf(node *models.Node, ifacename, confPath string, isConnected bool) error {
2022-01-12 07:28:41 +08:00
var err error
2022-01-12 23:03:23 +08:00
_ = WgQuickDownMac(node, ifacename)
2022-08-20 00:08:31 +08:00
if !isConnected {
return nil
}
2022-01-12 07:28:41 +08:00
err = WgQuickUpMac(node, ifacename, confPath)
return err
}
2021-10-09 03:07:12 +08:00
// RemoveWGQuickConf - calls wg-quick down
2021-09-20 02:03:47 +08:00
func RemoveWGQuickConf(confPath string, printlog bool) error {
2022-01-04 08:09:19 +08:00
_, err := ncutils.RunCmd(fmt.Sprintf("wg-quick down %s", confPath), printlog)
2021-11-13 00:24:29 +08:00
return err
2021-09-20 02:03:47 +08:00
}
2021-10-09 03:07:12 +08:00
// StorePrivKey - stores wg priv key on disk locally
2021-09-20 02:03:47 +08:00
func StorePrivKey(key string, network string) error {
2021-10-13 03:44:19 +08:00
var err error
2021-09-20 02:03:47 +08:00
d1 := []byte(key)
err = os.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0600)
2021-09-20 02:03:47 +08:00
return err
}
2021-10-09 03:07:12 +08:00
// RetrievePrivKey - reads wg priv key from local disk
2021-09-20 02:03:47 +08:00
func RetrievePrivKey(network string) (string, error) {
2022-02-06 03:26:19 +08:00
dat, err := ncutils.GetFileWithRetry(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, 2)
2021-09-20 02:03:47 +08:00
return string(dat), err
}