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, doc, output_xpath_filter=None):
17 processor = self.processors[type]
20 filepath = os.path.join(sfatables_config, 'processors', processor)
23 styledoc = libxml2.parseFile(filepath)
24 style = libxslt.parseStylesheetDoc(styledoc)
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
35 stylesheet_result = result #style.saveResultToString(result)
37 style.freeStylesheet()
41 return stylesheet_result
43 def wrap_up(self, doc):
44 filepath = os.path.join(sfatables_config, 'processors', self.final_processor)
46 if not os.path.exists(filepath):
47 # TODO: final_processor is not there yet
50 styledoc = libxml2.parseFile(filepath)
51 style = libxslt.parseStylesheetDoc(styledoc)
52 #doc = libxml2.parseDoc(rspec)
53 result = style.applyStylesheet(doc, None)
54 stylesheet_result = result #style.saveResultToString(result)
55 style.freeStylesheet()
59 return stylesheet_result
61 def match(self, rspec):
62 match_result = self.apply_processor('match',rspec,"//result/@verdict")
63 return (match_result[0].content=='True')
65 def target(self, rspec):
66 target_result = self.apply_processor('target',rspec,None)
69 def apply_interpreted(self, rspec):
73 # if (match(match_args, rspec)
74 # then target(target_args, rspec)
77 if (self.match(rspec)):
78 return self.target(rspec)
83 def apply_compiled(rspec):
87 def load_xml_extension (self, type, chain, rule_number):
88 filename = sfatables_config+"/"+chain+"/"+"sfatables-%d-%s"%(rule_number,type)
90 self.xmldoc = libxml2.parseFile(filename)
91 p = self.xmldoc.xpathNewContext()
93 context = p.xpathEval('//context/@select')
94 self.context[type] = context[0].content
96 processor = p.xpathEval('//processor/@filename')
98 context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
102 self.processors[type] = processor[0].content
103 self.arguments[type] = p.xpathEval('//rule')
108 def wrap_rspec (self, type, rspec):
109 argument = self.arguments[type]
110 p = rspec.xmldoc.xpathNewContext()
111 root_node = p.xpathEval('/RSpec')
112 if (not root_node or not root_node):
113 raise Exception('An evil aggregate manager sent me a malformed RSpec. Please see the stack trace to identify it.')
115 root_node.addChild(arguments[type])
118 def __init__(self, chain=None, rule_number=None):
119 if (chain and rule_number):
120 self.load_xml_extension('match', chain, rule_number)
121 self.load_xml_extension('target',chain, rule_number)
122 self.rule_number = rule_number
127 self.xmldoc.freeDoc()