3 from sfatables.globals import *
11 arguments = {'match':None,'target':None}
12 processors = {'match':None,'target':None}
13 context = {'match':None,'target':None}
15 def apply_processor(self, type, rspec, output_xpath_filter=None):
16 processor = self.processors[type]
19 filepath = 'processors/' + processor
22 styledoc = libxml2.parseFile(filepath)
23 style = libxslt.parseStylesheetDoc(styledoc)
24 doc = libxml2.parseDoc(rspec)
25 result = style.applyStylesheet(doc, None)
26 if (output_xpath_filter):
27 p = result.xpathNewContext()
28 xpath_result = p.xpathEval(output_xpath_filter)
29 if (xpath_result == []):
30 raise Exception("Could not apply processor %s."%processor)
32 stylesheet_result = xpath_result[0].content
35 stylesheet_result = style.saveResultToString(result)
36 style.freeStylesheet()
41 return stylesheet_result
43 def match(self, rspec):
46 match_result = self.apply_processor('match',rspec,"//result/@verdict")
47 return (match_result=='True')
49 def target(self, rspec):
50 target_result = self.apply_processor('target',rspec,None)
53 def apply_interpreted(self, rspec):
57 # if (match(match_args, rspec)
58 # then target(target_args, rspec)
61 if (self.match(rspec)):
62 return self.target(rspec)
67 def apply_compiled(rspec):
71 def load_xml_extension (self, type, chain, rule_number):
72 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
74 self.xmldoc = libxml2.parseFile(filename)
75 p = self.xmldoc.xpathNewContext()
77 context = p.xpathEval('//context/@select')
78 self.context[type] = context[0].content
80 processor = p.xpathEval('//processor/@filename')
82 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
86 self.processors[type] = processor[0].content
87 self.arguments[type] = p.xpathEval('//rule')
92 def wrap_rspec (self, type, rspec):
93 argument = self.arguments[type]
94 p = rspec.xmldoc.xpathNewContext()
95 root_node = p.xpathEval('/RSpec')
96 if (not root_node or not root_node):
97 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
99 root_node.addChild(arguments[type])
102 def __init__(self, chain, rule_number):
104 self.load_xml_extension('match', chain, rule_number)
105 self.load_xml_extension('target',chain, rule_number)
106 self.rule_number = rule_number
112 self.xmldoc.freeDoc()