netmaker/netclient/functions/localport.go

64 lines
1.9 KiB
Go
Raw Normal View History

//go:build !freebsd
// +build !freebsd
2022-04-22 20:36:42 +08:00
package functions
import (
"strconv"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/netclient/config"
"github.com/gravitl/netmaker/netclient/local"
"github.com/gravitl/netmaker/netclient/ncutils"
"golang.zx2c4.com/wireguard/wgctrl"
2022-04-22 20:36:42 +08:00
)
2022-04-25 01:47:23 +08:00
// GetLocalListenPort - Gets the port running on the local interface
2022-04-22 20:36:42 +08:00
func GetLocalListenPort(ifacename string) (int32, error) {
client, err := wgctrl.New()
2022-04-22 20:36:42 +08:00
if err != nil {
logger.Log(0, "failed to start wgctrl")
2022-04-22 20:36:42 +08:00
return 0, err
}
defer client.Close()
device, err := client.Device(ifacename)
2022-04-22 20:36:42 +08:00
if err != nil {
logger.Log(0, "failed to parse interface", ifacename)
2022-04-22 20:36:42 +08:00
return 0, err
}
return int32(device.ListenPort), nil
2022-04-22 20:36:42 +08:00
}
2022-04-22 20:53:05 +08:00
// UpdateLocalListenPort - check local port, if different, mod config and publish
2022-04-22 20:36:42 +08:00
func UpdateLocalListenPort(nodeCfg *config.ClientConfig) error {
var err error
ifacename := getRealIface(nodeCfg.Node.Interface, nodeCfg.Node.Address)
localPort, err := GetLocalListenPort(ifacename)
if err != nil {
logger.Log(1, "network:", nodeCfg.Node.Network, "error encountered checking local listen port: ", ifacename, err.Error())
2022-04-22 20:36:42 +08:00
} else if nodeCfg.Node.LocalListenPort != localPort && localPort != 0 {
logger.Log(1, "network:", nodeCfg.Node.Network, "local port has changed from ", strconv.Itoa(int(nodeCfg.Node.LocalListenPort)), " to ", strconv.Itoa(int(localPort)))
2022-04-22 20:36:42 +08:00
nodeCfg.Node.LocalListenPort = localPort
2022-06-01 00:07:56 +08:00
err = config.ModNodeConfig(&nodeCfg.Node)
2022-04-22 20:36:42 +08:00
if err != nil {
return err
}
if err := PublishNodeUpdate(nodeCfg); err != nil {
2022-08-30 02:08:01 +08:00
logger.Log(0, "could not publish local port change", err.Error())
2022-04-22 20:36:42 +08:00
}
}
return err
}
func getRealIface(ifacename string, address string) string {
var deviceiface = ifacename
var err error
if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
deviceiface, err = local.GetMacIface(address)
if err != nil || deviceiface == "" {
deviceiface = ifacename
}
}
return deviceiface
}