From d361d71a2a7df24dbf7bf321d68742b8af5edbd1 Mon Sep 17 00:00:00 2001 From: Dan Ballard Date: Mon, 4 Oct 2021 16:21:41 -0700 Subject: [PATCH] adding 'servers' interface to manage multiple servers and support for encrypted configs --- README.md | 2 + app/main.go | 40 ++++------ server.go | 122 +++++++++++++++++++++++++------ serverConfig.go | 119 +++++++++++++++++++++++------- server_tokenboard.go | 8 +- servers.go | 134 ++++++++++++++++++++++++++++++++++ storage/message_store.go | 2 +- storage/message_store_test.go | 2 +- 8 files changed, 350 insertions(+), 79 deletions(-) create mode 100644 servers.go diff --git a/README.md b/README.md index d730e68..62f0f2c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ The app takes the following arguments The app takes the following environment variables - CWTCH_HOME: sets the config dir for the app +`env CONFIG_HOME=./conf ./app` + ## Using the Server When run the app will output standard log lines, one of which will contain the `tofubundle` in purple. This is the part you need to capture and import into a Cwtch client app so you can use the server for hosting groups diff --git a/app/main.go b/app/main.go index 8656290..42eed2f 100644 --- a/app/main.go +++ b/app/main.go @@ -2,10 +2,8 @@ package main import ( "crypto/rand" - "cwtch.im/cwtch/model" "encoding/base64" "flag" - "fmt" cwtchserver "git.openprivacy.ca/cwtch.im/server" "git.openprivacy.ca/cwtch.im/tapir/primitives" "git.openprivacy.ca/openprivacy/connectivity/tor" @@ -19,10 +17,6 @@ import ( "time" ) -const ( - serverConfigFile = "serverConfig.json" -) - func main() { flagDebug := flag.Bool("debug", false, "Enable debug logging") flagExportTofu := flag.Bool("exportTofuBundle", false, "Export the tofubundle to a file called tofubundle") @@ -52,19 +46,25 @@ func main() { ReportingGroupID: "", ReportingServerAddr: "", } - config.Save(".", "serverConfig.json") + config.ConfigDir = "." + config.FilePath = cwtchserver.ServerConfigFile + config.Encrypted = false + config.Save() return } - serverConfig := cwtchserver.LoadConfig(configDir, serverConfigFile) - + serverConfig, err := cwtchserver.LoadCreateDefaultConfigFile(configDir, cwtchserver.ServerConfigFile, false, "") + if err != nil { + log.Errorf("Could not load/create config file: %s\n", err) + return + } // we don't need real randomness for the port, just to avoid a possible conflict... mrand.Seed(int64(time.Now().Nanosecond())) controlPort := mrand.Intn(1000) + 9052 // generate a random password key := make([]byte, 64) - _, err := rand.Read(key) + _, err = rand.Read(key) if err != nil { panic(err) } @@ -79,25 +79,15 @@ func main() { } defer acn.Close() - server := new(cwtchserver.Server) + server := cwtchserver.NewServer(serverConfig) log.Infoln("starting cwtch server...") + log.Infof("Server 'hash name': %s\n", server.HashName()) - server.Setup(serverConfig) - - // TODO create a random group for testing - group, _ := model.NewGroup(tor.GetTorV3Hostname(serverConfig.PublicKey)) - invite, err := group.Invite() - if err != nil { - panic(err) - } - - bundle := server.KeyBundle().Serialize() - tofubundle := fmt.Sprintf("tofubundle:server:%s||%s", base64.StdEncoding.EncodeToString(bundle), invite) - log.Infof("Server Tofu Bundle (import into client to use server): %s", log.Magenta(tofubundle)) - log.Infof("Server Config: server address:%s", base64.StdEncoding.EncodeToString(bundle)) + log.Infof("Server bundle (import into client to use server): %s\n", log.Magenta(server.Server())) if *flagExportTofu { - ioutil.WriteFile(path.Join(serverConfig.ConfigDir, "tofubundle"), []byte(tofubundle), 0600) + // Todo: change all to server export + ioutil.WriteFile(path.Join(serverConfig.ConfigDir, "tofubundle"), []byte(server.TofuBundle()), 0600) } // Graceful Shutdown diff --git a/server.go b/server.go index e874510..8755327 100644 --- a/server.go +++ b/server.go @@ -3,6 +3,9 @@ package server import ( "crypto/ed25519" "cwtch.im/cwtch/model" + "encoding/base64" + "encoding/binary" + "errors" "fmt" "git.openprivacy.ca/cwtch.im/server/metrics" "git.openprivacy.ca/cwtch.im/server/storage" @@ -15,14 +18,37 @@ import ( "git.openprivacy.ca/openprivacy/connectivity" "git.openprivacy.ca/openprivacy/connectivity/tor" "git.openprivacy.ca/openprivacy/log" + "os" "path" + "strings" "sync" ) +const ( + // ServerConfigFile is the standard filename for a server's config to be written to in a directory + ServerConfigFile = "serverConfig.json" +) + // Server encapsulates a complete, compliant Cwtch server. -type Server struct { +type Server interface { + Identity() primitives.Identity + Run(acn connectivity.ACN) error + KeyBundle() *model.KeyBundle + CheckStatus() (bool, error) + Shutdown() + GetStatistics() Statistics + ConfigureAutostart(autostart bool) + Close() + Delete(password string) error + Onion() string + Server() string + TofuBundle() string + HashName() string +} + +type server struct { service tapir.Service - config Config + config *Config metricsPack metrics.Monitors tokenTapirService tapir.Service tokenServer *privacypass.TokenServer @@ -35,31 +61,39 @@ type Server struct { lock sync.RWMutex } -// Setup initialized a server from a given configuration -func (s *Server) Setup(serverConfig Config) { - s.config = serverConfig +// NewServer creates and configures a new server based on the supplied configuration +func NewServer(serverConfig *Config) Server { + server := new(server) + server.running = false + server.config = serverConfig bs := new(persistence.BoltPersistence) bs.Open(path.Join(serverConfig.ConfigDir, "tokens.db")) - s.tokenServer = privacypass.NewTokenServerFromStore(&serverConfig.TokenServiceK, bs) - log.Infof("Y: %v", s.tokenServer.Y) - s.tokenService = s.config.TokenServiceIdentity() - s.tokenServicePrivKey = s.config.TokenServerPrivateKey + server.tokenServer = privacypass.NewTokenServerFromStore(&serverConfig.TokenServiceK, bs) + log.Infof("Y: %v", server.tokenServer.Y) + server.tokenService = server.config.TokenServiceIdentity() + server.tokenServicePrivKey = server.config.TokenServerPrivateKey + return server } // Identity returns the main onion identity of the server -func (s *Server) Identity() primitives.Identity { +func (s *server) Identity() primitives.Identity { return s.config.Identity() } // Run starts a server with the given privateKey -func (s *Server) Run(acn connectivity.ACN) error { - addressIdentity := tor.GetTorV3Hostname(s.config.PublicKey) +func (s *server) Run(acn connectivity.ACN) error { + s.lock.Lock() + defer s.lock.Unlock() + if s.running { + return nil + } + identity := primitives.InitializeIdentity("", &s.config.PrivateKey, &s.config.PublicKey) var service tapir.Service service = new(tor2.BaseOnionService) service.Init(acn, s.config.PrivateKey, &identity) s.service = service - log.Infof("cwtch server running on cwtch:%s\n", addressIdentity+".onion:") + log.Infof("cwtch server running on cwtch:%s\n", s.Onion()) s.metricsPack.Start(service, s.config.ConfigDir, s.config.ServerReporting.LogMetricsToFile) ms, err := storage.InitializeSqliteMessageStore(path.Join(s.config.ConfigDir, "cwtch.messages"), s.metricsPack.MessageCounter) @@ -87,14 +121,12 @@ func (s *Server) Run(acn connectivity.ACN) error { s.onionServiceStopped = true }() - s.lock.Lock() s.running = true - s.lock.Unlock() return nil } // KeyBundle provides the signed keybundle of the server -func (s *Server) KeyBundle() *model.KeyBundle { +func (s *server) KeyBundle() *model.KeyBundle { kb := model.NewKeyBundle() identity := s.config.Identity() kb.Keys[model.KeyTypeServerOnion] = model.Key(identity.Hostname()) @@ -105,7 +137,7 @@ func (s *Server) KeyBundle() *model.KeyBundle { } // CheckStatus returns true if the server is running and/or an error if any part of the server needs to be restarted. -func (s *Server) CheckStatus() (bool, error) { +func (s *server) CheckStatus() (bool, error) { s.lock.RLock() defer s.lock.RUnlock() if s.onionServiceStopped == true || s.tokenServiceStopped == true { @@ -115,7 +147,7 @@ func (s *Server) CheckStatus() (bool, error) { } // Shutdown kills the app closing all connections and freeing all goroutines -func (s *Server) Shutdown() { +func (s *server) Shutdown() { s.lock.Lock() defer s.lock.Unlock() s.service.Shutdown() @@ -132,7 +164,7 @@ type Statistics struct { // GetStatistics is a stub method for providing some high level information about // the server operation to bundling applications (e.g. the UI) -func (s *Server) GetStatistics() Statistics { +func (s *server) GetStatistics() Statistics { // TODO Statistics from Metrics is very awkward. Metrics needs an overhaul to make safe total := s.existingMessageCount if s.metricsPack.TotalMessageCounter != nil { @@ -145,16 +177,60 @@ func (s *Server) GetStatistics() Statistics { } // ConfigureAutostart sets whether this server should autostart (in the Cwtch UI/bundling application) -func (s *Server) ConfigureAutostart(autostart bool) { +func (s *server) ConfigureAutostart(autostart bool) { s.config.AutoStart = autostart - s.config.Save(s.config.ConfigDir, s.config.FilePath) + s.config.Save() } // Close shuts down the cwtch server in a safe way. -func (s *Server) Close() { +func (s *server) Close() { log.Infof("Shutting down server") s.lock.Lock() defer s.lock.Unlock() - log.Infof("Closing Token Server Database...") + log.Infof("Closing Token server Database...") s.tokenServer.Close() } + +func (s *server) Delete(password string) error { + s.lock.Lock() + defer s.lock.Unlock() + if s.config.Encrypted && !s.config.CheckPassword(password) { + return errors.New("Cannot delete server, passwords do not match") + } + os.RemoveAll(s.config.ConfigDir) + return nil +} + +func (s *server) Onion() string { + return tor.GetTorV3Hostname(s.config.PublicKey) + ".onion" +} + +func (s *server) Server() string { + bundle := s.KeyBundle().Serialize() + return fmt.Sprintf("server:%s", base64.StdEncoding.EncodeToString(bundle)) +} + +func (s *server) TofuBundle() string { + group, _ := model.NewGroup(tor.GetTorV3Hostname(s.config.PublicKey)) + invite, err := group.Invite() + if err != nil { + panic(err) + } + bundle := s.KeyBundle().Serialize() + return fmt.Sprintf("tofubundle:server:%s||%s", base64.StdEncoding.EncodeToString(bundle), invite) +} + +// TODO demo implementation only, not nearly enough entropy +// TODO Apache license +// https://github.com/dustinkirkland/petname/blob/master/usr/share/petname/small/names.txt +var namesSmall = []string{"ox", "ant", "ape", "asp", "bat", "bee", "boa", "bug", "cat", "cod", "cow", "cub", "doe", "dog", "eel", "eft", "elf", "elk", "emu", "ewe", "fly", "fox", "gar", "gnu", "hen", "hog", "imp", "jay", "kid", "kit", "koi", "lab", "man", "owl", "pig", "pug", "pup", "ram", "rat", "ray", "yak", "bass", "bear", "bird", "boar", "buck", "bull", "calf", "chow", "clam", "colt", "crab", "crow", "dane", "deer", "dodo", "dory", "dove", "drum", "duck", "fawn", "fish", "flea", "foal", "fowl", "frog", "gnat", "goat", "grub", "gull", "hare", "hawk", "ibex", "joey", "kite", "kiwi", "lamb", "lark", "lion", "loon", "lynx", "mako", "mink", "mite", "mole", "moth", "mule", "mutt", "newt", "orca", "oryx", "pika", "pony", "puma", "seal", "shad", "slug", "sole", "stag", "stud", "swan", "tahr", "teal", "tick", "toad", "tuna", "wasp", "wolf", "worm", "wren", "yeti", "adder", "akita", "alien", "aphid", "bison", "boxer", "bream", "bunny", "burro", "camel", "chimp", "civet", "cobra", "coral", "corgi", "crane", "dingo", "drake", "eagle", "egret", "filly", "finch", "gator", "gecko", "ghost", "ghoul", "goose", "guppy", "heron", "hippo", "horse", "hound", "husky", "hyena", "koala", "krill", "leech", "lemur", "liger", "llama", "louse", "macaw", "midge", "molly", "moose", "moray", "mouse", "panda", "perch", "prawn", "quail", "racer", "raven", "rhino", "robin", "satyr", "shark", "sheep", "shrew", "skink", "skunk", "sloth", "snail", "snake", "snipe", "squid", "stork", "swift", "swine", "tapir", "tetra", "tiger", "troll", "trout", "viper", "wahoo", "whale", "zebra", "alpaca", "amoeba", "baboon", "badger", "beagle", "bedbug", "beetle", "bengal", "bobcat", "caiman", "cattle", "cicada", "collie", "condor", "cougar", "coyote", "dassie", "donkey", "dragon", "earwig", "falcon", "feline", "ferret", "gannet", "gibbon", "glider", "goblin", "gopher", "grouse", "guinea", "hermit", "hornet", "iguana", "impala", "insect", "jackal", "jaguar", "jennet", "kitten", "kodiak", "lizard", "locust", "maggot", "magpie", "mammal", "mantis", "marlin", "marmot", "marten", "martin", "mayfly", "minnow", "monkey", "mullet", "muskox", "ocelot", "oriole", "osprey", "oyster", "parrot", "pigeon", "piglet", "poodle", "possum", "python", "quagga", "rabbit", "raptor", "rodent", "roughy", "salmon", "sawfly", "serval", "shiner", "shrimp", "spider", "sponge", "tarpon", "thrush", "tomcat", "toucan", "turkey", "turtle", "urchin", "vervet", "walrus", "weasel", "weevil", "wombat", "anchovy", "anemone", "bluejay", "buffalo", "bulldog", "buzzard", "caribou", "catfish", "chamois", "cheetah", "chicken", "chigger", "cowbird", "crappie", "crawdad", "cricket", "dogfish", "dolphin", "firefly", "garfish", "gazelle", "gelding", "giraffe", "gobbler", "gorilla", "goshawk", "grackle", "griffon", "grizzly", "grouper", "haddock", "hagfish", "halibut", "hamster", "herring", "jackass", "javelin", "jawfish", "jaybird", "katydid", "ladybug", "lamprey", "lemming", "leopard", "lioness", "lobster", "macaque", "mallard", "mammoth", "manatee", "mastiff", "meerkat", "mollusk", "monarch", "mongrel", "monitor", "monster", "mudfish", "muskrat", "mustang", "narwhal", "oarfish", "octopus", "opossum", "ostrich", "panther", "peacock", "pegasus", "pelican", "penguin", "phoenix", "piranha", "polecat", "primate", "quetzal", "raccoon", "rattler", "redbird", "redfish", "reptile", "rooster", "sawfish", "sculpin", "seagull", "skylark", "snapper", "spaniel", "sparrow", "sunbeam", "sunbird", "sunfish", "tadpole", "termite", "terrier", "unicorn", "vulture", "wallaby", "walleye", "warthog", "whippet", "wildcat", "aardvark", "airedale", "albacore", "anteater", "antelope", "arachnid", "barnacle", "basilisk", "blowfish", "bluebird", "bluegill", "bonefish", "bullfrog", "cardinal", "chipmunk", "cockatoo", "crayfish", "dinosaur", "doberman", "duckling", "elephant", "escargot", "flamingo", "flounder", "foxhound", "glowworm", "goldfish", "grubworm", "hedgehog", "honeybee", "hookworm", "humpback", "kangaroo", "killdeer", "kingfish", "labrador", "lacewing", "ladybird", "lionfish", "longhorn", "mackerel", "malamute", "marmoset", "mastodon", "moccasin", "mongoose", "monkfish", "mosquito", "pangolin", "parakeet", "pheasant", "pipefish", "platypus", "polliwog", "porpoise", "reindeer", "ringtail", "sailfish", "scorpion", "seahorse", "seasnail", "sheepdog", "shepherd", "silkworm", "squirrel", "stallion", "starfish", "starling", "stingray", "stinkbug", "sturgeon", "terrapin", "titmouse", "tortoise", "treefrog", "werewolf", "woodcock"} + +func (s *server) HashName() string { + var bytes []byte = s.config.PublicKey + var words []string + for i := 0; i < 8; i++ { + index := int(binary.BigEndian.Uint32(bytes[i*4:(i+1)*4])) % len(namesSmall) + words = append(words, namesSmall[index]) + } + return strings.Join(words, "-") +} diff --git a/serverConfig.go b/serverConfig.go index b305db3..7b3834b 100644 --- a/serverConfig.go +++ b/serverConfig.go @@ -2,15 +2,22 @@ package server import ( "crypto/rand" + v1 "cwtch.im/cwtch/storage/v1" "encoding/json" "git.openprivacy.ca/cwtch.im/tapir/primitives" "git.openprivacy.ca/openprivacy/log" "github.com/gtank/ristretto255" "golang.org/x/crypto/ed25519" "io/ioutil" + "os" "path" ) +const ( + // SaltFile is the standard filename to store an encrypted config's SALT under beside it + SaltFile = "SALT" +) + // 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 { LogMetricsToFile bool `json:"logMetricsToFile"` @@ -22,7 +29,9 @@ type Reporting struct { type Config struct { ConfigDir string `json:"-"` FilePath string `json:"-"` - MaxBufferLines int `json:"maxBufferLines"` + Encrypted bool `json:"-"` + key [32]byte + MaxBufferLines int `json:"maxBufferLines"` PublicKey ed25519.PublicKey `json:"publicKey"` PrivateKey ed25519.PrivateKey `json:"privateKey"` @@ -46,17 +55,8 @@ func (config *Config) TokenServiceIdentity() primitives.Identity { return primitives.InitializeIdentity("", &config.TokenServerPrivateKey, &config.TokenServerPublicKey) } -// Save dumps the latest version of the config to a json file given by filename -func (config *Config) Save(dir, filename string) { - log.Infof("Saving config to %s\n", path.Join(dir, filename)) - bytes, _ := json.MarshalIndent(config, "", "\t") - ioutil.WriteFile(path.Join(dir, filename), bytes, 0600) -} - -// LoadConfig loads a Config from a json file specified by filename -func LoadConfig(configDir, filename string) Config { - log.Infof("Loading config from %s\n", path.Join(configDir, filename)) - config := Config{} +func initDefaultConfig(configDir, filename string, encrypted bool) Config { + config := Config{Encrypted: encrypted, ConfigDir: configDir, FilePath: filename} id, pk := primitives.InitializeEphemeralIdentity() tid, tpk := primitives.InitializeEphemeralIdentity() @@ -71,8 +71,6 @@ func LoadConfig(configDir, filename string) Config { ReportingServerAddr: "", } config.AutoStart = false - config.ConfigDir = configDir - config.FilePath = filename k := new(ristretto255.Scalar) b := make([]byte, 64) @@ -83,16 +81,87 @@ func LoadConfig(configDir, filename string) Config { } k.FromUniformBytes(b) config.TokenServiceK = *k - - raw, err := ioutil.ReadFile(path.Join(configDir, filename)) - if err == nil { - err = json.Unmarshal(raw, &config) - - if err != nil { - log.Errorf("reading config: %v", err) - } - } - // Always save (first time generation, new version with new variables populated) - config.Save(configDir, filename) return config } + +// LoadCreateDefaultConfigFile loads a Config from or creates a default config and saves it to a json file specified by filename +// if the encrypted flag is true the config is store encrypted by password +func LoadCreateDefaultConfigFile(configDir, filename string, encrypted bool, password string) (*Config, error) { + if _, err := os.Stat(path.Join(configDir, filename)); os.IsNotExist(err) { + return CreateConfig(configDir, filename, encrypted, password) + } + return LoadConfig(configDir, filename, encrypted, password) +} + +// CreateConfig creates a default config and saves it to a json file specified by filename +// if the encrypted flag is true the config is store encrypted by password +func CreateConfig(configDir, filename string, encrypted bool, password string) (*Config, error) { + os.Mkdir(configDir, 0700) + config := initDefaultConfig(configDir, filename, encrypted) + if encrypted { + key, _, err := v1.InitV1Directory(configDir, password) + if err != nil { + log.Errorf("Could not create server directory: %s", err) + return nil, err + } + config.key = key + } + + config.Save() + return &config, nil +} + +// LoadConfig loads a Config from a json file specified by filename +func LoadConfig(configDir, filename string, encrypted bool, password string) (*Config, error) { + log.Infof("Loading config from %s\n", path.Join(configDir, filename)) + + config := initDefaultConfig(configDir, filename, encrypted) + + raw, err := ioutil.ReadFile(path.Join(configDir, filename)) + if err != nil { + return nil, err + } + + if encrypted { + salt, err := ioutil.ReadFile(path.Join(configDir, SaltFile)) + if err != nil { + return nil, err + } + key := v1.CreateKey(password, salt) + settingsStore := v1.NewFileStore(configDir, ServerConfigFile, key) + raw, err = settingsStore.Read() + if err != nil { + return nil, err + } + } + + if err = json.Unmarshal(raw, &config); err != nil { + log.Errorf("reading config: %v", err) + return nil, err + } + + // Always save (first time generation, new version with new variables populated) + config.Save() + return &config, nil +} + +// Save dumps the latest version of the config to a json file given by filename +func (config *Config) Save() error { + log.Infof("Saving config to %s\n", path.Join(config.ConfigDir, config.FilePath)) + bytes, _ := json.MarshalIndent(config, "", "\t") + if config.Encrypted { + settingStore := v1.NewFileStore(config.ConfigDir, config.FilePath, config.key) + return settingStore.Write(bytes) + } + return ioutil.WriteFile(path.Join(config.ConfigDir, config.FilePath), bytes, 0600) +} + +// CheckPassword returns true if the given password produces the same key as the current stored key, otherwise false. +func (config *Config) CheckPassword(checkpass string) bool { + salt, err := ioutil.ReadFile(path.Join(config.ConfigDir, SaltFile)) + if err != nil { + return false + } + oldkey := v1.CreateKey(checkpass, salt[:]) + return oldkey == config.key +} diff --git a/server_tokenboard.go b/server_tokenboard.go index 0ad36c1..bf5924c 100644 --- a/server_tokenboard.go +++ b/server_tokenboard.go @@ -50,14 +50,14 @@ func (ta *TokenboardServer) Listen() { for { data := ta.connection.Expect() if len(data) == 0 { - log.Debugf("Server Closing Connection") + log.Debugf("server Closing Connection") ta.connection.Close() return // connection is closed } var message groups.Message if err := json.Unmarshal(data, &message); err != nil { - log.Debugf("Server Closing Connection Because of Malformed Client Packet %v", err) + log.Debugf("server Closing Connection Because of Malformed Client Packet %v", err) ta.connection.Close() return // connection is closed } @@ -69,7 +69,7 @@ func (ta *TokenboardServer) Listen() { log.Debugf("Received a Post Message Request: %v", ta.connection.Hostname()) ta.postMessageRequest(postrequest) } else { - log.Debugf("Server Closing Connection Because of PostRequestMessage Client Packet") + log.Debugf("server Closing Connection Because of PostRequestMessage Client Packet") ta.connection.Close() return // connection is closed } @@ -97,7 +97,7 @@ func (ta *TokenboardServer) Listen() { ta.connection.Send(data) } } else { - log.Debugf("Server Closing Connection Because of Malformed ReplayRequestMessage Packet") + log.Debugf("server Closing Connection Because of Malformed ReplayRequestMessage Packet") ta.connection.Close() return // connection is closed } diff --git a/servers.go b/servers.go new file mode 100644 index 0000000..5849245 --- /dev/null +++ b/servers.go @@ -0,0 +1,134 @@ +package server + +import ( + "cwtch.im/cwtch/model" + "errors" + "fmt" + "git.openprivacy.ca/openprivacy/connectivity" + "io/ioutil" + "path" + "sync" +) + +// Servers is an interface to manage multiple Cwtch servers +// Unlike a standalone server, server's dirs will be under one "$CwtchDir/servers" and use a cwtch style localID to obscure +// what servers are hosted. Users are of course free to use a default password. This means Config file will be encrypted +// with cwtch/storage/v1/file_enc and monitor files will not be generated +type Servers interface { + LoadServers(password string) ([]string, error) + CreateServer(password string) (Server, error) + + GetServer(onion string) Server + ListServers() []string + DeleteServer(onion string, currentPassword string) error + + LaunchServers() + ShutdownServer(string) + Shutdown() +} + +type servers struct { + lock sync.Mutex + servers map[string]Server + directory string + acn connectivity.ACN +} + +// NewServers returns a Servers interface to manage a collection of servers +// expecting directory: $CWTCH_HOME/servers +func NewServers(acn connectivity.ACN, directory string) Servers { + return &servers{acn: acn, directory: directory} +} + +// LoadServers will attempt to load any servers in the servers directory that are encrypted with the supplied password +// returns a list of onions identifiers for servers loaded or an error +func (s *servers) LoadServers(password string) ([]string, error) { + s.lock.Lock() + defer s.lock.Unlock() + + dirs, err := ioutil.ReadDir(s.directory) + if err != nil { + return nil, fmt.Errorf("error: cannot read server directory: %v", err) + } + + loadedServers := []string{} + for _, dir := range dirs { + newConfig, err := LoadConfig(path.Join(s.directory, dir.Name()), ServerConfigFile, true, password) + if err == nil { + server := NewServer(newConfig) + s.servers[server.Onion()] = server + loadedServers = append(loadedServers, server.Onion()) + } + } + return loadedServers, nil +} + +// CreateServer creates a new server and stores it, also returns an interface to it +func (s *servers) CreateServer(password string) (Server, error) { + newLocalID := model.GenerateRandomID() + directory := path.Join(s.directory, newLocalID) + config, err := CreateConfig(directory, ServerConfigFile, true, password) + if err != nil { + return nil, err + } + server := NewServer(config) + s.lock.Lock() + defer s.lock.Unlock() + s.servers[server.Onion()] = server + return server, nil +} + +// GetServer returns a server interface for the supplied onion +func (s *servers) GetServer(onion string) Server { + s.lock.Lock() + defer s.lock.Unlock() + return s.servers[onion] +} + +// ListServers returns a list of server onion identifies this servers struct is managing +func (s *servers) ListServers() []string { + s.lock.Lock() + defer s.lock.Unlock() + list := []string{} + for onion := range s.servers { + list = append(list, onion) + } + return list +} + +// DeleteServer delete's the requested server (assuming the passwords match +func (s *servers) DeleteServer(onion string, password string) error { + s.lock.Lock() + defer s.lock.Unlock() + server := s.servers[onion] + if server != nil { + server.Shutdown() + err := server.Delete(password) + delete(s.servers, onion) + return err + } + return errors.New("Server not found") +} + +// LaunchServers Run() all loaded servers +func (s *servers) LaunchServers() { + s.lock.Lock() + defer s.lock.Unlock() + for _, server := range s.servers { + server.Run(s.acn) + } +} + +// ShutdownServer Shutsdown the specified server +func (s *servers) ShutdownServer(onion string) { + s.servers[onion].Shutdown() +} + +// Shutdown shutsdown all the servers +func (s *servers) Shutdown() { + s.lock.Lock() + defer s.lock.Unlock() + for _, server := range s.servers { + server.Shutdown() + } +} diff --git a/storage/message_store.go b/storage/message_store.go index 7cbb274..2e4f83d 100644 --- a/storage/message_store.go +++ b/storage/message_store.go @@ -2,10 +2,10 @@ package storage import ( "cwtch.im/cwtch/protocol/groups" - "git.openprivacy.ca/cwtch.im/server/metrics" "database/sql" "encoding/base64" "fmt" + "git.openprivacy.ca/cwtch.im/server/metrics" "git.openprivacy.ca/openprivacy/log" _ "github.com/mattn/go-sqlite3" // sqlite3 driver ) diff --git a/storage/message_store_test.go b/storage/message_store_test.go index 97316d5..54dd364 100644 --- a/storage/message_store_test.go +++ b/storage/message_store_test.go @@ -2,8 +2,8 @@ package storage import ( "cwtch.im/cwtch/protocol/groups" - "git.openprivacy.ca/cwtch.im/server/metrics" "encoding/binary" + "git.openprivacy.ca/cwtch.im/server/metrics" "git.openprivacy.ca/openprivacy/log" "os" "testing"