-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
6521 lines (5202 loc) · 206 KB
/
test.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/python2.3
import sys
import types
import exceptions
import re
import socket
import struct
import time
import thread
import threading
import random
import CSThread
# some debugging flags and functions
_debug = 0
_debugVLAN = _debug or 0
_debugAdapterRefs = _debug or 0
_debugSegmentation = _debug or 0
_debugAPDUcodec = _debug or 0
def StringToHex(x,sep=''):
return sep.join(["%02X" % (ord(c),) for c in x])
def HexToString(x,sep=''):
return ''.join([chr(int(x[i:i+2],16)) for i in range(0,len(x),len(sep)+2)])
#
# Exceptions
#
class ConfigurationError(exceptions.ValueError):
def __init__(self,args=None):
self.args = args
class EncodingError(exceptions.ValueError):
def __init__(self,args=None):
self.args = args
class DecodingError(exceptions.ValueError):
def __init__(self,args=None):
self.args = args
#
# Address
#
IPAddrMaskPortRE = re.compile(r'^(?:(\d+):)?(\d+\.\d+\.\d+\.\d+)(?:/(\d+))?(?::(\d+))?$' )
class Address:
nullAddr = 0
localBroadcastAddr = 1
localStationAddr = 2
remoteBroadcastAddr = 3
remoteStationAddr = 4
globalBroadcastAddr = 5
def __init__(self,*args):
self.addrType = Address.nullAddr
self.addrNet = None
self.addrLen = 0
self.addrAddr = ''
if len(args) == 1:
self.DecodeAddress(args[0])
elif len(args) == 2:
self.DecodeAddress(args[1])
if self.addrType == Address.localStationAddr:
self.addrType = Address.remoteStationAddr
self.addrNet = args[0]
elif self.addrType == Address.localBroadcastAddr:
self.addrType = Address.remoteBroadcastAddr
self.addrNet = args[0]
else:
raise ValueError, "unrecognized address ctor form"
def DecodeAddress(self,addr):
"""Initialize the address from a string. Lots of different forms are supported."""
if _debug:
print self, "DecodeAddress", addr
# start out assuming this is a local station
self.addrType = Address.localStationAddr
self.addrNet = None
if addr == "*":
self.addrType = Address.localBroadcastAddr
self.addrNet = None
self.addrAddr = None
self.addrLen = None
elif addr == "*:*":
self.addrType = Address.globalBroadcastAddr
self.addrNet = None
self.addrAddr = None
self.addrLen = None
elif isinstance(addr,types.IntType):
if (addr < 0) or (addr >= 256):
raise ValueError, "address out of range"
self.addrAddr = chr(addr)
self.addrLen = 1
elif isinstance(addr,types.StringType):
m = IPAddrMaskPortRE.match(addr)
if m:
net, addr, mask, port = m.groups()
if not mask: mask = '32'
if not port: port = '47808'
if net:
net = int(net)
if (net >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteStationAddr
self.addrNet = net
self.addrPort = int(port)
self.addrTuple = (addr,self.addrPort)
addrstr = socket.inet_aton(addr)
self.addrIP = struct.unpack('!L',addrstr)[0]
self.addrMask = -1L << (32 - int(mask))
self.addrHost = (self.addrIP & ~self.addrMask)
self.addrSubnet = (self.addrIP & self.addrMask)
bcast = (self.addrSubnet | ~self.addrMask)
self.addrBroadcastTuple = (socket.inet_ntoa(struct.pack('!L',bcast)),self.addrPort)
self.addrAddr = addrstr + struct.pack('!H',self.addrPort)
self.addrLen = 6
elif re.match(r"^\d+$",addr):
addr = int(addr)
if (addr > 255):
raise ValueError, "address out of range"
self.addrAddr = chr(addr)
self.addrLen = 1
elif re.match(r"^\d+:[*]$",addr):
addr = int(addr[:-2])
if (addr >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteBroadcastAddr
self.addrNet = addr
self.addrAddr = None
self.addrLen = None
elif re.match(r"^\d+:\d+$",addr):
net, addr = addr.split(':')
net = int(net)
addr = int(addr)
if (net >= 65535):
raise ValueError, "network out of range"
if (addr > 255):
raise ValueError, "address out of range"
self.addrType = Address.remoteStationAddr
self.addrNet = net
self.addrAddr = chr(addr)
self.addrLen = 1
elif re.match(r"^0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
self.addrAddr = HexToString(addr[2:])
self.addrLen = len(self.addrAddr)
elif re.match(r"^X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
self.addrAddr = HexToString(addr[2:-1])
self.addrLen = len(self.addrAddr)
elif re.match(r"^\d+:0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
net, addr = addr.split(':')
net = int(net)
if (net >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteStationAddr
self.addrNet = net
self.addrAddr = HexToString(addr[2:])
self.addrLen = len(self.addrAddr)
elif re.match(r"^\d+:X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
net, addr = addr.split(':')
net = int(net)
if (net >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteStationAddr
self.addrNet = net
self.addrAddr = HexToString(addr[2:-1])
self.addrLen = len(self.addrAddr)
else:
raise ValueError, "unrecognized format"
elif isinstance(addr,types.TupleType):
addr, port = addr
self.addrPort = int(port)
if isinstance(addr,types.StringType):
addrstr = socket.inet_aton(addr)
self.addrTuple = (addr,self.addrPort)
elif isinstance(addr,types.LongType):
addrstr = struct.pack('!L',addr)
self.addrTuple = (socket.inet_ntoa(addrstr),self.addrPort)
else:
raise TypeError, "tuple must be (string,port) or (long,port)"
self.addrIP = struct.unpack('!L',addrstr)[0]
self.addrMask = -1L
self.addrHost = None
self.addrSubnet = None
self.addrBroadcastTuple = self.addrTuple
self.addrAddr = addrstr + struct.pack('!H',self.addrPort)
self.addrLen = 6
else:
raise TypeError, "integer, string or tuple required"
def __str__(self):
if self.addrType == Address.nullAddr:
return 'Null'
elif self.addrType == Address.localBroadcastAddr:
return '*'
elif self.addrType == Address.localStationAddr:
rslt = ''
if self.addrLen == 1:
rslt += str(ord(self.addrAddr[0]))
else:
port = ord(self.addrAddr[-2]) * 256 + ord(self.addrAddr[-1])
if (len(self.addrAddr) == 6) and (port >= 47808) and (port <= 47823):
rslt += '.'.join(["%d" % ord(x) for x in self.addrAddr[0:4]])
if port != 47808:
rslt += ':' + str(port)
else:
rslt += '0x' + StringToHex(self.addrAddr)
return rslt
elif self.addrType == Address.remoteBroadcastAddr:
return '%d:*' % (self.addrNet,)
elif self.addrType == Address.remoteStationAddr:
rslt = '%d:' % (self.addrNet,)
if self.addrLen == 1:
rslt += str(ord(self.addrAddr[0]))
else:
port = ord(self.addrAddr[-2]) * 256 + ord(self.addrAddr[-1])
if (len(self.addrAddr) == 6) and (port >= 47808) and (port <= 47823):
rslt += '.'.join(["%d" % ord(x) for x in self.addrAddr[0:4]])
if port != 47808:
rslt += ':' + str(port)
else:
rslt += '0x' + StringToHex(self.addrAddr)
return rslt
elif self.addrType == Address.globalBroadcastAddr:
return '*:*'
else:
raise TypeError, "unknown address type %d" % self.addrType
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.__str__())
def __hash__(self):
return hash( (self.addrType, self.addrNet, self.addrAddr) )
def __eq__(self,arg):
# try an coerce it into an address
if not isinstance(arg,Address):
arg = Address(arg)
# all of the components must match
return (self.addrType == arg.addrType) and (self.addrNet == arg.addrNet) and (self.addrAddr == arg.addrAddr)
def __ne__(self,arg):
return not self.__eq__(arg)
def IPAddrPack(addr):
return socket.inet_aton(addr[0]) + struct.pack('!H',addr[1])
def IPAddrUnpack(addr):
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H',addr[4:6])[0] )
#
class LocalStation(Address):
def __init__(self,addr):
self.addrType = Address.localStationAddr
self.addrNet = None
if isinstance(addr,types.IntType):
if (addr < 0) or (addr >= 256):
raise ValueError, "address out of range"
self.addrAddr = chr(addr)
self.addrLen = 1
else:
self.addrAddr = addr
self.addrLen = len(addr)
class RemoteStation(Address):
def __init__(self,net,addr):
if (net < 0) or (net >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteStationAddr
self.addrNet = net
if isinstance(addr,types.IntType):
if (addr < 0) or (addr >= 256):
raise ValueError, "address out of range"
self.addrAddr = chr(addr)
self.addrLen = 1
else:
self.addrAddr = addr
self.addrLen = len(addr)
class LocalBroadcast(Address):
def __init__(self):
self.addrType = Address.localBroadcastAddr
self.addrNet = None
self.addrAddr = None
self.addrLen = None
class RemoteBroadcast(Address):
def __init__(self,net):
if (net < 0) or (net >= 65535):
raise ValueError, "network out of range"
self.addrType = Address.remoteBroadcastAddr
self.addrNet = net
self.addrAddr = None
self.addrLen = None
class GlobalBroadcast(Address):
def __init__(self):
self.addrType = Address.globalBroadcastAddr
self.addrNet = None
self.addrAddr = None
self.addrLen = None
#
# PDUData
#
class PDUData:
def __init__(self, data=''):
if isinstance(data,PDUData):
self.pduData = data.pduData
elif isinstance(data,types.StringType):
self.pduData = data
else:
raise ValueError, "PDUData ctor parameter must be PDUData or a string"
def Get(self):
if len(self.pduData) == 0:
raise DecodingError, "no more packet data"
ch = self.pduData[0]
self.pduData = self.pduData[1:]
return ord(ch)
def GetShort(self):
if len(self.pduData) < 2:
raise DecodingError, "no more packet data"
rslt = (ord(self.pduData[0]) << 8) + ord(self.pduData[1])
self.pduData = self.pduData[2:]
return rslt
def GetLong(self):
return struct.unpack('>L',self.GetData(4))[0]
def GetData(self, dlen):
if len(self.pduData) < dlen:
raise DecodingError, "no more packet data"
data = self.pduData[:dlen]
self.pduData = self.pduData[dlen:]
return data
def Put(self, ch):
self.pduData += chr(ch)
def PutShort(self, n):
self.pduData += chr((n >> 8) & 0xFF) + chr(n & 0xFF)
def PutLong(self, n):
self.pduData += struct.pack('>L',n)
def PutData(self, data):
self.pduData += data
def __str__(self):
"""Useful for debugging."""
return "PDUData(" + StringToHex(self.pduData,'.') + ")"
#
# Tag
#
class Tag:
applicationTagClass = 0
contextTagClass = 1
openingTagClass = 2
closingTagClass = 3
nullAppTag = 0
booleanAppTag = 1
unsignedAppTag = 2
integerAppTag = 3
realAppTag = 4
doubleAppTag = 5
octetStringAppTag = 6
characterStringAppTag = 7
bitStringAppTag = 8
enumeratedAppTag = 9
dateAppTag = 10
timeAppTag = 11
objectIdentifierAppTag = 12
reservedAppTag13 = 13
reservedAppTag14 = 14
reservedAppTag15 = 15
_applicationTagName = \
[ 'null', 'boolean', 'unsigned', 'integer'
, 'real', 'double', 'octetString', 'characterString'
, 'bitString', 'enumerated', 'date', 'time'
, 'objectIdentifier', 'reserved13', 'reserved14', 'reserved15'
]
_applicationTagClass = [] # defined later
def __init__(self, *args):
self.tagClass = None
self.tagNumber = None
self.tagLVT = None
self.tagData = None
if args:
if (len(args) == 1) and isinstance(args[0],PDUData):
self.Decode(args[0])
elif (len(args) >= 2):
self.Set(*args)
else:
raise ValueError, "invalid Tag ctor arguments"
def Set(self, tclass, tnum, tlvt=0, tdata=''):
"""Set the values of the tag."""
self.tagClass = tclass
self.tagNumber = tnum
self.tagLVT = tlvt
self.tagData = tdata
def SetAppData(self, tnum, tdata):
"""Set the values of the tag."""
self.tagClass = Tag.applicationTagClass
self.tagNumber = tnum
self.tagLVT = len(tdata)
self.tagData = tdata
def Encode(self, pdu):
# check for special encoding of open and close tags
if (self.tagClass == Tag.openingTagClass):
pdu.Put(((self.tagNumber & 0x0F) << 4) + 0x0E)
return
if (self.tagClass == Tag.closingTagClass):
pdu.Put(((self.tagNumber & 0x0F) << 4) + 0x0F)
return
# check for context encoding
if (self.tagClass == Tag.contextTagClass):
data = 0x08
else:
data = 0x00
# encode the tag number part
if (self.tagNumber < 15):
data += (self.tagNumber << 4)
else:
data += 0xF0
# encode the length/value/type part
if (self.tagLVT < 5):
data += self.tagLVT
else:
data += 0x05
# save this and the extended tag value
pdu.Put( data )
if (self.tagNumber >= 15):
pdu.Put(self.tagNumber)
# really short lengths are already done
if (self.tagLVT >= 5):
if (self.tagLVT <= 253):
pdu.Put( self.tagLVT )
elif (self.tagLVT <= 65535):
enc.Put( 254 )
pdu.PutShort( self.tagLVT )
else:
pdu.Put( 255 )
pdu.PutLong( self.tagLVT )
# now put the data
pdu.PutData(self.tagData)
def Decode(self, pdu):
tag = pdu.Get()
# extract the type
self.tagClass = (tag >> 3) & 0x01
# extract the tag number
self.tagNumber = (tag >> 4)
if (self.tagNumber == 0x0F):
self.tagNumber = dec.Get()
# extract the length
self.tagLVT = tag & 0x07
if (self.tagLVT == 5):
self.tagLVT = pdu.Get()
if (self.tagLVT == 254):
self.tagLVT = pdu.GetShort()
elif (self.tagLVT == 255):
self.tagLVT = pdu.GetLong()
elif (self.tagLVT == 6):
self.tagClass = Tag.openingTagClass
self.tagLVT = 0
elif (self.tagLVT == 7):
self.tagClass = Tag.closingTagClass
self.tagLVT = 0
# application tagged boolean has no more data
if (self.tagClass == Tag.applicationTagClass) and (self.tagNumber == Tag.booleanAppTag):
# tagLVT contains value
self.tagData = ''
else:
# tagLVT contains length
self.tagData = pdu.GetData(self.tagLVT)
def AppToCtx(self, context):
"""Return a context encoded tag."""
if self.tagClass != Tag.applicationTagClass:
raise ValueError, "application tag required"
# application tagged boolean now has data
if (self.tagNumber == Tag.booleanAppTag):
return ContextTag(context, chr(self.tagLVT))
else:
return ContextTag(context, self.tagData)
def CtxToApp(self, dataType):
"""Return an application encoded tag."""
if self.tagClass != Tag.contextTagClass:
raise ValueError, "context tag required"
# context booleans have value in data
if (dataType == Tag.booleanAppTag):
return Tag(Tag.applicationTagClass, Tag.booleanAppTag, ord(self.tagData[0]), '')
else:
return ApplicationTag(dataType, self.tagData)
def AppToObject(self):
"""Return the application object encoded by the tag."""
if self.tagClass != Tag.applicationTagClass:
raise ValueError, "application tag required"
# get the class to build
klass = self._applicationTagClass[self.tagNumber]
if not klass:
return None
# build an object, tell it to decode this tag, and return it
return klass(self)
def __repr__(self):
xid = id(self)
if (xid < 0): xid += (1L << 32)
sname = self.__module__ + '.' + self.__class__.__name__
try:
if self.tagClass == Tag.openingTagClass:
desc = "(open(%d))" % (self.tagNumber,)
elif self.tagClass == Tag.closingTagClass:
desc = "(close(%d))" % (self.tagNumber,)
elif self.tagClass == Tag.contextTagClass:
desc = "(context(%d))" % (self.tagNumber,)
elif self.tagClass == Tag.applicationTagClass:
desc = "(%s)" % (self._applicationTagName[self.tagNumber],)
else:
raise ValueError, "invalid tag class"
except:
desc = "(?)"
return '<' + sname + desc + ' instance at 0x%08x' % (xid,) + '>'
def __eq__(self, tag):
return (self.tagClass == tag.tagClass) \
and (self.tagNumber == tag.tagNumber) \
and (self.tagLVT == tag.tagLVT) \
and (self.tagData == tag.tagData)
def __ne__(self,arg):
return not self.__eq__(arg)
#
# ApplicationTag
#
class ApplicationTag(Tag):
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], PDUData):
Tag.__init__(self, args[0])
if self.tagClass != Tag.applicationTagClass:
raise DecodingError, "application tag not decoded"
elif len(args) == 2:
tnum, tdata = args
Tag.__init__(self, Tag.applicationTagClass, tnum, len(tdata), tdata)
else:
raise ValueError, "ApplicationTag ctor requires a type and data or PDUData"
#
# ContextTag
#
class ContextTag(Tag):
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], PDUData):
Tag.__init__(self, args[0])
if self.tagClass != Tag.contextTagClass:
raise DecodingError, "context tag not decoded"
elif len(args) == 2:
tnum, tdata = args
Tag.__init__(self, Tag.contextTagClass, tnum, len(tdata), tdata)
else:
raise ValueError, "ContextyTag ctor requires a type and data or PDUData"
#
# OpeningTag
#
class OpeningTag(Tag):
def __init__(self, context):
if isinstance(context, PDUData):
Tag.__init__(self, context)
if self.tagClass != Tag.openingTagClass:
raise DecodingError, "opening tag not decoded"
elif isinstance(context, types.IntType):
Tag.__init__(self, Tag.openingTagClass, context)
else:
raise TypeError, "OpeningTag ctor requires an integer or PDUData"
#
# ClosingTag
#
class ClosingTag(Tag):
def __init__(self, context):
if isinstance(context, PDUData):
Tag.__init__(self, context)
if self.tagClass != Tag.closingTagClass:
raise DecodingError, "closing tag not decoded"
elif isinstance(context, types.IntType):
Tag.__init__(self, Tag.closingTagClass, context)
else:
raise TypeError, "OpeningTag ctor requires an integer or PDUData"
#
# DebugTag
#
def DebugTag(tag):
print "DebugTag", tag
print " tagClass =", tag.tagClass,
if tag.tagClass == Tag.applicationTagClass: print 'application'
elif tag.tagClass == Tag.contextTagClass: print 'context'
elif tag.tagClass == Tag.openingTagClass: print 'opening'
elif tag.tagClass == Tag.closingTagClass: print 'closing'
else: print "?"
print " tagNumber =", tag.tagNumber,
if tag.tagClass == Tag.applicationTagClass:
try:
print tag._applicationTagName[tag.tagNumber]
except:
print "?"
else: print
print " tagLVT =", tag.tagLVT,
if tag.tagLVT != len(tag.tagData): print "(length does not match data)"
else: print "(length match)"
print " tagData = '%s'" % (StringToHex(tag.tagData,'.'),)
#
# TagList
#
class TagList:
def __init__(self, arg=None):
self.tagList = []
if isinstance(arg, types.ListType):
self.tagList = arg
elif isinstance(arg, TagList):
self.tagList = arg.tagList[:]
elif isinstance(arg, PDUData):
self.Decode(arg)
def append(self, tag):
self.tagList.append(tag)
def extend(self, taglist):
self.tagList.extend(taglist)
def __getitem__(self, item):
return self.tagList[item]
def __len__(self):
return len(self.tagList)
def Peek(self):
"""Return the tag at the front of the list."""
if self.tagList:
tag = self.tagList[0]
else:
tag = None
if _debug:
print "(peek)", tag
return tag
def Push(self, tag):
"""Return a tag back to the front of the list."""
if _debug:
print "(push)", tag
self.tagList = [tag] + self.tagList
def Pop(self):
"""Remove the tag from the front of the list and return it."""
if self.tagList:
tag = self.tagList[0]
del self.tagList[0]
else:
tag = None
if _debug:
print "(pop)", tag
return tag
def GetContext(self, context):
"""Return a tag or a list of tags context encoded."""
# forward pass
i = 0
while i < len(self.tagList):
tag = self.tagList[i]
# skip application stuff
if tag.tagClass == Tag.applicationTagClass:
pass
# check for context encoded atomic value
elif tag.tagClass == Tag.contextTagClass:
if tag.tagNumber == context:
return tag
# check for context encoded group
elif tag.tagClass == Tag.openingTagClass:
keeper = tag.tagNumber == context
rslt = []
i += 1
lvl = 0
while i < len(self.tagList):
tag = self.tagList[i]
if tag.tagClass == Tag.openingTagClass:
lvl += 1
elif tag.tagClass == Tag.closingTagClass:
lvl -= 1
if lvl < 0: break
rslt.append(tag)
i += 1
# make sure everything balances
if lvl >= 0:
raise DecodingError, "mismatched open/close tags"
# get everything we need?
if keeper:
return TagList(rslt)
else:
raise DecodingError, "unexpected tag"
# try the next tag
i += 1
# nothing found
return None
def Encode(self, pdu):
"""Encode the tag list into a PDU."""
for tag in self.tagList:
tag.Encode(pdu)
def Decode(self, pdu):
"""Decode the tags from a PDU."""
while pdu.pduData:
self.tagList.append( Tag(pdu) )
#
# DebugTagList
#
def DebugTagList(tags):
print "DebugTagList", tags
for tag in tags.tagList:
print " ", tag
#
# Atomic
#
class Atomic:
_appTag = None
def __cmp__(self, other):
# hoop jump it
if not isinstance(other, self.__class__):
other = self.__class__(other)
# now compare the values
if (self.value < other.value):
return -1
elif (self.value > other.value):
return 1
else:
return 0
#
# Null
#
class Null(Atomic):
_appTag = Tag.nullAppTag
def __init__(self, arg=None):
self.value = ()
if arg is None:
pass
elif isinstance(arg,Tag):
self.Decode(arg)
elif isinstance(arg,types.TupleType):
if len(arg) != 0:
raise ValueError, "empty tuple required"
else:
raise TypeError, "invalid constructor datatype"
def Encode(self, tag):
tag.SetAppData(Tag.nullAppTag, '')
def Decode(self, tag):
if (tag.tagClass != Tag.applicationTagClass) or (tag.tagNumber != Tag.nullAppTag):
raise ValueError, "null application tag required"
self.value = ()
def __str__(self):
return "Null"
#
# Boolean
#
class Boolean(Atomic):
_appTag = Tag.booleanAppTag
def __init__(self, arg=None):
self.value = False
if arg is None:
pass
elif isinstance(arg,Tag):
self.Decode(arg)
elif isinstance(arg,types.BooleanType):
self.value = arg
else:
raise TypeError, "invalid constructor datatype"
def Encode(self, tag):
tag.Set(Tag.applicationTagClass, Tag.booleanAppTag, int(self.value), '')
def Decode(self, tag):
if (tag.tagClass != Tag.applicationTagClass) or (tag.tagNumber != Tag.booleanAppTag):
raise ValueError, "boolean application tag required"
# get the data
self.value = bool(tag.tagLVT)
def __str__(self):
return "Boolean(%s)" % (str(self.value), )
#
# Unsigned
#
class Unsigned(Atomic):
_appTag = Tag.unsignedAppTag
def __init__(self,arg = None):
self.value = 0L
if arg is None:
pass
elif isinstance(arg,Tag):
self.Decode(arg)
elif isinstance(arg,types.IntType):
if (arg < 0):
raise ValueError, "unsigned integer required"
self.value = long(arg)
elif isinstance(arg,types.LongType):
if (arg < 0):
raise ValueError, "unsigned integer required"
self.value = arg
else:
raise TypeError, "invalid constructor datatype"
def Encode(self, tag):
# rip apart the number
data = [ord(c) for c in struct.pack('>L',self.value)]
# reduce the value to the smallest number of octets
while (len(data) > 1) and (data[0] == 0):
del data[0]
# encode the tag
tag.SetAppData(Tag.unsignedAppTag, ''.join(chr(c) for c in data))
def Decode(self, tag):
if (tag.tagClass != Tag.applicationTagClass) or (tag.tagNumber != Tag.unsignedAppTag):
raise ValueError, "unsigned application tag required"
# get the data
rslt = 0L
for c in tag.tagData:
rslt = (rslt << 8) + ord(c)
# save the result
self.value = rslt
def __str__(self):
return "Unsigned(%s)" % (self.value, )
#
# Integer
#
class Integer(Atomic):
_appTag = Tag.integerAppTag
def __init__(self,arg = None):
self.value = 0
if arg is None:
pass
elif isinstance(arg,Tag):
self.Decode(arg)
elif isinstance(arg,types.IntType):
self.value = arg
elif isinstance(arg,types.LongType):
self.value = arg
else:
raise TypeError, "invalid constructor datatype"
def Encode(self, tag):
# rip apart the number
data = [ord(c) for c in struct.pack('>I',self.value)]
# reduce the value to the smallest number of bytes, be
# careful about sign extension