/
main.go
277 lines (242 loc) · 5.79 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package main
import (
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"regexp"
"runtime"
"time"
"github.com/creativeprojects/clog"
"github.com/creativeprojects/hosts-filter/cfg"
"github.com/creativeprojects/hosts-filter/constants"
"github.com/creativeprojects/hosts-filter/hosts"
"github.com/creativeprojects/hosts-filter/list"
)
// These fields are populated by the goreleaser build
var (
version = "0.1.0-dev"
commit = ""
date = ""
builtBy = ""
)
func main() {
var exitCode = 0
var err error
// trick to run all defer functions before returning with an exit code
defer func() {
if exitCode != 0 {
os.Exit(exitCode)
}
}()
flagset, flags := loadFlags()
// help
if flags.help {
flagset.Usage()
return
}
if flags.logFile != "" {
file, err := setupFileLogger(flags)
if err != nil {
// back to a console logger
setupConsoleLogger(flags)
clog.Errorf("cannot open logfile: %s", err)
} else {
// close the log file at the end
defer file.Close()
}
} else {
// Use the console logger
setupConsoleLogger(flags)
}
// keep this defer last if possible (so it will be first at the end)
defer showPanicData()
banner()
// seed random number generation
rand.Seed(time.Now().UnixNano())
configFile, err := cfg.FindConfigurationFile(flags.config)
if err != nil {
clog.Error(err)
exitCode = 1
return
}
if configFile != flags.config {
clog.Infof("using configuration file: %s", configFile)
}
c, err := cfg.LoadFile(configFile)
if err != nil {
clog.Errorf("cannot load configuration file: %v", err)
exitCode = 1
return
}
// validate missing configuration with defaults
if c.IP == "" {
c.IP = constants.DefaultFilteredIP
}
if c.HostsFile == "" {
if runtime.GOOS == "windows" {
c.HostsFile = constants.DefaultWindowsHostFile
} else {
c.HostsFile = constants.DefaultUnixHostFile
}
}
c.HostsFile = expandEnv(c.HostsFile)
var entries map[string]bool
// load the entries if not in remove mode - otherwise empty entries will remove the section from the hosts file
if !flags.remove {
entries = make(map[string]bool, constants.BufferInitialEntries)
for _, def := range c.BlockLists {
if def.URL == "" {
continue
}
err := loadListfile(def.URL, entries)
if err != nil {
clog.Error(err)
continue
}
}
if len(entries) == 0 {
clog.Warning("the blocklist is empty")
exitCode = 1
return
}
// remove entries from the allow list
for _, allow := range c.Allow {
if allow == "" {
continue
}
delete(entries, allow)
}
if c.AllowFrom != "" {
allowList, err := loadAllowList(c.AllowFrom)
if err != nil {
clog.Errorf("error while loading the allow list: %v", err)
} else {
for _, allow := range allowList {
if allow == "" {
continue
}
delete(entries, allow)
}
}
}
}
var source string
if fileExists(c.HostsFile) {
source, err = loadHostsfile(c.HostsFile)
if err != nil {
clog.Errorf("cannot read hosts file: %v", err)
exitCode = 1
return
}
} else {
clog.Warningf("hosts file %q does not exist and will be created.", c.HostsFile)
}
if flags.stdout {
// send the file to the default output
err = hosts.Update(source, c.IP, list.SortedKeys(entries), os.Stdout)
if err != nil {
clog.Errorf("cannot write to standard output: %v", err)
exitCode = 1
return
}
return
}
// save the hosts file back (via a temporary file)
tempfile := c.HostsFile + "-" + randSeq(6)
err = saveHostsfile(source, c.IP, list.SortedKeys(entries), tempfile)
if err != nil {
clog.Errorf("cannot write to temporary file: %v", err)
exitCode = 1
return
}
// now rename the temp file into the hosts file
err = os.Rename(tempfile, c.HostsFile)
if err != nil {
clog.Errorf("cannot move the temporary file into place: %v", err)
exitCode = 1
return
}
clog.Debugf("file %q successfully saved", c.HostsFile)
}
func banner() {
clog.Debugf("%s %s compiled with %s", constants.Name, version, runtime.Version())
}
func loadListfile(filename string, entries map[string]bool) error {
var reader io.Reader
URL, err := url.Parse(filename)
if err != nil || URL.Scheme == "" {
// entry should be a file on disk
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
reader = file
} else {
// entry is http resource
resp, err := http.Get(filename)
if err != nil {
return err
}
defer resp.Body.Close()
reader = resp.Body
}
lines, err := list.LoadLines(reader)
if err != nil {
return err
}
list.LoadEntries(lines, entries)
clog.Infof("loaded %q: %d entries in total", filename, len(entries))
return nil
}
func loadHostsfile(hostsfile string) (string, error) {
file, err := os.Open(hostsfile)
if err != nil {
return "", err
}
defer file.Close()
buffer, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
return string(buffer), nil
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func saveHostsfile(source, ip string, entries []string, dest string) error {
file, err := os.Create(dest)
if err != nil {
return err
}
defer file.Close()
return hosts.Update(source, ip, entries, file)
}
func randSeq(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyz")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func expandEnv(value string) string {
if runtime.GOOS == "windows" {
// variable expansion is always done the "unix" way, but never the "windows" way
pattern := regexp.MustCompile(`%([^%]+)%`)
value = pattern.ReplaceAllString(value, `${$1}`)
}
return os.ExpandEnv(value)
}
func loadAllowList(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return list.LoadLines(file)
}