summaryrefslogtreecommitdiff
path: root/translating_proxy.py
diff options
context:
space:
mode:
Diffstat (limited to 'translating_proxy.py')
-rwxr-xr-xtranslating_proxy.py81
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
3import struct
4from bson import BSON
5from StringIO import StringIO
6
7
8DB_OFFSET = 16 + 4 # headers + flags
9
10OP_REPLY = 1
11OP_UPDATE = 2001
12OP_INSERT = 2002
13OP_QUERY = 2004
14OP_GET_MORE = 2005
15OP_DELETE = 2006
16
17# Touchup DB
18OP_TOUCHUP_DB = set((OP_UPDATE, OP_INSERT, OP_QUERY, OP_GET_MORE, OP_DELETE))
19
20def 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
34def 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
42def 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
76line = ''
77
78handle_line(line)
79
80#for line in open("unifi_snapshot.log"):
81# handle_line(eval(line))