diff --git a/gosa-si/gosa-si-server b/gosa-si/gosa-si-server
index 027814b80a50c84c481ce95cf9e50a37a23935b9..b93f07cc7a58c9c717e13303941b4b720f0f92a0 100755 (executable)
--- a/gosa-si/gosa-si-server
+++ b/gosa-si/gosa-si-server
# DESCRIPTION:
#
# OPTIONS: ---
-# REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl libipc-shareable-perl libdata-dumper-simple-perl
+# REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl
+# libdata-dumper-simple-perl libdbd-sqlite3-perl libnet-ldap-perl
+# libpoe-perl
# BUGS: ---
# NOTES:
# AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
use Getopt::Long;
use Config::IniFiles;
use POSIX;
-use Time::HiRes qw( gettimeofday );
use Fcntl;
use IO::Socket::INET;
+use IO::Handle;
+use IO::Select;
+use Symbol qw(qualify_to_ref);
use Crypt::Rijndael;
use MIME::Base64;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Sys::Syslog qw( :DEFAULT setlogsock);
use Cwd;
use File::Spec;
-use IPC::Shareable qw( :lock);
-IPC::Shareable->clean_up_all;
-
-use lib "/etc/gosa-si/modules";
-my $modules_path = "/etc/gosa-si/modules";
-
-my ($cfg_file, %cfg_defaults, $foreground, $verbose, $ping_timeout, $no_bus);
-my ($bus, $msg_to_bus, $bus_cipher);
-my ($server, $server_mac_address, $server_events);
-my ($gosa_server);
-my ($known_daemons, $shmda, $known_clients, $shmcl, $known_modules);
-my ($max_clients);
+use File::Basename;
+use File::Find;
+use File::Copy;
+use File::Path;
+use GOSA::DBsqlite;
+use GOSA::GosaSupportDaemon;
+use POE qw(Component::Server::TCP Wheel::Run Filter::Reference);
+use Net::LDAP;
+use Net::LDAP::Util qw(:escape);
+
+my $modules_path = "/usr/lib/gosa-si/modules";
+use lib "/usr/lib/gosa-si/modules";
+
+# TODO es gibt eine globale funktion get_ldap_handle
+# - ist in einer session dieses ldap handle schon vorhanden, wird es zurückgegeben
+# - ist es nicht vorhanden, wird es erzeugt, im heap für spätere ldap anfragen gespeichert und zurückgegeben
+# - sessions die kein ldap handle brauchen, sollen auch keins haben
+# - wird eine session geschlossen, muss das ldap verbindung vorher beendet werden
+our $global_kernel;
+
+my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
+my ($bus_activ, $bus, $msg_to_bus, $bus_cipher);
+my ($server);
+my ($gosa_server, $job_queue_timeout, $job_queue_loop_delay);
+my ($known_modules);
my ($pid_file, $procid, $pid, $log_file);
-my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
-my ($arp_activ, $arp_fifo, $arp_fifo_path, $no_arp);
-
+my ($arp_activ, $arp_fifo);
+my ($xml);
+my $sources_list;
+my $max_clients;
+my %repo_files=();
+my $repo_path;
+my %repo_dirs=();
# variables declared in config file are always set to 'our'
our (%cfg_defaults, $log_file, $pid_file,
- $bus_activ, $bus_passwd, $bus_ip, $bus_port,
- $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
- $arp_activ, $arp_fifo_path,
- $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
+ $server_ip, $server_port, $SIPackages_key,
+ $arp_activ, $gosa_unit_tag,
+ $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
);
# additional variable which should be globaly accessable
-our $xml;
our $server_address;
+our $server_mac_address;
our $bus_address;
our $gosa_address;
+our $no_bus;
+our $no_arp;
+our $verbose;
+our $forground;
+our $cfg_file;
+#our ($ldap_handle, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $ldap_server_dn);
+our ($ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $ldap_server_dn);
+
# specifies the verbosity of the daemon_log
$verbose = 0 ;
$ping_timeout = 5;
$no_bus = 0;
+$bus_activ = "true";
$no_arp = 0;
+our $prg= basename($0);
+
+# holds all gosa jobs
+our $job_db;
+our $job_queue_tn = 'jobs';
+my $job_queue_file_name;
+my @job_queue_col_names = ("id INTEGER",
+ "timestamp",
+ "status DEFAULT 'none'",
+ "result DEFAULT 'none'",
+ "progress DEFAULT 'none'",
+ "headertag DEFAULT 'none'",
+ "targettag DEFAULT 'none'",
+ "xmlmessage DEFAULT 'none'",
+ "macaddress DEFAULT 'none'",
+ );
+
# holds all other gosa-sd as well as the gosa-sd-bus
-our $known_daemons = {};
-our $shmda = tie($known_daemons, 'IPC::Shareable', undef, {create => 1,
- exclusive => 1,
- mode => 0666,
- destroy => 1,
- });
+our $known_server_db;
+our $known_server_tn = "known_server";
+my $known_server_file_name;
+my @known_server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
+
# holds all registrated clients
-our $known_clients = {};
-our $shmcl = tie($known_clients, 'IPC::Shareable', undef, {create => 1,
- exclusive => 1,
- mode => 0666,
- destroy => 1,
- });
-
-
-%cfg_defaults =
-("general" =>
- {"log_file" => [\$log_file, "/var/run/".$0.".log"],
- "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
- "child_max" => [\$child_max, 10],
- "child_min" => [\$child_min, 3],
- "child_timeout" => [\$child_timeout, 180],
- },
-"bus" =>
- {"bus_activ" => [\$bus_activ, "on"],
- "bus_passwd" => [\$bus_passwd, ""],
- "bus_ip" => [\$bus_ip, ""],
- "bus_port" => [\$bus_port, "20080"],
+our $known_clients_db;
+our $known_clients_tn = "known_clients";
+my $known_clients_file_name;
+my @known_clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
+
+# holds all logged in user at each client
+our $login_users_db;
+our $login_users_tn = "login_users";
+my $login_users_file_name;
+my @login_users_col_names = ('client', 'user', 'timestamp');
+
+# holds all fai server, the debian release and tag
+our $fai_server_db;
+our $fai_server_tn = "fai_server";
+my $fai_server_file_name;
+our @fai_server_col_names = ('timestamp', 'server', 'release', 'sections', 'tag');
+our $fai_release_tn = "fai_release";
+our @fai_release_col_names = ('timestamp', 'release', 'class', 'type', 'state');
+
+# holds all packages available from different repositories
+our $packages_list_db;
+our $packages_list_tn = "packages_list";
+my $packages_list_file_name;
+our @packages_list_col_names = ('distribution', 'package', 'version', 'section', 'description', 'template', 'timestamp');
+my $outdir = "/tmp/packages_list_db";
+my $arch = "i386";
+
+# holds all messages which should be delivered to a user
+our $messaging_db;
+our $messaging_tn = "messaging";
+our @messaging_col_names = ('subject', 'from', 'to', 'flag', 'direction', 'delivery_time', 'message', 'timestamp', 'id INTEGER', );
+my $messaging_file_name;
+
+# path to directory to store client install log files
+our $client_fai_log_dir = "/var/log/fai";
+
+# queue which stores taskes until one of the $max_children children are ready to process the task
+my @tasks = qw();
+my $max_children = 2;
+
+
+%cfg_defaults = (
+"general" => {
+ "log-file" => [\$log_file, "/var/run/".$prg.".log"],
+ "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
},
-"server" =>
- {"server_activ" => [\$server_activ, "on"],
- "server_ip" => [\$server_ip, ""],
- "server_port" => [\$server_port, "20081"],
- "server_passwd" => [\$server_passwd, ""],
- "max_clients" => [\$max_clients, 100],
+"bus" => {
+ "activ" => [\$bus_activ, "true"],
},
-"arp" =>
- {"arp_activ" => [\$arp_activ, "on"],
- "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
+"server" => {
+ "port" => [\$server_port, "20081"],
+ "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
+ "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
+ "login-users" => [\$login_users_file_name, '/var/lib/gosa-si/users.db'],
+ "fai-server" => [\$fai_server_file_name, '/var/lib/gosa-si/fai.db'],
+ "packages-list" => [\$packages_list_file_name, '/var/lib/gosa-si/packages.db'],
+ "messaging" => [\$messaging_file_name, '/var/lib/gosa-si/messaging.db'],
+ "source-list" => [\$sources_list, '/etc/apt/sources.list'],
+ "repo-path" => [\$repo_path, '/srv/www/repository'],
+ "ldap-uri" => [\$ldap_uri, ""],
+ "ldap-base" => [\$ldap_base, ""],
+ "ldap-admin-dn" => [\$ldap_admin_dn, ""],
+ "ldap-admin-password" => [\$ldap_admin_password, ""],
+ "gosa-unit-tag" => [\$gosa_unit_tag, ""],
+ "max-clients" => [\$max_clients, 10],
},
-"gosa" =>
- {"gosa_activ" => [\$gosa_activ, "on"],
- "gosa_ip" => [\$gosa_ip, ""],
- "gosa_port" => [\$gosa_port, "20082"],
- "gosa_passwd" => [\$gosa_passwd, "none"],
+"GOsaPackages" => {
+ "ip" => [\$gosa_ip, "0.0.0.0"],
+ "port" => [\$gosa_port, "20082"],
+ "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
+ "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
+ "key" => [\$GosaPackages_key, "none"],
},
- );
+"SIPackages" => {
+ "key" => [\$SIPackages_key, "none"],
+ },
+);
#=== FUNCTION ================================================================
#===============================================================================
sub usage {
print STDERR << "EOF" ;
-usage: $0 [-hvf] [-c config]
+usage: $prg [-hvf] [-c config]
-h : this (help) message
-c <file> : config file
-f : foreground, process will not be forked to background
-v : be verbose (multiple to increase verbosity)
+ -no-bus : starts $prg without connection to bus
+ -no-arp : starts $prg without connection to arp module
+
EOF
print "\n" ;
}
#===============================================================================
sub read_configfile {
my $cfg;
- if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
+ if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
if( -r $cfg_file ) {
$cfg = Config::IniFiles->new( -file => $cfg_file );
} else {
- print STDERR "Couldn't read config file!";
+ print STDERR "Couldn't read config file!\n";
}
} else {
$cfg = Config::IniFiles->new() ;
# DESCRIPTION: function for logging
#===============================================================================
sub daemon_log {
-# log into log_file
+ # log into log_file
my( $msg, $level ) = @_;
if(not defined $msg) { return }
if(not defined $level) { $level = 1 }
return }
chomp($msg);
if($level <= $verbose){
- print LOG_HANDLE "$level $msg\n";
- if(defined $foreground) { print $msg."\n" }
+ my ($seconds, $minutes, $hours, $monthday, $month,
+ $year, $weekday, $yearday, $sommertime) = localtime(time);
+ $hours = $hours < 10 ? $hours = "0".$hours : $hours;
+ $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
+ $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
+ my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
+ $month = $monthnames[$month];
+ $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
+ $year+=1900;
+ my $name = $prg;
+
+ my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
+ print LOG_HANDLE $log_msg;
+ if( $foreground ) {
+ print STDERR $log_msg;
+ }
}
+ close( LOG_HANDLE );
}
- close( LOG_HANDLE );
-#log into syslog
-# my ($msg, $level, $facility) = @_;
-# if(not defined $msg) {return}
-# if(not defined $level) {$level = "info"}
-# if(not defined $facility) {$facility = "LOG_DAEMON"}
-# openlog($0, "pid,cons,", $facility);
-# syslog($level, $msg);
-# closelog;
-# return;
}
sub check_cmdline_param () {
my $err_config;
my $err_counter = 0;
- if( not defined( $cfg_file)) {
- #$err_config = "please specify a config file";
- #$err_counter += 1;
- my $cwd = getcwd;
- my $name = "/etc/gosa-si/server.conf";
- $cfg_file = File::Spec->catfile( $cwd, $name );
+ if(not defined($cfg_file)) {
+ $cfg_file = "/etc/gosa-si/server.conf";
+ if(! -r $cfg_file) {
+ $err_config = "please specify a config file";
+ $err_counter += 1;
+ }
}
if( $err_counter > 0 ) {
&usage( "", 1 );
chomp( $pid );
if( -f "/proc/$pid/stat" ) {
my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
- if( $0 eq $stat ) {
+ if( $stat ) {
+ daemon_log("ERROR: Already running",1);
close( LOCK_FILE );
exit -1;
}
}
}
-
-#=== FUNCTION ================================================================
-# NAME: get_ip_and_mac
-# PARAMETERS: nothing
-# RETURNS: (ip, mac)
-# DESCRIPTION: executes /sbin/ifconfig and parses the output, the first occurence
-# of a inet address is returned as well as the mac address in the line
-# above the inet address
-#===============================================================================
-sub get_ip_and_mac {
- my $ip = "0.0.0.0.0"; # Defualt-IP
- my $mac = "00:00:00:00:00:00"; # Default-MAC
- my @ifconfig = qx(/sbin/ifconfig);
- foreach(@ifconfig) {
- if (/Hardware Adresse (\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/) {
- $mac = "$1:$2:$3:$4:$5:$6";
- next;
- }
- if (/inet Adresse:(\d+).(\d+).(\d+).(\d+)/) {
- $ip = "$1.$2.$3.$4";
- last;
- }
- }
- return ($ip, $mac);
-}
-
-
-
#=== FUNCTION ================================================================
# NAME: import_modules
-# PARAMETERS: module_path - string - abs. path to the directory the modules are stored
+# PARAMETERS: module_path - string - abs. path to the directory the modules
+# are stored
# RETURNS: nothing
-# DESCRIPTION: each file in module_path which ends with '.pm' is imported by "require 'file';"
+# DESCRIPTION: each file in module_path which ends with '.pm' and activation
+# state is on is imported by "require 'file';"
#===============================================================================
sub import_modules {
daemon_log(" ", 1);
if (not $file =~ /(\S*?).pm$/) {
next;
}
+ my $mod_name = $1;
+
+ if( $file =~ /ArpHandler.pm/ ) {
+ if( $no_arp > 0 ) {
+ next;
+ }
+ }
+
eval { require $file; };
if ($@) {
- daemon_log("ERROR: gosa-sd could not load module $file", 1);
+ daemon_log("ERROR: gosa-si-server could not load module $file", 1);
daemon_log("$@", 5);
- next;
- }
- my $mod_name = $1;
- my $module_tag_hash = eval( $mod_name.'::get_module_tags()' );
- $known_modules->{$mod_name} = $module_tag_hash;
-
- daemon_log("load module $mod_name", 1);
+ } else {
+ my $info = eval($mod_name.'::get_module_info()');
+ # Only load module if get_module_info() returns a non-null object
+ if( $info ) {
+ my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
+ $known_modules->{$mod_name} = $info;
+ daemon_log("INFO: module $mod_name loaded", 5);
+ }
+ }
}
-
- # for debugging
- #while ( my ($module, $tag_hash) = each(%$known_modules)) {
- # print "\tmodule: $module"."\n";
- # print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
- #}
close (DIR);
}
-#=== FUNCTION ================================================================
-# NAME: register_at_bus
-# PARAMETERS: nothing
-# RETURNS: nothing
-# DESCRIPTION: creates an entry in known_daemons and send a 'here_i_am' msg to bus
-#===============================================================================
-sub register_at_bus {
-
- # create known_daemons entry
- &create_known_daemon($bus_address);
- &add_content2known_daemons(hostname=>$bus_address, status=>"register_at_bus", passwd=>$bus_passwd);
-
- my $msg_hash = &create_xml_hash("here_i_am", "$server_ip:$server_port", $bus_address);
- my $answer = "";
- $answer = &send_msg_hash2address($msg_hash, $bus_address);
- if ($answer == 0) {
- daemon_log("register at bus: $bus_address", 1);
- } else {
- daemon_log("unable to send 'register'-msg to bus: $bus_address", 1);
- }
- return;
-}
-
-
#=== FUNCTION ================================================================
# NAME: sig_int_handler
# PARAMETERS: signal - string - signal arose from system
#===============================================================================
sub sig_int_handler {
my ($signal) = @_;
- if($server){
- close($server);
- daemon_log("daemon server closed", 1);
- }
- if( -p $arp_fifo_path ) {
- close $arp_fifo ;
- unlink($arp_fifo_path) ;
- daemon_log("ARP_FIFO closed", 1) ;
- }
- if($gosa_server){
- close($gosa_server);
- daemon_log("gosa server closed", 1);
- }
-
- print STDERR "$signal\n";
+# if (defined($ldap_handle)) {
+# $ldap_handle->disconnect;
+# }
+ # TODO alle verbliebenden ldap verbindungen aus allen heaps beenden
- exit(1);
+
+ daemon_log("shutting down gosa-si-server", 1);
+ system("kill `ps -C gosa-si-server -o pid=`");
}
$SIG{INT} = \&sig_int_handler;
-#=== FUNCTION ================================================================
-# NAME: activating_child
-# PARAMETERS: msg - string - incoming message
-# host - string - host from which the incomming message comes
-# RETURNS: nothing
-# DESCRIPTION: handels the distribution of incoming messages to working childs
-#===============================================================================
-sub activating_child {
- my ($msg, $host, $client) = @_;
- my $child = &get_processing_child();
- my $pipe_wr = $$child{'pipe_wr'};
- my $pipe_rd = $$child{'pipe_rd'};
- $$child{client_ref} = $client;
- daemon_log("activating: childpid:$$child{'pid'}", 5);
+sub check_key_and_xml_validity {
+ my ($crypted_msg, $module_key, $session_id) = @_;
+ my $msg;
+ my $msg_hash;
+ my $error_string;
+ eval{
+ $msg = &decrypt_msg($crypted_msg, $module_key);
- print $pipe_wr $msg.".".$host."\n";
+ if ($msg =~ /<xml>/i){
+ $msg =~ s/\s+/ /g; # just for better daemon_log
+ daemon_log("$session_id DEBUG: decrypted_msg: \n$msg", 8);
+ $msg_hash = $xml->XMLin($msg, ForceArray=>1);
- return;
+ ##############
+ # check header
+ if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
+ my $header_l = $msg_hash->{'header'};
+ if( 1 > @{$header_l} ) { die 'empty header tag'; }
+ if( 1 < @{$header_l} ) { die 'more than one header specified'; }
+ my $header = @{$header_l}[0];
+ if( 0 == length $header) { die 'empty string in header tag'; }
+
+ ##############
+ # check source
+ if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
+ my $source_l = $msg_hash->{'source'};
+ if( 1 > @{$source_l} ) { die 'empty source tag'; }
+ if( 1 < @{$source_l} ) { die 'more than one source specified'; }
+ my $source = @{$source_l}[0];
+ if( 0 == length $source) { die 'source error'; }
+
+ ##############
+ # check target
+ if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
+ my $target_l = $msg_hash->{'target'};
+ if( 1 > @{$target_l} ) { die 'empty target tag'; }
+ }
+ };
+ if($@) {
+ daemon_log("$session_id DEBUG: do not understand the message: $@", 7);
+ $msg = undef;
+ $msg_hash = undef;
+ }
+
+ return ($msg, $msg_hash);
}
-#=== FUNCTION ================================================================
-# NAME: get_processing_child
-# PARAMETERS: nothing
-# RETURNS: child - hash - holding the process id and the references to the pipe
-# handles pipe_wr and pipe_rd
-# DESCRIPTION: handels the forking, reactivating and keeping alive tasks
-#===============================================================================
-sub get_processing_child {
- my $child;
+sub check_outgoing_xml_validity {
+ my ($msg) = @_;
+
+ my $msg_hash;
+ eval{
+ $msg_hash = $xml->XMLin($msg, ForceArray=>1);
- while(my ($key, $val) = each(%free_child)) {
- my $exitus_pid = waitpid($key, WNOHANG);
- if($exitus_pid != 0) {
- delete $free_child{$key};
+ ##############
+ # check header
+ my $header_l = $msg_hash->{'header'};
+ if( 1 != @{$header_l} ) {
+ die 'no or more than one headers specified';
}
- daemon_log("free child:$key", 5);
- }
- # check @free_child and @busy_child
- my $free_len = scalar(keys(%free_child));
- my $busy_len = scalar(keys(%busy_child));
- daemon_log("free children $free_len, busy children $busy_len", 5);
-
- # if there is a free child, let the child work
- if($free_len > 0){
- my @keys = keys(%free_child);
- $child = $free_child{$keys[0]};
- if(defined $child) {
- $busy_child{$$child{'pid'}} = $child ;
- delete $free_child{$$child{'pid'}};
+ my $header = @{$header_l}[0];
+ if( 0 == length $header) {
+ die 'header has length 0';
+ }
+
+ ##############
+ # check source
+ my $source_l = $msg_hash->{'source'};
+ if( 1 != @{$source_l} ) {
+ die 'no or more than 1 sources specified';
+ }
+ my $source = @{$source_l}[0];
+ if( 0 == length $source) {
+ die 'source has length 0';
}
- return $child;
+ unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
+ $source =~ /^GOSA$/i ) {
+ die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
+ }
+
+ ##############
+ # check target
+ my $target_l = $msg_hash->{'target'};
+ if( 0 == @{$target_l} ) {
+ die "no targets specified";
+ }
+ foreach my $target (@$target_l) {
+ if( 0 == length $target) {
+ die "target has length 0";
+ }
+ unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
+ $target =~ /^GOSA$/i ||
+ $target =~ /^\*$/ ||
+ $target =~ /KNOWN_SERVER/i ||
+ $target =~ /JOBDB/i ||
+ $target =~ /^([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$/i ){
+ die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
+ }
+ }
+ };
+ if($@) {
+ daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
+ daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 8);
+ $msg_hash = undef;
}
- # no free child, try to fork another one
- if($free_len + $busy_len < $child_max) {
+ return ($msg_hash);
+}
- daemon_log("not enough children, create a new one", 5);
- # New pipes for communication
- my( $PARENT_wr, $PARENT_rd );
- my( $CHILD_wr, $CHILD_rd );
- pipe( $CHILD_rd, $PARENT_wr );
- pipe( $PARENT_rd, $CHILD_wr );
- $PARENT_wr->autoflush(1);
- $CHILD_wr->autoflush(1);
+sub input_from_known_server {
+ my ($input, $remote_ip, $session_id) = @_ ;
+ my ($msg, $msg_hash, $module);
- ############
- # fork child
- ############
- my $child_pid = fork();
-
- #CHILD
- if($child_pid == 0) {
- # Close unused pipes
- close( $CHILD_rd );
- close( $CHILD_wr );
- while( 1 ) {
- my $rbits = "";
- vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
- my $nf = select($rbits, undef, undef, $child_timeout);
- if($nf < 0 ) {
- die "select(): $!\n";
- } elsif (! $nf) {
- # if already child_min childs are alive, then leave loop
- $free_len = scalar(keys(%free_child));
- $busy_len = scalar(keys(%busy_child));
- if($free_len + $busy_len >= $child_min) {
- last;
- } else {
- redo;
- }
- }
+ my $sql_statement= "SELECT * FROM known_server";
+ my $query_res = $known_server_db->select_dbentry( $sql_statement );
- # a job for a child arise
- if ( vec $rbits, fileno $PARENT_rd, 1 ) {
- # read everything from pipe
- my $msg = "";
- $PARENT_rd->blocking(0);
- while(1) {
- my $read = <$PARENT_rd>;
- if(not defined $read) { last}
- $msg .= $read;
- }
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ if( not $host_name =~ "^$remote_ip") {
+ next;
+ }
+ my $host_key = $hit->{hostkey};
+ daemon_log("$session_id DEBUG: input_from_known_server: host_name: $host_name", 7);
+ daemon_log("DEBUG: input_from_known_server: host_key: $host_key", 7);
+
+ # check if module can open msg envelope with module key
+ my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
+ if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
+ daemon_log("$session_id DEBUG: input_from_known_server: deciphering raise error", 7);
+ daemon_log("$@", 8);
+ next;
+ }
+ else {
+ $msg = $tmp_msg;
+ $msg_hash = $tmp_msg_hash;
+ $module = "SIPackages";
+ last;
+ }
+ }
- ######################################
- # forward msg to all imported modules
- no strict "refs";
- my $answer;
- while( my ($module, $tag_hash) = each(%$known_modules)) {
- #if(exists $known_modules->{$module}->{server_packages}) {
- my $tmp = &{ $module."::process_incoming_msg" }($msg);
- if (defined $tmp) {
- $answer = $tmp;
- }
- #}
- }
+ if( (!$msg) || (!$msg_hash) || (!$module) ) {
+ daemon_log("$session_id DEBUG: Incoming message is not from a known server", 7);
+ }
+
+ return ($msg, $msg_hash, $module);
+}
- #&print_known_daemons();
- #&print_known_clients();
- daemon_log("processing of msg finished", 5);
+sub input_from_known_client {
+ my ($input, $remote_ip, $session_id) = @_ ;
+ my ($msg, $msg_hash, $module);
- if (defined $answer) {
- print $PARENT_wr $answer."\n";
- daemon_log("\t$answer", 5);
- daemon_log(" ", 5);
- } else {
- print $PARENT_wr "done"."\n";
- daemon_log(" ", 5);
- }
- redo;
- }
- }
- # childs leaving the loop are allowed to die
- exit(0);
+ my $sql_statement= "SELECT * FROM known_clients";
+ my $query_res = $known_clients_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ if( not $host_name =~ /^$remote_ip:\d*$/) {
+ next;
+ }
+ my $host_key = $hit->{hostkey};
+ &daemon_log("$session_id DEBUG: input_from_known_client: host_name: $host_name", 7);
+ &daemon_log("$session_id DEBUG: input_from_known_client: host_key: $host_key", 7);
+ # check if module can open msg envelope with module key
+ ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
- #PARENT
- } else {
- # Close unused pipes
- close( $PARENT_rd );
- close( $PARENT_wr );
-
- # add child to child alive hash
- my %child_hash = (
- 'pid' => $child_pid,
- 'pipe_wr' => $CHILD_wr,
- 'pipe_rd' => $CHILD_rd,
- 'client_ref' => "",
- );
-
- $child = \%child_hash;
- $busy_child{$$child{'pid'}} = $child;
- return $child;
+ if( (!$msg) || (!$msg_hash) ) {
+ &daemon_log("$session_id DEGUG: input_from_known_client: deciphering raise error", 7);
+ &daemon_log("$@", 8);
+ next;
}
+ else {
+ $module = "SIPackages";
+ last;
+ }
+ }
+
+ if( (!$msg) || (!$msg_hash) || (!$module) ) {
+ &daemon_log("$session_id DEBUG: Incoming message is not from a known client", 7);
}
+
+ return ($msg, $msg_hash, $module);
}
-#=== FUNCTION ================================================================
-# NAME: process_incoming_msg
-# PARAMETERS: crypted_msg - string - incoming crypted message
-# RETURNS: nothing
-# DESCRIPTION: handels the proceeded distribution to the appropriated functions
-#===============================================================================
-sub process_incoming_msg {
- my ($crypted_msg) = @_;
- if(not defined $crypted_msg) {
- daemon_log("function 'process_incoming_msg': got no msg", 7);
- }
- $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
- $crypted_msg = $1;
- my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
- daemon_log("msg from host:", 1);
- daemon_log("\t$host", 1);
- #daemon_log("crypted msg:", 7);
- #daemon_log("\t$crypted_msg", 7);
-
- # collect addresses from possible incoming clients
- my @valid_keys;
- my @host_keys = keys %$known_daemons;
- foreach my $host_key (@host_keys) {
- if($host_key =~ "^$host") {
- push(@valid_keys, $host_key);
+sub input_from_unknown_host {
+ no strict "refs";
+ my ($input, $session_id) = @_ ;
+ my ($msg, $msg_hash, $module);
+ my $error_string;
+
+ my %act_modules = %$known_modules;
+
+ while( my ($mod, $info) = each(%act_modules)) {
+
+ # check a key exists for this module
+ my $module_key = ${$mod."_key"};
+ if( not defined $module_key ) {
+ if( $mod eq 'ArpHandler' ) {
+ next;
+ }
+ daemon_log("$session_id ERROR: no key specified in config file for $mod", 1);
+ next;
}
- }
- my @client_keys = keys %$known_clients;
- foreach my $client_key (@client_keys) {
- if($client_key =~ "^$host"){
- push(@valid_keys, $client_key);
+ daemon_log("$session_id DEBUG: $mod: $module_key", 7);
+
+ # check if module can open msg envelope with module key
+ ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key, $session_id);
+ if( (not defined $msg) || (not defined $msg_hash) ) {
+ next;
}
- }
- push(@valid_keys, $server_address);
-
- my $l = @valid_keys;
- my ($msg, $msg_hash);
- my $msg_flag = 0;
-
- # determine the correct passwd for deciphering of the incoming msgs
- foreach my $host_key (@valid_keys) {
- eval{
- daemon_log( "key: $host_key", 7);
- my $key_passwd;
- if (exists $known_daemons->{$host_key}) {
- $key_passwd = $known_daemons->{$host_key}->{passwd};
- } elsif (exists $known_clients->{$host_key}) {
- $key_passwd = $known_clients->{$host_key}->{passwd};
- } elsif ($host_key eq $server_address) {
- $key_passwd = $server_passwd;
- }
- daemon_log("key_passwd: $key_passwd", 7);
- my $key_cipher = &create_ciphering($key_passwd);
- $msg = &decrypt_msg($crypted_msg, $key_cipher);
- $msg_hash = $xml->XMLin($msg, ForceArray=>1);
- };
- if($@) {
- daemon_log("key raise error", 7);
- $msg_flag += 1;
- } else {
+ else {
+ $module = $mod;
last;
}
- }
-
- if($msg_flag >= $l) {
- daemon_log("ERROR: do not understand the message:", 1);
- daemon_log("\t$msg", 1);
- return;
}
- # process incoming msg
- my $header = &get_content_from_xml_hash($msg_hash, "header");
- my $source = @{$msg_hash->{source}}[0];
-
- daemon_log("header from msg:", 1);
- daemon_log("\t$header", 1);
- daemon_log("msg to process:", 5);
- daemon_log("\t$msg", 5);
-
- my @targets = @{$msg_hash->{target}};
- my $len_targets = @targets;
- if ($len_targets == 0){
- daemon_log("ERROR: no target specified for msg $header", 1);
-
- } elsif ($len_targets == 1){
- # we have only one target symbol
-
- my $target = $targets[0];
- daemon_log("msg is for:", 7);
- daemon_log("\t$target", 7);
-
- if ($target eq $server_address) {
- # msg is for server
- if ($header eq 'new_passwd'){ &new_passwd($msg_hash)}
- elsif ($header eq 'here_i_am') { &here_i_am($msg_hash)}
- elsif ($header eq 'who_has') { &who_has($msg_hash) }
- elsif ($header eq 'who_has_i_do') { &who_has_i_do($msg_hash)}
- elsif ($header eq 'update_status') { &update_status($msg_hash) }
- elsif ($header eq 'get_load') { &execute_actions($msg_hash)}
- else { daemon_log("ERROR: no function assigned to this msg", 5) }
+ if( (!$msg) || (!$msg_hash) || (!$module)) {
+ daemon_log("$session_id DEBUG: Incoming message is not from an unknown host", 7);
+ }
-
- } elsif ($target eq "*") {
- # msg is for all clients
-
- my @target_addresses = keys(%$known_clients);
- foreach my $target_address (@target_addresses) {
- if ($target_address eq $source) { next; }
- $msg_hash->{target} = [$target_address];
- &send_msg_hash2address($msg_hash, $target_address);
- }
- } else {
- # msg is for one client
+ return ($msg, $msg_hash, $module);
+}
- if (exists $known_clients->{$target}) {
- # target is known
- &send_msg_hash2address($msg_hash, $target);
- } else {
- # target is not known
+sub create_ciphering {
+ my ($passwd) = @_;
+ if((!defined($passwd)) || length($passwd)==0) {
+ $passwd = "";
+ }
+ $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
+ my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
+ my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
+ $my_cipher->set_iv($iv);
+ return $my_cipher;
+}
- daemon_log("ERROR: target $target is not known in known_clients", 1);
- }
- }
- } else {
- # we have multiple target symbols
- my $target_string = join(", ", @targets);
- daemon_log("msg is for:", 7);
- daemon_log("\t$target_string", 7);
-
- my $target_address;
- foreach $target_address (@targets) {
- if (exists $known_clients->{$target_address}) {
- # target_address is known
+sub encrypt_msg {
+ my ($msg, $key) = @_;
+ my $my_cipher = &create_ciphering($key);
+ my $len;
+ {
+ use bytes;
+ $len= 16-length($msg)%16;
+ }
+ $msg = "\0"x($len).$msg;
+ $msg = $my_cipher->encrypt($msg);
+ chomp($msg = &encode_base64($msg));
+ # there are no newlines allowed inside msg
+ $msg=~ s/\n//g;
+ return $msg;
+}
- &send_msg_hash2address($msg_hash, $target_address);
- daemon_log("server forwards msg $header to client $target_address", 3);
- } else {
- # target is not known
- daemon_log("ERROR: target $target_address is not known in known_clients", 1);
+sub decrypt_msg {
+
+ my ($msg, $key) = @_ ;
+ $msg = &decode_base64($msg);
+ my $my_cipher = &create_ciphering($key);
+ $msg = $my_cipher->decrypt($msg);
+ $msg =~ s/\0*//g;
+ return $msg;
+}
+
+
+sub get_encrypt_key {
+ my ($target) = @_ ;
+ my $encrypt_key;
+ my $error = 0;
+
+ # target can be in known_server
+ if( not defined $encrypt_key ) {
+ my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
+ my $query_res = $known_server_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ if( $host_name ne $target ) {
+ next;
}
+ $encrypt_key = $hit->{hostkey};
+ last;
}
+ }
-
+ # target can be in known_client
+ if( not defined $encrypt_key ) {
+ my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
+ my $query_res = $known_clients_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ if( $host_name ne $target ) {
+ next;
+ }
+ $encrypt_key = $hit->{hostkey};
+ last;
+ }
}
- return;
+ return $encrypt_key;
}
$PeerAddr = $PeerAddr.":".$PeerPort;
}
my $socket;
- $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
- Porto => "tcp" ,
+ $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
+ Porto => "tcp",
Type => SOCK_STREAM,
Timeout => 5,
);
if(not defined $socket) {
return;
}
- daemon_log("open_socket:", 7);
- daemon_log("\t$PeerAddr", 7);
+# &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
return $socket;
}
#=== FUNCTION ================================================================
-# NAME: open_fifo
-# PARAMETERS: $fifo_path
-# RETURNS: 0: FIFO couldn"t be setup, 1: FIFO setup correctly
-# DESCRIPTION: creates a FIFO at $fifo_path
+# NAME: get_ip
+# PARAMETERS: interface name (i.e. eth0)
+# RETURNS: (ip address)
+# DESCRIPTION: Uses ioctl to get ip address directly from system.
#===============================================================================
-sub open_fifo {
- my ($fifo_path) = @_ ;
- if( -p $fifo_path ) {
- daemon_log("FIFO at $fifo_path already exists! Is being deleted!", 1);
- unlink($fifo_path);
- }
- POSIX::mkfifo($fifo_path, 0666) or die "can't mkfifo $fifo_path: $!";
- daemon_log( "FIFO started at $fifo_path", 1) ;
- return 1;
+sub get_ip {
+ my $ifreq= shift;
+ my $result= "";
+ my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
+ my $proto= getprotobyname('ip');
+
+ socket SOCKET, PF_INET, SOCK_DGRAM, $proto
+ or die "socket: $!";
+
+ if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
+ my ($if, $sin) = unpack 'a16 a16', $ifreq;
+ my ($port, $addr) = sockaddr_in $sin;
+ my $ip = inet_ntoa $addr;
+
+ if ($ip && length($ip) > 0) {
+ $result = $ip;
+ }
+ }
+
+ return $result;
}
-#=== FUNCTION ================================================================
-# NAME: read_from_socket
-# PARAMETERS: socket fh -
-# RETURNS: result string - readed characters from socket
-# DESCRIPTION: reads data from socket in 16 byte steps
-#===============================================================================
-sub read_from_socket {
- my ($socket) = @_;
- my $result = "";
+sub get_local_ip_for_remote_ip {
+ my $remote_ip= shift;
+ my $result="0.0.0.0";
+
+ if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
+ if($remote_ip eq "127.0.0.1") {
+ $result = "127.0.0.1";
+ } else {
+ my $PROC_NET_ROUTE= ('/proc/net/route');
+
+ open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
+ or die "Could not open $PROC_NET_ROUTE";
+
+ my @ifs = <PROC_NET_ROUTE>;
+
+ close(PROC_NET_ROUTE);
+
+ # Eat header line
+ shift @ifs;
+ chomp @ifs;
+ foreach my $line(@ifs) {
+ my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
+ my $destination;
+ my $mask;
+ my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
+ $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
+ ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
+ $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
+ if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
+ # destination matches route, save mac and exit
+ $result= &get_ip($Iface);
+ last;
+ }
+ }
+ }
+ } else {
+ daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
+ }
+ return $result;
+}
- $socket->blocking(1);
- $result = <$socket>;
- $socket->blocking(0);
- while ( my $char = <$socket> ) {
- if (not defined $char) { last }
- $result .= $char;
+sub send_msg_to_target {
+ my ($msg, $address, $encrypt_key, $msg_header, $session_id) = @_ ;
+ my $error = 0;
+ my $header;
+ my $new_status;
+ my $act_status;
+ my ($sql_statement, $res);
+
+ if( $msg_header ) {
+ $header = "'$msg_header'-";
+ } else {
+ $header = "";
}
- return $result;
-}
+ # Patch the source ip
+ if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
+ my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
+ $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
+ }
+ # encrypt xml msg
+ my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
-#=== FUNCTION ================================================================
-# NAME: create_xml_hash
-# PARAMETERS: header - string - message header (required)
-# source - string - where the message come from (required)
-# target - string - where the message should go to (required)
-# [header_value] - string - something usefull (optional)
-# RETURNS: hash - hash - nomen est omen
-# DESCRIPTION: creates a key-value hash, all values are stored in a array
-#===============================================================================
-sub create_xml_hash {
- my ($header, $source, $target, $header_value) = @_;
- my $hash = {
- header => [$header],
- source => [$source],
- target => [$target],
- $header => [$header_value],
- };
- #daemon_log("create_xml_hash:", 7),
- #chomp(my $tmp = Dumper $hash);
- #daemon_log("\t$tmp", 7);
- return $hash
-}
+ # opensocket
+ my $socket = &open_socket($address);
+ if( !$socket ) {
+ daemon_log("$session_id ERROR: cannot send ".$header."msg to $address , host not reachable", 1);
+ $error++;
+ }
+
+ if( $error == 0 ) {
+ # send xml msg
+ print $socket $crypted_msg."\n";
+ daemon_log("$session_id INFO: send ".$header."msg to $address", 5);
+ #daemon_log("DEBUG: message:\n$msg", 9);
+
+ }
-#=== FUNCTION ================================================================
-# NAME: create_xml_string
-# PARAMETERS: xml_hash - hash - hash from function create_xml_hash
-# RETURNS: xml_string - string - xml string representation of the hash
-# DESCRIPTION: transform the hash to a string using XML::Simple module
-#===============================================================================
-sub create_xml_string {
- my ($xml_hash) = @_ ;
- my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
- $xml_string =~ s/[\n]+//g;
- #daemon_log("create_xml_string:",7);
- #daemon_log("$xml_string\n", 7);
- return $xml_string;
-}
+ # close socket in any case
+ if( $socket ) {
+ close $socket;
+ }
+ if( $error > 0 ) { $new_status = "down"; }
+ else { $new_status = $msg_header; }
+
+
+ # known_clients
+ $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
+ $res = $known_clients_db->select_dbentry($sql_statement);
+ if( keys(%$res) > 0) {
+ $act_status = $res->{1}->{'status'};
+ if( $act_status eq "down" ) {
+ $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
+ $res = $known_clients_db->del_dbentry($sql_statement);
+ daemon_log("$session_id WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
+ } else {
+ $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
+ $res = $known_clients_db->update_dbentry($sql_statement);
+ if($new_status eq "down"){
+ daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
+ } else {
+ daemon_log("$session_id INFO: set '$address' from status '$act_status' to '$new_status'", 5);
+ }
+ }
+ }
-#=== FUNCTION ================================================================
-# NAME: add_content2xml_hash
-# PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
-# element - string - key for the hash
-# content - string - value for the hash
-# RETURNS: nothing
-# DESCRIPTION: add key-value pair to xml_ref, if key alread exists, then append value to list
-#===============================================================================
-sub add_content2xml_hash {
- my ($xml_ref, $element, $content) = @_;
- if(not exists $$xml_ref{$element} ) {
- $$xml_ref{$element} = [];
+ # known_server
+ $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
+ $res = $known_server_db->select_dbentry($sql_statement);
+ if( keys(%$res) > 0 ) {
+ $act_status = $res->{1}->{'status'};
+ if( $act_status eq "down" ) {
+ $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
+ $res = $known_server_db->del_dbentry($sql_statement);
+ daemon_log("$session_id WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
+ }
+ else {
+ $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
+ $res = $known_server_db->update_dbentry($sql_statement);
+ if($new_status eq "down"){
+ daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
+ }
+ else {
+ daemon_log("$session_id INFO: set '$address' from status '$act_status' to '$new_status'", 5);
+ }
+ }
}
- my $tmp = $$xml_ref{$element};
- push(@$tmp, $content);
- return;
+ return $error;
}
-#=== FUNCTION ================================================================
-# NAME: get_content_from_xml_hash
-# PARAMETERS: xml_ref - ref - reference of the xml hash
-# element - string - key of the value you want
-# RETURNS: value - string - if key is either header, target or source
-# value - list - for all other keys in xml hash
-# DESCRIPTION:
-#===============================================================================
-sub get_content_from_xml_hash {
- my ($xml_ref, $element) = @_ ;
- my $result = $xml_ref->{$element};
- if( $element eq "header" || $element eq "target" || $element eq "source") {
- return @$result[0];
+sub update_jobdb_status_for_send_msgs {
+ my ($answer, $error) = @_;
+ if( $answer =~ /<jobdb_id>(\d+)<\/jobdb_id>/ ) {
+ my $jobdb_id = $1;
+
+ # sending msg faild
+ if( $error ) {
+ if (not $answer =~ /<header>trigger_action_reinstall<\/header>/) {
+ my $sql_statement = "UPDATE $job_queue_tn ".
+ "SET status='error', result='can not deliver msg, please consult log file' ".
+ "WHERE id='$jobdb_id'";
+ my $res = $job_db->update_dbentry($sql_statement);
+ }
+
+ # sending msg was successful
+ } else {
+ my $sql_statement = "UPDATE $job_queue_tn ".
+ "SET status='done' ".
+ "WHERE id='$jobdb_id' AND status='processed'";
+ my $res = $job_db->update_dbentry($sql_statement);
+ }
}
- return @$result;
}
-
-#=== FUNCTION ================================================================
-# NAME: encrypt_msg
-# PARAMETERS: msg - string - message to encrypt
-# my_cipher - ref - reference to a Crypt::Rijndael object
-# RETURNS: crypted_msg - string - crypted message
-# DESCRIPTION: crypts the incoming message with the Crypt::Rijndael module
-#===============================================================================
-sub encrypt_msg {
- my ($msg, $my_cipher) = @_;
- if(not defined $my_cipher) { print "no cipher object\n"; }
- $msg = "\0"x(16-length($msg)%16).$msg;
- my $crypted_msg = $my_cipher->encrypt($msg);
- chomp($crypted_msg = &encode_base64($crypted_msg));
- return $crypted_msg;
+sub _start {
+ my ($kernel) = $_[KERNEL];
+ &trigger_db_loop($kernel);
+ $global_kernel = $kernel;
+ $kernel->yield('create_fai_server_db', $fai_server_tn );
+ $kernel->yield('create_fai_release_db', $fai_release_tn );
+ $kernel->sig(USR1 => "sig_handler");
+ $kernel->sig(USR2 => "create_packages_list_db");
}
-
-#=== FUNCTION ================================================================
-# NAME: decrypt_msg
-# PARAMETERS: crypted_msg - string - message to decrypt
-# my_cipher - ref - reference to a Crypt::Rijndael object
-# RETURNS: msg - string - decrypted message
-# DESCRIPTION: decrypts the incoming message with the Crypt::Rijndael module
-#===============================================================================
-sub decrypt_msg {
- my ($crypted_msg, $my_cipher) = @_ ;
- $crypted_msg = &decode_base64($crypted_msg);
- my $msg = $my_cipher->decrypt($crypted_msg);
- $msg =~ s/\0*//g;
- return $msg;
+sub sig_handler {
+ my ($kernel, $signal) = @_[KERNEL, ARG0] ;
+ daemon_log("0 INFO got signal '$signal'", 1);
+ $kernel->sig_handled();
+ return;
}
+sub next_task {
+ my ($session, $heap) = @_[SESSION, HEAP];
-#=== FUNCTION ================================================================
-# NAME: create_ciphering
-# PARAMETERS: passwd - string - used to create ciphering
-# RETURNS: cipher - object
-# DESCRIPTION: creates a Crypt::Rijndael::MODE_CBC object with passwd as key
-#===============================================================================
-sub create_ciphering {
- my ($passwd) = @_;
- $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
- my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
+ while ( keys( %{ $heap->{task} } ) < $max_children ) {
+ my $next_task = shift @tasks;
+ last unless defined $next_task;
- #daemon_log("iv: $iv", 7);
- #daemon_log("key: $passwd", 7);
- my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
- $my_cipher->set_iv($iv);
- return $my_cipher;
-}
+ my $task = POE::Wheel::Run->new(
+ Program => sub { process_task($session, $heap, $next_task) },
+ StdioFilter => POE::Filter::Reference->new(),
+ StdoutEvent => "task_result",
+ StderrEvent => "task_debug",
+ CloseEvent => "task_done",
+ );
+ $heap->{task}->{ $task->ID } = $task;
+ }
+}
-#=== FUNCTION ================================================================
-# NAME: send_msg_hash2address
-# PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
-# PeerAddr string - socket address to send msg
-# PeerPort string - socket port, if not included in socket address
-# RETURNS: nothing
-# DESCRIPTION: ????
-#===============================================================================
-sub send_msg_hash2address {
- my ($msg_hash, $address, $passwd) = @_ ;
+sub handle_task_result {
+ my ($kernel, $heap, $result) = @_[KERNEL, HEAP, ARG0];
+ my $client_answer = $result->{'answer'};
+ if( $client_answer =~ s/session_id=(\d+)$// ) {
+ my $session_id = $1;
+ if( defined $session_id ) {
+ my $session_reference = $kernel->ID_id_to_session($session_id);
+ if( defined $session_reference ) {
+ $heap = $session_reference->get_heap();
+ }
+ }
- # fetch header for logging
- my $header = &get_content_from_xml_hash($msg_hash, "header");
-
- # generate xml string
- my $msg_xml = &create_xml_string($msg_hash);
-
- # fetch the appropriated passwd from hash
- if(not defined $passwd) {
- if(exists $known_daemons->{$address}) {
- $passwd = $known_daemons->{$address}->{passwd};
- } elsif(exists $known_clients->{$address}) {
- $passwd = $known_clients->{$address}->{passwd};
-
- } else {
- daemon_log("$address not known, neither as server nor as client", 1);
- return 1;
+ if(exists $heap->{'client'}) {
+ $heap->{'client'}->put($client_answer);
}
}
-
- # create ciphering object
- my $act_cipher = &create_ciphering($passwd);
-
- # encrypt xml msg
- my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
-
- # opensocket
- my $socket = &open_socket($address);
- if(not defined $socket){
- daemon_log( "cannot send '$header'-msg to $address , server not reachable", 5);
+ $kernel->sig(CHLD => "child_reap");
+}
- if (exists $known_clients->{$address}) {
- if ($known_clients->{$address}->{status} eq "down") {
- # if status of not reachable client is already 'down', then delete client from known_clients
- &clean_up_known_clients($address);
+sub handle_task_debug {
+ my $result = $_[ARG0];
+ print STDERR "$result\n";
+}
- } else {
- # update status to 'down'
- &update_known_clients(hostname=>$address, status=>"down");
+sub handle_task_done {
+ my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
+ delete $heap->{task}->{$task_id};
+ $kernel->yield("next_task");
+}
- }
+sub process_task {
+ no strict "refs";
+ my ($session, $heap, $input) = @_;
+ my $session_id = $session->ID;
+ my ($msg, $msg_hash, $module);
+ my $error = 0;
+ my $answer_l;
+ my ($answer_header, @answer_target_l, $answer_source);
+ my $client_answer = "";
+
+ daemon_log("", 5);
+ daemon_log("$session_id INFO: Incoming msg with session ID $session_id from '".$heap->{'remote_ip'}."'", 5);
+ daemon_log("$session_id DEBUG: Incoming msg:\n$input", 9);
+
+ ####################
+ # check incoming msg
+ # msg is from a new client or gosa
+ ($msg, $msg_hash, $module) = &input_from_unknown_host($input, $session_id);
+ # msg is from a gosa-si-server or gosa-si-bus
+ if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
+ ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'}, $session_id);
+ }
+ # msg is from a gosa-si-client
+ if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
+ ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'}, $session_id);
+ }
+ # an error occurred
+ if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
+ # if an incoming msg could not be decrypted (maybe a wrong key), send client a ping. If the client
+ # could not understand a msg from its server the client cause a re-registering process
+ daemon_log("$session_id INFO cannot understand incoming msg, send 'ping'-msg to all host with ip '".$heap->{remote_ip}."' to cause a re-registering of the client if necessary", 5);
+ my $sql_statement = "SELECT * FROM $main::known_clients_tn WHERE (hostname LIKE '".$heap->{'remote_ip'}."%')";
+ my $query_res = $known_clients_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{'hostname'};
+ my $host_key = $hit->{'hostkey'};
+ my $ping_msg = "<xml> <header>gosa_ping</header> <source>$server_address</source> <target>$host_name</target></xml>";
+ my $error = &send_msg_to_target($ping_msg, $host_name, $host_key, "gosa_ping", $session_id);
+ &update_jobdb_status_for_send_msgs($ping_msg, $error);
}
- return 1;
+ $error++;
}
-
- # send xml msg
- print $socket $crypted_msg."\n";
-
- close $socket;
- daemon_log("send '$header'-msg to $address", 1);
+ ######################
+ # process incoming msg
+ if( $error == 0) {
+ daemon_log("$session_id INFO: Incoming msg with header '".@{$msg_hash->{'header'}}[0].
+ "' from '".$heap->{'remote_ip'}."'", 5);
+ daemon_log("$session_id DEBUG: Processing module ".$module, 7);
+ $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
+
+ if ( 0 < @{$answer_l} ) {
+ my $answer_str = join("\n", @{$answer_l});
+ daemon_log("$session_id DEBUG: $module: Got answer from module: \n".$answer_str,8);
+ }
+ }
+ if( !$answer_l ) { $error++ };
- daemon_log("$msg_xml", 5);
+ ########
+ # answer
+ if( $error == 0 ) {
- #daemon_log("crypted message:",7);
- #daemon_log("\t$crypted_msg", 7);
+ foreach my $answer ( @{$answer_l} ) {
+ # for each answer in answer list
+
+ # check outgoing msg to xml validity
+ my $answer_hash = &check_outgoing_xml_validity($answer);
+ if( not defined $answer_hash ) {
+ next;
+ }
+
+ $answer_header = @{$answer_hash->{'header'}}[0];
+ @answer_target_l = @{$answer_hash->{'target'}};
+ $answer_source = @{$answer_hash->{'source'}}[0];
+
+ # deliver msg to all targets
+ foreach my $answer_target ( @answer_target_l ) {
+
+ # targets of msg are all gosa-si-clients in known_clients_db
+ if( $answer_target eq "*" ) {
+ # answer is for all clients
+ my $sql_statement= "SELECT * FROM known_clients";
+ my $query_res = $known_clients_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ my $host_key = $hit->{hostkey};
+ my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ }
+ }
- # update status of client in known_clients with last send msg
- if(exists $known_daemons->{$address}) {
- #&update_known_daemons();
- } elsif(exists $known_clients->{$address}) {
- &update_known_clients(hostname=>$address, status=>$header);
- }
+ # targets of msg are all gosa-si-server in known_server_db
+ elsif( $answer_target eq "KNOWN_SERVER" ) {
+ # answer is for all server in known_server
+ my $sql_statement= "SELECT * FROM known_server";
+ my $query_res = $known_server_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ my $host_key = $hit->{hostkey};
+ $answer =~ s/KNOWN_SERVER/$host_name/g;
+ my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ }
+ }
- return 0;
-}
+ # target of msg is GOsa
+ elsif( $answer_target eq "GOSA" ) {
+ my $session_id = ($1) if $answer =~ /<session_id>(\d+?)<\/session_id>/;
+ my $add_on = "";
+ if( defined $session_id ) {
+ $add_on = ".session_id=$session_id";
+ }
+ # answer is for GOSA and has to returned to connected client
+ my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
+ $client_answer = $gosa_answer.$add_on;
+ }
+ # target of msg is job queue at this host
+ elsif( $answer_target eq "JOBDB") {
+ $answer =~ /<header>(\S+)<\/header>/;
+ my $header;
+ if( defined $1 ) { $header = $1; }
+ my $error = &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header, $session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ }
-#=== FUNCTION ================================================================
-# NAME: send_msg_hash2bus
-# PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
-# RETURNS: nothing
-# DESCRIPTION: ????
-#===============================================================================
-sub send_msg_hash2bus {
- my($msg_hash) = @_;
+ # target of msg is a mac address
+ elsif( $answer_target =~ /^([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$/i ) {
+ daemon_log("$session_id INFO: target is mac address '$answer_target', looking for host in known_clients", 5);
+ my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$answer_target'";
+ my $query_res = $known_clients_db->select_dbentry( $sql_statement );
+ my $found_ip_flag = 0;
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $host_name = $hit->{hostname};
+ my $host_key = $hit->{hostkey};
+ $answer =~ s/$answer_target/$host_name/g;
+ daemon_log("$session_id INFO: found host '$host_name', associated to '$answer_target'", 5);
+ my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ $found_ip_flag++ ;
+ }
+ if( $found_ip_flag == 0) {
+ daemon_log("$session_id WARNING: no host found in known_clients with mac address '$answer_target'", 3);
+ if( $bus_activ eq "true" ) {
+ daemon_log("$session_id INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
+ my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
+ my $query_res = $known_server_db->select_dbentry( $sql_statement );
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $bus_address = $hit->{hostname};
+ my $bus_key = $hit->{hostkey};
+ my $error = &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header, $session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ last;
+ }
+ }
- # fetch header for logging
- my $header = &get_content_from_xml_hash($msg_hash, "header");
+ }
- # generate xml string
- my $msg_xml = &create_xml_string($msg_hash);
+ # answer is for one specific host
+ } else {
+ # get encrypt_key
+ my $encrypt_key = &get_encrypt_key($answer_target);
+ if( not defined $encrypt_key ) {
+ # unknown target, forward msg to bus
+ daemon_log("$session_id WARNING: unknown target '$answer_target'", 3);
+ if( $bus_activ eq "true" ) {
+ daemon_log("$session_id INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
+ my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
+ my $query_res = $known_server_db->select_dbentry( $sql_statement );
+ my $res_length = keys( %{$query_res} );
+ if( $res_length == 0 ){
+ daemon_log("$session_id WARNING: send '$answer_header' to '$bus_address' failed, ".
+ "no bus found in known_server", 3);
+ }
+ else {
+ while( my ($hit_num, $hit) = each %{ $query_res } ) {
+ my $bus_key = $hit->{hostkey};
+ my $error = &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header,$session_id );
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ }
+ }
+ }
+ next;
+ }
+ my $error = &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header,$session_id);
+ &update_jobdb_status_for_send_msgs($answer, $error);
+ }
+ }
+ }
+ }
- # encrypt xml msg
- my $crypted_msg = &encrypt_msg($msg_xml, $bus_cipher);
+ my $filter = POE::Filter::Reference->new();
+ my %result = (
+ status => "seems ok to me",
+ answer => $client_answer,
+ );
- # open socket
- my $socket = &open_socket($bus_address);
- if(not defined $socket){
- daemon_log( "cannot send '$header'-msg to $bus_address , bus not reachable", 5);
- return;
- }
-
- # send xml msg
- print $socket $crypted_msg."\n";
-
- close $socket;
-
+ my $output = $filter->put( [ \%result ] );
+ print @$output;
- daemon_log("send '$header'-msg to bus", 1);
- daemon_log("$msg_xml", 5);
- #daemon_log("crypted msg:",7);
- #daemon_log("\t$crypted_msg", 7);
- return;
}
+sub trigger_db_loop {
+ my ($kernel) = @_ ;
+ $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
+ $kernel->delay_set('watch_for_done_jobs', $job_queue_loop_delay);
+}
+sub watch_for_done_jobs {
+ my ($kernel,$heap) = @_[KERNEL, HEAP];
+ my $sql_statement = "SELECT * FROM ".$job_queue_tn.
+ " WHERE status='done'";
+ my $res = $job_db->select_dbentry( $sql_statement );
+ while( my ($id, $hit) = each %{$res} ) {
+ my $jobdb_id = $hit->{id};
+ my $sql_statement = "DELETE FROM $job_queue_tn WHERE id='$jobdb_id'";
+ my $res = $job_db->del_dbentry($sql_statement);
+ }
+ $kernel->delay_set('watch_for_done_jobs',$job_queue_loop_delay);
+}
-##=== FUNCTION ================================================================
-## NAME: new_passwd
-## PARAMETERS: msg_hash - ref - hash from function create_xml_hash
-## RETURNS: nothing
-## DESCRIPTION: process this incoming message
-##===============================================================================
-#sub new_passwd {
-# my ($msg_hash) = @_;
-#
-# my $source = &get_content_from_xml_hash($msg_hash, "source");
-# my $passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
-#
-# if (exists $known_daemons->{$source}) {
-# &add_content2known_daemons(hostname=>$source, status=>"new_passwd", passwd=>$passwd);
-# $bus_cipher = &create_ciphering($passwd);
-# my $hash = &create_xml_hash("confirm_new_passwd", "$server_ip:$server_port", "$source");
-# &send_msg_hash2address($hash, $source);
-#
-# } elsif (exists $known_clients->{$source}) {
-# &add_content2known_clients(hostname=>$source, status=>"new_passwd", passwd=>$passwd);
-#
-# } else {
-# daemon_log("ERROR: $source not known, neither in known_daemons nor in known_clients", 1)
-# }
-#
-# return;
-#}
-
-
-##=== FUNCTION ================================================================
-## NAME: make ping
-## PARAMETERS: address - string - address which should be pinged
-## RETURNS: nothing
-## DESCRIPTION: send ping message to address
-##===============================================================================
-#sub make_ping {
-# my ($msg_hash) = @_;
-#
-# my $source = &get_content_from_xml_hash($msg_hash, "source");
-# my $target = &get_content_from_xml_hash($msg_hash, "target");
-#
-# print "make_ping:$source\n";
-# my $out_hash = &create_xml_hash("ping", $target, $source);
-# &send_msg_hash2address($out_hash, $source);
-# return;
-#}
-
-
-##=== FUNCTION ================================================================
-## NAME: got_ping
-## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
-## RETURNS: nothing
-## DESCRIPTION: process this incoming message
-##===============================================================================
-#sub got_ping {
-# my ($msg_hash) = @_;
-#
-# my $source = &get_content_from_xml_hash($msg_hash, 'source');
-# my $target = &get_content_from_xml_hash($msg_hash, 'target');
-# my $header = &get_content_from_xml_hash($msg_hash, 'header');
-#
-# if(exists $known_daemons->{$source}) {
-# &add_content2known_daemons(hostname=>$source, status=>$header);
-# } else {
-# &add_content2known_clients(hostname=>$source, status=>$header);
-# }
-#
-# return;
-#}
-
-
-##=== FUNCTION ================================================================
-## NAME: here_i_am
-## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
-## RETURNS: nothing
-## DESCRIPTION: process this incoming message
-##===============================================================================
-#sub here_i_am {
-# my ($msg_hash) = @_;
-#
-# my $source = &get_content_from_xml_hash($msg_hash, "source");
-# my $mac_address = (&get_content_from_xml_hash($msg_hash, "mac_address"))[0];
-# my $out_hash;
-#
-# # number of known clients
-# my $nu_clients = keys %$known_clients;
-#
-# # check wether client address or mac address is already known
-# if (exists $known_clients->{$source}) {
-# daemon_log("WARNING: $source is already known as a client", 1);
-# daemon_log("WARNING: values for $source are being overwritten", 1);
-# $nu_clients --;
-# }
-#
-# # number of actual activ clients
-# my $act_nu_clients = $nu_clients;
-#
-# daemon_log("number of actual activ clients: $act_nu_clients", 5);
-# daemon_log("number of maximal allowed clients: $max_clients", 5);
-#
-# if($max_clients <= $act_nu_clients) {
-# my $out_hash = &create_xml_hash("denied", $server_address, $source);
-# &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
-# my $passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
-# &send_msg_hash2address($out_hash, $source, $passwd);
-# return;
-# }
-#
-# # new client accepted
-# my $new_passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
-#
-# # create known_daemons entry
-# my $events = (&get_content_from_xml_hash($msg_hash, "events"))[0];
-# &create_known_client($source);
-# &add_content2known_clients(hostname=>$source, events=>$events, mac_address=>$mac_address,
-# status=>"registered", passwd=>$new_passwd);
-#
-# # return acknowledgement to client
-# $out_hash = &create_xml_hash("registered", $server_address, $source);
-# &send_msg_hash2address($out_hash, $source);
-#
-# # notify registered client to bus
-# $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
-# &send_msg_hash2bus($out_hash);
-#
-# # give the new client his ldap config
-# &new_ldap_config($source);
-#
-# return;
-#}
+sub watch_for_new_jobs {
+ my ($kernel,$heap) = @_[KERNEL, HEAP];
+
+ # check gosa job queue for jobs with executable timestamp
+ my $timestamp = &get_time();
+ my $sql_statement = "SELECT * FROM $job_queue_tn WHERE status='waiting' AND (CAST (timestamp AS INTEGER) + 120) < $timestamp ORDER BY timestamp";
+ my $res = $job_db->exec_statement( $sql_statement );
+
+ # Merge all new jobs that would do the same actions
+ my @drops;
+ my $hits;
+ foreach my $hit (reverse @{$res} ) {
+ my $macaddress= lc @{$hit}[8];
+ my $headertag= @{$hit}[5];
+ if(defined($hits->{$macaddress}->{$headertag})) {
+ push @drops, "DELETE FROM $job_queue_tn WHERE id = '$hits->{$macaddress}->{$headertag}[0]'";
+ }
+ $hits->{$macaddress}->{$headertag}= $hit;
+ }
+
+ # Delete new jobs with a matching job in state 'processing'
+ foreach my $macaddress (keys %{$hits}) {
+ foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
+ my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
+ my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND headertag='$jobdb_headertag' AND status='processing'";
+ my $res = $job_db->exec_statement( $sql_statement );
+ foreach my $hit (@{$res}) {
+ push @drops, "DELETE FROM $job_queue_tn WHERE id = '$jobdb_id'";
+ }
+ }
+ }
+
+ # Commit deletion
+ $job_db->exec_statementlist(\@drops);
+
+ # Look for new jobs that could be executed
+ foreach my $macaddress (keys %{$hits}) {
+
+ # Look if there is an executing job
+ my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND status='processing'";
+ my $res = $job_db->exec_statement( $sql_statement );
+
+ # Skip new jobs for host if there is a processing job
+ if(defined($res) and defined @{$res}[0]) {
+ next;
+ }
+
+ foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
+ my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
+ my $job_msg = @{$hits->{$macaddress}->{$jobdb_headertag}}[7];
+
+ daemon_log("J DEBUG: its time to execute $job_msg", 7);
+ my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$macaddress'";
+ my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
+
+ # expect macaddress is unique!!!!!!
+ my $target = $res_hash->{1}->{hostname};
+
+ # change header
+ $job_msg =~ s/<header>job_/<header>gosa_/;
+
+ # add sqlite_id
+ $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
+
+ $job_msg =~ /<header>(\S+)<\/header>/;
+ my $header = $1 ;
+ my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header, "J");
+
+ # update status in job queue to 'processing'
+ $sql_statement = "UPDATE $job_queue_tn SET status='processing' WHERE id='$jobdb_id'";
+ my $res = $job_db->update_dbentry($sql_statement);
+
+ # We don't want parallel processing
+ last;
+ }
+ }
+
+ $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
+}
-#=== FUNCTION ================================================================
-# NAME: who_has
-# PARAMETERS: msg_hash - hash - hash from function create_xml_hash
-# RETURNS: nothing
-# DESCRIPTION: process this incoming message
-#===============================================================================
-#sub who_has {
-# my ($msg_hash) = @_ ;
-#
-# # what is your search pattern
-# my $search_pattern = (&get_content_from_xml_hash($msg_hash, "who_has"))[0];
-# my $search_element = (&get_content_from_xml_hash($msg_hash, $search_pattern))[0];
-# daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
-#
-# # scanning known_clients for search_pattern
-# my @host_addresses = keys %$known_clients;
-# my $known_clients_entries = length @host_addresses;
-# my $host_address;
-# foreach my $host (@host_addresses) {
-# my $client_element = $known_clients->{$host}->{$search_pattern};
-# if ($search_element eq $client_element) {
-# $host_address = $host;
-# last;
-# }
-# }
-#
-# # search was successful
-# if (defined $host_address) {
-# my $source = @{$msg_hash->{source}}[0];
-# my $out_msg = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
-# &add_content2xml_hash($out_msg, "mac_address", $search_element);
-# &send_msg_hash2address($out_msg, $bus_address);
-# }
-# return;
-#}
-
-
-#sub who_has_i_do {
-# my ($msg_hash) = @_ ;
-# my $header = &get_content_from_xml_hash($msg_hash, "header");
-# my $source = &get_content_from_xml_hash($msg_hash, "source");
-# my $search_param = (&get_content_from_xml_hash($msg_hash, $header))[0];
-# my $search_value = (&get_content_from_xml_hash($msg_hash, $search_param))[0];
-# print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
-#}
+sub get_ldap_handle {
+ my ($session_id) = @_;
+ my $heap;
+ my $ldap_handle;
+
+ if (not defined $session_id ) { $session_id = 0 };
+
+ if ($session_id == 0) {
+ daemon_log("$session_id DEBUG: get_ldap_handle invoked without a session_id, create a new ldap_handle", 7);
+ $ldap_handle = Net::LDAP->new( $ldap_uri );
+ $ldap_handle->bind($ldap_admin_dn, password => $ldap_admin_password);
+
+ } else {
+ my $session_reference = $global_kernel->ID_id_to_session($session_id);
+ if( defined $session_reference ) {
+ $heap = $session_reference->get_heap();
+ }
+
+ if (not defined $heap) {
+ daemon_log("$session_id DEBUG: cannot get heap for session_id '$session_id'", 7);
+ return;
+ }
+
+ # TODO: This "if" is nonsense, because it doesn't prove that the
+ # used handle is still valid - or if we've to reconnect...
+ #if (not exists $heap->{ldap_handle}) {
+ $ldap_handle = Net::LDAP->new( $ldap_uri );
+ $ldap_handle->bind($ldap_admin_dn, password => $ldap_admin_password);
+ $heap->{ldap_handle} = $ldap_handle;
+ #}
+ }
+ return $ldap_handle;
+}
-#=== FUNCTION ================================================================
-# NAME: update_status
-# PARAMETERS: msg_hash - hash - hash from function create_xml_hash
-# RETURNS: nothing
-# DESCRIPTION: process this incoming message
-#===============================================================================
-#sub update_status {
-# my ($msg_hash) = @_;
-# my $header = &get_content_from_xml_hash($msg_hash, "header");
-# my $source = &get_content_from_xml_hash($msg_hash, "source");
-# my $new_status = (&get_content_from_xml_hash($msg_hash, "update_status"))[0];
-#
-# # find the source
-# my $act_known_hash;
-# if (exists $known_daemons->{$source}) {
-#
-# &add_content2known_daemons(hostname=>$source, status=>$new_status);
-# } elsif (exists $known_clients->{$source}) {
-# &update_known_clients(hostname=>$source, status=>$new_status);
-# #&add_content2known_clients(hostname=>$source, status=>$new_status);
-# } else {
-# daemon_log("ERROR: got $header-msg, but cannot find $source in my hashes, unable to update status", 1);
-# return;
-# }
-#
-# return;
-#}
-
-
-##=== FUNCTION ================================================================
-## NAME: new_ldap_config
-## PARAMETERS: address - string - ip address and port of a host
-## RETURNS: nothing
-## DESCRIPTION: send to address the ldap configuration found for dn gotoLdapServer
-##===============================================================================
-#sub new_ldap_config {
-# my ($address) = @_ ;
-#
-# if (not exists $known_clients->{$address}) {
-# daemon_log("ERROR: $address does not exist in known_clients, cannot send him his ldap config", 1);
-# return;
-# }
-#
-# my $mac_address = $known_clients->{$address}->{"mac_address"};
-# if (not defined $mac_address) {
-# daemon_log("ERROR: no mac address found for client $address", 1);
-# return;
-# }
-#
-# # fetch dn
-# my $goHard_cmd = "ldapsearch -x '(&(objectClass=goHard)(macAddress=00:11:22:33:44:57))' dn gotoLdapServer";
-# my $dn;
-# my @gotoLdapServer;
-# open (PIPE, "$goHard_cmd 2>&1 |");
-# while(<PIPE>) {
-# chomp $_;
-# # If it's a comment, goto next
-# if ($_ =~ m/^[#]/) { next;}
-# if ($_ =~ m/^dn: ([\S]+?)$/) {
-# $dn = $1;
-# } elsif ($_ =~ m/^gotoLdapServer: ([\S]+?)$/) {
-# push(@gotoLdapServer, $1);
-# }
-# }
-# close(PIPE);
-#
-# # no dn found
-# if (not defined $dn) {
-# daemon_log("ERROR: no dn arose from command: $goHard_cmd", 1);
-# return;
-# }
-#
-# # no gotoLdapServer found
-# my $gosaGroupOfNames_cmd = "ldapsearch -x '(&(objectClass=gosaGroupOfNames)(member=$dn))' gotoLdapServer";
-# if (@gotoLdapServer == 0) {
-# open (PIPE, "$gosaGroupOfNames_cmd 2>&1 |");
-# while(<PIPE>) {
-# chomp $_;
-# if ($_ =~ m/^[#]/) { next; }
-# if ($_ =~ m/^gotoLdapServer: ([\S]+?)$/) {
-# push(@gotoLdapServer, $1);
-# }
-# }
-# close(PIPE);
-# }
-#
-# # still no gotoLdapServer found
-# if (@gotoLdapServer == 0) {
-# daemon_log("ERROR: cannot find gotoLdapServer entry in command: $gosaGroupOfNames_cmd", 1);
-# return;
-# }
-#
-# # sort @gotoLdapServer and then split of ranking
-# my @sorted_gotoLdapServer = sort(@gotoLdapServer);
-# @gotoLdapServer = reverse(@sorted_gotoLdapServer);
-# foreach (@gotoLdapServer) {
-# $_ =~ s/^\d://;
-# }
-#
-# my $t = join(" ", @gotoLdapServer);
-#
-# my $out_hash = &create_xml_hash("new_ldap_config", $server_address, $address);
-# map(&add_content2xml_hash($out_hash, "new_ldap_config", $_), @gotoLdapServer);
-# &send_msg_hash2address($out_hash, $address);
-#
-# return;
-#}
-
-
-##=== FUNCTION ================================================================
-## NAME: execute_actions
-## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
-## RETURNS: nothing
-## DESCRIPTION: invokes the script specified in msg_hash which is located under
-## /etc/gosad/actions
-##===============================================================================
-#sub execute_actions {
-# my ($msg_hash) = @_ ;
-# my $configdir= '/etc/gosad/actions/';
-# my $result;
-#
-# my $header = &get_content_from_xml_hash($msg_hash, 'header');
-# my $source = &get_content_from_xml_hash($msg_hash, 'source');
-# my $target = &get_content_from_xml_hash($msg_hash, 'target');
-#
-#
-# if((not defined $source)
-# && (not defined $target)
-# && (not defined $header)) {
-# daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
-# } else {
-# my $parameters="";
-# my @params = &get_content_from_xml_hash($msg_hash, $header);
-# my $params = join(", ", @params);
-# daemon_log("execute_actions: got parameters: $params", 5);
-#
-# if (@params) {
-# foreach my $param (@params) {
-# my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
-# daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
-# $parameters.= " ".$param_value;
-# }
-# }
-#
-# my $cmd= $configdir.$header."$parameters";
-# daemon_log("execute_actions: executing cmd: $cmd", 7);
-# $result= "";
-# open(PIPE, "$cmd 2>&1 |");
-# while(<PIPE>) {
-# $result.=$_;
-# }
-# close(PIPE);
-# }
-#
-# # process the event result
-#
-#
-# return;
-#}
+sub change_fai_state {
+ my ($st, $targets, $session_id) = @_;
+ $session_id = 0 if not defined $session_id;
+ # Set FAI state to localboot
+ my %mapActions= (
+ reboot => '',
+ update => 'softupdate',
+ localboot => 'localboot',
+ reinstall => 'install',
+ rescan => '',
+ wake => '',
+ memcheck => 'memcheck',
+ sysinfo => 'sysinfo',
+ install => 'install',
+ );
+ # Return if this is unknown
+ if (!exists $mapActions{ $st }){
+ daemon_log("$session_id ERROR: unknown action '$st', can not translate ot FAIstate", 1);
+ return;
+ }
-#=== FUNCTION ================================================================
-# NAME: print_known_daemons
-# PARAMETERS: nothing
-# RETURNS: nothing
-# DESCRIPTION: nomen est omen
-#===============================================================================
-sub print_known_daemons {
- my ($tmp) = @_ ;
- print "####################################\n";
- print "# status of known_daemons\n";
- $shmda->shlock(LOCK_EX);
- my @hosts = keys %$known_daemons;
- foreach my $host (@hosts) {
- my $status = $known_daemons->{$host}->{status} ;
- my $passwd = $known_daemons->{$host}->{passwd};
- my $timestamp = $known_daemons->{$host}->{timestamp};
- print "$host\n";
- print "\tstatus: $status\n";
- print "\tpasswd: $passwd\n";
- print "\ttimestamp: $timestamp\n";
+ my $state= $mapActions{ $st };
+
+ my $ldap_handle = &get_ldap_handle($session_id);
+ if( defined($ldap_handle) ) {
+
+ # Build search filter for hosts
+ my $search= "(&(objectClass=GOhard)";
+ foreach (@{$targets}){
+ $search.= "(macAddress=$_)";
+ }
+ $search.= ")";
+
+ # If there's any host inside of the search string, procress them
+ if (!($search =~ /macAddress/)){
+ daemon_log("$session_id ERROR: no macAddress found in filter statement for LDAP search: '$search'", 1);
+ return;
+ }
+
+ # Perform search for Unit Tag
+ my $mesg = $ldap_handle->search(
+ base => $ldap_base,
+ scope => 'sub',
+ attrs => ['dn', 'FAIstate', 'objectClass'],
+ filter => "$search"
+ );
+
+ if ($mesg->count) {
+ my @entries = $mesg->entries;
+ foreach my $entry (@entries) {
+ # Only modify entry if it is not set to '$state'
+ if ($entry->get_value("FAIstate") ne "$state"){
+ daemon_log("$session_id INFO: Setting FAIstate to '$state' for ".$entry->dn, 5);
+ my $result;
+ my %tmp = map { $_ => 1 } $entry->get_value("objectClass");
+ if (exists $tmp{'FAIobject'}){
+ if ($state eq ''){
+ $result= $ldap_handle->modify($entry->dn, changes => [
+ delete => [ FAIstate => [] ] ]);
+ } else {
+ $result= $ldap_handle->modify($entry->dn, changes => [
+ replace => [ FAIstate => $state ] ]);
+ }
+ } elsif ($state ne ''){
+ $result= $ldap_handle->modify($entry->dn, changes => [
+ add => [ objectClass => 'FAIobject' ],
+ add => [ FAIstate => $state ] ]);
+ }
+
+ # Errors?
+ if ($result->code){
+ daemon_log("$session_id Error: Setting FAIstate to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
+ }
+ } else {
+ daemon_log("$session_id DEBUG FAIstate at host '".$entry->dn."' already at state '$st'", 7);
+ }
+ }
+ }
+ # if no ldap handle defined
+ } else {
+ daemon_log("$session_id ERROR: no LDAP handle defined for update FAIstate", 1);
}
- $shmda->shunlock(LOCK_EX);
- print "####################################\n";
- return;
+
}
-#=== FUNCTION ================================================================
-# NAME: create_known_daemon
-# PARAMETERS: hostname - string - key for the hash known_daemons
-# RETURNS: nothing
-# DESCRIPTION: creates a dummy entry for hostname in known_daemons
-#===============================================================================
-sub create_known_daemon {
- my ($hostname) = @_;
- $shmda->shlock(LOCK_EX);
- $known_daemons->{$hostname} = {};
- $known_daemons->{$hostname}->{status} = "none";
- $known_daemons->{$hostname}->{passwd} = "none";
- $known_daemons->{$hostname}->{timestamp} = "none";
- $shmda->shunlock(LOCK_EX);
- return;
-}
+sub change_goto_state {
+ my ($st, $targets, $session_id) = @_;
+ $session_id = 0 if not defined $session_id;
+ # Switch on or off?
+ my $state= $st eq 'active' ? 'active': 'locked';
-#=== FUNCTION ================================================================
-# NAME: add_content2known_daemons
-# PARAMETERS: hostname - string - ip address and port of host (required)
-# status - string - (optional)
-# passwd - string - (optional)
-# mac_address - string - mac address of host (optional)
-# RETURNS: nothing
-# DESCRIPTION: nome est omen and updates each time the timestamp of hostname
-#===============================================================================
-sub add_content2known_daemons {
- my $arg = {
- hostname => undef, status => undef, passwd => undef,
- mac_address => undef, events => undef,
- @_ };
- my $hostname = $arg->{hostname};
- my $status = $arg->{status};
- my $passwd = $arg->{passwd};
- my $mac_address = $arg->{mac_address};
- my $events = $arg->{events};
-
- if (not defined $hostname) {
- daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
+ my $ldap_handle = &get_ldap_handle($session_id);
+ if( defined($ldap_handle) ) {
+
+ # Build search filter for hosts
+ my $search= "(&(objectClass=GOhard)";
+ foreach (@{$targets}){
+ $search.= "(macAddress=$_)";
+ }
+ $search.= ")";
+
+ # If there's any host inside of the search string, procress them
+ if (!($search =~ /macAddress/)){
return;
+ }
+
+ # Perform search for Unit Tag
+ my $mesg = $ldap_handle->search(
+ base => $ldap_base,
+ scope => 'sub',
+ attrs => ['dn', 'gotoMode'],
+ filter => "$search"
+ );
+
+ if ($mesg->count) {
+ my @entries = $mesg->entries;
+ foreach my $entry (@entries) {
+
+ # Only modify entry if it is not set to '$state'
+ if ($entry->get_value("gotoMode") ne $state){
+
+ daemon_log("$session_id INFO: Setting gotoMode to '$state' for ".$entry->dn, 5);
+ my $result;
+ $result= $ldap_handle->modify($entry->dn, changes => [
+ replace => [ gotoMode => $state ] ]);
+
+ # Errors?
+ if ($result->code){
+ &daemon_log("$session_id Error: Setting gotoMode to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
+ }
+
+ }
+ }
+ }
+
}
+}
- my ($seconds, $minutes, $hours, $monthday, $month,
- $year, $weekday, $yearday, $sommertime) = localtime(time);
- $hours = $hours < 10 ? $hours = "0".$hours : $hours;
- $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
- $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
- $month+=1;
- $month = $month < 10 ? $month = "0".$month : $month;
- $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
- $year+=1900;
- my $t = "$year$month$monthday$hours$minutes$seconds";
+
+sub create_fai_server_db {
+ my ($table_name, $kernel) = @_;
+ my $result;
+ my $ldap_handle = &get_ldap_handle();
+ if(defined($ldap_handle)) {
+ daemon_log("INFO: create_fai_server_db: start", 5);
+ my $mesg= $ldap_handle->search(
+ base => $ldap_base,
+ scope => 'sub',
+ attrs => ['FAIrepository', 'gosaUnitTag'],
+ filter => "(&(FAIrepository=*)(objectClass=FAIrepositoryServer))",
+ );
+ if($mesg->{'resultCode'} == 0 &&
+ $mesg->count != 0) {
+ foreach my $entry (@{$mesg->{entries}}) {
+ if($entry->exists('FAIrepository')) {
+ # Add an entry for each Repository configured for server
+ foreach my $repo(@{$entry->get_value('FAIrepository', asref => 1)}) {
+ my($tmp_url,$tmp_server,$tmp_release,$tmp_sections) = split(/\|/, $repo);
+ my $tmp_tag= $entry->get_value('gosaUnitTag') || "";
+ $result= $fai_server_db->add_dbentry( {
+ table => $table_name,
+ primkey => ['server', 'release', 'tag'],
+ server => $tmp_url,
+ release => $tmp_release,
+ sections => $tmp_sections,
+ tag => (length($tmp_tag)>0)?$tmp_tag:"",
+ } );
+ }
+ }
+ }
+ }
+ daemon_log("INFO: create_fai_server_db: finished", 5);
+
+ # TODO: Find a way to post the 'create_packages_list_db' event
+ &create_packages_list_db($ldap_handle);
+ }
- $shmda->shlock(LOCK_EX);
- if (defined $status) {
- $known_daemons->{$hostname}->{status} = $status;
- }
- if (defined $passwd) {
- $known_daemons->{$hostname}->{passwd} = $passwd;
- }
- if (defined $mac_address) {
- $known_daemons->{$hostname}->{mac_address} = $mac_address;
- }
- if (defined $events) {
- $known_daemons->{$hostname}->{events} = $events;
- }
- $known_daemons->{$hostname}->{timestamp} = $t;
- $shmda->shlock(LOCK_EX);
+ $ldap_handle->disconnect;
+ return $result;
+}
+
+sub run_create_fai_server_db {
+ my ($kernel, $session, $heap, $table_name) = @_[KERNEL, SESSION, HEAP, ARG0];
+ my $task = POE::Wheel::Run->new(
+ Program => sub { &create_fai_server_db($table_name,$kernel) },
+ StdoutEvent => "session_run_result",
+ StderrEvent => "session_run_debug",
+ CloseEvent => "session_run_done",
+ );
+
+ $heap->{task}->{ $task->ID } = $task;
return;
}
-#=== FUNCTION ================================================================
-# NAME: update_known_daemons
-# PARAMETERS: hostname - string - ip address and port of host (required)
-# status - string - (optional)
-# passwd - string - (optional)
-# client - string - ip address and port of client (optional)
-# RETURNS: nothing
-# DESCRIPTION: nome est omen and updates each time the timestamp of hostname
-#===============================================================================
-sub update_known_daemons {
- my $arg = {
- hostname => undef, status => undef, passwd => undef,
- @_ };
- my $hostname = $arg->{hostname};
- my $status = $arg->{status};
- my $passwd = $arg->{passwd};
-
- if (not defined $hostname) {
- daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
- return;
- }
+sub create_fai_release_db {
+ my ($table_name) = @_;
+ my $result;
+
+ my $ldap_handle = &get_ldap_handle();
+ if(defined($ldap_handle)) {
+ daemon_log("INFO: create_fai_release_db: start",5);
+ my $mesg= $ldap_handle->search(
+ base => $ldap_base,
+ scope => 'sub',
+ attrs => [],
+ filter => "(&(objectClass=organizationalUnit)(ou=fai))",
+ );
+ if($mesg->{'resultCode'} == 0 &&
+ $mesg->count != 0) {
+ # Walk through all possible FAI container ou's
+ my @sql_list;
+ my $timestamp= &get_time();
+ foreach my $ou (@{$mesg->{entries}}) {
+ my $tmp_classes= resolve_fai_classes($ou->dn, $ldap_handle);
+ if(defined($tmp_classes) && ref($tmp_classes) eq 'HASH') {
+ my @tmp_array=get_fai_release_entries($tmp_classes);
+ if(@tmp_array) {
+ foreach my $entry (@tmp_array) {
+ if(defined($entry) && ref($entry) eq 'HASH') {
+ my $sql=
+ "INSERT INTO $table_name "
+ ."(timestamp, release, class, type, state) VALUES ("
+ .$timestamp.","
+ ."'".$entry->{'release'}."',"
+ ."'".$entry->{'class'}."',"
+ ."'".$entry->{'type'}."',"
+ ."'".$entry->{'state'}."')";
+ push @sql_list, $sql;
+ }
+ }
+ }
+ }
+ }
+ daemon_log("DEBUG: Inserting ".scalar @sql_list." entries to DB",6);
+ if(@sql_list) {
+ unshift @sql_list, "DELETE FROM $table_name";
+ $fai_server_db->exec_statementlist(\@sql_list);
+ }
+ daemon_log("DEBUG: Done with inserting",6);
+ }
+ daemon_log("INFO: create_fai_release_db: finished",5);
+ }
+ $ldap_handle->disconnect;
+ return $result;
+}
+sub run_create_fai_release_db {
+ my ($session, $heap, $table_name) = @_[SESSION, HEAP, ARG0];
+ my $task = POE::Wheel::Run->new(
+ Program => sub { &create_fai_release_db($table_name) },
+ StdoutEvent => "session_run_result",
+ StderrEvent => "session_run_debug",
+ CloseEvent => "session_run_done",
+ );
- my ($seconds, $minutes, $hours, $monthday, $month,
- $year, $weekday, $yearday, $sommertime) = localtime(time);
- $hours = $hours < 10 ? $hours = "0".$hours : $hours;
- $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
- $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
- $month+=1;
- $month = $month < 10 ? $month = "0".$month : $month;
- $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
- $year+=1900;
- my $t = "$year$month$monthday$hours$minutes$seconds";
-
- $shmda->shlock(LOCK_EX);
- if (defined $status) {
- $known_daemons->{$hostname}->{status} = $status;
- }
- if (defined $passwd) {
- $known_daemons->{$hostname}->{passwd} = $passwd;
- }
- $known_daemons->{$hostname}->{timestamp} = $t;
- $shmda->shunlock(LOCK_EX);
+ $heap->{task}->{ $task->ID } = $task;
return;
}
+sub get_fai_types {
+ my $tmp_classes = shift || return undef;
+ my @result;
+
+ foreach my $type(keys %{$tmp_classes}) {
+ if(defined($tmp_classes->{$type}[0]) && (!($tmp_classes->{$type}[0] =~ /^.*?removed.*?$/))) {
+ my $entry = {
+ type => $type,
+ state => $tmp_classes->{$type}[0],
+ };
+ push @result, $entry;
+ }
+ }
+
+ return @result;
+}
-#=== FUNCTION ================================================================
-# NAME: print_known_clients
-# PARAMETERS: nothing
-# RETURNS: nothing
-# DESCRIPTION: nomen est omen
-#===============================================================================
-sub print_known_clients {
-
- print "####################################\n";
- print "# status of known_clients\n";
- $shmcl->shlock(LOCK_EX);
- my @hosts = keys %$known_clients;
- if (@hosts) {
- foreach my $host (@hosts) {
- my $status = $known_clients->{$host}->{status} ;
- my $passwd = $known_clients->{$host}->{passwd};
- my $timestamp = $known_clients->{$host}->{timestamp};
- my $mac_address = $known_clients->{$host}->{mac_address};
- my $events = $known_clients->{$host}->{events};
- print "$host\n";
- print "\tstatus: $status\n";
- print "\tpasswd: $passwd\n";
- print "\ttimestamp: $timestamp\n";
- print "\tmac_address: $mac_address\n";
- print "\tevents: $events\n";
- }
- }
- $shmcl->shunlock(LOCK_EX);
- print "####################################\n";
- return;
+sub get_fai_state {
+ my $result = "";
+ my $tmp_classes = shift || return $result;
+
+ foreach my $type(keys %{$tmp_classes}) {
+ if(defined($tmp_classes->{$type}[0])) {
+ $result = $tmp_classes->{$type}[0];
+
+ # State is equal for all types in class
+ last;
+ }
+ }
+
+ return $result;
}
+sub resolve_fai_classes {
+ my ($fai_base, $ldap_handle) = @_;
+ my $result;
+ my @possible_fai_classes= ("FAIscript", "FAIhook", "FAIpartitionTable", "FAItemplate", "FAIvariable", "FAIprofile", "FAIpackageList");
+ my $fai_filter= "(|(&(objectClass=FAIclass)(|(objectClass=".join(")(objectClass=", @possible_fai_classes).")))(objectClass=FAIbranch))";
+ my $fai_classes;
+
+ daemon_log("DEBUG: Searching for FAI entries in base $fai_base",6);
+ my $mesg= $ldap_handle->search(
+ base => $fai_base,
+ scope => 'sub',
+ attrs => ['cn','objectClass','FAIstate'],
+ filter => $fai_filter,
+ );
+ daemon_log("DEBUG: Found ".$mesg->count()." FAI entries",6);
+
+ if($mesg->{'resultCode'} == 0 &&
+ $mesg->count != 0) {
+ foreach my $entry (@{$mesg->{entries}}) {
+ if($entry->exists('cn')) {
+ my $tmp_dn= $entry->dn();
+
+ # Skip classname and ou dn parts for class
+ my $tmp_release = ($1) if $tmp_dn =~ /^[^,]+,[^,]+,(.*?),$fai_base$/;
+
+ # Skip classes without releases
+ if((!defined($tmp_release)) || length($tmp_release)==0) {
+ next;
+ }
+
+ my $tmp_cn= $entry->get_value('cn');
+ my $tmp_state= $entry->get_value('FAIstate');
+
+ my $tmp_type;
+ # Get FAI type
+ for my $oclass(@{$entry->get_value('objectClass', asref => 1)}) {
+ if(grep $_ eq $oclass, @possible_fai_classes) {
+ $tmp_type= $oclass;
+ last;
+ }
+ }
+
+ if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
+ # A Subrelease
+ my @sub_releases = split(/,/, $tmp_release);
+
+ # Walk through subreleases and build hash tree
+ my $hash;
+ while(my $tmp_sub_release = pop @sub_releases) {
+ $hash .= "\{'$tmp_sub_release'\}->";
+ }
+ eval('push @{$fai_classes->'.$hash.'{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";');
+ } else {
+ # A branch, no subrelease
+ push @{$fai_classes->{$tmp_release}->{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";
+ }
+ } elsif (!$entry->exists('cn')) {
+ my $tmp_dn= $entry->dn();
+ my $tmp_release = ($1) if $tmp_dn =~ /^(.*?),$fai_base$/;
+
+ # Skip classes without releases
+ if((!defined($tmp_release)) || length($tmp_release)==0) {
+ next;
+ }
+
+ if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
+ # A Subrelease
+ my @sub_releases= split(/,/, $tmp_release);
+
+ # Walk through subreleases and build hash tree
+ my $hash;
+ while(my $tmp_sub_release = pop @sub_releases) {
+ $hash .= "\{'$tmp_sub_release'\}->";
+ }
+ # Remove the last two characters
+ chop($hash);
+ chop($hash);
+
+ eval('$fai_classes->'.$hash.'= {}');
+ } else {
+ # A branch, no subrelease
+ if(!exists($fai_classes->{$tmp_release})) {
+ $fai_classes->{$tmp_release} = {};
+ }
+ }
+ }
+ }
+
+ # The hash is complete, now we can honor the copy-on-write based missing entries
+ foreach my $release (keys %$fai_classes) {
+ $result->{$release}= deep_copy(apply_fai_inheritance($fai_classes->{$release}));
+ }
+ }
+ return $result;
+}
-#=== FUNCTION ================================================================
-# NAME: create_known_client
-# PARAMETERS: hostname - string - key for the hash known_clients
-# RETURNS: nothing
-# DESCRIPTION: creates a dummy entry for hostname in known_clients
-#===============================================================================
-sub create_known_client {
- my ($hostname) = @_;
- $shmcl->shlock(LOCK_EX);
- $known_clients->{$hostname} = {};
- $known_clients->{$hostname}->{status} = "none";
- $known_clients->{$hostname}->{passwd} = "none";
- $known_clients->{$hostname}->{timestamp} = "none";
- $known_clients->{$hostname}->{mac_address} = "none";
- $known_clients->{$hostname}->{events} = "none";
- $shmcl->shunlock(LOCK_EX);
- return;
+sub apply_fai_inheritance {
+ my $fai_classes = shift || return {};
+ my $tmp_classes;
+
+ # Get the classes from the branch
+ foreach my $class (keys %{$fai_classes}) {
+ # Skip subreleases
+ if($class =~ /^ou=.*$/) {
+ next;
+ } else {
+ $tmp_classes->{$class}= deep_copy($fai_classes->{$class});
+ }
+ }
+
+ # Apply to each subrelease
+ foreach my $subrelease (keys %{$fai_classes}) {
+ if($subrelease =~ /ou=/) {
+ foreach my $tmp_class (keys %{$tmp_classes}) {
+ if(!exists($fai_classes->{$subrelease}->{$tmp_class})) {
+ $fai_classes->{$subrelease}->{$tmp_class} =
+ deep_copy($tmp_classes->{$tmp_class});
+ } else {
+ foreach my $type (keys %{$tmp_classes->{$tmp_class}}) {
+ if(!exists($fai_classes->{$subrelease}->{$tmp_class}->{$type})) {
+ $fai_classes->{$subrelease}->{$tmp_class}->{$type}=
+ deep_copy($tmp_classes->{$tmp_class}->{$type});
+ }
+ }
+ }
+ }
+ }
+ }
+
+ # Find subreleases in deeper levels
+ foreach my $subrelease (keys %{$fai_classes}) {
+ if($subrelease =~ /ou=/) {
+ foreach my $subsubrelease (keys %{$fai_classes->{$subrelease}}) {
+ if($subsubrelease =~ /ou=/) {
+ apply_fai_inheritance($fai_classes->{$subrelease});
+ }
+ }
+ }
+ }
+
+ return $fai_classes;
}
+sub get_fai_release_entries {
+ my $tmp_classes = shift || return;
+ my $parent = shift || "";
+ my @result = shift || ();
+
+ foreach my $entry (keys %{$tmp_classes}) {
+ if(defined($entry)) {
+ if($entry =~ /^ou=.*$/) {
+ my $release_name = $entry;
+ $release_name =~ s/ou=//g;
+ if(length($parent)>0) {
+ $release_name = $parent."/".$release_name;
+ }
+ my @bufentries = get_fai_release_entries($tmp_classes->{$entry}, $release_name, @result);
+ foreach my $bufentry(@bufentries) {
+ push @result, $bufentry;
+ }
+ } else {
+ my @types = get_fai_types($tmp_classes->{$entry});
+ foreach my $type (@types) {
+ push @result,
+ {
+ 'class' => $entry,
+ 'type' => $type->{'type'},
+ 'release' => $parent,
+ 'state' => $type->{'state'},
+ };
+ }
+ }
+ }
+ }
+
+ return @result;
+}
-#=== FUNCTION ================================================================
-# NAME: add_content2known_clients
-# PARAMETERS: hostname - string - ip address and port of host (required)
-# status - string - (optional)
-# passwd - string - (optional)
-# mac_address - string - (optional)
-# events - string - event of client, executable skripts under /etc/gosac/events
-# RETURNS: nothing
-# DESCRIPTION: nome est omen and updates each time the timestamp of hostname
-#===============================================================================
-sub add_content2known_clients {
- my $arg = {
- hostname => undef, status => undef, passwd => undef,
- mac_address => undef, events => undef,
- @_ };
- my $hostname = $arg->{hostname};
- my $status = $arg->{status};
- my $passwd = $arg->{passwd};
- my $mac_address = $arg->{mac_address};
- my $events = $arg->{events};
-
- if (not defined $hostname) {
- daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
- return;
+sub deep_copy {
+ my $this = shift;
+ if (not ref $this) {
+ $this;
+ } elsif (ref $this eq "ARRAY") {
+ [map deep_copy($_), @$this];
+ } elsif (ref $this eq "HASH") {
+ +{map { $_ => deep_copy($this->{$_}) } keys %$this};
+ } else { die "what type is $_?" }
+}
+
+
+sub session_run_result {
+ my ($kernel, $heap, $client_answer) = @_[KERNEL, HEAP, ARG0];
+ $kernel->sig(CHLD => "child_reap");
+}
+
+sub session_run_debug {
+ my $result = $_[ARG0];
+ print STDERR "$result\n";
+}
+
+sub session_run_done {
+ my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
+ delete $heap->{task}->{$task_id};
+}
+
+sub create_sources_list {
+ my ($ldap_handle) = @_;
+ my $result="/tmp/gosa_si_tmp_sources_list";
+
+ # Remove old file
+ if(stat($result)) {
+ unlink($result);
+ }
+
+ my $fh;
+ open($fh, ">$result") or return undef;
+ if(defined($ldap_server_dn) and length($ldap_server_dn) > 0) {
+ my $mesg=$ldap_handle->search(
+ base => $ldap_server_dn,
+ scope => 'base',
+ attrs => 'FAIrepository',
+ filter => 'objectClass=FAIrepositoryServer'
+ );
+ if($mesg->count) {
+ foreach my $entry(@{$mesg->{'entries'}}) {
+ foreach my $value(@{$entry->get_value('FAIrepository', asref => 1)}) {
+ my ($server, $tag, $release, $sections)= split /\|/, $value;
+ my $line = "deb $server $release";
+ $sections =~ s/,/ /g;
+ $line.= " $sections";
+ print $fh $line."\n";
+ }
+ }
+ }
+ }
+ close($fh);
+
+ return $result;
+}
+
+sub create_packages_list_db {
+ my ($ldap_handle, $sources_file) = @_ ;
+
+ if (not defined $ldap_handle) {
+ $ldap_handle= &get_ldap_handle();
+
+ if (not defined $ldap_handle) {
+ daemon_log("0 ERROR: no ldap_handle available to create_packages_list_db", 1);
+ return;
+ }
+ }
+
+ if (not defined $sources_file) {
+ $sources_file = &create_sources_list($ldap_handle);
}
- my ($seconds, $minutes, $hours, $monthday, $month,
- $year, $weekday, $yearday, $sommertime) = localtime(time);
- $hours = $hours < 10 ? $hours = "0".$hours : $hours;
- $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
- $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
- $month+=1;
- $month = $month < 10 ? $month = "0".$month : $month;
- $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
- $year+=1900;
- my $t = "$year$month$monthday$hours$minutes$seconds";
+ my $line;
+ daemon_log("INFO: create_packages_list_db: start", 5);
+
+ open(CONFIG, "<$sources_file") or do {
+ daemon_log( "ERROR: create_packages_list_db: Failed to open '$sources_file'", 1);
+ return;
+ };
- $shmcl->shlock(LOCK_EX);
- if (defined $status) {
- $known_clients->{$hostname}->{status} = $status;
- }
- if (defined $passwd) {
- $known_clients->{$hostname}->{passwd} = $passwd;
- }
- if (defined $mac_address) {
- $known_clients->{$hostname}->{mac_address} = $mac_address;
- }
- if (defined $events) {
- $known_clients->{$hostname}->{events} = $events;
+ # Read lines
+ while ($line = <CONFIG>){
+ # Unify
+ chop($line);
+ $line =~ s/^\s+//;
+ $line =~ s/^\s+/ /;
+
+ # Strip comments
+ $line =~ s/#.*$//g;
+
+ # Skip empty lines
+ if ($line =~ /^\s*$/){
+ next;
+ }
+
+ # Interpret deb line
+ if ($line =~ /^deb [^\s]+\s[^\s]+\s[^\s]+/){
+ my( $baseurl, $dist, $sections ) = ($line =~ /^deb\s([^\s]+)\s+([^\s]+)\s+(.*)$/);
+ my $section;
+ foreach $section (split(' ', $sections)){
+ &parse_package_info( $baseurl, $dist, $section );
+ }
+ }
}
- $known_clients->{$hostname}->{timestamp} = $t;
- $shmcl->shlock(LOCK_EX);
+
+ close (CONFIG);
+
+ daemon_log("INFO: create_packages_list_db: finished", 5);
return;
}
-
-#=== FUNCTION ================================================================
-# NAME:
-# PARAMETERS:
-# RETURNS:
-# DESCRIPTION:
-#===============================================================================
-sub clean_up_known_clients {
- my ($address) = @_ ;
-
- if (not exists $known_clients->{$address}) {
- daemon_log("cannot prune known_clients from $address, client not known", 5);
- return;
- }
+sub run_create_packages_list_db {
+ my ($session, $heap) = @_[SESSION, HEAP];
+ my $task = POE::Wheel::Run->new(
+ Program => sub {&create_packages_list_db},
+ StdoutEvent => "session_run_result",
+ StderrEvent => "session_run_debug",
+ CloseEvent => "session_run_done",
+ );
+ $heap->{task}->{ $task->ID } = $task;
+}
- delete $known_clients->{$address};
+sub parse_package_info {
+ my ($baseurl, $dist, $section)= @_;
+ my ($package);
- # send bus a msg that address was deleted from known_clients
- my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
- &send_msg_hash2bus($out_hash);
+ my ($path) = ($baseurl =~ m%://[^/]*(.*)$%);
+ $repo_dirs{ "${repo_path}/pool" } = 1;
- daemon_log("client $address deleted from known_clients because of multiple down time", 3);
- return;
+ foreach $package ("Packages.gz"){
+ daemon_log("DEBUG: create_packages_list: fetch $baseurl, $dist, $section", 7);
+ get_package( "$baseurl/dists/$dist/$section/binary-$arch/$package", "$outdir/$dist/$section" );
+ parse_package( "$outdir/$dist/$section", $dist, $path );
+ }
+ find(\&cleanup_and_extract, keys( %repo_dirs ) );
}
+sub get_package {
+ my ($url, $dest)= @_;
-#=== FUNCTION ================================================================
-# NAME: update_known_clients
-# PARAMETERS: hostname - string - ip address and port of host (required)
-# status - string - (optional)
-# passwd - string - (optional)
-# client - string - ip address and port of client (optional)
-# RETURNS: nothing
-# DESCRIPTION: nome est omen and updates each time the timestamp of hostname
-#===============================================================================
-sub update_known_clients {
- my $arg = {
- hostname => undef, status => undef, passwd => undef,
- mac_address => undef, events => undef,
- @_ };
- my $hostname = $arg->{hostname};
- my $status = $arg->{status};
- my $passwd = $arg->{passwd};
- my $mac_address = $arg->{mac_address};
- my $events = $arg->{events};
-
- if (not defined $hostname) {
- daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
+ my $tpath = dirname($dest);
+ -d "$tpath" || mkpath "$tpath";
+
+ # This is ugly, but I've no time to take a look at "how it works in perl"
+ if(0 == system("wget '$url' -O '$dest' 2>/dev/null") ) {
+ system("gunzip -cd '$dest' > '$dest.in'");
+ unlink($dest);
+ } else {
+ daemon_log("ERROR: create_packages_list_db: get_packages: fetching '$url' failed!", 1);
+ }
+ return 0;
+}
+
+sub parse_package {
+ my ($path, $dist, $srv_path)= @_;
+ my ($package, $version, $section, $description);
+ my @sql_list;
+ my $PACKAGES;
+
+ if(not stat("$path.in")) {
+ daemon_log("ERROR: create_packages_list: parse_package: file '$path.in' is not readable",1);
return;
}
- my ($seconds, $minutes, $hours, $monthday, $month,
- $year, $weekday, $yearday, $sommertime) = localtime(time);
- $hours = $hours < 10 ? $hours = "0".$hours : $hours;
- $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
- $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
- $month+=1;
- $month = $month < 10 ? $month = "0".$month : $month;
- $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
- $year+=1900;
- my $t = "$year$month$monthday$hours$minutes$seconds";
-
- $shmcl->shlock(LOCK_EX);
- if (defined $status) {
- $known_clients->{$hostname}->{status} = $status;
- }
- if (defined $passwd) {
- $known_clients->{$hostname}->{passwd} = $passwd;
- }
- if (defined $mac_address) {
- $known_clients->{$hostname}->{mac_address} = $mac_address;
+ open($PACKAGES, "<$path.in");
+ if(not defined($PACKAGES)) {
+ daemon_log("ERROR: create_packages_list_db: parse_package: can not open '$path.in'",1);
+ return;
}
- if (defined $events) {
- $known_clients->{$hostname}->{events} = $events;
+
+ # Read lines
+ while (<$PACKAGES>){
+ my $line = $_;
+ # Unify
+ chop($line);
+
+ # Use empty lines as a trigger
+ if ($line =~ /^\s*$/){
+ my $sql = "INSERT INTO packages_list VALUES ('$dist', '$package', '$version', '$section', '', 'none', '0')";
+ push(@sql_list, $sql);
+ $package = "none";
+ $version = "none";
+ $section = "none";
+ $description = "none";
+ next;
+ }
+
+ # Trigger for package name
+ if ($line =~ /^Package:\s/){
+ ($package)= ($line =~ /^Package: (.*)$/);
+ next;
+ }
+
+ # Trigger for version
+ if ($line =~ /^Version:\s/){
+ ($version)= ($line =~ /^Version: (.*)$/);
+ next;
+ }
+
+ # Trigger for description
+ if ($line =~ /^Description:\s/){
+ ($description)= ($line =~ /^Description: (.*)$/);
+ next;
+ }
+
+ # Trigger for section
+ if ($line =~ /^Section:\s/){
+ ($section)= ($line =~ /^Section: (.*)$/);
+ next;
+ }
+
+ # Trigger for filename
+ if ($line =~ /^Filename:\s/){
+ my ($filename) = ($line =~ /^Filename: (.*)$/);
+ store_fileinfo( $package, $filename, $dist, $srv_path, $version, $repo_path );
+ next;
+ }
}
- $known_clients->{$hostname}->{timestamp} = $t;
- $shmcl->shunlock(LOCK_EX);
- return;
+
+ close( $PACKAGES );
+ unlink( "$path.in" );
+
+ $packages_list_db->exec_statementlist(\@sql_list);
}
+sub store_fileinfo {
+ my( $package, $file, $dist, $path, $vers, $srvdir) = @_;
+ my %fileinfo = (
+ 'package' => $package,
+ 'dist' => $dist,
+ 'version' => $vers,
+ );
+ $repo_files{ "${srvdir}/$file" } = \%fileinfo;
+}
+sub cleanup_and_extract {
+ my $fileinfo = $repo_files{ $File::Find::name };
+ if( defined $fileinfo ) {
+ my $dir = "$outdir/$fileinfo->{ 'dist' }/debconf.d";
+ my $sql;
+ my $package = $fileinfo->{ 'package' };
+ my $newver = $fileinfo->{ 'version' };
+
+ mkpath($dir);
+ system( "dpkg -e '$File::Find::name' '$dir/DEBIAN'" );
+
+ if( -f "$dir/DEBIAN/templates" ) {
+
+ daemon_log("DEBUG: Found debconf templates in '$package' - $newver", 5);
+
+ my $tmpl= "";
+ {
+ local $/=undef;
+ open FILE, "$dir/DEBIAN/templates";
+ $tmpl = &encode_base64(<FILE>);
+ close FILE;
+ }
+ rmtree("$dir/DEBIAN/templates");
+
+ $sql= "update $main::packages_list_tn set template = '$tmpl' where package = '$package' and version = '$newver';";
+
+ } else {
+ $sql= "update $main::packages_list_tn set template = '' where package = '$package' and version = '$newver';";
+ }
+
+ my $res= $main::packages_list_db->update_dbentry($sql);
+ }
+}
-#==== MAIN = main ==============================================================
+#==== MAIN = main ==============================================================
# parse commandline options
Getopt::Long::Configure( "bundling" );
GetOptions("h|help" => \&usage,
&check_cmdline_param ;
&read_configfile;
&check_pid;
-&import_modules;
$SIG{CHLD} = 'IGNORE';
-# restart daemon log file
-if(-e $log_file ) { unlink $log_file }
-daemon_log(" ", 1);
-daemon_log("gosa-si-server started!", 1);
+# forward error messages to logfile
+if( ! $foreground ) {
+ open( STDIN, '+>/dev/null' );
+ open( STDOUT, '+>&STDIN' );
+ open( STDERR, '+>&STDIN' );
+}
-# Just fork, if we"re not in foreground mode
-if( ! $foreground ) { $pid = fork(); }
-else { $pid = $$; }
+# Just fork, if we are not in foreground mode
+if( ! $foreground ) {
+ chdir '/' or die "Can't chdir to /: $!";
+ $pid = fork;
+ setsid or die "Can't start a new session: $!";
+ umask 0;
+} else {
+ $pid = $$;
+}
# Do something useful - put our PID into the pid_file
if( 0 != $pid ) {
open( LOCK_FILE, ">$pid_file" );
print LOCK_FILE "$pid\n";
-close( LOCK_FILE );
- if( !$foreground ) { exit( 0 ) };
-}
-
-# detect own ip and mac address
-($server_ip, $server_mac_address) = &get_ip_and_mac();
-if (not defined $server_ip) {
- die "EXIT: ip address of $0 could not be detected";
+ close( LOCK_FILE );
+ if( !$foreground ) {
+ exit( 0 )
+ };
}
-daemon_log("server ip address detected: $server_ip", 1);
-daemon_log("server mac address detected: $server_mac_address", 1);
-
-# setup xml parser
-$xml = new XML::Simple();
-
-# create cipher object
-$bus_cipher = &create_ciphering($bus_passwd);
-$bus_address = "$bus_ip:$bus_port";
-# create reading and writing vectors
-my $rbits = my $wbits = my $ebits = "";
-
-# open server socket
-$server_address = "$server_ip:$server_port";
-if($server_activ eq "on"){
- daemon_log(" ", 1);
- $server = IO::Socket::INET->new(LocalPort => $server_port,
- Type => SOCK_STREAM,
- Reuse => 1,
- Listen => 20,
- );
- if(not defined $server){
- daemon_log("cannot be a tcp server at $server_port : $@");
- } else {
- daemon_log("start server: $server_address", 1);
- vec($rbits, fileno $server, 1) = 1;
- vec($wbits, fileno $server, 1) = 1;
- }
-}
+daemon_log(" ", 1);
+daemon_log("$0 started!", 1);
-# register at bus
if ($no_bus > 0) {
- $bus_activ = "off"
-}
-if($bus_activ eq "on") {
- daemon_log(" ", 1);
- ®ister_at_bus();
-}
-
-
-# start arp fifo
-if ($no_arp > 0) {
- $arp_activ = "off";
-}
-my $my_fifo;
-if($arp_activ eq "on") {
- daemon_log(" ", 1);
- $my_fifo = &open_fifo($arp_fifo_path);
- if($my_fifo == 0) { die "fifo file disappeared\n" }
- sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
-
- vec($rbits, fileno $arp_fifo, 1) = 1;
-}
-
-$gosa_address = "$gosa_ip:$gosa_port";
-# start gosa inferface fifos
-if ($gosa_activ eq "on") {
- daemon_log(" ",1);
- $gosa_server = IO::Socket::INET->new(LocalPort => $gosa_port,
- Type => SOCK_STREAM,
- Reuse => 1,
- Listen => 1,
- );
- if (not defined $gosa_server) {
- daemon_log("cannot start tcp server at $gosa_port for communication to gosa: $@", 1);
- } else {
- daemon_log("start server at for communication to gosa: $gosa_address", 1);
- vec($rbits, fileno $gosa_server, 1) = 1;
-
- }
+ $bus_activ = "false"
}
+# connect to gosa-si job queue
+$job_db = GOSA::DBsqlite->new($job_queue_file_name);
+$job_db->create_table($job_queue_tn, \@job_queue_col_names);
-###################################
-#everything ready, okay, lets start
-###################################
-while(1) {
+# connect to known_clients_db
+$known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
+$known_clients_db->create_table($known_clients_tn, \@known_clients_col_names);
- # add all handles from the childs
- while ( my ($pid, $child_hash) = each %busy_child ) {
-
- # check whether process still exists
- my $exitus_pid = waitpid($pid, WNOHANG);
- if($exitus_pid != 0) {
- delete $busy_child{$pid};
- next;
- }
-
- # add child fhd to the listener
- my $fhd = $$child_hash{'pipe_rd'};
- vec($rbits, fileno $fhd, 1) = 1;
- }
+# connect to known_server_db
+$known_server_db = GOSA::DBsqlite->new($known_server_file_name);
+$known_server_db->create_table($known_server_tn, \@known_server_col_names);
- my ($rout, $wout);
- my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
+# connect to login_usr_db
+$login_users_db = GOSA::DBsqlite->new($login_users_file_name);
+$login_users_db->create_table($login_users_tn, \@login_users_col_names);
- # error handling
- if($nf < 0 ) {
- }
+# connect to fai_server_db and fai_release_db
+unlink($fai_server_file_name);
+$fai_server_db = GOSA::DBsqlite->new($fai_server_file_name);
+$fai_server_db->create_table($fai_server_tn, \@fai_server_col_names);
+$fai_server_db->create_table($fai_release_tn, \@fai_release_col_names);
- # something is coming in
- if($server_activ eq "on" && vec($rout, fileno $server, 1)) {
- daemon_log(" ", 1);
- my $client = $server->accept();
- my $other_end = getpeername($client);
- if(not defined $other_end) {
- daemon_log("client cannot be identified: $!");
- } else {
- my ($port, $iaddr) = unpack_sockaddr_in($other_end);
- my $actual_ip = inet_ntoa($iaddr);
- daemon_log("accept client at daemon socket from $actual_ip", 5);
- my $in_msg = &read_from_socket($client);
- if(defined $in_msg){
- chomp($in_msg);
- &activating_child($in_msg, $actual_ip);
- } else {
- daemon_log("cannot read from $actual_ip", 5);
- }
- }
- close($client);
- }
+# connect to packages_list_db
+unlink($packages_list_file_name);
+$packages_list_db = GOSA::DBsqlite->new($packages_list_file_name);
+$packages_list_db->create_table($packages_list_tn, \@packages_list_col_names);
- if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
- my $in_msg = <$arp_fifo>;
- chomp($in_msg);
- print "arp_activ: msg: $in_msg\n";
- my $act_passwd = $known_daemons->{$bus_address}->{passwd};
- print "arp_activ: arp_passwd: $act_passwd\n";
+# connect to messaging_db
+$messaging_db = GOSA::DBsqlite->new($messaging_file_name);
+$messaging_db->create_table($messaging_tn, \@messaging_col_names);
- my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
- my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
+# create xml object used for en/decrypting
+$xml = new XML::Simple();
- if ($target eq $server_address) {
- print "arp_activ: forward to server\n";
- my $arp_cipher = &create_ciphering($act_passwd);
- my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
- &activating_child($crypted_msg, $server_ip);
- } else {
- print "arp_activ: send to bus\n";
- &send_msg_hash2address($in_msg_hash, $bus_address);
- }
- print "\n";
- }
-
- if($gosa_activ eq "on" && vec($rout, fileno $gosa_server, 1)) {
- daemon_log(" ", 1);
- my $client = $gosa_server->accept();
- my $other_end = getpeername($client);
- if(not defined $other_end) {
- daemon_log("client cannot be identified: $!");
- } else {
- my ($port, $iaddr) = unpack_sockaddr_in($other_end);
- my $actual_ip = inet_ntoa($iaddr);
- daemon_log("accept client at gosa socket from $actual_ip", 5);
- my $in_msg = <$client>;
- #my $in_msg = &read_from_socket($client);
-
- if(defined $in_msg){
- chomp($in_msg);
- &activating_child($in_msg, $actual_ip, $client);
- } else {
- daemon_log("cannot read from $actual_ip", 5);
- }
- }
- #close($client);
+# create socket for incoming xml messages
+
+POE::Component::Server::TCP->new(
+ Port => $server_port,
+ ClientInput => sub {
+ my ($kernel, $input) = @_[KERNEL, ARG0];
+ push(@tasks, $input);
+ $kernel->yield("next_task");
+ },
+ InlineStates => {
+ next_task => \&next_task,
+ task_result => \&handle_task_result,
+ task_done => \&handle_task_done,
+ task_debug => \&handle_task_debug,
+ child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
}
+);
- # check all processing childs whether they are finished ('done') or
- while ( my ($pid, $child_hash) = each %busy_child ) {
- my $fhd = $$child_hash{'pipe_rd'};
+daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
+
+# create session for repeatedly checking the job queue for jobs
+POE::Session->create(
+ inline_states => {
+ _start => \&_start,
+ sig_handler => \&sig_handler,
+ watch_for_new_jobs => \&watch_for_new_jobs,
+ watch_for_done_jobs => \&watch_for_done_jobs,
+ create_packages_list_db => \&run_create_packages_list_db,
+ create_fai_server_db => \&run_create_fai_server_db,
+ create_fai_release_db => \&run_create_fai_release_db,
+ session_run_result => \&session_run_result,
+ session_run_debug => \&session_run_debug,
+ session_run_done => \&session_run_done,
+ child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
+ }
+);
- if (vec($rout, fileno $fhd, 1) ) {
- daemon_log("process child $pid is ready to read", 5);
- $fhd->blocking(1);
- my $in_msg = <$fhd>;
- $fhd->blocking(0);
- my $part_in_msg;
- while ($part_in_msg = <$fhd>) {
- if (not defined $part_in_msg) {
- last;
- }
- $in_msg .= $part_in_msg;
- }
- chomp($in_msg);
-
- daemon_log("process child read: $in_msg", 5);
- if (not defined $in_msg) {
- next;
- } elsif ($in_msg =~ "done") {
- delete $busy_child{$pid};
- $free_child{$pid} = $child_hash;
-
- } else {
- my $act_client = $busy_child{$pid}{client_ref};
- print $act_client $in_msg."\n";
- my $act_pipe = $busy_child{$pid}{pipe_rd};
- sleep(10);
- close ($act_client);
- delete $busy_child{$pid};
- $free_child{$pid} = $child_hash;
+# import all modules
+&import_modules;
- }
- }
- }
+# check wether all modules are gosa-si valid passwd check
+POE::Kernel->run();
+exit;
-}