unix.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package wireguard
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/gravitl/netmaker/logger"
  6. "github.com/gravitl/netmaker/models"
  7. "github.com/gravitl/netmaker/netclient/ncutils"
  8. )
  9. // ApplyWGQuickConf - applies wg-quick commands if os supports
  10. func ApplyWGQuickConf(confPath, ifacename string, isConnected bool) error {
  11. if ncutils.IsWindows() {
  12. return ApplyWindowsConf(confPath, isConnected)
  13. } else {
  14. _, err := os.Stat(confPath)
  15. if err != nil {
  16. logger.Log(0, confPath+" does not exist "+err.Error())
  17. return err
  18. }
  19. if ncutils.IfaceExists(ifacename) {
  20. ncutils.RunCmd("wg-quick down "+confPath, true)
  21. }
  22. if !isConnected {
  23. return nil
  24. }
  25. _, err = ncutils.RunCmd("wg-quick up "+confPath, true)
  26. return err
  27. }
  28. }
  29. // ApplyMacOSConf - applies system commands similar to wg-quick using golang for MacOS
  30. func ApplyMacOSConf(node *models.Node, ifacename, confPath string, isConnected bool) error {
  31. var err error
  32. _ = WgQuickDownMac(node, ifacename)
  33. if !isConnected {
  34. return nil
  35. }
  36. err = WgQuickUpMac(node, ifacename, confPath)
  37. return err
  38. }
  39. // RemoveWGQuickConf - calls wg-quick down
  40. func RemoveWGQuickConf(confPath string, printlog bool) error {
  41. _, err := ncutils.RunCmd(fmt.Sprintf("wg-quick down %s", confPath), printlog)
  42. return err
  43. }
  44. // StorePrivKey - stores wg priv key on disk locally
  45. func StorePrivKey(key string, network string) error {
  46. var err error
  47. d1 := []byte(key)
  48. err = os.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0600)
  49. return err
  50. }
  51. // RetrievePrivKey - reads wg priv key from local disk
  52. func RetrievePrivKey(network string) (string, error) {
  53. dat, err := ncutils.GetFileWithRetry(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, 2)
  54. return string(dat), err
  55. }