3 from sfatables.command import Command
4 from sfatables.globals import *
7 options = [('-A','--add')]
8 help = 'Add a rule to a chain'
15 def getnextfilename(self,type,chain):
16 dir = sfatables_config + "/"+chain;
19 for (root, dirs, files) in os.walk(dir):
21 if (file.startswith('sfatables-') and file.endswith(type)):
22 number_str = file.split('-')[1]
23 number = int(number_str)
24 if (number>last_rule_number):
25 last_rule_number = number
27 return "sfatables-%d-%s"%(last_rule_number+1,type)
29 def call_gen(self, chain, type, dir, options):
30 filename = os.path.join(dir, options.name+".xml")
31 xmldoc = libxml2.parseFile(filename)
33 p = xmldoc.xpathNewContext()
35 supplied_arguments = options.arguments
36 if (hasattr(options,'element') and options.element):
37 element = options.element
41 for option in supplied_arguments:
42 option_name = option['name']
43 option_value = getattr(options,option_name)
45 if (hasattr(options,option_name)):
46 context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name))
48 raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element))
50 # Add the value of option
51 valueNode = libxml2.newNode('value')
52 valueNode.addContent(option_value)
53 context[0].addChild(valueNode)
55 filename = self.getnextfilename(type,chain)
56 file_path = os.path.join(sfatables_config, chain, filename)
57 if not os.path.isdir(os.path.dirname(file_path)):
58 os.makedirs(os.path.dirname(file_path))
59 xmldoc.saveFile(file_path)
65 def call(self, command_options, match_options, target_options):
66 chain = command_options.args[0]
67 ret = self.call_gen(chain, 'match',match_dir, match_options)
69 ret = self.call_gen(chain, 'target',target_dir, target_options)