| 1 |
package log |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log/slog" |
| 6 |
"net" |
| 7 |
|
| 8 |
"codeberg.org/miekg/dns" |
| 9 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx" |
| 10 |
"codeberg.org/miekg/dns/dnsutil" |
| 11 |
) |
| 12 |
|
| 13 |
type Log struct { |
| 14 |
Contexts map[string][]string |
| 15 |
UnixAddr string |
| 16 |
} |
| 17 |
|
| 18 |
func (l *Log) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc { |
| 19 |
return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) { |
| 20 |
if !state.Load() { |
| 21 |
next.ServeDNS(ctx, w, r) |
| 22 |
return |
| 23 |
} |
| 24 |
|
| 25 |
ecs := slog.Attr{} |
| 26 |
if a := dnsctx.Addr(ctx, "ecs/addr"); a.IsValid() { |
| 27 |
ecs = slog.Group("ecs", slog.Any("addr", a)) |
| 28 |
} |
| 29 |
|
| 30 |
_, unix := w.RemoteAddr().(*net.UnixAddr) |
| 31 |
log := slog.Default(). |
| 32 |
With(dnsctx.Id(ctx)). |
| 33 |
With("network", func() string { |
| 34 |
if unix { |
| 35 |
return "unix" |
| 36 |
} |
| 37 |
return dnsutil.Network(w) |
| 38 |
}()). |
| 39 |
With("remote", func() string { |
| 40 |
if unix { |
| 41 |
return l.UnixAddr |
| 42 |
} |
| 43 |
return dnsutil.RemoteIP(w) |
| 44 |
}()). |
| 45 |
With("port", dnsutil.RemotePort(w)). |
| 46 |
With(ecs). |
| 47 |
With(slog.Int("id", int(r.ID))). |
| 48 |
With("type", func() string { _, t := dnsutil.Question(r); return dnsutil.TypeToString(t) }()). |
| 49 |
With("class", dnsutil.ClassToString(r.Question[0].Header().Class)). |
| 50 |
With("name", func() string { z, _ := dnsutil.Question(r); return z }()). |
| 51 |
With(slog.Int("size", len(r.Data))). |
| 52 |
With(slog.Int("bufsize", func() int { |
| 53 |
if r.UDPSize < 512 { |
| 54 |
return 512 |
| 55 |
} |
| 56 |
return int(r.UDPSize) |
| 57 |
}())). |
| 58 |
With("opcode", dnsutil.OpcodeToString(r.Opcode)) |
| 59 |
|
| 60 |
groups := []slog.Attr{} |
| 61 |
for key, values := range l.Contexts { |
| 62 |
attrs := make([]any, 0, len(values)) |
| 63 |
for _, v := range values { |
| 64 |
if x := dnsctx.Value(ctx, key+"/"+v); x != nil { |
| 65 |
attrs = append(attrs, slog.Any(v, x)) |
| 66 |
} |
| 67 |
} |
| 68 |
if len(attrs) > 0 { |
| 69 |
groups = append(groups, slog.Group(key, attrs...)) |
| 70 |
} |
| 71 |
} |
| 72 |
for _, group := range groups { |
| 73 |
log = log.With(group) |
| 74 |
} |
| 75 |
|
| 76 |
log.Info(dns.Zone(ctx)) |
| 77 |
|
| 78 |
next.ServeDNS(ctx, w, r) |
| 79 |
}) |
| 80 |
} |