Code

Updated to the new use of messages
[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 Time::HiRes qw( gettimeofday );
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 GOSA::DBsqlite;
44 use POE qw(Component::Server::TCP);
46 my $modules_path = "/usr/lib/gosa-si/modules";
47 use lib "/usr/lib/gosa-si/modules";
49 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
50 my ($bus, $msg_to_bus, $bus_cipher);
51 my ($server, $server_mac_address, $server_events);
52 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
53 my ($known_modules, $known_clients_file_name, $known_server_file_name);
54 my ($max_clients);
55 my ($pid_file, $procid, $pid, $log_file);
56 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
57 my ($arp_activ, $arp_fifo, $arp_fifo_path);
58 my ($xml);
60 # variables declared in config file are always set to 'our'
61 our (%cfg_defaults, $log_file, $pid_file, 
62     $bus_activ, $bus_passwd, $bus_ip, $bus_port,
63     $server_activ, $server_ip, $server_port, $SIPackages_key, $max_clients,
64     $arp_activ, $arp_fifo_path,
65     $gosa_activ, $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
66 );
68 # additional variable which should be globaly accessable
69 our $server_address;
70 our $bus_address;
71 our $gosa_address;
72 our $no_bus;
73 our $no_arp;
74 our $verbose;
75 our $forground;
76 our $cfg_file;
78 # specifies the verbosity of the daemon_log
79 $verbose = 0 ;
81 # if foreground is not null, script will be not forked to background
82 $foreground = 0 ;
84 # specifies the timeout seconds while checking the online status of a registrating client
85 $ping_timeout = 5;
87 $no_bus = 0;
89 $no_arp = 0;
91 # name of table for storing gosa jobs
92 our $job_queue_table_name = 'jobs';
93 our $job_db;
95 # holds all other gosa-sd as well as the gosa-sd-bus
96 our $known_server_db;
98 # holds all registrated clients
99 our $known_clients_db;
101 %cfg_defaults =
102 ("general" =>
103     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
104     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
105     "child_max" => [\$child_max, 10],
106     "child_min" => [\$child_min, 3],
107     "child_timeout" => [\$child_timeout, 180],
108     "job_queue_timeout" => [\$job_queue_timeout, undef],
109     "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
110     "job_queue_loop_delay" => [\$job_queue_loop_delay, 3],
111     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
112     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/known_server.db'],
113    },
114 "bus" =>
115     {"bus_activ" => [\$bus_activ, "on"],
116     "bus_passwd" => [\$bus_passwd, ""],
117     "bus_ip" => [\$bus_ip, "0.0.0.0"],
118     "bus_port" => [\$bus_port, "20080"],
119     },
120 "server" =>
121     {"server_activ" => [\$server_activ, "on"],
122     "server_ip" => [\$server_ip, "0.0.0.0"],
123     "server_port" => [\$server_port, "20081"],
124     "SIPackages_key" => [\$SIPackages_key, "none"],
125     "max_clients" => [\$max_clients, 100],
126     },
127 "arp" =>
128     {"arp_activ" => [\$arp_activ, "on"],
129     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
130     },
131 "gosa" =>
132     {"gosa_activ" => [\$gosa_activ, "on"],
133     "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
134     "gosa_port" => [\$gosa_port, "20082"],
135     "GosaPackages_key" => [\$GosaPackages_key, "none"],
136     },
137     );
140 #===  FUNCTION  ================================================================
141 #         NAME:  usage
142 #   PARAMETERS:  nothing
143 #      RETURNS:  nothing
144 #  DESCRIPTION:  print out usage text to STDERR
145 #===============================================================================
146 sub usage {
147     print STDERR << "EOF" ;
148 usage: $0 [-hvf] [-c config]
150            -h        : this (help) message
151            -c <file> : config file
152            -f        : foreground, process will not be forked to background
153            -v        : be verbose (multiple to increase verbosity)
154            -no-bus   : starts $0 without connection to bus
155            -no-arp   : starts $0 without connection to arp module
156  
157 EOF
158     print "\n" ;
162 #===  FUNCTION  ================================================================
163 #         NAME:  read_configfile
164 #   PARAMETERS:  cfg_file - string -
165 #      RETURNS:  nothing
166 #  DESCRIPTION:  read cfg_file and set variables
167 #===============================================================================
168 sub read_configfile {
169     my $cfg;
170     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
171         if( -r $cfg_file ) {
172             $cfg = Config::IniFiles->new( -file => $cfg_file );
173         } else {
174             print STDERR "Couldn't read config file!\n";
175         }
176     } else {
177         $cfg = Config::IniFiles->new() ;
178     }
179     foreach my $section (keys %cfg_defaults) {
180         foreach my $param (keys %{$cfg_defaults{ $section }}) {
181             my $pinfo = $cfg_defaults{ $section }{ $param };
182             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
183         }
184     }
188 #===  FUNCTION  ================================================================
189 #         NAME:  logging
190 #   PARAMETERS:  level - string - default 'info'
191 #                msg - string -
192 #                facility - string - default 'LOG_DAEMON'
193 #      RETURNS:  nothing
194 #  DESCRIPTION:  function for logging
195 #===============================================================================
196 sub daemon_log {
197     # log into log_file
198     my( $msg, $level ) = @_;
199     if(not defined $msg) { return }
200     if(not defined $level) { $level = 1 }
201     if(defined $log_file){
202         open(LOG_HANDLE, ">>$log_file");
203         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
204             print STDERR "cannot open $log_file: $!";
205             return }
206             chomp($msg);
207             if($level <= $verbose){
208                 my ($seconds, $minutes, $hours, $monthday, $month,
209                         $year, $weekday, $yearday, $sommertime) = localtime(time);
210                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
211                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
212                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
213                 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
214                 $month = $monthnames[$month];
215                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
216                 $year+=1900;
217                 my $name = $0;
218                 $name =~ s/\.\///;
220                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
221                 print LOG_HANDLE $log_msg;
222                 if( $foreground ) { 
223                     print STDERR $log_msg;
224                 }
225             }
226         close( LOG_HANDLE );
227     }
228 #log into syslog
229 #    my ($msg, $level, $facility) = @_;
230 #    if(not defined $msg) {return}
231 #    if(not defined $level) {$level = "info"}
232 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
233 #    openlog($0, "pid,cons,", $facility);
234 #    syslog($level, $msg);
235 #    closelog;
236 #    return;
240 sub get_time {
241     my ($seconds, $minutes, $hours, $monthday, $month,
242             $year, $weekday, $yearday, $sommertime) = localtime(time);
243     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
244     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
245     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
246     $month+=1;
247     $month = $month < 10 ? $month = "0".$month : $month;
248     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
249     $year+=1900;
250     return "$year$month$monthday$hours$minutes$seconds";
255 #===  FUNCTION  ================================================================
256 #         NAME:  check_cmdline_param
257 #   PARAMETERS:  nothing
258 #      RETURNS:  nothing
259 #  DESCRIPTION:  validates commandline parameter
260 #===============================================================================
261 sub check_cmdline_param () {
262     my $err_config;
263     my $err_counter = 0;
264         if(not defined($cfg_file)) {
265                 $cfg_file = "/etc/gosa-si/server.conf";
266                 if(! -r $cfg_file) {
267                         $err_config = "please specify a config file";
268                         $err_counter += 1;
269                 }
270     }
271     if( $err_counter > 0 ) {
272         &usage( "", 1 );
273         if( defined( $err_config)) { print STDERR "$err_config\n"}
274         print STDERR "\n";
275         exit( -1 );
276     }
280 #===  FUNCTION  ================================================================
281 #         NAME:  check_pid
282 #   PARAMETERS:  nothing
283 #      RETURNS:  nothing
284 #  DESCRIPTION:  handels pid processing
285 #===============================================================================
286 sub check_pid {
287     $pid = -1;
288     # Check, if we are already running
289     if( open(LOCK_FILE, "<$pid_file") ) {
290         $pid = <LOCK_FILE>;
291         if( defined $pid ) {
292             chomp( $pid );
293             if( -f "/proc/$pid/stat" ) {
294                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
295                 if( $0 eq $stat ) {
296                     close( LOCK_FILE );
297                     exit -1;
298                 }
299             }
300         }
301         close( LOCK_FILE );
302         unlink( $pid_file );
303     }
305     # create a syslog msg if it is not to possible to open PID file
306     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
307         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
308         if (open(LOCK_FILE, '<', $pid_file)
309                 && ($pid = <LOCK_FILE>))
310         {
311             chomp($pid);
312             $msg .= "(PID $pid)\n";
313         } else {
314             $msg .= "(unable to read PID)\n";
315         }
316         if( ! ($foreground) ) {
317             openlog( $0, "cons,pid", "daemon" );
318             syslog( "warning", $msg );
319             closelog();
320         }
321         else {
322             print( STDERR " $msg " );
323         }
324         exit( -1 );
325     }
328 #===  FUNCTION  ================================================================
329 #         NAME:  import_modules
330 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
331 #                are stored
332 #      RETURNS:  nothing
333 #  DESCRIPTION:  each file in module_path which ends with '.pm' and activation 
334 #                state is on is imported by "require 'file';"
335 #===============================================================================
336 sub import_modules {
337     daemon_log(" ", 1);
339     if (not -e $modules_path) {
340         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
341     }
343     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
344     while (defined (my $file = readdir (DIR))) {
345         if (not $file =~ /(\S*?).pm$/) {
346             next;
347         }
348                 my $mod_name = $1;
350         if( $file =~ /ArpHandler.pm/ ) {
351             if( $no_arp > 0 ) {
352                 next;
353             }
354         }
355         
356         eval { require $file; };
357         if ($@) {
358             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
359             daemon_log("$@", 5);
360                 } else {
361                         my $info = eval($mod_name.'::get_module_info()');
362                         # Only load module if get_module_info() returns a non-null object
363                         if(defined($info)) {
364                                 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
365                                 $known_modules->{$mod_name} = $info;
366                                 daemon_log("module $mod_name loaded", 1);
367                         }
368                 }
369     }   
370     close (DIR);
374 #===  FUNCTION  ================================================================
375 #         NAME:  sig_int_handler
376 #   PARAMETERS:  signal - string - signal arose from system
377 #      RETURNS:  noting
378 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
379 #===============================================================================
380 sub sig_int_handler {
381     my ($signal) = @_;
383     daemon_log("shutting down gosa-si-server", 1);
384     exit(1);
386 $SIG{INT} = \&sig_int_handler;
390 sub check_key_and_xml_validity {
391     my ($crypted_msg, $module_key) = @_;
392 #print STDERR "crypted_msg:$crypted_msg\n";
393 #print STDERR "modul:$module\n";
394 #print STDERR "modul_key:$module_key\n";
396     my $msg;
397     my $msg_hash;
398     eval{
399         $msg = &decrypt_msg($crypted_msg, $module_key);
400         &main::daemon_log("decrypted_msg: \n$msg", 8);
402         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
404         # check header
405         my $header_l = $msg_hash->{'header'};
406         if( 1 != @{$header_l} ) {
407             die'header error';
408         }
409         my $header = @{$header_l}[0];
410         if( 0 == length $header) {
411             die 'header error';
412         }
414         # check source
415         my $source_l = $msg_hash->{'source'};
416         if( 1 != @{$source_l} ) {
417             die'source error';
418         }
419         my $source = @{$source_l}[0];
420         if( 0 == length $source) {
421             die 'source error';
422         }
424         # check target
425         my $target_l = $msg_hash->{'target'};
426         if( 1 != @{$target_l} ) {
427             die'target error';
428         }
429         my $target = @{$target_l}[0];
430         if( 0 == length $target) {
431             die 'target error';
432         }
434     };
435     if($@) {
436         &main::daemon_log("WARNING: do not understand the message:", 5);
437         &main::daemon_log("$@", 8);
438     }
440     return ($msg, $msg_hash);
444 sub input_from_known_server {
445     my ($input, $remote_ip) = @_ ;  
446     my ($msg, $msg_hash, $module);
448     
449     my $sql_statement= "SELECT * FROM known_server";
450     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
451     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
452         my $host_name = $hit->{hostname};
453         if( not $host_name =~ "^$remote_ip") {
454             next;
455         }
456         my $host_key = $hit->{hostkey};
457         daemon_log("ServerPackages: host_name: $host_name", 7);
458         daemon_log("ServerPackages: host_key: $host_key", 7);
460         # check if module can open msg envelope with module key
461         my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
462         if( (!$msg) || (!$msg_hash) ) {
463             daemon_log("ServerPackages: deciphering raise error", 7);
464             daemon_log("$@", 8);
465             next;
466         }
467         else {
468             $module = "ServerPackages";
469             last;
470         }
471     }
473     if( (!$msg) || (!$msg_hash) || (!$module) ) {
474         daemon_log("Incoming message is not from a known server", 3);
475     }
476   
477     return ($msg, $msg_hash, $module);
481 sub input_from_known_client {
482     my ($input, $remote_ip) = @_ ;  
483     my ($msg, $msg_hash, $module);
485     my $sql_statement= "SELECT * FROM known_clients";
486     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
487     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
488         my $host_name = $hit->{hostname};
489         if( not $host_name =~ "^$remote_ip") {
490             next;
491         }
492         my $host_key = $hit->{hostkey};
493         daemon_log("ServerPackages: host_name: $host_name", 7);
494         daemon_log("ServerPackages: host_key: $host_key", 7);
496         # check if module can open msg envelope with module key
497         my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
498         if( (!$msg) || (!$msg_hash) ) {
499             daemon_log("ServerPackages: deciphering raise error", 7);
500             daemon_log("$@", 8);
501             next;
502         }
503         else {
504             $module = "ServerPackages";
505             last;
506         }
507     }
509     if( (!$msg) || (!$msg_hash) || (!$module) ) {
510         daemon_log("Incoming message is not from a known client", 3);
511     }
513     return ($msg, $msg_hash, $module);
517 sub input_from_unknown_host {
518     no strict "refs";
519     my ($input) = @_ ;
520     my ($msg, $msg_hash, $module);
521     
522         my %act_modules = %$known_modules;
524         while( my ($mod, $info) = each(%act_modules)) {
525         # check a key exists for this module
526         my $module_key = ${$mod."_key"};
527         if( ! $module_key ) {
528             daemon_log("ERROR: no key specified in config file for $mod", 1);
529             next;
530         }
531         daemon_log("$mod: $module_key", 5);
533         # check if module can open msg envelope with module key
534         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
535         if( (!$msg) || (!$msg_hash) ) {
536             daemon_log("$mod: deciphering failed", 5);
537             next;
538         }
539         else {
540             $module = $mod;
541             last;
542         }
543     }
545     if( (!$msg) || (!$msg_hash) || (!$module)) {
546         daemon_log("Incoming message is not from a unknown host", 3);
547     }
549     return ($msg, $msg_hash, $module);
552 sub create_ciphering {
553     my ($passwd) = @_;
554     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
555     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
556     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
557     $my_cipher->set_iv($iv);
558     return $my_cipher;
562 sub encrypt_msg {
563     my ($msg, $key) = @_;
564     my $my_cipher = &create_ciphering($key);
565     {
566       use bytes;
567       $msg = "\0"x(16-length($msg)%16).$msg;
568     }
569     $msg = $my_cipher->encrypt($msg);
570     chomp($msg = &encode_base64($msg));
571     # there are no newlines allowed inside msg
572     $msg=~ s/\n//g;
573     return $msg;
577 sub decrypt_msg {
578     my ($msg, $key) = @_ ;
579     $msg = &decode_base64($msg);
580     my $my_cipher = &create_ciphering($key);
581     $msg = $my_cipher->decrypt($msg); 
582     $msg =~ s/\0*//g;
583     return $msg;
587 sub get_encrypt_key {
588     my ($target) = @_ ;
589     my $encrypt_key;
590     my $error = 0;
592     # target can be in known_server
593     if( !$encrypt_key ) {
594         my $sql_statement= "SELECT * FROM known_server";
595         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
596         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
597             my $host_name = $hit->{hostname};
598             if( $host_name ne $target ) {
599                 next;
600             }
601             my $host_key = $hit->{hostkey};
602             last;
603         }
604     }
605    
607     # target can be in known_client
608     if( !$encrypt_key ) {
609         my $sql_statement= "SELECT * FROM known_clients";
610         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
611         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
612             my $host_name = $hit->{hostname};
613             if( $host_name ne $target ) {
614                 next;
615             }
616             $encrypt_key = $hit->{hostkey};
617             last;
618         }
619     }
621     return $encrypt_key;
625 #===  FUNCTION  ================================================================
626 #         NAME:  open_socket
627 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
628 #                [PeerPort] string necessary if port not appended by PeerAddr
629 #      RETURNS:  socket IO::Socket::INET
630 #  DESCRIPTION:  open a socket to PeerAddr
631 #===============================================================================
632 sub open_socket {
633     my ($PeerAddr, $PeerPort) = @_ ;
634     if(defined($PeerPort)){
635         $PeerAddr = $PeerAddr.":".$PeerPort;
636     }
637     my $socket;
638     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
639             Porto => "tcp",
640             Type => SOCK_STREAM,
641             Timeout => 5,
642             );
643     if(not defined $socket) {
644         return;
645     }
646     &daemon_log("open_socket: $PeerAddr", 7);
647     return $socket;
651 sub send_msg_to_target {
652     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
653     my $error = 0;
655     if( !$msg_header ) {
656         $msg_header = "";
657     }
659     # encrypt xml msg
660     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
662     # opensocket
663     my $socket = &open_socket($address);
664     if(not defined $socket){
665         daemon_log("cannot send $msg_header msg to $address , host not reachable", 1);
666         $error++;
667     }
668     
669     if( $error == 0 ) {
671         # send xml msg
672         print $socket $crypted_msg."\n";
674         close $socket;
676         daemon_log("send msg to $address", 1);
677         daemon_log("message:\n$msg", 8);
679     }
681     return;
685 sub client_input {
686     no strict "refs";
687     my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
688     my ($msg, $msg_hash, $module);
689     my $error = 0;
690     my $answer_l;
691     my ($answer_header, @answer_target_l, $answer_source);
692     my $client_answer;
694     daemon_log("Incoming msg:\n$input\n", 8);
696     # msg is from a new client or gosa
697     ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
699     # msg is from a gosa-si-server or gosa-si-bus
700     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
701         ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
702     }
704     # msg is from a gosa-si-client
705     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
706         ($msg, $msg_hash, $module) = &input_from_known_client($input);
707     }
709     # an error occurred
710     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
711         $error++;
712     }
714     ######################
715     # process incoming msg
716     if( $error == 0) {
717         daemon_log("Processing module ".$module, 3);
718         $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
720         if ( 0 > @{$answer_l} ) {
721             my $answer_str = join("\n", @{$answer_l});
722             daemon_log("$module: Got answer from module: \n".$answer_str,8);
723         }
724     }
725     if( !$answer_l ) { $error++ };
727     # for each answer in answer list
728     foreach my $answer ( @{$answer_l} ) {
730         # check answer if gosa-si envelope conform
731         if( $error == 0 ) {
732             my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
733             $answer_header = @{$answer_hash->{'header'}}[0];
734             @answer_target_l = @{$answer_hash->{'target'}};
735             $answer_source = @{$answer_hash->{'source'}}[0];
736             if( !$answer_header ) {
737                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
738                 $error++;
739             }
740             if( 0 == length @answer_target_l ) {
741                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
742                 $error++;
743             }
744             if( !$answer_source ) {
745                 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
746                 $error++;
747             }
748         }
750         # deliver msg to all targets 
751         foreach my $answer_target ( @answer_target_l ) {
752             if( $answer_target eq "*" ) {
753                 # answer is for all clients
754                 my $sql_statement= "SELECT * FROM known_clients";
755                 my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
756                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
757                     my $host_name = $hit->{hostname};
758                     my $host_key = $hit->{hostkey};
759                     &send_msg_to_target($answer, $host_name, $host_key);
760                 }
761             }
762             elsif( $answer_target eq "GOSA" ) {
763                 # answer is for GOSA and has to returned to connected client
764                 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
765                 $client_answer = $gosa_answer;
766             }
767             else {
768                 # answer is for one specific host
769                 # get encrypt_key
770                 my $encrypt_key = &get_encrypt_key($answer_target);
771                 if( !$encrypt_key ) {
772                     daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
773                     next;
774                 }
775                 # send_msg
776                 &send_msg_to_target($answer, $answer_target, $encrypt_key);
777             }
778         }
779     }
781     if( $client_answer ) {
782         $heap->{client}->put($client_answer);
783     }
785     return;
789 sub trigger_db_loop {
790         my ($kernel) = $_[KERNEL];
791         $kernel->delay_set('watch_for_new_jobs',3);
795 sub watch_for_new_jobs {
796         my ($kernel,$heap) = @_[KERNEL, HEAP];
798         # check gosa job queue for jobs with executable timestamp
799     my $timestamp = &get_time();
801     my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
802         " WHERE status='waiting' AND timestamp<'$timestamp'";
804         my $res = $job_db->select_dbentry( $sql_statement );
806         while( my ($id, $hit) = each %{$res} ) {         
808                 my $jobdb_id = $hit->{id};
809                 my $macaddress = $hit->{macaddress};
810                 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
811                 my $out_msg_hash = $job_msg_hash;
812         my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
813                 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
814                 # expect macaddress is unique!!!!!!
815                 my $target = $res_hash->{1}->{hostname};
817                 if (not defined $target) {
818                         &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
819                         &daemon_log("xml message: $hit->{xmlmessage}", 5);
820             my $sql_statement = "UPDATE $job_queue_table_name ".
821                 "SET status='error', result='no host found for mac address' ".
822                 "WHERE id='$jobdb_id'";
823                         my $res = $job_db->update_dbentry($sql_statement);
824                         next;
825                 }
827                 # add target
828                 &add_content2xml_hash($out_msg_hash, "target", $target);
830                 # add new header
831                 my $out_header = $job_msg_hash->{header}[0];
832                 $out_header =~ s/job_/gosa_/;
833                 delete $out_msg_hash->{header};
834                 &add_content2xml_hash($out_msg_hash, "header", $out_header);
836                 # add sqlite_id 
837                 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
839                 my $out_msg = &create_xml_string($out_msg_hash);
841                 # encrypt msg as a GosaPackage module
842                 my $cipher = &create_ciphering($GosaPackages_key);
843                 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
845                 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
847                 if ($error == 0) {
848                         my $sql_statement = "UPDATE $job_queue_table_name ".
849                 "SET status='processing', targettag='$target' ".
850                 "WHERE id='$jobdb_id'";
851                         my $res = $job_db->update_dbentry($sql_statement);
852                 } else {
853             my $sql_statement = "UPDATE $job_queue_table_name ".
854                 "SET status='error' ".
855                 "WHERE id='$jobdb_id'";
856                         my $res = $job_db->update_dbentry($sql_statement);
857                 }
858         }
860         $kernel->delay_set('watch_for_new_jobs',3);
864 #==== MAIN = main ==============================================================
865 #  parse commandline options
866 Getopt::Long::Configure( "bundling" );
867 GetOptions("h|help" => \&usage,
868         "c|config=s" => \$cfg_file,
869         "f|foreground" => \$foreground,
870         "v|verbose+" => \$verbose,
871         "no-bus+" => \$no_bus,
872         "no-arp+" => \$no_arp,
873            );
875 #  read and set config parameters
876 &check_cmdline_param ;
877 &read_configfile;
878 &check_pid;
880 $SIG{CHLD} = 'IGNORE';
882 # forward error messages to logfile
883 if( ! $foreground ) {
884     open(STDERR, '>>', $log_file);
885     open(STDOUT, '>>', $log_file);
888 # Just fork, if we are not in foreground mode
889 if( ! $foreground ) { 
890     chdir '/'                 or die "Can't chdir to /: $!";
891     $pid = fork;
892     setsid                    or die "Can't start a new session: $!";
893     umask 0;
894 } else { 
895     $pid = $$; 
898 # Do something useful - put our PID into the pid_file
899 if( 0 != $pid ) {
900     open( LOCK_FILE, ">$pid_file" );
901     print LOCK_FILE "$pid\n";
902     close( LOCK_FILE );
903     if( !$foreground ) { 
904         exit( 0 ) 
905     };
908 daemon_log(" ", 1);
909 daemon_log("$0 started!", 1);
911 # delete old DBsqlite lock files
912 system('rm -f /tmp/gosa_si_lock*');
914 # connect to gosa-si job queue
915 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
916 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
917 $job_db->create_table('jobs', \@job_col_names);
919 # connect to known_clients_db
920 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
921 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
922 $known_clients_db->create_table('known_clients', \@clients_col_names);
924 # connect to known_server_db
925 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
926 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
927 $known_server_db->create_table('known_server', \@server_col_names);
929 # import all modules
930 &import_modules;
932 # check wether all modules are gosa-si valid passwd check
934 # create xml object used for en/decrypting
935 $xml = new XML::Simple();
937 # create session for repeatedly checking the job queue for jobs
938 POE::Session->create(
939         inline_states => {
940                 _start => \&trigger_db_loop,
941                 watch_for_new_jobs => \&watch_for_new_jobs,
942         }
943 );
945 # create socket for incoming xml messages
946 POE::Component::Server::TCP->new(
947         Port => $server_port,
948         ClientInput => \&client_input,
949 );
950 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
952 POE::Kernel->run();
953 exit;