-
Notifications
You must be signed in to change notification settings - Fork 34
/
Objects.py
executable file
·3465 lines (2915 loc) · 120 KB
/
Objects.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 software was developed at the National Institute of Standards
# and Technology in whole or in part by employees of the Federal
# Government in the course of their official duties. Pursuant to
# title 17 Section 105 of the United States Code portions of this
# software authored by NIST employees are not subject to copyright
# protection and are in the public domain. For portions not authored
# by NIST employees, NIST has been granted unlimited rights. NIST
# assumes no responsibility whatsoever for its use by other parties,
# and makes no guarantees, expressed or implied, about its quality,
# reliability, or any other characteristic.
#
# We would appreciate acknowledgement if the software is used.
"""
This file re-creates the major DFXML classes with an emphasis on type safety, serializability, and de-serializability.
With this module, reading disk images or DFXML files is done with the parse or iterparse functions. Writing DFXML files can be done with the DFXMLObject.print_dfxml function.
"""
__version__ = "0.7.2"
#Remaining roadmap to 1.0.0:
# * Documentation.
# * User testing.
# * Compatibility with the DFXML schema, version >1.1.1.
import logging
import re
import copy
import xml.etree.ElementTree as ET
import subprocess
import dfxml
import os
import sys
import struct
import platform
_logger = logging.getLogger(os.path.basename(__file__))
#Contains: (namespace, local name) qualified XML element name pairs
_warned_elements = set([])
_warned_byterun_attribs = set([])
#Contains: Unexpected 'facet' values on byte_runs elements.
_warned_byterun_facets = set([])
#Issue some log statements only once per program invocation.
_nagged_alloc = False
_warned_byterun_badtypecomp = False
_nagged_volume_error_impldrift = False
_nagged_volume_error_standin = False
XMLNS_REGXML = "http://www.forensicswiki.org/wiki/RegXML"
def _ET_tostring(e):
"""Between Python v2 and v3, there are some differences in the ElementTree library's tostring() behavior. One, the method balks at the "unicode" encoding in v2. Two, in 2, the XML prototypes output with every invocation. This method serves as a wrapper to deal with those issues, plus another issue where ET.tostring prints repeated xmlns declarations (observed on reading and writing a DFXML file twice in the same process). The repeated prints appear to be from a lack of inspection of existing namespace declarations in the attributes dictionary."""
retval = None
if sys.version_info[0] < 3:
tmp = ET.tostring(e, encoding="UTF-8")
if tmp[0:2] == "<?":
#Trim away first line; it's an XML prototype. This only appears in Python 2's ElementTree output.
retval = tmp[ tmp.find("?>\n")+3 : ]
else:
retval = tmp
else:
retval = ET.tostring(e, encoding="unicode")
container_end = retval.index(">")
for (uri, prefix) in list(ET._namespace_map.items()):
if prefix == "":
xmlns_attr_name = "xmlns"
else:
xmlns_attr_name = "xmlns:" + prefix
xmlns_attr_string = '%s="%s"' % (xmlns_attr_name, uri)
xmlns_attr_tally = retval.count(xmlns_attr_string, 0, container_end)
if xmlns_attr_tally > 1:
_logger.warning("ET.tostring() printed a repeated xmlns declaration: %r. Trimming %d repetition(s)." % (xmlns_attr_string, xmlns_attr_tally-1))
container_string = retval[ : container_end+1 ]
retval = container_string.replace(xmlns_attr_string, "", xmlns_attr_tally-1) + retval[ container_end+1 : ]
return retval
def _boolcast(val):
"""Takes Boolean values, and 0 or 1 in string or integer form, and casts them all to Boolean. Preserves nulls. Balks at everything else."""
if val is None:
return None
if val in [True, False]:
return val
_val = val
if val in ["0", "1"]:
_val = int(val)
if _val in [0, 1]:
return _val == 1
_logger.debug("val = " + repr(val))
raise ValueError("Received a not-straightforwardly-Boolean value. Expected some form of 0, 1, True, or False.")
def _bytecast(val):
"""Casts a value as a byte string. If a character string, assumes a UTF-8 encoding."""
if val is None:
return None
if isinstance(val, bytes):
return val
return _strcast(val).encode("utf-8")
def _intcast(val):
"""Casts input integer or string to integer. Preserves nulls. Balks at everything else."""
if val is None:
return None
if sys.version_info[0] < 3:
if isinstance(val, long):
return val
if isinstance(val, int):
return val
if isinstance(val, str):
if val[0] == "-":
if val[1:].isdigit():
return int(val)
else:
if val.isdigit():
return int(val)
_logger.debug("val = " + repr(val))
raise ValueError("Received a non-int-castable value. Expected an integer or an integer as a string.")
def _read_differential_annotations(annodict, element, annoset):
"""
Uses the shorthand-to-attribute mappings of annodict to translate attributes of element into annoset.
"""
#_logger.debug("annoset, before: %r." % annoset)
#Start with inverting the dictionary
_d = { annodict[k].replace("delta:",""):k for k in annodict }
#_logger.debug("Inverted dictionary: _d = %r" % _d)
for attr in element.attrib:
#_logger.debug("Looking for differential annotations: %r" % element.attrib)
(ns, an) = _qsplit(attr)
if an in _d and ns == dfxml.XMLNS_DELTA:
#_logger.debug("Found; adding %r." % _d[an])
annoset.add(_d[an])
#_logger.debug("annoset, after: %r." % annoset)
def _qsplit(tagname):
"""Requires string input. Returns namespace and local tag name as a pair. I could've sworn this was a basic implementation gimme, but ET.QName ain't it."""
_typecheck(tagname, str)
if tagname[0] == "{":
i = tagname.rfind("}")
return ( tagname[1:i], tagname[i+1:] )
else:
return (None, tagname)
def _strcast(val):
if val is None:
return None
return str(val)
def _typecheck(obj, classinfo):
if not isinstance(obj, classinfo):
_logger.info("obj = " + repr(obj))
if isinstance(classinfo, tuple):
raise TypeError("Expecting object to be one of the types %r." % (classinfo,))
else:
raise TypeError("Expecting object to be of type %r." % classinfo)
class DFXMLObject(object):
def __init__(self, *args, **kwargs):
self.command_line = kwargs.get("command_line")
self.program = kwargs.get("program")
self.program_version = kwargs.get("program_version")
self.version = kwargs.get("version")
self.sources = kwargs.get("sources", [])
self.dc = kwargs.get("dc", dict())
self.externals = kwargs.get("externals", OtherNSElementList())
self.diff_file_ignores = kwargs.get("diff_file_ignores", set())
self._namespaces = dict()
self._volumes = []
self._files = []
self._build_libraries = []
self._creator_libraries = []
input_volumes = kwargs.get("volumes") or []
input_files = kwargs.get("files") or []
for v in input_volumes:
self.append(v)
for f in input_files:
self.append(f)
#Add default namespaces
self.add_namespace("", dfxml.XMLNS_DFXML)
self.add_namespace("dc", dfxml.XMLNS_DC)
def __iter__(self):
"""Yields all VolumeObjects, recursively their FileObjects, and the FileObjects directly attached to this DFXMLObject, in that order."""
for v in self._volumes:
yield v
for f in v:
yield f
for f in self._files:
yield f
def _add_library(self, target_list, *args, **kwargs):
#_logger.debug("_add_library:args = %r." % (args,))
_library = None
if len(args) == 1 and isinstance(args[0], LibraryObject):
_library = args[0]
elif len(args) > 1 and isinstance(args[0], str) and isinstance(args[1], str):
_library = LibraryObject(args[0], args[1])
else:
raise ValueError("Unexpected arguments format (expecting (string, string) or a LibraryObject): %r." % (args,))
#_logger.debug("_library = %r." % _library)
if not _library is None:
target_list.append(_library)
def add_build_library(self, *args, **kwargs):
self._add_library(self.build_libraries, *args, **kwargs)
def add_creator_library(self, *args, **kwargs):
self._add_library(self.creator_libraries, *args, **kwargs)
def add_namespace(self, prefix, url):
"""In case of conflicting namespace definitions, first definition wins."""
#_logger.debug("self._namespaces.keys() = %r." % self._namespaces.keys())
if prefix not in self._namespaces.keys():
#_logger.debug("Registering namespace: %r, %r." % (prefix, url))
self._namespaces[prefix] = url
ET.register_namespace(prefix, url)
#_logger.debug("ET namespaces after registration: %r." % ET._namespace_map)
def append(self, value):
if isinstance(value, VolumeObject):
self._volumes.append(value)
elif isinstance(value, FileObject):
self._files.append(value)
else:
_logger.debug("value = %r" % value)
raise TypeError("Expecting a VolumeObject or a FileObject. Got instead this type: %r." % type(value))
def iter_namespaces(self):
"""Yields (prefix, url) pairs of each namespace registered in this DFXMLObject."""
for prefix in sorted(self._namespaces.keys()):
yield (prefix, self._namespaces[prefix])
def populate_from_Element(self, e):
if "version" in e.attrib:
self.version = e.attrib["version"]
for ce in e.findall(".//*"):
(cns, cln) = _qsplit(ce.tag)
if cln == "program":
self.program = ce.text
elif cln == "version":
self.program_version = ce.text
elif cln == "command_line":
self.command_line = ce.text
elif cln == "image_filename":
self.sources.append(ce.text)
elif cln in ("creator", "build_environment"):
for cce in ce.findall(".//*"):
if _qsplit(cce.tag)[1] != "library":
continue
lobj = LibraryObject()
lobj.populate_from_Element(cce)
if cln == "build_environment":
self.add_build_library(lobj)
elif cln == "creator":
self.add_creator_library(lobj)
elif (cns, cln) == (dfxml.XMLNS_DELTA, "file_ignore"):
self.diff_file_ignores.add(ce.text)
elif cns not in [dfxml.XMLNS_DFXML, ""]:
#Put all non-DFXML-namespace elements into the externals list.
self.externals.append(ce)
def print_dfxml(self, output_fh=sys.stdout):
"""Memory-efficient DFXML document printer. However, it assumes the whole element tree is already constructed."""
pe = self.to_partial_Element()
dfxml_wrapper = _ET_tostring(pe)
#_logger.debug("print_dfxml:dfxml_wrapper = %r." % dfxml_wrapper)
dfxml_foot = "</dfxml>"
#Check for an empty element
if dfxml_wrapper.strip()[-3:] == " />":
dfxml_head = dfxml_wrapper.strip()[:-3] + ">"
elif dfxml_wrapper.strip()[-2:] == "/>":
dfxml_head = dfxml_wrapper.strip()[:-2] + ">"
else:
dfxml_head = dfxml_wrapper.strip()[:-len(dfxml_foot)]
output_fh.write("""<?xml version="1.0"?>\n""")
output_fh.write(dfxml_head)
output_fh.write("\n")
_logger.debug("Writing %d volume objects." % len(self._volumes))
for v in self._volumes:
v.print_dfxml(output_fh)
output_fh.write("\n")
_logger.debug("Writing %d file objects." % len(self._files))
for f in self._files:
e = f.to_Element()
output_fh.write(_ET_tostring(e))
output_fh.write("\n")
output_fh.write(dfxml_foot)
output_fh.write("\n")
def to_Element(self):
outel = self.to_partial_Element()
for v in self._volumes:
tmpel = v.to_Element()
outel.append(tmpel)
for f in self._files:
tmpel = f.to_Element()
outel.append(tmpel)
return outel
def to_dfxml(self):
"""Serializes the entire DFXML document tree into a string. Then returns that string. RAM-intensive. Most will want to use print_dfxml() instead"""
return _ET_tostring(self.to_Element())
def to_partial_Element(self):
outel = ET.Element("dfxml")
_logger.debug("self.diff_file_ignores = %r." % self.diff_file_ignores)
for diff_file_ignore in sorted(self.diff_file_ignores):
self.add_namespace("delta", dfxml.XMLNS_DELTA)
tmpel0 = ET.Element("delta:file_ignore")
tmpel0.text = diff_file_ignore
outel.append(tmpel0)
for e in self.externals:
outel.append(e)
tmpel0 = ET.Element("metadata")
for key in sorted(self.dc):
_typecheck(key, str)
if ":" in key:
raise ValueError("Dublin Core key-value entries should have keys without the colon character. If this causes an interesting namespace issue for you, please report it as a bug.")
tmpel1 = ET.Element("dc:" + key)
tmpel1.text = self.dc[key]
tmpel0.append(tmpel1)
outel.append(tmpel0)
if self.command_line or \
self.program or \
self.program_version or \
0 < len(self.build_libraries) or \
0 < len(self.creator_libraries):
tmpel0 = ET.Element("creator")
if self.program:
tmpel1 = ET.Element("program")
tmpel1.text = self.program
tmpel0.append(tmpel1)
if self.program_version:
tmpel1 = ET.Element("version")
tmpel1.text = self.program_version
tmpel0.append(tmpel1)
if 0 < len(self.build_libraries):
tmpel1 = ET.Element("build_environment")
for library in self._build_libraries:
tmpel2 = library.to_Element()
tmpel1.append(tmpel2)
tmpel0.append(tmpel1)
if self.command_line:
tmpel1 = ET.Element("execution_environment")
tmpel2 = ET.Element("command_line")
tmpel2.text = self.command_line
tmpel1.append(tmpel2)
tmpel0.append(tmpel1)
for library in self.creator_libraries:
tmpel1 = library.to_Element()
tmpel0.append(tmpel1)
outel.append(tmpel0)
if len(self.sources) > 0:
tmpel0 = ET.Element("source")
for source in self.sources:
tmpel1 = ET.Element("image_filename")
tmpel1.text = source
tmpel0.append(tmpel1)
outel.append(tmpel0)
if self.version:
outel.attrib["version"] = self.version
#Apparently, namespace setting is only available with the write() function, which is memory-impractical for significant uses of DFXML.
#Ref: http://docs.python.org/3.3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write
for (prefix, url) in self.iter_namespaces():
if prefix == "":
attrib_name = "xmlns"
else:
attrib_name = "xmlns:" + prefix
outel.attrib[attrib_name] = url
#_logger.debug("ET namespaces at outel generation: %r." % ET._namespace_map)
#_logger.debug("outel.attrib = %r." % outel.attrib)
return outel
@property
def command_line(self):
return self._command_line
@command_line.setter
def command_line(self, value):
self._command_line = _strcast(value)
@property
def build_libraries(self):
return self._build_libraries
@property
def creator_libraries(self):
return self._creator_libraries
@property
def dc(self):
"""The Dublin Core dictionary of key-value pairs for this document. Typically, "type" is "Hash List", or "Disk Image". Keys should be strings not containing colons, values should be strings. If this causes an issue for you, please report it as a bug."""
return self._dc
@dc.setter
def dc(self, value):
_typecheck(value, dict)
self._dc = value
@property
def diff_file_ignores(self):
"""A set of DFXML file properties that are excluded from being flagged as differences. An example of when one may want to use this is when comparing two file system trees in the same file system: inodes are likely to be a differing factor, best excluded to inspect other changes."""
return self._diff_file_ignores
@diff_file_ignores.setter
def diff_file_ignores(self, value):
_typecheck(value, set)
self._diff_file_ignores = value
@property
def externals(self):
"""(This property behaves the same as FileObject.externals.)"""
return self._externals
@externals.setter
def externals(self, val):
_typecheck(val, OtherNSElementList)
self._externals = val
@property
def files(self):
"""List of file objects directly attached to this DFXMLObject. No setter for now."""
return self._files
@property
def namespaces(self):
raise AttributeError("The namespaces dictionary should not be directly accessed; instead, use .iter_namespaces().")
@property
def program(self):
"""This property becomes the element at dfxml/creator/program."""
return self._program
@program.setter
def program(self, value):
self._program = _strcast(value)
@property
def program_version(self):
"""This property becomes the element at dfxml/creator/version."""
return self._program_version
@program_version.setter
def program_version(self, value):
self._program_version = _strcast(value)
@property
def sources(self):
return self._sources
@sources.setter
def sources(self, value):
if not value is None:
_typecheck(value, list)
self._sources = value
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = _strcast(value)
@property
def volumes(self):
"""List of volume objects directly attached to this DFXMLObject. No setter for now."""
return self._volumes
class LibraryObject(object):
def __init__(self, *args, **kwargs):
self.name = None
self.version = None
if len(args) >= 1:
self.name = args[0]
if len(args) >= 2:
self.version = args[1]
def __eq__(self, other):
"""
This equality function tests the name and version values strictly. For less-strict testing, like allowing matching on missing versions, use relaxed_eq.
This function can compare against another LibraryObject.
"""
if not isinstance(other, LibraryObject):
return False
return self.name == other.name and \
self.version == other.version
def __repr__(self):
parts = []
if self.name:
parts.append("name=%r" % self.name)
if self.version:
parts.append("version=%r" % self.version)
return "LibraryObject(" + ", ".join(parts) + ")"
def populate_from_Element(self, e):
if "name" in e.attrib:
self.name = e.attrib["name"]
if "version" in e.attrib:
self.version = e.attrib["version"]
def relaxed_eq(self, other):
"""
This function can compare against another LibraryObject.
"""
if not isinstance(other, LibraryObject):
return False
if self.name != other.name:
return False
if self.version is None or other.version is None:
return True
return self.version == other.version
def to_Element(self):
outel = ET.Element("library")
if not self.name is None:
outel.attrib["name"] = self.name
if not self.version is None:
outel.attrib["version"] = self.version
return outel
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = _strcast(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = _strcast(value)
class RegXMLObject(object):
def __init__(self, *args, **kwargs):
self.command_line = kwargs.get("command_line")
self.interpreter = kwargs.get("interpreter")
self.metadata = kwargs.get("metadata")
self.program = kwargs.get("program")
self.program_version = kwargs.get("program_version")
self.sources = kwargs.get("sources", [])
self.version = kwargs.get("version")
self._hives = []
self._cells = []
self._namespaces = dict()
input_hives = kwargs.get("hives") or [] # In case kwargs["hives"] = None.
input_cells = kwargs.get("cells") or []
for hive in input_hives:
self.append(hive)
for cell in input_cells:
self.append(cells)
#Add default namespaces
#TODO This will cause a problem when the Objects bindings are used for a DFXML document and RegXML document in the same program.
self.add_namespace("", XMLNS_REGXML)
def __iter__(self):
"""Yields all HiveObjects, recursively their CellObjects, and the CellObjects directly attached to this RegXMLObject, in that order."""
for h in self._hives:
yield h
for c in h:
yield c
for c in self._cells:
yield c
def add_namespace(self, prefix, url):
self._namespaces[prefix] = url
ET.register_namespace(prefix, url)
def append(self, value):
if isinstance(value, HiveObject):
self._hives.append(value)
elif isinstance(value, CellObject):
self._cells.append(value)
else:
_logger.debug("value = %r" % value)
raise TypeError("Expecting a HiveObject or a CellObject. Got instead this type: %r." % type(value))
def print_regxml(self, output_fh=sys.stdout):
"""Serializes and prints the entire object, without constructing the whole tree."""
regxml_wrapper = _ET_tostring(self.to_partial_Element())
#_logger.debug("regxml_wrapper = %r." % regxml_wrapper)
regxml_foot = "</regxml>"
#Check for an empty element
if regxml_wrapper.strip()[-3:] == " />":
regxml_head = regxml_wrapper.strip()[:-3] + ">"
elif regxml_wrapper.strip()[-2:] == "/>":
regxml_head = regxml_wrapper.strip()[:-2] + ">"
else:
regxml_head = regxml_wrapper.strip()[:-len(regxml_foot)]
output_fh.write(regxml_head)
output_fh.write("\n")
for hive in self._hives:
hive.print_regxml(output_fh)
output_fh.write(regxml_foot)
output_fh.write("\n")
def to_Element(self):
outel = self.to_partial_Element()
for hive in self._hives:
tmpel = hive.to_Element()
outel.append(tmpel)
for cell in self._cells:
tmpel = cell.to_Element()
outel.append(tmpel)
return outel
def to_partial_Element(self):
"""
Creates the wrapping RegXML element. No hives, no cells. Saves on creating an entire Element tree in memory.
"""
outel = ET.Element("regxml")
if self.version:
outel.attrib["version"] = self.version
if self.program or self.program_version:
tmpel0 = ET.Element("creator")
if self.program:
tmpel1 = ET.Element("program")
tmpel1.text = self.program
tmpel0.append(tmpel1)
if self.program_version:
tmpel1 = ET.Element("version")
tmpel1.text = self.program_version
tmpel0.append(tmpel1)
outel.append(tmpel0)
if self.command_line:
tmpel0 = ET.Element("execution_environment")
if self.interpreter:
tmpel1 = ET.Element("interpreter")
tmpel1.text = self.interpreter
tmpel1 = ET.Element("command_line")
tmpel1.text = self.command_line
tmpel0.append(tmpel1)
#TODO Note libraries used at run-time
outel.append(tmpel0)
if len(self.sources) > 0:
tmpel0 = ET.Element("source")
for source in self.sources:
tmpel1 = ET.Element("image_filename")
tmpel1.text = source
tmpel0.append(tmpel1)
outel.append(tmpel0)
#Apparently, namespace setting is only available with the write() function, which is memory-impractical for significant uses of RegXML.
#Ref: http://docs.python.org/3.3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write
for prefix in sorted(self._namespaces.keys()):
if prefix == "":
attrib_name = "xmlns"
else:
attrib_name += "xmlns:" + prefix
outel.attrib[attrib_name] = self._namespaces[prefix]
return outel
def to_regxml(self):
"""Serializes the entire RegXML document tree into a string. Returns that string. RAM-intensive. Most will want to use print_regxml() instead."""
return _ET_tostring(self.to_Element())
class VolumeObject(object):
_all_properties = set([
"annos",
"allocated_only",
"block_count",
"block_size",
"byte_runs",
"error",
"externals",
"first_block",
"ftype",
"ftype_str",
"last_block",
"partition_offset",
"original_volume",
"sector_size"
])
_diff_attr_names = {
"new":"delta:new_volume",
"deleted":"delta:deleted_volume",
"modified":"delta:modified_volume",
"matched":"delta:matched"
}
#TODO There may be need in the future to compare the annotations as well. It complicates make_differential_dfxml too much for now.
_incomparable_properties = set([
"annos"
])
def __init__(self, *args, **kwargs):
self._files = []
self._annos = set()
self._diffs = set()
for prop in VolumeObject._all_properties:
if prop in ["annos", "files"]:
continue
elif prop == "externals":
setattr(self, prop, kwargs.get(prop, OtherNSElementList()))
else:
setattr(self, prop, kwargs.get(prop))
def __iter__(self):
"""Yields all FileObjects directly attached to this VolumeObject."""
for f in self._files:
yield f
def __repr__(self):
parts = []
for prop in VolumeObject._all_properties:
#Skip outputting the files list.
if prop == "files":
continue
val = getattr(self, prop)
if not val is None:
parts.append("%s=%r" % (prop, val))
return "VolumeObject(" + ", ".join(parts) + ")"
def append(self, value):
_typecheck(value, FileObject)
self._files.append(value)
def compare_to_original(self):
self._diffs = self.compare_to_other(self.original_volume, True)
def compare_to_other(self, other, ignore_original=False):
"""Returns a set of all the properties found to differ."""
_typecheck(other, VolumeObject)
diffs = set()
for prop in VolumeObject._all_properties:
if prop in VolumeObject._incomparable_properties:
continue
if ignore_original and prop == "original_volume":
continue
#_logger.debug("getattr(self, %r) = %r" % (prop, getattr(self, prop)))
#_logger.debug("getattr(other, %r) = %r" % (prop, getattr(other, prop)))
#Allow file system type to be case-insensitive
if prop == "ftype_str":
o = getattr(other, prop)
if o: o = o.lower()
s = getattr(self, prop)
if s: s = s.lower()
if s != o:
diffs.add(prop)
else:
if getattr(self, prop) != getattr(other, prop):
diffs.add(prop)
return diffs
def populate_from_Element(self, e):
global _warned_elements
_typecheck(e, (ET.Element, ET.ElementTree))
#_logger.debug("e = %r" % e)
#Read differential annotations
_read_differential_annotations(VolumeObject._diff_attr_names, e, self.annos)
#Split into namespace and tagname
(ns, tn) = _qsplit(e.tag)
assert tn in ["volume", "original_volume"]
#Look through direct-child elements to populate run array
for ce in e.findall("./*"):
#_logger.debug("ce = %r" % ce)
(cns, ctn) = _qsplit(ce.tag)
#_logger.debug("cns = %r" % cns)
#_logger.debug("ctn = %r" % ctn)
if ctn == "byte_runs":
self.byte_runs = ByteRuns()
self.byte_runs.populate_from_Element(ce)
elif ctn == "byte_run":
#byte_runs' block recursively handles this element.
continue
elif ctn == "original_volume":
self.original_volume = VolumeObject()
self.original_volume.populate_from_Element(ce)
elif ctn in VolumeObject._all_properties:
#_logger.debug("ce.text = %r" % ce.text)
setattr(self, ctn, ce.text)
#_logger.debug("getattr(self, %r) = %r" % (ctn, getattr(self, ctn)))
elif cns not in [dfxml.XMLNS_DFXML, ""]:
#Put all non-DFXML-namespace elements into the externals list.
self.externals.append(ce)
else:
if (cns, ctn) not in _warned_elements:
_warned_elements.add((cns, ctn))
_logger.warning("Unsure what to do with this element in a VolumeObject: %r" % ce)
def print_dfxml(self, output_fh=sys.stdout):
pe = self.to_partial_Element()
dfxml_wrapper = _ET_tostring(pe)
if len(pe) == 0 and len(self._files) == 0:
output_fh.write(dfxml_wrapper)
return
dfxml_foot = "</volume>"
#Deal with an empty element being printed as <elem/>
if len(pe) == 0:
replaced_dfxml_wrapper = dfxml_wrapper.replace(" />", ">")
dfxml_head = replaced_dfxml_wrapper
else:
dfxml_head = dfxml_wrapper.strip()[:-len(dfxml_foot)]
output_fh.write(dfxml_head)
output_fh.write("\n")
_logger.debug("Writing %d file objects for this volume." % len(self._files))
for f in self._files:
e = f.to_Element()
output_fh.write(_ET_tostring(e))
output_fh.write("\n")
output_fh.write(dfxml_foot)
output_fh.write("\n")
def to_Element(self):
outel = self.to_partial_Element()
#If there is an error reported on this volume, pop the element off of the partial element's end.
errorel = None
if not (self.error is None or self.error == ""):
if len(outel) == 0:
raise ValueError("Partial volume element has no children, but at least the error property was set.")
if _qsplit(outel[-1].tag)[1] == "error":
#(ET.Element does not have pop().)
errorel = outel[-1]
del(outel[-1])
else:
if outel.find("error"):
global _nagged_volume_error_impldrift
if not _nagged_volume_error_impldrift:
_logger.error("Implementation drift - when this code was initially written, the error element was the last to be appended to the partial element. Leaving the found error element in place for now, but this may fail validation against the schema because of child ordering.")
_nagged_volume_error_impldrift = True
else:
global _nagged_volume_error_standin
if not _nagged_volume_error_standin:
_logger.warning("Could not find 'error' child on partial volume element. Creating a replacement.")
_nagged_volume_error_standin = True
errorel = ET.Element("error")
errorel.text = str(self.error)
for f in self._files:
tmpel = f.to_Element()
outel.append(tmpel)
#The error element comes after the fileobject list in the schema.
if not errorel is None:
outel.append(errorel)
return outel
def to_partial_Element(self):
"""Returns the volume element with its properties, except for the child fileobjects. Properties are appended in DFXML schema order."""
outel = ET.Element("volume")
annos_whittle_set = copy.deepcopy(self.annos)
diffs_whittle_set = copy.deepcopy(self.diffs)
#Add differential annotations
for annodiff in VolumeObject._diff_attr_names:
if annodiff in annos_whittle_set:
outel.attrib[VolumeObject._diff_attr_names[annodiff]] = "1"
annos_whittle_set.remove(annodiff)
if len(annos_whittle_set) > 0:
_logger.warning("Failed to export some differential annotations: %r." % annos_whittle_set)
for e in self.externals:
outel.append(e)
if self.byte_runs:
outel.append(self.byte_runs.to_Element())
def _append_el(prop, value):
tmpel = ET.Element(prop)
_keep = False
if not value is None:
tmpel.text = str(value)
_keep = True
if prop in self.diffs:
tmpel.attrib["delta:changed_property"] = "1"
diffs_whittle_set.remove(prop)
_keep = True
if _keep:
outel.append(tmpel)
def _append_str(prop):
value = getattr(self, prop)
_append_el(prop, value)
def _append_bool(prop):
value = getattr(self, prop)
if not value is None:
value = "1" if value else "0"
_append_el(prop, value)
for prop in [
"partition_offset",
"sector_size",
"block_size",
"ftype",
"ftype_str",
"block_count",
"first_block",
"last_block"
]:
_append_str(prop)
#Output the one Boolean property
_append_bool("allocated_only")
#Output the original volume's properties
if not self.original_volume is None or "original_volume" in diffs_whittle_set:
#Skip FileObject list, if any
if self.original_volume is None:
tmpel = ET.Element("delta:original_volume")
else:
tmpel = self.original_volume.to_partial_Element()
tmpel.tag = "delta:original_volume"
if "original_volume" in diffs_whittle_set:
tmpel.attrib["delta:changed_property"] = "1"
outel.append(tmpel)
#Output the error property (which will be popped and re-appended after the file list in to_Element)
#The error should come last because of the two spots extended elements can be placed; this is to simplify the file-listing VolumeObject.to_Element() method.
_append_str("error")
if len(diffs_whittle_set) > 0:
_logger.warning("Did not annotate all of the differing properties of this volume. Remaining properties: %r." % diffs_whittle_set)
return outel
@property
def allocated_only(self):
return self._allocated_only
@allocated_only.setter
def allocated_only(self, val):
self._allocated_only = _boolcast(val)
@property
def annos(self):
"""Set of differential annotations. Expected members are the keys of this class's _diff_attr_names dictionary."""
return self._annos
@annos.setter
def annos(self, val):
_typecheck(val, set)
self._annos = val
@property
def block_count(self):
return self._block_count
@block_count.setter
def block_count(self, val):
self._block_count = _intcast(val)
@property
def block_size(self):