-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconfig.go
74 lines (62 loc) · 1.83 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"github.com/evilsocket/opensnitch/daemon/rule"
)
var defaultConfig = &uiConfig{
DefaultTimeout: 15,
DefaultAction: rule.Allow,
DefaultDuration: rule.Restart,
DefaultOperator: rule.OpProcessPath,
}
type uiConfig struct {
DefaultTimeout uint `json:"default_timeout"`
DefaultAction rule.Action `json:"default_action"`
DefaultDuration rule.Duration `json:"default_duration"`
DefaultOperator rule.Operand `json:"default_operand"`
}
func loadConfigFromFile(configFile string) (*uiConfig, error) {
if strings.HasPrefix(configFile, "~") {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("Could not get the current user's home directory: %v", err)
}
configFile = strings.Replace(configFile, "~", home, 1)
}
_, err := os.Stat(configFile)
if os.IsNotExist(err) {
return createDefaultConfigFile(configFile)
}
cfg := &uiConfig{}
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("Could not open the config file %q. Error: %v", configFile, err)
}
defer f.Close()
err = json.NewDecoder(f).Decode(cfg)
if err != nil {
return nil, fmt.Errorf("Could not read the config file %q. Error: %v", configFile, err)
}
return cfg, nil
}
func createDefaultConfigFile(configFile string) (*uiConfig, error) {
dir := path.Dir(configFile)
err := os.MkdirAll(dir, 0755)
if err != nil {
return nil, fmt.Errorf("Could not create the config folder %q. Error: %v", dir, err)
}
f, err := os.Create(configFile)
if err != nil {
return nil, fmt.Errorf("Could not create the config file %q. Error: %v", configFile, err)
}
defer f.Close()
err = json.NewEncoder(f).Encode(defaultConfig)
if err != nil {
return nil, fmt.Errorf("Could not write the config file %q. Error: %v", configFile, err)
}
return defaultConfig, nil
}