-
Notifications
You must be signed in to change notification settings - Fork 302
/
doh_handler.go
151 lines (132 loc) · 4.34 KB
/
doh_handler.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
// Copyright (C) 2020-2021, IrineSistiana
//
// This file is part of mosdns.
//
// mosdns is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mosdns is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package server
import (
"context"
"encoding/base64"
"errors"
"fmt"
"github.com/IrineSistiana/mosdns/dispatcher/handler"
"github.com/IrineSistiana/mosdns/dispatcher/pkg/dnsutils"
"github.com/IrineSistiana/mosdns/dispatcher/pkg/pool"
"github.com/IrineSistiana/mosdns/dispatcher/pkg/utils"
"github.com/miekg/dns"
"go.uber.org/zap"
"io"
"net/http"
"sync"
"time"
)
type DoHHandler struct {
DNSHandler DNSServerHandler // DNS handler for incoming requests. This cannot be nil.
URLPath string // If empty, DoHHandler will not check request's path.
GetUserIPFromHeader string // Get client ip from http header, e.g. for nginx, X-Forwarded-For.
QueryTimeout time.Duration // Default is defaultQueryTimeout.
Logger *zap.Logger // Nil logger disables logging.
initLoggerOnce sync.Once
logger *zap.Logger
}
func (h *DoHHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.initLoggerOnce.Do(func() {
if extLogger := h.Logger; extLogger != nil {
h.logger = extLogger
} else {
h.logger = zap.NewNop()
}
})
if len(h.URLPath) != 0 && req.URL.Path != h.URLPath {
w.WriteHeader(http.StatusNotFound)
return
}
q, err := GetMsgFromReq(req)
if err != nil {
h.logger.Warn("invalid request", zap.String("from", req.RemoteAddr), zap.String("url", req.RequestURI), zap.String("method", req.Method), zap.Error(err))
w.WriteHeader(http.StatusBadRequest)
return
}
qCtx := handler.NewContext(q, GetClientIPFromReq(req, h.GetUserIPFromHeader))
qCtx.SetTCPClient(true)
ctx, cancel := context.WithTimeout(req.Context(), h.queryTimeout())
defer cancel()
if h.DNSHandler == nil {
h.logger.Error("nil dns handler")
w.WriteHeader(http.StatusInternalServerError)
}
h.DNSHandler.ServeDNS(ctx, qCtx, &httpDnsRespWriter{httpRespWriter: w})
}
func (h *DoHHandler) queryTimeout() time.Duration {
if t := h.QueryTimeout; t > 0 {
return t
}
return defaultQueryTimeout
}
func GetClientIPFromReq(req *http.Request, checkHeader string) *utils.NetAddr {
remoteAddr := req.RemoteAddr
if len(checkHeader) != 0 {
if ip := req.Header.Get(checkHeader); len(ip) != 0 {
remoteAddr = ip + ":0"
}
}
return utils.NewNetAddr(remoteAddr, req.URL.Scheme)
}
func GetMsgFromReq(req *http.Request) (*dns.Msg, error) {
var b []byte
var err error
switch req.Method {
case http.MethodGet:
s := req.URL.Query().Get("dns")
if len(s) == 0 {
return nil, errors.New("no dns parameter")
}
msgSize := base64.RawURLEncoding.DecodedLen(len(s))
if msgSize > dns.MaxMsgSize {
return nil, fmt.Errorf("query length %d is too big", msgSize)
}
msgBuf := pool.GetBuf(msgSize)
defer pool.ReleaseBuf(msgBuf)
strBuf := readBufPool.Get()
defer readBufPool.Release(strBuf)
strBuf.WriteString(s)
n, err := base64.RawURLEncoding.Decode(msgBuf, strBuf.Bytes())
if err != nil {
return nil, fmt.Errorf("failed to decode query: %w", err)
}
b = msgBuf[:n]
case http.MethodPost:
buf := readBufPool.Get()
defer readBufPool.Release(buf)
_, err = buf.ReadFrom(io.LimitReader(req.Body, dns.MaxMsgSize))
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
b = buf.Bytes()
default:
return nil, fmt.Errorf("unsupported method: %s", req.Method)
}
q := new(dns.Msg)
if err := q.Unpack(b); err != nil {
return nil, fmt.Errorf("invalid request: %w", err)
}
return q, nil
}
var readBufPool = pool.NewBytesBufPool(512)
type httpDnsRespWriter struct {
httpRespWriter http.ResponseWriter
}
func (h *httpDnsRespWriter) Write(m *dns.Msg) (n int, err error) {
return dnsutils.WriteMsgToUDP(h.httpRespWriter, m)
}