-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosts.go
130 lines (108 loc) · 2.27 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
package main
import (
"github.com/lobre/goodhosts"
)
type hostsProcessor struct {
config config
em entriesManager
}
func newHostsProcessor(config config, em entriesManager) hostsProcessor {
return hostsProcessor{config, em}
}
func (h hostsProcessor) init() error {
return h.add()
}
func (h hostsProcessor) startEvent(id string) error {
return h.add(id)
}
func (h hostsProcessor) dieEvent(id string) error {
return h.remove(id)
}
func (h hostsProcessor) add(ids ...string) error {
entries, err := h.em.get(ids...)
if err != nil {
return err
}
hosts, err := goodhosts.NewHostsPath(h.config.Hosts)
if err != nil {
return err
}
if h.config.HostsForceWindowsStyle {
hosts.ForceWindowsStyle()
}
for _, entry := range entries {
if entry.NoHosts || entry.WebDirect {
continue
}
ip := h.config.ProxyIP
if entry.Direct || !h.config.ProxyMode {
ip = entry.IP
}
for _, segment := range entry.Segments {
for _, host := range segment.Hosts {
hosts.Remove("", host)
hosts.Add(ip, host)
}
}
}
if err := hosts.Flush(); err != nil {
return err
}
return nil
}
func (h hostsProcessor) remove(ids ...string) error {
entries, err := h.em.get(ids...)
if err != nil {
return err
}
hosts, err := goodhosts.NewHostsPath(h.config.Hosts)
if err != nil {
return err
}
if h.config.HostsForceWindowsStyle {
hosts.ForceWindowsStyle()
}
for _, entry := range entries {
ip := h.config.ProxyIP
if entry.Direct || !h.config.ProxyMode {
ip = entry.IP
}
for _, segment := range entry.Segments {
for _, host := range segment.Hosts {
if hosts.Has(ip, host) {
isUnique, err := h.isUnique(host, entry)
if err != nil {
return err
}
if h.config.ProxyMode && !entry.Direct && !isUnique {
continue
}
hosts.Remove(ip, host)
}
}
}
}
if err := hosts.Flush(); err != nil {
return err
}
return nil
}
// Check if host exist in another container
func (h hostsProcessor) isUnique(host string, entry entry) (bool, error) {
entries, err := h.em.get()
if err != nil {
return false, err
}
for _, e := range entries {
if e.Name != entry.Name {
for _, s := range e.Segments {
for _, h := range s.Hosts {
if h == host {
return false, nil
}
}
}
}
}
return true, nil
}