forked from lobre/goodhosts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goodhosts.go
269 lines (220 loc) · 5.21 KB
/
goodhosts.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
package goodhosts
import (
"bufio"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strings"
)
const commentChar string = "#"
// Represents a single line in the hosts file.
type HostsLine struct {
IP string
Hosts []string
Raw string
Err error
}
// Return ```true``` if the line is a comment.
func (l HostsLine) IsComment() bool {
trimLine := strings.TrimSpace(l.Raw)
isComment := strings.HasPrefix(trimLine, commentChar)
return isComment
}
// Return a new instance of ```HostsLine```.
func NewHostsLine(raw string) HostsLine {
fields := strings.Fields(raw)
if len(fields) == 0 {
return HostsLine{Raw: raw}
}
output := HostsLine{Raw: raw}
if !output.IsComment() {
rawIP := fields[0]
if net.ParseIP(rawIP) == nil {
output.Err = errors.New(fmt.Sprintf("Bad hosts line: %q", raw))
}
output.IP = rawIP
output.Hosts = fields[1:]
}
return output
}
// Represents a hosts file.
type Hosts struct {
Path string
Lines []HostsLine
EOL string
Single bool
}
// Return ```true``` if hosts file is writable.
func (h *Hosts) IsWritable() bool {
_, err := os.OpenFile(h.Path, os.O_WRONLY, 0660)
if err != nil {
return false
}
return true
}
// Load the hosts file into ```l.Lines```.
// ```Load()``` is called by ```NewHosts()``` and ```Hosts.Flush()``` so you
// generally you won't need to call this yourself.
func (h *Hosts) Load() error {
var lines []HostsLine
file, err := os.Open(h.Path)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := NewHostsLine(scanner.Text())
if err != nil {
return err
}
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
return err
}
h.Lines = lines
return nil
}
// Flush any changes made to hosts file.
func (h Hosts) Flush() error {
file, err := os.Create(h.Path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range h.Lines {
if h.Single && line.IP != "" {
for _, host := range line.Hosts {
fmt.Fprintf(w, "%s %s%s", line.IP, host, h.EOL)
}
} else {
fmt.Fprintf(w, "%s%s", line.Raw, h.EOL)
}
}
err = w.Flush()
if err != nil {
return err
}
return h.Load()
}
// Add an entry to the hosts file.
func (h *Hosts) Add(ip string, hosts ...string) error {
if net.ParseIP(ip) == nil {
return errors.New(fmt.Sprintf("%q is an invalid IP address.", ip))
}
position := h.getIpPosition(ip)
if position == -1 {
endLine := NewHostsLine(buildRawLine(ip, hosts))
// Ip line is not in file, so we just append our new line.
h.Lines = append(h.Lines, endLine)
} else {
// Otherwise, we replace the line in the correct position
newHosts := h.Lines[position].Hosts
for _, addHost := range hosts {
if itemInSlice(addHost, newHosts) {
continue
}
newHosts = append(newHosts, addHost)
}
endLine := NewHostsLine(buildRawLine(ip, newHosts))
h.Lines[position] = endLine
}
return nil
}
// Return a bool if ip/host combo in hosts file.
func (h Hosts) Has(ip string, host string) bool {
pos := h.getHostPosition(ip, host)
return pos != -1
}
// Remove an entry from the hosts file.
func (h *Hosts) Remove(ip string, hosts ...string) error {
var outputLines []HostsLine
if ip != "" && net.ParseIP(ip) == nil {
return errors.New(fmt.Sprintf("%q is an invalid IP address.", ip))
}
for _, line := range h.Lines {
// Bad lines or comments just get readded.
if line.Err != nil || line.IsComment() || (ip != "" && line.IP != ip) {
outputLines = append(outputLines, line)
continue
}
var newHosts []string
for _, checkHost := range line.Hosts {
if !itemInSlice(checkHost, hosts) {
newHosts = append(newHosts, checkHost)
}
}
// If hosts is empty, skip the line completely.
if len(newHosts) > 0 {
newLineRaw := line.IP
for _, host := range newHosts {
newLineRaw = fmt.Sprintf("%s %s", newLineRaw, host)
}
newLine := NewHostsLine(newLineRaw)
outputLines = append(outputLines, newLine)
}
}
h.Lines = outputLines
return nil
}
func (h Hosts) getHostPosition(ip string, host string) int {
for i := range h.Lines {
line := h.Lines[i]
if !line.IsComment() && line.Raw != "" {
if (ip != "" && ip == line.IP) && itemInSlice(host, line.Hosts) {
return i
}
}
}
return -1
}
func (h Hosts) getIpPosition(ip string) int {
for i := range h.Lines {
line := h.Lines[i]
if !line.IsComment() && line.Raw != "" {
if line.IP == ip {
return i
}
}
}
return -1
}
// Force Windows style no matter the current os
// This can be handy if a Windows hosts file is mounted into a docker container for instance
func (h *Hosts) ForceWindowsStyle() {
h.EOL = "\r\n"
h.Single = true
}
// Return a new instance of ``Hosts``.
func NewHosts() (Hosts, error) {
hosts := Hosts{
Path: os.ExpandEnv(filepath.FromSlash(defaultPath)),
EOL: defaultEOL,
Single: defaultSingle,
}
err := hosts.Load()
if err != nil {
return hosts, err
}
return hosts, nil
}
// Return a new instance of ``Hosts`` with custom Path.
func NewHostsPath(path string) (Hosts, error) {
if path == "" {
return NewHosts()
}
hosts := Hosts{
Path: path,
EOL: defaultEOL,
Single: defaultSingle,
}
err := hosts.Load()
if err != nil {
return hosts, err
}
return hosts, nil
}