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