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 = style.saveResultToString(result)
46 style.freeStylesheet()
52 return stylesheet_result
54 def match(self, rspec):
55 match_result = self.apply_processor('match',rspec,"//result/@verdict")
56 return (match_result[0].content=='True')
58 def target(self, rspec):
59 target_result = self.apply_processor('target',rspec,None)
62 def apply_interpreted(self, rspec):
66 # if (match(match_args, rspec)
67 # then target(target_args, rspec)
70 if (self.match(rspec)):
71 return self.target(rspec)
76 def apply_compiled(rspec):
80 def load_xml_extension (self, type, chain, rule_number):
81 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
83 self.xmldoc = libxml2.parseFile(filename)
84 p = self.xmldoc.xpathNewContext()
86 context = p.xpathEval('//context/@select')
87 self.context[type] = context[0].content
89 processor = p.xpathEval('//processor/@filename')
91 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
95 self.processors[type] = processor[0].content
96 self.arguments[type] = p.xpathEval('//rule')
101 def wrap_rspec (self, type, rspec):
102 argument = self.arguments[type]
103 p = rspec.xmldoc.xpathNewContext()
104 root_node = p.xpathEval('/RSpec')
105 if (not root_node or not root_node):
106 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
108 root_node.addChild(arguments[type])
111 def __init__(self, chain=None, rule_number=None):
112 self.rule_number = None
116 self.final_processor = '__sfatables_wrap_up__.xsl'
118 self.arguments = {'match':None,'target':None}
119 self.processors = {'match':None,'target':None}
120 self.context = {'match':None,'target':None}
122 if (chain and rule_number):
123 self.load_xml_extension('match', chain, rule_number)
124 self.load_xml_extension('target',chain, rule_number)
125 self.rule_number = rule_number
130 self.xmldoc.freeDoc()