root/branch/BTSniff/PacketManipulator/PM/Gui/Core/MainWindow.py @ 5395

Revision 5395, 29.0 kB (checked in by qsy, 4 years ago)

Old PM for testing BtSniffer?. Pre-renaming to namespace

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 the MainWindow class
23"""
24
25import gtk
26import os
27
28from PM import Backend
29from PM.Core.Logger import log
30from PM.Manager.PreferenceManager import Prefs
31from PM.Manager.AttackManager import AttackManager
32
33from PM.Gui.Widgets.StatusBar import StatusBar
34from PM.higwidgets.higdialogs import HIGAlertDialog
35
36__paned_imported = False
37
38if Prefs()['gui.docking'].value.lower() == 'moo':
39    try:
40        from MooPaned import *
41        __paned_imported = True
42    except ImportError:
43        log.info("moo library is not installed.")
44
45elif Prefs()['gui.docking'].value.lower() == 'gdl':
46    try:
47        from GdlPaned import *
48        __paned_imported = True
49    except ImportError:
50        log.info("GDL is not installed. Using fallback paned.")
51
52if Prefs()['gui.docking'].value.lower() == 'standard' or not __paned_imported:
53    from FallbackPaned import *
54    __paned_imported = True
55
56    log.info('Using fallback paned')
57
58from PM.Gui.Tabs.VteTab import VteTab
59from PM.Gui.Tabs.MainTab import MainTab
60from PM.Gui.Tabs.HackTab import HackTab
61from PM.Gui.Tabs.StatusTab import StatusTab
62from PM.Gui.Tabs.ConsoleTab import ConsoleTab
63from PM.Gui.Tabs.PropertyTab import PropertyTab
64from PM.Gui.Tabs.HostListTab import HostListTab
65from PM.Gui.Tabs.OperationsTab import FileOperation
66from PM.Gui.Tabs.ProtocolSelectorTab import ProtocolSelectorTab
67from PM.Gui.Tabs.OperationsTab import OperationsTab, SniffOperation, \
68     AttackOperation, BtSniffOperation
69
70from PM.Gui.Dialogs.Interface import InterfaceDialog
71from PM.Gui.Dialogs.BtInterface import BtInterfaceDialog
72from PM.Gui.Dialogs.Preferences import PreferenceDialog
73from PM.Gui.Dialogs.NewAttack import NewAttackDialog
74from PM.Gui.Dialogs.Routes import RoutesDialog
75from PM.Gui.Plugins.Window import PluginWindow
76
77from PM.Gui.Pages import PerspectiveType
78
79from PM.Gui.Sessions.Base import Session
80from PM.Gui.Sessions.AttackSession import AttackSession
81
82from PM.Gui.Sessions import SessionType
83
84from PM.Core.I18N import _
85from PM.Core.Const import PM_DEVELOPMENT, PM_SVN_REVISION
86from PM.Core.Const import PIXMAPS_DIR, PM_VERSION, PM_SITE
87
88class MainWindow(gtk.Window):
89    def __init__(self):
90        gtk.Window.__init__(self)
91
92        self.set_title("Packet Manipulator")
93        self.set_icon_from_file(os.path.join(PIXMAPS_DIR, 'pm-logo.png'))
94        self.set_default_size(600, 400)
95
96        self.registered_tabs = {}
97
98        # Binders for plugins
99        self.perspective_binder = []
100        self.session_binder = []
101
102        for i in PerspectiveType.types:
103            self.perspective_binder.append(list())
104
105        for i in SessionType.types:
106            self.session_binder.append(list())
107
108        self.perspective_binder = tuple(self.perspective_binder)
109        self.session_binder = tuple(self.session_binder)
110
111        self.__create_widgets()
112        self.__pack_widgets()
113        self.__connect_signals()
114
115        self.statusbar.push(_("Ready."), image=gtk.STOCK_YES)
116
117        self.show_all()
118
119    def __create_widgets(self):
120        "Create widgets"
121
122        self.main_actions = [
123            ('File', None, _('File'), None),
124
125            ('NewAttack', gtk.STOCK_NEW, _('New A_ttack'), '<Control>t',
126                _('Create a new attack'), self.__on_new_attack),
127
128            ('NewSequence', gtk.STOCK_NEW, _('_New sequence'), '<Control>n',
129                _('Create a new sequence'), self.__on_new_sequence),
130
131            ('Open', gtk.STOCK_OPEN, _('_Open'), '<Control>o',
132                _('Open session'), self.__on_open_session),
133
134            ('Save', gtk.STOCK_SAVE, _('_Save'), '<Control>s',
135                _('Save session'), self.__on_save_session),
136
137            ('SaveAs', gtk.STOCK_SAVE_AS, _('_Save as'), '<Control><Shift>s',
138                _('Save session as'), self.__on_save_session_as),
139
140            ('Quit', gtk.STOCK_QUIT, _('_Quit'), '<Control>q',
141                _('Quit from application'), self.__on_quit),
142
143            ('Capture', None, _('Capture'), None),
144
145            ('Interface', gtk.STOCK_CONNECT, _('_Interface'), '<Control>i',
146                _('Capture from interface'), self.__on_select_iface),
147               
148            ('Bluetooth', gtk.STOCK_CONNECT, _('Bluetooth'), None,
149            _('Capture from Bluetooth interface'), self.__on_select_btiface),
150
151            ('Attacks', None, _('Attacks'), None),
152
153            ('Options', None, _('Options'), None),
154
155            ('Routes', gtk.STOCK_NETWORK, _('Routing table'), '<Control>r',
156                _('Routes editor'), self.__on_routing),
157
158            ('Plugins', 'extension_small', _('Plugins'), None,
159                _('Plugin manager'), self.__on_plugins),
160
161            ('Preferences', gtk.STOCK_PREFERENCES, _('_Preferences'),
162                '<Control>p', _('Preferences'), self.__on_preferences),
163
164            ('Views', None, _('Views'), None),
165
166            ('Help', None, _('Help'), None),
167
168            ('About', gtk.STOCK_ABOUT, _('About'), None, None, self.__on_about),
169        ]
170
171        self.default_ui = """<menubar>
172            <menu action='File'>
173                <menuitem action='NewSequence'/>
174                <menuitem action='NewAttack'/>
175                <separator/>
176                <menuitem action='Open'/>
177                <menuitem action='Save'/>
178                <menuitem action='SaveAs'/>
179                <separator/>
180                <menuitem action='Quit'/>
181            </menu>
182            <menu action='Capture'>
183                <menuitem action='Interface'/>
184                <menuitem action='Bluetooth'/>
185            </menu>
186            <menu action='Attacks'/>
187            <menu action='Options'>
188                <menuitem action='Routes'/>
189                <separator/>
190                <menuitem action='Plugins'/>
191                <separator/>
192                <menuitem action='Preferences'/>
193            </menu>
194            <menu action='Views'/>
195            <menu action='Help'>
196                <menuitem action='About'/>
197            </menu>
198            </menubar>
199
200            <toolbar>
201                <toolitem action='Open'/>
202                <toolitem action='Save'/>
203                <toolitem action='Interface'/>
204                <separator/>
205                <toolitem action='Routes'/>
206                <toolitem action='Preferences'/>
207                <separator/>
208            </toolbar>
209            """
210
211        self.ui_manager = gtk.UIManager()
212
213        self.main_accel_group = gtk.AccelGroup()
214        self.main_action_group = gtk.ActionGroup('MainActionGroup')
215        self.main_action_group.add_actions(self.main_actions)
216
217        self.add_accel_group(self.main_accel_group)
218
219        for action in self.main_action_group.list_actions():
220            action.set_accel_group(self.main_accel_group)
221            action.connect_accelerator()
222
223        self.ui_manager.insert_action_group(self.main_action_group, 0)
224        self.ui_manager.add_ui_from_string(self.default_ui)
225
226        self.ui_manager.connect('connect-proxy', self.__on_connect_proxy)
227        self.ui_manager.connect('disconnect-proxy', self.__on_disconnect_proxy)
228
229        # Set unsensitive the attack menu
230        item = self.ui_manager.get_widget('/menubar/Attacks')
231        item.set_sensitive(False)
232
233        # Central widgets
234        self.main_paned = UmitPaned()
235
236        self.vbox = gtk.VBox(False, 2)
237        self.statusbar = StatusBar()
238
239        self.plugin_window = PluginWindow()
240
241    def register_attack_item(self, name, lbl, tooltip, stock, callback):
242        attackitem = self.ui_manager.get_widget('/menubar/Attacks')
243        menu = attackitem.get_submenu()
244
245        attackitem.show()
246
247        if not menu:
248            menu = gtk.Menu()
249            attackitem.set_submenu(menu)
250
251        act = gtk.Action(name, lbl, tooltip, stock)
252        act.connect('activate', callback)
253
254        item = act.create_menu_item()
255        item.show()
256
257        menu.append(item)
258
259        return act, item
260
261    def deregister_attack_item(self, item):
262        attackitem = self.ui_manager.get_widget('/menubar/Attacks')
263        menu = attackitem.get_submenu()
264
265        if not menu:
266            return
267
268        for citem in menu:
269            if citem is item:
270                citem.hide()
271                menu.remove(citem)
272
273                if not menu.get_children():
274                    attackitem.set_sensitive(False)
275
276                return True
277
278        return False
279
280    def get_tab(self, name):
281        """
282        Get a tab from its name
283
284        @param name the name of the tab
285        """
286
287        return self.registered_tabs[name]
288
289    def deregister_tab(self, tab):
290        """
291        Deregister a tab deleting his CheckMenu and tab from the paned
292
293        @param tab the tab to deregister
294        @return True if is ok or False
295        """
296
297        item = self.ui_manager.get_widget('/menubar/Views')
298        menu = item.get_submenu()
299
300        def find_tab(item, udata):
301            tab, find = udata
302
303            if item.get_data('tab-object') is tab:
304                find = item
305                return True
306
307        find = None
308        menu.foreach(find_tab, (tab, find))
309
310        if find is not None:
311            menu.remove(find)
312            self.main_paned.remove_view(tab)
313            del self.registered_tabs[tab.name]
314
315            return True
316
317        return False
318
319    def register_tab(self, tab, show=True):
320        """
321        Register a tab
322
323        @param tab the Tab object
324        @param show if the Tab should be showed
325        """
326
327        item = self.ui_manager.get_widget('/menubar/Views')
328        menu = item.get_submenu()
329
330        item.show()
331
332        if not menu:
333            menu = gtk.Menu()
334            item.set_submenu(menu)
335
336        if tab.name in self.registered_tabs:
337            raise Exception("Tab already present")
338
339        # Ok we should add a CheckMenuItem to this fucking menu
340        self.registered_tabs[tab.name] = tab
341
342        log.debug("Tab %s registered as %s" % (tab.label_text, tab.name))
343
344        if tab.tab_position is None:
345            # This is the central widget so it should be added
346            # with no MenuItem
347            self.main_paned.add_view(tab)
348            return
349
350        new_item = gtk.CheckMenuItem(tab.label_text)
351        new_item.set_data('tab-object', tab)
352        new_item.connect('toggled', self.__on_toggle_tab_menu, tab)
353
354        if show:
355            new_item.set_active(True)
356
357        new_item.show()
358        menu.append(new_item)
359
360    def create_session(self, menu, tup):
361        """
362        Create a new session using ctxklass and sessklass
363
364        @param menu gtk.MenuItem
365        @param tuple a tuple containing (sessklass, ctxklass)
366        """
367        sessklass, ctxklass = tup
368        maintab = self.get_tab("MainTab")
369        maintab.session_notebook.create_session(sessklass, ctxklass)
370
371    def register_session(self, sessklass, ctxklass=None):
372        """
373        Register a custom session class and returns the new id
374        of the SessionType
375
376        @param sessklass the custom session class
377        @param ctxklass the context class to use
378        @return id
379        """
380
381        log.debug('Registering a new session')
382
383        if sessklass.session_menu is not None:
384            log.debug('Creating new menu entry named %s for the session' % \
385                      sessklass.session_menu)
386
387            item = self.ui_manager.get_widget('/menubar/File')
388            menu = item.get_submenu()
389
390            item = gtk.MenuItem(sessklass.session_menu)
391            item.connect('activate', self.create_session, (sessklass, ctxklass))
392            item.show()
393
394            menu.insert(item, 2)
395
396            sessklass.session_menu_object = item
397
398        return SessionType.add_session(sessklass)
399
400    def deregister_session(self, sessklass):
401        if sessklass.session_menu_object:
402            menu = self.ui_manager.get_widget('/menubar/File').get_submenu()
403            sessklass.session_menu_object.hide()
404
405            menu.remove(sessklass.session_menu_object)
406
407        return SessionType.remove_session(sessklass)
408
409    def bind_session(self, ptype, persp_klass, show_pers=True, resize=False, \
410                     shrink=True):
411        """
412        Bind the perspective 'pers_klass' to Session 'ptype'
413
414        @param ptype the Session type to customize
415        @param persp_klass the perspective class to add to the selected Session
416        @param show_pers choose to show the perspective
417        @param resize if True child should resize when the paned is resized
418        @param shrink if True child can be made smaller than its minimum size
419                      request
420        """
421
422        log.debug(
423            "Binding perspective %s to Session %s" % \
424            (persp_klass, SessionType.types[ptype])
425        )
426
427        self.session_binder[ptype].append((persp_klass, show_pers, \
428                                           resize, shrink))
429
430        klass = SessionType.types[ptype]
431        maintab = self.get_tab("MainTab")
432
433        for page in maintab.session_notebook:
434            if isinstance(page, klass):
435                self.apply_bindings(page, ptype)
436
437    def unbind_session(self, type, persp_klass):
438        try:
439            for i in range(len(self.session_binder[ptype])):
440                (klass, show, resize, shrink) = self.session_binder[ptype][i]
441
442                if klass is not persp_klass:
443                    continue
444
445                del self.session_binder[type][i]
446
447                klass = SessionType.types[type]
448                maintab = self.get_tab("MainTab")
449
450                for page in maintab.session_notebook:
451                    if isinstance(page, klass):
452                        page.remove_perspective(klass)
453
454                log.debug(
455                    "Binding method %s for perspective of type %s removed" % \
456                    (persp_klass, SessionType.types[type])
457                )
458
459                return True
460        except:
461            log.error(
462                "Failed to remove binding method %s for session of type %s" % \
463                (persp_klass, SessionType.type[ptype])
464            )
465
466        return False
467
468    def apply_bindings(self, page, ptype):
469        for persp_klass, show, resize, shrink in self.session_binder[ptype]:
470            page.add_perspective(persp_klass, show, resize, shrink)
471
472    def bind_perspective(self, ptype, callback):
473        """
474        Bind the perspective 'type'
475
476        The callback should be of the type
477          def perspective_cb(perspective, type, already_present, added)
478
479        @param type the perspective's type (see also PerspectiveType)
480        @param callback the callback to execute when a new
481               perspective of type 'type' is created
482        """
483
484        log.debug(
485            "Binding method %s for perspective of type %s" % \
486            (callback, PerspectiveType.types[ptype])
487        )
488
489        self.perspective_binder[ptype].append(callback)
490
491        maintab = self.get_tab("MainTab")
492
493        for page in maintab.session_notebook:
494            if not isinstance(page, Session):
495                continue
496
497            for perspective in page.perspectives:
498                idx = PerspectiveType.types[type(perspective)]
499
500                callback(perspective, idx, True, True)
501
502    def debind_perspective(self, type, callback):
503        """
504        Remove the binding callback for perspective of type 'type'
505
506        @param type the perspective type
507        @param callback the callback to remove
508        @return True if the callback is removed correctly
509        """
510
511        try:
512            self.perspective_binder[type].remove(callback)
513
514            maintab = self.get_tab("MainTab")
515
516            for page in maintab.session_notebook:
517                if not isinstance(page, Session):
518                    continue
519
520                for perspective in page.perspectives:
521                    idx = PerspectiveType.types[type(perspective)]
522
523                    callback(perspective, idx, True, False)
524
525            log.debug(
526                "Binding method %s for perspective of type %s removed" % \
527                (callback, PerspectiveType.types[type])
528            )
529
530            return True
531        except:
532            log.error(
533                "Failed to remove binding method %s "
534                "for perspective of type %s" % \
535                (callback, PerspectiveType.types[type])
536            )
537
538        return False
539
540    def __pack_widgets(self):
541        "Pack widgets"
542
543        self.menubar = self.ui_manager.get_widget("/menubar")
544        self.vbox.pack_start(self.menubar, False, False, 0)
545
546        self.toolbar = self.ui_manager.get_widget("/toolbar")
547        self.toolbar.set_style(gtk.TOOLBAR_ICONS)
548
549        self.vbox.pack_start(self.toolbar, False, False, 0)
550
551        item = self.ui_manager.get_widget('/menubar/Views')
552        item.remove_submenu()
553
554        item = self.ui_manager.get_widget('/menubar/Attacks')
555        item.remove_submenu()
556
557        self.vbox.pack_start(self.main_paned)
558        self.vbox.pack_start(self.statusbar, False, False)
559
560        # Tabs
561        self.register_tab(MainTab())
562
563        self.register_tab(ProtocolSelectorTab(),
564                          Prefs()['gui.views.protocol_selector_tab'].value)
565        self.register_tab(PropertyTab(),
566                          Prefs()['gui.views.property_tab'].value)
567        self.register_tab(StatusTab(),
568                          Prefs()['gui.views.status_tab'].value)
569        self.register_tab(OperationsTab(),
570                          Prefs()['gui.views.operations_tab'].value)
571        self.register_tab(VteTab(),
572                          Prefs()['gui.views.vte_tab'].value)
573        self.register_tab(HackTab(),
574                          Prefs()['gui.views.hack_tab'].value)
575        self.register_tab(ConsoleTab(),
576                          Prefs()['gui.views.console_tab'].value)
577        self.register_tab(HostListTab(),
578                          Prefs()['gui.views.hostlist_tab'].value)
579
580        self.add(self.vbox)
581
582    def __on_menuitem_selected(self, menuitem, tooltip):
583        self.statusbar.push(tooltip)
584
585    def __on_menuitem_deselected(self, menuitem):
586        self.statusbar.pop()
587
588    def __on_connect_proxy(self, uimgr, action, widget):
589        tooltip = action.get_property('tooltip')
590
591        if isinstance(widget, gtk.MenuItem) and tooltip:
592            cid = widget.connect('select', self.__on_menuitem_selected, tooltip)
593            cid2 = widget.connect('deselect', self.__on_menuitem_deselected)
594            widget.set_data('pm::cids', (cid, cid2))
595
596    def __on_disconnect_proxy(self, uimgr, action, widget):
597        cids = widget.get_data('pm::cids')
598
599        if not isinstance(cids, tuple):
600            return
601
602        try:
603            for name, cid in cids:
604                widget.disconnect(cid)
605        except:
606            pass
607
608    def __connect_signals(self):
609        "Connect signals"
610        self.connect('delete-event', self.__on_quit)
611
612        # Ok we need also to connect signals from main notebook
613        # so we could manage easilly the bind_perspective calls
614
615        maintab = self.get_tab("MainTab")
616        maintab.session_notebook.connect('page-added',
617                                         self.__on_maintab_page_added)
618        maintab.session_notebook.connect('page-removed',
619                                         self.__on_maintab_page_removed)
620        maintab.session_notebook.connect('switch-page',
621                                         self.__on_maintab_page_switched)
622
623    def connect_tabs_signals(self):
624        "Used to connect signals between tabs"
625
626        for key, tab in self.registered_tabs.items():
627            tab.connect_tab_signals()
628
629    def __on_maintab_page_added(self, notebook, page, pagenum):
630        if not isinstance(page, Session):
631            return
632
633        for perspective in page.perspectives:
634            try:
635                idx = PerspectiveType.types[type(perspective)]
636
637                for callback in self.perspective_binder[idx]:
638                    callback(perspective, idx, False, True)
639            except:
640                pass
641
642    def __on_maintab_page_removed(self, notebook, page, pagenum):
643        if not isinstance(page, Session):
644            return
645
646        for perspective in page.perspectives:
647            try:
648                idx = PerspectiveType.types[type(perspective)]
649
650                for callback in self.perspective_binder[idx]:
651                    callback(perspective, idx, True, False)
652            except:
653                pass
654
655    def __on_maintab_page_switched(self, notebook, page, pagenum):
656        page = notebook.get_nth_page(pagenum)
657        item = self.ui_manager.get_widget('/menubar/Attacks')
658
659        if not isinstance(page, AttackSession):
660            item.set_sensitive(False)
661        else:
662            submenu = item.get_submenu()
663
664            if submenu and submenu.get_children():
665                item.set_sensitive(True)
666
667    def __on_toggle_tab_menu(self, menuitem, tab):
668        if menuitem.get_active():
669            self.main_paned.add_view(tab)
670        else:
671            self.main_paned.remove_view(tab)
672
673    def __on_routing(self, action):
674        dialog = RoutesDialog(self)
675
676        if dialog.run() == gtk.RESPONSE_ACCEPT:
677            dialog.save()
678
679        dialog.hide()
680        dialog.destroy()
681
682    def __on_plugins(self, action):
683        self.plugin_window.show()
684
685    def __on_preferences(self, action):
686        dialog = PreferenceDialog(self)
687        dialog.show()
688
689    def __on_about(self, action):
690        dialog = gtk.AboutDialog()
691
692        dialog.set_logo(
693            gtk.gdk.pixbuf_new_from_file(os.path.join(PIXMAPS_DIR,
694                                                      'pm-logo.png'))
695        )
696        dialog.set_name("PacketManipulator")
697        dialog.set_version(PM_VERSION)
698
699        dialog.set_website(PM_SITE)
700        dialog.set_website_label(PM_SITE)
701
702        dialog.set_comments(_("Packet manipulation made easy%s" \
703                              "\n«Audaces fortuna adiuvat»") % \
704                            ((PM_DEVELOPMENT) and \
705                                (' (SVN revision %s)' % PM_SVN_REVISION) or \
706                                ('')))
707
708        dialog.set_authors(['Francesco Piccinno <stack.box@gmail.com>'])
709
710        dialog.set_copyright('\n'.join(
711            ('Copyright (C) 2008 Francesco Piccinno' \
712                     ' <stack.box at gmail dot com>',
713             'Copyright (C) 2008 Adriano Monteiro Marques' \
714                          ' <py.adriano at gmail dot com>')))
715
716        dialog.set_license(_('This program is relased '
717                             'under the terms of GPLv2'))
718
719        dialog.run()
720        dialog.hide()
721        dialog.destroy()
722
723    def __on_select_iface(self, action):
724        dialog = InterfaceDialog(self)
725
726        if dialog.run() == gtk.RESPONSE_ACCEPT:
727            iface = dialog.get_selected()
728            args = dialog.get_options()
729
730            if iface or args['capmethod'] == 1:
731                tab = self.get_tab('OperationsTab')
732                tab.tree.append_operation(SniffOperation(iface, **args))
733
734        dialog.hide()
735        dialog.destroy()
736   
737    def __on_select_btiface(self, action):
738        log.debug('On_select_btiface')
739        dialog = BtInterfaceDialog(self)
740
741        if dialog.run() == gtk.RESPONSE_ACCEPT:
742           
743           
744            iface = dialog.get_selected()
745            args = dialog.get_options()
746           
747            if iface:
748                log.debug('MainWindow: BtSniff: %s selected' % iface)
749                tab = self.get_tab('OperationsTab')
750                tab.tree.append_operation(BtSniffOperation(iface, **args))
751       
752        dialog.hide()
753        dialog.destroy()
754
755    def start_new_attack(self, dev1, dev2, bpf_filter):
756        log.debug('Creating a new AttackOperation using %s %s %s' \
757                  % (dev1, dev2, bpf_filter))
758
759        tab = self.get_tab('OperationsTab')
760        tab.tree.append_operation(AttackOperation(dev1, dev2, bpf_filter))
761
762    def __on_new_attack(self, action):
763        dialog = NewAttackDialog(self)
764
765        if dialog.run() == gtk.RESPONSE_ACCEPT:
766            inputs = dialog.get_inputs()
767            self.start_new_attack(*inputs)
768
769        dialog.hide()
770        dialog.destroy()
771
772    def __on_new_sequence(self, action):
773        tab = self.get_tab('MainTab')
774        tab.session_notebook.create_sequence_session([])
775
776    def __on_open_session(self, action):
777        types = {}
778        sessions = (Backend.StaticContext,
779                    Backend.SequenceContext,
780                    Backend.SniffContext)
781
782        for ctx in sessions:
783            for name, pattern in ctx.file_types:
784                types[pattern] = (name, ctx)
785
786        dialog = gtk.FileChooserDialog(_("Select a session"), self,
787                               buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
788                                        gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
789
790        filterall = gtk.FileFilter()
791        filterall.set_name(_('All supported files'))
792        [filterall.add_pattern(k) for k in types]
793        dialog.add_filter(filterall)
794
795        for pattern, (name, ctx) in types.items():
796            filter = gtk.FileFilter()
797            filter.set_name(name)
798            filter.add_pattern(pattern)
799            dialog.add_filter(filter)
800
801        if dialog.run() == gtk.RESPONSE_ACCEPT:
802            ctx = None
803            fname = dialog.get_filename()
804
805            try:
806                find = fname.split('.')[-1]
807
808                for pattern in types:
809                    if pattern.split('.')[-1] == find:
810                        ctx = types[pattern][1]
811            except:
812                pass
813
814            if ctx is not Backend.SequenceContext and \
815               ctx is not Backend.SniffContext and \
816               ctx is not Backend.StaticContext:
817
818                d = HIGAlertDialog(type=gtk.MESSAGE_ERROR,
819                    message_format=_("Unable to open selected session"),
820                    secondary_text=_("PacketManipulator is unable to guess the "
821                                     "file type. Try to modify the extension "
822                                     "and to reopen the file."))
823                d.run()
824                d.destroy()
825            else:
826                self.open_generic_file_async(fname)
827
828        dialog.hide()
829        dialog.destroy()
830
831    def open_generic_file_async(self, fname):
832        """
833        Open a generic file (pcap/sequence and other supported file format)
834        @param fname the path to the file to open
835        """
836        tab = self.get_tab("OperationsTab")
837        tab.tree.append_operation(FileOperation(fname, FileOperation.TYPE_LOAD))
838
839    def open_generic_file(self, fname):
840        """
841        Open a generic file (pcap/sequence and other supported file format)
842        @param fname the path to the file to open
843        @return a PM.Session.Base.Session object or None on errors
844        """
845
846        if not os.path.isfile(fname):
847            return None
848
849        types = {}
850        sessions = (Backend.StaticContext,
851                    Backend.SequenceContext,
852                    Backend.SniffContext)
853
854        for ctx in sessions:
855            for name, pattern in ctx.file_types:
856                types[pattern] = (name, ctx)
857
858        try:
859            find = fname.split('.')[-1]
860
861            for pattern in types:
862                if pattern.split('.')[-1] == find:
863                    ctx = types[pattern][1]
864        except:
865            pass
866
867        tab = self.get_tab("MainTab")
868
869        if ctx is Backend.SequenceContext:
870            return tab.session_notebook.load_sequence_session(fname)
871
872        elif ctx is Backend.SniffContext:
873            return tab.session_notebook.load_sniff_session(fname)
874
875        elif ctx is Backend.StaticContext:
876            return tab.session_notebook.load_static_session(fname)
877
878    def __on_save_session(self, action):
879        maintab = self.get_tab("MainTab")
880        session = maintab.get_current_session()
881
882        if session:
883            session.save()
884
885    def __on_save_session_as(self, action):
886        maintab = self.get_tab("MainTab")
887        session = maintab.get_current_session()
888
889        if session:
890            session.save_as()
891
892    def __on_quit(self, *args):
893        self.hide()
894
895        # We need to stop the pending sniff threads
896        maintab = self.get_tab("MainTab")
897
898        lst = []
899
900        for page in maintab.session_notebook:
901            if isinstance(page, Session) and \
902               isinstance(page.context, Backend.TimedContext):
903                lst.append(page.context)
904
905        for ctx in lst:
906            ctx.stop()
907
908        # Avoids joining all threads are daemon
909        #for ctx in lst:
910        #    ctx.join()
911
912        log.debug('Saving options before exiting')
913        Prefs().write_options()
914
915        log.debug('Saving attack configurations')
916        AttackManager().write_configurations()
917
918        gtk.main_quit()
Note: See TracBrowser for help on using the browser.