config.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "goseg/structs"
  6. "io/ioutil"
  7. "log/slog"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "sync"
  13. "time"
  14. )
  15. var (
  16. globalConfig structs.SysConfig
  17. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  18. basePath = "/home/reid/gits/np/goseg"
  19. Version = "v2.0.0"
  20. Ready = false
  21. VersionServerReady = false
  22. VersionInfo structs.Version
  23. Ram int
  24. Cpu int
  25. CoreTemp int
  26. Disk int
  27. WifiEnabled = false
  28. ActiveNetwork string
  29. WifiNetworks []string
  30. HttpOpen = false
  31. UploadSecret string
  32. confMutex sync.Mutex
  33. versMutex sync.Mutex
  34. )
  35. // try initializing from system.json on disk
  36. func init() {
  37. // try loading existing config
  38. confPath := filepath.Join(basePath, "settings", "system.json")
  39. file, err := os.Open(confPath)
  40. if err != nil {
  41. // create a default if it doesn't exist
  42. err = createDefaultConf()
  43. if err != nil {
  44. errmsg := fmt.Sprintf("Unable to create config! %v", err)
  45. logger.Error(errmsg)
  46. }
  47. }
  48. defer file.Close()
  49. decoder := json.NewDecoder(file)
  50. err = decoder.Decode(&globalConfig)
  51. if err != nil {
  52. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  53. logger.Error(errmsg)
  54. }
  55. }
  56. // return the global conf var
  57. func Conf() structs.SysConfig {
  58. confMutex.Lock()
  59. defer confMutex.Unlock()
  60. return globalConfig
  61. }
  62. // update by passing in a map of key:values you want to modify
  63. func UpdateConf(values map[string]interface{}) error {
  64. // mutex lock to avoid race conditions
  65. confMutex.Lock()
  66. defer confMutex.Unlock()
  67. confPath := filepath.Join(basePath, "settings", "system.json")
  68. file, err := ioutil.ReadFile(confPath)
  69. if err != nil {
  70. errmsg := fmt.Sprintf("Unable to load config: %v", err)
  71. logger.Error(errmsg)
  72. return err
  73. }
  74. // unmarshal the config to struct
  75. var configMap map[string]interface{}
  76. if err := json.Unmarshal(file, &configMap); err != nil {
  77. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  78. logger.Error(errmsg)
  79. return err
  80. }
  81. // update our unmarshaled struct
  82. for key, value := range values {
  83. configMap[key] = value
  84. }
  85. // marshal and persist it
  86. updatedJSON, err := json.MarshalIndent(configMap, "", " ")
  87. if err != nil {
  88. errmsg := fmt.Sprintf("Error encoding JSON: %v", err)
  89. logger.Error(errmsg)
  90. return err
  91. }
  92. if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
  93. errmsg := fmt.Sprintf("Error updating global config: %v", err)
  94. logger.Error(errmsg)
  95. return err
  96. }
  97. if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
  98. errmsg := fmt.Sprintf("Error writing to file: %v", err)
  99. logger.Error(errmsg)
  100. return err
  101. }
  102. return nil
  103. }
  104. // write a default conf to disk
  105. func createDefaultConf() error {
  106. defaultConfig := structs.SysConfig{
  107. Setup: "start",
  108. EndpointUrl: "api.startram.io",
  109. ApiVersion: "v1",
  110. Piers: []string{},
  111. NetCheck: "1.1.1.1:53",
  112. UpdateMode: "auto",
  113. UpdateUrl: "https://version.groundseg.app",
  114. UpdateBranch: "latest",
  115. SwapVal: 16,
  116. SwapFile: filepath.Join(basePath, "settings", "swapfile"),
  117. KeyFile: filepath.Join(basePath, "settings", "session.key"),
  118. Sessions: struct {
  119. Authorized map[string]structs.SessionInfo `json:"authorized"`
  120. Unauthorized map[string]structs.SessionInfo `json:"unauthorized"`
  121. }{
  122. Authorized: make(map[string]structs.SessionInfo),
  123. Unauthorized: make(map[string]structs.SessionInfo),
  124. },
  125. LinuxUpdates: struct {
  126. Value int `json:"value"`
  127. Interval string `json:"interval"`
  128. Previous bool `json:"previous"`
  129. }{
  130. Value: 1,
  131. Interval: "week",
  132. Previous: false,
  133. },
  134. DockerData: "/var/lib/docker",
  135. WgOn: false,
  136. WgRegistered: false,
  137. PwHash: "",
  138. C2cInterval: 0,
  139. FirstBoot: false,
  140. WgRegisterd: false,
  141. GsVersion: Version,
  142. CfgDir: "",
  143. UpdateInterval: 0,
  144. BinHash: "",
  145. Pubkey: "",
  146. Privkey: "",
  147. Salt: "",
  148. }
  149. path := filepath.Join(basePath, "settings", "system.json")
  150. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  151. return err
  152. }
  153. file, err := os.Create(path)
  154. if err != nil {
  155. return err
  156. }
  157. defer file.Close()
  158. encoder := json.NewEncoder(file)
  159. encoder.SetIndent("", " ")
  160. if err := encoder.Encode(&defaultConfig); err != nil {
  161. return err
  162. }
  163. return nil
  164. }
  165. // check outbound tcp connectivity
  166. // takes ip:port
  167. func NetCheck(netCheck string) bool {
  168. logger.Info("Checking internet access")
  169. internet := false
  170. timeout := 3 * time.Second
  171. conn, err := net.DialTimeout("tcp", netCheck, timeout)
  172. if err != nil {
  173. errmsg := fmt.Sprintf("Check internet access error: %v", err)
  174. logger.Error(errmsg)
  175. } else {
  176. internet = true
  177. _ = conn.Close()
  178. }
  179. return internet
  180. }
  181. // check the version server and return unmarshaled result
  182. func CheckVersion() (structs.Version, bool) {
  183. versMutex.Lock()
  184. defer versMutex.Unlock()
  185. const retries = 10
  186. const delay = time.Second
  187. url := globalConfig.UpdateUrl
  188. for i := 0; i < retries; i++ {
  189. resp, err := http.Get(url)
  190. if err != nil {
  191. errmsg := fmt.Sprintf("Unable to connect to update server: %v", err)
  192. logger.Warn(errmsg)
  193. if i < retries-1 {
  194. time.Sleep(delay)
  195. continue
  196. } else {
  197. return VersionInfo, false
  198. }
  199. }
  200. // read the body bytes
  201. body, err := ioutil.ReadAll(resp.Body)
  202. resp.Body.Close()
  203. if err != nil {
  204. errmsg := fmt.Sprintf("Error reading version info: %v", err)
  205. logger.Warn(errmsg)
  206. if i < retries-1 {
  207. time.Sleep(delay)
  208. continue
  209. } else {
  210. return VersionInfo, false
  211. }
  212. }
  213. // unmarshal values into Version struct
  214. err = json.Unmarshal(body, &VersionInfo)
  215. if err != nil {
  216. errmsg := fmt.Sprintf("Error unmarshalling JSON: %v", err)
  217. logger.Warn(errmsg)
  218. if i < retries-1 {
  219. time.Sleep(delay)
  220. continue
  221. } else {
  222. return VersionInfo, false
  223. }
  224. }
  225. // debug: re-marshal and write to disk
  226. confPath := filepath.Join(basePath, "settings", "version_info.json")
  227. file, err := os.Create(confPath)
  228. if err != nil {
  229. errmsg := fmt.Sprintf("Failed to create file: %v", err)
  230. logger.Error(errmsg)
  231. return VersionInfo, false
  232. }
  233. defer file.Close()
  234. encoder := json.NewEncoder(file)
  235. encoder.SetIndent("", " ")
  236. if err := encoder.Encode(&VersionInfo); err != nil {
  237. errmsg := fmt.Sprintf("Failed to write JSON: %v", err)
  238. logger.Error(errmsg)
  239. }
  240. return VersionInfo, true
  241. }
  242. return VersionInfo, false
  243. }