1# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
2# See LICENSE.txt for complete terms.
3
4import sys
5
6from mixbox.binding_utils import *
7from . import cybox_common
8
9
10class PipeObjectType(cybox_common.ObjectPropertiesType):
11    """The PipeObjectType type is intended to characterize generic system
12    pipes.The named field specifies whether the pipe is named."""
13
14    subclass = None
15    superclass = cybox_common.ObjectPropertiesType
16    def __init__(self, object_reference=None, Custom_Properties=None, xsi_type=None, named=None, Name=None):
17        super(PipeObjectType, self).__init__(object_reference, Custom_Properties, xsi_type )
18        self.named = _cast(bool, named)
19        self.Name = Name
20    def factory(*args_, **kwargs_):
21        if PipeObjectType.subclass:
22            return PipeObjectType.subclass(*args_, **kwargs_)
23        else:
24            return PipeObjectType(*args_, **kwargs_)
25    factory = staticmethod(factory)
26    def get_Name(self): return self.Name
27    def set_Name(self, Name): self.Name = Name
28    def validate_StringObjectPropertyType(self, value):
29        # Validate type cybox_common.StringObjectPropertyType, a restriction on None.
30        pass
31    def get_named(self): return self.named
32    def set_named(self, named): self.named = named
33    def hasContent_(self):
34        if (
35            self.Name is not None or
36            super(PipeObjectType, self).hasContent_()
37            ):
38            return True
39        else:
40            return False
41    def export(self, lwrite, level, namespace_='PipeObj:', name_='PipeObjectType', namespacedef_='', pretty_print=True):
42        if pretty_print:
43            eol_ = '\n'
44        else:
45            eol_ = ''
46        showIndent(lwrite, level, pretty_print)
47        lwrite('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
48        already_processed = set()
49        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='PipeObjectType')
50        if self.hasContent_():
51            lwrite('>%s' % (eol_, ))
52            self.exportChildren(lwrite, level + 1, namespace_, name_, pretty_print=pretty_print)
53            showIndent(lwrite, level, pretty_print)
54            lwrite('</%s%s>%s' % (namespace_, name_, eol_))
55        else:
56            lwrite('/>%s' % (eol_, ))
57    def exportAttributes(self, lwrite, level, already_processed, namespace_='PipeObj:', name_='PipeObjectType'):
58        super(PipeObjectType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='PipeObjectType')
59        if self.named is not None:
60
61            lwrite(' named="%s"' % self.gds_format_boolean(self.named, input_name='named'))
62    def exportChildren(self, lwrite, level, namespace_='PipeObj:', name_='PipeObjectType', fromsubclass_=False, pretty_print=True):
63        super(PipeObjectType, self).exportChildren(lwrite, level, 'PipeObj:', name_, True, pretty_print=pretty_print)
64        if pretty_print:
65            eol_ = '\n'
66        else:
67            eol_ = ''
68        if self.Name is not None:
69            self.Name.export(lwrite, level, 'PipeObj:', name_='Name', pretty_print=pretty_print)
70    def build(self, node):
71        self.__sourcenode__ = node
72        already_processed = set()
73        self.buildAttributes(node, node.attrib, already_processed)
74        for child in node:
75            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
76            self.buildChildren(child, node, nodeName_)
77    def buildAttributes(self, node, attrs, already_processed):
78        value = find_attr_value_('named', node)
79        if value is not None:
80
81            if value in ('true', '1'):
82                self.named = True
83            elif value in ('false', '0'):
84                self.named = False
85            else:
86                raise_parse_error(node, 'Bad boolean attribute')
87        super(PipeObjectType, self).buildAttributes(node, attrs, already_processed)
88    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
89        if nodeName_ == 'Name':
90            obj_ = cybox_common.StringObjectPropertyType.factory()
91            obj_.build(child_)
92            self.set_Name(obj_)
93        super(PipeObjectType, self).buildChildren(child_, node, nodeName_, True)
94# end class PipeObjectType
95
96GDSClassesMapping = {
97    'Build_Utility': cybox_common.BuildUtilityType,
98    'Errors': cybox_common.ErrorsType,
99    'Time': cybox_common.TimeType,
100    'Certificate_Issuer': cybox_common.StringObjectPropertyType,
101    'Metadata': cybox_common.MetadataType,
102    'Hash': cybox_common.HashType,
103    'Information_Source_Type': cybox_common.ControlledVocabularyStringType,
104    'Block_Hash_Value': cybox_common.HashValueType,
105    'Fuzzy_Hash_Structure': cybox_common.FuzzyHashStructureType,
106    'SubDatum': cybox_common.MetadataType,
107    'Segment_Hash': cybox_common.HashValueType,
108    'Digital_Signature': cybox_common.DigitalSignatureInfoType,
109    'Code_Snippets': cybox_common.CodeSnippetsType,
110    'Value': cybox_common.StringObjectPropertyType,
111    'Length': cybox_common.IntegerObjectPropertyType,
112    'Encoding': cybox_common.ControlledVocabularyStringType,
113    'Internationalization_Settings': cybox_common.InternationalizationSettingsType,
114    'Tool_Configuration': cybox_common.ToolConfigurationType,
115    'English_Translation': cybox_common.StringObjectPropertyType,
116    'Functions': cybox_common.FunctionsType,
117    'String_Value': cybox_common.StringObjectPropertyType,
118    'Build_Utility_Platform_Specification': cybox_common.PlatformSpecificationType,
119    'Compiler_Informal_Description': cybox_common.CompilerInformalDescriptionType,
120    'System': cybox_common.ObjectPropertiesType,
121    'Platform': cybox_common.PlatformSpecificationType,
122    'Usage_Context_Assumptions': cybox_common.UsageContextAssumptionsType,
123    'Type': cybox_common.ControlledVocabularyStringType,
124    'Compilers': cybox_common.CompilersType,
125    'Tool_Type': cybox_common.ControlledVocabularyStringType,
126    'String': cybox_common.ExtractedStringType,
127    'Tool': cybox_common.ToolInformationType,
128    'Build_Information': cybox_common.BuildInformationType,
129    'Tool_Hashes': cybox_common.HashListType,
130    'Compiler_Platform_Specification': cybox_common.PlatformSpecificationType,
131    'Error_Instances': cybox_common.ErrorInstancesType,
132    'Data_Segment': cybox_common.StringObjectPropertyType,
133    'Certificate_Subject': cybox_common.StringObjectPropertyType,
134    'Language': cybox_common.StringObjectPropertyType,
135    'Identifier': cybox_common.PlatformIdentifierType,
136    'Strings': cybox_common.ExtractedStringsType,
137    'File_System_Offset': cybox_common.IntegerObjectPropertyType,
138    'Reference_Description': cybox_common.StructuredTextType,
139    'User_Account_Info': cybox_common.ObjectPropertiesType,
140    'Configuration_Settings': cybox_common.ConfigurationSettingsType,
141    'Simple_Hash_Value': cybox_common.SimpleHashValueType,
142    'Byte_String_Value': cybox_common.HexBinaryObjectPropertyType,
143    'Instance': cybox_common.ObjectPropertiesType,
144    'Import': cybox_common.StringObjectPropertyType,
145    'Property': cybox_common.PropertyType,
146    'Tool_Specific_Data': cybox_common.ToolSpecificDataType,
147    'Execution_Environment': cybox_common.ExecutionEnvironmentType,
148    'Dependencies': cybox_common.DependenciesType,
149    'Offset': cybox_common.IntegerObjectPropertyType,
150    'Date': cybox_common.DateRangeType,
151    'Hashes': cybox_common.HashListType,
152    'Segments': cybox_common.HashSegmentsType,
153    'Segment_Count': cybox_common.IntegerObjectPropertyType,
154    'Usage_Context_Assumption': cybox_common.StructuredTextType,
155    'Block_Hash': cybox_common.FuzzyHashBlockType,
156    'Dependency': cybox_common.DependencyType,
157    'Error': cybox_common.ErrorType,
158    'Trigger_Point': cybox_common.HexBinaryObjectPropertyType,
159    'Environment_Variable': cybox_common.EnvironmentVariableType,
160    'Byte_Run': cybox_common.ByteRunType,
161    'Contributors': cybox_common.PersonnelType,
162    'Image_Offset': cybox_common.IntegerObjectPropertyType,
163    'Imports': cybox_common.ImportsType,
164    'Library': cybox_common.LibraryType,
165    'References': cybox_common.ToolReferencesType,
166    'Internal_Strings': cybox_common.InternalStringsType,
167    'Custom_Properties': cybox_common.CustomPropertiesType,
168    'Configuration_Setting': cybox_common.ConfigurationSettingType,
169    'Libraries': cybox_common.LibrariesType,
170    'Function': cybox_common.StringObjectPropertyType,
171    'Description': cybox_common.StructuredTextType,
172    'Code_Snippet': cybox_common.ObjectPropertiesType,
173    'Build_Configuration': cybox_common.BuildConfigurationType,
174    'Address': cybox_common.HexBinaryObjectPropertyType,
175    'Search_Within': cybox_common.IntegerObjectPropertyType,
176    'Segment': cybox_common.HashSegmentType,
177    'Compiler': cybox_common.CompilerType,
178    'Name': cybox_common.StringObjectPropertyType,
179    'Signature_Description': cybox_common.StringObjectPropertyType,
180    'Block_Size': cybox_common.IntegerObjectPropertyType,
181    'Search_Distance': cybox_common.IntegerObjectPropertyType,
182    'Fuzzy_Hash_Value': cybox_common.FuzzyHashValueType,
183    'Dependency_Description': cybox_common.StructuredTextType,
184    'Contributor': cybox_common.ContributorType,
185    'Tools': cybox_common.ToolsInformationType,
186    'Data_Size': cybox_common.DataSizeType,
187}
188
189USAGE_TEXT = """
190Usage: python <Parser>.py [ -s ] <in_xml_file>
191"""
192
193def usage():
194    print(USAGE_TEXT)
195    sys.exit(1)
196
197def get_root_tag(node):
198    tag = Tag_pattern_.match(node.tag).groups()[-1]
199    rootClass = GDSClassesMapping.get(tag)
200    if rootClass is None:
201        rootClass = globals().get(tag)
202    return tag, rootClass
203
204def parse(inFileName):
205    doc = parsexml_(inFileName)
206    rootNode = doc.getroot()
207    rootTag, rootClass = get_root_tag(rootNode)
208    if rootClass is None:
209        rootTag = 'Pipe'
210        rootClass = PipeObjectType
211    rootObj = rootClass.factory()
212    rootObj.build(rootNode)
213    # Enable Python to collect the space used by the DOM.
214    doc = None
215#    sys.stdout.write('<?xml version="1.0" ?>\n')
216#    rootObj.export(sys.stdout.write, 0, name_=rootTag,
217#        namespacedef_='',
218#        pretty_print=True)
219    return rootObj
220
221def parseEtree(inFileName):
222    doc = parsexml_(inFileName)
223    rootNode = doc.getroot()
224    rootTag, rootClass = get_root_tag(rootNode)
225    if rootClass is None:
226        rootTag = 'Pipe'
227        rootClass = PipeObjectType
228    rootObj = rootClass.factory()
229    rootObj.build(rootNode)
230    # Enable Python to collect the space used by the DOM.
231    doc = None
232    rootElement = rootObj.to_etree(None, name_=rootTag)
233    content = etree_.tostring(rootElement, pretty_print=True,
234        xml_declaration=True, encoding="utf-8")
235    sys.stdout.write(content)
236    sys.stdout.write('\n')
237    return rootObj, rootElement
238
239def parseString(inString):
240    from mixbox.vendor.six import StringIO
241    doc = parsexml_(StringIO(inString))
242    rootNode = doc.getroot()
243    rootTag, rootClass = get_root_tag(rootNode)
244    if rootClass is None:
245        rootTag = 'Pipe'
246        rootClass = PipeObjectType
247    rootObj = rootClass.factory()
248    rootObj.build(rootNode)
249    # Enable Python to collect the space used by the DOM.
250    doc = None
251#    sys.stdout.write('<?xml version="1.0" ?>\n')
252#    rootObj.export(sys.stdout.write, 0, name_="Pipe",
253#        namespacedef_='')
254    return rootObj
255
256def main():
257    args = sys.argv[1:]
258    if len(args) == 1:
259        parse(args[0])
260    else:
261        usage()
262
263if __name__ == '__main__':
264    #import pdb; pdb.set_trace()
265    main()
266
267__all__ = [
268    "PipeObjectType"
269    ]
270