-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
371 lines (305 loc) · 7.25 KB
/
http.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"crypto/rand"
"crypto/tls"
_ "embed"
"encoding/base32"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/devel/dnsmapper/storeapi"
"github.com/gorilla/handlers"
)
type ipResponse struct {
DNS string
EDNS string
HTTP string
}
var (
uuidCh chan string
localNets []*net.IPNet
)
//go:embed index.html
var HOMEPAGE string
func init() {
go uuidFactory()
pn := []string{
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}
for _, p := range pn {
_, ipnet, err := net.ParseCIDR(p)
if err != nil {
panic(err)
}
localNets = append(localNets, ipnet)
}
}
func uuidFactory() {
uuidCh = make(chan string, 10)
enc := base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567")
length := 20
buf := make([]byte, length)
uuid := make([]byte, enc.EncodedLen(length))
for {
rand.Read(buf)
enc.Encode(uuid, buf)
uuidCh <- string(uuid)
}
}
func uuid() string {
return <-uuidCh
}
func remoteIP(xff string) string {
if len(xff) > 0 {
ips := strings.Split(xff, ",")
for i := len(ips) - 1; i >= 0; i-- {
ip := strings.TrimSpace(ips[i])
nip := net.ParseIP(ip)
if nip != nil {
if localNet(nip) {
continue
}
return nip.String()
}
}
}
return ""
}
func (resp *ipResponse) JSON() (string, error) {
js, err := json.Marshal(resp)
if err != nil {
log.Print("JSON ERROR:", err)
return "", err
}
return string(js), err
}
func responseData(req *http.Request) (*ipResponse, error) {
ip, _, _ := net.SplitHostPort(req.RemoteAddr)
nip := net.ParseIP(ip)
if xff := req.Header.Get("X-Forwarded-For"); len(xff) > 0 && localNet(nip) {
ip = remoteIP(xff)
}
resp := &ipResponse{HTTP: ip, DNS: ""}
uuid := getUUIDFromDomain(req.Host)
dns, edns, ok := getCache(uuid)
if !ok {
return nil, errors.New("UUID not found")
}
resp.DNS = dns
resp.EDNS = edns
data := storeapi.RequestData{
TestIP: *flagip,
ServerIP: resp.DNS,
ClientIP: resp.HTTP,
EdnsNet: resp.EDNS,
}
select {
case ch <- &data:
default:
log.Println("dropped log data, queue full")
}
return resp, nil
}
func redirectUUID(w http.ResponseWriter, req *http.Request) {
uuid := uuid()
host := uuid + "." + *flagdomain
proto := "http"
if req.TLS != nil || req.Header.Get("X-Forwarded-Proto") == "https" {
proto = "https"
}
http.Redirect(w, req, proto+"://"+host+req.RequestURI, http.StatusFound)
}
var apiPaths = map[string]interface{}{
"/jsonp": nil,
"/json": nil,
"/ip": nil,
"/none": nil,
"/gone": nil,
"/notfound": nil,
}
func mainServer(w http.ResponseWriter, req *http.Request) {
if _, ok := apiPaths[req.URL.Path]; ok {
w.Header().Set("Cache-Control", "private, no-cache, no-store, must-revalidate")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET")
uuid := getUUIDFromDomain(req.Host)
if uuid == "www" {
redirectUUID(w, req)
return
}
resp, err := responseData(req)
if err != nil {
log.Printf("redirecting to new uuid, err: %s", err)
redirectUUID(w, req)
return
}
switch req.URL.Path {
case "/none":
w.WriteHeader(204)
return
case "/gone":
w.WriteHeader(410)
return
case "/notfound":
w.WriteHeader(404)
return
case "/ip":
w.WriteHeader(200)
w.Write([]byte(resp.HTTP))
return
}
// json request
js, err := resp.JSON()
if err != nil {
w.WriteHeader(500)
log.Printf("could not convert response %+v to json: %s", resp, err)
return
}
jsonp := req.FormValue("jsonp")
if len(jsonp) == 0 {
jsonp = req.FormValue("callback")
}
if len(jsonp) > 0 {
w.Header().Set("Content-Type", "text/javascript")
io.WriteString(w, jsonp+"("+js+");\n")
return
}
// not jsonp
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, js+"\n")
return
}
mapperScript := `
(function(global){"use strict";var id=function(){var chars="0123456789abcdefghijklmnopqrstuvxyz".split("");
var uuid=[],rnd=Math.random,r;for(var i=0;i<17;i++){if(!uuid[i]){r=0|rnd()*16;uuid[i]=chars[i==19?r&3|8:r&15]}}
return uuid.join("")};
setTimeout(function(){(new Image).src=location.protocol+"//"+id()+".` +
*flagdomain +
`/none"},3200)})(this);
`
if req.URL.Path == "/mapper.js" {
w.Header().Set("Cache-Control", "public, max-age=86400")
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
w.WriteHeader(200)
io.WriteString(w, mapperScript)
return
}
if req.URL.Path == "/mapper-v6compat.js" {
w.Header().Set("Cache-Control", "public, max-age=60")
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
w.WriteHeader(200)
io.WriteString(w, mapperScript)
io.WriteString(w, `v6 = { "version": "2", test: function(){} };`)
return
}
if req.URL.Path == "/" {
w.Header().Set("Cache-Control", "public, max-age=900")
w.WriteHeader(200)
io.WriteString(w, HOMEPAGE)
return
}
if req.URL.Path == "/robots.txt" {
w.Header().Set("Cache-Control", "public, max-age=604800")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(200)
io.WriteString(w, "# Hi Robot!\n")
return
}
if req.URL.Path == "/version" {
io.WriteString(w, `<html><head><title>DNS Mapper `+
VERSION+`</title><body>`+
`Hello`+
`</body></html>`)
return
}
http.NotFound(w, req)
}
func httpListen(h http.Handler, ip string, port int, tlsconfig *tls.Config) error {
listen := fmt.Sprintf("%s:%d", ip, port)
srv := &http.Server{
Handler: h,
Addr: listen,
WriteTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
TLSConfig: tlsconfig,
}
if tlsconfig != nil {
log.Printf("HTTPS listen on %s", listen)
return srv.ListenAndServeTLS(
*flagtlscrtfile,
*flagtlskeyfile,
)
}
log.Printf("HTTP listen on %s", listen)
return srv.ListenAndServe()
}
func httpHandler(listenIP string, listenHTTPPort, listenHTTPSPort int) {
http.HandleFunc("/", mainServer)
h := handlers.CombinedLoggingHandler(os.Stdout, http.DefaultServeMux)
if len(*flagtlskeyfile) > 0 {
log.Printf("Starting TLS with key='%s' and cert='%s'",
*flagtlskeyfile,
*flagtlscrtfile,
)
tlsconfig := &tls.Config{
ClientSessionCache: tls.NewLRUClientSessionCache(300),
}
IPs := []string{listenIP}
// we have some sort of proxy, so listen on localhost
if listenHTTPSPort != 443 {
if listenIP != "127.0.0.1" {
IPs = append(IPs, "127.0.0.1")
}
}
for _, ip := range IPs {
listenIP := ip
log.Printf("listenIP TLS: %q", listenIP)
go func() {
err := httpListen(h, listenIP, listenHTTPSPort, tlsconfig)
if err != nil {
log.Fatalf("https error %s:%d: %s", listenIP, listenHTTPSPort, err)
}
}()
}
}
IPs := []string{listenIP}
if listenHTTPSPort != 80 {
if listenIP != "127.0.0.1" {
IPs = append(IPs, "127.0.0.1")
}
}
for _, ip := range IPs {
listenIP := ip
go func() {
err := httpListen(h, listenIP, listenHTTPPort, nil)
if err != nil {
log.Fatalf("http error %s:%d: %s", listenIP, listenHTTPPort, err)
}
}()
}
// maybe later we can be smarter; now we just wait forever or until something
// "fatals" out
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
}
func localNet(ip net.IP) bool {
for _, n := range localNets {
if n.Contains(ip) {
return true
}
}
return false
}