-
Notifications
You must be signed in to change notification settings - Fork 1
/
Restore.go
85 lines (78 loc) · 2.51 KB
/
Restore.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
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"errors"
"fmt"
"os"
"path"
"github.com/mkideal/cli"
)
type restoreT struct {
cli.Helper
RestoreIPtables bool `cli:"t,iptables" usage:"Restore iptables" dft:"false"`
RestoreIPset bool `cli:"s,ipset" usage:"Restore ipset" dft:"true"`
All bool `cli:"a,all" usage:"Restore ipset and iptables" dft:"false"`
ConfigName string `cli:"C,config" usage:"Specify the config to use" dft:"config.json"`
Verbose int `cli:"v,verbose" usage:"Specify how much logs should be displayed" dft:"0"`
}
var restoreCMD = &cli.Command{
Name: "restore",
Aliases: []string{"res", "restore", "rest"},
Desc: "restore ipset and iptables",
Argv: func() interface{} { return new(restoreT) },
Fn: func(ctx *cli.Context) error {
if os.Getuid() != 0 {
fmt.Println("You need to be root!")
return nil
}
argv := ctx.Argv().(*restoreT)
verboseLevel = argv.Verbose
logStatus, configFile := createAndValidateConfigFile(argv.ConfigName)
if logStatus < 0 {
return errors.New("config not found")
}
if argv.All {
argv.RestoreIPset = true
argv.RestoreIPtables = true
}
restoreIPs(configFile, argv.RestoreIPset, argv.RestoreIPtables)
return nil
},
}
func restoreIPs(configFile string, restoreIPset, restoreIPtables bool) {
configFolder, configfilename := path.Split(configFile)
blocklistName := getBlocklistName(configfilename)
iptablesFile := configFolder + "iptables_" + blocklistName + ".bak"
ipsetFile := configFolder + "ipset_" + blocklistName + ".bak"
if restoreIPset {
if isIpsetInstalled(false) {
stat, err := os.Stat(ipsetFile)
if err != nil || stat.Size() == 0 {
_, err = os.Create(ipsetFile)
LogInfo("There is no ipset backup! Skipping")
} else {
runCommand(nil, "ipset flush "+blocklistName)
_, err = runCommand(nil, "ipset restore < "+ipsetFile)
if err != nil {
LogError("Error restoring ipset: " + err.Error() + " -> \"" + "ipset restore < " + ipsetFile + "\"")
} else {
LogInfo("Successfully restored ipset")
}
}
} else {
LogInfo("IPset not installed, can't restore. Skipping")
}
}
if restoreIPtables {
stat, err := os.Stat(iptablesFile)
if err != nil || stat.Size() == 0 {
LogError("There is no iptables backup! Skipping")
} else {
_, err = runCommand(nil, "iptables-restore < "+iptablesFile)
if err != nil {
LogError("Error restoring iptables: " + err.Error() + "-> \"" + "iptables-restore < " + iptablesFile + "\"")
} else {
LogInfo("Successfully restored iptables")
}
}
}
}