3 from sfatables.globals import *
7 def apply_processor(self, type, doc, output_xpath_filter=None):
8 processor = self.processors[type]
11 filepath = os.path.join(sfatables_config, 'processors', processor)
14 styledoc = libxml2.parseFile(filepath)
15 style = libxslt.parseStylesheetDoc(styledoc)
16 result = style.applyStylesheet(doc, None)
17 if (output_xpath_filter):
18 p = result.xpathNewContext()
19 xpath_result = p.xpathEval(output_xpath_filter)
20 if (xpath_result == []):
21 raise Exception("Could not apply processor %s."%processor)
23 stylesheet_result = xpath_result
26 stylesheet_result = result #style.saveResultToString(result)
28 style.freeStylesheet()
32 return stylesheet_result
34 def wrap_up(self, doc):
35 filepath = os.path.join(sfatables_config, 'processors', self.final_processor)
37 if not os.path.exists(filepath):
38 # TODO: final_processor is not there yet
41 styledoc = libxml2.parseFile(filepath)
42 style = libxslt.parseStylesheetDoc(styledoc)
43 #doc = libxml2.parseDoc(rspec)
44 result = style.applyStylesheet(doc, None)
45 stylesheet_result = result #style.saveResultToString(result)
46 style.freeStylesheet()
50 return stylesheet_result
52 def match(self, rspec):
53 match_result = self.apply_processor('match',rspec,"//result/@verdict")
54 return (match_result[0].content=='True')
56 def target(self, rspec):
57 target_result = self.apply_processor('target',rspec,None)
60 def apply_interpreted(self, rspec):
64 # if (match(match_args, rspec)
65 # then target(target_args, rspec)
68 if (self.match(rspec)):
69 return self.target(rspec)
74 def apply_compiled(rspec):
78 def load_xml_extension (self, type, chain, rule_number):
79 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
81 self.xmldoc = libxml2.parseFile(filename)
82 p = self.xmldoc.xpathNewContext()
84 context = p.xpathEval('//context/@select')
85 self.context[type] = context[0].content
87 processor = p.xpathEval('//processor/@filename')
89 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
93 self.processors[type] = processor[0].content
94 self.arguments[type] = p.xpathEval('//rule')
99 def wrap_rspec (self, type, rspec):
100 argument = self.arguments[type]
101 p = rspec.xmldoc.xpathNewContext()
102 root_node = p.xpathEval('/RSpec')
103 if (not root_node or not root_node):
104 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
106 root_node.addChild(arguments[type])
109 def __init__(self, chain=None, rule_number=None):
110 self.rule_number = None
114 self.final_processor = '__sfatables_wrap_up__.xsl'
116 self.arguments = {'match':None,'target':None}
117 self.processors = {'match':None,'target':None}
118 self.context = {'match':None,'target':None}
120 if (chain and rule_number):
121 self.load_xml_extension('match', chain, rule_number)
122 self.load_xml_extension('target',chain, rule_number)
123 self.rule_number = rule_number
128 self.xmldoc.freeDoc()