Code

bdc990bea7e824f875f57849b8837f195610ba37
[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;
29 use Fcntl;
30 use IO::Socket::INET;
31 use IO::Handle;
32 use IO::Select;
33 use Symbol qw(qualify_to_ref);
34 use Crypt::Rijndael;
35 use MIME::Base64;
36 use Digest::MD5  qw(md5 md5_hex md5_base64);
37 use XML::Simple;
38 use Data::Dumper;
39 use Sys::Syslog qw( :DEFAULT setlogsock);
40 use Cwd;
41 use File::Spec;
42 use GOSA::DBsqlite;
43 use POE qw(Component::Server::TCP);
45 my $modules_path = "/usr/lib/gosa-si/modules";
46 use lib "/usr/lib/gosa-si/modules";
48 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
49 my ($bus, $msg_to_bus, $bus_cipher);
50 my ($server, $server_mac_address);
51 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
52 my ($known_modules, $known_clients_file_name, $known_server_file_name);
53 my ($pid_file, $procid, $pid, $log_file);
54 my ($arp_activ, $arp_fifo);
55 my ($xml);
57 # variables declared in config file are always set to 'our'
58 our (%cfg_defaults, $log_file, $pid_file, 
59     $server_ip, $server_port, $SIPackages_key, 
60     $arp_activ, 
61     $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
62 );
64 # additional variable which should be globaly accessable
65 our $server_address;
66 our $bus_address;
67 our $gosa_address;
68 our $no_bus;
69 our $no_arp;
70 our $verbose;
71 our $forground;
72 our $cfg_file;
74 # specifies the verbosity of the daemon_log
75 $verbose = 0 ;
77 # if foreground is not null, script will be not forked to background
78 $foreground = 0 ;
80 # specifies the timeout seconds while checking the online status of a registrating client
81 $ping_timeout = 5;
83 $no_bus = 0;
85 $no_arp = 0;
87 # name of table for storing gosa jobs
88 our $job_queue_table_name = 'jobs';
89 our $job_db;
91 # holds all other gosa-sd as well as the gosa-sd-bus
92 our $known_server_db;
94 # holds all registrated clients
95 our $known_clients_db;
97 %cfg_defaults = (
98 "general" => {
99     "log-file" => [\$log_file, "/var/run/".$0.".log"],
100     "pid-file" => [\$pid_file, "/var/run/".$0.".pid"],
101     },
102 "server" => {
103 #    "ip" => [\$server_ip, "0.0.0.0"],
104     "port" => [\$server_port, "20081"],
105     "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
106     "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
107     },
108 "GOsaPackages" => {
109     "ip" => [\$gosa_ip, "0.0.0.0"],
110     "port" => [\$gosa_port, "20082"],
111     "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
112     "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
113     "key" => [\$GosaPackages_key, "none"],
114     },
115 "SIPackages" => {
116     "key" => [\$SIPackages_key, "none"],
117     },
118 );
121 #===  FUNCTION  ================================================================
122 #         NAME:  usage
123 #   PARAMETERS:  nothing
124 #      RETURNS:  nothing
125 #  DESCRIPTION:  print out usage text to STDERR
126 #===============================================================================
127 sub usage {
128     print STDERR << "EOF" ;
129 usage: $0 [-hvf] [-c config]
131            -h        : this (help) message
132            -c <file> : config file
133            -f        : foreground, process will not be forked to background
134            -v        : be verbose (multiple to increase verbosity)
135            -no-bus   : starts $0 without connection to bus
136            -no-arp   : starts $0 without connection to arp module
137  
138 EOF
139     print "\n" ;
143 #===  FUNCTION  ================================================================
144 #         NAME:  read_configfile
145 #   PARAMETERS:  cfg_file - string -
146 #      RETURNS:  nothing
147 #  DESCRIPTION:  read cfg_file and set variables
148 #===============================================================================
149 sub read_configfile {
150     my $cfg;
151     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
152         if( -r $cfg_file ) {
153             $cfg = Config::IniFiles->new( -file => $cfg_file );
154         } else {
155             print STDERR "Couldn't read config file!\n";
156         }
157     } else {
158         $cfg = Config::IniFiles->new() ;
159     }
160     foreach my $section (keys %cfg_defaults) {
161         foreach my $param (keys %{$cfg_defaults{ $section }}) {
162             my $pinfo = $cfg_defaults{ $section }{ $param };
163             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
164         }
165     }
169 #===  FUNCTION  ================================================================
170 #         NAME:  logging
171 #   PARAMETERS:  level - string - default 'info'
172 #                msg - string -
173 #                facility - string - default 'LOG_DAEMON'
174 #      RETURNS:  nothing
175 #  DESCRIPTION:  function for logging
176 #===============================================================================
177 sub daemon_log {
178     # log into log_file
179     my( $msg, $level ) = @_;
180     if(not defined $msg) { return }
181     if(not defined $level) { $level = 1 }
182     if(defined $log_file){
183         open(LOG_HANDLE, ">>$log_file");
184         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
185             print STDERR "cannot open $log_file: $!";
186             return }
187             chomp($msg);
188             if($level <= $verbose){
189                 my ($seconds, $minutes, $hours, $monthday, $month,
190                         $year, $weekday, $yearday, $sommertime) = localtime(time);
191                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
192                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
193                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
194                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
195                 $month = $monthnames[$month];
196                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
197                 $year+=1900;
198                 my $name = $0;
199                 $name =~ s/\.\///;
201                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
202                 print LOG_HANDLE $log_msg;
203                 if( $foreground ) { 
204                     print STDERR $log_msg;
205                 }
206             }
207         close( LOG_HANDLE );
208     }
209 #log into syslog
210 #    my ($msg, $level, $facility) = @_;
211 #    if(not defined $msg) {return}
212 #    if(not defined $level) {$level = "info"}
213 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
214 #    openlog($0, "pid,cons,", $facility);
215 #    syslog($level, $msg);
216 #    closelog;
217 #    return;
221 sub get_time {
222     my ($seconds, $minutes, $hours, $monthday, $month,
223             $year, $weekday, $yearday, $sommertime) = localtime(time);
224     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
225     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
226     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
227     $month+=1;
228     $month = $month < 10 ? $month = "0".$month : $month;
229     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
230     $year+=1900;
231     return "$year$month$monthday$hours$minutes$seconds";
236 #===  FUNCTION  ================================================================
237 #         NAME:  check_cmdline_param
238 #   PARAMETERS:  nothing
239 #      RETURNS:  nothing
240 #  DESCRIPTION:  validates commandline parameter
241 #===============================================================================
242 sub check_cmdline_param () {
243     my $err_config;
244     my $err_counter = 0;
245         if(not defined($cfg_file)) {
246                 $cfg_file = "/etc/gosa-si/server.conf";
247                 if(! -r $cfg_file) {
248                         $err_config = "please specify a config file";
249                         $err_counter += 1;
250                 }
251     }
252     if( $err_counter > 0 ) {
253         &usage( "", 1 );
254         if( defined( $err_config)) { print STDERR "$err_config\n"}
255         print STDERR "\n";
256         exit( -1 );
257     }
261 #===  FUNCTION  ================================================================
262 #         NAME:  check_pid
263 #   PARAMETERS:  nothing
264 #      RETURNS:  nothing
265 #  DESCRIPTION:  handels pid processing
266 #===============================================================================
267 sub check_pid {
268     $pid = -1;
269     # Check, if we are already running
270     if( open(LOCK_FILE, "<$pid_file") ) {
271         $pid = <LOCK_FILE>;
272         if( defined $pid ) {
273             chomp( $pid );
274             if( -f "/proc/$pid/stat" ) {
275                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
276                 if( $0 eq $stat ) {
277                     close( LOCK_FILE );
278                     exit -1;
279                 }
280             }
281         }
282         close( LOCK_FILE );
283         unlink( $pid_file );
284     }
286     # create a syslog msg if it is not to possible to open PID file
287     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
288         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
289         if (open(LOCK_FILE, '<', $pid_file)
290                 && ($pid = <LOCK_FILE>))
291         {
292             chomp($pid);
293             $msg .= "(PID $pid)\n";
294         } else {
295             $msg .= "(unable to read PID)\n";
296         }
297         if( ! ($foreground) ) {
298             openlog( $0, "cons,pid", "daemon" );
299             syslog( "warning", $msg );
300             closelog();
301         }
302         else {
303             print( STDERR " $msg " );
304         }
305         exit( -1 );
306     }
309 #===  FUNCTION  ================================================================
310 #         NAME:  import_modules
311 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
312 #                are stored
313 #      RETURNS:  nothing
314 #  DESCRIPTION:  each file in module_path which ends with '.pm' and activation 
315 #                state is on is imported by "require 'file';"
316 #===============================================================================
317 sub import_modules {
318     daemon_log(" ", 1);
320     if (not -e $modules_path) {
321         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
322     }
324     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
325     while (defined (my $file = readdir (DIR))) {
326         if (not $file =~ /(\S*?).pm$/) {
327             next;
328         }
329                 my $mod_name = $1;
331         if( $file =~ /ArpHandler.pm/ ) {
332             if( $no_arp > 0 ) {
333                 next;
334             }
335         }
336         
337         eval { require $file; };
338         if ($@) {
339             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
340             daemon_log("$@", 5);
341                 } else {
342                         my $info = eval($mod_name.'::get_module_info()');
343                         # Only load module if get_module_info() returns a non-null object
344                         if( $info ) {
345                                 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
346                                 $known_modules->{$mod_name} = $info;
347                                 daemon_log("module $mod_name loaded", 1);
348                         }
349                 }
350     }   
351     close (DIR);
355 #===  FUNCTION  ================================================================
356 #         NAME:  sig_int_handler
357 #   PARAMETERS:  signal - string - signal arose from system
358 #      RETURNS:  noting
359 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
360 #===============================================================================
361 sub sig_int_handler {
362     my ($signal) = @_;
364     daemon_log("shutting down gosa-si-server", 1);
365     exit(1);
367 $SIG{INT} = \&sig_int_handler;
371 sub check_key_and_xml_validity {
372     my ($crypted_msg, $module_key) = @_;
373 #print STDERR "crypted_msg:$crypted_msg\n";
374 #print STDERR "modul_key:$module_key\n";
376     my $msg;
377     my $msg_hash;
378     eval{
379         $msg = &decrypt_msg($crypted_msg, $module_key);
381         if ($msg =~ /<xml>/i){
382                 &main::daemon_log("decrypted_msg: \n$msg", 8);
383                 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
385                 # check header
386                 my $header_l = $msg_hash->{'header'};
387                 if( 1 != @{$header_l} ) {
388                     die 'header error';
389                 }
390                 my $header = @{$header_l}[0];
391                 if( 0 == length $header) {
392                     die 'header error';
393                 }
395                 # check source
396                 my $source_l = $msg_hash->{'source'};
397                 if( not defined @{$source_l} or 1 != @{$source_l} ) {
398                     die 'source error';
399                 }
400                 my $source = @{$source_l}[0];
401                 if( 0 == length $source) {
402                     die 'source error';
403                 }
405                 # check target
406                 my $target_l = $msg_hash->{'target'};
407                 if( 1 != @{$target_l} ) {
408                     die'target error';
409                 }
410                 my $target = @{$target_l}[0];
411                 if( 0 == length $target) {
412                     die 'target error';
413                 }
414         }
415     };
416     if($@) {
417         &main::daemon_log("WARNING: do not understand the message", 5);
418         &main::daemon_log("$@", 8);
419     }
421     return ($msg, $msg_hash);
425 sub input_from_known_server {
426     my ($input, $remote_ip) = @_ ;  
427     my ($msg, $msg_hash, $module);
429     my $sql_statement= "SELECT * FROM known_server";
430     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
432     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
433         my $host_name = $hit->{hostname};
434         if( not $host_name =~ "^$remote_ip") {
435             next;
436         }
437         my $host_key = $hit->{hostkey};
438         daemon_log("SIPackages: known_server host_name: $host_name", 7);
439         daemon_log("SIPackages: known_server host_key: $host_key", 7);
441         # check if module can open msg envelope with module key
442         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
443         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
444             daemon_log("SIPackages: deciphering raise error", 7);
445             daemon_log("$@", 8);
446             next;
447         }
448         else {
449             $msg = $tmp_msg;
450             $msg_hash = $tmp_msg_hash;
451             $module = "SIPackages";
452             last;
453         }
454     }
456     if( (!$msg) || (!$msg_hash) || (!$module) ) {
457         daemon_log("Incoming message is not from a known server", 3);
458     }
459   
460     return ($msg, $msg_hash, $module);
464 sub input_from_known_client {
465     my ($input, $remote_ip) = @_ ;  
466     my ($msg, $msg_hash, $module);
468     my $sql_statement= "SELECT * FROM known_clients";
469     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
470     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
471         my $host_name = $hit->{hostname};
472         if( not $host_name =~ /^$remote_ip:\d*$/) {
473             next;
474                 }
475         my $host_key = $hit->{hostkey};
476         &daemon_log("SIPackages: known_client host_name: $host_name", 7);
477         &daemon_log("SIPackages: known_client host_key: $host_key", 7);
479         # check if module can open msg envelope with module key
480         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
482         if( (!$msg) || (!$msg_hash) ) {
483             &daemon_log("SIPackages: deciphering raise error", 7);
484             &daemon_log("$@", 8);
485             next;
486         }
487         else {
488             $module = "SIPackages";
489             last;
490         }
491     }
493     if( (!$msg) || (!$msg_hash) || (!$module) ) {
494         &daemon_log("Incoming message is not from a known client", 3);
495     }
497     return ($msg, $msg_hash, $module);
501 sub input_from_unknown_host {
502     no strict "refs";
503     my ($input) = @_ ;
504     my ($msg, $msg_hash, $module);
505     
506         my %act_modules = %$known_modules;
508         while( my ($mod, $info) = each(%act_modules)) {
510         # check a key exists for this module
511         my $module_key = ${$mod."_key"};
512         if( ! $module_key ) {
513             daemon_log("ERROR: no key specified in config file for $mod", 1);
514             next;
515         }
516         daemon_log("$mod: $module_key", 5);
518         # check if module can open msg envelope with module key
519         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
520         if( (!$msg) || (!$msg_hash) ) {
521             #daemon_log("$mod: deciphering failed", 5);
522             next;
523         }
524         else {
525             $module = $mod;
526             last;
527         }
528     }
530     if( (!$msg) || (!$msg_hash) || (!$module)) {
531         daemon_log("Incoming message is not from a unknown host", 5);
532     }
534     return ($msg, $msg_hash, $module);
537 sub create_ciphering {
538     my ($passwd) = @_;
539         if((!defined($passwd)) || length($passwd)==0) {
540                 $passwd = "";
541         }
542     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
543     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
544     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
545     $my_cipher->set_iv($iv);
546     return $my_cipher;
550 sub encrypt_msg {
551     my ($msg, $key) = @_;
552     my $my_cipher = &create_ciphering($key);
553     {
554       use bytes;
555       $msg = "\0"x(16-length($msg)%16).$msg;
556     }
557     $msg = $my_cipher->encrypt($msg);
558     chomp($msg = &encode_base64($msg));
559     # there are no newlines allowed inside msg
560     $msg=~ s/\n//g;
561     return $msg;
565 sub decrypt_msg {
566     my ($msg, $key) = @_ ;
567     $msg = &decode_base64($msg);
568     my $my_cipher = &create_ciphering($key);
569     $msg = $my_cipher->decrypt($msg); 
570     $msg =~ s/\0*//g;
571     return $msg;
575 sub get_encrypt_key {
576     my ($target) = @_ ;
577     my $encrypt_key;
578     my $error = 0;
580     # target can be in known_server
581     if( not defined $encrypt_key ) {
582         my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
583         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
584         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
585             my $host_name = $hit->{hostname};
586             if( $host_name ne $target ) {
587                 next;
588             }
589             $encrypt_key = $hit->{hostkey};
590             last;
591         }
592     }
594     # target can be in known_client
595     if( not defined $encrypt_key ) {
596         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
597         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
598         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
599             my $host_name = $hit->{hostname};
600             if( $host_name ne $target ) {
601                 next;
602             }
603             $encrypt_key = $hit->{hostkey};
604             last;
605         }
606     }
608     return $encrypt_key;
612 #===  FUNCTION  ================================================================
613 #         NAME:  open_socket
614 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
615 #                [PeerPort] string necessary if port not appended by PeerAddr
616 #      RETURNS:  socket IO::Socket::INET
617 #  DESCRIPTION:  open a socket to PeerAddr
618 #===============================================================================
619 sub open_socket {
620     my ($PeerAddr, $PeerPort) = @_ ;
621     if(defined($PeerPort)){
622         $PeerAddr = $PeerAddr.":".$PeerPort;
623     }
624     my $socket;
625     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
626             Porto => "tcp",
627             Type => SOCK_STREAM,
628             Timeout => 5,
629             );
630     if(not defined $socket) {
631         return;
632     }
633     &daemon_log("open_socket: $PeerAddr", 7);
634     return $socket;
638 #===  FUNCTION  ================================================================
639 #         NAME:  get_ip 
640 #   PARAMETERS:  interface name (i.e. eth0)
641 #      RETURNS:  (ip address) 
642 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
643 #===============================================================================
644 sub get_ip {
645         my $ifreq= shift;
646         my $result= "";
647         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
648         my $proto= getprotobyname('ip');
650         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
651                 or die "socket: $!";
653         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
654                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
655                 my ($port, $addr) = sockaddr_in $sin;
656                 my $ip            = inet_ntoa $addr;
658                 if ($ip && length($ip) > 0) {
659                         $result = $ip;
660                 }
661         }
663         return $result;
666 sub get_local_ip_for_remote_ip {
667         my $remote_ip= shift;
668         my $result="0.0.0.0";
670         if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
671                 if($remote_ip eq "127.0.0.1") {
672                         $result = "127.0.0.1";
673                 } else {
674                         my $PROC_NET_ROUTE= ('/proc/net/route');
676                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
677                                 or die "Could not open $PROC_NET_ROUTE";
679                         my @ifs = <PROC_NET_ROUTE>;
681                         close(PROC_NET_ROUTE);
683                         # Eat header line
684                         shift @ifs;
685                         chomp @ifs;
686                         foreach my $line(@ifs) {
687                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
688                                 my $destination;
689                                 my $mask;
690                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
691                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
692                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
693                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
694                                 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
695                                         # destination matches route, save mac and exit
696                                         $result= &get_ip($Iface);
697                                         last;
698                                 }
699                         }
700                 }
701         } else {
702                 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
703         }
704         return $result;
707 sub send_msg_to_target {
708     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
709     my $error = 0;
710     my $header;
711     my $new_status;
712     my $act_status;
713     my ($sql_statement, $res);
714   
715     if( $msg_header ) {
716         $header = "'$msg_header'-";
717     }
718     else {
719         $header = "";
720     }
722         # Patch the source ip
723         if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
724                 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
725                 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
726         }
728     # encrypt xml msg
729     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
731     # opensocket
732     my $socket = &open_socket($address);
733     if( !$socket ) {
734         daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
735         $error++;
736     }
737     
738     if( $error == 0 ) {
739         # send xml msg
740         print $socket $crypted_msg."\n";
742         daemon_log("send ".$header."msg to $address", 1);
743         daemon_log("message:\n$msg", 8);
744         
745     }
747     # close socket in any case
748     if( $socket ) {
749         close $socket;
750     }
752     if( $error > 0 ) { $new_status = "down"; }
753     else { $new_status = $msg_header; }
756     # known_clients
757     $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
758     $res = $known_clients_db->select_dbentry($sql_statement);
759     if( keys(%$res) > 0) {
760         $act_status = $res->{1}->{'status'};
761         if( $act_status eq "down" ) {
762             $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
763             $res = $known_clients_db->del_dbentry($sql_statement);
764             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
765         } 
766         else { 
767             $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
768             $res = $known_clients_db->update_dbentry($sql_statement);
769             if($new_status eq "down"){
770                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
771             }
772             else {
773                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
774             }
775         }
776     }
778     # known_server
779     $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
780     $res = $known_server_db->select_dbentry($sql_statement);
781     if( keys(%$res) > 0 ) {
782         $act_status = $res->{1}->{'status'};
783         if( $act_status eq "down" ) {
784             $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
785             $res = $known_clients_db->del_dbentry($sql_statement);
786             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
787         } 
788         else { 
789             $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
790             $res = $known_server_db->update_dbentry($sql_statement);
791             if($new_status eq "down"){
792                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
793             }
794             else {
795                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
796             }
797         }
798     }
800     return; 
804 sub _start {
805     my ($kernel) = $_[KERNEL];
806     &trigger_db_loop($kernel);
810 sub client_input {
811     no strict "refs";
812     my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
813     my ($msg, $msg_hash, $module);
814     my $error = 0;
815     my $answer_l;
816     my ($answer_header, @answer_target_l, $answer_source);
817     my $client_answer;
819     daemon_log("Incoming msg from '".$heap->{'remote_ip'}."'", 7);
820     daemon_log("\n$input", 8);
822     # msg is from a new client or gosa
823     ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
825     # msg is from a gosa-si-server or gosa-si-bus
826     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
827         ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
828     }
830     # msg is from a gosa-si-client
831     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
832         ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
833     }
835     # an error occurred
836     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
837         $error++;
838     }
840     ######################
841     # process incoming msg
842     if( $error == 0) {
843         daemon_log("Processing module ".$module, 5);
844         $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $heap->{'remote_ip'});
846         if ( 0 > @{$answer_l} ) {
847             my $answer_str = join("\n", @{$answer_l});
848             daemon_log("$module: Got answer from module: \n".$answer_str,8);
849         }
850     }
851     if( !$answer_l ) { $error++ };
853     ########
854     # answer
855     if( $error == 0 ) {
857         # for each answer in answer list
858         foreach my $answer ( @{$answer_l} ) {
860                 my $error = 0;
861                 # check answer if gosa-si envelope conform
862                 if(defined($answer)) {
863                         my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
864                         $answer_header = @{$answer_hash->{'header'}}[0];
865                         @answer_target_l = @{$answer_hash->{'target'}};
866                         $answer_source = @{$answer_hash->{'source'}}[0];
867                         if( !$answer_header ) {
868                                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
869                                 daemon_log("\n$answer", 8);
870                                 $error++;
871                         }
872                         if( 0 == length @answer_target_l ) {
873                                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
874                                 daemon_log("\n$answer", 8);
875                                 $error++;
876                         }
877                         if( !$answer_source ) {
878                                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
879                                 daemon_log("\n$answer", 8);
880                                 $error++;
881                         }
883                         if( $error != 0 ) {
884                                 next;
885                         }
886                 }
888                 # deliver msg to all targets 
889                 foreach my $answer_target ( @answer_target_l ) {
890                         if( $answer_target eq "*" ) {
891                                 # answer is for all clients
892                                 my $sql_statement= "SELECT * FROM known_clients";
893                                 my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
894                                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
895                                         my $host_name = $hit->{hostname};
896                                         my $host_key = $hit->{hostkey};
897                                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
898                                 }
899                         }
900                         elsif( $answer_target eq "GOSA" ) {
901                                 # answer is for GOSA and has to returned to connected client
902                                 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
903                                 $client_answer = $gosa_answer;
904                         }
905                         elsif( $answer_target eq "KNOWN_SERVER" ) {
906                                 # answer is for all server in known_server
907                                 my $sql_statement= "SELECT * FROM known_server";
908                                 my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
909                                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
910                                         my $host_name = $hit->{hostname};
911                                         my $host_key = $hit->{hostkey};
912                                         $answer =~ s/KNOWN_SERVER/$host_name/g;
913                                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
914                                 }
915                         }
916                         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 ) {
917                                 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
918                                 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
919                                 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
920                                 my $found_ip_flag = 0;
921                                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
922                                         my $host_name = $hit->{hostname};
923                                         my $host_key = $hit->{hostkey};
924                                         $answer =~ s/$answer_target/$host_name/g;
925                                         daemon_log("found host '$host_name', assoziated to '$answer_target'", 3);
926                                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
927                                         $found_ip_flag++ ;
928                                 }   
929                                 if( $found_ip_flag == 0) {
930                                         daemon_log("WARNING: no host found in known_clients with mac address '$answer_target', forward msg to bus", 1);
931                                         my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
932                                         my $query_res = $known_server_db->select_dbentry( $sql_statement );
933                                         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
934                                                 my $bus_address = $hit->{hostname};
935                                                 my $bus_key = $hit->{hostkey};
936                                                 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
937                                                 last;
938                                         }
940                                 }
941                         } else {
942                                 # ... answer is for one specific host
944                                 # get encrypt_key
945                                 my $encrypt_key = &get_encrypt_key($answer_target);
946                                 if( not defined $encrypt_key ) {
947                                         # unknown target, forward msg to bus
948                                         daemon_log("WARNING: unknown target '$answer_target', forward msg to bus", 3);
949                                         my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
950                                         my $query_res = $known_server_db->select_dbentry( $sql_statement );
951                                         my $bus_key = $query_res->{1}->{hostkey};
952                                         &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
953                                         next;
954                                 }
955                                 # send_msg
956                                 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
957                         }
958                 }
959         }
960     }
962     if( $client_answer ) {
963             $heap->{client}->put($client_answer);
964     }
966     return;
971 sub trigger_db_loop {
972 #       my ($kernel) = $_[KERNEL];
973         my ($kernel) = @_ ;
974         $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
978 sub watch_for_new_jobs {
979         my ($kernel,$heap) = @_[KERNEL, HEAP];
981         # check gosa job queue for jobs with executable timestamp
982     my $timestamp = &get_time();
984     my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
985         " WHERE status='waiting' AND timestamp<'$timestamp'";
987         my $res = $job_db->select_dbentry( $sql_statement );
989         while( my ($id, $hit) = each %{$res} ) {         
991                 my $jobdb_id = $hit->{id};
992                 my $macaddress = $hit->{macaddress};
993                 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
994                 my $out_msg_hash = $job_msg_hash;
995         my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
996                 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
997                 # expect macaddress is unique!!!!!!
998                 my $target = $res_hash->{1}->{hostname};
1000                 if (not defined $target) {
1001                         &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1002                         &daemon_log("xml message: $hit->{xmlmessage}", 5);
1003             my $sql_statement = "UPDATE $job_queue_table_name ".
1004                 "SET status='error', result='no host found for mac address' ".
1005                 "WHERE id='$jobdb_id'";
1006                         my $res = $job_db->update_dbentry($sql_statement);
1007                         next;
1008                 }
1010                 # add target
1011                 &add_content2xml_hash($out_msg_hash, "target", $target);
1013                 # add new header
1014                 my $out_header = $job_msg_hash->{header}[0];
1015                 $out_header =~ s/job_/gosa_/;
1016                 delete $out_msg_hash->{header};
1017                 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1019                 # add sqlite_id 
1020                 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1022                 my $out_msg = &create_xml_string($out_msg_hash);
1024                 # encrypt msg as a GosaPackage module
1025                 my $cipher = &create_ciphering($GosaPackages_key);
1026                 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1028                 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
1030                 if ($error == 0) {
1031                         my $sql_statement = "UPDATE $job_queue_table_name ".
1032                 "SET status='processing', targettag='$target' ".
1033                 "WHERE id='$jobdb_id'";
1034                         my $res = $job_db->update_dbentry($sql_statement);
1035                 } else {
1036             my $sql_statement = "UPDATE $job_queue_table_name ".
1037                 "SET status='error' ".
1038                 "WHERE id='$jobdb_id'";
1039                         my $res = $job_db->update_dbentry($sql_statement);
1040                 }
1041         }
1043         $kernel->delay_set('watch_for_new_jobs',3);
1047 #==== MAIN = main ==============================================================
1048 #  parse commandline options
1049 Getopt::Long::Configure( "bundling" );
1050 GetOptions("h|help" => \&usage,
1051         "c|config=s" => \$cfg_file,
1052         "f|foreground" => \$foreground,
1053         "v|verbose+" => \$verbose,
1054         "no-bus+" => \$no_bus,
1055         "no-arp+" => \$no_arp,
1056            );
1058 #  read and set config parameters
1059 &check_cmdline_param ;
1060 &read_configfile;
1061 &check_pid;
1063 $SIG{CHLD} = 'IGNORE';
1065 # forward error messages to logfile
1066 if( ! $foreground ) {
1067     open(STDERR, '>>', $log_file);
1068     open(STDOUT, '>>', $log_file);
1071 # Just fork, if we are not in foreground mode
1072 if( ! $foreground ) { 
1073     chdir '/'                 or die "Can't chdir to /: $!";
1074     $pid = fork;
1075     setsid                    or die "Can't start a new session: $!";
1076     umask 0;
1077 } else { 
1078     $pid = $$; 
1081 # Do something useful - put our PID into the pid_file
1082 if( 0 != $pid ) {
1083     open( LOCK_FILE, ">$pid_file" );
1084     print LOCK_FILE "$pid\n";
1085     close( LOCK_FILE );
1086     if( !$foreground ) { 
1087         exit( 0 ) 
1088     };
1091 daemon_log(" ", 1);
1092 daemon_log("$0 started!", 1);
1094 # delete old DBsqlite lock files
1095 #unlink('/tmp/gosa_si_lock*');
1097 # connect to gosa-si job queue
1098 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1099 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1100 $job_db->create_table('jobs', \@job_col_names);
1102 # connect to known_clients_db
1103 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1104 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1105 $known_clients_db->create_table('known_clients', \@clients_col_names);
1107 # connect to known_server_db
1108 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1109 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1110 $known_server_db->create_table('known_server', \@server_col_names);
1112 # create xml object used for en/decrypting
1113 $xml = new XML::Simple();
1115 # create socket for incoming xml messages
1116 POE::Component::Server::TCP->new(
1117         Port => $server_port,
1118         ClientInput => \&client_input,
1119 );
1120 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1122 # create session for repeatedly checking the job queue for jobs
1123 POE::Session->create(
1124         inline_states => {
1125                 _start => \&_start,
1126                 watch_for_new_jobs => \&watch_for_new_jobs,
1127         }
1128 );
1131 # import all modules
1132 &import_modules;
1134 # check wether all modules are gosa-si valid passwd check
1136 POE::Kernel->run();
1137 exit;