-
Notifications
You must be signed in to change notification settings - Fork 0
/
dmap_parser.py
94 lines (68 loc) · 3.54 KB
/
dmap_parser.py
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
90
91
92
93
94
"""
The MIT License (MIT)
Copyright (c) 2020 Pierre Ståhl
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
"""Parser and data extractor for raw DMAP data.
DMAP is basically TLV (see Wikipedia) where the key is a 4 byte ASCII value,
a four byte big endian unsigned int as length and the data as data. So:
+---------------+------------------+--------------------+
| Key (4 bytes) | Length (4 bytes) | Data (Length bytes |
+---------------+------------------+--------------------+
"""
from collections import namedtuple
from tags import read_bplist, read_str, read_uint
class DmapTag(namedtuple("DmapTag", ["type", "name"])):
"""Representation of a DMAP tag used when defining a protocol."""
__slots__ = ()
def __str__(self):
"""Return a string representation of this tag."""
if isinstance(self.type, str):
type_name = self.type
else:
type_name = self.type.__name__[5:]
return f"[{type_name}, {self.name}]"
def _parse(data, data_len, tag_lookup, pos, ctx=None):
if ctx is None:
ctx = []
if pos >= data_len:
return ctx
f_name = read_str(data, pos, 4)
f_len = read_uint(data, pos + 4, 4)
pos += 8
tag = tag_lookup(f_name)
if tag.type == "container":
ctx.append({f_name: _parse(data, pos + f_len, tag_lookup, pos, ctx=[])})
else:
ctx.append({f_name: tag.type(data, pos, f_len)})
return _parse(data, data_len, tag_lookup, pos + f_len, ctx)
def parse(data, tag_lookup):
"""Parse raw DAAP data and returns it as a python object."""
return _parse(data, len(data), tag_lookup, 0, [])
def first(dmap_data, *path):
"""Look up a value given a path in some parsed DMAP data."""
if not (path and isinstance(dmap_data, list)):
return dmap_data
for key in dmap_data:
if path[0] in key:
return first(key[path[0]], *path[1:])
return None
def pprint(data, tag_lookup, indent=0):
"""Return a pretty formatted string of parsed DMAP data."""
output = ""
if isinstance(data, dict):
for key, value in data.items():
tag = tag_lookup(key)
if isinstance(value, (dict, list)) and tag.type is not read_bplist:
output += indent * " " + f"{key}: {tag}\n"
output += pprint(value, tag_lookup, indent + 2)
else:
output += indent * " " + f"{key}: {value} {tag}\n"
elif isinstance(data, list):
for elem in data:
output += pprint(elem, tag_lookup, indent)
else:
raise Exception(f"invalid dmap data: {data}")
return output