Fail softly and create necessary directory for config

socks-filter
xSmurf 8 years ago
parent c10ba7df23
commit d4e09d2f51

@ -1,12 +1,10 @@
// TODO: Check permissions on file
// TODO: Create dir if needed
// TODO: Dont' fail hard on failed read
package main package main
import ( import (
"bufio" "bufio"
"io/ioutil" "io/ioutil"
"os" "os"
"path"
"github.com/naoina/toml" "github.com/naoina/toml"
"github.com/op/go-logging" "github.com/op/go-logging"
@ -28,18 +26,25 @@ type FirewallConfigs struct {
var FirewallConfig FirewallConfigs var FirewallConfig FirewallConfigs
func readConfig() { func _readConfig(file string) []byte {
f, err := os.Open(configDefaultPath) f, err := os.Open(configDefaultPath)
if err != nil { if err != nil {
log.Error(err.Error()) log.Warning(err.Error())
os.Exit(1) return []byte{}
} }
defer f.Close() defer f.Close()
buf, err := ioutil.ReadAll(f) buf, err := ioutil.ReadAll(f)
if err != nil { if err != nil {
log.Error(err.Error()) log.Warning(err.Error())
os.Exit(1) return []byte{}
} }
return buf
}
func readConfig() {
buf := _readConfig(configDefaultPath)
FirewallConfig = FirewallConfigs{ FirewallConfig = FirewallConfigs{
LogLevel: "NOTICE", LogLevel: "NOTICE",
LoggingLevel: logging.NOTICE, LoggingLevel: logging.NOTICE,
@ -50,10 +55,12 @@ func readConfig() {
DefaultActionId: 1, DefaultActionId: 1,
} }
if len(buf) > 0 {
if err := toml.Unmarshal(buf, &FirewallConfig); err != nil { if err := toml.Unmarshal(buf, &FirewallConfig); err != nil {
log.Error(err.Error()) log.Error(err.Error())
os.Exit(1) os.Exit(1)
} }
}
FirewallConfig.LoggingLevel, _ = logging.LogLevel(FirewallConfig.LogLevel) FirewallConfig.LoggingLevel, _ = logging.LogLevel(FirewallConfig.LogLevel)
FirewallConfig.DefaultActionId = valueScope(FirewallConfig.DefaultAction) FirewallConfig.DefaultActionId = valueScope(FirewallConfig.DefaultAction)
} }
@ -62,10 +69,19 @@ func writeConfig() {
FirewallConfig.LogLevel = FirewallConfig.LoggingLevel.String() FirewallConfig.LogLevel = FirewallConfig.LoggingLevel.String()
FirewallConfig.DefaultAction = printScope(FirewallConfig.DefaultActionId) FirewallConfig.DefaultAction = printScope(FirewallConfig.DefaultActionId)
if _, err := os.Stat(path.Dir(configDefaultPath)); err != nil && os.IsNotExist(err) {
if err := os.MkdirAll(path.Dir(configDefaultPath), 0755); err != nil {
log.Error(err.Error())
//os.Exit(1)
return
}
}
f, err := os.Create(configDefaultPath) f, err := os.Create(configDefaultPath)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
os.Exit(1) //os.Exit(1)
return
} }
defer f.Close() defer f.Close()
@ -73,7 +89,8 @@ func writeConfig() {
cw := toml.NewEncoder(w) cw := toml.NewEncoder(w)
if err := cw.Encode(FirewallConfig); err != nil { if err := cw.Encode(FirewallConfig); err != nil {
log.Error(err.Error()) log.Error(err.Error())
os.Exit(1) //os.Exit(1)
return
} }
w.Flush() w.Flush()
} }

Loading…
Cancel
Save