]>
gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - djbdns/tinydns.py
1 # Don't clobber the global compile() with a named import.
4 from typing
import Optional
5 from djbdns
.common
import *
7 # The "hex4" pattern matches a string of four hexadecimal digits. This
8 # is used, for example, by tinydns to encode the query type
10 hex4_pat
= r
'[0-9a-f]{4}'
12 # The IP pattern matches a string of either 8 or 32 hexadecimal
13 # characters, which correspond to IPv4 and IPv6 addresses,
14 # respectively, in tinydns logs.
15 ip_pat
= r
'[0-9a-f]{8,32}'
17 # The regex to match tinydns log lines.
18 tinydns_log_re
= re
.compile(
19 rf
'({timestamp_pat}) ({ip_pat}):({hex4_pat}):({hex4_pat}) ([\+\-IC/]) ({hex4_pat}) (.*)'
22 # tinydns can drop a query for one of three reasons; this dictionary
23 # maps the symbol that gets logged in each case to a human-readable
24 # reason. We include the "+" case here, indicating that the query was
25 # NOT dropped, to avoid a special case later on when we're formatting
26 # the human-readable output.
36 def handle_tinydns_log(line
: str) -> Optional
[str]:
38 Handle a single log line if it matches the ``tinydns_log_re`` regex.
44 The log line that might match ``tinydns_log_re``.
49 Either the human-readable string if the log line was handled (that
50 is, if it was really a tinydns log line), or ``None`` if it was
56 >>> line = "2022-09-14 21:04:40.206516500 7f000001:9d61:be69 - 0001 www.example.com"
57 >>> handle_tinydns_log(line)
58 '2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com'
60 >>> line = "this line is nonsense"
61 >>> handle_tinydns_log(line)
64 match
= tinydns_log_re
.match(line
)
68 (timestamp
, ip
, port
, request_id
, code
, query_type
, name
) = match
.groups()
71 request_id
= int(request_id
, 16)
73 # Convert the "type" field to a human-readable record type name
74 # using the query_type dictionary. If the right name isn't present
75 # in the dictionary, we use the (decimal) type id instead.
76 query_type
= int(query_type
, 16) # "001c" -> 28
77 query_type
= query_type_name
.get(query_type
, type) # 28 -> "aaaa"
79 line_tpl
= "{timestamp} "
81 reason
= query_drop_reason
[code
]
83 line_tpl
+= "sent response to {ip}:{port} (id {request_id}): "
84 line_tpl
+= "{query_type} {name}"
86 line_tpl
+= "dropped query ({reason}) from {ip}:{port}"
88 # If the query can actually be parsed, the log line is a
89 # bit more informative than it would have been otherwise.
90 line_tpl
+= " (id {request_id}): {query_type} {name}"
92 return line_tpl
.format(timestamp
=timestamp
,
96 request_id
=request_id
,
97 query_type
=query_type
,