]> gitweb.michael.orlitzky.com - djbdns-logparse.git/blob - djbdns/common.py
djbdns/*.py: add module docstrings.
[djbdns-logparse.git] / djbdns / common.py
1 r"""
2 Information needed to parse *both* tinydns and dnscache logs.
3 """
4 from struct import pack
5
6 # A pattern to match the timestamp format that the tai64nlocal program
7 # produces. It appears in both dnscache and tinydns lines, after
8 # they've been piped through tai64nlocal, of course.
9 TIMESTAMP_PAT = r'[\d-]+ [\d:\.]+'
10
11 # A dictionary mapping query type identifiers, in decimal, to their
12 # friendly names for tinydns. Reference:
13 #
14 # https://en.wikipedia.org/wiki/List_of_DNS_record_types
15 #
16 # Note that mapping here is non-exhaustive, and that tinydns will
17 # log responses for record types that it does not know about.
18 QUERY_TYPE_NAME = {
19 1: "a",
20 2: "ns",
21 5: "cname",
22 6: "soa",
23 12: "ptr",
24 13: "hinfo",
25 15: "mx",
26 16: "txt",
27 17: "rp",
28 24: "sig",
29 25: "key",
30 28: "aaaa",
31 33: "srv",
32 35: "naptr",
33 38: "a6",
34 48: "dnskey",
35 52: "tlsa",
36 65: "https",
37 252: "axfr",
38 255: "any",
39 257: "caa"
40 }
41
42 def convert_ip(ip : str) -> str:
43 r"""
44 Convert a hex string representing an IP address to
45 human-readable form.
46
47 Parameters
48 ----------
49
50 ip : str
51 The hexadecimal representation of either an IPv4 or an IPv6
52 address.
53
54 Returns
55 -------
56
57 The usual decimal dotted-quad representation is returned for an
58 IPv4 address. IPv6 addresses are returned almost as-is, but with
59 colons inserted in the appropriate places, between every four
60 characters.
61
62 Examples
63 --------
64
65 >>> convert_ip("7f000001")
66 '127.0.0.1'
67 >>> convert_ip("00000000000000000000ffff7f000001")
68 '0000:0000:0000:0000:0000:ffff:7f00:0001'
69 """
70 if len(ip) == 8:
71 # IPv4, eg. "7f000001" -> "7f 00 00 01" -> "127.0.0.1"
72 return ".".join(map(str, pack(">L", int(ip, 16))))
73
74 # IPv6 is actually simpler -- it's just a string-slicing operation.
75 return ":".join([ip[(4*i) : (4*i+4)] for i in range(8)])