This repository was archived by the owner on Jul 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathslog.go
More file actions
89 lines (80 loc) · 2.34 KB
/
slog.go
File metadata and controls
89 lines (80 loc) · 2.34 KB
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
// SPDX-License-Identifier: GPL-3.0-or-later
package dnscore
import (
"context"
"log/slog"
"net/netip"
"time"
"github.com/rbmk-project/common/netipx"
)
// addrToAddrPort is an alias for [common.AddrToAddrPort].
var addrToAddrPort = netipx.AddrToAddrPort
// protocolMap maps the DNS protocol to the corresponding network protocol.
var protocolMap = map[Protocol]string{
ProtocolDoH: "tcp",
ProtocolTCP: "tcp",
ProtocolDoT: "tcp",
ProtocolUDP: "udp",
ProtocolDoQ: "udp",
}
// maybeLogQuery is a helper function that logs the query if the logger is set
// and returns the current time for subsequent logging.
func (t *Transport) maybeLogQuery(
ctx context.Context, addr *ServerAddr, rawQuery []byte) time.Time {
t0 := t.timeNow()
if t.Logger != nil {
t.Logger.InfoContext(
ctx,
"dnsQuery",
slog.Any("dnsRawQuery", rawQuery),
slog.String("serverAddr", addr.Address),
slog.String("serverProtocol", string(addr.Protocol)),
slog.Time("t", t0),
slog.String("protocol", protocolMap[addr.Protocol]),
)
}
return t0
}
// maybeLogResponseAddrPort is a helper function that logs the response if the logger is set.
func (t *Transport) maybeLogResponseAddrPort(ctx context.Context,
addr *ServerAddr, t0 time.Time, rawQuery, rawResp []byte,
laddr, raddr netip.AddrPort) {
if t.Logger != nil {
// Convert zero values to unspecified
if !laddr.IsValid() {
laddr = netip.AddrPortFrom(netip.IPv6Unspecified(), 0)
}
if !raddr.IsValid() {
raddr = netip.AddrPortFrom(netip.IPv6Unspecified(), 0)
}
t.Logger.InfoContext(
ctx,
"dnsResponse",
slog.String("localAddr", laddr.String()),
slog.Any("dnsRawQuery", rawQuery),
slog.Any("dnsRawResponse", rawResp),
slog.String("remoteAddr", raddr.String()),
slog.String("serverAddr", addr.Address),
slog.String("serverProtocol", string(addr.Protocol)),
slog.Time("t0", t0),
slog.Time("t", t.timeNow()),
slog.String("protocol", protocolMap[addr.Protocol]),
)
}
}
// maybeLogResponseConn is a helper function that logs the response if the logger is set.
func (t *Transport) maybeLogResponseConn(ctx context.Context,
addr *ServerAddr, t0 time.Time, rawQuery, rawResp []byte,
conn dnsStream) {
if t.Logger != nil {
t.maybeLogResponseAddrPort(
ctx,
addr,
t0,
rawQuery,
rawResp,
addrToAddrPort(conn.LocalAddr()),
addrToAddrPort(conn.RemoteAddr()),
)
}
}