Code

add April to list of months
[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, $server_events);
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 ($max_clients);
54 my ($pid_file, $procid, $pid, $log_file);
55 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
56 my ($arp_activ, $arp_fifo, $arp_fifo_path);
57 my ($xml);
59 # variables declared in config file are always set to 'our'
60 our (%cfg_defaults, $log_file, $pid_file, 
61     $bus_activ, $bus_passwd, $bus_ip, $bus_port,
62     $server_activ, $server_ip, $server_port, $SIPackages_key, $max_clients,
63     $arp_activ, $arp_fifo_path,
64     $gosa_activ, $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;
88 $no_arp = 0;
90 # name of table for storing gosa jobs
91 our $job_queue_table_name = 'jobs';
92 our $job_db;
94 # holds all other gosa-sd as well as the gosa-sd-bus
95 our $known_server_db;
97 # holds all registrated clients
98 our $known_clients_db;
100 %cfg_defaults =
101 ("general" =>
102     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
103     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
104     "child_max" => [\$child_max, 10],
105     "child_min" => [\$child_min, 3],
106     "child_timeout" => [\$child_timeout, 180],
107     "job_queue_timeout" => [\$job_queue_timeout, undef],
108     "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/gosa-si-server_jobs.db'],
109     "job_queue_loop_delay" => [\$job_queue_loop_delay, 3],
110     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/gosa-si-server_known_clients.db' ],
111     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/gosa-si-server_known_server.db'],
112    },
113 "bus" =>
114     {"bus_activ" => [\$bus_activ, "on"],
115     "bus_passwd" => [\$bus_passwd, ""],
116     "bus_ip" => [\$bus_ip, "0.0.0.0"],
117     "bus_port" => [\$bus_port, "20080"],
118     },
119 "server" =>
120     {"server_activ" => [\$server_activ, "on"],
121     "server_ip" => [\$server_ip, "0.0.0.0"],
122     "server_port" => [\$server_port, "20081"],
123     "SIPackages_key" => [\$SIPackages_key, "none"],
124     "max_clients" => [\$max_clients, 100],
125     },
126 "arp" =>
127     {"arp_activ" => [\$arp_activ, "on"],
128     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
129     },
130 "gosa" =>
131     {"gosa_activ" => [\$gosa_activ, "on"],
132     "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
133     "gosa_port" => [\$gosa_port, "20082"],
134     "GosaPackages_key" => [\$GosaPackages_key, "none"],
135     },
136     );
139 #===  FUNCTION  ================================================================
140 #         NAME:  usage
141 #   PARAMETERS:  nothing
142 #      RETURNS:  nothing
143 #  DESCRIPTION:  print out usage text to STDERR
144 #===============================================================================
145 sub usage {
146     print STDERR << "EOF" ;
147 usage: $0 [-hvf] [-c config]
149            -h        : this (help) message
150            -c <file> : config file
151            -f        : foreground, process will not be forked to background
152            -v        : be verbose (multiple to increase verbosity)
153            -no-bus   : starts $0 without connection to bus
154            -no-arp   : starts $0 without connection to arp module
155  
156 EOF
157     print "\n" ;
161 #===  FUNCTION  ================================================================
162 #         NAME:  read_configfile
163 #   PARAMETERS:  cfg_file - string -
164 #      RETURNS:  nothing
165 #  DESCRIPTION:  read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168     my $cfg;
169     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
170         if( -r $cfg_file ) {
171             $cfg = Config::IniFiles->new( -file => $cfg_file );
172         } else {
173             print STDERR "Couldn't read config file!\n";
174         }
175     } else {
176         $cfg = Config::IniFiles->new() ;
177     }
178     foreach my $section (keys %cfg_defaults) {
179         foreach my $param (keys %{$cfg_defaults{ $section }}) {
180             my $pinfo = $cfg_defaults{ $section }{ $param };
181             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
182         }
183     }
187 #===  FUNCTION  ================================================================
188 #         NAME:  logging
189 #   PARAMETERS:  level - string - default 'info'
190 #                msg - string -
191 #                facility - string - default 'LOG_DAEMON'
192 #      RETURNS:  nothing
193 #  DESCRIPTION:  function for logging
194 #===============================================================================
195 sub daemon_log {
196     # log into log_file
197     my( $msg, $level ) = @_;
198     if(not defined $msg) { return }
199     if(not defined $level) { $level = 1 }
200     if(defined $log_file){
201         open(LOG_HANDLE, ">>$log_file");
202         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
203             print STDERR "cannot open $log_file: $!";
204             return }
205             chomp($msg);
206             if($level <= $verbose){
207                 my ($seconds, $minutes, $hours, $monthday, $month,
208                         $year, $weekday, $yearday, $sommertime) = localtime(time);
209                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
210                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
211                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
212                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
213                 $month = $monthnames[$month];
214                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
215                 $year+=1900;
216                 my $name = $0;
217                 $name =~ s/\.\///;
219                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
220                 print LOG_HANDLE $log_msg;
221                 if( $foreground ) { 
222                     print STDERR $log_msg;
223                 }
224             }
225         close( LOG_HANDLE );
226     }
227 #log into syslog
228 #    my ($msg, $level, $facility) = @_;
229 #    if(not defined $msg) {return}
230 #    if(not defined $level) {$level = "info"}
231 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
232 #    openlog($0, "pid,cons,", $facility);
233 #    syslog($level, $msg);
234 #    closelog;
235 #    return;
239 sub get_time {
240     my ($seconds, $minutes, $hours, $monthday, $month,
241             $year, $weekday, $yearday, $sommertime) = localtime(time);
242     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
243     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
244     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
245     $month+=1;
246     $month = $month < 10 ? $month = "0".$month : $month;
247     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
248     $year+=1900;
249     return "$year$month$monthday$hours$minutes$seconds";
254 #===  FUNCTION  ================================================================
255 #         NAME:  check_cmdline_param
256 #   PARAMETERS:  nothing
257 #      RETURNS:  nothing
258 #  DESCRIPTION:  validates commandline parameter
259 #===============================================================================
260 sub check_cmdline_param () {
261     my $err_config;
262     my $err_counter = 0;
263         if(not defined($cfg_file)) {
264                 $cfg_file = "/etc/gosa-si/server.conf";
265                 if(! -r $cfg_file) {
266                         $err_config = "please specify a config file";
267                         $err_counter += 1;
268                 }
269     }
270     if( $err_counter > 0 ) {
271         &usage( "", 1 );
272         if( defined( $err_config)) { print STDERR "$err_config\n"}
273         print STDERR "\n";
274         exit( -1 );
275     }
279 #===  FUNCTION  ================================================================
280 #         NAME:  check_pid
281 #   PARAMETERS:  nothing
282 #      RETURNS:  nothing
283 #  DESCRIPTION:  handels pid processing
284 #===============================================================================
285 sub check_pid {
286     $pid = -1;
287     # Check, if we are already running
288     if( open(LOCK_FILE, "<$pid_file") ) {
289         $pid = <LOCK_FILE>;
290         if( defined $pid ) {
291             chomp( $pid );
292             if( -f "/proc/$pid/stat" ) {
293                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
294                 if( $0 eq $stat ) {
295                     close( LOCK_FILE );
296                     exit -1;
297                 }
298             }
299         }
300         close( LOCK_FILE );
301         unlink( $pid_file );
302     }
304     # create a syslog msg if it is not to possible to open PID file
305     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
306         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
307         if (open(LOCK_FILE, '<', $pid_file)
308                 && ($pid = <LOCK_FILE>))
309         {
310             chomp($pid);
311             $msg .= "(PID $pid)\n";
312         } else {
313             $msg .= "(unable to read PID)\n";
314         }
315         if( ! ($foreground) ) {
316             openlog( $0, "cons,pid", "daemon" );
317             syslog( "warning", $msg );
318             closelog();
319         }
320         else {
321             print( STDERR " $msg " );
322         }
323         exit( -1 );
324     }
327 #===  FUNCTION  ================================================================
328 #         NAME:  import_modules
329 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
330 #                are stored
331 #      RETURNS:  nothing
332 #  DESCRIPTION:  each file in module_path which ends with '.pm' and activation 
333 #                state is on is imported by "require 'file';"
334 #===============================================================================
335 sub import_modules {
336     daemon_log(" ", 1);
338     if (not -e $modules_path) {
339         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
340     }
342     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
343     while (defined (my $file = readdir (DIR))) {
344         if (not $file =~ /(\S*?).pm$/) {
345             next;
346         }
347                 my $mod_name = $1;
349         if( $file =~ /ArpHandler.pm/ ) {
350             if( $no_arp > 0 ) {
351                 next;
352             }
353         }
354         
355         eval { require $file; };
356         if ($@) {
357             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
358             daemon_log("$@", 5);
359                 } else {
360                         my $info = eval($mod_name.'::get_module_info()');
361                         # Only load module if get_module_info() returns a non-null object
362                         if( $info ) {
363                                 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
364                                 $known_modules->{$mod_name} = $info;
365                                 daemon_log("module $mod_name loaded", 1);
366                         }
367                 }
368     }   
369     close (DIR);
373 #===  FUNCTION  ================================================================
374 #         NAME:  sig_int_handler
375 #   PARAMETERS:  signal - string - signal arose from system
376 #      RETURNS:  noting
377 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
378 #===============================================================================
379 sub sig_int_handler {
380     my ($signal) = @_;
382     daemon_log("shutting down gosa-si-server", 1);
383     exit(1);
385 $SIG{INT} = \&sig_int_handler;
389 sub check_key_and_xml_validity {
390     my ($crypted_msg, $module_key) = @_;
391 #print STDERR "crypted_msg:$crypted_msg\n";
392 #print STDERR "modul_key:$module_key\n";
394     my $msg;
395     my $msg_hash;
396     eval{
397         $msg = &decrypt_msg($crypted_msg, $module_key);
398         &main::daemon_log("decrypted_msg: \n$msg", 8);
400         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
402         # check header
403         my $header_l = $msg_hash->{'header'};
404         if( 1 != @{$header_l} ) {
405             die'header error';
406         }
407         my $header = @{$header_l}[0];
408         if( 0 == length $header) {
409             die 'header error';
410         }
412         # check source
413         my $source_l = $msg_hash->{'source'};
414         if( 1 != @{$source_l} ) {
415             die'source error';
416         }
417         my $source = @{$source_l}[0];
418         if( 0 == length $source) {
419             die 'source error';
420         }
422         # check target
423         my $target_l = $msg_hash->{'target'};
424         if( 1 != @{$target_l} ) {
425             die'target error';
426         }
427         my $target = @{$target_l}[0];
428         if( 0 == length $target) {
429             die 'target error';
430         }
432     };
433     if($@) {
434         &main::daemon_log("WARNING: do not understand the message:", 5);
435         &main::daemon_log("$@", 8);
436     }
438     return ($msg, $msg_hash);
442 sub input_from_known_server {
443     my ($input, $remote_ip) = @_ ;  
444     my ($msg, $msg_hash, $module);
446     my $sql_statement= "SELECT * FROM known_server";
447     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
448     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
449         my $host_name = $hit->{hostname};
450         if( not $host_name =~ "^$remote_ip") {
451             next;
452         }
453         my $host_key = $hit->{hostkey};
454         daemon_log("SIPackages: host_name: $host_name", 7);
455         daemon_log("SIPackages: host_key: $host_key", 7);
457         # check if module can open msg envelope with module key
458         my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
459         if( (!$msg) || (!$msg_hash) ) {
460             daemon_log("SIPackages: deciphering raise error", 7);
461             daemon_log("$@", 8);
462             next;
463         }
464         else {
465             $module = "SIPackages";
466             last;
467         }
468     }
470     if( (!$msg) || (!$msg_hash) || (!$module) ) {
471         daemon_log("Incoming message is not from a known server", 3);
472     }
473   
474     return ($msg, $msg_hash, $module);
478 sub input_from_known_client {
479     my ($input, $remote_ip) = @_ ;  
480     my ($msg, $msg_hash, $module);
482     my $sql_statement= "SELECT * FROM known_clients";
483     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
484     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
485         my $host_name = $hit->{hostname};
486         if( not $host_name =~ /^$remote_ip:\d*$/) {
487             next;
488                 }
489         my $host_key = $hit->{hostkey};
490         &daemon_log("SIPackages: host_name: $host_name", 7);
491         &daemon_log("SIPackages: host_key: $host_key", 7);
493         # check if module can open msg envelope with module key
494         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
496         if( (!$msg) || (!$msg_hash) ) {
497             &daemon_log("SIPackages: deciphering raise error", 7);
498             &daemon_log("$@", 8);
499             next;
500         }
501         else {
502             $module = "SIPackages";
503             last;
504         }
505     }
507     if( (!$msg) || (!$msg_hash) || (!$module) ) {
508         &daemon_log("Incoming message is not from a known client", 3);
509     }
511     return ($msg, $msg_hash, $module);
515 sub input_from_unknown_host {
516     no strict "refs";
517     my ($input) = @_ ;
518     my ($msg, $msg_hash, $module);
519     
520         my %act_modules = %$known_modules;
522         while( my ($mod, $info) = each(%act_modules)) {
523         # check a key exists for this module
524         my $module_key = ${$mod."_key"};
525         if( ! $module_key ) {
526             daemon_log("ERROR: no key specified in config file for $mod", 1);
527             next;
528         }
529         daemon_log("$mod: $module_key", 5);
531         # check if module can open msg envelope with module key
532         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
533         if( (!$msg) || (!$msg_hash) ) {
534             daemon_log("$mod: deciphering failed", 5);
535             next;
536         }
537         else {
538             $module = $mod;
539             last;
540         }
541     }
543     if( (!$msg) || (!$msg_hash) || (!$module)) {
544         daemon_log("Incoming message is not from a unknown host", 3);
545     }
547     return ($msg, $msg_hash, $module);
550 sub create_ciphering {
551     my ($passwd) = @_;
552     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
553     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
554     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
555     $my_cipher->set_iv($iv);
556     return $my_cipher;
560 sub encrypt_msg {
561     my ($msg, $key) = @_;
562     my $my_cipher = &create_ciphering($key);
563     {
564       use bytes;
565       $msg = "\0"x(16-length($msg)%16).$msg;
566     }
567     $msg = $my_cipher->encrypt($msg);
568     chomp($msg = &encode_base64($msg));
569     # there are no newlines allowed inside msg
570     $msg=~ s/\n//g;
571     return $msg;
575 sub decrypt_msg {
576     my ($msg, $key) = @_ ;
577     $msg = &decode_base64($msg);
578     my $my_cipher = &create_ciphering($key);
579     $msg = $my_cipher->decrypt($msg); 
580     $msg =~ s/\0*//g;
581     return $msg;
585 sub get_encrypt_key {
586     my ($target) = @_ ;
587     my $encrypt_key;
588     my $error = 0;
590     # target can be in known_server
591     if( !$encrypt_key ) {
592         my $sql_statement= "SELECT * FROM known_server";
593         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
594         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
595             my $host_name = $hit->{hostname};
596             if( $host_name ne $target ) {
597                 next;
598             }
599             my $host_key = $hit->{hostkey};
600             last;
601         }
602     }
603    
605     # target can be in known_client
606     if( !$encrypt_key ) {
607         my $sql_statement= "SELECT * FROM known_clients";
608         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
609         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
610             my $host_name = $hit->{hostname};
611             if( $host_name ne $target ) {
612                 next;
613             }
614             $encrypt_key = $hit->{hostkey};
615             last;
616         }
617     }
619     return $encrypt_key;
623 #===  FUNCTION  ================================================================
624 #         NAME:  open_socket
625 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
626 #                [PeerPort] string necessary if port not appended by PeerAddr
627 #      RETURNS:  socket IO::Socket::INET
628 #  DESCRIPTION:  open a socket to PeerAddr
629 #===============================================================================
630 sub open_socket {
631     my ($PeerAddr, $PeerPort) = @_ ;
632     if(defined($PeerPort)){
633         $PeerAddr = $PeerAddr.":".$PeerPort;
634     }
635     my $socket;
636     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
637             Porto => "tcp",
638             Type => SOCK_STREAM,
639             Timeout => 5,
640             );
641     if(not defined $socket) {
642         return;
643     }
644     &daemon_log("open_socket: $PeerAddr", 7);
645     return $socket;
649 sub send_msg_to_target {
650     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
651     my $error = 0;
653     if( $msg_header ) {
654         $msg_header = "'$msg_header'-";
655     }
656     else {
657         $msg_header = "";
658     }
660     # encrypt xml msg
661     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
663     # opensocket
664     my $socket = &open_socket($address);
665     if( !$socket ) {
666         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
667         $error++;
668     }
669     
670     if( $error == 0 ) {
671         # send xml msg
672         print $socket $crypted_msg."\n";
674         daemon_log("send ".$msg_header."msg to $address", 1);
675         daemon_log("message:\n$msg", 8);
677     }
679     # close socket in any case
680     if( $socket ) {
681         close $socket;
682     }
684     return;
688 sub _start {
689     my ($kernel) = $_[KERNEL];
690     &trigger_db_loop($kernel);
694 sub client_input {
695     no strict "refs";
696     my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
697     my ($msg, $msg_hash, $module);
698     my $error = 0;
699     my $answer_l;
700     my ($answer_header, @answer_target_l, $answer_source);
701     my $client_answer;
703     daemon_log("Incoming msg:\n$input\n", 8);
705     # msg is from a new client or gosa
706     ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
708     # msg is from a gosa-si-server or gosa-si-bus
709     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
710         ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
711     }
713     # msg is from a gosa-si-client
714     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
715         ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
716     }
718     # an error occurred
719     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
720         $error++;
721     }
723     ######################
724     # process incoming msg
725     if( $error == 0) {
726         daemon_log("Processing module ".$module, 3);
727         $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
729         if ( 0 > @{$answer_l} ) {
730             my $answer_str = join("\n", @{$answer_l});
731             daemon_log("$module: Got answer from module: \n".$answer_str,8);
732         }
733     }
734     if( !$answer_l ) { $error++ };
736     ########
737     # answer
738     if( $error == 0 ) {
740         # for each answer in answer list
741         foreach my $answer ( @{$answer_l} ) {
743             # check answer if gosa-si envelope conform
744             if( $error == 0 ) {
745                 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
746                 $answer_header = @{$answer_hash->{'header'}}[0];
747                 @answer_target_l = @{$answer_hash->{'target'}};
748                 $answer_source = @{$answer_hash->{'source'}}[0];
749                 if( !$answer_header ) {
750                     daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
751                     $error++;
752                 }
753                 if( 0 == length @answer_target_l ) {
754                     daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
755                     $error++;
756                 }
757                 if( !$answer_source ) {
758                     daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
759                     $error++;
760                 }
762                 if( $error != 0 ) {
763                     next;
764                 }
766                 # deliver msg to all targets 
767                 foreach my $answer_target ( @answer_target_l ) {
768                     if( $answer_target eq "*" ) {
769                         # answer is for all clients
770                         my $sql_statement= "SELECT * FROM known_clients";
771                         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
772                         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
773                             my $host_name = $hit->{hostname};
774                             my $host_key = $hit->{hostkey};
775                             &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
776                         }
777                     }
778                     elsif( $answer_target eq "GOSA" ) {
779                         # answer is for GOSA and has to returned to connected client
780                         my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
781                         $client_answer = $gosa_answer;
782                     }
783                     elsif( $answer_target eq "KNOWN_SERVER" ) {
784                         # answer is for all server in known_server
785                         my $sql_statement= "SELECT * FROM known_server";
786                         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
787                         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
788                             my $host_name = $hit->{hostname};
789                             my $host_key = $hit->{hostkey};
790                             $answer =~ s/KNOWN_SERVER/$host_name/g;
791                             &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
792                         }
793                     }
794                     else {
795                         # answer is for one specific host
796                         # get encrypt_key
797                         my $encrypt_key = &get_encrypt_key($answer_target);
798                         if( !$encrypt_key ) {
799                             daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
800                             next;
801                         }
802                         # send_msg
803                         &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
804                     }
805                 }
806             }
807         }
808     }
810     if( $client_answer ) {
811         $heap->{client}->put($client_answer);
812     }
814     return;
819 sub trigger_db_loop {
820 #       my ($kernel) = $_[KERNEL];
821         my ($kernel) = @_ ;
822         $kernel->delay_set('watch_for_new_jobs',3);
826 sub watch_for_new_jobs {
827         my ($kernel,$heap) = @_[KERNEL, HEAP];
829         # check gosa job queue for jobs with executable timestamp
830     my $timestamp = &get_time();
832     my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
833         " WHERE status='waiting' AND timestamp<'$timestamp'";
835         my $res = $job_db->select_dbentry( $sql_statement );
837         while( my ($id, $hit) = each %{$res} ) {         
839                 my $jobdb_id = $hit->{id};
840                 my $macaddress = $hit->{macaddress};
841                 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
842                 my $out_msg_hash = $job_msg_hash;
843         my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
844                 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
845                 # expect macaddress is unique!!!!!!
846                 my $target = $res_hash->{1}->{hostname};
848                 if (not defined $target) {
849                         &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
850                         &daemon_log("xml message: $hit->{xmlmessage}", 5);
851             my $sql_statement = "UPDATE $job_queue_table_name ".
852                 "SET status='error', result='no host found for mac address' ".
853                 "WHERE id='$jobdb_id'";
854                         my $res = $job_db->update_dbentry($sql_statement);
855                         next;
856                 }
858                 # add target
859                 &add_content2xml_hash($out_msg_hash, "target", $target);
861                 # add new header
862                 my $out_header = $job_msg_hash->{header}[0];
863                 $out_header =~ s/job_/gosa_/;
864                 delete $out_msg_hash->{header};
865                 &add_content2xml_hash($out_msg_hash, "header", $out_header);
867                 # add sqlite_id 
868                 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
870                 my $out_msg = &create_xml_string($out_msg_hash);
872                 # encrypt msg as a GosaPackage module
873                 my $cipher = &create_ciphering($GosaPackages_key);
874                 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
876                 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
878                 if ($error == 0) {
879                         my $sql_statement = "UPDATE $job_queue_table_name ".
880                 "SET status='processing', targettag='$target' ".
881                 "WHERE id='$jobdb_id'";
882                         my $res = $job_db->update_dbentry($sql_statement);
883                 } else {
884             my $sql_statement = "UPDATE $job_queue_table_name ".
885                 "SET status='error' ".
886                 "WHERE id='$jobdb_id'";
887                         my $res = $job_db->update_dbentry($sql_statement);
888                 }
889         }
891         $kernel->delay_set('watch_for_new_jobs',3);
895 #==== MAIN = main ==============================================================
896 #  parse commandline options
897 Getopt::Long::Configure( "bundling" );
898 GetOptions("h|help" => \&usage,
899         "c|config=s" => \$cfg_file,
900         "f|foreground" => \$foreground,
901         "v|verbose+" => \$verbose,
902         "no-bus+" => \$no_bus,
903         "no-arp+" => \$no_arp,
904            );
906 #  read and set config parameters
907 &check_cmdline_param ;
908 &read_configfile;
909 &check_pid;
911 $SIG{CHLD} = 'IGNORE';
913 # forward error messages to logfile
914 if( ! $foreground ) {
915     open(STDERR, '>>', $log_file);
916     open(STDOUT, '>>', $log_file);
919 # Just fork, if we are not in foreground mode
920 if( ! $foreground ) { 
921     chdir '/'                 or die "Can't chdir to /: $!";
922     $pid = fork;
923     setsid                    or die "Can't start a new session: $!";
924     umask 0;
925 } else { 
926     $pid = $$; 
929 # Do something useful - put our PID into the pid_file
930 if( 0 != $pid ) {
931     open( LOCK_FILE, ">$pid_file" );
932     print LOCK_FILE "$pid\n";
933     close( LOCK_FILE );
934     if( !$foreground ) { 
935         exit( 0 ) 
936     };
939 daemon_log(" ", 1);
940 daemon_log("$0 started!", 1);
942 # delete old DBsqlite lock files
943 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
945 # connect to gosa-si job queue
946 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
947 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
948 $job_db->create_table('jobs', \@job_col_names);
950 # connect to known_clients_db
951 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
952 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
953 $known_clients_db->create_table('known_clients', \@clients_col_names);
955 # connect to known_server_db
956 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
957 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
958 $known_server_db->create_table('known_server', \@server_col_names);
960 # import all modules
961 &import_modules;
963 # check wether all modules are gosa-si valid passwd check
965 # create xml object used for en/decrypting
966 $xml = new XML::Simple();
969 # create socket for incoming xml messages
970 POE::Component::Server::TCP->new(
971         Port => $server_port,
972         ClientInput => \&client_input,
973 );
974 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
976 # create session for repeatedly checking the job queue for jobs
977 POE::Session->create(
978         inline_states => {
979                 _start => \&_start,
980                 watch_for_new_jobs => \&watch_for_new_jobs,
981         }
982 );
984 POE::Kernel->run();
985 exit;