(no commit message)
[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 = 1
18
19         for (root, dirs, files) in os.walk(dir):
20             for file in files:
21                 if (file.startswith('sfatables-')):
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(self, command_options, match_options, target_options):
30         filename = match_dir + "/"+match_options.match_name+".xml"
31         xmldoc = libxml2.parseFile(filename)
32     
33         p = xmldoc.xpathNewContext()
34
35         supplied_arguments = match_options.arguments
36         for option in supplied_arguments:
37             option_name = option['name']
38             option_value = getattr(match_options,option_name)
39
40             if (hasattr(match_options,option_name)):
41                 context = p.xpathEval("//rule/argument[name='%s']"%option_name)
42                 import pdb
43                 pdb.set_trace()
44                 if (not context):
45                     raise Exception('Unknown option %s for match %s'%(option,option['name']))
46                 else:
47                     # Add the value of option
48                     valueNode = libxml2.newNode('value')
49                     valueNode.addContent(option_value)
50                     context[0].addChild(valueNode)
51
52         chain = command_options.args[0]
53         filename = self.getnextfilename('match',chain)
54         file_path = sfatables_config + '/' + chain + '/' + filename
55         xmldoc.saveFile(file_path)
56         p.xpathFreeContext()
57         xmldoc.freeDoc()
58
59         return True