-
Notifications
You must be signed in to change notification settings - Fork 112
/
bitsparser.py
executable file
·1973 lines (1748 loc) · 72.4 KB
/
bitsparser.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 tw=0 et pm=:
import sys
import re
import struct
import fileinput
import datetime
from math import sqrt,atan2,pi,log
import crcmod
from bch import ndivide, nrepair, bch_repair, bch_repair1
import rs
import rs6
from util import *
import itl
iridium_access="001100000011000011110011" # Actually 0x789h in BPSK
uplink_access= "110011000011110011111100" # BPSK: 0xc4b
UW_DOWNLINK = [0,2,2,2,2,0,0,0,2,0,0,2]
UW_UPLINK = [2,2,0,0,0,2,0,0,2,0,2,2]
header_messaging="00110011111100110011001111110011" # 0x9669 in BPSK
header_time_location="11"+"0"*94
messaging_bch_poly=1897
ringalert_bch_poly=1207
acch_bch_poly=3545 # 1207 also works?
hdr_poly=29 # IBC header
f_doppler= 36e3 # maximum doppler_shift
f_jitter= 1e3 # iridium-extractor precision
sdr_ppm= 100e-6 # SDR freq offset
f_simplex = (1626104e3 - f_doppler - f_jitter ) * (1- sdr_ppm) # lower bound for simplex channel
f_duplex = (1625979e3 + f_doppler + f_jitter ) * (1+ sdr_ppm) # upper bound for duplex cannel
# commandline arguments
args = None
def set_opts(new_args):
global args
args = new_args
class ParserError(Exception):
def __init__(self, message):
super().__init__(message)
self.cls=sys._getframe(1).f_locals['self'].__class__.__name__
tswarning=False
tsoffset=0
maxts=0
class Message(object):
p=re.compile(r'(RAW|RWA): ([^ ]*) (-?[\d.]+) (\d+) (?:N:([+-]?\d+(?:\.\d+)?)([+-]\d+(?:\.\d+)?)|A:(\w+)) [IL]:(\w+) +(\d+)% ([\d.]+|inf|nan) +(\d+) ([\[\]<> 01]+)(.*)')
parse_error=False
error=False
def __init__(self,line):
self.error_msg=[]
self.lineno=fileinput.lineno()
m=self.p.match(line)
if(args.errorfile != None):
self.line=line
if(not m):
self._new_error("Couldn't parse: "+line)
self.parse_error=True
return
self.swapped=(m.group(1)=="RAW")
self.filename=m.group(2)
if self.filename=="/dev/stdin":
self.filename="-";
self.timestamp=float(m.group(3))
if self.timestamp<0 or self.timestamp>1000*60*60*24*999: # 999d
self._new_error("Timestamp out of range")
self.frequency=int(m.group(4))
if args.channelize:
self.freq_print=channelize_str(self.frequency)
else:
self.freq_print="%010d"%(self.frequency)
if m.group(5) is not None:
self.snr=float(m.group(5))
self.noise=float(m.group(6))
else:
self.access_ok=(m.group(7)=="OK")
self.id=m.group(8)
self.confidence=int(m.group(9))
self.level=float(m.group(10))
if self.level==0:
self.level=float(m.group(10)+"1")
self.leveldb=20*log(self.level,10)
# self.raw_length=m.group(11)
self.bitstream_raw=(re.sub(r"[\[\]<> ]","",m.group(12))) # raw bitstring with correct symbols
if self.swapped:
self.bitstream_raw=symbol_reverse(self.bitstream_raw)
self.symbols=len(self.bitstream_raw)//2
if m.group(13):
self.extra_data=m.group(13)
self._new_error("There is crap at the end in extra_data")
# Make a "global" timestamp - needs to be an int to avoid precision loss
# Current format:
mm=re.match(r"i-(\d+)-t1$",self.filename)
if mm:
startts=int(mm.group(1))
self.fileinfo="p-%d"%startts
self.globalns=startts*(10**9)+int(float(self.timestamp)*(10**6))
return
# Older file formats:
mm=re.match(r"(\d\d)-(\d\d)-(20\d\d)T(\d\d)-(\d\d)-(\d\d)-[sr]1",self.filename)
if mm:
month, day, year, hour, minute, second = map(int, mm.groups())
ts=datetime.datetime(year,month,day,hour,minute,second)
startts=int(ts.timestamp())
self.fileinfo="p-%d"%startts
self.globalns=startts*(10**9)+int(float(self.timestamp)*(10**6))
return
mm=re.match(r"i-(\d+(?:\.\d+)?)-[vbsrtl]1.([a-z])([a-z])",self.filename)
if mm:
self.b26=(ord(mm.group(2))-ord('a'))*26+ ord(mm.group(3))-ord('a')
startts=float(mm.group(1))+self.b26*600
if startts != int(startts):
self.timestamp+=(startts%1)*(10**3)
startts=int(startts)
self.fileinfo="p-%d"%startts
self.globalns=startts*(10**9)+int(float(self.timestamp)*(10**6))
return
mm=re.match(r"i-(\d+(?:\.\d+)?)-[vbsrtl]1(?:-o[+-]\d+)?$",self.filename)
if mm:
startts=float(mm.group(1))
if startts != int(startts):
self.timestamp+=(startts%1)*(10**3)
startts=int(startts)
self.fileinfo="p-%d"%startts
self.globalns=startts*(10**9)+int(float(self.timestamp)*(10**6))
return
global tswarning,tsoffset,maxts
self.fileinfo="u-"+self.filename.replace("-",".")
if not tswarning:
print("Warning: no timestamp found in filename", file=sys.stderr)
tswarning=True
ts=tsoffset+float(self.timestamp)/1000
if ts<maxts:
tsoffset=maxts
ts=tsoffset+float(self.timestamp)/1000
maxts=ts
self.globalns=int(ts*(10**9))
def upgrade(self):
if self.error: return self
if(self.bitstream_raw.startswith(iridium_access)):
self.uplink=0
elif(self.bitstream_raw.startswith(uplink_access)):
self.uplink=1
else:
if args.uwec and len(self.bitstream_raw)>=len(iridium_access):
access=de_dqpsk(self.bitstream_raw[:len(iridium_access)])
if bitdiff(access,UW_DOWNLINK) <4:
self.uplink=0
self.ec_uw=bitdiff(access,UW_DOWNLINK)
elif bitdiff(access,UW_UPLINK) <4:
self.uplink=1
self.ec_uw=bitdiff(access,UW_UPLINK)
else:
self._new_error("Access code distance too big: %d/%d "%(bitdiff(access,UW_DOWNLINK),bitdiff(access,UW_UPLINK)))
if("uplink" not in self.__dict__):
self._new_error("Access code missing")
return self
try:
return IridiumMessage(self).upgrade()
except ParserError as e:
self._new_error(str(e), e.cls)
return self
def _new_error(self,msg, cls=None):
self.error=True
if cls is None:
msg=str(type(self).__name__) + ": "+msg
else:
msg=cls + ": "+msg
if not self.error_msg or self.error_msg[-1] != msg:
self.error_msg.append(msg)
def _pretty_header(self):
flags=""
if args.uwec or args.harder or not args.perfect:
flags="-e"
if("ec_uw" in self.__dict__):
flags+="%d"%self.ec_uw
else:
flags+="0"
if("ec_lcw" in self.__dict__):
flags+="%d"%self.ec_lcw
else:
flags+="0"
if("fixederrs" in self.__dict__):
if self.fixederrs>9:
flags+="9"
else:
flags+="%d"%self.fixederrs
else:
flags+="0"
hdr="%s%s %014.4f"%(self.fileinfo,flags,self.timestamp)
if "snr" not in self.__dict__:
return "%s %s %3d%% %7.3f"%(hdr,self.freq_print,self.confidence,self.level)
else:
return "%s %s %3d%% %06.2f|%07.2f|%05.2f"%(hdr,self.freq_print,self.confidence,self.leveldb,self.noise,self.snr)
def _pretty_trailer(self):
return ""
def pretty(self):
if self.parse_error:
return "ERR: "
str= "RAW: "+self._pretty_header()
bs=self.bitstream_raw
if "uplink" in self.__dict__:
str+= " %03d"%(self.symbols-len(iridium_access)//2)
if (self.uplink):
str+=" UL"
else:
str+=" DL"
str+=" <%s>"%bs[:len(iridium_access)]
bs=bs[len(iridium_access):]
str+=" "+" ".join(slice(bs,16))
if("extra_data" in self.__dict__):
str+=" "+self.extra_data
str+=self._pretty_trailer()
return str
class IridiumMessage(Message):
def __init__(self,msg):
self.__dict__=msg.__dict__
if (self.uplink):
data=self.bitstream_raw[len(uplink_access):]
else:
data=self.bitstream_raw[len(iridium_access):]
# Try to detect packet type.
# Will not detect packets with correctable bit errors at the beginning
# unless '--harder' is specifed
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency > f_simplex) and not (args.freqclass and self.uplink):
if data[:32] == header_messaging:
self.msgtype="MS"
if "msgtype" not in self.__dict__ and args.linefilter['type'] == "IridiumMSMessage":
self._new_error("filtered message")
return
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency > f_simplex) and not (args.freqclass and self.uplink):
if data[:96]==header_time_location:
self.msgtype="TL"
if "msgtype" not in self.__dict__ and args.linefilter['type'] == "IridiumSTLMessage":
self._new_error("filtered message")
return
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency < f_duplex) and not (args.freqclass and self.uplink):
hdrlen=6
blocklen=64
if len(data)>hdrlen+blocklen:
if ndivide(hdr_poly,data[:hdrlen])==0:
(o_bc1,o_bc2)=de_interleave(data[hdrlen:hdrlen+blocklen])
if ndivide(ringalert_bch_poly,o_bc1[:31])==0:
if ndivide(ringalert_bch_poly,o_bc2[:31])==0:
self.msgtype="BC"
if "msgtype" not in self.__dict__ and args.linefilter['type'] == "IridiumBCMessage":
self._new_error("filtered message")
return
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency < f_duplex):
if len(data)>64: # XXX: heuristic based on LCW / first BCH block, can we do better?
(o_lcw1,o_lcw2,o_lcw3)=de_interleave_lcw(data[:46])
if ndivide( 29,o_lcw1)==0:
if ndivide( 41,o_lcw3)==0:
(e2,lcw2,bch)= bch_repair(465,o_lcw2+'0') # One bit missing, so we guess
if (e2==1): # Maybe the other one...
(e2,lcw2,bch)= bch_repair(465,o_lcw2+'1')
if e2==0:
self.msgtype="LW"
if "msgtype" not in self.__dict__ and args.linefilter['type'] == "IridiumLCWMessage":
self._new_error("filtered message")
return
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency > f_simplex) and not (args.freqclass and self.uplink):
firstlen=3*32
if len(data)>=3*32:
(o_ra1,o_ra2,o_ra3)=de_interleave3(data[:firstlen])
if ndivide(ringalert_bch_poly,o_ra1[:31])==0:
if ndivide(ringalert_bch_poly,o_ra2[:31])==0:
if ndivide(ringalert_bch_poly,o_ra3[:31])==0:
self.msgtype="RA"
if "msgtype" not in self.__dict__ and args.linefilter['type'] == "IridiumRAMessage":
self._new_error("filtered message")
return
if "msgtype" not in self.__dict__ and (not args.freqclass or self.frequency < f_duplex) and self.uplink:
if len(data)>=2*26 and len(data)<2*50:
self.msgtype="AQ"
if "msgtype" not in self.__dict__:
if args.harder:
# try IBC
if len(data)>=70 and not (args.freqclass and self.uplink):
hdrlen=6
blocklen=64
(e1,_,_)=bch_repair1(hdr_poly,data[:hdrlen])
(o_bc1,o_bc2)=de_interleave(data[hdrlen:hdrlen+blocklen])
(e2,d2,b2)=bch_repair(ringalert_bch_poly,o_bc1[:31])
(e3,d3,b3)=bch_repair(ringalert_bch_poly,o_bc2[:31])
if e1>=0 and e2>=0 and e3>=0:
if ((d2+b2+o_bc1[31]).count('1') % 2)==0:
if ((d3+b3+o_bc2[31]).count('1') % 2)==0:
self.msgtype="BC"
self.ec_lcw=e1
# try for LCW
if "msgtype" not in self.__dict__ and len(data)>=64:
(o_lcw1,o_lcw2,o_lcw3)=de_interleave_lcw(data[:46])
(e1 ,lcw1,bch)=bch_repair( 29,o_lcw1) # BCH(7,3)
(e2a,lcw2,bch)=bch_repair(465,o_lcw2+'0') # BCH(13,16)
(e2b,lcw2,bch)=bch_repair(465,o_lcw2+'1')
(e3 ,lcw3,bch)=bch_repair( 41,o_lcw3) # BCH(26,21)
e2=e2a
if (e2b>=0 and e2b<e2a) or (e2a<0):
e2=e2b
if e1>=0 and e2>=0 and e3>=0:
self.msgtype="LW"
self.ec_lcw=(e1+e2+e3)
# try for IRA
firstlen=3*32
if "msgtype" not in self.__dict__ and len(data)>=firstlen and not (args.freqclass and self.uplink):
(o_ra1,o_ra2,o_ra3)=de_interleave3(data[:firstlen])
(e1,d1,b1)=bch_repair(ringalert_bch_poly,o_ra1[:31])
(e2,d2,b2)=bch_repair(ringalert_bch_poly,o_ra2[:31])
(e3,d3,b3)=bch_repair(ringalert_bch_poly,o_ra3[:31])
if e1>=0 and e2>=0 and e3>=0:
if ((d1+b1+o_ra1[31]).count('1') % 2)==0:
if ((d2+b2+o_ra2[31]).count('1') % 2)==0:
if ((d3+b3+o_ra3[31]).count('1') % 2)==0:
self.msgtype="RA"
# try ITL
if "msgtype" not in self.__dict__ and len(data)>=96+(8*8*12) and not (args.freqclass and self.uplink):
if bitdiff(data[:96],header_time_location)<4:
self.ec_lcw=1
self.msgtype="TL"
# try IMS
if "msgtype" not in self.__dict__ and len(data)>=32 and not (args.freqclass and self.uplink):
if bitdiff(data[:32],header_messaging)<2:
self.ec_lcw=1
self.msgtype="MS"
if "msgtype" not in self.__dict__:
if len(data)<64:
raise ParserError("Iridium message too short")
if args.forcetype:
self.msgtype=args.forcetype.partition(':')[0]
if "msgtype" not in self.__dict__:
raise ParserError("unknown Iridium message type")
if self.msgtype=="MS":
hdrlen=32
self.header=data[:hdrlen]
if self.header==header_messaging:
self.header=""
self.descrambled=[]
(blocks,self.descramble_extra)=slice_extra(data[hdrlen:],64)
for x in blocks:
self.descrambled+=de_interleave(x)
elif self.msgtype=="AQ":
datalen=2*26
self.header=""
self.descrambled=data[:datalen]
self.descramble_extra=data[datalen:]
elif self.msgtype=="TL":
hdrlen=96
self.header=data[:hdrlen]
self.descrambled=data[hdrlen:hdrlen+(256*3)]
self.descramble_extra=data[hdrlen+(256*3):]
elif self.msgtype=="RA":
firstlen=3*32
if len(data)<firstlen:
self._new_error("No data to descramble")
self.header=""
self.descrambled=[]
self.descrambled+=de_interleave3(data[:firstlen])
(blocks,self.descramble_extra)=slice_extra(data[firstlen:],64)
for x in blocks:
self.descrambled+=de_interleave(x)
elif self.msgtype=="BC":
hdrlen=6
self.header=data[:hdrlen]
(e,d,bch)=bch_repair1(hdr_poly,self.header)
self.bc_type = int(d, 2)
if e<0:
self.header="%s/E%d"%(self.header,e)
if not args.forcetype:
self._new_error("IBC header error")
else:
self.header=""
self.descrambled=[]
(blocks,self.descramble_extra)=slice_extra(data[hdrlen:],64)
for x in blocks:
self.descrambled+=de_interleave(x)
elif self.msgtype=="LW":
lcwlen=46
(o_lcw1,o_lcw2,o_lcw3)=de_interleave_lcw(data[:lcwlen])
(e1, self.lcw1,bch)= bch_repair( 29,o_lcw1)
(e2, self.lcw2,bch)= bch_repair(465,o_lcw2+'0') # One bit error expected
(e2b,lcw2b, bch)= bch_repair(465,o_lcw2+'1') # Other bit flip?
(e3,self.lcw3, bch)= bch_repair( 41,o_lcw3)
if (e2b>=0 and e2b<=e2) or (e2<0):
e2=e2b
self.lcw2=lcw2b
self.ft=int(self.lcw1,2) # Frame type
if e1<0 or e2<0 or e3<0:
if not ( args.forcetype and ':' in args.forcetype):
self._new_error("LCW decode failed")
self.header="LCW(%s_%s/%01dE%d,%s_%sx/%03dE%d,%s_%s/%06dE%d)"%(o_lcw1[:3],o_lcw1[3:],int(self.lcw1,2),e1,o_lcw2[:6],o_lcw2[6:],int(self.lcw2,2),e2,o_lcw3[:21],o_lcw3[21:],int(self.lcw3,2),e3)
data=data[lcwlen:]
self.descramble_extra=data[312:]
self.descrambled=data[:312]
else:
raise Exception("Illegal Iridium frame type")
def upgrade(self):
if self.error: return self
try:
if self.msgtype=="LW":
return IridiumLCWMessage(self).upgrade()
elif self.msgtype=="TL":
return IridiumSTLMessage(self).upgrade()
elif self.msgtype=="AQ":
return IridiumAQMessage(self).upgrade()
elif self.msgtype in ("MS", "RA", "BC"):
return IridiumECCMessage(self).upgrade()
raise AssertionError("unknown frame type encountered")
except ParserError as e:
self._new_error(str(e), e.cls)
return self
return self
def _pretty_header(self):
str= super()._pretty_header()
str+= " %03d"%(self.symbols-len(iridium_access)//2)
if (self.uplink):
str+=" UL"
else:
str+=" DL"
if self.header:
str+=" "+self.header
return str
def _pretty_trailer(self):
str= super()._pretty_trailer()
if("descramble_extra" in self.__dict__) and self.descramble_extra != "":
str+= " descr_extra:"+self.descramble_extra
return str
def pretty(self):
sstr= "IRI: "+self._pretty_header()
sstr+= " %2s"%self.msgtype
if self.msgtype == "TL" and "i" in self.__dict__:
sstr+= " <"+" ".join(self.i)+">"
sstr+= " <"+" ".join(self.q)+">"
elif self.descrambled!="":
sstr+= " ["
sstr+=".".join(["%02x"%int("0"+x,2) for x in slice("".join(self.descrambled), 8) ])
sstr+="]"
sstr+= self._pretty_trailer()
return sstr
class IridiumLCWMessage(IridiumMessage):
def __init__(self,msg):
self.__dict__=msg.__dict__
if args.forcetype and ':' in args.forcetype:
self.ft=int(args.forcetype.partition(':')[2])
data=self.descrambled
self.pretty_lcw()
if self.ft<=3 and len(data)<312:
self._new_error("Not enough data in data packet")
self.descrambled=[]
self.payload_r=[]
self.payload_f=[]
if self.ft==0: # Voice - Mission data - voice
self.msgtype="VO"
for x in slice(data,8):
self.descrambled+=[x]
self.payload_f+=[int(x,2)]
self.payload_r+=[int(x[::-1],2)]
self.payload_6=[int(x,2) for x in slice(data[:312], 6)]
elif self.ft==1: # IP via PPP - Mission data - data
self.msgtype="IP"
for x in slice(data,8):
self.descrambled+=[x[::-1]]
self.payload_f+=[int(x,2)]
self.payload_r+=[int(x[::-1],2)]
elif self.ft==2: # DAta (SBD) - Mission control data - ISU/SV
self.msgtype="DA"
blocks=slice(data,124)
end=blocks.pop()
for x in blocks:
(b1,b2)=de_interleave(x)
(b1,b2,b3,b4)=slice(b1+b2,31)
self.descrambled+=[b4,b2,b3,b1]
(b1,b2)=de_interleave(end)
self.descrambled+=[b2[1:],b1[1:]] # Throw away the extra bit
elif self.ft==7: # Synchronisation
self.msgtype="SY"
self.descrambled=data
self.sync=[int(x,2) for x in slice(self.descrambled, 8)]
elif self.ft==3: # Mission control data - inband sig
self.msgtype="U3"
self.descrambled=data
self.payload6=[int(x,2) for x in slice(self.descrambled, 6)]
self.payload8=[int(x,2) for x in slice(self.descrambled, 8)]
elif self.ft==6: # "PT=,"
self.msgtype="U6"
self.descrambled=data
else: # Need to check what other ft are
self.msgtype="U%d"%self.ft
self.descrambled=data
if self.msgtype!="VO" and self.msgtype!="IP" and len(self.descrambled)==0:
self._new_error("No data to descramble")
def upgrade(self):
if args.linefilter['type']=='IridiumLCW3Message' and self.msgtype!="U3":
self._new_error("filtered message")
if self.error: return self
try:
if self.msgtype=="VO":
return IridiumVOMessage(self).upgrade()
elif self.msgtype=="IP":
return IridiumIPMessage(self).upgrade()
elif self.msgtype=="SY":
return IridiumSYMessage(self).upgrade()
elif self.msgtype=="DA":
return IridiumLCWECCMessage(self).upgrade()
elif self.msgtype=="U3":
return IridiumLCW3Message(self).upgrade()
elif self.msgtype.startswith("U"):
return self # XXX: probably need to descramble/BCH it
raise AssertionError("unknown frame type encountered")
except ParserError as e:
self._new_error(str(e), e.cls)
return self
return self
def pretty_lcw(self):
# LCW:=xx[type] yyyy[code]
# 0: maint
# 6: geoloc
# f: "no text"
# c: maint [lqi[x1c,2], power[[x19,3]]
# 789abde: reserved
# 0: sync [status[xa,1], dtoa[xc,10], dfoa[x16,8]]
# 3: maint [lqi[xa,2], power[xc,3], fine dtoa[xf,7], fine dfoa[x16,3]]
# 245: reserved
# 1: switch [dtoa[xc,10], dfoa[x16,8]]
# 1: acchl
# 1: acchl
# *: reserved
# 2: handoff
# c: handoff cand.
# f: "no text"
# 3: handoff resp. [cand[%c[0=P,1=S::0xb,1]], denied[0xc,1], ref[xd,1], slot[xf,2]+1, subband up[x11,5], subband down[x16,5], access[x1b,3]+1]
# *: reserved
# 3: reserved
self.lcw_ft=int(self.lcw2[:2],2)
self.lcw_code=int(self.lcw2[2:],2)
lcw3bits=self.lcw3
if self.lcw_ft == 0:
ty="maint"
if self.lcw_code == 6:
code="geoloc"
elif self.lcw_code == 15:
code="<silent>"
elif self.lcw_code == 12:
code="maint[1]"
code+="[lqi:%d,power:%d]"%(int(self.lcw3[19:21],2),int(self.lcw3[16:19],2))
lcw3bits="%s"%(self.lcw3[:16])
elif self.lcw_code == 0:
code="sync"
code+="[status:%d,dtoa:%d,dfoa:%d]"%(int(self.lcw3[1:2],2),int(self.lcw3[3:13],2),int(self.lcw3[13:21],2))
lcw3bits="%s|%s"%(self.lcw3[0],self.lcw3[2])
elif self.lcw_code == 3:
code="maint[2]"
code+="[lqi:%d,power:%d,f_dtoa:%d,f_dfoa:%d]"%(int(self.lcw3[1:3],2),int(self.lcw3[3:6],2),int(self.lcw3[6:13],2),int(self.lcw3[13:20],2))
lcw3bits="%s|%s"%(self.lcw3[0],self.lcw3[20:])
elif self.lcw_code == 1:
code="switch"
code+="[dtoa:%d,dfoa:%d]"%(int(self.lcw3[3:13],2),int(self.lcw3[13:21],2))
lcw3bits="%s"%(self.lcw3[0:3])
else:
code="rsrvd(%d)"%(self.lcw_code)
elif self.lcw_ft == 1:
ty="acchl"
if self.lcw_code == 1:
code="acchl" # 1(0), 3(msg_type), 1(block_num), 3(sapi_code), 8(segm_list), 5(unused)
code+="[msg_type:%01x,bloc_num:%01x,sapi_code:%01x,segm_list:%08s]"%(int(self.lcw3[1:4],2),int(self.lcw3[4:5],2),int(self.lcw3[5:8],2),self.lcw3[8:16])
lcw3bits="%s,%02x"%(self.lcw3[:1],int(self.lcw3[16:],2))
else:
code="rsrvd(%d)"%(self.lcw_code)
elif self.lcw_ft == 2:
ty="hndof"
if self.lcw_code == 12:
code="handoff_cand"
lcw3bits="%s,%s"%(self.lcw3[:11],self.lcw3[11:])
elif self.lcw_code == 3:
code="handoff_resp"
code+="[cand:%s,denied:%d,ref:%d,slot:%d,sband_up:%d,sband_dn:%d,access:%d]"%(['P','S'][int(self.lcw3[2:3],2)],int(self.lcw3[3:4],2),int(self.lcw3[4:5],2),1+int(self.lcw3[6:8],2),int(self.lcw3[8:13],2),int(self.lcw3[13:18],2),1+int(self.lcw3[18:21],2))
lcw3bits="%s,%s"%(self.lcw3[0:2],self.lcw3[5:6])
elif self.lcw_code == 15:
code="<silent>"
else:
code="rsrvd(%d)"%(self.lcw_code)
elif self.lcw_ft == 3:
ty="rsrvd"
code="<%d>"%(self.lcw_code)
self.header="LCW(%d,T:%s,C:%s,%s)"%(self.ft,ty,code,lcw3bits)
self.header="%-110s "%self.header
def pretty(self):
sstr= "IRI: "+self._pretty_header()
sstr+= " %2s"%self.msgtype
if self.descrambled!="":
sstr+= " ["
sstr+=".".join(["%02x"%int("0"+x,2) for x in slice("".join(self.descrambled), 8) ])
sstr+="]"
sstr+= self._pretty_trailer()
return sstr
class IridiumSYMessage(IridiumLCWMessage):
def __init__(self,imsg):
self.__dict__=imsg.__dict__
def upgrade(self):
self.fixederrs=(1+bitdiff(self.descrambled,"10"*(len(self.descrambled)//2)))//2 # count symbols
if self.uplink:
fe=(1+bitdiff(self.descrambled,"11"*(len(self.descrambled)//2)))//2 # count symbols
if fe + 5 < self.fixederrs:
self.fixederrs=fe
self.pattern="11"
else:
self.pattern="10"
return self
def pretty(self):
str= "ISY: "+self._pretty_header()
if self.fixederrs==0:
str+=" Sync=OK"
else:
str+=" Sync=no errs=%d"%self.fixederrs
if len(self.descrambled) < 312:
str+=" short:%s "%len(self.descrambled)
if self.uplink:
str+=" pattern=%s"%self.pattern
str+=self._pretty_trailer()
return str
iaq_crc16=crcmod.mkCrcFun(poly=0x15101,initCrc=0,rev=False,xorOut=0)
class IridiumAQMessage(IridiumMessage):
def __init__(self,imsg):
self.__dict__=imsg.__dict__
self.fixederrs=0
self.sym=[]
imap=['0','e','e','1']
bits=self.descrambled
for x in range(0,len(bits)-1,2):
self.sym.append(imap[int(bits[x+0])*2 + int(bits[x+1])])
if 'e' in self.sym:
raise ParserError("IAQ content not BPSK")
self.rid=int(self.sym[4]+self.sym[6]+self.sym[8]+self.sym[10]+self.sym[5]+self.sym[7]+self.sym[9]+self.sym[11],2)
self.val=bytes([int("".join(self.sym[:4]),2),int("".join(self.sym[4:12]),2)])
self.ridcrc=int("".join(self.sym[12:]),2)
self.crcval=iaq_crc16( bytes(self.val)) >>2
def upgrade(self):
return self
def pretty(self):
st= "IAQ: "+self._pretty_header()
st+= " " + "".join(self.sym[0:4])
st+= " " + "Rid:%03d"%self.rid
if self.ridcrc==self.crcval:
st+= " " + "CRC:OK"
else:
st+= " " + "CRC:no[%04x]"%self.ridcrc
st+=self._pretty_trailer()
return st
class IridiumSTLMessage(IridiumMessage):
def __init__(self,imsg):
self.__dict__=imsg.__dict__
if not args.forcetype:
self.header="<11>"
else:
self.header="<"+self.header+">"
self.fixederrs=0
if len(self.descrambled) < 8*8*12: # 12 blocks of 8 bytes
raise ParserError("ITL content too short")
symbols=de_dqpsk(self.descrambled)
(i_list,q_list)=split_qpsk(symbols)
i_list=["%02x"%int(x,2) for x in slice(i_list,8)]
q_list=["%02x"%int(x,2) for x in slice(q_list,8)]
self.i=["".join(x) for x in (i_list[:16],i_list[16:])]
self.q=["".join(x) for x in slice(q_list,12)]
if args.harder:
MAX_DIFF=10
self.ib=[bin(int(x, 16))[2:].zfill(len(x*4)) for x in self.i]
# Try to determine ITL version
self.itl_version= None
try:
self.itl_version= itl.PRS_HDR.index(self.i[0])
except ValueError:
if args.harder: # harder only supports V2
if bitdiff(self.ib[0],itl.BIN_HDR[2])<MAX_DIFF:
self.fixederrs+= 1
self.itl_version= 2
else:
raise ParserError("ITL PRS I#0 (version) unknown")
else:
raise ParserError("ITL PRS I#0 (version) unknown")
self.header="V%d"%self.itl_version
if self.itl_version==0: # No decoding yet
self.i= ["".join(x) for x in slice(i_list,16)]
self.q= ["".join(x) for x in slice(q_list,16)]
return
elif self.itl_version==1:
try:
self.plane= itl.MAP_PLANE_V1[self.i[1]]
except KeyError:
raise ParserError("ITL V1 PRS I#1 (plane) unknown")
self.msg=[]
for i,x in enumerate(self.q):
if x in itl.MAP_PRS_V1:
self.msg.append(itl.MAP_PRS_V1[x])
else:
if i==0 or self.msg[0]<77: # M8 does not contain normal PRS'
raise ParserError("ITL V1 PRS Q#%d unknown"%i)
self.msg.append(x)
elif self.itl_version==2 and not args.harder:
try:
self.plane= itl.MAP_PLANE[self.i[1]]
except KeyError:
raise ParserError("ITL V2 PRS I#1 (plane) unknown")
self.msg=[]
for i,x in enumerate(self.q):
if x in itl.MAP_PRS:
self.msg.append(itl.MAP_PRS[x])
else:
if i==0 or self.msg[0] != 108: # special message does not contain normal PRS
raise ParserError("ITL V2 PRS Q#%d unknown"%i)
self.msg.append(x)
if self.msg[0] != 108:
#sanity check the PRS sequence order
sanity = "".join([str(itl.MAP_PRS_TYPE[x]) for x in self.q])
if self.plane%2 == 0:
if sanity not in ("0123","1032"):
raise ParserError("ITL V2 PRS from unexpected set")
else:
if sanity not in ("2301","3210"):
raise ParserError("ITL V2 PRS from unexpected set")
elif self.itl_version==2 and args.harder:
self.plane=None
self.msg=[None]*4
if self.i[1] in itl.MAP_PLANE:
self.plane= itl.MAP_PLANE[self.i[1]]
else:
for i,p in enumerate(itl.BIN_PLANES):
if bitdiff(self.ib[1],p)<MAX_DIFF*2:
self.plane=i+1
self.fixederrs+=1
break
if self.plane is None:
raise ParserError("ITL V2 PRS I#1 (plane) unknown")
cat=None
for qidx in range(len(self.q)):
mindist=999
if qidx > 0 and self.msg[0] == 108:
self.msg[qidx]=self.q[qidx]
next
if self.q[qidx] in itl.MAP_PRS:
self.msg[qidx]= itl.MAP_PRS[self.q[qidx]]
cat=itl.MAP_PRS_TYPE[self.q[qidx]]
else:
q=bin(int(self.q[qidx], 16))[2:].zfill(len(self.q[qidx]*4))
if qidx==0: # Only search in correct PRS subset
if self.plane%2==0:
s=0
e=256
else:
s=256
e=512
elif qidx==1 or qidx==3:
cat^=1
s=128*cat
e=128*(cat+1)
elif qidx==2:
cat^=3
s=128*cat
e=128*(cat+1)
else:
raise AssertionError("ITL category error")
for i,prs in enumerate(itl.BIN_PRS[s:e]):
dist=bitdiff(q,prs)
if dist<mindist: mindist=dist
if dist<MAX_DIFF:
self.msg[qidx]=i%128
if cat is None:
cat=(i+s)//128
self.fixederrs+=1
break
if self.msg[qidx] is None:
self._new_error("ITL V2 PRS Q#%d unknown"%qidx)
raise ParserError("ITL PRS dist=%d"%mindist)
else:
raise AssertionError("ITL version error")
try:
(self.sat, self.mt)= itl.map_sat(self.msg[0], self.itl_version)
except ValueError:
raise ParserError("ITL invalid sat ID")
self.msg=self.msg[1:]
def upgrade(self):
return self
def pretty(self):
st= "ITL: "+self._pretty_header()
if self.itl_version==0:
st+= " -"
st+= " <"+" ".join(self.i)+">"
st+= " <"+" ".join(self.q)+">"
elif self.itl_version==1:
st+= " OK P%d"%self.plane
st+= " "+self.sat+" "+self.mt
for x in self.msg:
try:
st+= " "+"{0:07b}".format(x)
except ValueError:
st+= " "+x
else:
st+=" OK P%d"%self.plane
st+=" "+self.sat+" "+self.mt
for x in self.msg:
try:
st+= " "+"{0:07b}".format(x)
except ValueError:
st+= " "+x
st+=self._pretty_trailer()
return st
class IridiumLCW3Message(IridiumLCWMessage):
def __init__(self,imsg):
self.__dict__=imsg.__dict__
self.utype="IU3"
self.rs8p=False
self.rs6p=False
self.fixederrs=0
(ok,msg,csum)=rs.rs_fix(self.payload8)
self.rs8=ok
if ok:
self.utype="I38"
if bytearray(self.payload8)==msg+csum:
self.rs8p=True
else:
self.fixederrs+=1
self.rs8m=msg
self.rs8c=csum
self.csum=checksum_16(self.rs8m)
else:
(ok,msg,csum)=rs6.rs_fix(self.payload6)
self.rs6=ok
if ok:
self.utype="I36"
if bytearray(self.payload6)==msg+csum:
self.rs6p=True
else:
self.fixederrs+=1
self.rs6m=msg
self.rs6c=csum
def upgrade(self):
return self
def pretty(self):
str= self.utype+": "+self._pretty_header()
if self.utype=='I38':
if self.rs8p:
str+=" RS8=OK"
else:
str+=" RS8=ok"
if self.csum==0:
str+=" CS=OK"
self.rs8m=self.rs8m[0:-3]
remove_zeros(self.rs8m)
else:
str+=" CS=no"
str+= " ["
str+=" ".join(["%02x"%(x) for x in self.rs8m ])
str+= "]"
elif self.utype=='I36':
if self.rs6p:
str+=" RS6=OK"
else:
str+=" RS6=ok"
str+=" {%02d}"%self.rs6m[0]
str+= " ["
num=None
v="".join(["{0:06b}".format(x) for x in self.rs6m[1:] ])
if self.rs6m[0]==0:
str+=v[:2]+"| "+group(v[2:],10)
elif self.rs6m[0]==6:
str+=v[:2]+"| "+group(v[2:],24)
num=[int(x,2) for x in slice(v[2:],24)]
remove_zeros(num)
elif self.rs6m[0]==32 or self.rs6m[0]==34:
str+=v[:2]+"| "+group(v[2:],24)
num=[int(x,2) for x in slice(v[2:-4],24)]
if int(v[-4:],2)!=0:
num+=[int(v[-4:],2)]
while len(num)>0 and num[-1]==0x7ffff:
num=num[:-1]
else:
str+=group(v,6)
str+="]"
if num is not None:
str+=" <"+" ".join(["%06x"%x for x in num])+">"
else:
str+=" RS=no"
str+= " ["
str+=group(self.descrambled,8)
str+="]"
str+=self._pretty_trailer()
return str
class IridiumVOMessage(IridiumLCWMessage):
def __init__(self,imsg):
self.__dict__=imsg.__dict__
# Test if CRC24 is ok -> VDA
self.crcval=iip_crc24( bytes(self.payload_r))
if self.crcval==0:
self.vtype="VDA"
return
# Test if rs6 accepts it -> VO6 (unknown)
(ok,msg,csum)=rs6.rs_fix(self.payload_6)
self.rs6p=False
self.rs6=ok