Code

change progress column in jobdb from string to integer
[gosa.git] / gosa-si / gosa-si-server
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 #         FILE:  gosa-sd
5 #
6 #        USAGE:  ./gosa-sd
7 #
8 #  DESCRIPTION:
9 #
10 #      OPTIONS:  ---
11 # REQUIREMENTS:  libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl 
12 #                libdata-dumper-simple-perl libdbd-sqlite3-perl libnet-ldap-perl
13 #                libpoe-perl
14 #         BUGS:  ---
15 #        NOTES:
16 #       AUTHOR:   (Andreas Rettenberger), <rettenberger@gonicus.de>
17 #      COMPANY:
18 #      VERSION:  1.0
19 #      CREATED:  12.09.2007 08:54:41 CEST
20 #     REVISION:  ---
21 #===============================================================================
23 use strict;
24 use warnings;
25 use Getopt::Long;
26 use Config::IniFiles;
27 use POSIX;
28 use utf8;
30 use Fcntl;
31 use IO::Socket::INET;
32 use IO::Handle;
33 use IO::Select;
34 use Symbol qw(qualify_to_ref);
35 use Crypt::Rijndael;
36 use MIME::Base64;
37 use Digest::MD5  qw(md5 md5_hex md5_base64);
38 use XML::Simple;
39 use Data::Dumper;
40 use Sys::Syslog qw( :DEFAULT setlogsock);
41 use Cwd;
42 use File::Spec;
43 use File::Basename;
44 use GOSA::DBsqlite;
45 use GOSA::GosaSupportDaemon;
46 use POE qw(Component::Server::TCP);
48 my $modules_path = "/usr/lib/gosa-si/modules";
49 use lib "/usr/lib/gosa-si/modules";
51 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
52 my ($bus_activ, $bus, $msg_to_bus, $bus_cipher);
53 my ($server, $server_mac_address);
54 my ($gosa_server, $job_queue_timeout, $job_queue_loop_delay);
55 my ($known_modules);
56 my ($pid_file, $procid, $pid, $log_file);
57 my ($arp_activ, $arp_fifo);
58 my ($xml);
60 # variables declared in config file are always set to 'our'
61 our (%cfg_defaults, $log_file, $pid_file, 
62     $server_ip, $server_port, $SIPackages_key, 
63     $arp_activ, $gosa_unit_tag,
64     $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
65 );
67 # additional variable which should be globaly accessable
68 our $server_address;
69 our $bus_address;
70 our $gosa_address;
71 our $no_bus;
72 our $no_arp;
73 our $verbose;
74 our $forground;
75 our $cfg_file;
77 # specifies the verbosity of the daemon_log
78 $verbose = 0 ;
80 # if foreground is not null, script will be not forked to background
81 $foreground = 0 ;
83 # specifies the timeout seconds while checking the online status of a registrating client
84 $ping_timeout = 5;
86 $no_bus = 0;
87 $bus_activ = "true";
89 $no_arp = 0;
91 our $prg= basename($0);
93 # holds all gosa jobs
94 my $job_queue_file_name;
95 our $job_db;
96 our $job_queue_tn = 'jobs';
98 # holds all other gosa-sd as well as the gosa-sd-bus
99 my $known_server_file_name;
100 our $known_server_db;
101 our $known_server_tn = "known_server";
103 # holds all registrated clients
104 my $known_clients_file_name;
105 our $known_clients_db;
106 our $known_clients_tn = "known_clients";
108 # holds all logged in user at each client 
109 my $login_users_file_name;
110 our $login_users_db;
111 our $login_users_tn = "login_users";
113 %cfg_defaults = (
114 "general" => {
115     "log-file" => [\$log_file, "/var/run/".$prg.".log"],
116     "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
117     },
118 "bus" => {
119     "activ" => [\$bus_activ, "true"],
120     },
121 "server" => {
122 #    "ip" => [\$server_ip, "0.0.0.0"],  
123     "port" => [\$server_port, "20081"],
124     "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
125     "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
126     "login-users" => [\$login_users_file_name, '/var/lib/gosa-si/users.db'],
127         "gosa-unit-tag" => [\$gosa_unit_tag, ""],
128     },
129 "GOsaPackages" => {
130     "ip" => [\$gosa_ip, "0.0.0.0"],
131     "port" => [\$gosa_port, "20082"],
132     "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
133     "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
134     "key" => [\$GosaPackages_key, "none"],
135     },
136 "SIPackages" => {
137     "key" => [\$SIPackages_key, "none"],
138     },
139 );
142 #===  FUNCTION  ================================================================
143 #         NAME:  usage
144 #   PARAMETERS:  nothing
145 #      RETURNS:  nothing
146 #  DESCRIPTION:  print out usage text to STDERR
147 #===============================================================================
148 sub usage {
149     print STDERR << "EOF" ;
150 usage: $prg [-hvf] [-c config]
152            -h        : this (help) message
153            -c <file> : config file
154            -f        : foreground, process will not be forked to background
155            -v        : be verbose (multiple to increase verbosity)
156            -no-bus   : starts $prg without connection to bus
157            -no-arp   : starts $prg without connection to arp module
158  
159 EOF
160     print "\n" ;
164 #===  FUNCTION  ================================================================
165 #         NAME:  read_configfile
166 #   PARAMETERS:  cfg_file - string -
167 #      RETURNS:  nothing
168 #  DESCRIPTION:  read cfg_file and set variables
169 #===============================================================================
170 sub read_configfile {
171     my $cfg;
172     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
173         if( -r $cfg_file ) {
174             $cfg = Config::IniFiles->new( -file => $cfg_file );
175         } else {
176             print STDERR "Couldn't read config file!\n";
177         }
178     } else {
179         $cfg = Config::IniFiles->new() ;
180     }
181     foreach my $section (keys %cfg_defaults) {
182         foreach my $param (keys %{$cfg_defaults{ $section }}) {
183             my $pinfo = $cfg_defaults{ $section }{ $param };
184             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
185         }
186     }
190 #===  FUNCTION  ================================================================
191 #         NAME:  logging
192 #   PARAMETERS:  level - string - default 'info'
193 #                msg - string -
194 #                facility - string - default 'LOG_DAEMON'
195 #      RETURNS:  nothing
196 #  DESCRIPTION:  function for logging
197 #===============================================================================
198 sub daemon_log {
199     # log into log_file
200     my( $msg, $level ) = @_;
201     if(not defined $msg) { return }
202     if(not defined $level) { $level = 1 }
203     if(defined $log_file){
204         open(LOG_HANDLE, ">>$log_file");
205         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
206             print STDERR "cannot open $log_file: $!";
207             return }
208             chomp($msg);
209             if($level <= $verbose){
210                 my ($seconds, $minutes, $hours, $monthday, $month,
211                         $year, $weekday, $yearday, $sommertime) = localtime(time);
212                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
213                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
214                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
215                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
216                 $month = $monthnames[$month];
217                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
218                 $year+=1900;
219                 my $name = $prg;
221                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
222                 print LOG_HANDLE $log_msg;
223                 if( $foreground ) { 
224                     print STDERR $log_msg;
225                 }
226             }
227         close( LOG_HANDLE );
228     }
232 #===  FUNCTION  ================================================================
233 #         NAME:  check_cmdline_param
234 #   PARAMETERS:  nothing
235 #      RETURNS:  nothing
236 #  DESCRIPTION:  validates commandline parameter
237 #===============================================================================
238 sub check_cmdline_param () {
239     my $err_config;
240     my $err_counter = 0;
241         if(not defined($cfg_file)) {
242                 $cfg_file = "/etc/gosa-si/server.conf";
243                 if(! -r $cfg_file) {
244                         $err_config = "please specify a config file";
245                         $err_counter += 1;
246                 }
247     }
248     if( $err_counter > 0 ) {
249         &usage( "", 1 );
250         if( defined( $err_config)) { print STDERR "$err_config\n"}
251         print STDERR "\n";
252         exit( -1 );
253     }
257 #===  FUNCTION  ================================================================
258 #         NAME:  check_pid
259 #   PARAMETERS:  nothing
260 #      RETURNS:  nothing
261 #  DESCRIPTION:  handels pid processing
262 #===============================================================================
263 sub check_pid {
264     $pid = -1;
265     # Check, if we are already running
266     if( open(LOCK_FILE, "<$pid_file") ) {
267         $pid = <LOCK_FILE>;
268         if( defined $pid ) {
269             chomp( $pid );
270             if( -f "/proc/$pid/stat" ) {
271                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
272                 if( $0 eq $stat ) {
273                     close( LOCK_FILE );
274                     exit -1;
275                 }
276             }
277         }
278         close( LOCK_FILE );
279         unlink( $pid_file );
280     }
282     # create a syslog msg if it is not to possible to open PID file
283     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
284         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
285         if (open(LOCK_FILE, '<', $pid_file)
286                 && ($pid = <LOCK_FILE>))
287         {
288             chomp($pid);
289             $msg .= "(PID $pid)\n";
290         } else {
291             $msg .= "(unable to read PID)\n";
292         }
293         if( ! ($foreground) ) {
294             openlog( $0, "cons,pid", "daemon" );
295             syslog( "warning", $msg );
296             closelog();
297         }
298         else {
299             print( STDERR " $msg " );
300         }
301         exit( -1 );
302     }
305 #===  FUNCTION  ================================================================
306 #         NAME:  import_modules
307 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
308 #                are stored
309 #      RETURNS:  nothing
310 #  DESCRIPTION:  each file in module_path which ends with '.pm' and activation 
311 #                state is on is imported by "require 'file';"
312 #===============================================================================
313 sub import_modules {
314     daemon_log(" ", 1);
316     if (not -e $modules_path) {
317         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
318     }
320     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
321     while (defined (my $file = readdir (DIR))) {
322         if (not $file =~ /(\S*?).pm$/) {
323             next;
324         }
325                 my $mod_name = $1;
327         if( $file =~ /ArpHandler.pm/ ) {
328             if( $no_arp > 0 ) {
329                 next;
330             }
331         }
332         
333         eval { require $file; };
334         if ($@) {
335             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
336             daemon_log("$@", 5);
337                 } else {
338                         my $info = eval($mod_name.'::get_module_info()');
339                         # Only load module if get_module_info() returns a non-null object
340                         if( $info ) {
341                                 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
342                                 $known_modules->{$mod_name} = $info;
343                                 daemon_log("INFO: module $mod_name loaded", 5);
344                         }
345                 }
346     }   
347     close (DIR);
351 #===  FUNCTION  ================================================================
352 #         NAME:  sig_int_handler
353 #   PARAMETERS:  signal - string - signal arose from system
354 #      RETURNS:  noting
355 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
356 #===============================================================================
357 sub sig_int_handler {
358     my ($signal) = @_;
360     daemon_log("shutting down gosa-si-server", 1);
361     exit(1);
363 $SIG{INT} = \&sig_int_handler;
367 sub check_key_and_xml_validity {
368     my ($crypted_msg, $module_key) = @_;
369     my $msg;
370     my $msg_hash;
371     my $error_string;
372     eval{
373         $msg = &decrypt_msg($crypted_msg, $module_key);
375         if ($msg =~ /<xml>/i){
376             &main::daemon_log("decrypted_msg: \n$msg", 8);
377             $msg_hash = $xml->XMLin($msg, ForceArray=>1);
379             ##############
380             # check header
381             if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
382             my $header_l = $msg_hash->{'header'};
383             if( 1 > @{$header_l} ) { die 'empty header tag'; }
384             if( 1 < @{$header_l} ) { die 'more than one header specified'; }
385             my $header = @{$header_l}[0];
386             if( 0 == length $header) { die 'empty string in header tag'; }
388             ##############
389             # check source
390             if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
391             my $source_l = $msg_hash->{'source'};
392             if( 1 > @{$source_l} ) { die 'empty source tag'; }
393             if( 1 < @{$source_l} ) { die 'more than one source specified'; }
394             my $source = @{$source_l}[0];
395             if( 0 == length $source) { die 'source error'; }
397             ##############
398             # check target
399             if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
400             my $target_l = $msg_hash->{'target'};
401             if( 1 > @{$target_l} ) { die 'empty target tag'; }
402         }
403     };
404     if($@) {
405         &main::daemon_log("WARNING: do not understand the message", 5);
406         &main::daemon_log("$@", 8);
407         $msg = undef;
408         $msg_hash = undef;
409     }
411     return ($msg, $msg_hash);
415 sub check_outgoing_xml_validity {
416     my ($msg) = @_;
418     my $msg_hash;
419     eval{
420         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
422         ##############
423         # check header
424         my $header_l = $msg_hash->{'header'};
425         if( 1 != @{$header_l} ) {
426             die 'no or more than one headers specified';
427         }
428         my $header = @{$header_l}[0];
429         if( 0 == length $header) {
430             die 'header has length 0';
431         }
433         ##############
434         # check source
435         my $source_l = $msg_hash->{'source'};
436         if( 1 != @{$source_l} ) {
437             die 'no or more than 1 sources specified';
438         }
439         my $source = @{$source_l}[0];
440         if( 0 == length $source) {
441             die 'source has length 0';
442         }
443         unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
444                 $source =~ /^GOSA$/i ) {
445             die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
446         }
447         
448         ##############
449         # check target  
450         my $target_l = $msg_hash->{'target'};
451         if( 0 == @{$target_l} ) {
452             die "no targets specified";
453         }
454         foreach my $target (@$target_l) {
455             if( 0 == length $target) {
456                 die "target has length 0";
457             }
458             unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
459                     $target =~ /^GOSA$/i ||
460                     $target =~ /^\*$/ ||
461                     $target =~ /KNOWN_SERVER/i ||
462                     $target =~ /JOBDB/i ||
463                     $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 ){
464                 die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
465             }
466         }
467     };
468     if($@) {
469         daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
470         daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 8);
471         $msg_hash = undef;
472     }
474     return ($msg_hash);
478 sub input_from_known_server {
479     my ($input, $remote_ip) = @_ ;  
480     my ($msg, $msg_hash, $module);
482     my $sql_statement= "SELECT * FROM known_server";
483     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
485     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
486         my $host_name = $hit->{hostname};
487         if( not $host_name =~ "^$remote_ip") {
488             next;
489         }
490         my $host_key = $hit->{hostkey};
491         daemon_log("DEBUG: input_from_known_server: host_name: $host_name", 7);
492         daemon_log("DEBUG: input_from_known_server: host_key: $host_key", 7);
494         # check if module can open msg envelope with module key
495         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
496         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
497             daemon_log("DEBUG: input_from_known_server: deciphering raise error", 7);
498             daemon_log("$@", 8);
499             next;
500         }
501         else {
502             $msg = $tmp_msg;
503             $msg_hash = $tmp_msg_hash;
504             $module = "SIPackages";
505             last;
506         }
507     }
509     if( (!$msg) || (!$msg_hash) || (!$module) ) {
510         daemon_log("INFO: Incoming message is not from a known server", 5);
511     }
512   
513     return ($msg, $msg_hash, $module);
517 sub input_from_known_client {
518     my ($input, $remote_ip) = @_ ;  
519     my ($msg, $msg_hash, $module);
521     my $sql_statement= "SELECT * FROM known_clients";
522     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
523     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
524         my $host_name = $hit->{hostname};
525         if( not $host_name =~ /^$remote_ip:\d*$/) {
526                 next;
527                 }
528         my $host_key = $hit->{hostkey};
529         &daemon_log("DEBUG: input_from_known_client: host_name: $host_name", 7);
530         &daemon_log("DEBUG: input_from_known_client: host_key: $host_key", 7);
532         # check if module can open msg envelope with module key
533         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
535         if( (!$msg) || (!$msg_hash) ) {
536             &daemon_log("DEGUG: input_from_known_client: deciphering raise error", 7);
537             &daemon_log("$@", 8);
538             next;
539         }
540         else {
541             $module = "SIPackages";
542             last;
543         }
544     }
546     if( (!$msg) || (!$msg_hash) || (!$module) ) {
547         &daemon_log("INFO: Incoming message is not from a known client", 5);
548     }
550     return ($msg, $msg_hash, $module);
554 sub input_from_unknown_host {
555     no strict "refs";
556     my ($input) = @_ ;
557     my ($msg, $msg_hash, $module);
558     my $error_string;
559     
560         my %act_modules = %$known_modules;
562         while( my ($mod, $info) = each(%act_modules)) {
564         # check a key exists for this module
565         my $module_key = ${$mod."_key"};
566         if( not defined $module_key ) {
567             if( $mod eq 'ArpHandler' ) {
568                 next;
569             }
570             daemon_log("ERROR: no key specified in config file for $mod", 1);
571             next;
572         }
573         daemon_log("DEBUG: $mod: $module_key", 7);
575         # check if module can open msg envelope with module key
576         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
577         if( (not defined $msg) || (not defined $msg_hash) ) {
578             next;
579         }
580         else {
581             $module = $mod;
582             last;
583         }
584     }
586     if( (!$msg) || (!$msg_hash) || (!$module)) {
587         daemon_log("INFO: Incoming message is not from an unknown host", 5);
588     }
590     return ($msg, $msg_hash, $module);
594 sub create_ciphering {
595     my ($passwd) = @_;
596         if((!defined($passwd)) || length($passwd)==0) {
597                 $passwd = "";
598         }
599     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
600     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
601     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
602     $my_cipher->set_iv($iv);
603     return $my_cipher;
607 sub encrypt_msg {
608     my ($msg, $key) = @_;
609     my $my_cipher = &create_ciphering($key);
610     my $len;
611     {
612             use bytes;
613             $len= 16-length($msg)%16;
614     }
615     $msg = "\0"x($len).$msg;
616     $msg = $my_cipher->encrypt($msg);
617     chomp($msg = &encode_base64($msg));
618     # there are no newlines allowed inside msg
619     $msg=~ s/\n//g;
620     return $msg;
624 sub decrypt_msg {
626     my ($msg, $key) = @_ ;
627     $msg = &decode_base64($msg);
628     my $my_cipher = &create_ciphering($key);
629     $msg = $my_cipher->decrypt($msg); 
630     $msg =~ s/\0*//g;
631     return $msg;
635 sub get_encrypt_key {
636     my ($target) = @_ ;
637     my $encrypt_key;
638     my $error = 0;
640     # target can be in known_server
641     if( not defined $encrypt_key ) {
642         my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
643         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
644         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
645             my $host_name = $hit->{hostname};
646             if( $host_name ne $target ) {
647                 next;
648             }
649             $encrypt_key = $hit->{hostkey};
650             last;
651         }
652     }
654     # target can be in known_client
655     if( not defined $encrypt_key ) {
656         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
657         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
658         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
659             my $host_name = $hit->{hostname};
660             if( $host_name ne $target ) {
661                 next;
662             }
663             $encrypt_key = $hit->{hostkey};
664             last;
665         }
666     }
668     return $encrypt_key;
672 #===  FUNCTION  ================================================================
673 #         NAME:  open_socket
674 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
675 #                [PeerPort] string necessary if port not appended by PeerAddr
676 #      RETURNS:  socket IO::Socket::INET
677 #  DESCRIPTION:  open a socket to PeerAddr
678 #===============================================================================
679 sub open_socket {
680     my ($PeerAddr, $PeerPort) = @_ ;
681     if(defined($PeerPort)){
682         $PeerAddr = $PeerAddr.":".$PeerPort;
683     }
684     my $socket;
685     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
686             Porto => "tcp",
687             Type => SOCK_STREAM,
688             Timeout => 5,
689             );
690     if(not defined $socket) {
691         return;
692     }
693 #    &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
694     return $socket;
698 #===  FUNCTION  ================================================================
699 #         NAME:  get_ip 
700 #   PARAMETERS:  interface name (i.e. eth0)
701 #      RETURNS:  (ip address) 
702 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
703 #===============================================================================
704 sub get_ip {
705         my $ifreq= shift;
706         my $result= "";
707         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
708         my $proto= getprotobyname('ip');
710         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
711                 or die "socket: $!";
713         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
714                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
715                 my ($port, $addr) = sockaddr_in $sin;
716                 my $ip            = inet_ntoa $addr;
718                 if ($ip && length($ip) > 0) {
719                         $result = $ip;
720                 }
721         }
723         return $result;
726 sub get_local_ip_for_remote_ip {
727         my $remote_ip= shift;
728         my $result="0.0.0.0";
730         if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
731                 if($remote_ip eq "127.0.0.1") {
732                         $result = "127.0.0.1";
733                 } else {
734                         my $PROC_NET_ROUTE= ('/proc/net/route');
736                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
737                                 or die "Could not open $PROC_NET_ROUTE";
739                         my @ifs = <PROC_NET_ROUTE>;
741                         close(PROC_NET_ROUTE);
743                         # Eat header line
744                         shift @ifs;
745                         chomp @ifs;
746                         foreach my $line(@ifs) {
747                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
748                                 my $destination;
749                                 my $mask;
750                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
751                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
752                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
753                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
754                                 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
755                                         # destination matches route, save mac and exit
756                                         $result= &get_ip($Iface);
757                                         last;
758                                 }
759                         }
760                 }
761         } else {
762                 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
763         }
764         return $result;
767 sub send_msg_to_target {
768     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
769     my $error = 0;
770     my $header;
771     my $new_status;
772     my $act_status;
773     my ($sql_statement, $res);
774   
775     if( $msg_header ) {
776         $header = "'$msg_header'-";
777     }
778     else {
779         $header = "";
780     }
782         # Patch the source ip
783         if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
784                 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
785                 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
786         }
788     # encrypt xml msg
789     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
791     # opensocket
792     my $socket = &open_socket($address);
793     if( !$socket ) {
794         daemon_log("ERROR: cannot send ".$header."msg to $address , host not reachable", 1);
795         $error++;
796     }
797     
798     if( $error == 0 ) {
799         # send xml msg
800         print $socket $crypted_msg."\n";
802         daemon_log("INFO: send ".$header."msg to $address", 5);
803         daemon_log("message:\n$msg", 8);
804         
805     }
807     # close socket in any case
808     if( $socket ) {
809         close $socket;
810     }
812     if( $error > 0 ) { $new_status = "down"; }
813     else { $new_status = $msg_header; }
816     # known_clients
817     $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
818     $res = $known_clients_db->select_dbentry($sql_statement);
819     if( keys(%$res) > 0) {
820         $act_status = $res->{1}->{'status'};
821         if( $act_status eq "down" ) {
822             $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
823             $res = $known_clients_db->del_dbentry($sql_statement);
824             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
825         } 
826         else { 
827             $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
828             $res = $known_clients_db->update_dbentry($sql_statement);
829             if($new_status eq "down"){
830                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
831             }
832             else {
833                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
834             }
835         }
836     }
838     # known_server
839     $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
840     $res = $known_server_db->select_dbentry($sql_statement);
841     if( keys(%$res) > 0 ) {
842         $act_status = $res->{1}->{'status'};
843         if( $act_status eq "down" ) {
844             $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
845             $res = $known_server_db->del_dbentry($sql_statement);
846             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
847         } 
848         else { 
849             $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
850             $res = $known_server_db->update_dbentry($sql_statement);
851             if($new_status eq "down"){
852                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
853             }
854             else {
855                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
856             }
857         }
858     }
859     return $error; 
863 sub _start {
864     my ($kernel) = $_[KERNEL];
865     &trigger_db_loop($kernel);
869 sub client_input {
870     no strict "refs";
871     my ($kernel, $session, $heap,$input,$wheel) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
872     my $session_id = $session->ID;
873     my ($msg, $msg_hash, $module);
874     my $error = 0;
875     my $answer_l;
876     my ($answer_header, @answer_target_l, $answer_source);
877     my $client_answer;
879     daemon_log("INFO: Incoming msg from '".$heap->{'remote_ip'}."'", 5);
880     daemon_log("DEBUG: Incoming message:\n$input", 8);
882     ####################
883     # check incoming msg
884     # msg is from a new client or gosa
885     ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
886     # msg is from a gosa-si-server or gosa-si-bus
887     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
888         ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
889     }
890     # msg is from a gosa-si-client
891     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
892         ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
893     }
894     # an error occurred
895     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
896         $error++;
897     }
899     ######################
900     # process incoming msg
901     if( $error == 0) {
902         daemon_log("DEBUG: Processing module ".$module, 7);
903         $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
905         if ( 0 > @{$answer_l} ) {
906             my $answer_str = join("\n", @{$answer_l});
907             daemon_log("DEGUB: $module: Got answer from module: \n".$answer_str,8);
908         }
909     }
910     if( !$answer_l ) { $error++ };
912     ########
913     # answer
914     if( $error == 0 ) {
916         foreach my $answer ( @{$answer_l} ) {
917             # for each answer in answer list
918             
919             # check outgoing msg to xml validity
920             my $answer_hash = &check_outgoing_xml_validity($answer);
921             if( not defined $answer_hash ) {
922                 next;
923             }
924             
925             $answer_header = @{$answer_hash->{'header'}}[0];
926             @answer_target_l = @{$answer_hash->{'target'}};
927             $answer_source = @{$answer_hash->{'source'}}[0];
929             # deliver msg to all targets 
930             foreach my $answer_target ( @answer_target_l ) {
932                 # targets of msg are all gosa-si-clients in known_clients_db
933                 if( $answer_target eq "*" ) {
934                     # answer is for all clients
935                     my $sql_statement= "SELECT * FROM known_clients";
936                     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
937                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
938                         my $host_name = $hit->{hostname};
939                         my $host_key = $hit->{hostkey};
940                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
941                     }
942                 }
944                 # targets of msg are all gosa-si-server in known_server_db
945                 elsif( $answer_target eq "KNOWN_SERVER" ) {
946                     # answer is for all server in known_server
947                     my $sql_statement= "SELECT * FROM known_server";
948                     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
949                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
950                         my $host_name = $hit->{hostname};
951                         my $host_key = $hit->{hostkey};
952                         $answer =~ s/KNOWN_SERVER/$host_name/g;
953                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
954                     }
955                 }
957                 # target of msg is GOsa
958                 elsif( $answer_target eq "GOSA" ) {
959                     $answer =~ /<session_id>(\d+)<\/session_id>/;
960                     my $session_id = $1;
961                     my $add_on = "";
962                     if( defined $session_id ) {
963                         $add_on = ".session_id=$session_id";
964                     }
965                     # answer is for GOSA and has to returned to connected client
966                     my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
967                     $client_answer = $gosa_answer.$add_on;
968                 }
970                 # target of msg is job queue at this host
971                 elsif( $answer_target eq "JOBDB") {
972                     $answer =~ /<header>(\S+)<\/header>/;   
973                     my $header;
974                     if( defined $1 ) { $header = $1; }
975                     &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header);
976                 }
978                 # target of msg is a mac address
979                 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 ) {
980                     daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
981                     my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
982                     my $query_res = $known_clients_db->select_dbentry( $sql_statement );
983                     my $found_ip_flag = 0;
984                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
985                         my $host_name = $hit->{hostname};
986                         my $host_key = $hit->{hostkey};
987                         $answer =~ s/$answer_target/$host_name/g;
988                         daemon_log("found host '$host_name', associated to '$answer_target'", 3);
989                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
990                         $found_ip_flag++ ;
991                     }   
992                     if( $found_ip_flag == 0) {
993                         daemon_log("WARNING: no host found in known_clients with mac address '$answer_target'", 3);
994                         if( $bus_activ eq "true" ) { 
995                             daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
996                             my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
997                             my $query_res = $known_server_db->select_dbentry( $sql_statement );
998                             while( my ($hit_num, $hit) = each %{ $query_res } ) {    
999                                 my $bus_address = $hit->{hostname};
1000                                 my $bus_key = $hit->{hostkey};
1001                                 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
1002                                 last;
1003                             }
1004                         }
1006                     }
1008                 #  answer is for one specific host   
1009                 } else {
1010                     # get encrypt_key
1011                     my $encrypt_key = &get_encrypt_key($answer_target);
1012                     if( not defined $encrypt_key ) {
1013                         # unknown target, forward msg to bus
1014                         daemon_log("WARNING: unknown target '$answer_target'", 3);
1015                         if( $bus_activ eq "true" ) { 
1016                             daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
1017                             my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
1018                             my $query_res = $known_server_db->select_dbentry( $sql_statement );
1019                             my $res_length = keys( %{$query_res} );
1020                             if( $res_length == 0 ){
1021                                 daemon_log("WARNING: send '$answer_header' to '$bus_address' failed, no bus found in known_server", 3);
1022                             }
1023                             else {
1024                                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
1025                                     my $bus_key = $hit->{hostkey};
1026                                     &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
1027                                 }
1028                             }
1029                         }
1030                         next;
1031                     }
1032                     # send_msg
1033                     &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
1034                 }
1035             }
1036         }
1037     }
1039     if( $client_answer ) {
1040         if( $client_answer =~ s/session_id=(\d+)$// ) {
1041             my $session_id = $1;
1042             if( defined $session_id ) {
1043                 my $session_reference = $kernel->ID_id_to_session($session_id);
1044                 $heap = $session_reference->get_heap();
1045             }     
1046         }
1047         $heap->{client}->put($client_answer);
1048     }
1050     return;
1055 sub trigger_db_loop {
1056 #       my ($kernel) = $_[KERNEL];
1057         my ($kernel) = @_ ;
1058         $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1062 sub watch_for_new_jobs {
1063         my ($kernel,$heap) = @_[KERNEL, HEAP];
1065         # check gosa job queue for jobs with executable timestamp
1066     my $timestamp = &get_time();
1067     my $sql_statement = "SELECT * FROM ".$job_queue_tn.
1068         " WHERE status='waiting' AND timestamp<'$timestamp'";
1069         my $res = $job_db->select_dbentry( $sql_statement );
1071         while( my ($id, $hit) = each %{$res} ) {         
1072                 my $jobdb_id = $hit->{id};
1073                 my $macaddress = $hit->{'macaddress'};
1074         my $job_msg = $hit->{'xmlmessage'};
1075         my $header = $hit->{'headertag'};
1076         my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1077                 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1078                 # expect macaddress is unique!!!!!!
1079                 my $target = $res_hash->{1}->{hostname};
1081                 if (not defined $target) {
1082                         &daemon_log("ERROR: no host found for mac address: $macaddress", 1);
1083                         &daemon_log("$hit->{xmlmessage}", 8);
1084             my $sql_statement = "UPDATE $job_queue_tn ".
1085                 "SET status='error', result='no host found for mac address' ".
1086                 "WHERE id='$jobdb_id'";
1087                         my $res = $job_db->update_dbentry($sql_statement);
1088                         next;
1089                 }
1091                 # change header
1092         $job_msg =~ s/<header>job_/<header>gosa_/;
1094                 # add sqlite_id 
1095         $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1097                 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header);
1098     }
1100         $kernel->delay_set('watch_for_new_jobs',3);
1104 #==== MAIN = main ==============================================================
1105 #  parse commandline options
1106 Getopt::Long::Configure( "bundling" );
1107 GetOptions("h|help" => \&usage,
1108         "c|config=s" => \$cfg_file,
1109         "f|foreground" => \$foreground,
1110         "v|verbose+" => \$verbose,
1111         "no-bus+" => \$no_bus,
1112         "no-arp+" => \$no_arp,
1113            );
1115 #  read and set config parameters
1116 &check_cmdline_param ;
1117 &read_configfile;
1118 &check_pid;
1120 $SIG{CHLD} = 'IGNORE';
1122 # forward error messages to logfile
1123 if( ! $foreground ) {
1124     open(STDERR, '>>', $log_file);
1125     open(STDOUT, '>>', $log_file);
1128 # Just fork, if we are not in foreground mode
1129 if( ! $foreground ) { 
1130     chdir '/'                 or die "Can't chdir to /: $!";
1131     $pid = fork;
1132     setsid                    or die "Can't start a new session: $!";
1133     umask 0;
1134 } else { 
1135     $pid = $$; 
1138 # Do something useful - put our PID into the pid_file
1139 if( 0 != $pid ) {
1140     open( LOCK_FILE, ">$pid_file" );
1141     print LOCK_FILE "$pid\n";
1142     close( LOCK_FILE );
1143     if( !$foreground ) { 
1144         exit( 0 ) 
1145     };
1148 daemon_log(" ", 1);
1149 daemon_log("$0 started!", 1);
1151 if ($no_bus > 0) {
1152     $bus_activ = "false"
1157 # delete old DBsqlite lock files
1158 #unlink('/tmp/gosa_si_lock*');
1160 # connect to gosa-si job queue
1161 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "progress INTEGER", "headertag", "targettag", "xmlmessage", "macaddress");
1162 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1163 $job_db->create_table('jobs', \@job_col_names);
1165 # connect to known_clients_db
1166 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1167 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1168 $known_clients_db->create_table('known_clients', \@clients_col_names);
1170 # connect to known_server_db
1171 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1172 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1173 $known_server_db->create_table('known_server', \@server_col_names);
1175 # connect to login_usr_db
1176 my @login_users_col_names = ('client', 'user', 'timestamp');
1177 $login_users_db = GOSA::DBsqlite->new($login_users_file_name);
1178 $login_users_db->create_table("login_users", \@login_users_col_names);
1180 # create xml object used for en/decrypting
1181 $xml = new XML::Simple();
1183 # create socket for incoming xml messages
1184 POE::Component::Server::TCP->new(
1185         Port => $server_port,
1186         ClientInput => \&client_input,
1187 );
1188 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1190 # create session for repeatedly checking the job queue for jobs
1191 POE::Session->create(
1192         inline_states => {
1193                 _start => \&_start,
1194                 watch_for_new_jobs => \&watch_for_new_jobs,
1195         }
1196 );
1199 # import all modules
1200 &import_modules;
1202 # check wether all modules are gosa-si valid passwd check
1204 POE::Kernel->run();
1205 exit;