#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2005 Insecure.Com LLC.
#
# Author: Adriano Monteiro Marques <py.adriano@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

import gobject
import gtk
import pango
import os
import os.path
import xml.sax

from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog, HIGDialog
from zenmapGUI.higwidgets.higboxes import HIGVBox, HIGHBox, hig_box_space_holder
from zenmapGUI.higwidgets.higlabels import HIGSectionLabel
from zenmapGUI.higwidgets.higtables import HIGTable
from zenmapGUI.higwidgets.higbuttons import HIGButton

from zenmapCore.NmapParser import NmapParser
from zenmapCore.UmitLogging import log
import zenmapCore.I18N
import zenmapCore.Diff

from zenmapGUI.FileChoosers import ResultsFileSingleChooserDialog

# In milliseconds.
NDIFF_CHECK_TIMEOUT = 200

PORT_STATE_CHANGE_CONSOLIDATION_THRESHOLD = 10

class ScanChooser(HIGVBox):
    """This class allows the selection of scan results from the list of open
    tabs or from a file. It emits the "changed" signal when the scan selection
    has changed."""

    __gsignals__ = {
        "changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
    }

    def __init__(self, scan_dict, title):
        self.__gobject_init__()
        self.title = title
        self.scan_dict = scan_dict
        
        # Setting HIGVBox
        self.set_border_width(5)
        self.set_spacing(6)
        
        self._create_widgets()
        self._pack_hbox()
        self._attaching_widgets()
        self._set_scrolled()
        self._set_text_view()
        self._set_open_button()
        
        for scan in scan_dict:
            self.list_scan.append([scan])
        
        self.combo_scan.connect('changed', self.show_scan)
        self.combo_scan.connect('changed', lambda x: self.emit('changed'))
        
        self._pack_noexpand_nofill(self.lbl_scan)
        self._pack_expand_fill(self.hbox)
    
    def _create_widgets(self):
        self.lbl_scan = HIGSectionLabel(self.title)
        self.hbox = HIGHBox()
        self.table = HIGTable()
        self.list_scan = gtk.ListStore(str)
        self.combo_scan = gtk.ComboBoxEntry(self.list_scan, 0)
        self.btn_open_scan = gtk.Button(stock=gtk.STOCK_OPEN)
        self.exp_scan = gtk.Expander(_("Scan Output"))
        self.scrolled = gtk.ScrolledWindow()
        self.txt_scan_result = gtk.TextView()
        self.txg_tag = gtk.TextTag("scan_style")

    def get_buffer(self):
        return self.txt_scan_result.get_buffer()
    
    def show_scan (self, widget):
        nmap_output = self.get_nmap_output()
        if nmap_output is not None:
            self.txt_scan_result.get_buffer().set_text(nmap_output)

    def normalize_output(self, output):
        return "\n".join(output.split("\\n"))

    def _pack_hbox (self):
        self.hbox._pack_noexpand_nofill(hig_box_space_holder())
        self.hbox._pack_expand_fill(self.table)

    def _attaching_widgets (self):
        self.table.attach(self.combo_scan, 0,1,0,1, yoptions=0)
        self.table.attach(self.btn_open_scan, 1,2,0,1, yoptions=0, xoptions=0)
        self.table.attach(self.exp_scan, 0,2,1,2)
    
    def _set_scrolled(self):
        self.scrolled.set_border_width(5)
        self.scrolled.set_size_request(-1, 130)
        
        # Packing scrolled window into expander
        self.exp_scan.add(self.scrolled)
        
        # Packing text view into scrolled window
        self.scrolled.add_with_viewport(self.txt_scan_result)
        
        # Setting scrolled window
        self.scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
    
    def _set_text_view (self):
        self.txg_table = self.txt_scan_result.get_buffer().get_tag_table()
        self.txg_table.add(self.txg_tag)
        self.txg_tag.set_property("family", "Monospace")
        
        self.txt_scan_result.set_wrap_mode(gtk.WRAP_WORD)
        self.txt_scan_result.set_editable(False)
        self.txt_scan_result.get_buffer().connect("changed", self._text_changed_cb)

    def _set_open_button (self):
        self.btn_open_scan.connect('clicked', self.open_file)
    
    def open_file (self, widget):
        file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result"))
        
        response = file_chooser.run()
        file_chosen = file_chooser.get_filename()
        file_chooser.destroy()
        if response == gtk.RESPONSE_OK:
            try:
                parser = NmapParser()
                parser.parse_file(file_chosen)
            except xml.sax.SAXParseException, e:
                alert = HIGAlertDialog(
                    message_format='<b>%s</b>' % _('Error parsing file'),
                    secondary_text=_("The file is not an Nmap XML output file. \
The parsing error that occurred was\n%s") % str(e))
                alert.run()
                alert.destroy()
                return False
            except Exception, e:
                alert = HIGAlertDialog(
                        message_format='<b>%s</b>' % _('Cannot open selected file'),
                        secondary_text=_("This error occurred while trying to open the file:\n%s") % str(e))
                alert.run()
                alert.destroy()
                return False

            scan_name = os.path.split(file_chosen)[-1]
            self.add_scan(scan_name, parser)
            
            self.combo_scan.set_active(len(self.list_scan) - 1)

    def add_scan(self, scan_name, parser):
        scan_id = 1
        new_scan_name = scan_name
        while new_scan_name in self.scan_dict.keys():
            new_scan_name = "%s (%s)" % (scan_name, scan_id)
            scan_id += 1
                
        self.list_scan.append([new_scan_name])
        self.scan_dict[new_scan_name] = parser
    
    def _text_changed_cb (self, widget):
        buff = self.txt_scan_result.get_buffer ()
        buff.apply_tag(self.txg_tag, buff.get_start_iter(), buff.get_end_iter())

    def get_parsed_scan(self):
        """Return the currently selected scan's parsed output as an NmapParser
        object, or None if no valid scan is selected."""
        selected_scan = self.combo_scan.child.get_text()
        if selected_scan in self.scan_dict:
            return self.scan_dict[selected_scan]
        # What's typed in the entry doesn't match a registered scan.
        return None

    def get_nmap_output(self):
        """Return the currently selected scan's output as a string, or None if
        no valid scan is selected."""
        parsed = self.parsed_scan
        if parsed is not None:
            return parsed.nmap_output
        return None

    nmap_output = property(get_nmap_output)
    parsed_scan = property(get_parsed_scan)


class DiffWindow(gtk.Window):
    def __init__(self, scans):
        """scans in the format: {"scan_title":parsed_scan}
        """
        gtk.Window.__init__(self)
        self.set_title(_("Compare Results"))
        self.scans = scans
        self.ndiff_process = None
        # We allow the user to start a new diff before the old one has finished.
        # We have to keep references to old processes until they finish to avoid
        # problems when tearing down the Python interpreter at program exit.
        self.old_processes = []
        self.timer_id = None

        self._create_widgets()
        self._pack_widgets()
        self._connect_widgets()

        self.set_default_size(-1, 500)

        # Initial Size Request
        self.initial_size = self.get_size()

    def _create_widgets(self):
        self.main_vbox = HIGVBox()
        self.diff_view = DiffView()
        self.diff_view.set_size_request(-1, 100)
        self.hbox_buttons = HIGHBox()
        self.progress = gtk.ProgressBar()
        self.btn_close = HIGButton(stock=gtk.STOCK_CLOSE)
        self.hbox_selection = HIGHBox()
        self.scan_chooser_a = ScanChooser(self.scans, _(u"A Scan"))
        self.scan_chooser_b = ScanChooser(self.scans, _(u"B Scan"))

    def _pack_widgets(self):
        self.main_vbox.set_border_width(6)
        
        self.hbox_selection.pack_start(self.scan_chooser_a, True, True)
        self.hbox_selection.pack_start(self.scan_chooser_b, True, True)

        self.main_vbox.pack_start(self.hbox_selection, False)

        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll.add(self.diff_view)
        self.main_vbox.pack_start(scroll, True, True)

        self.progress.hide()
        self.progress.set_no_show_all(True)
        self.hbox_buttons.pack_start(self.progress, False)
        self.hbox_buttons.pack_end(self.btn_close, False)

        self.main_vbox._pack_noexpand_nofill(self.hbox_buttons)

        self.add(self.main_vbox)

    def _connect_widgets(self):
        self.connect("delete-event", self.close)
        self.btn_close.connect("clicked", self.close)
        self.scan_chooser_a.connect('changed', self.refresh_diff)
        self.scan_chooser_b.connect('changed', self.refresh_diff)

    def refresh_diff (self, widget):
        """This method is called whenever the diff output might have changed,
        such as when a different scan was selected in one of the choosers."""
        log.debug("Refresh diff.")

        if self.ndiff_process is not None and self.ndiff_process.poll() is None:
            # Put this in the list of old processes we keep track of.
            self.old_processes.append(self.ndiff_process)
            self.ndiff_process = None

        scan_a = self.scan_chooser_a.parsed_scan
        scan_b = self.scan_chooser_b.parsed_scan

        if scan_a is None or scan_b is None:
            self.diff_view.clear()
        else:
            try:
                self.ndiff_process = zenmapCore.Diff.ndiff(scan_a, scan_b)
            except OSError, e:
                alert = HIGAlertDialog(
                    message_format = _("Error running ndiff"),
                    secondary_text = _("There was an error running the ndiff program.\n\n") + str(e))
                alert.run()
                alert.destroy()
            else:
                self.progress.show()
                if self.timer_id is None:
                    self.timer_id = gobject.timeout_add(NDIFF_CHECK_TIMEOUT, self.check_ndiff_process)

    def check_ndiff_process(self):
        """Check if the ndiff subprocess is done and show the diff if it is.
        Also remove any finished processes from the old process list."""
        # Check if any old background processes have finished.
        for p in self.old_processes[:]:
            if p.poll() is not None:
                p.close()
                self.old_processes.remove(p)

        if self.ndiff_process is not None:
            # We're running the most recent scan. Check if it's done.
            status = self.ndiff_process.poll()

            if status is None:
                # Keep calling this function on a timer until the process
                # finishes.
                self.progress.pulse()
                return True

            if status == 0:
                # Successful completion.
                try:
                    diff = self.ndiff_process.get_scan_diff()
                except zenmapCore.Diff.NdiffParseException, e:
                    alert = HIGAlertDialog(
                        message_format = _("Error parsing ndiff output"),
                        secondary_text = str(e))
                    alert.run()
                    alert.destroy()
                else:
                    self.diff_view.show_diff(diff)
            else:
                # Unsuccessful completion (non-zero return code).
                error_text = _("The ndiff process terminated with status code %d.") % status
                stderr = self.ndiff_process.stderr.read()
                if len(stderr) > 0:
                    error_text += "\n\n" + stderr
                alert = HIGAlertDialog(
                    message_format = _("Error running ndiff"),
                    secondary_text = error_text)
                alert.run()
                alert.destroy()

            self.progress.hide()
            self.ndiff_process.close()
            self.ndiff_process = None

        if len(self.old_processes) > 0:
            # Keep calling this callback.
            return True
        else:
            # All done.
            self.timer_id = None
            return False

    def close(self, widget=None, extra=None):
        self.destroy()

def spec_to_string(spec):
    """Convert a port specification like (10, "tcp") to a string like
    "10/tcp"."""
    return "%d/%s" % spec

class DiffView(gtk.TextView):
    """A widget displaying a zenmapCore.Diff.ScanDiff."""
    def __init__(self):
        gtk.TextView.__init__(self)
        self.set_editable(False)

        buff = self.get_buffer()
        # Create text markup tags.
        buff.create_tag("hostname", weight = pango.WEIGHT_BOLD)
        buff.create_tag("hunk", indent = -20, left_margin = 20, wrap_mode = gtk.WRAP_WORD)

    def clear(self):
        self.get_buffer().set_text(u"")

    def host_id(host):
        """Get a string representation of a host."""
        address = None
        for address_type in ("ipv4", "ipv6", "mac"):
            addrs = [addr for addr in host.addresses if addr[0] == address_type]
            if len(addrs) > 0:
                address = addrs[0][1]
                break
        hostname = None
        if len(host.hostnames) > 0:
            hostname = host.hostnames[0]
        if hostname is not None:
            if address is not None:
                return "%s (%s)" % (hostname, address)
            else:
                return hostname
        elif address is not None:
            return address
        else:
            return "<unnamed host>"
    host_id = staticmethod(host_id)

    def show_diff(self, diff):
        self.clear()
        buff = self.get_buffer()
        if diff.a_start and diff.b_start:
            buff.insert_at_cursor(_(u"%s \N{RIGHTWARDS ARROW} %s\n") % (diff.a_start.ctime(), diff.b_start.ctime()))
        for host_diff in diff.host_diffs:
            buff.insert_with_tags_by_name(buff.get_end_iter(),
                u"%s\n" % self.host_id(host_diff), "hostname")
            diff = host_diff.diff[:]
            port_state_changes = zenmapCore.Diff.consolidate_port_state_changes(diff, PORT_STATE_CHANGE_CONSOLIDATION_THRESHOLD)
            for hunk in diff:
                if hunk.type == zenmapCore.Diff.HOST_STATE_CHANGE:
                    s = _(u"Host is %s, was %s.") % (hunk.b_state, hunk.a_state)
                elif hunk.type == zenmapCore.Diff.HOST_ADDRESS_ADD:
                    s = _(u"Add %s address %s.") % (hunk.address[0], hunk.address[1])
                elif hunk.type == zenmapCore.Diff.HOST_ADDRESS_REMOVE:
                    s = _(u"Remove %s address %s.") % (hunk.address[0], hunk.address[1])
                elif hunk.type == zenmapCore.Diff.HOST_HOSTNAME_ADD:
                    s = _(u"Add hostname %s.") % hunk.hostname
                elif hunk.type == zenmapCore.Diff.HOST_HOSTNAME_REMOVE:
                    s = _(u"Remove hostname %s.") % hunk.hostname
                elif hunk.type == zenmapCore.Diff.PORT_ID_CHANGE:
                    s = _(u"Service on %s is now running on %s.") % (spec_to_string(hunk.a_spec), spec_to_string(hunk.b_spec))
                elif hunk.type == zenmapCore.Diff.PORT_STATE_CHANGE:
                    if hunk.a_state == "unknown":
                        s = _(u"%s is %s.") % (spec_to_string(hunk.spec), hunk.b_state)
                    else:
                        s = _(u"%s is %s, was %s.") % (spec_to_string(hunk.spec), hunk.b_state, hunk.a_state)
                else:
                    log.debug("Ignoring unknown diff hunk type %d." % hunk.type)
                    continue
                buff.insert_with_tags_by_name(buff.get_end_iter(),
                    u"%s\n" % s, "hunk")
            for group in port_state_changes:
                a_state = group[0].a_state
                b_state = group[0].b_state
                protocol = group[0].spec[1]
                port_list = [hunk.spec[0] for hunk in group]
                if a_state == "unknown":
                    s = _(u"%d %s ports are %s.") % \
                        (len(port_list), protocol, b_state)
                else:
                    s = _(u"%d %s ports changed state from %s to %s.") % \
                        (len(port_list), protocol, a_state, b_state)
                mark = buff.create_mark(None, buff.get_end_iter(), True)
                # Create an expander to show the port list.
                anchor = buff.create_child_anchor(buff.get_end_iter())
                child = self.make_port_list_widget(port_list, s)
                child.show()
                self.add_child_at_anchor(child, anchor)
                buff.insert(buff.get_end_iter(), "\n")
                buff.apply_tag_by_name("hunk", buff.get_iter_at_mark(mark), buff.get_end_iter())
                buff.delete_mark(mark)

    def port_list_to_string(port_list):
        port_list = port_list[:]
        port_list.sort()
        chunks = []
        i = 0
        while i < len(port_list):
            start = i
            i += 1
            while i < len(port_list) and i - start == port_list[i] - port_list[start]:
                i += 1
            if i - start == 1:
                chunks.append(u"%d" % port_list[start])
            elif i - start == 2:
                chunks.append(u"%d" % port_list[start])
                chunks.append(u"%d" % port_list[i - 1])
            else:
                chunks.append(u"%d\N{EN DASH}%d" % (port_list[start], port_list[i - 1]))
        return u", ".join(chunks)
    port_list_to_string = staticmethod(port_list_to_string)

    def make_port_list_widget(port_list, label):
        """Return a widget showing a list of port numbers."""
        store = gtk.TreeStore(str)
        parent = store.append(None, (label,))
        store.append(parent, (DiffView.port_list_to_string(port_list),))
        view = gtk.TreeView(store)
        renderer = gtk.CellRendererText()
        # I can't find a way to make the wrap width dynamic based on widget
        # size.
        renderer.set_property("wrap-width", 500)
        col = gtk.TreeViewColumn("", renderer, text = 0)
        view.append_column(col)
        view.set_headers_visible(False)
        view.show_all()
        return view
    make_port_list_widget = staticmethod(make_port_list_widget)

if __name__ == "__main__":
    from zenmapCore.NmapParser import NmapParser

    parsed1 = NmapParser()
    parsed2 = NmapParser()
    parsed3 = NmapParser()
    parsed4 = NmapParser()

    parsed1.parse_file("test/xml_test1.xml")
    parsed2.parse_file("test/xml_test2.xml")
    parsed3.parse_file("test/xml_test3.xml")
    parsed4.parse_file("test/xml_test4.xml")
    
    dw = DiffWindow({"Parsed 1": parsed1,
                     "Parsed 2": parsed2,
                     "Parsed 3": parsed3,
                     "Parsed 4": parsed4})

    dw.show_all()
    dw.connect("delete-event", lambda x,y: gtk.main_quit())

    gtk.main()
