config.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package config
  2. // code for managing groundseg and container configurations
  3. import (
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "goseg/defaults"
  8. "goseg/structs"
  9. "io/ioutil"
  10. "log/slog"
  11. "math/rand"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "sync"
  17. "time"
  18. )
  19. var (
  20. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  21. // global settings config (accessed via funcs)
  22. globalConfig structs.SysConfig
  23. // base path for installation (override default with env var)
  24. BasePath = os.Getenv("GS_BASE_PATH")
  25. // only amd64 or arm64
  26. Architecture = getArchitecture()
  27. // struct of /retrieve blob
  28. StartramConfig structs.StartramRetrieve
  29. // unused for now, set with `./groundseg dev`
  30. DebugMode = false
  31. Ready = false
  32. // representation of desired/actual container states
  33. GSContainers = make(map[string]structs.ContainerState)
  34. DockerDir = "/var/lib/docker/volumes/"
  35. // version server check
  36. checkInterval = 5 * time.Minute
  37. confPath = filepath.Join(BasePath, "settings", "system.json")
  38. confMutex sync.Mutex
  39. contMutex sync.Mutex
  40. versMutex sync.Mutex
  41. )
  42. // try initializing from system.json on disk
  43. func init() {
  44. logger.Info("Starting GroundSeg")
  45. logger.Info("Urbit is love <3")
  46. for _, arg := range os.Args[1:] {
  47. // trigger this with `./groundseg dev`
  48. if arg == "dev" {
  49. logger.Info("Starting GroundSeg in debug mode")
  50. DebugMode = true
  51. }
  52. }
  53. if BasePath == "" {
  54. // default base path
  55. BasePath = "/opt/nativeplanet/groundseg"
  56. }
  57. pathMsg := fmt.Sprintf("Loading configs from %s", BasePath)
  58. logger.Info(pathMsg)
  59. confPath := filepath.Join(BasePath, "settings", "system.json")
  60. file, err := os.Open(confPath)
  61. if err != nil {
  62. // create a default if it doesn't exist
  63. err = createDefaultConf()
  64. if err != nil {
  65. // panic if we can't create it
  66. errmsg := fmt.Sprintf("Unable to create config! Please elevate permissions. %v", err)
  67. logger.Error(errmsg)
  68. panic(errmsg)
  69. }
  70. // generate and insert wireguard keys
  71. wgPriv, wgPub, err := WgKeyGen()
  72. salt := RandString(32)
  73. if err != nil {
  74. logger.Error(fmt.Sprintf("%v", err))
  75. } else {
  76. err = UpdateConf(map[string]interface{}{
  77. "Pubkey": wgPub,
  78. "Privkey": wgPriv,
  79. "Salt": salt,
  80. })
  81. if err != nil {
  82. logger.Error(fmt.Sprintf("%v", err))
  83. }
  84. }
  85. }
  86. defer file.Close()
  87. // read the sysconfig to memory
  88. decoder := json.NewDecoder(file)
  89. err = decoder.Decode(&globalConfig)
  90. if err != nil {
  91. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  92. logger.Error(errmsg)
  93. }
  94. }
  95. // return the global conf var
  96. func Conf() structs.SysConfig {
  97. confMutex.Lock()
  98. defer confMutex.Unlock()
  99. return globalConfig
  100. }
  101. // tell if we're amd64 or arm64
  102. func getArchitecture() string {
  103. switch runtime.GOARCH {
  104. case "arm64", "aarch64":
  105. return "arm64"
  106. default:
  107. return "amd64"
  108. }
  109. }
  110. // update by passing in a map of key:values you want to modify
  111. func UpdateConf(values map[string]interface{}) error {
  112. // mutex lock to avoid race conditions
  113. confMutex.Lock()
  114. defer confMutex.Unlock()
  115. file, err := ioutil.ReadFile(confPath)
  116. if err != nil {
  117. return fmt.Errorf("Unable to load config: %v", err)
  118. }
  119. // unmarshal the config to struct
  120. var configMap map[string]interface{}
  121. if err := json.Unmarshal(file, &configMap); err != nil {
  122. return fmt.Errorf("Error decoding JSON: %v", err)
  123. }
  124. // update our unmarshaled struct
  125. for key, value := range values {
  126. configMap[key] = value
  127. }
  128. if err = persistConf(configMap); err != nil {
  129. return fmt.Errorf("Unable to persist config update: %v", err)
  130. }
  131. return nil
  132. }
  133. // remove a tokenid from the session map if present
  134. func RemoveSession(sessionID string, fromAuthorized bool) error {
  135. confMutex.Lock()
  136. defer confMutex.Unlock()
  137. confPath := filepath.Join(BasePath, "settings", "system.json")
  138. file, err := ioutil.ReadFile(confPath)
  139. if err != nil {
  140. return fmt.Errorf("Unable to load config: %v", err)
  141. }
  142. var configMap map[string]interface{}
  143. if err := json.Unmarshal(file, &configMap); err != nil {
  144. return fmt.Errorf("Error decoding JSON: %v", err)
  145. }
  146. sessions, ok := configMap["sessions"].(map[string]interface{})
  147. if !ok {
  148. return fmt.Errorf("Unexpected format for sessions in config")
  149. }
  150. targetMapName := "unauthorized"
  151. if fromAuthorized {
  152. targetMapName = "authorized"
  153. }
  154. targetMap, ok := sessions[targetMapName].(map[string]interface{})
  155. if !ok {
  156. return fmt.Errorf("Unexpected format for %s in sessions", targetMapName)
  157. }
  158. delete(targetMap, sessionID)
  159. if err = persistConf(configMap); err != nil {
  160. return fmt.Errorf("Unable to persist config update: %v", err)
  161. }
  162. return nil
  163. }
  164. func persistConf(configMap map[string]interface{}) error {
  165. // marshal and persist it
  166. updatedJSON, err := json.MarshalIndent(configMap, "", " ")
  167. if err != nil {
  168. return fmt.Errorf("Error encoding JSON: %v", err)
  169. }
  170. // update the globalConfig var
  171. if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
  172. return fmt.Errorf("Error updating global config: %v", err)
  173. }
  174. // write to disk
  175. if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
  176. return fmt.Errorf("Error writing to file: %v", err)
  177. }
  178. return nil
  179. }
  180. // we keep map[string]structs.ContainerState in memory to keep track of the containers
  181. // eg if they're running and whether they should be
  182. // modify the desired/actual state of containers
  183. func UpdateContainerState(name string, containerState structs.ContainerState) {
  184. contMutex.Lock()
  185. defer contMutex.Unlock()
  186. GSContainers[name] = containerState
  187. res, _ := json.Marshal(containerState)
  188. logger.Info(fmt.Sprintf("%s:%s", name, string(res)))
  189. }
  190. // get the current container state
  191. func GetContainerState() map[string]structs.ContainerState {
  192. contMutex.Lock()
  193. defer contMutex.Unlock()
  194. return GSContainers
  195. }
  196. // write a default conf to disk
  197. func createDefaultConf() error {
  198. defaultConfig := defaults.SysConfig(BasePath)
  199. path := filepath.Join(BasePath, "settings", "system.json")
  200. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  201. return err
  202. }
  203. file, err := os.Create(path)
  204. if err != nil {
  205. return err
  206. }
  207. defer file.Close()
  208. encoder := json.NewEncoder(file)
  209. encoder.SetIndent("", " ")
  210. if err := encoder.Encode(&defaultConfig); err != nil {
  211. return err
  212. }
  213. return nil
  214. }
  215. // check outbound tcp connectivity
  216. // takes ip:port
  217. func NetCheck(netCheck string) bool {
  218. internet := false
  219. timeout := 3 * time.Second
  220. conn, err := net.DialTimeout("tcp", netCheck, timeout)
  221. if err != nil {
  222. errmsg := fmt.Sprintf("Check internet access error: %v", err)
  223. logger.Error(errmsg)
  224. } else {
  225. internet = true
  226. _ = conn.Close()
  227. }
  228. return internet
  229. }
  230. // generates a random secret string of the input length
  231. func RandString(length int) string {
  232. randBytes := make([]byte, length)
  233. _, err := rand.Read(randBytes)
  234. if err != nil {
  235. logger.Warn("Random error :s")
  236. return ""
  237. }
  238. return base64.URLEncoding.EncodeToString(randBytes)
  239. }