root/branch/PacketManipulator/PM/Manager/PreferenceManager.py @ 3585

Revision 3585, 6.5 kB (checked in by nopper, 5 years ago)

Backend changes:
- Implementing a SequenceObject? and a SequencePacket? object
- Adding a get_proto_field function to the Scapy backend and get_protocols,

haslayer and getlayer in packet (MetaPacket?)

- Adding a BaseSequenceContext? and implementing the real code in Scapy

Needs fixing

GUI changes:
- Adding a sequence page that permits to the user to construct a conditional

stack of packets. Packets are evaluated in depth order so if we have a packet
B wich is child of A, then B is sent only if there are replies for packet A.

- Also implement a merging feature to sequence page that permits to set common

fields to multiple packets in one click.

- Adding Sequence Operation to the OperationsTab?
- Updating the PreferenceManager? and Dialog accordingly to respect changes.
- Splitting SessionPage? into a base class called Session and added a

SequencePage?, also implementing sane functions like reload_container and
reload_editor.

- Moving send/receive controls and operations from PacketPage? to SequencePage?,

now packet page is only for editing

- Moving the sniff renderer to widgets and renamed to GridRenderer? to use also

in sequence window

Indipendent:
- Some print replace with log.debug

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (C) 2008 Adriano Monteiro Marques
4#
5# Author: Francesco Piccinno <stack.box@gmail.com>
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21"""
22This module contains various class to load and store preferences to
23XML file using SAX parser provided by python
24"""
25
26import sys
27import os.path
28
29from xml.sax import handler, make_parser
30from xml.sax.saxutils import XMLGenerator
31from xml.sax.xmlreader import AttributesNSImpl
32
33from PM.Core.Logger import log
34from PM.Core.Const import PM_HOME
35from PM.Core.Atoms import Singleton
36
37TYPES = {
38    str        : 'str',
39    bool       : 'bool',
40    dict       : 'dict',
41    float      : 'float',
42    int        : 'int',
43    list       : 'list',
44    tuple      : 'tuple'
45}
46
47class Option(object):
48    def __init__(self, value, default=None):
49        self.type = 'str'
50        self.converter = str
51        self.cbs = []
52
53        for k, v in TYPES.items():
54            if isinstance(value, k):
55                self.type = v
56                self.converter = k
57                break
58
59        self._value = self.converter(value)
60
61    def connect(self, callback, call=True):
62        self.cbs.append(callback)
63
64        if call:
65            callback(self.value)
66
67    def disconnect(self, callback):
68        if callback in self.cbs:
69            self.cbs.remove(callback)
70
71    def get_value(self):
72        assert isinstance(self._value, self.converter)
73        return self._value
74
75    def set_value(self, val):
76        # Check type?
77        if not isinstance(val, self.converter):
78            val = self.converter(val)
79
80        for cb in self.cbs:
81            # Lock if a callback returns True
82            if cb(val):
83                log.debug("Ignoring change")
84                return
85
86        log.debug("%s = %s" % (self, val))
87        self._value = val
88
89    def __repr__(self):
90        return "(%s)" % self._value
91
92    value = property(get_value, set_value)
93
94class PreferenceLoader(handler.ContentHandler):
95    def __init__(self, outfile):
96        self.outfile = outfile
97        self.options = {}
98
99    def startElement(self, name, attrs):
100        if name in ('bool', 'int', 'float', \
101                    'str', 'list', 'tuple'):
102
103            opt_name = None
104            opt_value = None
105
106            for attr in attrs.keys():
107                if attr == 'id':
108                    opt_name = attrs.get(attr)
109                if attr == 'value':
110                    opt_value = attrs.get(attr)
111           
112            try:
113                if name == 'bool':
114                    if opt_value.lower() == 'true' or opt_value == '1':
115                        opt_value = True
116                    else:
117                        opt_value = False
118                elif name == 'int':
119                    opt_value = int(opt_value)
120                elif name == 'float':
121                    opt_value = float(opt_value)
122                elif name == 'list':
123                    opt_value = opt_value.split(",")
124                    opt_value = filter(None, opt_value)
125                elif name == 'tuple':
126                    opt_value = opt_value.split(",")
127                    opt_value = filter(None, opt_value)
128                    opt_value = tuple(opt_value)
129            except:
130                return
131
132            if opt_name != None and opt_value != None:
133                self.options[opt_name] = Option(opt_value)
134
135class PreferenceWriter:
136    def __init__(self, fname, options):
137        output = open(fname, 'w')
138        self.writer = XMLGenerator(output, 'utf-8')
139        self.writer.startDocument()
140        self.writer.startElementNS((None, 'PacketManipulator'), 'PacketManipulator', {})
141
142        for key, option in options.items():
143
144            attr_vals = {
145                (None, u'id') : key,
146                (None, u'value') : str(option.value)
147            }
148
149            attr_qnames = {
150                (None, u'id') : u'id',
151                (None, u'value') : u'value'
152            }
153
154            attrs = AttributesNSImpl(attr_vals, attr_qnames)
155            self.writer.startElementNS((None, str(option.type)), str(option.type), attrs)
156            self.writer.endElementNS((None, str(option.type)), str(option.type))
157
158        self.writer.endElementNS((None, 'PacketManipulator'), 'PacketManipulator')
159        self.writer.endDocument()
160        output.close()
161
162class Prefs(Singleton):
163    options = {
164        'gui.docking' : True,
165        'gui.maintab.sniffview.font' : 'Monospace 10',
166        'gui.maintab.sniffview.usecolors' : True,
167        'gui.maintab.hexview.font' : 'Monospace 10',
168        'gui.maintab.hexview.bpl' : 16,
169        'gui.maintab.sequenceview.font' : 'Monospace 10',
170        'gui.maintab.sequenceview.usecolors' : True,
171
172        'gui.statustab.font' : 'Monospace 10',
173       
174        'gui.views.protocol_selector_tab' : True,
175        'gui.views.property_tab' : True,
176        'gui.views.status_tab' : True,
177        'gui.views.operations_tab' : True,
178        'gui.views.vte_tab' : False,
179        'gui.views.hack_tab' : False,
180        'gui.views.console_tab' : False,
181
182        'backend.system' : 'scapy',
183        'backend.scapy.interface' : ''
184    }
185
186    def __init__(self):
187        self.fname = os.path.join(PM_HOME, 'pm-prefs.xml')
188       
189        try:
190            opts = self.load_options()
191            self.options.update(self.load_options())
192        except Exception:
193            pass
194
195        diff_dict = {}
196        for name, opt in self.options.items():
197            if not isinstance(opt, Option):
198                diff_dict[name] = Option(opt)
199
200        self.options.update(diff_dict)
201
202    def load_options(self):
203        handler = PreferenceLoader(sys.stdout)
204        parser = make_parser()
205        parser.setContentHandler(handler)
206        parser.parse(self.fname)
207
208        return handler.options
209
210    def write_options(self):
211        writer = PreferenceWriter(self.fname, self.options)
212
213    def __getitem__(self, x):
214        return self.options[x]
Note: See TracBrowser for help on using the browser.