-
Notifications
You must be signed in to change notification settings - Fork 8
/
sds-parser.py
executable file
·325 lines (256 loc) · 9.09 KB
/
sds-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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/python
import subprocess
import sys
from Queue import Queue, Empty
from threading import Thread, Lock
import getopt
import os
import time
import struct
import sqlite3 as lite
import signal
from binman import *
from multiframe import *
from sds import parsesds, parsesds_safe
from dbo import create_schema
from libdeka import setloglevel, mylog as l
from fragtype import Fragtype
from cpdu import CPDU, pdu2string
from pcap import pcap_header
from config import *
def dkinit(arfcn, timeslot, multiframes):
""" Create empty list on a given arfcn and timeslot """
if not (arfcn, timeslot) in multiframes.keys():
multiframes[(arfcn, timeslot)] = []
"""Dictionary of pending multiframes.
The keys are tuples of (ARFCN, TIMESLOT).
The values are lists of CPDU objects."""
mlock = Lock()
multiframes = {}
def tshark_in_thr(tshark_filter, pcapq):
""" Thread that feeds tshark from pcapq """
tshark_filter.stdin.write(pcap_header)
if dumppcap:
dumppcap.write(pcap_header)
while True:
msg = pcapq.get()
tshark_filter.stdin.write(msg)
if dumppcap:
dumppcap.write(msg)
def tshark_out_thr(tshark_filter, pduq):
""" Thread that reads CPDUs from tshark and puts them to pduq """
while True:
line = tshark_filter.stdout.readline()
if not line:
break
pduq.put(line.strip())
if dumpcpdu:
dumpcpdu.write(line)
tshark_filter.stdout.flush()
l("tshark died!", "CRIT")
def pcap_in_thr(path, q):
""" Thread that reads packets from path and stuffs them into q """
f = open(path, "rb")
data = ""
while True:
newdata = f.read(1024)
if not newdata:
break
data += newdata
hlen = 4 * 4
while len(data) >= hlen:
hdr = data[:hlen]
ret = struct.unpack('4I', hdr)
assert ret[2] == ret[3], "pcap packet truncate %X %X %X %X" % (ret[0], ret[1], ret[2], ret[3])
size = ret[2] + hlen
if len(data) > size:
packet = data[:size]
q.put(packet)
data = data[size:]
else:
break
l("Read for pipe %s died" % path, "CRIT")
def stdin_thr(q):
""" Thread that reads CPDUs from stdin """
while True:
line = sys.stdin.readline()
if not line:
sys.exit(0)
q.put(line.strip())
def gc_thr(mq, mlock):
""" Garbage collector, eats orphaned unfinished multiframes. """
while True:
time.sleep(5)
mlock.acquire()
cutoff = time.time() - multiframe_tx_interval
for item in mq.keys():
if mq[item] and mq[item] != []:
child = mq[item][0]
if child.time < cutoff:
l("Sacrifice child with %i frames, arfcn=%i, ts=%i" % (len(item), child.arfcn, child.timeslot),
"INFO")
for frm in mq[item]:
s = pdu2string(frm)
l("Lost: " + s, "DBG")
mq[item] = []
mlock.release()
""" *** Main program *** """
""" Parse command-line options """
try:
opts, args = getopt.getopt(sys.argv[1:], "p:c:r:l:")
except getopt.GetoptError:
print "Usage: %s [-p pcap_dir] [-c dump.cpdu] [-r dump.pcap] [-l loglevel]" % sys.argv[0]
print " -p pcap_dir read packets from directory"
print " -c dump.cpdu save decoded CPDUs to file"
print " -r dump.pcap generate packet capture of the entire network"
print " -l loglevel loglevel: DBG, SDS, INFO, WARN, CRIT"
sys.exit(2)
pcapdir = None
dumpcpdu = None
dumppcap = None
for opt, arg in opts:
if opt == "-p":
pcapdir = arg
elif opt == "-c":
dumpcpdu = open(arg, "a")
elif opt == "-r":
dumppcap = open(arg, "wb")
elif opt == "-l":
setloglevel(arg)
else:
assert False, "unhandled option"
""" Initialize output database """
con = lite.connect('sds.db')
cur = con.cursor()
create_schema(cur)
""" Handle signal """
def sigint(signal, frame):
con.commit()
sys.exit(0)
signal.signal(signal.SIGINT, sigint)
""" Queue to hold PDUs from tshark """
pduq = Queue()
""" Queue to hold packets from tetra-rx """
pcapq = Queue()
""" Spawn on thread for each tetra-rx """
if pcapdir:
files = os.listdir(pcapdir)
for f in files:
ppath = pcapdir + "/" + f
l("Adding packet input from %s" % ppath, "DBG")
t = Thread(target=pcap_in_thr, args=(ppath, pcapq), name=f)
t.daemon = True
t.start()
""" Spawn tshark and its threads """
tshark_filter = subprocess.Popen([tshark_pipe], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
t = Thread(target=tshark_in_thr, args=(tshark_filter, pcapq), name="tshark_in_thr")
t.daemon = True
t.start()
t = Thread(target=tshark_out_thr, args=(tshark_filter, pduq), name="tshark_out_thr")
t.daemon = True
t.start()
in_t = Thread(target=stdin_thr, args=(pduq,), name="stdin_thr")
in_t.daemon = True
in_t.start()
t = Thread(target=gc_thr, args=(multiframes, mlock), name="gc_thr")
t.daemon = True
t.start()
sqlite_wall = 0
""" Main loop. Get CPDUs from pduq and process them. """
while True:
""" https://docs.python.org/2/library/sqlite3.html#multithreading
We must do commit explicitly here, instead of a gc thread. Awww. """
if time.time() - sqlite_wall > 10:
try:
con.commit()
except:
l("Cannot commit database", "WARN")
sqlite_wall = time.time()
try:
line = pduq.get(timeout=1)
except Empty:
if not in_t.isAlive():
con.commit()
sys.exit(0)
continue
mlock.acquire()
if len(line) < 2:
mlock.release()
continue
pdata = line.split(";")
if len(pdata) < 4:
l("Skipping wrong input format line %s" % line, "WARN")
mlock.release()
continue
payload = pdata[0].replace(":", "")
arfcn = int(pdata[1])
timeslot = int(pdata[2])
frameno = int(pdata[3])
key = (arfcn, timeslot)
InMacType = getMacType(payload)
fillbit = getStartFbi(payload)
l("PDU: arfcn=%i, ts=%i, fn=%i, ct=%i, fill=%i, data=%s" % (arfcn, timeslot, frameno, InMacType, fillbit, payload),
"DBG")
if InMacType == Fragtype.MAC_SINGLE:
# This is not a multiframe -> parse immediately
parsesds_safe(hex_to_binary(payload), arfcn, timeslot, 0, cur, 1)
if InMacType == Fragtype.MAC_START:
# This is the first frame of a multiframe
dkinit(arfcn, timeslot, multiframes)
# This is the first frame. There should be nothing before it.
if multiframes[key]:
l("Lost multiframe on ARFCN %i TS %i" % (arfcn, timeslot), "INFO")
for frm in multiframes[key]:
s = pdu2string(frm)
l("Lost: " + s, "DBG")
multiframes[key] = []
cpdu = CPDU(hex_to_binary(payload)[:-4], Fragtype.MAC_START, arfcn=arfcn, timeslot=timeslot)
multiframes[key].append(cpdu)
elif InMacType == Fragtype.MAC_INNER:
# This is a frame of a multiframe, but neither the first, nor the last
dkinit(arfcn, timeslot, multiframes)
if not multiframes[key]:
l("Stray MAC_INNER frame on ARFCN %i TS %i" % (arfcn, timeslot), "INFO")
mlock.release()
continue
elif multiframes[(arfcn, timeslot)][0].ftype != Fragtype.MAC_START:
l("%i stray MAC_INNER frames on ARFCN %i TS %i" % (len(multiframes[key]), arfcn, timeslot), "INFO")
for frm in multiframes[key]:
s = pdu2string(frm)
l("Stray: " + s, "DBG")
multiframes[key] = []
mlock.release()
continue
tmsdu = ""
if fillbit == 1:
tmsdu = getFragTmsdu(stripFillingHex(payload))
else:
tmsdu = getFragTmsdu(hex_to_binary(payload))
cpdu = CPDU(tmsdu, Fragtype.MAC_INNER, arfcn=arfcn, timeslot=timeslot)
multiframes[key].append(cpdu)
elif InMacType == Fragtype.MAC_END:
# This is the last frame of a multiframe
dkinit(arfcn, timeslot, multiframes)
if not multiframes[key]:
l("Stray MAC_END frame on ARFCN %i TS %i" % (arfcn, timeslot), "INFO")
mlock.release()
continue
elif multiframes[(arfcn, timeslot)][0].ftype != Fragtype.MAC_START:
l("BUG: %i stray frames in on ARFCN %i TS %i on MAC_END" % (len(multiframes[key]), arfcn, timeslot), "BUG")
for frm in multiframes[key]:
s = pdu2string(frm)
l("Stray: " + s, "DBG")
multiframes[key] = []
mlock.release()
continue
tmsdu = ""
if fillbit == 1:
tmsdu = stripFillingBin(getEndTmsdu(hex_to_binary(payload)))
else:
tmsdu = getEndTmsdu(stripFillingBin(hex_to_binary(payload)))
for frm in reversed(multiframes[key]):
tmsdu = frm.data + tmsdu
parsesds_safe(tmsdu, arfcn, timeslot, 1, cur, 1)
del (multiframes[key])
mlock.release()
log("Main thread died", "CRIT")