mqhandlers.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package functions
  2. import (
  3. "encoding/json"
  4. "log"
  5. "runtime"
  6. "strings"
  7. "time"
  8. mqtt "github.com/eclipse/paho.mqtt.golang"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/netclient/config"
  12. "github.com/gravitl/netmaker/netclient/local"
  13. "github.com/gravitl/netmaker/netclient/ncutils"
  14. "github.com/gravitl/netmaker/netclient/wireguard"
  15. "github.com/guumaster/hostctl/pkg/file"
  16. "github.com/guumaster/hostctl/pkg/parser"
  17. "github.com/guumaster/hostctl/pkg/types"
  18. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  19. )
  20. // All -- mqtt message hander for all ('#') topics
  21. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  22. logger.Log(0, "default message handler -- received message but not handling")
  23. logger.Log(0, "Topic: "+string(msg.Topic()))
  24. //logger.Log(0, "Message: " + string(msg.Payload()))
  25. }
  26. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  27. func NodeUpdate(client mqtt.Client, msg mqtt.Message) {
  28. var newNode models.Node
  29. var nodeCfg config.ClientConfig
  30. var network = parseNetworkFromTopic(msg.Topic())
  31. nodeCfg.Network = network
  32. nodeCfg.ReadConfig()
  33. data, dataErr := decryptMsg(&nodeCfg, msg.Payload())
  34. if dataErr != nil {
  35. return
  36. }
  37. err := json.Unmarshal([]byte(data), &newNode)
  38. if err != nil {
  39. logger.Log(0, "error unmarshalling node update data"+err.Error())
  40. return
  41. }
  42. logger.Log(0, "received message to update node "+newNode.Name)
  43. // see if cache hit, if so skip
  44. var currentMessage = read(newNode.Network, lastNodeUpdate)
  45. if currentMessage == string(data) {
  46. return
  47. }
  48. insert(newNode.Network, lastNodeUpdate, string(data)) // store new message in cache
  49. // ensure that OS never changes
  50. newNode.OS = runtime.GOOS
  51. // check if interface needs to delta
  52. ifaceDelta := ncutils.IfaceDelta(&nodeCfg.Node, &newNode)
  53. shouldDNSChange := nodeCfg.Node.DNSOn != newNode.DNSOn
  54. hubChange := nodeCfg.Node.IsHub != newNode.IsHub
  55. keepaliveChange := nodeCfg.Node.PersistentKeepalive != newNode.PersistentKeepalive
  56. nodeCfg.Node = newNode
  57. switch newNode.Action {
  58. case models.NODE_DELETE:
  59. logger.Log(0, "received delete request for %s", nodeCfg.Node.Name)
  60. unsubscribeNode(client, &nodeCfg)
  61. if err = LeaveNetwork(nodeCfg.Node.Network, true); err != nil {
  62. if !strings.Contains("rpc error", err.Error()) {
  63. logger.Log(0, "failed to leave, please check that local files for network", nodeCfg.Node.Network, "were removed")
  64. return
  65. }
  66. }
  67. logger.Log(0, nodeCfg.Node.Name, " was removed")
  68. return
  69. case models.NODE_UPDATE_KEY:
  70. // == get the current key for node ==
  71. oldPrivateKey, retErr := wireguard.RetrievePrivKey(nodeCfg.Network)
  72. if retErr != nil {
  73. break
  74. }
  75. if err := UpdateKeys(&nodeCfg, client); err != nil {
  76. logger.Log(0, "err updating wireguard keys, reusing last key\n", err.Error())
  77. if key, parseErr := wgtypes.ParseKey(oldPrivateKey); parseErr == nil {
  78. wireguard.StorePrivKey(key.String(), nodeCfg.Network)
  79. nodeCfg.Node.PublicKey = key.PublicKey().String()
  80. }
  81. }
  82. ifaceDelta = true
  83. case models.NODE_FORCE_UPDATE:
  84. ifaceDelta = true
  85. case models.NODE_NOOP:
  86. default:
  87. }
  88. // Save new config
  89. nodeCfg.Node.Action = models.NODE_NOOP
  90. if err := config.Write(&nodeCfg, nodeCfg.Network); err != nil {
  91. logger.Log(0, "error updating node configuration: ", err.Error())
  92. }
  93. nameserver := nodeCfg.Server.CoreDNSAddr
  94. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  95. if err != nil {
  96. logger.Log(0, "error reading PrivateKey "+err.Error())
  97. return
  98. }
  99. file := ncutils.GetNetclientPathSpecific() + nodeCfg.Node.Interface + ".conf"
  100. if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
  101. logger.Log(0, "error updating wireguard config "+err.Error())
  102. return
  103. }
  104. if keepaliveChange {
  105. wireguard.UpdateKeepAlive(file, newNode.PersistentKeepalive)
  106. }
  107. if ifaceDelta { // if a change caused an ifacedelta we need to notify the server to update the peers
  108. logger.Log(0, "applying WG conf to "+file)
  109. if ncutils.IsWindows() {
  110. wireguard.RemoveConfGraceful(nodeCfg.Node.Interface)
  111. }
  112. err = wireguard.ApplyConf(&nodeCfg.Node, nodeCfg.Node.Interface, file)
  113. if err != nil {
  114. logger.Log(0, "error restarting wg after node update "+err.Error())
  115. return
  116. }
  117. time.Sleep(time.Second >> 0)
  118. // if newNode.DNSOn == "yes" {
  119. // for _, server := range newNode.NetworkSettings.DefaultServerAddrs {
  120. // if server.IsLeader {
  121. // go local.SetDNSWithRetry(newNode, server.Address)
  122. // break
  123. // }
  124. // }
  125. // }
  126. doneErr := publishSignal(&nodeCfg, ncutils.DONE)
  127. if doneErr != nil {
  128. logger.Log(0, "could not notify server to update peers after interface change")
  129. } else {
  130. logger.Log(0, "signalled finished interface update to server")
  131. }
  132. } else if hubChange {
  133. doneErr := publishSignal(&nodeCfg, ncutils.DONE)
  134. if doneErr != nil {
  135. logger.Log(0, "could not notify server to update peers after hub change")
  136. } else {
  137. logger.Log(0, "signalled finished hub update to server")
  138. }
  139. }
  140. //deal with DNS
  141. if newNode.DNSOn != "yes" && shouldDNSChange && nodeCfg.Node.Interface != "" {
  142. logger.Log(0, "settng DNS off")
  143. if err := removeHostDNS(nodeCfg.Network, ncutils.IsWindows()); err != nil {
  144. logger.Log(0, "error removing netmaker profile from /etc/hosts "+err.Error())
  145. }
  146. // _, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+nodeCfg.Node.Interface, true)
  147. // if err != nil {
  148. // logger.Log(0, "error applying dns" + err.Error())
  149. // }
  150. }
  151. _ = UpdateLocalListenPort(&nodeCfg)
  152. }
  153. // UpdatePeers -- mqtt message handler for peers/<Network>/<NodeID> topic
  154. func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
  155. var peerUpdate models.PeerUpdate
  156. var network = parseNetworkFromTopic(msg.Topic())
  157. var cfg = config.ClientConfig{}
  158. cfg.Network = network
  159. cfg.ReadConfig()
  160. data, dataErr := decryptMsg(&cfg, msg.Payload())
  161. if dataErr != nil {
  162. return
  163. }
  164. err := json.Unmarshal([]byte(data), &peerUpdate)
  165. if err != nil {
  166. logger.Log(0, "error unmarshalling peer data")
  167. return
  168. }
  169. // see if cached hit, if so skip
  170. var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
  171. if currentMessage == string(data) {
  172. return
  173. }
  174. insert(peerUpdate.Network, lastPeerUpdate, string(data))
  175. // check version
  176. log.Println(peerUpdate.ServerVersion)
  177. if peerUpdate.ServerVersion != ncutils.Version {
  178. logger.Log(0, "server/client version mismatch server: ", peerUpdate.ServerVersion, " client: ", ncutils.Version)
  179. }
  180. log.Println(cfg.Server.Version)
  181. if peerUpdate.ServerVersion != cfg.Server.Version {
  182. logger.Log(1, "updating server version")
  183. cfg.Server.Version = peerUpdate.ServerVersion
  184. config.Write(&cfg, cfg.Network)
  185. }
  186. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  187. err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
  188. if err != nil {
  189. logger.Log(0, "error updating wireguard peers"+err.Error())
  190. return
  191. }
  192. queryAddr := cfg.Node.PrimaryAddress()
  193. //err = wireguard.SyncWGQuickConf(cfg.Node.Interface, file)
  194. var iface = cfg.Node.Interface
  195. if ncutils.IsMac() {
  196. iface, err = local.GetMacIface(queryAddr)
  197. if err != nil {
  198. logger.Log(0, "error retrieving mac iface: "+err.Error())
  199. return
  200. }
  201. }
  202. err = wireguard.SetPeers(iface, &cfg.Node, peerUpdate.Peers)
  203. if err != nil {
  204. logger.Log(0, "error syncing wg after peer update: "+err.Error())
  205. return
  206. }
  207. logger.Log(0, "received peer update for node "+cfg.Node.Name+" "+cfg.Node.Network)
  208. if cfg.Node.DNSOn == "yes" {
  209. if err := setHostDNS(peerUpdate.DNS, cfg.Node.Network, ncutils.IsWindows()); err != nil {
  210. logger.Log(0, "error updating /etc/hosts "+err.Error())
  211. return
  212. }
  213. } else {
  214. if err := removeHostDNS(cfg.Node.Network, ncutils.IsWindows()); err != nil {
  215. logger.Log(0, "error removing profile from /etc/hosts "+err.Error())
  216. return
  217. }
  218. }
  219. _ = UpdateLocalListenPort(&cfg)
  220. }
  221. func setHostDNS(dns, iface string, windows bool) error {
  222. etchosts := "/etc/hosts"
  223. if windows {
  224. etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
  225. }
  226. dnsdata := strings.NewReader(dns)
  227. profile, err := parser.ParseProfile(dnsdata)
  228. if err != nil {
  229. return err
  230. }
  231. hosts, err := file.NewFile(etchosts)
  232. if err != nil {
  233. return err
  234. }
  235. profile.Name = iface
  236. profile.Status = types.Enabled
  237. if err := hosts.ReplaceProfile(profile); err != nil {
  238. return err
  239. }
  240. if err := hosts.Flush(); err != nil {
  241. return err
  242. }
  243. return nil
  244. }
  245. func removeHostDNS(iface string, windows bool) error {
  246. etchosts := "/etc/hosts"
  247. if windows {
  248. etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
  249. }
  250. hosts, err := file.NewFile(etchosts)
  251. if err != nil {
  252. return err
  253. }
  254. if err := hosts.RemoveProfile(iface); err != nil {
  255. if err == types.ErrUnknownProfile {
  256. return nil
  257. }
  258. return err
  259. }
  260. if err := hosts.Flush(); err != nil {
  261. return err
  262. }
  263. return nil
  264. }