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)
37 style.freeStylesheet()
41 return stylesheet_result
43 def wrap_up(self, rspec):
44 filepath = 'processors/' + self.final_processor
46 styledoc = libxml2.parseFile(filepath)
47 style = libxslt.parseStylesheetDoc(styledoc)
48 doc = libxml2.parseDoc(rspec)
49 result = style.applyStylesheet(doc, None)
50 stylesheet_result = style.saveResultToString(result)
51 style.freeStylesheet()
55 return stylesheet_result
57 def match(self, rspec):
58 match_result = self.apply_processor('match',rspec,"//result/@verdict")
59 return (match_result=='True')
61 def target(self, rspec):
62 target_result = self.apply_processor('target',rspec,None)
65 def apply_interpreted(self, rspec):
69 # if (match(match_args, rspec)
70 # then target(target_args, rspec)
73 if (self.match(rspec)):
74 return self.target(rspec)
79 def apply_compiled(rspec):
83 def load_xml_extension (self, type, chain, rule_number):
84 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
86 self.xmldoc = libxml2.parseFile(filename)
87 p = self.xmldoc.xpathNewContext()
89 context = p.xpathEval('//context/@select')
90 self.context[type] = context[0].content
92 processor = p.xpathEval('//processor/@filename')
94 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
98 self.processors[type] = processor[0].content
99 self.arguments[type] = p.xpathEval('//rule')
104 def wrap_rspec (self, type, rspec):
105 argument = self.arguments[type]
106 p = rspec.xmldoc.xpathNewContext()
107 root_node = p.xpathEval('/RSpec')
108 if (not root_node or not root_node):
109 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
111 root_node.addChild(arguments[type])
114 def __init__(self, chain=None, rule_number=None):
115 if (chain and rule_number):
116 self.load_xml_extension('match', chain, rule_number)
117 self.load_xml_extension('target',chain, rule_number)
118 self.rule_number = rule_number
123 self.xmldoc.freeDoc()