forked from hgsgtk/wsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upstreams.go
164 lines (134 loc) · 3.46 KB
/
upstreams.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
package mulery
import (
"fmt"
"net"
"net/http"
"strings"
"time"
)
const dnsRefreshInterval = 3 * time.Minute
func (c *Config) HandleAll(resp http.ResponseWriter, _ *http.Request) {
if c.RedirectURL == "" {
resp.WriteHeader(http.StatusUnauthorized)
return
}
resp.Header().Add("Location", c.RedirectURL)
resp.WriteHeader(http.StatusFound)
}
func (c *Config) HandleOK(resp http.ResponseWriter, _ *http.Request) {
http.Error(resp, "OK", http.StatusOK)
}
func (c *Config) ValidateUpstream(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if c.allow.Contains(req.RemoteAddr) {
next.ServeHTTP(resp, req)
} else {
c.HandleAll(resp, req)
}
})
}
// AllowedIPs determines who make can requests.
type AllowedIPs struct {
askIP chan string
allow chan bool
input []string
nets []*net.IPNet
}
var _ = fmt.Stringer(&AllowedIPs{})
// String turns a list of allowedIPs into a printable masterpiece.
func (n *AllowedIPs) String() string {
if n == nil || len(n.nets) < 1 {
return "(none)"
}
output := ""
for idx := range n.nets {
if output != "" {
output += ", "
}
if n.nets[idx] != nil {
output += n.nets[idx].String() + " (input: " + n.input[idx] + ")"
} else {
output += n.input[idx] + " (ignored)"
}
}
return output
}
// Contains returns true if an IP is allowed.
func (n *AllowedIPs) Contains(ip string) bool {
n.askIP <- strings.Trim(ip[:strings.LastIndex(ip, ":")], "[]")
return <-n.allow
}
// MakeIPs turns a list of CIDR strings, IPs or dns hostnames into a list of net.IPNet.
// This "allowed" list is later used to check incoming IPs from web requests.
// Starts a go routine that does periodic dns lookups for hostnames in the upstreams list.
func MakeIPs(upstreams []string) *AllowedIPs {
allowed := &AllowedIPs{
input: make([]string, len(upstreams)),
nets: make([]*net.IPNet, len(upstreams)),
}
allowed.parseAndLookup(upstreams)
go allowed.Start()
return allowed
}
func (n *AllowedIPs) parseAndLookup(upstreams []string) {
for idx, ipAddr := range upstreams {
n.input[idx] = ipAddr
if !strings.Contains(ipAddr, "/") {
if strings.Contains(ipAddr, ":") {
ipAddr += "/128"
} else {
ipAddr += "/32"
}
}
if _, ipnet, err := net.ParseCIDR(ipAddr); err == nil {
n.nets[idx] = ipnet
continue // it's an ip, no dns lookup needed.
}
iplist, err := net.LookupHost(n.input[idx])
if err != nil || len(iplist) < 1 {
continue // keep what we had if the lookup is empty.
}
// if err != nil, keep what we had, or "nothing" if it never recovers.
if _, ipnet, err := net.ParseCIDR(iplist[0] + "/32"); err == nil {
n.nets[idx] = ipnet // update what we had with new lookup.
}
}
}
func (n *AllowedIPs) Start() {
if n.askIP != nil {
panic("AllowedIPs already running!")
}
n.askIP = make(chan string)
n.allow = make(chan bool)
ticker := time.NewTicker(dnsRefreshInterval)
defer func() {
n.askIP = nil
close(n.allow) // signal finished.
ticker.Stop()
}()
for {
select {
case <-ticker.C:
n.parseAndLookup(n.input) // update input w/ input.
case askIP, ok := <-n.askIP:
if !ok {
return
}
n.allow <- n.contains(askIP)
}
}
}
func (n *AllowedIPs) contains(askIP string) bool {
for i := range n.nets {
if n.nets[i] != nil && n.nets[i].Contains(net.ParseIP(askIP)) {
return true
}
}
return false
}
// Stop the running allow IP routine.
func (n *AllowedIPs) Stop() {
close(n.askIP)
<-n.allow
n.allow = nil
}