-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhttp.go
123 lines (108 loc) · 2.6 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
package zns
import (
"bytes"
"encoding/base64"
"io"
"net"
"net/http"
"net/netip"
"github.com/miekg/dns"
)
type Handler struct {
Upstream string
Repo TicketRepo
AltSvc string
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.AltSvc != "" {
w.Header().Set("Alt-Svc", h.AltSvc)
}
token := r.PathValue("token")
if token == "" {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
ts, err := h.Repo.List(token, 1)
if err != nil {
http.Error(w, "invalid token", http.StatusInternalServerError)
return
}
if len(ts) == 0 || ts[0].Bytes <= 0 {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
var question []byte
if r.Method == http.MethodGet {
q := r.URL.Query().Get("dns")
question, err = base64.RawURLEncoding.DecodeString(q)
} else {
question, err = io.ReadAll(r.Body)
r.Body.Close()
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var m dns.Msg
if err := m.Unpack(question); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var hasSubnet bool
if e := m.IsEdns0(); e != nil {
for _, o := range e.Option {
if o.Option() == dns.EDNS0SUBNET {
a := o.(*dns.EDNS0_SUBNET).Address[:2]
// skip empty subnet like 0.0.0.0/0
if !bytes.HasPrefix(a, []byte{0, 0}) {
hasSubnet = true
}
break
}
}
}
if !hasSubnet {
ip, err := netip.ParseAddrPort(r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
addr := ip.Addr()
opt := &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}}
ecs := &dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
var bits int
if addr.Is4() {
bits = 24
ecs.Family = 1
} else {
bits = 48
ecs.Family = 2
}
ecs.SourceNetmask = uint8(bits)
p := netip.PrefixFrom(addr, bits)
ecs.Address = net.IP(p.Masked().Addr().AsSlice())
opt.Option = append(opt.Option, ecs)
m.Extra = []dns.RR{opt}
}
if question, err = m.Pack(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := http.Post(h.Upstream, "application/dns-message", bytes.NewReader(question))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
answer, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = h.Repo.Cost(token, len(question)+len(answer)); err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
w.Header().Add("content-type", "application/dns-message")
w.Write(answer)
}