-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosts.go
189 lines (157 loc) · 4.37 KB
/
hosts.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
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"golang.org/x/sys/unix"
)
const (
markerStart = "# BEGIN dblock"
markerEnd = "# END dblock"
)
func EnableBlocking(config *Config) error {
if err := CheckPermissions(config.HostsFile); err != nil {
return err
}
contentBytes, err := ioutil.ReadFile(config.HostsFile)
if err != nil {
return err
}
content := string(contentBytes)
// Create backup
backupDir := filepath.Join(GetHomeDir(), ".dblock", "backups")
err = EnsureDir(backupDir)
if err != nil {
return fmt.Errorf("failed to ensure backup directory: %v", err)
}
backupPath := filepath.Join(backupDir, "hosts.bak")
if err := ioutil.WriteFile(backupPath, contentBytes, 0644); err != nil {
return err
}
// Change ownership of the backup file
uid, gid, err := getOriginalUserIDs()
if err == nil {
os.Chown(backupPath, uid, gid)
}
newContent := RemoveExistingBlocks(content)
blockEntries := GenerateBlockEntries(config)
// Trim trailing spaces and newlines
newContent = strings.TrimRight(newContent, " \n")
// Decide whether to add a newline before the dblock section
if len(newContent) > 0 {
newContent += "\n\n"
} else {
newContent += "\n"
}
// Append the dblock section
newContent += fmt.Sprintf("%s\n%s\n%s", markerStart, blockEntries, markerEnd)
// Ensure the file ends with a single newline
newContent += "\n"
if err := ioutil.WriteFile(config.HostsFile, []byte(newContent), 0644); err != nil {
return err
}
return nil
}
func DisableBlocking(config *Config) error {
if err := CheckPermissions(config.HostsFile); err != nil {
return err
}
contentBytes, err := ioutil.ReadFile(config.HostsFile)
if err != nil {
return err
}
content := string(contentBytes)
// Create backup
backupDir := filepath.Join(GetHomeDir(), ".dblock", "backups")
err = EnsureDir(backupDir)
if err != nil {
return fmt.Errorf("failed to ensure backup directory: %v", err)
}
backupPath := filepath.Join(backupDir, "hosts.bak")
if err := ioutil.WriteFile(backupPath, contentBytes, 0644); err != nil {
return err
}
// Change ownership of the backup file
uid, gid, err := getOriginalUserIDs()
if err == nil {
os.Chown(backupPath, uid, gid)
}
newContent := RemoveExistingBlocks(content)
// Trim trailing spaces and newlines
newContent = strings.TrimRight(newContent, " \n")
// Ensure the file ends with a single newline
if len(newContent) > 0 {
newContent += "\n"
}
if err := ioutil.WriteFile(config.HostsFile, []byte(newContent), 0644); err != nil {
return err
}
return nil
}
func GetStatus(config *Config) (string, error) {
content, err := ioutil.ReadFile(config.HostsFile)
if err != nil {
return "", err
}
if strings.Contains(string(content), markerStart) {
return "Enabled", nil
}
return "Disabled", nil
}
func GenerateBlockEntries(config *Config) string {
var entries []string
for _, domain := range config.Domains {
entries = append(entries, generateDomainEntries(domain)...)
}
for _, subdomain := range config.Subdomains {
entries = append(entries, generateEntry(subdomain))
}
return strings.Join(entries, "\n")
}
func generateDomainEntries(domain string) []string {
subdomains := []string{domain, "www." + domain}
var entries []string
for _, subdomain := range subdomains {
entries = append(entries, generateEntry(subdomain))
}
return entries
}
func generateEntry(domain string) string {
return fmt.Sprintf("127.0.0.1\t%s\n::1\t%s", domain, domain)
}
func RemoveExistingBlocks(content string) string {
lines := strings.Split(content, "\n")
var newLines []string
skip := false
for _, line := range lines {
trimmedLine := strings.TrimSpace(line)
if strings.Contains(trimmedLine, markerStart) {
skip = true
// Remove any preceding blank lines
for len(newLines) > 0 && strings.TrimSpace(newLines[len(newLines)-1]) == "" {
newLines = newLines[:len(newLines)-1]
}
continue
}
if strings.Contains(trimmedLine, markerEnd) {
skip = false
continue
}
if !skip {
newLines = append(newLines, line)
}
}
// Remove any trailing blank lines
for len(newLines) > 0 && strings.TrimSpace(newLines[len(newLines)-1]) == "" {
newLines = newLines[:len(newLines)-1]
}
return strings.Join(newLines, "\n")
}
func CheckPermissions(filePath string) error {
if unix.Access(filePath, unix.W_OK) != nil {
return fmt.Errorf("insufficient permissions to modify %s", filePath)
}
return nil
}