3 from sfatables.globals import *
10 final_processor = '__sfatables_wrap_up__.xsl'
12 arguments = {'match':None,'target':None}
13 processors = {'match':None,'target':None}
14 context = {'match':None,'target':None}
16 def apply_processor(self, type, rspec, output_xpath_filter=None):
17 processor = self.processors[type]
20 filepath = 'processors/' + processor
23 styledoc = libxml2.parseFile(filepath)
24 style = libxslt.parseStylesheetDoc(styledoc)
25 doc = libxml2.parseDoc(rspec)
26 result = style.applyStylesheet(doc, None)
27 if (output_xpath_filter):
28 p = result.xpathNewContext()
29 xpath_result = p.xpathEval(output_xpath_filter)
30 if (xpath_result == []):
31 raise Exception("Could not apply processor %s."%processor)
33 stylesheet_result = xpath_result[0].content
36 stylesheet_result = style.saveResultToString(result)
38 style.freeStylesheet()
42 return stylesheet_result
44 def wrap_up(self, rspec):
45 filepath = 'processors/' + self.final_processor
47 styledoc = libxml2.parseFile(filepath)
48 style = libxslt.parseStylesheetDoc(styledoc)
49 doc = libxml2.parseDoc(rspec)
50 result = style.applyStylesheet(doc, None)
51 stylesheet_result = style.saveResultToString(result)
52 style.freeStylesheet()
56 return stylesheet_result
58 def match(self, rspec):
59 match_result = self.apply_processor('match',rspec,"//result/@verdict")
60 return (match_result=='True')
62 def target(self, rspec):
63 target_result = self.apply_processor('target',rspec,None)
66 def apply_interpreted(self, rspec):
70 # if (match(match_args, rspec)
71 # then target(target_args, rspec)
74 if (self.match(rspec)):
75 return self.target(rspec)
80 def apply_compiled(rspec):
84 def load_xml_extension (self, type, chain, rule_number):
85 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
87 self.xmldoc = libxml2.parseFile(filename)
88 p = self.xmldoc.xpathNewContext()
90 context = p.xpathEval('//context/@select')
91 self.context[type] = context[0].content
93 processor = p.xpathEval('//processor/@filename')
95 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
99 self.processors[type] = processor[0].content
100 self.arguments[type] = p.xpathEval('//rule')
105 def wrap_rspec (self, type, rspec):
106 argument = self.arguments[type]
107 p = rspec.xmldoc.xpathNewContext()
108 root_node = p.xpathEval('/RSpec')
109 if (not root_node or not root_node):
110 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
112 root_node.addChild(arguments[type])
115 def __init__(self, chain=None, rule_number=None):
116 if (chain and rule_number):
117 self.load_xml_extension('match', chain, rule_number)
118 self.load_xml_extension('target',chain, rule_number)
119 self.rule_number = rule_number
124 self.xmldoc.freeDoc()