Debian Codegraph @

dnshttp/response.go

raw
1 package dnshttp
2
3 import (
4 "net"
5 "net/http"
6 "strconv"
7
8 "codeberg.org/miekg/dns"
9 )
10
11 // ResponseWriter is DOH capable [dns.ResponseWriter].
12 type ResponseWriter struct {
13 // Req is the original HTTP request.
14 Req *http.Request
15 // w is the http responseWriter we are wrapping.
16 w http.ResponseWriter
17 // laddr is the local address, it's partially tracked in the net/http package.
18 laddr net.Addr
19 }
20
21 // NewResponseWriter returns a new ResponseWriter that embeds w. See [Request] for example usage in a http
22 // handler.
23 func NewResponseWriter(w http.ResponseWriter, req *http.Request, laddr net.Addr) *ResponseWriter {
24 return &ResponseWriter{w: w, laddr: laddr, Req: req}
25 }
26
27 func (w *ResponseWriter) Conn() net.Conn { return nil }
28 func (w *ResponseWriter) Session() *dns.Session { return nil }
29 func (w *ResponseWriter) Hijack() {}
30 func (w *ResponseWriter) Close() error { return nil }
31
32 // Write writes the [dns.Msg]'s byffer to the underlaying HTTP response writer. It sets a defaults
33 // cache-control of 600 seconds.
34 func (w *ResponseWriter) Write(p []byte) (n int, err error) {
35 // this is a TCP response, the first 2 bytes, are the length, skip those.
36 p = p[2:]
37 w.w.Header().Set("Content-Type", MimeType)
38 w.w.Header().Set("Cache-Control", "max-age=600")
39 w.w.Header().Set("Content-Length", strconv.Itoa(len(p)))
40 w.w.WriteHeader(http.StatusOK)
41 return w.w.Write(p)
42 }
43
44 // LocalAddr implements the ResponseWriter.LocalAddr method.
45 func (w *ResponseWriter) LocalAddr() net.Addr { return w.laddr }
46
47 // RemoteAddr implements the ResponseWriter.RemoteAddr method.
48 func (w *ResponseWriter) RemoteAddr() net.Addr {
49 h, p, _ := net.SplitHostPort(w.Req.RemoteAddr)
50 return &net.TCPAddr{IP: net.ParseIP(h), Port: func(p string) int { i, _ := strconv.Atoi(p); return i }(p)}
51 }