#!/usr/bin/perl

use strict;
use lib qw(/usr/lib/libDrakX);
use c;
use common;
use standalone;
use network::network;
use network::tools;
use run_program;
use mygtk2 qw(gtknew);
use dbus_object;
use network::activefw;
use network::monitor;

use Gtk2::TrayIcon;

use ugtk2 qw(:create :helpers :wrappers :dialogs);

my ($eventbox, $img);
my ($current_state, $current_interface, $menu, $timeout, $update_timeout);
my $onstartupfile = "$ENV{HOME}/.net_applet";
add_icon_path("/usr/share/libDrakX/pixmaps/");
# Allow multiple instances, but only one per user:
is_running('net_applet') and die "net_applet already running\n";

my $net = {};
my $watched_interface;

my $dbus = dbus_object::system_bus();
my $monitor = network::monitor->new($dbus);

my %pixbufs =
  (
      state => { map { $_ => gtkcreate_pixbuf($_) } qw(connected disconnected) },
      link_level => { map {
          my $f = "./wifi-$_.png";
          my $pixbuf = gtkcreate_pixbuf(-r $f ? $f : 'default')->scale_simple(24, 24, 'hyper');
          $_ => $pixbuf;
      } qw(20 40 60 80 100) },
      keyring => gtkcreate_pixbuf("/usr/share/pixmaps/keyring-small.png")->scale_simple(24, 24, 'hyper'), #- provided by usermode, required by drakxtools
  );
my %wireless_networks;
my %tooltips =
  (
      connected => N_("Network is up on interface %s"),
      disconnected =>
        #-PO: keep the "Configure Network" substring synced with the "Configure Network" message below
        N_("Network is down on interface %s. Click on \"Configure Network\""),
      notconfigured => N_("You do not have any configured Internet connection.
Run the \"%s\" assistant from the Mandriva Linux Control Center", N("Set up a new network interface (LAN, ISDN, ADSL, ...)")),
  );

my %actions = (
               'upNetwork' => { name => sub { N("Connect %s", $_[0]) }, launch => sub { network::tools::start_interface($_[0], 1) } },
               'downNetwork' => { name => sub { N("Disconnect %s", $_[0]) }, launch => sub { network::tools::stop_interface($_[0], 1) } },
               'monitorNetwork' => { name => N("Monitor Network"), launch => \&run_net_monitor },
               'wireless' => { name => N("Manage wireless networks"), launch => \&run_drakroam },
               'confNetwork' => { name => N("Configure Network"), launch => sub { system("/usr/sbin/drakconnect --skip-wizard &") } },
               'chooseInterface' => {
                   name => N("Watched interface"),
                   choices => sub { N("Auto-detect"), sort keys %{$net->{ifcfg}} },
                   choice_selected => sub { $watched_interface ? $_[0] eq $watched_interface : $_[0] eq N("Auto-detect") },
                   launch => sub {
                       $watched_interface = $_[0] eq N("Auto-detect") ? undef : $_[0];
                       checkNetworkForce();
                   }
               },
               'chooseProfile' => {
                   name => N("Profiles"),
                   choices => sub { network::network::netprofile_list() },
                   choice_selected => sub { $_[0] eq $net->{PROFILE} },
                   launch => sub {
		       require run_program;
		       $net->{PROFILE} = $_[0];
		       run_program::raw({ detach => 1 }, network::tools::wrap_command_for_root('/sbin/set-netprofile', $net->{PROFILE}));
                   }
               },
               'help' => { name => N("Get Online Help"), launch => sub { system("drakhelp --id internet-connection &") } },
               'quit' => { name => N("Quit"), launch => \&mainQuit },
              );

gtkadd(my $icon = Gtk2::TrayIcon->new("Net_Applet"),
       gtkadd($eventbox = Gtk2::EventBox->new,
              gtkpack($img = Gtk2::Image->new)
             )
      );
$eventbox->signal_connect(button_press_event => sub {
    $_[1]->button == 1 and run_net_monitor();
    $_[1]->button == 3 && $menu and $menu->popup(undef, undef, undef, undef, $_[1]->button, $_[1]->time);
});

shouldStart() or die "$onstartupfile should be set to TRUE or use net_applet --force";

my $activefw;
my $interactive_cb;
my @attacks_queue;

$activefw = network::activefw->new($dbus, sub {
    my ($_con, $msg) = @_;
    my $member = $msg->get_member;
    if ($member eq 'Attack') {
        handle_attack($msg->get_args_list);
    } elsif ($member eq 'Init') {
        $activefw->attach_object;
        checkNetworkForce();
    }
});

checkNetworkForce();
cronNetwork();
cronUpdate();
get_unprocessed_attacks();

$icon->show_all;

$SIG{HUP} = sub {
    print "received SIGHUP, reloading network configuration\n";
    checkNetworkForce();
};

Gtk2->main;

ugtk2::exit(0);

sub is_running {
    my ($name) = @_;
    any {
	my ($ppid, $pid, $n) = /^\s*(\d+)\s+(\d+)\s+(.*)/;
	$pid != $$ && $n eq $name;
    } `ps -o '%P %p %c' -u $ENV{USER}`;
}
sub shouldStart() {
    my ($opt) = @ARGV;
    if ($opt eq '--force' || $opt eq '-f') {
        return 1;
    }
    return getAutoStart();
}
sub run_net_monitor() { 
    run_program::raw({ detach => 1 }, '/usr/sbin/net_monitor', '--defaultintf', $current_interface) unless is_running('net_monitor');
}
sub run_drakroam() { 
    run_program::raw({ detach => 1 }, '/usr/sbin/drakroam') unless is_running('drakroam');
}
sub checkWireless() {
    my $networks = $monitor->list_wireless;
    foreach (keys %$networks) {
        my $net = $wireless_networks{$_} ||= {};
        put_in_hash($net, $networks->{$_});
        unless (exists $net->{menuitem}) {
            $net->{menuitem} = Gtk2::CheckMenuItem->new;
            $net->{menuitem}->set_draw_as_radio(1);
            $net->{menuitem}->add(gtkpack_(gtkshow(Gtk2::HBox->new),
                                           1, gtkset_alignment($net->{ssid_label} = Gtk2::Label->new, 0, 0),
                                           0, $net->{keyring_image} = Gtk2::Image->new_from_pixbuf($pixbufs{keyring}),
                                           0, $net->{level_image} = Gtk2::Image->new));
            $net->{activate} = $net->{menuitem}->signal_connect('activate' => sub {
                if (exists $net->{id}) {
                    eval { $monitor->select_network($net->{id}) };
                    if ($@) {
                        my $error = $@;
                        err_dialog(N("Error"), N("Unable to select wireless network: %s", $error));
                    }
                }
                checkNetworkForce();
            });
            undef $current_state; #- force menu redraw
        }
        $net->{ssid_label}->set_text($net->{ssid} || "[$_]");
        $net->{keyring_image}->visible(defined $net->{flags});
        my $approx_level = 20 + int(min($net->{signal_level}, 80)/20)*20;
        $net->{level_image}->set_from_pixbuf($pixbufs{link_level}{$approx_level});

        $net->{menuitem}->signal_handler_block($net->{activate});
        $net->{menuitem}->set_active($net->{current});
        $net->{menuitem}->signal_handler_unblock($net->{activate});
    }
    $wireless_networks{$_}{menuitem}->visible(exists $networks->{$_}) foreach keys %wireless_networks;
}
sub checkNetwork() {
    checkWireless();
    my ($gw_intf, $_is_up, $gw_address) = $watched_interface ?
      ($watched_interface, network::tools::get_interface_status($watched_interface)) :
      network::tools::get_internet_connection($net);
    go2State($gw_address ? 'connected' : $gw_intf ? 'disconnected' : 'notconfigured', $gw_intf);
}
sub checkNetworkForce() {
    $net = {};
    network::network::read_net_conf($net);
    undef $current_state;
    checkNetwork();
}
sub cronNetwork() {
    $timeout = Glib::Timeout->add(2000, sub {
                                      checkNetwork();
                                      1;
                                  });
}
sub cronUpdate() {
    my $current_md5 = common::md5file($0);
    $update_timeout = Glib::Timeout->add(60000, sub {
        common::md5file($0) ne $current_md5 and exec($0);
    });
}
sub go2State {
    my ($state_type, $interface) = @_;
    if ($current_state ne $state_type || $current_interface ne $interface) {
        $current_state = $state_type;
        $current_interface = $interface;
        if ($menu) {
            foreach (keys %wireless_networks) {
                $wireless_networks{$_}{menuitem}->get_parent and $menu->remove($wireless_networks{$_}{menuitem});
            }
            $menu->destroy;
        }
        $menu = generate_menu($state_type, $interface);
    }
}
sub generate_menu {
    my ($state_type, $interface) = @_;

    $img->set_from_pixbuf($pixbufs{state}{$state_type eq 'connected' ? 'connected' : 'disconnected'});
    gtkset_tip(Gtk2::Tooltips->new, $eventbox, formatAlaTeX(common::sprintf_fixutf8(translate($tooltips{$state_type}), $interface)));

    my $menu = Gtk2::Menu->new;
    my $create_item = sub {
        my ($action) = @_;
        my $name = ref($actions{$action}{name}) eq 'CODE' ? $actions{$action}{name}->($interface) : $actions{$action}{name};
        my $launch = $actions{$action}{launch};
        my @choices = exists $actions{$action}{choices} ? $actions{$action}{choices}->() : ();
        my $w;
        if (@choices == 0) {
            $w = gtksignal_connect(gtkshow(Gtk2::MenuItem->new_with_label($name)), activate => sub { $launch->($interface) });
        } elsif (@choices > 1) {
            my $selected = $actions{$action}{choice_selected};
            $w = gtkshow(create_menu($name, map {
                my $choice = $_;
                my $w = gtkshow(gtkset_active(Gtk2::CheckMenuItem->new_with_label($choice), $selected->($choice)));
                gtksignal_connect($w, activate => sub { $launch->($choice) });
                $w->set_draw_as_radio(1);
                $w;
            } $actions{$action}{choices}->()));
        }
        #- don't add submenu if only one choice exists
        $w;
    };

    my (@settings, @actions);
    my $has_wireless = keys %wireless_networks;

    if ($state_type eq 'connected') {
        push @actions, $create_item->($_) foreach qw(downNetwork monitorNetwork);
    } elsif ($state_type eq 'disconnected') {
        push @actions, $menu->append($create_item->('upNetwork'));
    }
    push @actions, $create_item->('confNetwork');

    if ($state_type ne 'notconfigured') {
        if ($has_wireless) {
            push @actions, $create_item->('wireless');
            $menu->append($_->{menuitem}) foreach values %wireless_networks;
            $menu->append(gtkshow(Gtk2::SeparatorMenuItem->new));
        }
        push @settings, $create_item->('chooseInterface');
    }

    push @settings, $create_item->('chooseProfile');
    my $interactive;
    eval { $interactive = $activefw->get_interactive };
    if (defined $interactive) {
        $interactive_cb = gtkshow(gtksignal_connect(gtkset_active(Gtk2::CheckMenuItem->new_with_label(N("Interactive intrusion detection")),
                                                                  $interactive),
                                                    toggled => sub { eval { $activefw->set_interactive(to_bool($_[0]->get_active)) } }));
        push @settings, $interactive_cb;
    }
    push @settings, gtkshow(gtksignal_connect(gtkset_active(Gtk2::CheckMenuItem->new_with_label(N("Always launch on startup")), getAutoStart()),
                                              toggled => sub { setAutoStart(uc(bool2text($_[0]->get_active))) }));

    if ($has_wireless) {
        $menu->append(gtkshow(create_menu(N("Actions"), @actions)));
    } else {
        $menu->append($_) foreach @actions;
        $menu->append(gtkshow(Gtk2::SeparatorMenuItem->new));
    }
    $menu->append(gtkshow(create_menu(N("Settings"), grep { $_ } @settings)));
    $menu->append(gtkshow(Gtk2::SeparatorMenuItem->new));
    $menu->append($create_item->('help'));
    $menu->append($create_item->('quit'));
    $menu;
}
sub mainQuit() {
     Glib::Source->remove($timeout) if $timeout;
     Glib::Source->remove($update_timeout) if $update_timeout;
     Gtk2->main_quit;
}
sub getAutoStart() {
    my %p = getVarsFromSh($onstartupfile);
    return to_bool($p{AUTOSTART} ne 'FALSE');
}
sub setAutoStart {
    my $state = shift;
    output_p $onstartupfile,
    qq(AUTOSTART=$state
);
}

sub get_unprocessed_attacks() {
    my @packets = eval { $activefw->get_reports };
    while (my @attack = splice(@packets, 0, 9)) {
        handle_attack(@attack);
    }
}

sub handle_attack {
    push @attacks_queue, [ @_ ];
    @attacks_queue == 1 and ask_attack_verdict($attacks_queue[0]);
}

sub set_attack_verdict {
    my ($seq, $verdict) = @_;
    eval { $activefw->blacklist($seq, $verdict) };
    $@ and err_dialog(N("Active Firewall"), N("Unable to contact daemon"));
    shift @attacks_queue;
    @attacks_queue and ask_attack_verdict($attacks_queue[0]);
}

sub ask_attack_verdict {
    my ($attack) = @_;
    my ($seq, $timestamp, $indev, $prefix, $_sensor, $protocol, $addr, $port, $icmp_type) = @$attack;

    unless ($interactive_cb->get_active) {
        #- let the daemon handle the blacklist policy in automatic mode
        set_attack_verdict($seq, undef);
        return;
    }

    my $ip_addr = network::activefw::get_ip_address($addr);
    my $hostname = network::activefw::resolve_address($ip_addr);
    my $service = network::activefw::get_service($port);

    my $msg = $prefix eq "SCAN" ? N("A port scanning attack has been attempted by %s.", $hostname)
            : $prefix eq "SERV" ? N("The %s service has been attacked by %s.", $service , $hostname)
            : $prefix eq "PASS" ? N("A password cracking attack has been attempted by %s.", $hostname)
            : undef;
    unless ($msg) {
        print "unhandled attack type, skipping\n";
        return;
    }

    my $w = Gtk2::Window->new;
    $w->set_title(N("Active Firewall: intrusion detected"));
    $w->set_icon(gtknew('Pixbuf', file => "/usr/lib/libDrakX/icons/drakfirewall.png"));
    my ($yes, $no, $auto);

    gtkadd($w,
           gtknew('VBox', spacing => 5, children_loose => [
               gtknew('HBox', children => [
                   0, Gtk2::Image->new_from_stock('gtk-dialog-warning', 'dialog'),
                   0, gtknew('Label', text => "   "),
                   1, gtknew('VBox', children => [
                       0, $msg,
                       0, N("Do you want to blacklist the attacker?")
                   ])
               ]),
               gtknew('HButtonBox', layout => 'edge', children_loose => [
                   $no = gtknew('Button', text => N("No"), clicked => sub {
                       $w->destroy;
                       set_attack_verdict($seq, 0);
                   }),
                   $yes = gtknew('Button', text => N("Yes"), clicked => sub {
                       $auto->get_active and $interactive_cb->set_active(0);
                       $w->destroy;
                       set_attack_verdict($seq, 1);
                   })
               ]),
               $auto = gtknew('CheckButton', text => N("Always blacklist (do not ask again)"), toggled => sub {
                   $no->set_sensitive(!$_[0]->get_active);
               }),
               gtkadd(Gtk2::Expander->new(N("Attack details")),
                      gtknew('HBox', children => [
                          0, gtknew('Label', text => "     "),
                          1, gtknew('VBox', children_loose => [
                              N("Attack time: %s", network::activefw::format_date($timestamp)),
                              N("Network interface: %s", $indev),
                              N("Attack type: %s", $prefix),
                              if_($protocol, N("Protocol: %s", $protocol)),
                              N("Attacker IP address: %s", $ip_addr),
                              if_($hostname ne $ip_addr, N("Attacker hostname: %s", $hostname)),
                              if_($service, N("Service attacked: %s", $service)),
                              if_($port, N("Port attacked: %s", $port)),
                              if_($icmp_type, N("Type of ICMP attack: %s", $icmp_type))
                          ])
                      ])),
           ]));
    $yes->grab_focus;
    gtksignal_connect($w, delete_event => sub {
        if ($auto->get_active) {
            $interactive_cb->set_active(0);
            set_attack_verdict($seq, 1);
        } else {
            set_attack_verdict($seq, 0);
        }
    });
    $w->show_all;
}