diff options
Diffstat (limited to 'translating_proxy.py')
-rwxr-xr-x | translating_proxy.py | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/translating_proxy.py b/translating_proxy.py new file mode 100755 index 0000000..7e03e1b --- /dev/null +++ b/translating_proxy.py | |||
@@ -0,0 +1,81 @@ | |||
1 | #!/usr/bin/env python | ||
2 | |||
3 | import struct | ||
4 | from bson import BSON | ||
5 | from StringIO import StringIO | ||
6 | |||
7 | |||
8 | DB_OFFSET = 16 + 4 # headers + flags | ||
9 | |||
10 | OP_REPLY = 1 | ||
11 | OP_UPDATE = 2001 | ||
12 | OP_INSERT = 2002 | ||
13 | OP_QUERY = 2004 | ||
14 | OP_GET_MORE = 2005 | ||
15 | OP_DELETE = 2006 | ||
16 | |||
17 | # Touchup DB | ||
18 | OP_TOUCHUP_DB = set((OP_UPDATE, OP_INSERT, OP_QUERY, OP_GET_MORE, OP_DELETE)) | ||
19 | |||
20 | def fixup_ns(raw_data, replace_with): | ||
21 | try: | ||
22 | data = BSON(raw_data).decode() | ||
23 | except: | ||
24 | return | ||
25 | |||
26 | if "ns" in data: | ||
27 | db, collection = data["ns"].split(".", 1) | ||
28 | data["ns"] = ".".join((replace_with, collection)) | ||
29 | return BSON.encode(data) | ||
30 | else: | ||
31 | return raw_data | ||
32 | |||
33 | |||
34 | def fixup_db(data, replace_with): | ||
35 | null = data.index("\x00") | ||
36 | db, collection = data[:null].split(".", 1) | ||
37 | replace_with = "admin" if db == "admin" else replace_with | ||
38 | fixed_up = "{}.{}\x00".format(replace_with, collection) | ||
39 | return fixed_up, (collection == "system.indexes") | ||
40 | |||
41 | |||
42 | def handle_line(line): | ||
43 | output = StringIO() | ||
44 | |||
45 | length, req_id, resp_to, msg_type, flags = struct.unpack_from("<iiiii", line) | ||
46 | |||
47 | print msg_type | ||
48 | |||
49 | if msg_type not in OP_TOUCHUP_DB: | ||
50 | return | ||
51 | |||
52 | db_collection, rewrite_body = fixup_db(line[DB_OFFSET:], "mfi") | ||
53 | |||
54 | output.write(struct.pack("<iiii", req_id, resp_to, msg_type, flags)) | ||
55 | output.write(db_collection) | ||
56 | |||
57 | if rewrite_body: | ||
58 | body_start = DB_OFFSET + len(db_collection) + 8 | ||
59 | print repr(line[body_start:]) | ||
60 | print BSON(line[body_start:]).decode() | ||
61 | output.write(fixup_ns(line[body_start:], "mfi")) | ||
62 | else: | ||
63 | body_start = DB_OFFSET + len(db_collection) | ||
64 | body = struct.pack("<i", 2280) + line[body_start+4:] | ||
65 | print struct.unpack_from("<i", line), len(body) | ||
66 | print repr(body) | ||
67 | print BSON(body).decode() | ||
68 | output.write(line[body_start:]) | ||
69 | |||
70 | value = output.getvalue() | ||
71 | # print repr(struct.pack("<i", len(value)) + value) | ||
72 | |||
73 | |||
74 | |||
75 | |||
76 | line = '' | ||
77 | |||
78 | handle_line(line) | ||
79 | |||
80 | #for line in open("unifi_snapshot.log"): | ||
81 | # handle_line(eval(line)) | ||