config.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package config
  2. import (
  3. //"github.com/davecgh/go-spew/spew"
  4. "crypto/ed25519"
  5. "crypto/x509"
  6. "crypto/x509/pkix"
  7. "errors"
  8. "fmt"
  9. "log"
  10. "os"
  11. "sync"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/netclient/ncutils"
  15. "github.com/urfave/cli/v2"
  16. "gopkg.in/yaml.v3"
  17. )
  18. var (
  19. configLock sync.Mutex
  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. }
  30. // ServerConfig - struct for dealing with the server information for a netclient
  31. type ServerConfig struct {
  32. CoreDNSAddr string `yaml:"corednsaddr"`
  33. AccessKey string `yaml:"accesskey"`
  34. Server string `yaml:"server"`
  35. API string `yaml:"api"`
  36. Version string `yaml:"version"`
  37. }
  38. // RegisterRequest - struct for registation with netmaker server
  39. type RegisterRequest struct {
  40. Key ed25519.PrivateKey
  41. CommonName pkix.Name
  42. }
  43. // RegisterResponse - the response to register function
  44. type RegisterResponse struct {
  45. CA x509.Certificate
  46. CAPubKey ed25519.PublicKey
  47. Cert x509.Certificate
  48. CertPubKey ed25519.PublicKey
  49. }
  50. // Write - writes the config of a client to disk
  51. func Write(config *ClientConfig, network string) error {
  52. configLock.Lock()
  53. defer configLock.Unlock()
  54. if network == "" {
  55. err := errors.New("no network provided - exiting")
  56. return err
  57. }
  58. _, err := os.Stat(ncutils.GetNetclientPath() + "/config")
  59. if os.IsNotExist(err) {
  60. os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0700)
  61. } else if err != nil {
  62. return err
  63. }
  64. home := ncutils.GetNetclientPathSpecific()
  65. file := fmt.Sprintf(home + "netconfig-" + network)
  66. f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  67. if err != nil {
  68. return err
  69. }
  70. defer f.Close()
  71. err = yaml.NewEncoder(f).Encode(config)
  72. if err != nil {
  73. return err
  74. }
  75. return f.Sync()
  76. }
  77. // ConfigFileExists - return true if config file exists
  78. func (config *ClientConfig) ConfigFileExists() bool {
  79. home := ncutils.GetNetclientPathSpecific()
  80. file := fmt.Sprintf(home + "netconfig-" + config.Network)
  81. info, err := os.Stat(file)
  82. if os.IsNotExist(err) {
  83. return false
  84. }
  85. return !info.IsDir()
  86. }
  87. // ClientConfig.ReadConfig - used to read config from client disk into memory
  88. func (config *ClientConfig) ReadConfig() {
  89. nofile := false
  90. //home, err := homedir.Dir()
  91. home := ncutils.GetNetclientPathSpecific()
  92. file := fmt.Sprintf(home + "netconfig-" + config.Network)
  93. //f, err := os.Open(file)
  94. f, err := os.OpenFile(file, os.O_RDONLY, 0600)
  95. if err != nil {
  96. logger.Log(1, "trouble opening file: ", err.Error())
  97. nofile = true
  98. //fmt.Println("Could not access " + home + "/.netconfig, proceeding...")
  99. }
  100. defer f.Close()
  101. //var cfg ClientConfig
  102. if !nofile {
  103. decoder := yaml.NewDecoder(f)
  104. err = decoder.Decode(&config)
  105. if err != nil {
  106. fmt.Println("no config or invalid")
  107. fmt.Println(err)
  108. log.Fatal(err)
  109. }
  110. }
  111. }
  112. // ModConfig - overwrites the node inside client config on disk
  113. func ModConfig(node *models.Node) error {
  114. network := node.Network
  115. if network == "" {
  116. return errors.New("no network provided")
  117. }
  118. var modconfig ClientConfig
  119. if FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network) {
  120. useconfig, err := ReadConfig(network)
  121. if err != nil {
  122. return err
  123. }
  124. modconfig = *useconfig
  125. }
  126. modconfig.Node = (*node)
  127. modconfig.NetworkSettings = node.NetworkSettings
  128. return Write(&modconfig, network)
  129. }
  130. // SaveBackup - saves a backup file of a given network
  131. func SaveBackup(network string) error {
  132. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  133. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  134. if FileExists(configPath) {
  135. input, err := os.ReadFile(configPath)
  136. if err != nil {
  137. logger.Log(0, "failed to read ", configPath, " to make a backup")
  138. return err
  139. }
  140. if err = os.WriteFile(backupPath, input, 0600); err != nil {
  141. logger.Log(0, "failed to copy backup to ", backupPath)
  142. return err
  143. }
  144. }
  145. return nil
  146. }
  147. // ReplaceWithBackup - replaces netconfig file with backup
  148. func ReplaceWithBackup(network string) error {
  149. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  150. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  151. if FileExists(backupPath) {
  152. input, err := os.ReadFile(backupPath)
  153. if err != nil {
  154. logger.Log(0, "failed to read file ", backupPath, " to backup network: ", network)
  155. return err
  156. }
  157. if err = os.WriteFile(configPath, input, 0600); err != nil {
  158. logger.Log(0, "failed backup ", backupPath, " to ", configPath)
  159. return err
  160. }
  161. }
  162. logger.Log(0, "used backup file for network: ", network)
  163. return nil
  164. }
  165. // GetCLIConfig - gets the cli flags as a config
  166. func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
  167. var cfg ClientConfig
  168. if c.String("token") != "" {
  169. accesstoken, err := ParseAccessToken(c.String("token"))
  170. if err != nil {
  171. return cfg, "", err
  172. }
  173. cfg.Network = accesstoken.ClientConfig.Network
  174. cfg.Node.Network = accesstoken.ClientConfig.Network
  175. cfg.Server.AccessKey = accesstoken.ClientConfig.Key
  176. cfg.Node.LocalRange = accesstoken.ClientConfig.LocalRange
  177. cfg.Server.Server = accesstoken.ServerConfig.Server
  178. cfg.Server.API = accesstoken.ServerConfig.APIConnString
  179. if c.String("key") != "" {
  180. cfg.Server.AccessKey = c.String("key")
  181. }
  182. if c.String("network") != "all" {
  183. cfg.Network = c.String("network")
  184. cfg.Node.Network = c.String("network")
  185. }
  186. if c.String("localrange") != "" {
  187. cfg.Node.LocalRange = c.String("localrange")
  188. }
  189. if c.String("corednsaddr") != "" {
  190. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  191. }
  192. if c.String("apiserver") != "" {
  193. cfg.Server.API = c.String("apiserver")
  194. }
  195. } else {
  196. cfg.Server.AccessKey = c.String("key")
  197. cfg.Network = c.String("network")
  198. cfg.Node.Network = c.String("network")
  199. cfg.Node.LocalRange = c.String("localrange")
  200. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  201. cfg.Server.API = c.String("apiserver")
  202. }
  203. cfg.Node.Name = c.String("name")
  204. cfg.Node.Interface = c.String("interface")
  205. cfg.Node.Password = c.String("password")
  206. cfg.Node.MacAddress = c.String("macaddress")
  207. cfg.Node.LocalAddress = c.String("localaddress")
  208. cfg.Node.Address = c.String("address")
  209. cfg.Node.Address6 = c.String("address6")
  210. //cfg.Node.Roaming = c.String("roaming")
  211. cfg.Node.DNSOn = c.String("dnson")
  212. cfg.Node.IsLocal = c.String("islocal")
  213. cfg.Node.IsStatic = c.String("isstatic")
  214. cfg.Node.PostUp = c.String("postup")
  215. cfg.Node.PostDown = c.String("postdown")
  216. cfg.Node.ListenPort = int32(c.Int("port"))
  217. cfg.Node.PersistentKeepalive = int32(c.Int("keepalive"))
  218. cfg.Node.PublicKey = c.String("publickey")
  219. privateKey := c.String("privatekey")
  220. cfg.Node.Endpoint = c.String("endpoint")
  221. cfg.Node.IPForwarding = c.String("ipforwarding")
  222. cfg.OperatingSystem = c.String("operatingsystem")
  223. cfg.Daemon = c.String("daemon")
  224. cfg.Node.UDPHolePunch = c.String("udpholepunch")
  225. cfg.Node.MTU = int32(c.Int("mtu"))
  226. return cfg, privateKey, nil
  227. }
  228. // ReadConfig - reads a config of a client from disk for specified network
  229. func ReadConfig(network string) (*ClientConfig, error) {
  230. if network == "" {
  231. err := errors.New("no network provided - exiting")
  232. return nil, err
  233. }
  234. nofile := false
  235. home := ncutils.GetNetclientPathSpecific()
  236. file := fmt.Sprintf(home + "netconfig-" + network)
  237. f, err := os.Open(file)
  238. if err != nil {
  239. if err = ReplaceWithBackup(network); err != nil {
  240. nofile = true
  241. }
  242. f, err = os.Open(file)
  243. if err != nil {
  244. nofile = true
  245. }
  246. }
  247. defer f.Close()
  248. var cfg ClientConfig
  249. if !nofile {
  250. decoder := yaml.NewDecoder(f)
  251. err = decoder.Decode(&cfg)
  252. if err != nil {
  253. fmt.Println("trouble decoding file")
  254. return nil, err
  255. }
  256. }
  257. return &cfg, err
  258. }
  259. // FileExists - checks if a file exists on disk
  260. func FileExists(f string) bool {
  261. info, err := os.Stat(f)
  262. if os.IsNotExist(err) {
  263. return false
  264. }
  265. return !info.IsDir()
  266. }
  267. // GetNode - parses a network specified client config for node data
  268. func GetNode(network string) models.Node {
  269. modcfg, err := ReadConfig(network)
  270. if err != nil {
  271. log.Fatalf("Error: %v", err)
  272. }
  273. var node models.Node
  274. node.Fill(&modcfg.Node)
  275. return node
  276. }