package server import ( "crypto/rsa" "encoding/json" "github.com/s-rah/go-ricochet/utils" "io/ioutil" "log" "sync" ) // Reporting is a struct for storing a the config a server needs to be a peer, and connect to a group to report type Reporting struct { PeerPrivateKey string `json:"privateKey"` ReportingGroupID string `json:"reportingGroupId"` ReportingServerAddr string `json:"reportingServerAddr"` } // Config is a struct for storing basic server configuration type Config struct { MaxBufferLines int `json:"maxBufferLines"` PrivateKeyBytes string `json:"privateKey"` ServerReporting Reporting `json:"serverReporting"` lock sync.Mutex } // PrivateKey returns an rsa.PrivateKey generated from the config's PrivateKeyBytes func (config *Config) PrivateKey() *rsa.PrivateKey { pk, err := utils.ParsePrivateKey([]byte(config.PrivateKeyBytes)) if err != nil { log.Println("Error parsing private key: ", err) } return pk } // Save dumps the latest version of the config to a json file given by filename func (config *Config) Save(filename string) { config.lock.Lock() defer config.lock.Unlock() bytes, _ := json.MarshalIndent(config, "", "\t") ioutil.WriteFile(filename, bytes, 0600) } // LoadConfig loads a Config from a json file specified by filename func LoadConfig(filename string) *Config { raw, err := ioutil.ReadFile(filename) if err != nil { log.Fatal("Could not read config: ", err) } config := Config{} err = json.Unmarshal(raw, &config) if err != nil { log.Fatal("Error reading config: ", err) } if config.PrivateKeyBytes == "" { config.generatePrivateKey() config.Save(filename) } if config.ServerReporting.PeerPrivateKey == "" { config.generatePeerPrivateKey() config.Save(filename) } return &config } func (config *Config) generatePrivateKey() { pk, err := utils.GeneratePrivateKey() if err != nil { log.Fatalf("error generating new private key: %v\n", err) } config.lock.Lock() config.PrivateKeyBytes = utils.PrivateKeyToString(pk) config.lock.Unlock() } func (config *Config) generatePeerPrivateKey() { pk, err := utils.GeneratePrivateKey() if err != nil { log.Fatalf("error generating new peer private key: %v\n", err) } config.lock.Lock() config.ServerReporting.PeerPrivateKey = utils.PrivateKeyToString(pk) config.lock.Unlock() }