config.go 8.8 KB

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