da02e869258646c75e1cdd2fac8ca19a15dffe47
[sfa.git] / sfatables / commands / Add.py
1 import os, time
2 import libxml2
3 from sfatables.command import Command
4 from sfatables.globals import *
5
6 class Add(Command):
7     options = [('-A','--add')]
8     help = 'Add a rule to a chain'
9     matches = True
10     targets = True
11
12     def __init__(self):
13         return
14
15     def getnextfilename(self,type,chain):
16         dir = sfatables_config + "/"+chain;
17         last_rule_number = 0
18
19         for (root, dirs, files) in os.walk(dir):
20             for file in files:
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
26
27         return "sfatables-%d-%s"%(last_rule_number+1,type)
28
29     def call_gen(self, chain, type, dir, options):
30         filename = os.path.join(dir, options.name+".xml")
31         xmldoc = libxml2.parseFile(filename)
32     
33         p = xmldoc.xpathNewContext()
34
35         supplied_arguments = options.arguments
36         if (hasattr(options,'element') and options.element):
37             element = options.element
38         else:
39             element='*'
40
41         for option in supplied_arguments:
42             option_name = option['name']
43             option_value = getattr(options,option_name)
44
45             if (hasattr(options,option_name)):
46                 context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name))
47                 if (not context):
48                     raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element))
49                 else:
50                     # Add the value of option
51                     valueNode = libxml2.newNode('value')
52                     valueNode.addContent(option_value)
53                     context[0].addChild(valueNode)
54
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)
60         p.xpathFreeContext()
61         xmldoc.freeDoc()
62
63         return True
64
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)
68         if (ret):
69             ret = self.call_gen(chain, 'target',target_dir, target_options)
70
71         return ret