netmaker/netclient/functions/daemon.go

563 lines
18 KiB
Go
Raw Normal View History

2022-01-03 00:02:59 +08:00
package functions
import (
"context"
2022-01-03 00:02:59 +08:00
"encoding/json"
"errors"
2022-01-26 11:14:31 +08:00
"fmt"
"os"
"os/signal"
"runtime"
2022-01-29 04:33:30 +08:00
"strings"
2022-01-26 11:14:31 +08:00
"sync"
"syscall"
2022-01-03 00:02:59 +08:00
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gravitl/netmaker/models"
2022-01-29 04:33:30 +08:00
"github.com/gravitl/netmaker/netclient/auth"
2022-01-03 00:02:59 +08:00
"github.com/gravitl/netmaker/netclient/config"
2022-01-25 04:46:38 +08:00
"github.com/gravitl/netmaker/netclient/local"
2022-01-03 00:02:59 +08:00
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/netclient/wireguard"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2022-01-03 00:02:59 +08:00
)
// ServerKeepalive - stores time of last server keepalive message
var keepalive = make(map[string]time.Time, 3)
2022-01-26 11:14:31 +08:00
var messageCache = make(map[string]string, 20)
const lastNodeUpdate = "lnu"
const lastPeerUpdate = "lpu"
func insert(network, which, cache string) {
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
messageCache[fmt.Sprintf("%s%s", network, which)] = cache
}
func read(network, which string) string {
return messageCache[fmt.Sprintf("%s%s", network, which)]
}
2022-01-04 07:27:13 +08:00
// Daemon runs netclient daemon from command line
2022-01-03 00:02:59 +08:00
func Daemon() error {
2022-01-04 05:26:40 +08:00
ctx, cancel := context.WithCancel(context.Background())
2022-01-03 00:02:59 +08:00
networks, err := ncutils.GetSystemNetworks()
if err != nil {
2022-01-04 07:27:13 +08:00
cancel()
2022-01-03 00:02:59 +08:00
return err
}
for _, network := range networks {
2022-01-16 07:16:44 +08:00
go MessageQueue(ctx, network)
2022-01-03 00:02:59 +08:00
}
2022-01-04 05:26:40 +08:00
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
<-quit
cancel()
ncutils.Log("all done")
2022-01-03 00:02:59 +08:00
return nil
}
2022-01-04 07:27:13 +08:00
// SetupMQTT creates a connection to broker and return client
func SetupMQTT(cfg *config.ClientConfig) mqtt.Client {
2022-01-03 00:02:59 +08:00
opts := mqtt.NewClientOptions()
2022-01-27 00:20:46 +08:00
for _, server := range cfg.Node.NetworkSettings.DefaultServerAddrs {
2022-01-26 23:40:39 +08:00
if server.Address != "" && server.IsLeader {
2022-02-02 03:01:13 +08:00
// ncutils.Log(fmt.Sprintf("adding server (%s) to listen on network %s", server.Address, cfg.Node.Network))
2022-01-26 23:40:39 +08:00
opts.AddBroker(server.Address + ":1883")
2022-01-27 00:20:46 +08:00
break
2022-01-26 11:14:31 +08:00
}
}
2022-01-03 00:02:59 +08:00
opts.SetDefaultPublishHandler(All)
client := mqtt.NewClient(opts)
2022-02-01 10:28:34 +08:00
tperiod := time.Now().Add(12 * time.Second)
2022-01-28 04:46:45 +08:00
for {
2022-02-01 10:28:34 +08:00
//if after 12 seconds, try a gRPC pull on the last try
if time.Now().After(tperiod) {
2022-02-01 11:43:12 +08:00
ncutils.Log("running pull for " + cfg.Node.Network)
2022-02-01 10:28:34 +08:00
_, err := Pull(cfg.Node.Network, true)
if err != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log("could not run pull, exiting " + cfg.Node.Network + " setup: " + err.Error())
return client
2022-02-01 10:28:34 +08:00
}
time.Sleep(2 * time.Second)
}
2022-01-28 04:46:45 +08:00
if token := client.Connect(); token.Wait() && token.Error() != nil {
2022-02-01 11:43:12 +08:00
ncutils.Log("unable to connect to broker, retrying ...")
2022-01-28 04:52:31 +08:00
if time.Now().After(tperiod) {
2022-02-01 12:18:58 +08:00
ncutils.Log("could not connect to broker, exiting " + cfg.Node.Network + " setup: " + token.Error().Error())
return client
2022-01-28 04:46:45 +08:00
}
} else {
break
}
time.Sleep(2 * time.Second)
2022-01-03 00:02:59 +08:00
}
return client
}
2022-01-16 07:16:44 +08:00
// MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
func MessageQueue(ctx context.Context, network string) {
ncutils.Log("netclient go routine started for " + network)
2022-01-21 19:16:49 +08:00
var cfg config.ClientConfig
cfg.Network = network
2022-02-01 11:43:12 +08:00
ncutils.Log("pulling latest config for " + cfg.Network)
_, err := Pull(network, true)
2022-02-01 11:43:12 +08:00
if err != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log(err.Error())
return
2022-02-01 11:43:12 +08:00
}
time.Sleep(time.Second << 1)
cfg.ReadConfig()
2022-02-01 11:43:12 +08:00
ncutils.Log("daemon started for network: " + network)
2022-01-21 19:16:49 +08:00
client := SetupMQTT(&cfg)
if cfg.DebugOn {
if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log(token.Error().Error())
return
}
2022-01-23 00:38:56 +08:00
ncutils.Log("subscribed to all topics for debugging purposes")
2022-01-03 00:02:59 +08:00
}
2022-01-29 04:33:30 +08:00
if token := client.Subscribe(fmt.Sprintf("update/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log(token.Error().Error())
return
2022-01-20 04:00:03 +08:00
}
2022-01-23 00:38:56 +08:00
if cfg.DebugOn {
ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
2022-01-23 00:38:56 +08:00
}
2022-01-29 04:33:30 +08:00
if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log(token.Error().Error())
return
2022-01-20 04:00:03 +08:00
}
2022-01-23 00:38:56 +08:00
if cfg.DebugOn {
ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
2022-01-23 00:38:56 +08:00
}
2022-01-27 22:48:32 +08:00
var id string
var found bool
2022-01-27 22:48:32 +08:00
for _, server := range cfg.NetworkSettings.DefaultServerAddrs {
if server.IsLeader {
id = server.ID
}
if server.Address != "" {
if token := client.Subscribe("serverkeepalive/"+id, 0, mqtt.MessageHandler(ServerKeepAlive)); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log(token.Error().Error())
return
2022-01-27 22:48:32 +08:00
}
found = true
2022-01-27 22:48:32 +08:00
if cfg.DebugOn {
ncutils.Log("subscribed to server keepalives for server " + id)
2022-01-27 22:48:32 +08:00
}
}
}
if !found {
ncutils.Log("leader not defined for network " + cfg.Network)
}
defer client.Disconnect(250)
go MonitorKeepalive(ctx, client, &cfg)
2022-01-21 19:16:49 +08:00
go Checkin(ctx, &cfg, network)
<-ctx.Done()
ncutils.Log("shutting down daemon")
2022-01-03 00:02:59 +08:00
}
2022-01-04 07:27:13 +08:00
// All -- mqtt message hander for all ('#') topics
2022-01-03 00:02:59 +08:00
var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
2022-01-20 04:00:03 +08:00
ncutils.Log("default message handler -- received message but not handling")
2022-01-03 00:02:59 +08:00
ncutils.Log("Topic: " + string(msg.Topic()))
2022-01-20 04:00:03 +08:00
//ncutils.Log("Message: " + string(msg.Payload()))
2022-01-03 00:02:59 +08:00
}
2022-01-04 07:27:13 +08:00
// NodeUpdate -- mqtt message handler for /update/<NodeID> topic
2022-01-26 23:40:39 +08:00
func NodeUpdate(client mqtt.Client, msg mqtt.Message) {
//potentiall blocking i/o so do this in a go routine
go func() {
var newNode models.Node
var cfg config.ClientConfig
2022-01-29 04:33:30 +08:00
var network = parseNetworkFromTopic(msg.Topic())
cfg.Network = network
cfg.ReadConfig()
data, dataErr := decryptMsg(&cfg, msg.Payload())
if dataErr != nil {
return
}
2022-01-30 04:02:37 +08:00
err := json.Unmarshal([]byte(data), &newNode)
if err != nil {
ncutils.Log("error unmarshalling node update data" + err.Error())
return
}
2022-01-29 04:33:30 +08:00
2022-01-27 00:24:47 +08:00
ncutils.Log("received message to update node " + newNode.Name)
2022-01-26 11:14:31 +08:00
// see if cache hit, if so skip
var currentMessage = read(newNode.Network, lastNodeUpdate)
2022-01-29 04:33:30 +08:00
if currentMessage == string(data) {
2022-01-26 11:14:31 +08:00
return
}
2022-01-29 04:33:30 +08:00
insert(newNode.Network, lastNodeUpdate, string(data))
//check if interface name has changed if so delete.
if cfg.Node.Interface != newNode.Interface {
if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
2022-01-13 05:23:34 +08:00
ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
}
}
newNode.PullChanges = "no"
//ensure that OS never changes
newNode.OS = runtime.GOOS
2022-01-31 23:46:34 +08:00
// check if interface needs to delta
ifaceDelta := ncutils.IfaceDelta(&cfg.Node, &newNode)
cfg.Node = newNode
switch newNode.Action {
case models.NODE_DELETE:
2022-01-13 05:23:34 +08:00
if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
return
}
2022-02-01 04:37:57 +08:00
if token := client.Unsubscribe(fmt.Sprintf("update/%s/%s", newNode.Network, newNode.ID), fmt.Sprintf("peers/%s/%s", newNode.Network, newNode.ID)); token.Wait() && token.Error() != nil {
ncutils.PrintLog("error unsubscribing during node deletion", 1)
}
2022-01-23 00:38:56 +08:00
return
case models.NODE_UPDATE_KEY:
if err := UpdateKeys(&cfg, client); err != nil {
ncutils.PrintLog("err updating wireguard keys: "+err.Error(), 1)
}
case models.NODE_NOOP:
default:
}
//Save new config
if err := config.Write(&cfg, cfg.Network); err != nil {
ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
}
nameserver := cfg.Server.CoreDNSAddr
2022-01-13 05:23:34 +08:00
privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
if err != nil {
ncutils.Log("error reading PrivateKey " + err.Error())
return
}
2022-01-23 00:38:56 +08:00
file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
ncutils.Log("error updating wireguard config " + err.Error())
return
}
2022-01-31 23:46:34 +08:00
if ifaceDelta {
ncutils.Log("applying WG conf to " + file)
err = wireguard.ApplyWGQuickConf(file, cfg.Node.Interface)
2022-01-31 23:46:34 +08:00
if err != nil {
ncutils.Log("error restarting wg after node update " + err.Error())
return
}
time.Sleep(time.Second >> 1)
2022-02-01 03:01:09 +08:00
if err = Resubscribe(client, &cfg); err != nil {
ncutils.Log("error resubscribing after interface change " + err.Error())
return
}
}
2022-02-01 05:49:40 +08:00
/*
else {
ncutils.Log("syncing conf to " + file)
err = wireguard.SyncWGQuickConf(cfg.Node.Interface, file)
if err != nil {
ncutils.Log("error syncing wg after peer update " + err.Error())
return
}
}
*/
2022-01-25 04:46:38 +08:00
//deal with DNS
2022-01-25 05:12:57 +08:00
if newNode.DNSOn == "yes" {
ncutils.Log("setting up DNS")
2022-01-25 04:46:38 +08:00
if err = local.UpdateDNS(cfg.Node.Interface, cfg.Network, cfg.Server.CoreDNSAddr); err != nil {
ncutils.Log("error applying dns" + err.Error())
}
} else {
2022-01-25 05:12:57 +08:00
ncutils.Log("settng DNS off")
_, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+cfg.Node.Interface, true)
2022-01-25 04:46:38 +08:00
if err != nil {
ncutils.Log("error applying dns" + err.Error())
}
}
}()
2022-01-03 00:02:59 +08:00
}
2022-02-01 04:37:57 +08:00
// UpdatePeers -- mqtt message handler for peers/<Network>/<NodeID> topic
2022-01-26 23:40:39 +08:00
func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
go func() {
var peerUpdate models.PeerUpdate
2022-01-29 04:33:30 +08:00
var network = parseNetworkFromTopic(msg.Topic())
var cfg = config.ClientConfig{}
cfg.Network = network
cfg.ReadConfig()
data, dataErr := decryptMsg(&cfg, msg.Payload())
if dataErr != nil {
return
}
2022-01-30 04:02:37 +08:00
err := json.Unmarshal([]byte(data), &peerUpdate)
if err != nil {
ncutils.Log("error unmarshalling peer data")
return
}
2022-01-26 11:14:31 +08:00
// see if cache hit, if so skip
var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
2022-01-29 04:33:30 +08:00
if currentMessage == string(data) {
2022-01-26 11:14:31 +08:00
return
}
2022-01-29 04:33:30 +08:00
insert(peerUpdate.Network, lastPeerUpdate, string(data))
2022-01-20 04:00:03 +08:00
ncutils.Log("update peer handler")
2022-01-29 04:33:30 +08:00
2022-02-01 00:29:00 +08:00
file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
if err != nil {
ncutils.Log("error updating wireguard peers" + err.Error())
return
}
ncutils.Log("syncing conf to " + file)
2022-02-01 05:49:40 +08:00
//err = wireguard.SyncWGQuickConf(cfg.Node.Interface, file)
err = wireguard.SetPeers(cfg.Node.Interface, cfg.Node.PersistentKeepalive, peerUpdate.Peers)
2022-02-01 00:29:00 +08:00
if err != nil {
ncutils.Log("error syncing wg after peer update " + err.Error())
return
}
}()
}
// MonitorKeepalive - checks time last server keepalive received. If more than 3+ minutes, notify and resubscribe
func MonitorKeepalive(ctx context.Context, client mqtt.Client, cfg *config.ClientConfig) {
2022-01-28 03:48:10 +08:00
var id string
for _, servAddr := range cfg.NetworkSettings.DefaultServerAddrs {
if servAddr.IsLeader {
id = servAddr.ID
}
}
for {
select {
case <-ctx.Done():
return
case <-time.After(time.Second * 150):
if time.Since(keepalive[id]) > time.Second*200 { // more than 3+ minutes
2022-02-02 03:01:13 +08:00
ncutils.Log("server keepalive not recieved recently, resubscribe to message queue")
2022-02-01 12:18:58 +08:00
err := Resubscribe(client, cfg)
if err != nil {
ncutils.Log("closing " + err.Error())
}
}
}
}
2022-01-03 00:02:59 +08:00
}
// ServerKeepAlive -- handler to react to keepalive messages published by server
func ServerKeepAlive(client mqtt.Client, msg mqtt.Message) {
2022-02-01 06:21:31 +08:00
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
serverid, err := getID(msg.Topic())
if err != nil {
ncutils.Log("invalid ID in serverkeepalive topic")
}
keepalive[serverid] = time.Now()
2022-02-01 06:21:31 +08:00
// ncutils.Log("keepalive from server")
}
2022-01-26 11:14:31 +08:00
// Resubscribe --- handles resubscribing if needed
2022-01-26 23:40:39 +08:00
func Resubscribe(client mqtt.Client, cfg *config.ClientConfig) error {
2022-01-26 11:14:31 +08:00
if err := config.ModConfig(&cfg.Node); err == nil {
2022-01-26 23:40:39 +08:00
ncutils.Log("resubbing on network " + cfg.Node.Network)
2022-01-26 11:14:31 +08:00
client.Disconnect(250)
client = SetupMQTT(cfg)
2022-02-01 04:37:57 +08:00
if token := client.Subscribe(fmt.Sprintf("update/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, NodeUpdate); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log("error resubscribing to updates for " + cfg.Node.Network)
return token.Error()
2022-01-26 11:14:31 +08:00
}
if cfg.DebugOn {
ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
}
2022-02-01 04:37:57 +08:00
if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, UpdatePeers); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log("error resubscribing to peers for " + cfg.Node.Network)
return token.Error()
2022-01-26 11:14:31 +08:00
}
2022-01-31 07:38:15 +08:00
var id string
var found bool
2022-01-31 07:38:15 +08:00
for _, server := range cfg.NetworkSettings.DefaultServerAddrs {
if server.IsLeader {
id = server.ID
}
if server.Address != "" {
if token := client.Subscribe("serverkeepalive/"+id, 0, mqtt.MessageHandler(ServerKeepAlive)); token.Wait() && token.Error() != nil {
2022-02-01 12:18:58 +08:00
ncutils.Log("error resubscribing to serverkeepalive for " + cfg.Node.Network)
return token.Error()
2022-01-31 07:38:15 +08:00
}
found = true
2022-01-31 07:38:15 +08:00
if cfg.DebugOn {
ncutils.Log("subscribed to server keepalives for server " + id)
}
}
}
if !found {
ncutils.Log("leader not defined for network " + cfg.Network)
}
2022-01-26 11:14:31 +08:00
ncutils.Log("finished re subbing")
2022-01-26 23:40:39 +08:00
return nil
2022-01-26 11:14:31 +08:00
} else {
ncutils.Log("could not mod config when re-subbing")
2022-01-26 23:40:39 +08:00
return err
2022-01-26 11:14:31 +08:00
}
}
// UpdateKeys -- updates private key and returns new publickey
func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) error {
ncutils.Log("received message to update keys")
//potentiall blocking i/o so do this in a go routine
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
ncutils.Log("error generating privatekey " + err.Error())
return err
}
2022-01-23 00:38:56 +08:00
file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
ncutils.Log("error updating wireguard key " + err.Error())
return err
}
cfg.Node.PublicKey = key.PublicKey().String()
PublishNodeUpdate(cfg)
if err := config.ModConfig(&cfg.Node); err != nil {
ncutils.Log("error updating local config " + err.Error())
}
return nil
2022-01-03 00:02:59 +08:00
}
2022-01-04 07:27:13 +08:00
// Checkin -- go routine that checks for public or local ip changes, publishes changes
// if there are no updates, simply "pings" the server as a checkin
func Checkin(ctx context.Context, cfg *config.ClientConfig, network string) {
for {
select {
case <-ctx.Done():
ncutils.Log("Checkin cancelled")
return
//delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
2022-01-19 06:36:10 +08:00
case <-time.After(time.Second * 60):
2022-02-01 06:21:31 +08:00
// ncutils.Log("Checkin running")
//read latest config
cfg.ReadConfig()
if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
extIP, err := ncutils.GetPublicIP()
if err != nil {
ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
}
if cfg.Node.Endpoint != extIP && extIP != "" {
ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
cfg.Node.Endpoint = extIP
PublishNodeUpdate(cfg)
}
intIP, err := getPrivateAddr()
if err != nil {
ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
}
if cfg.Node.LocalAddress != intIP && intIP != "" {
ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
cfg.Node.LocalAddress = intIP
PublishNodeUpdate(cfg)
}
} else {
localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
if err != nil {
ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
}
if cfg.Node.Endpoint != localIP && localIP != "" {
ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
cfg.Node.Endpoint = localIP
PublishNodeUpdate(cfg)
}
2022-01-03 00:02:59 +08:00
}
Hello(cfg, network)
2022-02-01 06:21:31 +08:00
// ncutils.Log("Checkin complete")
2022-01-03 00:02:59 +08:00
}
}
}
// PublishNodeUpdates -- saves node and pushes changes to broker
func PublishNodeUpdate(cfg *config.ClientConfig) {
if err := config.Write(cfg, cfg.Network); err != nil {
ncutils.Log("error saving configuration: " + err.Error())
}
data, err := json.Marshal(cfg.Node)
if err != nil {
ncutils.Log("error marshling node update: " + err.Error())
2022-01-03 00:02:59 +08:00
}
2022-01-29 04:33:30 +08:00
if err = publish(cfg, fmt.Sprintf("update/%s", cfg.Node.ID), data); err != nil {
ncutils.Log(fmt.Sprintf("error publishing endpoint update, %v", err))
}
}
2022-01-04 07:27:13 +08:00
// Hello -- ping the broker to let server know node is alive and doing fine
func Hello(cfg *config.ClientConfig, network string) {
2022-01-29 04:33:30 +08:00
if err := publish(cfg, fmt.Sprintf("ping/%s", cfg.Node.ID), []byte("hello world!")); err != nil {
ncutils.Log(fmt.Sprintf("error publishing ping, %v", err))
2022-01-29 04:33:30 +08:00
}
}
func publish(cfg *config.ClientConfig, dest string, msg []byte) error {
2022-01-30 04:02:37 +08:00
// setup the keys
trafficPrivKey, err := auth.RetrieveTrafficKey(cfg.Node.Network)
if err != nil {
return err
}
serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
if err != nil {
return err
}
client := SetupMQTT(cfg)
2022-01-29 04:33:30 +08:00
defer client.Disconnect(250)
2022-01-30 04:02:37 +08:00
encrypted, err := ncutils.BoxEncrypt(msg, serverPubKey, trafficPrivKey)
if err != nil {
return err
2022-01-29 04:33:30 +08:00
}
2022-01-30 04:02:37 +08:00
2022-01-29 04:33:30 +08:00
if token := client.Publish(dest, 0, false, encrypted); token.Wait() && token.Error() != nil {
return token.Error()
}
2022-01-29 04:33:30 +08:00
return nil
}
func parseNetworkFromTopic(topic string) string {
return strings.Split(topic, "/")[1]
}
func decryptMsg(cfg *config.ClientConfig, msg []byte) ([]byte, error) {
2022-01-30 04:02:37 +08:00
// setup the keys
diskKey, keyErr := auth.RetrieveTrafficKey(cfg.Node.Network)
if keyErr != nil {
return nil, keyErr
2022-01-29 04:33:30 +08:00
}
2022-01-30 04:02:37 +08:00
serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
if err != nil {
2022-01-29 04:33:30 +08:00
return nil, err
}
2022-01-30 04:02:37 +08:00
return ncutils.BoxDecrypt(msg, serverPubKey, diskKey)
}
2022-01-26 11:14:31 +08:00
2022-01-26 23:40:39 +08:00
func shouldResub(currentServers, newServers []models.ServerAddr) bool {
2022-01-26 11:14:31 +08:00
if len(currentServers) != len(newServers) {
2022-01-26 23:40:39 +08:00
return true
2022-01-26 11:14:31 +08:00
}
for _, srv := range currentServers {
2022-01-26 23:40:39 +08:00
if !ncutils.ServerAddrSliceContains(newServers, srv) {
2022-01-26 11:14:31 +08:00
return true
}
}
return false
}
func getID(topic string) (string, error) {
parts := strings.Split(topic, "/")
count := len(parts)
if count == 1 {
return "", errors.New("invalid topic")
}
//the last part of the topic will be the network.ID
return parts[count-1], nil
}