| 1 |
package atomhttp |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/tls" |
| 6 |
"log/slog" |
| 7 |
"net" |
| 8 |
"net/http" |
| 9 |
"time" |
| 10 |
|
| 11 |
"codeberg.org/miekg/dns" |
| 12 |
"codeberg.org/miekg/dns/cmd/atomdns/handlers/global" |
| 13 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/reuse" |
| 14 |
"codeberg.org/miekg/dns/dnshttp" |
| 15 |
"golang.org/x/net/netutil" |
| 16 |
) |
| 17 |
|
| 18 |
// ServeHTTP implements the http.Handler and is the bridge between the HTTP and DNS worlds. |
| 19 |
// It the request and converts to the DNS format, calls the handlers, converts it back and writes it to the client. |
| 20 |
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 21 |
m, err := dnshttp.Request(r) |
| 22 |
if err != nil { |
| 23 |
h.MsgInvalidFunc(m, err) |
| 24 |
http.Error(w, err.Error(), http.StatusBadRequest) |
| 25 |
return |
| 26 |
} |
| 27 |
hw := dnshttp.NewResponseWriter(w, r, r.Context().Value(http.LocalAddrContextKey).(net.Addr)) |
| 28 |
h.mux.ServeDNS(context.Background(), hw, m) |
| 29 |
} |
| 30 |
|
| 31 |
type Server struct { |
| 32 |
server *http.Server |
| 33 |
Listener net.Listener |
| 34 |
} |
| 35 |
|
| 36 |
func Serve(ch chan error, s *Server, global *global.Global) { |
| 37 |
l, err := reuse.ListenTCP("tcp", s.server.Addr, true, true) |
| 38 |
if err != nil { |
| 39 |
ch <- err |
| 40 |
return |
| 41 |
} |
| 42 |
ll := l |
| 43 |
if x := global.HttpLimits.MaxInflight; x > 0 { |
| 44 |
ll = netutil.LimitListener(l, x) |
| 45 |
} |
| 46 |
lt := ll |
| 47 |
if global.TlsConfig != nil { |
| 48 |
lt = tls.NewListener(l, global.TlsConfig) |
| 49 |
} |
| 50 |
if global.TlsCertConfig != nil { |
| 51 |
tlsConfig := global.TlsCertConfig.TLSConfig() |
| 52 |
tlsConfig.NextProtos = append(tlsConfig.NextProtos, dnshttp.NextProtos...) |
| 53 |
lt = tls.NewListener(l, tlsConfig) |
| 54 |
} |
| 55 |
go func() { |
| 56 |
if err := s.server.Serve(lt); err != nil { |
| 57 |
ch <- err |
| 58 |
return |
| 59 |
} |
| 60 |
}() |
| 61 |
s.Listener = lt |
| 62 |
ch <- nil |
| 63 |
} |
| 64 |
|
| 65 |
func (s *Server) Shutdown(ctx context.Context) error { |
| 66 |
s.server.Shutdown(ctx) |
| 67 |
return nil |
| 68 |
} |
| 69 |
|
| 70 |
func New(addr string, mux *dns.ServeMux, fn dns.InvalidMsgFunc) *Server { |
| 71 |
s := new(Server) |
| 72 |
h := newHandler(mux, fn) |
| 73 |
logger := slog.NewLogLogger(slog.Default().Handler(), slog.LevelError) |
| 74 |
s.server = &http.Server{Addr: addr, Handler: h, ErrorLog: logger, ReadTimeout: 5 * time.Second} |
| 75 |
return s |
| 76 |
} |
| 77 |
|
| 78 |
type handler struct { |
| 79 |
mux *dns.ServeMux |
| 80 |
MsgInvalidFunc dns.InvalidMsgFunc |
| 81 |
} |
| 82 |
|
| 83 |
func newHandler(mux *dns.ServeMux, fn dns.InvalidMsgFunc) *http.ServeMux { |
| 84 |
hmux := http.NewServeMux() |
| 85 |
handler := &handler{mux: mux, MsgInvalidFunc: fn} |
| 86 |
hmux.Handle("/dns-query", handler) |
| 87 |
return hmux |
| 88 |
} |