-
Notifications
You must be signed in to change notification settings - Fork 4
/
incoming.py
executable file
·2845 lines (2228 loc) · 103 KB
/
incoming.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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import struct
import logging
from Peach.Engine.common import *
from Peach.Engine.dom import *
import Peach
def Debug(level, msg):
"""
Debug output. Uncommenting the following
print line will cause *lots* of output
to be displayed. It significantly slows the
data cracking process.
"""
# Don't show look aheads
if Peach.Engine.engine.Engine.debug:
if DataCracker._tabLevel == 0:
print(msg)
def PeachStr(s):
"""
Our implementation of str() which does not
convert None to 'None'.
"""
if s is None:
return None
return str(s)
class DataCracker(object):
"""
This class will try and parse data into a data model. This
process will try and best-fit data based on performing look
aheads with fit-ratings.
"""
#: Have we recursed into DataCracker?
_tabLevel = 0
def __init__(self, peachXml, inner=False):
self.peach = peachXml
self.deepString = -1
#: To what depth are we looking ahead?
self.lookAheadDepth = 0
#: Are we looking ahead?
self.lookAhead = False
#: Parent position (if any)
self.parentPos = 0
if not inner:
DataCracker._tabLevel = 0
def internalCrackData(self, template, buff, method='setValue'):
"""
This is the internal method called when we recurse into
crackData. It will not perform certain operations that should
be performed on the entire data model instead of sub-portions.
"""
if not isinstance(buff, PublisherBuffer):
raise Exception("Error: buff is not a PublisherBuffer")
self.method = method
(rating, pos) = self._handleNode(template, buff, 0, None) #, self.dom)
Debug(1, "RATING: %d - POS: %d - LEN(DATA): %d" % (rating, self.parentPos + pos, len(buff.data)))
if pos < len(buff.data) - 1:
Debug(1, highlight.warning("WARNING: Did not consume all data!!!"))
Debug(1, "Done cracking stuff")
return rating, pos
def optmizeModelForCracking(self, datamodel, silent=False):
"""
This method will pre-compute some values that will
enable optimzing how we crack data into said model.
"""
if not silent:
logging.info("Optimizing DataModel '%s'" % datamodel.name)
# Setup choice fastcheck
for node in datamodel.getAllChildDataElements():
if node.elementType == 'choice':
for child in node:
# If _isTokenNext on our choice child is true we can cache
# cache that value and use it to super speed up choice checks
fastCheck = False
fastCheckValue = None
fastCheckOffset = 0
if child.isStatic:
fastCheck = True
fastCheckValue = child.getValue()
fastCheckOffset = 0
#Debug(1, "optmizeModelForCracking: FastCheck: Child is token for '%s'" % child.name)
else:
values = self._isTokenNext(child, True)
#Debug(1, "optmizeModelForCracking: FastCheck: back from _isTokenNext")
if values is not None and values[0].getFullname().find(child.getFullname()) != -1:
fastCheck = True
fastCheckValue = values[0].getValue()
fastCheckOffset = values[1]
# Sanity check
if len(fastCheckValue) < 1:
raise PeachException(
"optmizeModelForCracking: Warning, fastCheckValue is < 1 in length")
#Debug(1, "optmizeModelForCracking: FastCheck: Found next token for '%s' [%s]" % (child.name, values[0].name))
else:
#Debug(1, "optmizeModelForCracking: Found no token for '%s'" % child.name)
#raise PeachException("_handleChoice(): Found no token for '%s'" % child.name)
pass
child.choiceCache = (fastCheck, fastCheckOffset, fastCheckValue)
def crackData(self, template, buff, method='setValue'):
"""
Crack data based on template. Set values into data tree.
Will throw an exception (NeedMoreData) if additional data is required.
The exception contains the minimum amount of additional data needed before
trying to re-crack the data.
"""
if not isinstance(buff, PublisherBuffer):
raise Exception("Error: buff is not a PublisherBuffer")
# Reset all values in tree
# NOTE: Do not change setValue to method. We NEEVER want
# to run this with setDefaultValue or else DEATH AND DOOM TO U!
#
# Do we really need todo this?
#
#self._resetDataElementValues(template, 'setValue')
#self.method = 'setValue'
self.crackPassed = True
self.method = method
(rating, pos) = self._handleNode(template, buff, 0, None) #, self.dom)
Debug(1, "RATING: %d - POS: %d - LEN(DATA): %d" % (rating, self.parentPos + pos, len(buff.data)))
if pos < len(buff.data) - 1:
self.crackPassed = False
Debug(1, "WARNING: Did not consume all data!!!")
if rating > 2:
self.crackPassed = False
# Find all our placements and shift elements around.
placements = []
for placement in template.getAllPlacementsInDataModel():
placements.append(placement)
for placement in placements:
# ----
# We need to update all relations to fully qualified names since we have fully moved
# nodes around. There are two categories. First, of-relations and second relations.
# We will track these in to arrays of a tuple.
relations = []
relationsHold = []
paramReferences = []
Debug(1, "Get all relations")
for relation in placement.parent.getRelationsOfThisElement():
if relation.type == 'when':
continue
#print "Found:",relation.getFullname()
relations.append([relation, placement.parent])
relationsHold.append(relation)
for child in placement.parent.getAllChildDataElements():
for relation in child.getRelationsOfThisElement():
if relation not in relationsHold and relation.type != 'when':
#print "Found:",relation.getFullname()
relations.append([relation, child])
relationsHold.append(relation)
for relation in placement.parent._getAllRelationsInDataModel(placement.parent):
if relation not in relationsHold and relation.type != 'when':
try:
obj = relation.getOfElement()
if obj is None:
print("relation:", relation.getFullname())
print("of: ", relation.of)
raise Exception("obj is null")
except:
print("relation:", relation.getFullname())
print("of:", relation.of)
raise
#print "Found:",relation.getFullname()
relations.append([relation, obj])
relationsHold.append(relation)
# Locate things like <Param name="ref" value="Data" />
Debug(1, "Get all parameter references")
for param in placement.parent.getRootOfDataMap().getElementsByType(Param):
if param.name == 'ref':
obj = param.parent.parent.find(param.defaultValue.replace("'", ""))
if obj == placement.parent:
paramReferences.append([param, obj])
# ----
if placement.after is not None:
#after = template.findDataElementByName(placement.after)
after = placement.parent.find(placement.after)
if after is None:
raise Exception("Error: Unable to locate element [%s] for placement" % placement.after)
Debug(1, "Moving element [%s] to after [%s]." % (placement.parent.name, after.name))
Debug(1, " Pre-name: %s" % placement.parent.getFullnameInDataModel())
Debug(1, " Found %d relations" % len(relationsHold))
Debug(1, " Found %d param references" % len(paramReferences))
# Remove from old place
placement.parent.origName = placement.parent.name
del placement.parent.parent[placement.parent.origName]
# Do we need to rename our Element?
if after.parent.has_key(placement.parent.name):
# Yes... :)
cnt = 0
while after.parent.has_key(placement.parent.name):
placement.parent.name = placement.parent.origName + ("_%d" % cnt)
cnt += 1
Debug(1, " Renamed before move from [%s] to [%s]" % (
placement.parent.origName, placement.parent.name))
# Insert after after
after.parent.insert(after.parent.index(after) + 1, placement.parent)
# Update parent
placement.parent.parent = after.parent
# Remove placement
placement.parent.placement = None
elif placement.before is not None:
#before = template.findDataElementByName(placement.before)
before = placement.parent.find(placement.before)
if before is None:
raise Exception("Error: Unable to locate element [%s] for placement" % placement.before)
Debug(1, "Moving element [%s] to before [%s]." % (placement.parent.name, before.name))
Debug(1, " Pre-name: %s" % placement.parent.getFullnameInDataModel())
Debug(1, " Found %d relations" % len(relationsHold))
Debug(1, " Found %d param references" % len(paramReferences))
# Remove from old place
placement.parent.origName = placement.parent.name
del placement.parent.parent[placement.parent.origName]
# Do we need to rename our Element?
if before.parent.has_key(placement.parent.name):
# Yes... :)
cnt = 0
while before.parent.has_key(placement.parent.name):
placement.parent.name = placement.parent.origName + ("_%d" % cnt)
cnt += 1
Debug(1, " Renamed before move from [%s] to [%s]" % (
placement.parent.origName, placement.parent.name))
# Insert after after
before.parent.insert(before.parent.index(before), placement.parent)
# Update parent
placement.parent.parent = before.parent
# Remove placement
placement.parent.placement = None
Debug(1, " Final name: %s" % placement.parent.getFullnameInDataModel())
else:
raise Exception("Error: placement is all null in bad ways!")
# Update relations
Debug(1, "Update relations")
for relation, of in relations:
relation.of = of.getFullnameInDataModel()
# Handle FROM side too
for r in of.relations:
if r.From is not None and r.From.endswith(relation.parent.name):
r.From = relation.parent.getFullnameInDataModel()
#print "Updating %s to %s" % (relation.getFullname(), relation.of)
Debug(1, "Update param references")
for param, obj in paramReferences:
# Need to recreate the fixup to make sure
# it re-parses the ref parameter.
param.defaultValue = "'''%s'''" % obj.getFullnameInDataModel()
fixup = param.parent
code = "PeachXml_" + fixup.classStr + '('
isFirst = True
for param in fixup:
if not isinstance(param, Param):
continue
if not isFirst:
code += ', '
else:
isFirst = False
code += PeachStr(param.defaultValue)
code += ')'
fixup.fixup = evalEvent(code, {})
Debug(1, "Done cracking stuff")
#sys.exit(0)
#template.printDomMap()
return rating, pos
def _resetDataElementValues(self, node, method):
"""
Reset values in data tree to None.
"""
eval("node.%s(None)" % method)
if hasattr(node, 'rating'):
node.rating = None
if hasattr(node, 'pos'):
node.pos = None
for child in node._children:
if isinstance(child, Peach.Engine.dom.DataElement):
self._resetDataElementValues(child, method)
def _GetTemplateByName(self, str):
"""
Get the object indicated by ref. Currently the object must have
been defined prior to this point in the XML
"""
origStr = str
baseObj = self.peach
# Parse out a namespace
if str.find(":") > -1:
ns, tmp = str.split(':')
str = tmp
# Check for namespace
if hasattr(self.context.namespaces, ns):
baseObj = getattr(self.context.namespaces, ns)
else:
raise Exception("Unable to locate namespace")
for name in str.split('.'):
# check base obj
if hasattr(baseObj, name):
baseObj = getattr(baseObj, name)
# check templates
elif hasattr(baseObj, 'templates') and hasattr(baseObj.templates, name):
baseObj = getattr(baseObj.templates, name)
else:
raise Exception("Could not resolve ref '%s'" % origStr)
return baseObj
def _getRootParent(self, node):
root = node
while hasattr(root, 'parent') and root.parent is not None:
root = root.parent
return root
def _handleArray(self, node, buff, pos, parent=None, doingMinMax=False):
"""
This method is used when an array has been located (an element with
minOccurs or maxOccurs set).
Note: This code was moved out of _handleNode() on 11/16/08
Todo: This array handling code has gotten out of hand. It needs
some re-working and cleaning up.
"""
Debug(1, "_handleArray(%s): %s >>Enter" % (node.name, node.elementType))
Debug(1, "_handleArray(%s): %s" % (node.name, node.getFullname()))
if node.parent is None:
raise Exception("Error, parent is null: " + node.name)
Debug(1, "*** Node Occures more then once!")
rating = newRating = 1
newCurPos = pos
origPos = pos
dom = None
curpos = None
maxOccurs = node.maxOccurs
minOccurs = node.minOccurs
name = node.name
goodLookAhead = None
hasCountRelation = False
isDeterministic = self._doesNodeHaveStatic(node) or self._doesNodeHaveConstraint(node)
origionalNode = node.copy(node.parent)
## Locate any count restrictions and update maxCount to match
Debug(1, "-- Looking for Count relation...")
relation = node.getRelationOfThisElement('count')
if relation is not None and relation.type == 'count' and node.parent is not None:
maxOccurs = int(relation.getValue(True))
Debug(1, "@@@ Found count relation [%d]" % maxOccurs)
hasCountRelation = True
## Check for count relation, verify > 0
if maxOccurs < 0:
Debug(1, "_handleArray: Found negative count relation: %d" % maxOccurs)
return 4, pos
elif maxOccurs == 0:
for child in node.getElementsByType(DataElement):
if child == node:
continue
# Remove relation (else we get errors)
for relation in child.getRelationsOfThisElement():
if node.getFullname().find(relation.parent.getFullname()) == 0:
# Relation inside of block we are removing
continue
Debug(1, "@! Child Relation: From: %s - of: %s" % (relation.parent.name, relation.of))
if relation in relation.parent.relations:
relation.parent.relations.remove(relation)
if relation.parent.has_key(relation.name):
del relation.parent[relation.name]
for rfrom in node.relations:
if rfrom.From is not None and rfrom.From.endswith(relation.parent.name):
Debug(1, "@ Also removing FROM side")
node.relations.remove(rfrom)
if node.parent.has_key(rfrom.name):
del node.parent[rfrom.name]
# Remove relation (else we get errors)
for relation in node.getRelationsOfThisElement():
Debug(1, "@ Found and removing relation: %s" % relation.getFullname())
if relation in relation.parent.relations:
Debug(1, "@ Removing type: %s, parent.name: %s" % (relation.type, relation.parent.name))
relation.parent.relations.remove(relation)
if relation.parent.has_key(relation.name):
Debug(1, "@ Also removeing from collection")
del relation.parent[relation.name]
for rfrom in node.relations:
if rfrom.From is not None and rfrom.From.endswith(relation.parent.name):
Debug(1, "@ Also removing FROM side")
node.relations.remove(rfrom)
if node.parent.has_key(rfrom.name):
del node.parent[rfrom.name]
# Remove element
del node.parent[node.name]
# We passed muster...I think :)
rating = 2
pos = origPos
Debug(1, "_handleArray(%s): Zero count on array, removed <<EXIT 1" % node.name)
return rating, pos
## Hack for fixed length arrays to remove lookAheads
if hasCountRelation == False and node.occurs is not None:
maxOccurs = node.occurs
hasCountRelation = True
## Handle maxOccurs > 1
try:
node.relationOf = None
Debug(1, "@@@ Entering while loop")
for occurs in range(maxOccurs):
Debug(1, "@@@ In While, newCurPos=%d" % (self.parentPos + newCurPos))
## Are we out at end of stream?
if buff.haveAllData and newCurPos >= len(buff.data):
Debug(1, "@ Exiting while loop, end of data! YAY!")
if occurs == 0:
Debug(1, "@ Exiting while on first loop")
if node.minOccurs > 0:
Debug(1, "@ minOccurs != 0, changing rating to 4")
rating = 4
else:
# This code is duplicated lower down.
# Remove node and increase rating.
Debug(1, "@ minOccurs == 0, removing node")
# Remove relation (else we get errors)
for relation in node.getRelationsOfThisElement():
Debug(1, "@ Found and removing relation...")
relation.parent.relations.remove(relation)
relation.parent.__delitem__(relation.name)
# Delete node from parent
del node.parent[node.name]
# Fix up our rating
rating = 2
curpos = pos
break
else:
Debug(1, "@ Have enough data to try again: %d < %d" % (newCurPos, len(buff.data)))
## Make a copy so we don't overwrite existing node
if occurs > 0:
nodeCopy = origionalNode.copy(node.parent)
nodeCopy.name = name + "-%d" % occurs
## Add to parent
node.parent.insert(node.parent.index(node) + occurs, nodeCopy)
else:
## If we are on the first element
nodeCopy = node
## Run onArrayNext
if DataCracker._tabLevel == 0 and nodeCopy.onArrayNext is not None:
evalEvent(node.onArrayNext, {'node': nodeCopy}, node)
## Check out look-ahead (unless we have count relation)
if (not isDeterministic) and (not hasCountRelation) and self._nextNode(nodeCopy) is not None:
Debug(1, "*** >> node.name: %s" % node.name)
Debug(1, "*** >> nodeCopy.name: %s" % nodeCopy.name)
Debug(1, "*** >> LookAhead")
newRating = self._lookAhead(nodeCopy, buff, newCurPos, None, False)
Debug(1, "*** << LookAhead [%d]" % newRating)
# If look ahead was good, save and check later.
if newRating < 3:
goodLookAhead = newRating
## Do actual
Debug(1, "*** >> nodeCopy.name: %s" % nodeCopy.name)
Debug(1, "*** >> DOING ACTUAL HANDLENODE")
origNewCurPos = newCurPos
(newRating, newCurPos) = self._handleNode(nodeCopy, buff, newCurPos, None, True)
if newCurPos < origNewCurPos:
raise Exception("WHoa! We shouldn't have moved back in position there... [%d:%d]" % origNewCurPos,
newCurPos)
## Handle minOccurs == 0
if occurs == 0 and newRating >= 3 and node.minOccurs == 0:
# This code is duplicated higher up
if hasCountRelation and maxOccurs > 0:
Debug(1, "Error: We think count == 0, relation says %d" % maxOccurs)
Debug(1, "Returning a rating of suck (4)")
return 4, pos
# Remove node and increase rating.
Debug(1, "Firt element rating was poor and minOccurs == 0, remoing element and upping rating.")
# Remove relation (else we get errors)
for relation in node.getRelationsOfThisElement():
relation.parent.relations.remove(relation)
del relation.parent[relation.name]
# Delete our copy
if nodeCopy.name != node.name:
del node.parent[nodeCopy.name]
# Delete orig
del node.parent[node.name]
rating = 2
curpos = pos = origPos
break
## Verify we didn't break a good lookahead
if not hasCountRelation and newRating < 3 and not self.lookAhead and goodLookAhead is not None:
lookAheadRating = self._lookAhead(nodeCopy, buff, newCurPos, None, False)
if lookAheadRating >= 3:
del node.parent[nodeCopy.name]
Debug(1, "*** Exiting min/max: We broke a good lookAhead!")
break
## Verify high enough rating
if newRating < 3 and not self.lookAhead:
Debug(1, "*** That worked out!")
pos = curpos = newCurPos
rating = newRating
# First time through convert position 0 node
if occurs == 0:
## First fix up our first node
index = node.parent.index(node)
del node.parent[node.name]
node.array = node.name
node.name += "-0"
node.arrayPosition = 0
node.arrayMinOccurs = node.minOccurs
node.arrayMaxOccurs = node.maxOccurs
node.minOccurs = 1
node.maxOccurs = 1
node.parent.insert(index, node)
# Update relation to have new name
if relation is not None and relation.of is not None:
# We need to support out count being outside
# a double loop, so lets check and see if
# our relation is closer to root than us
# and if so check the parents in between
relationParents = []
obj = relation.parent.parent
while obj is not None and obj.parent is not None:
if isinstance(obj, DataElement):
relationParents.append(obj)
obj = obj.parent
currentParents = []
obj = node.parent
while obj is not None and obj.parent is not None:
if isinstance(obj, DataElement):
currentParents.append(obj)
obj = obj.parent
boolInsideArray = False
if len(currentParents) > len(relationParents):
minParents = len(relationParents)
else:
minParents = len(currentParents)
# Make sure i gets initialized
# in some cases (minParents == 0) we never
# go through this next for loop and i is unknown.
i = minParents
for i in range(minParents):
if relationParents[i] != currentParents[i]:
#Debug(1, "_handleArray: Miss-match parents: %s, %s" % (relationParents[i].name, currentParents[i].name))
break
#Debug(1, "_handleArray: i == %d" % i)
for x in range(i, len(currentParents)):
if currentParents[x].maxOccurs > 1:
#Debug(1, "_handleArray: Outside array found: %s" % currentParents[x].name)
boolInsideArray = True
break
if boolInsideArray:
Debug(1, "_handleArray: Our count relation is outside of a double array.")
Debug(1, "_handleArray: Keeping a copy around for next iteration.")
newRel = relation.copy(relation.parent)
relation.parent.append(newRel)
relation.parent.relations.append(newRel)
else:
Debug(1, "_handleArray: No double array relation issue")
# Should we remove From?
for r in origionalNode.relations:
if r.From == relation.parent.name:
Debug(1, "_handleArray: Removing r.From origionalNode")
origionalNode.relations.remove(r)
try:
del origionalNode[r.name]
except:
pass
# Now update curretn realtion
relation.of = node.name
else:
# Next fix up our copied node
nodeCopy.array = node.array
nodeCopy.arrayPosition = occurs
nodeCopy.arrayMinOccurs = node.arrayMinOccurs
nodeCopy.arrayMaxOccurs = node.arrayMaxOccurs
nodeCopy.minOccurs = 1
nodeCopy.maxOccurs = 1
else:
Debug(1, "*** Didn't work out!")
del node.parent[nodeCopy.name]
break
occurs += 1
Debug(1, "@@@ Looping, occurs=%d, rating=%d" % (occurs, rating))
if occurs < minOccurs:
rating = 4
Debug(1, "@@@ Exiting While Loop")
except:
#pass
raise
### Do a quick dump of parent's children:
#print "------"
#for c in node.parent:
# if isinstance(c, DataElement):
# print c.name
#print "------"
if curpos is not None:
Debug(1, "@@@ Returning a rating=%d, curpos=%d, pos=%d, newCurPos=%d, occuurs=%d" % (
rating, self.parentPos + curpos, self.parentPos + pos, self.parentPos + newCurPos, occurs))
node.relationOf = None
return rating, curpos
Debug(1, "_handleArray(%s): type=%s, realpos=%d, pos=%d, rating=%d <<EXIT" % (
node.name, node.elementType, self.parentPos + pos, pos, rating))
node.relationOf = None
return rating, pos
def _handleNode(self, node, buff, pos, parent=None, doingMinMax=False):
Debug(1, "_handleNode(%s): %s pos(%d) >>Enter" % (highlight.info(node.name), node.elementType, pos))
## Sanity checking
if pos > len(buff.data):
Debug(1, "_handleNode: Running past data!, pos: %d, len.data: %d" % (pos, len(buff.data)))
return 4, pos
if node is None:
raise Exception("_handleNode: Node is None, bailing!")
## Save off origional position
origPos = pos
## check for when relation
if node.HasWhenRelation():
rel = node.GetWhenRelation()
environment = {
#'Peach' : self.engine.peach,
'self': node,
'pos': pos,
'data': buff.data
}
Debug(1, "_handleNode: When: Running expression")
node._fixRealParent(node)
if not evalEvent(rel.when, environment, node):
# Remove this node from data tree
#print "REMOVING:",node.name
# Locate relations and kill 'em off
for r in node.getRelationsOfThisElement():
# With --new we had some issues with
# double deleteing.
try:
r.parent.relations.remove(r)
del r.parent[r.name]
except:
pass
# Remove relations for all children as well
for child in node.getAllChildDataElements():
for r in child.getRelationsOfThisElement():
try:
r.parent.relations.remove(r)
del r.parent[r.name]
except:
pass
node._unFixRealParent(node)
del node.parent[node.name]
Debug(1, "_handleNode: When: Returned False. Removing and returning 1.")
node.relationOf = None
return 1, pos
node._unFixRealParent(node)
Debug(1, "_handleNode: When: Returned True.")
## Skipp around if we have an offset relations
popPosition = None
if isinstance(node, DataElement) and not (not doingMinMax and (node.minOccurs < 1 or node.maxOccurs > 1)):
relation = node.getRelationOfThisElement('offset')
if relation is not None and relation.type == 'offset':
# We need to move this show!
try:
Debug(1, "_handleNode: Found offset relation")
Debug(1, "_handleNode: Origional position saved as %d" % (self.parentPos + pos))
popPosition = pos
pos = int(relation.getValue(True))
Debug(1, "_handleNode: Changed position to %d" % (self.parentPos + pos))
except:
raise
else:
Debug(1, "_handleNode: Did not find offset relation")
## Would be nice to have our current pos in scripting :)
node.possiblePos = pos
## Do the crazy! (aka call specific crack handler)
# Array handling *MUST* always be first!
if not doingMinMax and (node.minOccurs < 1 or node.maxOccurs > 1):
if popPosition is not None:
raise PeachException("Error: Found an offset relation to an array, this is not allowed!")
(rating, pos) = self._handleArray(node, buff, pos, parent, doingMinMax)
elif node.elementType == 'string':
(rating, pos) = self._handleString(node, buff, pos, parent, doingMinMax)
# Do we have a transformer, if so decode the data
if node.transformer is not None:
try:
Debug(1, "_handleNode: String: Found transformer, decoding...")
node.defaultValue = node.transformer.transformer.decode(node.defaultValue)
except:
Debug(1, "_handleNode: String: Transformer threw exception!")
pass
elif node.elementType == 'number':
(rating, pos) = self._handleNumber(node, buff, pos, parent, doingMinMax)
elif node.elementType in ['block', 'template', 'choice']:
# First -- Determin if we know the size of this block via a
# size-of relation
length = None
relation = node.getRelationOfThisElement('size')
if relation is not None and relation.isOutputOnly:
relation = None
if relation is not None and node.parent is not None:
try:
length = relation.getValue(True)
Debug(1, "-----> FOUND BLOCK OF RELATION [%s] <-----" % repr(length))
fullName = relation.parent.getFullname()
Debug(1, "Size-of Fullname: " + fullName)
Debug(1, "node Fullname: " + node.getFullname())
#length = relation.getValue()
Debug(1, "Size-of Length: %s" % length)
# Verify we are not inside the "of" portion
if fullName.find(node.getFullname() + ".") == 0:
length = None
Debug(1, "!!! Not using relation, inside of OF element")
except:
length = None
elif node.hasLength():
length = node.getLength()
Debug(1, "-----> Block has known legnth: %d" % length)
# Only if we have a length, and we are not already the top
# level element. This will prevent infinit recursion into
# the data cracker if we have a <Block length="10" /> type
# situation.
if length is not None and node.parent is not None:
# Make sure we have the data
if len(buff.data) < (pos + length):
if not buff.haveAllData:
node.relationOf = None
try:
buff.read((pos + length) - len(buff.data))
#raise NeedMoreData(length, "")
except:
rating = 4
pos = pos + length
else:
rating = 4
pos = pos + length
if len(buff.data) >= (pos + length):
Debug(1, "---- About to Crack internal Block ----")
# Parse this node on it's own
cracker = DataCracker(self.peach, True)
cracker.haveAllData = True
cracker.parentPos = pos + self.parentPos
data = buff.data[pos:pos + length]
# Do we have a transformer, if so decode the data
if node.transformer is not None:
try:
Debug(1, "Found transformer, decoding...")
data = node.transformer.transformer.decode(data)
except:
Debug(1, "Transformer threw exception!")
pass
# We need to remove the parent temporarily to
# avoid a recursion issue.
parent = node.parent
node.parent = None
node.realParent = parent
# We need to remove any offset relation temporarily
# to avoid running it twice
offsetRelation = node.getRelationOfThisElement('offset')
if offsetRelation is not None:
offsetRelationParent = offsetRelation.parent
if offsetRelation in offsetRelationParent.relations:
offsetRelationParent.relations.remove(offsetRelation)
if offsetRelationParent.has_key(offsetRelation.name):
del offsetRelationParent[offsetRelation.name]
offsetFromRelation = None
for child in node.relations:
if child.type == 'offset':
offsetFromRelation = child
if offsetFromRelation in node.relations:
node.relations.remove(offsetFromRelation)
if node.has_key(offsetFromRelation.name):
del node[offsetFromRelation.name]
try:
newBuff = PublisherBuffer(None, data)
(rating, crackpos) = cracker.internalCrackData(node, newBuff, self.method)
if rating == 0:
rating = 1
finally:
# We need to update the positions of each child
# to be + node.pos.
#
# Note: We are doing this in a finally to make
# sure the values in peach validation are
# correct.
for c in node.getAllChildDataElements():
if hasattr(c, 'pos') and c.pos is not None:
c.pos += pos
# Add back our offset relation
if offsetRelation is not None:
offsetRelationParent.relations.append(offsetRelation)
if offsetFromRelation is not None:
node.relations.append(offsetFromRelation)
# Add back our parent
node.parent = parent
delattr(node, "realParent")
node.pos = pos
node.rating = rating
pos += length