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
|
package server
import (
"encoding/base64"
"codeberg.org/miekg/dns"
"io"
"log/slog"
"net/http"
)
func (s *Server) dohHandler(w http.ResponseWriter, r *http.Request) {
var raw []byte
switch r.Method {
case http.MethodPost:
ct := r.Header.Get("Content-Type")
if ct != "application/dns-message" {
http.Error(w, "unsupported content type", http.StatusUnsupportedMediaType)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 65535))
if err != nil {
http.Error(w, "read body", http.StatusBadRequest)
return
}
raw = body
case http.MethodGet:
param := r.URL.Query().Get("dns")
if param == "" {
http.Error(w, "missing dns param", http.StatusBadRequest)
return
}
decoded, err := base64.RawURLEncoding.DecodeString(param)
if err != nil {
http.Error(w, "invalid base64url", http.StatusBadRequest)
return
}
raw = decoded
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
msg := new(dns.Msg)
msg.Data = raw
if err := msg.Unpack(); err != nil {
http.Error(w, "invalid dns message", http.StatusBadRequest)
return
}
if len(msg.Question) == 0 {
http.Error(w, "no question", http.StatusBadRequest)
return
}
resp, _ := s.buildResponse(msg)
if err := resp.Pack(); err != nil {
http.Error(w, "pack response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/dns-message")
w.Header().Set("Cache-Control", "no-cache, max-age=0")
if _, err := w.Write(resp.Data); err != nil {
slog.Error("doh write failed", "err", err)
return
}
slog.Info("doh query served",
"qname", msg.Question[0].Header().Name,
"qtype", dns.TypeToString[dns.RRToType(msg.Question[0])],
"rcode", dns.RcodeToString[resp.Rcode],
"client", r.RemoteAddr,
)
}
|