netmaker/netclient/functions/common.go

420 lines
11 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package functions
import (
"bytes"
2022-01-11 08:36:13 +08:00
"encoding/json"
"errors"
2021-08-03 06:06:26 +08:00
"fmt"
2022-04-26 07:28:56 +08:00
"io"
2021-03-26 00:17:52 +08:00
"log"
"net"
"net/http"
2021-09-20 02:03:47 +08:00
"os"
2022-08-29 17:35:23 +08:00
"path/filepath"
2022-07-07 21:52:20 +08:00
"strconv"
2022-01-12 23:03:23 +08:00
"strings"
2022-07-06 21:32:00 +08:00
"time"
2021-08-03 06:06:26 +08:00
"github.com/gravitl/netmaker/logger"
2021-08-03 06:06:26 +08:00
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/config"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/netclient/daemon"
2022-02-06 04:00:26 +08:00
"github.com/gravitl/netmaker/netclient/local"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/netclient/wireguard"
2021-03-26 00:17:52 +08:00
"golang.zx2c4.com/wireguard/wgctrl"
)
// LINUX_APP_DATA_PATH - linux path
const LINUX_APP_DATA_PATH = "/etc/netmaker"
2022-07-06 21:32:00 +08:00
// HTTP_TIMEOUT - timeout in seconds for http requests
const HTTP_TIMEOUT = 30
2022-08-24 02:18:12 +08:00
// HTTPClient - http client to be reused by all
var HTTPClient http.Client
// SetHTTPClient -sets http client with sane default
func SetHTTPClient() {
HTTPClient = http.Client{
Timeout: HTTP_TIMEOUT * time.Second,
}
}
2021-10-09 03:07:12 +08:00
// ListPorts - lists ports of WireGuard devices
2021-08-03 06:06:26 +08:00
func ListPorts() error {
wgclient, err := wgctrl.New()
2021-08-03 06:06:26 +08:00
if err != nil {
return err
}
2021-12-11 04:01:10 +08:00
defer wgclient.Close()
devices, err := wgclient.Devices()
2021-08-03 06:06:26 +08:00
if err != nil {
return err
}
fmt.Println("Here are your ports:")
2021-08-03 06:06:26 +08:00
for _, i := range devices {
fmt.Println(i.ListenPort)
}
return err
}
2021-08-31 03:58:23 +08:00
func getPrivateAddr() (string, error) {
2021-08-03 06:06:26 +08:00
var local string
2021-08-31 03:58:23 +08:00
conn, err := net.Dial("udp", "8.8.8.8:80")
2022-02-02 13:02:36 +08:00
if err == nil {
defer conn.Close()
2021-03-26 00:17:52 +08:00
2022-02-02 13:02:36 +08:00
localAddr := conn.LocalAddr().(*net.UDPAddr)
localIP := localAddr.IP
local = localIP.String()
}
2021-09-23 00:03:33 +08:00
if local == "" {
local, err = getPrivateAddrBackup()
}
2022-02-02 13:02:36 +08:00
2021-08-31 03:58:23 +08:00
if local == "" {
err = errors.New("could not find local ip")
2021-08-03 06:06:26 +08:00
}
if net.ParseIP(local).To16() != nil {
local = "[" + local + "]"
}
2022-02-02 13:02:36 +08:00
2021-08-03 06:06:26 +08:00
return local, err
}
2021-09-23 00:03:33 +08:00
func getPrivateAddrBackup() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
var local string
found := false
for _, i := range ifaces {
if i.Flags&net.FlagUp == 0 {
continue // interface down
}
if i.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := i.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
if !found {
ip = v.IP
local = ip.String()
found = true
}
case *net.IPAddr:
if !found {
ip = v.IP
local = ip.String()
found = true
}
}
}
}
if !found {
2022-01-02 23:30:07 +08:00
err := errors.New("local ip address not found")
2021-09-23 00:03:33 +08:00
return "", err
}
return local, err
}
2021-10-09 03:07:12 +08:00
// GetNode - gets node locally
2021-08-03 06:06:26 +08:00
func GetNode(network string) models.Node {
2021-08-03 06:06:26 +08:00
modcfg, err := config.ReadConfig(network)
if err != nil {
log.Fatalf("Error: %v", err)
}
2021-03-26 00:17:52 +08:00
2021-08-03 06:06:26 +08:00
return modcfg.Node
2021-03-26 00:17:52 +08:00
}
2021-10-09 03:07:12 +08:00
// Uninstall - uninstalls networks from client
2021-05-30 01:22:18 +08:00
func Uninstall() error {
networks, err := ncutils.GetSystemNetworks()
2021-05-30 01:22:18 +08:00
if err != nil {
logger.Log(1, "unable to retrieve networks: ", err.Error())
logger.Log(1, "continuing uninstall without leaving networks")
2021-05-30 01:22:18 +08:00
} else {
for _, network := range networks {
err = LeaveNetwork(network)
2021-05-30 01:22:18 +08:00
if err != nil {
logger.Log(1, "encounter issue leaving network", network, ":", err.Error())
2021-05-30 01:22:18 +08:00
}
}
}
2022-05-07 03:21:57 +08:00
err = nil
2022-07-15 01:48:11 +08:00
2021-08-31 03:58:23 +08:00
// clean up OS specific stuff
2021-09-20 02:03:47 +08:00
if ncutils.IsWindows() {
daemon.CleanupWindows()
2021-09-22 02:01:52 +08:00
} else if ncutils.IsMac() {
2021-09-20 02:03:47 +08:00
daemon.CleanupMac()
2021-10-20 03:53:01 +08:00
} else if ncutils.IsLinux() {
daemon.CleanupLinux()
2022-02-09 11:31:17 +08:00
} else if ncutils.IsFreeBSD() {
2022-02-09 11:06:41 +08:00
daemon.CleanupFreebsd()
2021-09-22 09:35:52 +08:00
} else if !ncutils.IsKernel() {
logger.Log(1, "manual cleanup required")
2021-08-31 03:58:23 +08:00
}
2021-09-18 23:01:34 +08:00
2021-05-30 01:22:18 +08:00
return err
}
2021-03-26 00:17:52 +08:00
2021-10-09 03:07:12 +08:00
// LeaveNetwork - client exits a network
func LeaveNetwork(network string) error {
2021-08-03 06:06:26 +08:00
cfg, err := config.ReadConfig(network)
if err != nil {
return err
}
2022-08-29 20:12:25 +08:00
logger.Log(2, "deleting node from server")
2022-08-29 17:35:23 +08:00
if err := deleteNodeFromServer(cfg); err != nil {
logger.Log(0, "error deleting node from server", err.Error())
}
2022-08-29 20:12:25 +08:00
logger.Log(2, "deleting wireguard interface")
2022-08-29 17:35:23 +08:00
if err := deleteLocalNetwork(cfg); err != nil {
2022-08-29 20:12:25 +08:00
logger.Log(0, "error deleting wireguard interface", err.Error())
2022-08-29 17:35:23 +08:00
}
2022-08-29 20:12:25 +08:00
logger.Log(2, "deleting configuration files")
2022-08-29 17:35:23 +08:00
if err := WipeLocal(cfg); err != nil {
2022-08-29 20:12:25 +08:00
logger.Log(0, "error deleting local network files", err.Error())
2021-11-15 08:17:30 +08:00
}
2022-08-29 20:12:25 +08:00
logger.Log(2, "removing dns entries")
2022-08-29 17:35:23 +08:00
if err := removeHostDNS(cfg.Node.Interface, ncutils.IsWindows()); err != nil {
logger.Log(0, "failed to delete dns entries for", cfg.Node.Interface, err.Error())
}
2022-08-29 20:12:25 +08:00
logger.Log(2, "deleting broker keys as required")
if !brokerInUse(cfg.Server.Server) {
if err := deleteBrokerFiles(cfg.Server.Server); err != nil {
logger.Log(0, "failed to deleter certs for", cfg.Server.Server, err.Error())
}
}
logger.Log(2, "restarting daemon")
2022-08-29 17:35:23 +08:00
return daemon.Restart()
}
2022-08-29 20:12:25 +08:00
func brokerInUse(broker string) bool {
networks, _ := ncutils.GetSystemNetworks()
for _, net := range networks {
cfg := config.ClientConfig{}
cfg.Network = net
cfg.ReadConfig()
if cfg.Server.Server == broker {
return true
}
}
return false
}
func deleteBrokerFiles(broker string) error {
dir := ncutils.GetNetclientServerPath(broker)
if err := os.RemoveAll(dir); err != nil {
return err
}
return nil
}
2022-08-29 17:35:23 +08:00
func deleteNodeFromServer(cfg *config.ClientConfig) error {
node := cfg.Node
if node.IsServer == "yes" {
return errors.New("attempt to delete server node ... not permitted")
}
token, err := Authenticate(cfg)
2022-02-05 00:31:22 +08:00
if err != nil {
2022-08-29 17:35:23 +08:00
return fmt.Errorf("unable to authenticate %w", err)
2022-02-05 00:31:22 +08:00
}
2022-08-29 17:35:23 +08:00
url := "https://" + cfg.Server.API + "/api/nodes/" + cfg.Network + "/" + cfg.Node.ID
response, err := API("", http.MethodDelete, url, token)
if err != nil {
return fmt.Errorf("error deleting node on server: %w", err)
}
if response.StatusCode != http.StatusOK {
bodybytes, _ := io.ReadAll(response.Body)
defer response.Body.Close()
return fmt.Errorf("error deleting node from network %s on server %s %s", cfg.Network, response.Status, string(bodybytes))
}
return nil
}
2022-02-05 00:31:22 +08:00
2022-08-29 17:35:23 +08:00
func deleteLocalNetwork(cfg *config.ClientConfig) error {
wgClient, wgErr := wgctrl.New()
if wgErr != nil {
return wgErr
}
removeIface := cfg.Node.Interface
queryAddr := cfg.Node.PrimaryAddress()
if ncutils.IsMac() {
var macIface string
macIface, wgErr = local.GetMacIface(queryAddr)
if wgErr == nil && removeIface != "" {
removeIface = macIface
}
}
dev, devErr := wgClient.Device(removeIface)
if devErr != nil {
return fmt.Errorf("error flushing routes %w", devErr)
}
local.FlushPeerRoutes(removeIface, queryAddr, dev.Peers[:])
_, cidr, cidrErr := net.ParseCIDR(cfg.NetworkSettings.AddressRange)
if cidrErr != nil {
return fmt.Errorf("error flushing routes %w", cidrErr)
}
local.RemoveCIDRRoute(removeIface, queryAddr, cidr)
return nil
2021-08-10 22:55:48 +08:00
}
2021-10-09 03:07:12 +08:00
// DeleteInterface - delete an interface of a network
2021-08-03 06:06:26 +08:00
func DeleteInterface(ifacename string, postdown string) error {
2021-12-30 20:11:01 +08:00
return wireguard.RemoveConf(ifacename, true)
2021-03-26 10:29:36 +08:00
}
2021-05-30 01:22:18 +08:00
2021-10-09 03:07:12 +08:00
// WipeLocal - wipes local instance
2022-08-29 17:35:23 +08:00
func WipeLocal(cfg *config.ClientConfig) error {
if err := wireguard.RemoveConf(cfg.Node.Interface, true); err == nil {
logger.Log(1, "network:", cfg.Node.Network, "removed WireGuard interface: ", cfg.Node.Interface)
} else if strings.Contains(err.Error(), "does not exist") {
err = nil
2021-09-20 02:03:47 +08:00
}
2022-08-29 20:12:25 +08:00
dir := ncutils.GetNetclientPathSpecific()
2022-08-29 17:35:23 +08:00
fail := false
2022-08-29 20:12:25 +08:00
files, err := filepath.Glob(dir + "*" + cfg.Node.Network)
2022-08-29 17:35:23 +08:00
if err != nil {
logger.Log(0, "no matching files", err.Error())
fail = true
2022-01-29 07:27:21 +08:00
}
2022-08-29 17:35:23 +08:00
for _, file := range files {
if err := os.Remove(file); err != nil {
logger.Log(0, "failed to delete file", file, err.Error())
fail = true
2022-02-08 04:37:59 +08:00
}
2021-09-20 02:03:47 +08:00
}
2022-08-29 20:12:25 +08:00
2022-08-29 17:35:23 +08:00
if cfg.Node.Interface != "" {
2022-08-29 20:12:25 +08:00
if ncutils.FileExists(dir + cfg.Node.Interface + ".conf") {
if err := os.Remove(dir + cfg.Node.Interface + ".conf"); err != nil {
2022-09-20 03:37:00 +08:00
logger.Log(0, err.Error())
2022-08-29 17:35:23 +08:00
fail = true
2022-08-01 18:18:34 +08:00
}
}
2021-09-20 02:03:47 +08:00
}
2022-08-29 17:35:23 +08:00
if fail {
return errors.New("not all files were deleted")
}
return nil
2021-09-20 02:03:47 +08:00
}
// GetNetmakerPath - gets netmaker path locally
func GetNetmakerPath() string {
return LINUX_APP_DATA_PATH
}
2022-08-24 02:18:12 +08:00
// API function to interact with netmaker api endpoints. response from endpoint is returned
func API(data any, method, url, authorization string) (*http.Response, error) {
var request *http.Request
var err error
if data != "" {
payload, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("error encoding data %w", err)
}
request, err = http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
return nil, fmt.Errorf("error creating http request %w", err)
}
request.Header.Set("Content-Type", "application/json")
} else {
request, err = http.NewRequest(method, url, nil)
if err != nil {
return nil, fmt.Errorf("error creating http request %w", err)
}
}
if authorization != "" {
request.Header.Set("authorization", "Bearer "+authorization)
}
2022-08-24 02:18:12 +08:00
return HTTPClient.Do(request)
}
// Authenticate authenticates with api to permit subsequent interactions with the api
func Authenticate(cfg *config.ClientConfig) (string, error) {
2022-05-25 04:31:18 +08:00
pass, err := os.ReadFile(ncutils.GetNetclientPathSpecific() + "secret-" + cfg.Network)
if err != nil {
return "", fmt.Errorf("could not read secrets file %w", err)
}
data := models.AuthParams{
MacAddress: cfg.Node.MacAddress,
ID: cfg.Node.ID,
Password: string(pass),
}
url := "https://" + cfg.Server.API + "/api/nodes/adm/" + cfg.Network + "/authenticate"
response, err := API(data, http.MethodPost, url, "")
if err != nil {
return "", err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
2022-04-26 07:28:56 +08:00
bodybytes, _ := io.ReadAll(response.Body)
return "", fmt.Errorf("failed to authenticate %s %s", response.Status, string(bodybytes))
}
resp := models.SuccessResponse{}
if err := json.NewDecoder(response.Body).Decode(&resp); err != nil {
return "", fmt.Errorf("error decoding respone %w", err)
}
tokenData := resp.Response.(map[string]interface{})
token := tokenData["AuthToken"]
return token.(string), nil
}
2022-05-31 20:42:12 +08:00
// RegisterWithServer calls the register endpoint with privatekey and commonname - api returns ca and client certificate
func SetServerInfo(cfg *config.ClientConfig) error {
cfg, err := config.ReadConfig(cfg.Network)
if err != nil {
return err
}
url := "https://" + cfg.Server.API + "/api/server/getserverinfo"
logger.Log(1, "server at "+url)
token, err := Authenticate(cfg)
if err != nil {
return err
}
response, err := API("", http.MethodGet, url, token)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return errors.New(response.Status)
}
2022-06-01 00:07:56 +08:00
var resp models.ServerConfig
2022-05-31 20:42:12 +08:00
if err := json.NewDecoder(response.Body).Decode(&resp); err != nil {
return errors.New("unmarshal cert error " + err.Error())
}
// set broker information on register
cfg.Server.Server = resp.Server
cfg.Server.MQPort = resp.MQPort
2022-06-01 00:07:56 +08:00
if err = config.ModServerConfig(&cfg.Server, cfg.Node.Network); err != nil {
2022-05-31 20:42:12 +08:00
logger.Log(0, "error overwriting config with broker information: "+err.Error())
}
return nil
}
2022-07-07 21:52:20 +08:00
func informPortChange(node *models.Node) {
if node.ListenPort == 0 {
logger.Log(0, "network:", node.Network, "UDP hole punching enabled for node", node.Name)
2022-07-07 21:52:20 +08:00
} else {
logger.Log(0, "network:", node.Network, "node", node.Name, "is using port", strconv.Itoa(int(node.ListenPort)))
2022-07-07 21:52:20 +08:00
}
}