config.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package config
  2. import (
  3. "crypto/ed25519"
  4. "crypto/x509"
  5. "crypto/x509/pkix"
  6. "errors"
  7. "fmt"
  8. "github.com/gravitl/netmaker/netclient/ncutils"
  9. "log"
  10. "os"
  11. "sync"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/netclient/global_settings"
  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 models.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. AccessKey string `yaml:"accesskey"`
  30. PublicIPService string `yaml:"publicipservice"`
  31. }
  32. // RegisterRequest - struct for registation with netmaker server
  33. type RegisterRequest struct {
  34. Key ed25519.PrivateKey
  35. CommonName pkix.Name
  36. }
  37. // RegisterResponse - the response to register function
  38. type RegisterResponse struct {
  39. CA x509.Certificate
  40. CAPubKey ed25519.PublicKey
  41. Cert x509.Certificate
  42. CertPubKey ed25519.PublicKey
  43. Broker string
  44. Port string
  45. }
  46. // Write - writes the config of a client to disk
  47. func Write(config *ClientConfig, network string) error {
  48. configLock.Lock()
  49. defer configLock.Unlock()
  50. if network == "" {
  51. err := errors.New("no network provided - exiting")
  52. return err
  53. }
  54. _, err := os.Stat(ncutils.GetNetclientPath() + "/config")
  55. if os.IsNotExist(err) {
  56. os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0700)
  57. } else if err != nil {
  58. return err
  59. }
  60. home := ncutils.GetNetclientPathSpecific()
  61. file := fmt.Sprintf(home + "netconfig-" + network)
  62. f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  63. if err != nil {
  64. return err
  65. }
  66. defer f.Close()
  67. err = yaml.NewEncoder(f).Encode(config)
  68. if err != nil {
  69. return err
  70. }
  71. return f.Sync()
  72. }
  73. // ConfigFileExists - return true if config file exists
  74. func (config *ClientConfig) ConfigFileExists() bool {
  75. home := ncutils.GetNetclientPathSpecific()
  76. file := fmt.Sprintf(home + "netconfig-" + config.Network)
  77. info, err := os.Stat(file)
  78. if os.IsNotExist(err) {
  79. return false
  80. }
  81. return !info.IsDir()
  82. }
  83. // ClientConfig.ReadConfig - used to read config from client disk into memory
  84. func (config *ClientConfig) ReadConfig() {
  85. nofile := false
  86. //home, err := homedir.Dir()
  87. home := ncutils.GetNetclientPathSpecific()
  88. file := fmt.Sprintf(home + "netconfig-" + config.Network)
  89. //f, err := os.Open(file)
  90. f, err := os.OpenFile(file, os.O_RDONLY, 0600)
  91. if err != nil {
  92. logger.Log(1, "trouble opening file: ", err.Error())
  93. nofile = true
  94. //fmt.Println("Could not access " + home + "/.netconfig, proceeding...")
  95. }
  96. defer f.Close()
  97. //var cfg ClientConfig
  98. if !nofile {
  99. decoder := yaml.NewDecoder(f)
  100. err = decoder.Decode(&config)
  101. if err != nil {
  102. fmt.Println("no config or invalid")
  103. fmt.Println(err)
  104. log.Fatal(err)
  105. }
  106. }
  107. }
  108. // ModNodeConfig - overwrites the node inside client config on disk
  109. func ModNodeConfig(node *models.Node) error {
  110. network := node.Network
  111. if network == "" {
  112. return errors.New("no network provided")
  113. }
  114. var modconfig ClientConfig
  115. if FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network) {
  116. useconfig, err := ReadConfig(network)
  117. if err != nil {
  118. return err
  119. }
  120. modconfig = *useconfig
  121. }
  122. modconfig.Node = (*node)
  123. modconfig.NetworkSettings = node.NetworkSettings
  124. return Write(&modconfig, network)
  125. }
  126. // ModNodeConfig - overwrites the server settings inside client config on disk
  127. func ModServerConfig(scfg *models.ServerConfig, network string) error {
  128. var modconfig ClientConfig
  129. if FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network) {
  130. useconfig, err := ReadConfig(network)
  131. if err != nil {
  132. return err
  133. }
  134. modconfig = *useconfig
  135. }
  136. modconfig.Server = (*scfg)
  137. return Write(&modconfig, network)
  138. }
  139. // SaveBackup - saves a backup file of a given network
  140. func SaveBackup(network string) error {
  141. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  142. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  143. if FileExists(configPath) {
  144. input, err := os.ReadFile(configPath)
  145. if err != nil {
  146. logger.Log(0, "failed to read ", configPath, " to make a backup")
  147. return err
  148. }
  149. if err = os.WriteFile(backupPath, input, 0600); err != nil {
  150. logger.Log(0, "failed to copy backup to ", backupPath)
  151. return err
  152. }
  153. }
  154. return nil
  155. }
  156. // ReplaceWithBackup - replaces netconfig file with backup
  157. func ReplaceWithBackup(network string) error {
  158. var backupPath = ncutils.GetNetclientPathSpecific() + "backup.netconfig-" + network
  159. var configPath = ncutils.GetNetclientPathSpecific() + "netconfig-" + network
  160. if FileExists(backupPath) {
  161. input, err := os.ReadFile(backupPath)
  162. if err != nil {
  163. logger.Log(0, "failed to read file ", backupPath, " to backup network: ", network)
  164. return err
  165. }
  166. if err = os.WriteFile(configPath, input, 0600); err != nil {
  167. logger.Log(0, "failed backup ", backupPath, " to ", configPath)
  168. return err
  169. }
  170. }
  171. logger.Log(0, "used backup file for network: ", network)
  172. return nil
  173. }
  174. // GetCLIConfig - gets the cli flags as a config
  175. func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
  176. var cfg ClientConfig
  177. if c.String("token") != "" {
  178. accesstoken, err := ParseAccessToken(c.String("token"))
  179. if err != nil {
  180. return cfg, "", err
  181. }
  182. cfg.Network = accesstoken.ClientConfig.Network
  183. cfg.Node.Network = accesstoken.ClientConfig.Network
  184. cfg.AccessKey = accesstoken.ClientConfig.Key
  185. cfg.Node.LocalRange = accesstoken.ClientConfig.LocalRange
  186. //cfg.Server.Server = accesstoken.ServerConfig.Server
  187. cfg.Server.API = accesstoken.APIConnString
  188. if c.String("key") != "" {
  189. cfg.AccessKey = c.String("key")
  190. }
  191. if c.String("network") != "all" {
  192. cfg.Network = c.String("network")
  193. cfg.Node.Network = c.String("network")
  194. }
  195. if c.String("localrange") != "" {
  196. cfg.Node.LocalRange = c.String("localrange")
  197. }
  198. if c.String("corednsaddr") != "" {
  199. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  200. }
  201. if c.String("apiserver") != "" {
  202. cfg.Server.API = c.String("apiserver")
  203. }
  204. } else {
  205. cfg.AccessKey = c.String("key")
  206. cfg.Network = c.String("network")
  207. cfg.Node.Network = c.String("network")
  208. cfg.Node.LocalRange = c.String("localrange")
  209. cfg.Server.CoreDNSAddr = c.String("corednsaddr")
  210. cfg.Server.API = c.String("apiserver")
  211. }
  212. cfg.PublicIPService = c.String("publicipservice")
  213. // populate the map as we're not running as a daemon so won't be building the map otherwise
  214. // (and the map will be used by GetPublicIP()).
  215. global_settings.PublicIPServices[cfg.Network] = cfg.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. }