-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
186 lines (149 loc) · 4.5 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"os"
"regexp"
"strings"
"time"
"github.com/spf13/cobra"
)
func overrideCmd() *cobra.Command {
var refresh bool
var refreshInterval time.Duration
rootCmd := &cobra.Command{
Use: "hosts-override [HOST_NAME,(IP|RESOLVABLE_HOST_NAME)...]",
Short: "Override hosts file entries for the lifetime of the process",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
clearScreen()
entries := parseArgs(&args)
file := hostsFileLocation()
createHostsBackup(file)
removeOverrides(file) // Fixes unclean shutdown
expandedEntries := parseOverrides(entries, false)
appendOverrides(file, expandedEntries)
displayStatus(&refresh, refreshInterval, expandedEntries)
if refresh {
refreshTicker := time.NewTicker(refreshInterval)
go func() {
for {
select {
case <-refreshTicker.C:
expandedEntries := parseOverrides(entries, true)
if expandedEntries != nil {
removeOverrides(file)
clearScreen()
appendOverrides(file, expandedEntries)
displayStatus(&refresh, refreshInterval, expandedEntries)
}
}
}
}()
}
waitUntilExit()
removeOverrides(file)
},
}
rootCmd.Flags().BoolVarP(&refresh, "refresh", "r", false, "Refresh unresolved hosts")
rootCmd.Flags().DurationVarP(&refreshInterval, "refresh-interval", "i", time.Duration(5)*time.Minute, "Refresh Interval")
return rootCmd
}
func main() {
overrideCmd().Execute()
}
func parseArgs(args *[]string) *hostsFileEntries {
var entries hostsFileEntries
for _, pair := range *args {
hv := strings.Split(pair, ",")
entries = append(entries, &hostsFileEntry{&hv[0], &hv[1], nil})
}
return &entries
}
func parseOverrides(entries *hostsFileEntries, continueOnError bool) *hostsFileEntries {
expandedEntries := hostsFileEntries{}
for _, entry := range *entries {
if maybeIP := *maybeIP(entry.ip); maybeIP != "" {
expandedEntries = append(expandedEntries, entry)
} else {
// NOTE: Try to resolve google.com, but this could be any domain to test
// if there is an Internet connection and hosts are resolvable.
//
// Can't use user provided domains, as they can already be in the
// hosts file and will provide a false positive.
_, googleErr := net.LookupIP("google.com")
ips, err := net.LookupIP(*entry.ip)
if googleErr != nil || err != nil {
if continueOnError {
return nil
}
fmt.Fprintf(os.Stderr, "Could not get IPs: %v\n", err)
os.Exit(1)
}
for _, ip := range ips {
ip := ip.String()
expandedEntries = append(
expandedEntries,
&hostsFileEntry{hostname: entry.hostname, ip: &ip, ipResovledFrom: entry.ip},
)
}
}
}
return &expandedEntries
}
func appendOverrides(hostsFileLocation *string, entries *hostsFileEntries) {
f, err := os.OpenFile(*hostsFileLocation, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
os.Exit(1)
}
defer f.Close()
if _, err := f.WriteString(*entriesAsString(entries)); err != nil {
log.Println(err)
}
}
func removeOverrides(hostsFileLocation *string) {
contents, err := ioutil.ReadFile(*hostsFileLocation)
if err != nil {
fmt.Println(err)
return
}
re := regexp.MustCompile("(?s)(" + startComment() + ").*(" + finishComment() + ")")
removedOverrides := re.ReplaceAll(contents, []byte(""))
if err := ioutil.WriteFile(*hostsFileLocation, removedOverrides, 0); err != nil {
log.Println(err)
}
}
func displayStatus(refresh *bool, refreshInterval time.Duration, entries *hostsFileEntries) {
fmt.Println("\nhosts-override: Overriding hosts file entries for the lifetime of the process")
if *refresh == true {
fmt.Println("\n(Refreshing every " + refreshInterval.String() + ")...")
}
fmt.Println("\n" + *entriesAsString(entries) + "\n")
fmt.Println("\nPress CTRL-C to exit gracefully (hosts file will reset)")
}
func wrappingComment(custom string) string {
return "\n#########################\n" +
"# hosts-override " + custom +
"\n#########################\n\n"
}
func startComment() string {
return wrappingComment("START")
}
func finishComment() string {
return wrappingComment("FINISH")
}
func entriesAsString(entries *hostsFileEntries) *string {
o := startComment()
for _, entry := range *entries {
o = o + fmt.Sprintf("%-16v", *entry.ip) + " " + *entry.hostname
if entry.ipResovledFrom != nil {
o = o + " # IP resolved from " + *entry.ipResovledFrom
}
o = o + "\n"
}
o = o + finishComment()
return &o
}