daemon.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package functions
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "os"
  8. "os/signal"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. mqtt "github.com/eclipse/paho.mqtt.golang"
  15. "github.com/gravitl/netmaker/models"
  16. "github.com/gravitl/netmaker/netclient/auth"
  17. "github.com/gravitl/netmaker/netclient/config"
  18. "github.com/gravitl/netmaker/netclient/local"
  19. "github.com/gravitl/netmaker/netclient/ncutils"
  20. "github.com/gravitl/netmaker/netclient/wireguard"
  21. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  22. )
  23. var messageCache = make(map[string]string, 20)
  24. const lastNodeUpdate = "lnu"
  25. const lastPeerUpdate = "lpu"
  26. func insert(network, which, cache string) {
  27. var mu sync.Mutex
  28. mu.Lock()
  29. defer mu.Unlock()
  30. messageCache[fmt.Sprintf("%s%s", network, which)] = cache
  31. }
  32. func read(network, which string) string {
  33. return messageCache[fmt.Sprintf("%s%s", network, which)]
  34. }
  35. // Daemon runs netclient daemon from command line
  36. func Daemon() error {
  37. ctx, cancel := context.WithCancel(context.Background())
  38. networks, err := ncutils.GetSystemNetworks()
  39. if err != nil {
  40. cancel()
  41. return err
  42. }
  43. for _, network := range networks {
  44. go MessageQueue(ctx, network)
  45. }
  46. quit := make(chan os.Signal, 1)
  47. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  48. <-quit
  49. cancel()
  50. ncutils.Log("all done")
  51. return nil
  52. }
  53. // SetupMQTT creates a connection to broker and return client
  54. func SetupMQTT(cfg *config.ClientConfig) mqtt.Client {
  55. opts := mqtt.NewClientOptions()
  56. for _, server := range cfg.Node.NetworkSettings.DefaultServerAddrs {
  57. if server.Address != "" && server.IsLeader {
  58. ncutils.Log(fmt.Sprintf("adding server (%s) to listen on network %s \n", server.Address, cfg.Node.Network))
  59. opts.AddBroker(server.Address + ":1883")
  60. break
  61. }
  62. }
  63. opts.SetDefaultPublishHandler(All)
  64. client := mqtt.NewClient(opts)
  65. if token := client.Connect(); token.Wait() && token.Error() != nil {
  66. log.Fatal(token.Error())
  67. }
  68. return client
  69. }
  70. // MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
  71. func MessageQueue(ctx context.Context, network string) {
  72. ncutils.Log("netclient go routine started for " + network)
  73. var cfg config.ClientConfig
  74. cfg.Network = network
  75. cfg.ReadConfig()
  76. ncutils.Log("daemon started for network:" + network)
  77. client := SetupMQTT(&cfg)
  78. if cfg.DebugOn {
  79. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  80. log.Fatal(token.Error())
  81. }
  82. ncutils.Log("subscribed to all topics for debugging purposes")
  83. }
  84. if token := client.Subscribe(fmt.Sprintf("update/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
  85. log.Fatal(token.Error())
  86. }
  87. if cfg.DebugOn {
  88. ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s \n", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  89. }
  90. if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
  91. log.Fatal(token.Error())
  92. }
  93. if cfg.DebugOn {
  94. ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s \n", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  95. }
  96. defer client.Disconnect(250)
  97. go Checkin(ctx, &cfg, network)
  98. <-ctx.Done()
  99. ncutils.Log("shutting down daemon")
  100. }
  101. // All -- mqtt message hander for all ('#') topics
  102. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  103. ncutils.Log("default message handler -- received message but not handling")
  104. ncutils.Log("Topic: " + string(msg.Topic()))
  105. //ncutils.Log("Message: " + string(msg.Payload()))
  106. }
  107. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  108. func NodeUpdate(client mqtt.Client, msg mqtt.Message) {
  109. //potentiall blocking i/o so do this in a go routine
  110. go func() {
  111. var newNode models.Node
  112. var cfg config.ClientConfig
  113. var network = parseNetworkFromTopic(msg.Topic())
  114. cfg.Network = network
  115. cfg.ReadConfig()
  116. data, dataErr := decryptMsg(&cfg, msg.Payload())
  117. if dataErr != nil {
  118. return
  119. }
  120. err := json.Unmarshal([]byte(data), &newNode)
  121. if err != nil {
  122. ncutils.Log("error unmarshalling node update data" + err.Error())
  123. return
  124. }
  125. ncutils.Log("received message to update node " + newNode.Name)
  126. // see if cache hit, if so skip
  127. var currentMessage = read(newNode.Network, lastNodeUpdate)
  128. if currentMessage == string(data) {
  129. return
  130. }
  131. insert(newNode.Network, lastNodeUpdate, string(data))
  132. //check if interface name has changed if so delete.
  133. if cfg.Node.Interface != newNode.Interface {
  134. if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
  135. ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
  136. }
  137. }
  138. newNode.PullChanges = "no"
  139. //ensure that OS never changes
  140. newNode.OS = runtime.GOOS
  141. cfg.Node = newNode
  142. switch newNode.Action {
  143. case models.NODE_DELETE:
  144. if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
  145. ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
  146. return
  147. }
  148. if token := client.Unsubscribe("update/"+newNode.ID, "update/peers/"+newNode.ID); token.Wait() && token.Error() != nil {
  149. ncutils.PrintLog("error unsubscribing during node deletion", 1)
  150. }
  151. return
  152. case models.NODE_UPDATE_KEY:
  153. if err := UpdateKeys(&cfg, client); err != nil {
  154. ncutils.PrintLog("err updating wireguard keys: "+err.Error(), 1)
  155. }
  156. case models.NODE_NOOP:
  157. default:
  158. }
  159. //Save new config
  160. if err := config.Write(&cfg, cfg.Network); err != nil {
  161. ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
  162. }
  163. nameserver := cfg.Server.CoreDNSAddr
  164. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  165. if err != nil {
  166. ncutils.Log("error reading PrivateKey " + err.Error())
  167. return
  168. }
  169. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  170. if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
  171. ncutils.Log("error updating wireguard config " + err.Error())
  172. return
  173. }
  174. ncutils.Log("applyWGQuickConf to " + file)
  175. err = wireguard.ApplyWGQuickConf(file)
  176. if err != nil {
  177. ncutils.Log("error restarting wg after node update " + err.Error())
  178. return
  179. }
  180. //deal with DNS
  181. if newNode.DNSOn == "yes" {
  182. ncutils.Log("setting up DNS")
  183. if err = local.UpdateDNS(cfg.Node.Interface, cfg.Network, cfg.Server.CoreDNSAddr); err != nil {
  184. ncutils.Log("error applying dns" + err.Error())
  185. }
  186. } else {
  187. ncutils.Log("settng DNS off")
  188. _, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+cfg.Node.Interface, true)
  189. if err != nil {
  190. ncutils.Log("error applying dns" + err.Error())
  191. }
  192. }
  193. }()
  194. }
  195. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  196. func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
  197. go func() {
  198. var peerUpdate models.PeerUpdate
  199. var network = parseNetworkFromTopic(msg.Topic())
  200. var cfg = config.ClientConfig{}
  201. cfg.Network = network
  202. cfg.ReadConfig()
  203. data, dataErr := decryptMsg(&cfg, msg.Payload())
  204. if dataErr != nil {
  205. return
  206. }
  207. err := json.Unmarshal([]byte(data), &peerUpdate)
  208. if err != nil {
  209. ncutils.Log("error unmarshalling peer data")
  210. return
  211. }
  212. // see if cache hit, if so skip
  213. var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
  214. if currentMessage == string(data) {
  215. return
  216. }
  217. insert(peerUpdate.Network, lastPeerUpdate, string(data))
  218. ncutils.Log("update peer handler")
  219. var shouldReSub = shouldResub(cfg.Node.NetworkSettings.DefaultServerAddrs, peerUpdate.ServerAddrs)
  220. if shouldReSub {
  221. Resubscribe(client, &cfg)
  222. cfg.Node.NetworkSettings.DefaultServerAddrs = peerUpdate.ServerAddrs
  223. }
  224. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  225. err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
  226. if err != nil {
  227. ncutils.Log("error updating wireguard peers" + err.Error())
  228. return
  229. }
  230. ncutils.Log("applyWGQuickConf to " + file)
  231. err = wireguard.ApplyWGQuickConf(file)
  232. if err != nil {
  233. ncutils.Log("error restarting wg after peer update " + err.Error())
  234. return
  235. }
  236. }()
  237. }
  238. // Resubscribe --- handles resubscribing if needed
  239. func Resubscribe(client mqtt.Client, cfg *config.ClientConfig) error {
  240. if err := config.ModConfig(&cfg.Node); err == nil {
  241. ncutils.Log("resubbing on network " + cfg.Node.Network)
  242. client.Disconnect(250)
  243. client = SetupMQTT(cfg)
  244. if token := client.Subscribe("update/"+cfg.Node.ID, 0, NodeUpdate); token.Wait() && token.Error() != nil {
  245. log.Fatal(token.Error())
  246. }
  247. if cfg.DebugOn {
  248. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
  249. }
  250. if token := client.Subscribe("update/peers/"+cfg.Node.ID, 0, UpdatePeers); token.Wait() && token.Error() != nil {
  251. log.Fatal(token.Error())
  252. }
  253. ncutils.Log("finished re subbing")
  254. return nil
  255. } else {
  256. ncutils.Log("could not mod config when re-subbing")
  257. return err
  258. }
  259. }
  260. // UpdateKeys -- updates private key and returns new publickey
  261. func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) error {
  262. ncutils.Log("received message to update keys")
  263. //potentiall blocking i/o so do this in a go routine
  264. key, err := wgtypes.GeneratePrivateKey()
  265. if err != nil {
  266. ncutils.Log("error generating privatekey " + err.Error())
  267. return err
  268. }
  269. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  270. if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
  271. ncutils.Log("error updating wireguard key " + err.Error())
  272. return err
  273. }
  274. cfg.Node.PublicKey = key.PublicKey().String()
  275. PublishNodeUpdate(cfg)
  276. if err := config.ModConfig(&cfg.Node); err != nil {
  277. ncutils.Log("error updating local config " + err.Error())
  278. }
  279. return nil
  280. }
  281. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  282. // if there are no updates, simply "pings" the server as a checkin
  283. func Checkin(ctx context.Context, cfg *config.ClientConfig, network string) {
  284. for {
  285. select {
  286. case <-ctx.Done():
  287. ncutils.Log("Checkin cancelled")
  288. return
  289. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  290. case <-time.After(time.Second * 60):
  291. ncutils.Log("Checkin running")
  292. //read latest config
  293. cfg.ReadConfig()
  294. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  295. extIP, err := ncutils.GetPublicIP()
  296. if err != nil {
  297. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  298. }
  299. if cfg.Node.Endpoint != extIP && extIP != "" {
  300. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  301. cfg.Node.Endpoint = extIP
  302. PublishNodeUpdate(cfg)
  303. }
  304. intIP, err := getPrivateAddr()
  305. if err != nil {
  306. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  307. }
  308. if cfg.Node.LocalAddress != intIP && intIP != "" {
  309. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  310. cfg.Node.LocalAddress = intIP
  311. PublishNodeUpdate(cfg)
  312. }
  313. } else {
  314. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  315. if err != nil {
  316. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  317. }
  318. if cfg.Node.Endpoint != localIP && localIP != "" {
  319. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  320. cfg.Node.Endpoint = localIP
  321. PublishNodeUpdate(cfg)
  322. }
  323. }
  324. Hello(cfg, network)
  325. ncutils.Log("Checkin complete")
  326. }
  327. }
  328. }
  329. // PublishNodeUpdates -- saves node and pushes changes to broker
  330. func PublishNodeUpdate(cfg *config.ClientConfig) {
  331. if err := config.Write(cfg, cfg.Network); err != nil {
  332. ncutils.Log("error saving configuration" + err.Error())
  333. }
  334. data, err := json.Marshal(cfg.Node)
  335. if err != nil {
  336. ncutils.Log("error marshling node update " + err.Error())
  337. }
  338. if err = publish(cfg, fmt.Sprintf("update/%s", cfg.Node.ID), data); err != nil {
  339. ncutils.Log(fmt.Sprintf("error publishing endpoint update, %v \n", err))
  340. }
  341. }
  342. // Hello -- ping the broker to let server know node is alive and doing fine
  343. func Hello(cfg *config.ClientConfig, network string) {
  344. if err := publish(cfg, fmt.Sprintf("ping/%s", cfg.Node.ID), []byte("hello world!")); err != nil {
  345. ncutils.Log(fmt.Sprintf("error publishing ping, %v \n", err))
  346. }
  347. }
  348. func publish(cfg *config.ClientConfig, dest string, msg []byte) error {
  349. // setup the keys
  350. trafficPrivKey, err := auth.RetrieveTrafficKey(cfg.Node.Network)
  351. if err != nil {
  352. return err
  353. }
  354. serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
  355. if err != nil {
  356. return err
  357. }
  358. client := SetupMQTT(cfg)
  359. defer client.Disconnect(250)
  360. encrypted, err := ncutils.BoxEncrypt(msg, serverPubKey, trafficPrivKey)
  361. if err != nil {
  362. return err
  363. }
  364. if token := client.Publish(dest, 0, false, encrypted); token.Wait() && token.Error() != nil {
  365. return token.Error()
  366. }
  367. return nil
  368. }
  369. func parseNetworkFromTopic(topic string) string {
  370. return strings.Split(topic, "/")[1]
  371. }
  372. func decryptMsg(cfg *config.ClientConfig, msg []byte) ([]byte, error) {
  373. // setup the keys
  374. diskKey, keyErr := auth.RetrieveTrafficKey(cfg.Node.Network)
  375. if keyErr != nil {
  376. return nil, keyErr
  377. }
  378. serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return ncutils.BoxDecrypt(msg, serverPubKey, diskKey)
  383. }
  384. func shouldResub(currentServers, newServers []models.ServerAddr) bool {
  385. if len(currentServers) != len(newServers) {
  386. return true
  387. }
  388. for _, srv := range currentServers {
  389. if !ncutils.ServerAddrSliceContains(newServers, srv) {
  390. return true
  391. }
  392. }
  393. return false
  394. }