Skip to content

Commit

Permalink
Allow more flexible configuration locations
Browse files Browse the repository at this point in the history
This adds a few standard locations for the configuration file:
  - `os.UserConfigDir()`/apiban/config.json
  - /etc/apiban/config.json
  - ./config.json
  - user-specified config location

Fixes palner#9

Signed-off-by: Seán C McCord <ulexus@gmail.com>
  • Loading branch information
Ulexus committed Mar 28, 2020
1 parent 0ab04b0 commit dfbc91f
Showing 1 changed file with 72 additions and 20 deletions.
92 changes: 72 additions & 20 deletions clients/go/apiban-iptables/apiban-iptables-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
package main

import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime"
Expand All @@ -34,11 +34,19 @@ import (
"github.com/palner/apiban/clients/go/apiban"
)

var configFileLocation string

func init() {
flag.StringVar(&configFileLocation, "config", "", "location of configuration file")
}

// ApibanConfig is the structure for the JSON config file
type ApibanConfig struct {
APIKEY string `json:"APIKEY"`
LKID string `json:"LKID"`
VERSION string `json:"VERSION"`

sourceFile string
}

// Function to see if string within string
Expand All @@ -52,6 +60,8 @@ func contains(list []string, value string) bool {
}

func main() {
flag.Parse()

defer os.Exit(0)
// Open our Log
logfile, err := os.OpenFile("/var/log/apiban-client.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
Expand All @@ -67,23 +77,13 @@ func main() {
log.Print("Licensed under GPLv2. See LICENSE for details.")

// Open our config file
ConfigFile, err := os.Open("/usr/local/bin/apiban/config.json")
apiconfig, err := LoadConfig()
if err != nil {
log.Panic(err)
fmt.Fprintf(os.Stderr, "error: %v\n", err)
runtime.Goexit()
}
defer ConfigFile.Close()

// get config values
ConfigValues, _ := ioutil.ReadAll(ConfigFile)
var apiconfig ApibanConfig
if err := json.Unmarshal(ConfigValues, &apiconfig); err != nil {
log.Fatalln("failed to parse config:", err)
log.Fatalln(err)
}

// if no APIKEY, exit
if len(apiconfig.APIKEY) == 0 {
if apiconfig.APIKEY == "" {
log.Fatalln("Invalid APIKEY. Exiting.")
}

Expand Down Expand Up @@ -182,12 +182,64 @@ func main() {
}

// Update the config with the updated LKID
UpdateConfig := bytes.Replace(ConfigValues, []byte("\""+apiconfig.LKID+"\""), []byte("\""+res.ID+"\""), -1)
if err = ioutil.WriteFile("/usr/local/bin/apiban/config.json", UpdateConfig, 0666); err != nil {
log.Panic(err)
runtime.Goexit()
apiconfig.LKID = res.ID
if err := apiconfig.Update(); err != nil {
log.Fatalln(err)
}

log.Print("** Done. Exiting.")
runtime.Goexit()
}

// LoadConfig attempts to load the APIBAN configuration file from various locations
func LoadConfig() (*ApibanConfig, error) {
var fileLocations []string

// If we have a user-specified configuration file, use it preferentially
if configFileLocation != "" {
fileLocations = append(fileLocations, configFileLocation)
}

// If we can determine the user configuration directory, try there
configDir, err := os.UserConfigDir()
if err == nil {
fileLocations = append(fileLocations, fmt.Sprintf("%s/apiban/config.json", configDir))
}

// Add standard static locations
fileLocations = append(fileLocations,
"/etc/apiban/config.json",
"config.json",
"/usr/local/bin/apiban/config.json",
)

for _, loc := range fileLocations {
f, err := os.Open(loc)
if err != nil {
continue
}
defer f.Close()

cfg := new(ApibanConfig)
if err := json.NewDecoder(f).Decode(cfg); err != nil {
return nil, fmt.Errorf("failed to read configuration from %s: %w", loc, err)
}

// Store the location of the config file so that we can update it later
cfg.sourceFile = loc

return cfg, nil
}

return nil, errors.New("failed to locate configuration file")
}

// Update rewrite the configuration file with and updated state (such as the LKID)
func (cfg *ApibanConfig) Update() error {
f, err := os.Create(cfg.sourceFile)
if err != nil {
return fmt.Errorf("failed to open configuration file for writing: %w", err)
}
defer f.Close()

return json.NewEncoder(f).Encode(cfg)
}

0 comments on commit dfbc91f

Please sign in to comment.