config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package config
  2. import (
  3. //"github.com/davecgh/go-spew/spew"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/netclient/ncutils"
  13. "github.com/urfave/cli/v2"
  14. "gopkg.in/yaml.v3"
  15. )
  16. // GlobalConfig - struct for handling IntClients currently
  17. type GlobalConfig struct {
  18. GRPCWireGuard string `yaml:"grpcwg"`
  19. Client models.IntClient
  20. }
  21. // ClientConfig - struct for dealing with client configuration
  22. type ClientConfig struct {
  23. Server ServerConfig `yaml:"server"`
  24. Node models.Node `yaml:"node"`
  25. NetworkSettings models.Network `yaml:"networksettings"`
  26. Network string `yaml:"network"`
  27. Daemon string `yaml:"daemon"`
  28. OperatingSystem string `yaml:"operatingsystem"`
  29. DebugJoin bool `yaml:"debugjoin"`
  30. FWMark int32 `yaml:"fwmark"`
  31. }
  32. // ServerConfig - struct for dealing with the server information for a netclient
  33. type ServerConfig struct {
  34. CoreDNSAddr string `yaml:"corednsaddr"`
  35. GRPCAddress string `yaml:"grpcaddress"`
  36. APIAddress string `yaml:"apiaddress"`
  37. AccessKey string `yaml:"accesskey"`
  38. GRPCSSL string `yaml:"grpcssl"`
  39. GRPCWireGuard string `yaml:"grpcwg"`
  40. CheckinInterval string `yaml:"checkininterval"`
  41. }
  42. // Write - writes the config of a client to disk
  43. func Write(config *ClientConfig, network string) error {
  44. if network == "" {
  45. err := errors.New("no network provided - exiting")
  46. return err
  47. }
  48. _, err := os.Stat(ncutils.GetNetclientPath() + "/config")
  49. if os.IsNotExist(err) {
  50. os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
  51. } else if err != nil {
  52. return err
  53. }
  54. home := ncutils.GetNetclientPathSpecific()
  55. file := fmt.Sprintf(home + "netconfig-" + network)
  56. f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  57. if err != nil {
  58. return err
  59. }
  60. defer f.Close()
  61. err = yaml.NewEncoder(f).Encode(config)
  62. if err != nil {
  63. return err
  64. }
  65. return err
  66. }
  67. // WriteServer - writes the config of a server to disk for client
  68. func WriteServer(server string, accesskey string, network string) error {
  69. if network == "" {
  70. err := errors.New("no network provided - exiting")
  71. return err
  72. }
  73. nofile := false
  74. //home, err := homedir.Dir()
  75. _, err := os.Stat(ncutils.GetNetclientPath() + "/config")
  76. if os.IsNotExist(err) {
  77. os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
  78. } else if err != nil {
  79. fmt.Println("couldnt find or create", ncutils.GetNetclientPath())
  80. return err
  81. }
  82. home := ncutils.GetNetclientPathSpecific()
  83. file := fmt.Sprintf(home + "netconfig-" + network)
  84. //f, err := os.Open(file)
  85. f, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, 0666)
  86. //f, err := ioutil.ReadFile(file)
  87. if err != nil {
  88. fmt.Println("couldnt open netconfig-" + network)
  89. fmt.Println(err)
  90. nofile = true
  91. //err = nil
  92. return err
  93. }
  94. defer f.Close()
  95. //cfg := &ClientConfig{}
  96. var cfg ClientConfig
  97. if !nofile {
  98. fmt.Println("Writing to existing config file at " + home + "netconfig-" + network)
  99. decoder := yaml.NewDecoder(f)
  100. err = decoder.Decode(&cfg)
  101. //err = yaml.Unmarshal(f, &cfg)
  102. if err != nil {
  103. //fmt.Println(err)
  104. //return err
  105. }
  106. f.Close()
  107. f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
  108. if err != nil {
  109. fmt.Println("couldnt open netconfig")
  110. fmt.Println(err)
  111. nofile = true
  112. //err = nil
  113. return err
  114. }
  115. defer f.Close()
  116. if err != nil {
  117. fmt.Println("trouble opening file")
  118. fmt.Println(err)
  119. }
  120. cfg.Server.GRPCAddress = server
  121. cfg.Server.AccessKey = accesskey
  122. err = yaml.NewEncoder(f).Encode(cfg)
  123. //_, err = yaml.Marshal(f, &cfg)
  124. if err != nil {
  125. fmt.Println("trouble encoding file")
  126. return err
  127. }
  128. } else {
  129. fmt.Println("Creating new config file at " + home + "netconfig-" + network)
  130. cfg.Server.GRPCAddress = server
  131. cfg.Server.AccessKey = accesskey
  132. newf, err := os.Create(home + "netconfig-" + network)
  133. err = yaml.NewEncoder(newf).Encode(cfg)
  134. defer newf.Close()
  135. if err != nil {
  136. return err
  137. }
  138. }
  139. return err
  140. }
  141. // ClientConfig.ReadConfig - used to read config from client disk into memory
  142. func (config *ClientConfig) ReadConfig() {
  143. nofile := false
  144. //home, err := homedir.Dir()
  145. home := ncutils.GetNetclientPathSpecific()
  146. file := fmt.Sprintf(home + "netconfig-" + config.Network)
  147. //f, err := os.Open(file)
  148. f, err := os.OpenFile(file, os.O_RDONLY, 0666)
  149. if err != nil {
  150. fmt.Println("trouble opening file")
  151. fmt.Println(err)
  152. nofile = true
  153. //fmt.Println("Could not access " + home + "/.netconfig, proceeding...")
  154. }
  155. defer f.Close()
  156. //var cfg ClientConfig
  157. if !nofile {
  158. decoder := yaml.NewDecoder(f)
  159. err = decoder.Decode(&config)
  160. if err != nil {
  161. fmt.Println("no config or invalid")
  162. fmt.Println(err)
  163. log.Fatal(err)
  164. } else {
  165. config.Node.SetID()
  166. //config = cfg
  167. }
  168. }
  169. }
  170. // ModConfig - overwrites the node inside client config on disk
  171. func ModConfig(node *models.Node) error {
  172. network := node.Network
  173. networksettings := node.NetworkSettings
  174. if network == "" {
  175. return errors.New("no network provided")
  176. }
  177. var modconfig ClientConfig
  178. var err error
  179. if FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network) {
  180. useconfig, err := ReadConfig(network)
  181. if err != nil {
  182. return err
  183. }
  184. modconfig = *useconfig
  185. }
  186. modconfig.Node = (*node)
  187. modconfig.NetworkSettings = (networksettings)
  188. err = Write(&modconfig, network)
  189. return err
  190. }
  191. // ModConfig - overwrites the node inside client config on disk
  192. func SaveBackup(network string) error {
  193. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  194. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  195. if FileExists(configPath) {
  196. input, err := ioutil.ReadFile(configPath)
  197. if err != nil {
  198. ncutils.Log("failed to read " + configPath + " to make a backup")
  199. return err
  200. }
  201. if err = ioutil.WriteFile(backupPath, input, 0644); err != nil {
  202. ncutils.Log("failed to copy backup to " + backupPath)
  203. return err
  204. }
  205. }
  206. return nil
  207. }
  208. // ReplaceWithBackup - replaces netconfig file with backup
  209. func ReplaceWithBackup(network string) error {
  210. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  211. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  212. if FileExists(backupPath) {
  213. input, err := ioutil.ReadFile(backupPath)
  214. if err != nil {
  215. ncutils.Log("failed to read file " + backupPath + " to backup network: " + network)
  216. return err
  217. }
  218. if err = ioutil.WriteFile(configPath, input, 0644); err != nil {
  219. ncutils.Log("failed backup " + backupPath + " to " + configPath)
  220. return err
  221. }
  222. }
  223. ncutils.Log("used backup file for network: " + network)
  224. return nil
  225. }
  226. // GetCLIConfig - gets the cli flags as a config
  227. func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
  228. var cfg ClientConfig
  229. if c.String("token") != "" {
  230. tokenbytes, err := base64.StdEncoding.DecodeString(c.String("token"))
  231. if err != nil {
  232. log.Println("error decoding token")
  233. return cfg, "", err
  234. }
  235. var accesstoken models.AccessToken
  236. if err := json.Unmarshal(tokenbytes, &accesstoken); err != nil {
  237. log.Println("error converting token json to object", tokenbytes)
  238. return cfg, "", err
  239. }
  240. if accesstoken.ServerConfig.APIConnString != "" {
  241. cfg.Server.APIAddress = accesstoken.ServerConfig.APIConnString
  242. } else {
  243. cfg.Server.APIAddress = accesstoken.ServerConfig.APIHost
  244. if accesstoken.ServerConfig.APIPort != "" {
  245. cfg.Server.APIAddress = cfg.Server.APIAddress + ":" + accesstoken.ServerConfig.APIPort
  246. }
  247. }
  248. if accesstoken.ServerConfig.GRPCConnString != "" {
  249. cfg.Server.GRPCAddress = accesstoken.ServerConfig.GRPCConnString
  250. } else {
  251. cfg.Server.GRPCAddress = accesstoken.ServerConfig.GRPCHost
  252. if accesstoken.ServerConfig.GRPCPort != "" {
  253. cfg.Server.GRPCAddress = cfg.Server.GRPCAddress + ":" + accesstoken.ServerConfig.GRPCPort
  254. }
  255. }
  256. cfg.Network = accesstoken.ClientConfig.Network
  257. cfg.Node.Network = accesstoken.ClientConfig.Network
  258. cfg.Server.AccessKey = accesstoken.ClientConfig.Key
  259. cfg.Node.LocalRange = accesstoken.ClientConfig.LocalRange
  260. cfg.Server.GRPCSSL = accesstoken.ServerConfig.GRPCSSL
  261. cfg.Server.CheckinInterval = accesstoken.ServerConfig.CheckinInterval
  262. cfg.Server.GRPCWireGuard = accesstoken.WG.GRPCWireGuard
  263. cfg.Server.CoreDNSAddr = accesstoken.ServerConfig.CoreDNSAddr
  264. if c.String("grpcserver") != "" {
  265. cfg.Server.GRPCAddress = c.String("grpcserver")
  266. }
  267. if c.String("apiserver") != "" {
  268. cfg.Server.APIAddress = c.String("apiserver")
  269. }
  270. if c.String("key") != "" {
  271. cfg.Server.AccessKey = c.String("key")
  272. }
  273. if c.String("network") != "all" {
  274. cfg.Network = c.String("network")
  275. cfg.Node.Network = c.String("network")
  276. }
  277. if c.String("localrange") != "" {
  278. cfg.Node.LocalRange = c.String("localrange")
  279. }
  280. if c.String("grpcssl") != "" {
  281. cfg.Server.GRPCSSL = c.String("grpcssl")
  282. }
  283. if c.String("corednsaddr") != "" {
  284. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  285. }
  286. if c.String("grpcwg") != "" {
  287. cfg.Server.GRPCWireGuard = c.String("grpcwg")
  288. }
  289. if c.String("checkininterval") != "" {
  290. cfg.Server.CheckinInterval = c.String("checkininterval")
  291. }
  292. } else {
  293. cfg.Server.GRPCAddress = c.String("grpcserver")
  294. cfg.Server.APIAddress = c.String("apiserver")
  295. cfg.Server.AccessKey = c.String("key")
  296. cfg.Network = c.String("network")
  297. cfg.Node.Network = c.String("network")
  298. cfg.Node.LocalRange = c.String("localrange")
  299. cfg.Server.GRPCWireGuard = c.String("grpcwg")
  300. cfg.Server.GRPCSSL = c.String("grpcssl")
  301. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  302. cfg.Server.CheckinInterval = c.String("checkininterval")
  303. }
  304. cfg.Node.Name = c.String("name")
  305. cfg.Node.Interface = c.String("interface")
  306. cfg.Node.Password = c.String("password")
  307. cfg.Node.MacAddress = c.String("macaddress")
  308. cfg.Node.LocalAddress = c.String("localaddress")
  309. cfg.Node.Address = c.String("address")
  310. cfg.Node.Address6 = c.String("addressIPV6")
  311. cfg.Node.Roaming = c.String("roaming")
  312. cfg.Node.DNSOn = c.String("dnson")
  313. cfg.Node.IsLocal = c.String("islocal")
  314. cfg.Node.IsDualStack = c.String("isdualstack")
  315. cfg.Node.PostUp = c.String("postup")
  316. cfg.Node.PostDown = c.String("postdown")
  317. cfg.Node.ListenPort = int32(c.Int("port"))
  318. cfg.Node.PersistentKeepalive = int32(c.Int("keepalive"))
  319. cfg.Node.PublicKey = c.String("publickey")
  320. privateKey := c.String("privatekey")
  321. cfg.Node.Endpoint = c.String("endpoint")
  322. cfg.Node.IPForwarding = c.String("ipforwarding")
  323. cfg.OperatingSystem = c.String("operatingsystem")
  324. cfg.Daemon = c.String("daemon")
  325. cfg.Node.UDPHolePunch = c.String("udpholepunch")
  326. cfg.Node.MTU = int32(c.Int("mtu"))
  327. if cfg.Server.CheckinInterval == "" {
  328. cfg.Server.CheckinInterval = "15"
  329. }
  330. return cfg, privateKey, nil
  331. }
  332. // ReadConfig - reads a config of a client from disk for specified network
  333. func ReadConfig(network string) (*ClientConfig, error) {
  334. if network == "" {
  335. err := errors.New("no network provided - exiting")
  336. return nil, err
  337. }
  338. nofile := false
  339. home := ncutils.GetNetclientPathSpecific()
  340. file := fmt.Sprintf(home + "netconfig-" + network)
  341. f, err := os.Open(file)
  342. if err != nil {
  343. if err = ReplaceWithBackup(network); err != nil {
  344. nofile = true
  345. }
  346. f, err = os.Open(file)
  347. if err != nil {
  348. nofile = true
  349. }
  350. }
  351. defer f.Close()
  352. var cfg ClientConfig
  353. if !nofile {
  354. decoder := yaml.NewDecoder(f)
  355. err = decoder.Decode(&cfg)
  356. if err != nil {
  357. fmt.Println("trouble decoding file")
  358. return nil, err
  359. }
  360. }
  361. return &cfg, err
  362. }
  363. // FileExists - checks if a file exists on disk
  364. func FileExists(f string) bool {
  365. info, err := os.Stat(f)
  366. if os.IsNotExist(err) {
  367. return false
  368. }
  369. return !info.IsDir()
  370. }
  371. // GetNode - parses a network specified client config for node data
  372. func GetNode(network string) models.Node {
  373. modcfg, err := ReadConfig(network)
  374. if err != nil {
  375. log.Fatalf("Error: %v", err)
  376. }
  377. var node models.Node
  378. node.Fill(&modcfg.Node)
  379. return node
  380. }