python3 - 2to3 + miscell obvious tweaks
[sfa.git] / sfatables / commands / Insert.py
1 import os, time
2 import libxml2
3 from sfatables.command import Command
4 from sfatables.globals import sfatables_config, target_dir, match_dir
5
6 class Insert(Command):
7     def __init__(self):
8         self.options = [('-I','--insert')]
9         self.help = 'Insert a rule into a chain'
10         self.matches = True
11         self.targets = True
12         return
13
14     def call_gen(self, chain, type, dir, options, file_path):
15         filename = os.path.join(dir, options.name+".xml")
16         xmldoc = libxml2.parseFile(filename)
17     
18         p = xmldoc.xpathNewContext()
19
20         supplied_arguments = options.arguments
21         if (hasattr(options,'element') and options.element):
22             element = options.element
23         else:
24             element='*'
25
26         for option in supplied_arguments:
27             option_name = option['name']
28             option_value = getattr(options,option_name)
29
30             if (hasattr(options,option_name) and getattr(options,option_name)):
31                 context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name))
32                 if (not context):
33                     raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element))
34                 else:
35                     # Add the value of option
36                     valueNode = libxml2.newNode('value')
37                     valueNode.addContent(option_value)
38                     context[0].addChild(valueNode)
39
40         if not os.path.isdir(os.path.dirname(file_path)):
41             os.makedirs(os.path.dirname(file_path))
42         xmldoc.saveFile(file_path)
43         p.xpathFreeContext()
44         xmldoc.freeDoc()
45
46         return True
47
48     def call(self, command_options, match_options, target_options):
49         if (len(command_options.args)<2):
50             print("Please specify the chain and the rule number to insert, e.g. sfatables -I INCOMING 1 -- ....")
51             return
52
53         chain = command_options.args[0]
54
55         rule_number = command_options.args[1]
56         chain_dir = sfatables_config + "/" + chain
57
58         match_path = chain_dir + "/" + "sfatables-%s-match"%rule_number
59         target_path = chain_dir + "/" + "sfatables-%s-target"%rule_number
60
61         ret = self.call_gen(chain, 'match',match_dir, match_options, match_path)
62         if (ret):
63             ret = self.call_gen(chain, 'target',target_dir, target_options, target_path)
64
65         return ret