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