Code

Should not map STD* if foreground.
[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 #         BUGS:  ---
14 #        NOTES:
15 #       AUTHOR:   (Andreas Rettenberger), <rettenberger@gonicus.de>
16 #      COMPANY:
17 #      VERSION:  1.0
18 #      CREATED:  12.09.2007 08:54:41 CEST
19 #     REVISION:  ---
20 #===============================================================================
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 Crypt::Rijndael;
33 use MIME::Base64;
34 use Digest::MD5  qw(md5 md5_hex md5_base64);
35 use XML::Simple;
36 use Data::Dumper;
37 use Sys::Syslog qw( :DEFAULT setlogsock);
38 use Cwd;
39 use File::Spec;
40 use GOSA::GosaSupportDaemon;
41 use GOSA::DBsqlite;
43 my $modules_path = "/usr/lib/gosa-si/modules";
44 use lib "/usr/lib/gosa-si/modules";
46 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
47 my ($bus, $msg_to_bus, $bus_cipher);
48 my ($server, $server_mac_address, $server_events);
49 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name);
50 my ($known_modules, $known_clients_file_name, $known_server_file_name);
51 my ($max_clients);
52 my ($pid_file, $procid, $pid, $log_file);
53 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
54 my ($arp_activ, $arp_fifo, $arp_fifo_path);
56 # variables declared in config file are always set to 'our'
57 our (%cfg_defaults, $log_file, $pid_file, 
58     $bus_activ, $bus_passwd, $bus_ip, $bus_port,
59     $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
60     $arp_activ, $arp_fifo_path,
61     $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
62 );
64 # additional variable which should be globaly accessable
65 our $xml;
66 our $server_address;
67 our $bus_address;
68 our $gosa_address;
69 our $no_bus;
70 our $no_arp;
71 our $verbose;
72 our $forground;
73 our $cfg_file;
75 # specifies the verbosity of the daemon_log
76 $verbose = 0 ;
78 # if foreground is not null, script will be not forked to background
79 $foreground = 0 ;
81 # specifies the timeout seconds while checking the online status of a registrating client
82 $ping_timeout = 5;
84 $no_bus = 0;
86 $no_arp = 0;
88 # name of table for storing gosa jobs
89 our $job_queue_table_name = 'jobs';
90 our $job_db;
92 # holds all other gosa-sd as well as the gosa-sd-bus
93 our $known_server_db;
95 # holds all registrated clients
96 our $known_clients_db;
98 %cfg_defaults =
99 ("general" =>
100     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
101     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
102     "child_max" => [\$child_max, 10],
103     "child_min" => [\$child_min, 3],
104     "child_timeout" => [\$child_timeout, 180],
105     "job_queue_timeout" => [\$job_queue_timeout, undef],
106     "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
107     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
108     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/known_server.db'],
109    },
110 "bus" =>
111     {"bus_activ" => [\$bus_activ, "on"],
112     "bus_passwd" => [\$bus_passwd, ""],
113     "bus_ip" => [\$bus_ip, "0.0.0.0"],
114     "bus_port" => [\$bus_port, "20080"],
115     },
116 "server" =>
117     {"server_activ" => [\$server_activ, "on"],
118     "server_ip" => [\$server_ip, "0.0.0.0"],
119     "server_port" => [\$server_port, "20081"],
120     "server_passwd" => [\$server_passwd, ""],
121     "max_clients" => [\$max_clients, 100],
122     },
123 "arp" =>
124     {"arp_activ" => [\$arp_activ, "on"],
125     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
126     },
127 "gosa" =>
128     {"gosa_activ" => [\$gosa_activ, "on"],
129     "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
130     "gosa_port" => [\$gosa_port, "20082"],
131     "gosa_passwd" => [\$gosa_passwd, "none"],
132     },
133     );
136 #===  FUNCTION  ================================================================
137 #         NAME:  usage
138 #   PARAMETERS:  nothing
139 #      RETURNS:  nothing
140 #  DESCRIPTION:  print out usage text to STDERR
141 #===============================================================================
142 sub usage {
143     print STDERR << "EOF" ;
144 usage: $0 [-hvf] [-c config]
146            -h        : this (help) message
147            -c <file> : config file
148            -f        : foreground, process will not be forked to background
149            -v        : be verbose (multiple to increase verbosity)
150            -no-bus   : starts $0 without connection to bus
151            -no-arp   : starts $0 without connection to arp module
152  
153 EOF
154     print "\n" ;
158 #===  FUNCTION  ================================================================
159 #         NAME:  read_configfile
160 #   PARAMETERS:  cfg_file - string -
161 #      RETURNS:  nothing
162 #  DESCRIPTION:  read cfg_file and set variables
163 #===============================================================================
164 sub read_configfile {
165     my $cfg;
166     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
167         if( -r $cfg_file ) {
168             $cfg = Config::IniFiles->new( -file => $cfg_file );
169         } else {
170             print STDERR "Couldn't read config file!\n";
171         }
172     } else {
173         $cfg = Config::IniFiles->new() ;
174     }
175     foreach my $section (keys %cfg_defaults) {
176         foreach my $param (keys %{$cfg_defaults{ $section }}) {
177             my $pinfo = $cfg_defaults{ $section }{ $param };
178             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
179         }
180     }
184 #===  FUNCTION  ================================================================
185 #         NAME:  logging
186 #   PARAMETERS:  level - string - default 'info'
187 #                msg - string -
188 #                facility - string - default 'LOG_DAEMON'
189 #      RETURNS:  nothing
190 #  DESCRIPTION:  function for logging
191 #===============================================================================
192 sub daemon_log {
193     # log into log_file
194     my( $msg, $level ) = @_;
195     if(not defined $msg) { return }
196     if(not defined $level) { $level = 1 }
197     if(defined $log_file){
198         open(LOG_HANDLE, ">>$log_file");
199         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
200             print STDERR "cannot open $log_file: $!";
201             return }
202             chomp($msg);
203             if($level <= $verbose){
204                 my ($seconds, $minutes, $hours, $monthday, $month,
205                         $year, $weekday, $yearday, $sommertime) = localtime(time);
206                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
207                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
208                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
209                 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
210                 $month = $monthnames[$month];
211                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
212                 $year+=1900;
213                 my $name = $0;
214                 $name =~ s/\.\///;
216                 my $log_msg = "\n$month $monthday $hours:$minutes:$seconds $name $msg";
217                 print LOG_HANDLE $log_msg;
218                 if( $foreground ) { 
219                     print STDERR $log_msg;
220                 }
221             }
222         close( LOG_HANDLE );
223     }
224 #log into syslog
225 #    my ($msg, $level, $facility) = @_;
226 #    if(not defined $msg) {return}
227 #    if(not defined $level) {$level = "info"}
228 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
229 #    openlog($0, "pid,cons,", $facility);
230 #    syslog($level, $msg);
231 #    closelog;
232 #    return;
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         #$err_config = "please specify a config file";
247         #$err_counter += 1;
248         my $cwd = getcwd;
249         my $name = "/etc/gosa-si/server.conf";
250         $cfg_file = File::Spec->catfile( $cwd, $name );
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' is imported by 
315 #                "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         eval { require $file; };
330         if ($@) {
331             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
332             daemon_log("$@", 5);
333         } else {
334             my $mod_name = $1;
335             my $info = eval($mod_name.'::get_module_info()');
336             my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
337             $known_modules->{$mod_name} = $info;
339             daemon_log("module $mod_name loaded", 1);
340         }
341     }   
343     # for debugging
344     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
345     #    print "\tmodule: $module"."\n";   
346     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
347     #}
348     close (DIR);
352 #===  FUNCTION  ================================================================
353 #         NAME:  sig_int_handler
354 #   PARAMETERS:  signal - string - signal arose from system
355 #      RETURNS:  noting
356 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
357 #===============================================================================
358 sub sig_int_handler {
359     my ($signal) = @_;
361     daemon_log("shutting down gosa-si-server", 1);
362     exit(1);
364 $SIG{INT} = \&sig_int_handler;
367 #===  FUNCTION  ================================================================
368 #         NAME:  activating_child
369 #   PARAMETERS:  msg - string - incoming message
370 #                host - string - host from which the incomming message comes
371 #      RETURNS:  nothing
372 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
373 #===============================================================================
374 sub activating_child {
375     my ($msg, $host, $client) = @_;
376     my $child = &get_processing_child();
377     my $pipe_wr = $$child{'pipe_wr'};
378     my $pipe_rd = $$child{'pipe_rd'};
379     $$child{client_ref} = $client;
380     
381     daemon_log("activating: childpid:$$child{'pid'}", 5);
383     print $pipe_wr $msg.".".$host."\n";
385     return;
389 #===  FUNCTION  ================================================================
390 #         NAME:  get_processing_child
391 #   PARAMETERS:  nothing
392 #      RETURNS:  child - hash - holding the process id and the references to the pipe
393 #                               handles pipe_wr and pipe_rd
394 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
395 #===============================================================================
396 sub get_processing_child {
397     my $child;
399     while(my ($key, $val) = each(%free_child)) {
400         my $exitus_pid = waitpid($key, WNOHANG);
401         if($exitus_pid != 0) {
402             delete $free_child{$key};
403         }
404         daemon_log("free child:$key", 5);
405     }
406     # check @free_child and @busy_child
407     my $free_len = scalar(keys(%free_child));
408     my $busy_len = scalar(keys(%busy_child));
409     daemon_log("free children $free_len, busy children $busy_len", 5);
411     # if there is a free child, let the child work
412     if($free_len > 0){
413         my @keys = keys(%free_child);
414         $child = $free_child{$keys[0]};
415         if(defined $child) {
416             $busy_child{$$child{'pid'}} = $child ;
417             delete $free_child{$$child{'pid'}};
418         }
419         return $child;
420     }
422     # no free child, try to fork another one
423     if($free_len + $busy_len < $child_max) {
425         daemon_log("not enough children, create a new one", 5);
427         # New pipes for communication
428         my( $PARENT_wr, $PARENT_rd );
429         my( $CHILD_wr, $CHILD_rd );
430         pipe( $CHILD_rd,  $PARENT_wr );
431         pipe( $PARENT_rd, $CHILD_wr  );
432         $PARENT_wr->autoflush(1);
433         $CHILD_wr->autoflush(1);
435         ############
436         # fork child
437         ############
438         my $child_pid = fork();
439         
440         #CHILD
441         if($child_pid == 0) {
442             # Close unused pipes
443             close( $CHILD_rd );
444             close( $CHILD_wr );
445             while( 1 ) {
446                 my $rbits = "";
447                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
448                 my $nf = select($rbits, undef, undef, $child_timeout);
449                 if($nf < 0 ) {
450                     die "select(): $!\n";
451                 } elsif (! $nf) {
452                     # if already child_min childs are alive, then leave loop
453                     $free_len = scalar(keys(%free_child));
454                     $busy_len = scalar(keys(%busy_child));
455                     if($free_len + $busy_len >= $child_min) {
456                         last;
457                     } else {
458                         redo;
459                     }
460                 }
462                 # a job for a child arise
463                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
464                     # read everything from pipe
465                     my $msg = "";
466                     $PARENT_rd->blocking(0);
467                     while(1) {
468                         my $read = <$PARENT_rd>;
469                         if(not defined $read) { last}
470                         $msg .= $read;
471                     }
473                     ######################################
474                     # forward msg to all imported modules 
475                     no strict "refs";
476                     my $answer;
477                     my %act_modules = %$known_modules;
478                     while( my ($module, $info) = each(%act_modules)) {
479                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
480                             if (defined $tmp) {
481                                 $answer = $tmp;
482                             }
483                     }        
485                     #&print_known_daemons();
486                     #&print_known_clients();
488                     daemon_log("processing of msg finished", 5);
489  
490                    if (defined $answer) {
491                         print $PARENT_wr $answer."\n";
492                         my $len_answer = length $answer;
493 #                        daemon_log("with answer: length of answer: $len_answer", 7);
494 #                        daemon_log("\n$answer", 7);
495                     } else {
496                         print $PARENT_wr "done"."\n";
497                         daemon_log(" ", 7);
498                     }
499                     redo;
500                 }
501             }
502             # childs leaving the loop are allowed to die
503             exit(0);
506         #PARENT
507         } else {
508             # Close unused pipes
509             close( $PARENT_rd );
510             close( $PARENT_wr );
512             # add child to child alive hash
513             my %child_hash = (
514                     'pid' => $child_pid,
515                     'pipe_wr' => $CHILD_wr,
516                     'pipe_rd' => $CHILD_rd,
517                     'client_ref' => "",
518                     );
520             $child = \%child_hash;
521             $busy_child{$$child{'pid'}} = $child;
522             return $child;
523         }
524     }
528 #===  FUNCTION  ================================================================
529 #         NAME:  read_from_socket
530 #   PARAMETERS:  socket fh - 
531 #      RETURNS:  result string - readed characters from socket
532 #  DESCRIPTION:  reads data from socket in 16 byte steps
533 #===============================================================================
534 sub read_from_socket {
535     my ($socket) = @_;
536     my $result = "";
538     $socket->blocking(1);
539     $result = <$socket>;
541     $socket->blocking(0);
542     while ( my $char = <$socket> ) {
543         if (not defined $char) { last }
544         $result .= $char;
545     }
547     return $result;
551 #===  FUNCTION  ================================================================
552 #         NAME:  print_known_daemons
553 #   PARAMETERS:  nothing
554 #      RETURNS:  nothing
555 #  DESCRIPTION:  nomen est omen
556 #===============================================================================
557 #sub print_known_daemons {
558 #    my ($tmp) = @_ ;
559 #    print "####################################\n";
560 #    print "# status of known_daemons\n";
561 #    $shmda->shlock(LOCK_EX);
562 #    my @hosts = keys %$known_daemons;
563 #    foreach my $host (@hosts) {
564 #        my $status = $known_daemons->{$host}->{status} ;
565 #        my $passwd = $known_daemons->{$host}->{passwd};
566 #        my $timestamp = $known_daemons->{$host}->{timestamp};
567 #        print "$host\n";
568 #        print "\tstatus:    $status\n";
569 #        print "\tpasswd:    $passwd\n";
570 #        print "\ttimestamp: $timestamp\n";
571 #    }
572 #    $shmda->shunlock(LOCK_EX);
573 #    print "####################################\n";
574 #    return;
575 #}
578 #===  FUNCTION  ================================================================
579 #         NAME:  create_known_daemon
580 #   PARAMETERS:  hostname - string - key for the hash known_daemons
581 #      RETURNS:  nothing
582 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
583 #===============================================================================
584 #sub create_known_daemon {
585 #    my ($hostname) = @_;
586 #    $shmda->shlock(LOCK_EX);
587 #    $known_daemons->{$hostname} = {};
588 #    $known_daemons->{$hostname}->{status} = "none";
589 #    $known_daemons->{$hostname}->{passwd} = "none";
590 #    $known_daemons->{$hostname}->{timestamp} = "none";
591 #    $shmda->shunlock(LOCK_EX); 
592 #    return;  
593 #}
596 #===  FUNCTION  ================================================================
597 #         NAME:  add_content2known_daemons
598 #   PARAMETERS:  hostname - string - ip address and port of host (required)
599 #                status - string - (optional)
600 #                passwd - string - (optional)
601 #                mac_address - string - mac address of host (optional)
602 #      RETURNS:  nothing
603 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
604 #===============================================================================
605 #sub add_content2known_daemons {
606 #    my $arg = {
607 #        hostname => undef, status => undef, passwd => undef,
608 #        mac_address => undef, events => undef, 
609 #        @_ };
610 #    my $hostname = $arg->{hostname};
611 #    my $status = $arg->{status};
612 #    my $passwd = $arg->{passwd};
613 #    my $mac_address = $arg->{mac_address};
614 #    my $events = $arg->{events};
616 #    if (not defined $hostname) {
617 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
618 #        return;
619 #    }
621 #    my ($seconds, $minutes, $hours, $monthday, $month,
622 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
623 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
624 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
625 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
626 #    $month+=1;
627 #    $month = $month < 10 ? $month = "0".$month : $month;
628 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
629 #    $year+=1900;
630 #    my $t = "$year$month$monthday$hours$minutes$seconds";
631 #    
632 #    $shmda->shlock(LOCK_EX);
633 #    if (defined $status) {
634 #        $known_daemons->{$hostname}->{status} = $status;
635 #    }
636 #    if (defined $passwd) {
637 #        $known_daemons->{$hostname}->{passwd} = $passwd;
638 #    }
639 #    if (defined $mac_address) {
640 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
641 #    }
642 #    if (defined $events) {
643 #        $known_daemons->{$hostname}->{events} = $events;
644 #    }
645 #    $known_daemons->{$hostname}->{timestamp} = $t;
646 #    $shmda->shlock(LOCK_EX);
647 #    return;
648 #}
651 #===  FUNCTION  ================================================================
652 #         NAME:  update_known_daemons
653 #   PARAMETERS:  hostname - string - ip address and port of host (required)
654 #                status - string - (optional)
655 #                passwd - string - (optional)
656 #                client - string - ip address and port of client (optional)
657 #      RETURNS:  nothing
658 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
659 #===============================================================================
660 #sub update_known_daemons {
661 #    my $arg = {
662 #        hostname => undef, status => undef, passwd => undef,
663 #        @_ };
664 #    my $hostname = $arg->{hostname};
665 #    my $status = $arg->{status};
666 #    my $passwd = $arg->{passwd};
668 #    if (not defined $hostname) {
669 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
670 #        return;
671 #    }
673 #    my ($seconds, $minutes, $hours, $monthday, $month,
674 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
675 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
676 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
677 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
678 #    $month+=1;
679 #    $month = $month < 10 ? $month = "0".$month : $month;
680 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
681 #    $year+=1900;
682 #    my $t = "$year$month$monthday$hours$minutes$seconds";
684 #    $shmda->shlock(LOCK_EX);
685 #    if (defined $status) {
686 #        $known_daemons->{$hostname}->{status} = $status;
687 #    }
688 #    if (defined $passwd) {
689 #        $known_daemons->{$hostname}->{passwd} = $passwd;
690 #    }
691 #    $known_daemons->{$hostname}->{timestamp} = $t;
692 #    $shmda->shunlock(LOCK_EX);
693 #    return;
694 #}
697 #===  FUNCTION  ================================================================
698 #         NAME:  print_known_clients 
699 #   PARAMETERS:  nothing
700 #      RETURNS:  nothing
701 #  DESCRIPTION:  nomen est omen
702 #===============================================================================
703 #sub print_known_clients {
705 #    print "####################################\n";
706 #    print "# status of known_clients\n";
707 #    $shmcl->shlock(LOCK_EX);
708 #    my @hosts = keys %$known_clients;
709 #    if (@hosts) {
710 #        foreach my $host (@hosts) {
711 #            my $status = $known_clients->{$host}->{status} ;
712 #            my $passwd = $known_clients->{$host}->{passwd};
713 #            my $timestamp = $known_clients->{$host}->{timestamp};
714 #            my $mac_address = $known_clients->{$host}->{mac_address};
715 #            my $events = $known_clients->{$host}->{events};
716 #            print "$host\n";
717 #            print "\tstatus:      $status\n";
718 #            print "\tpasswd:      $passwd\n";
719 #            print "\ttimestamp:   $timestamp\n";
720 #            print "\tmac_address: $mac_address\n";
721 #            print "\tevents:      $events\n";
722 #        }
723 #    }
724 #    $shmcl->shunlock(LOCK_EX);
725 #    print "####################################\n";
726 #    return;
727 #}
730 #===  FUNCTION  ================================================================
731 #         NAME:  create_known_client
732 #   PARAMETERS:  hostname - string - key for the hash known_clients
733 #      RETURNS:  nothing
734 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
735 #===============================================================================
736 sub create_known_client {
737     my ($hostname) = @_;
739     my $entry = { table=>'known_clients',
740         hostname=>$hostname,
741         status=>'none',
742         hostkey=>'none',
743         timestamp=>'none',
744         macaddress=>'none',
745         events=>'none',
746     };
747     my $res = $known_clients_db->add_dbentry($entry);
748     if ($res > 0) {
749         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
750     }
752     return;  
756 #===  FUNCTION  ================================================================
757 #         NAME:  add_content2known_clients
758 #   PARAMETERS:  hostname - string - ip address and port of host (required)
759 #                status - string - (optional)
760 #                passwd - string - (optional)
761 #                mac_address - string - (optional)
762 #                events - string - event of client, executable skripts 
763 #                under /etc/gosac/events
764 #      RETURNS:  nothing
765 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
766 #===============================================================================
767 #sub update_known_clients {
768 #    my $arg = {
769 #        hostname => undef, status => undef, hostkey => undef,
770 #        macaddress => undef, events => undef, timestamp=>undef,
771 #        @_ };
772 #    my $hostname = $arg->{hostname};
773 #    my $status = $arg->{status};
774 #    my $hostkey = $arg->{hostkey};
775 #    my $macaddress = $arg->{macaddress};
776 #    my $events = $arg->{events};
777 #    my $timestamp = $arg->{timestamp}; 
779 #    if (not defined $hostname) {
780 #        daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
781 #        return;
782 #    }
784 #    my $change_entry = { table=>'known_clients',
785 #                        where=>'hostname', 
786 #                        timestamp=>&get_time, 
787 #                        };
788 #   
789 #   
790 #    if (defined $status) {
791 #        $change_entry->{status} = $status;
792 #    }
793 #    if (defined $hostkey) {
794 #        $change_entry->{hostkey} = $hostkey;
795 #    }
796 #    if (defined $macaddress) {
797 #        $change_entry->{macaddress} = $macaddress;
798 #    }
799 #    if (defined $events) {
800 #        $change_entry->{events} = $events;
801 #    }
802 #    
803 #    $known_clients->change_dbentry($change_entry);
804 #    return;
805 #}
806  
808 #===  FUNCTION  ================================================================
809 #         NAME:  
810 #   PARAMETERS:  
811 #      RETURNS:  
812 #  DESCRIPTION:  
813 #===============================================================================    
814 #sub clean_up_known_clients {
815 #    my ($address) = @_ ;
816 #    
817 #    if (not exists $known_clients->{$address}) {
818 #        daemon_log("cannot prune known_clients from $address, client not known", 5);
819 #        return;
820 #    }
822 #    delete $known_clients->{$address};
824 #    # send bus a msg that address was deleted from known_clients
825 #    my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
826 #    &send_msg_hash2bus($out_hash);
828 #    daemon_log("client $address deleted from known_clients because of multiple down time", 3);
829 #    return;
830 #}
833 #===  FUNCTION  ================================================================
834 #         NAME:  update_known_clients
835 #   PARAMETERS:  hostname - string - ip address and port of host (required)
836 #                status - string - (optional)
837 #                passwd - string - (optional)
838 #                client - string - ip address and port of client (optional)
839 #      RETURNS:  nothing
840 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
841 #===============================================================================
842 #sub update_known_clients {
843 #    my $arg = {
844 #        hostname => undef, status => undef, passwd => undef,
845 #        mac_address => undef, events => undef,
846 #        @_ };
847 #    my $hostname = $arg->{hostname};
848 #    my $status = $arg->{status};
849 #    my $passwd = $arg->{passwd};
850 #    my $mac_address = $arg->{mac_address};
851 #    my $events = $arg->{events};
853 #    if (not defined $hostname) {
854 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
855 #        return;
856 #    }
858 #    my ($seconds, $minutes, $hours, $monthday, $month,
859 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
860 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
861 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
862 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
863 #    $month+=1;
864 #    $month = $month < 10 ? $month = "0".$month : $month;
865 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
866 #    $year+=1900;
867 #    my $t = "$year$month$monthday$hours$minutes$seconds";
869 #    if (defined $status) {
870 #        $known_clients->{$hostname}->{status} = $status;
871 #    }
872 #    if (defined $passwd) {
873 #        $known_clients->{$hostname}->{passwd} = $passwd;
874 #    }
875 #    if (defined $mac_address) {
876 #        $known_clients->{$hostname}->{mac_address} = $mac_address; 
877 #    }
878 #    if (defined $events) {
879 #        $known_clients->{$hostname}->{events} = $events;
880 #    }
881 #    $known_clients_db->{$hostname}->{timestamp} = $t;
882 #    return;
883 #}
891 #==== MAIN = main ==============================================================
893 #  parse commandline options
894 Getopt::Long::Configure( "bundling" );
895 GetOptions("h|help" => \&usage,
896         "c|config=s" => \$cfg_file,
897         "f|foreground" => \$foreground,
898         "v|verbose+" => \$verbose,
899         "no-bus+" => \$no_bus,
900         "no-arp+" => \$no_arp,
901            );
903 #  read and set config parameters
904 &check_cmdline_param ;
905 &read_configfile;
906 &check_pid;
908 $SIG{CHLD} = 'IGNORE';
910 # forward error messages to logfile
911 if( ! $foreground ) {
912     open(STDERR, '>>', $log_file);
913     open(STDOUT, '>>', $log_file);
916 # Just fork, if we are not in foreground mode
917 if( ! $foreground ) { 
918     chdir '/'                 or die "Can't chdir to /: $!";
919     $pid = fork;
920     setsid                    or die "Can't start a new session: $!";
921     umask 0;
922 } else { 
923     $pid = $$; 
926 # Do something useful - put our PID into the pid_file
927 if( 0 != $pid ) {
928     open( LOCK_FILE, ">$pid_file" );
929     print LOCK_FILE "$pid\n";
930     close( LOCK_FILE );
931     if( !$foreground ) { 
932         exit( 0 ) 
933     };
936 daemon_log(" ", 1);
937 daemon_log("$0 started!", 1);
940 # connect to gosa-si job queue
941 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
942 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
943 $job_db->create_table('jobs', \@job_col_names);
945 # connect to known_clients_db
946 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
947 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
948 $known_clients_db->create_table('known_clients', \@clients_col_names);
950 # connect to known_server_db
951 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
952 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
953 $known_server_db->create_table('known_server', \@server_col_names);
955 # import all modules
956 &import_modules;
958 # check wether all modules are gosa-si valid passwd check
960 # create reading and writing vectors
961 my $rbits = my $wbits = my $ebits = "";
963 # add all module inputs to listening vector
964 while( my ($mod_name, $info) = each %$known_modules ) {
965     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
966     vec($rbits, fileno $input, 1) = 1;   
971 ## start arp fifo
972 #if ($no_arp > 0) {
973 #    $arp_activ = "off";
974 #}
975 #my $my_fifo;
976 #if($arp_activ eq "on") {
977 #    daemon_log(" ", 1);
978 #    $my_fifo = &open_fifo($arp_fifo_path);
979 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
980 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
981 #    
982 #    vec($rbits, fileno $arp_fifo, 1) = 1;
983 #}
986 ##################################
987 #everything ready, okay, lets start
988 ##################################
989 while(1) {
991     # add all handles from the childs
992     while ( my ($pid, $child_hash) = each %busy_child ) {
993         
994         # check whether process still exists
995         my $exitus_pid = waitpid($pid, WNOHANG);
996         if($exitus_pid != 0) {
997             delete $busy_child{$pid};
998             next;
999         }
1000      
1001         # add child fhd to the listener    
1002         my $fhd = $$child_hash{'pipe_rd'};
1003         vec($rbits, fileno $fhd, 1) = 1;
1004     }
1006     my ($rout, $wout);
1007     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1009     # error handling
1010     if($nf < 0 ) {
1011     }
1014 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1015 #        my $in_msg = <$arp_fifo>;
1016 #        chomp($in_msg);
1017 #        print "arp_activ: msg: $in_msg\n";
1018 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1019 #        print "arp_activ: arp_passwd: $act_passwd\n";
1021 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1023 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1025 #        if ($target eq $server_address) { 
1026 #             print "arp_activ: forward to server\n";
1027 #            my $arp_cipher = &create_ciphering($act_passwd);
1028 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1029 #            &activating_child($crypted_msg, $server_ip);
1030 #        } else {
1031 #            print "arp_activ: send to bus\n";
1032 #            &send_msg_hash2address($in_msg_hash, $bus_address);
1033 #        }
1034 #        print "\n";
1035 #    }
1038     # check input fhd of all modules 
1039     while ( my ($mod_name, $info) = each %$known_modules) {
1040         my $input_fhd = @{$info}[2];    
1041         my $input_activ = @{$info}[3];
1042         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1043             daemon_log(" ", 1);
1044             my $client = $input_fhd->accept();
1045             my $other_end = getpeername($client);
1046             if(not defined $other_end) {
1047                 daemon_log("client cannot be identified: $!");
1048             } else {
1049                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1050                 my $actual_ip = inet_ntoa($iaddr);
1051                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1052                 my $in_msg = &read_from_socket($client);
1053                 if(defined $in_msg){
1054                     chomp($in_msg);
1055                     &activating_child($in_msg, $actual_ip, $client);
1056                 } else {
1057                     daemon_log("cannot read from $actual_ip", 5);
1058                 }
1059             }
1060         }
1061     }
1063     # check all processing childs whether they are finished ('done') or 
1064     while ( my ($pid, $child_hash) = each %busy_child ) {
1065         my $fhd = $$child_hash{'pipe_rd'};
1067         if (vec($rout, fileno $fhd, 1) ) {
1068             daemon_log("process child $pid is ready to read", 5);
1070             $fhd->blocking(1);
1071             my $in_msg = <$fhd>;
1072             $fhd->blocking(0);
1073             my $part_in_msg;
1074             while ($part_in_msg = <$fhd>) {
1075                 if (not defined $part_in_msg) {
1076                     last;
1077                 }
1078                 $in_msg .= $part_in_msg;
1079             }
1080             chomp($in_msg);
1082 #            daemon_log("process child read: $in_msg", 7);
1083 #            daemon_log("\n$in_msg", 7);
1084             if (not defined $in_msg) { 
1085                 next; 
1086             } elsif ($in_msg =~ "done") {
1087                 delete $busy_child{$pid};
1088                 $free_child{$pid} = $child_hash;
1089  
1090             } else {
1091                 # send computed answer back to connected client
1092                 my $act_client = $busy_child{$pid}{client_ref};
1093                 print $act_client $in_msg."\n";
1095                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1096                 delete $busy_child{$pid};
1097                 $free_child{$pid} = $child_hash;
1099                 # give the client a chance to read 
1100                 sleep(2);
1101                 close ($act_client);   
1102             }
1103         }
1104     }
1106     # check gosa job queue for jobs with executable timestamp
1107     my ($seconds, $minutes, $hours, $monthday, $month,
1108     $year, $weekday, $yearday, $sommertime) = localtime(time);
1109     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1110     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1111     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1112     $month+=1;
1113     $month = $month < 10 ? $month = "0".$month : $month;
1114     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1115     $year+=1900;
1116     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1117     
1118     
1119     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1121     while( my ($id, $hit) = each %{$res} ) {         
1123         my $jobdb_id = $hit->{ROWID};
1124         my $macaddress = $hit->{macaddress};
1125         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1126         my $out_msg_hash = $job_msg_hash;
1127         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1128         # expect macaddress is unique!!!!!!
1129         my $target = $res_hash->{1}->{hostname};
1130         
1131         if (not defined $target) {
1132             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1133             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1134             my $update_hash = { table=>$job_queue_table_name,
1135                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1136                 where=> [ { ROWID=>[$jobdb_id] } ],
1137             };
1138             my $res = $job_db->update_dbentry($update_hash);
1140             next;
1141         }
1143         # add target
1144         &add_content2xml_hash($out_msg_hash, "target", $target);
1146         # add new header
1147         my $out_header = $job_msg_hash->{header}[0];
1148         $out_header =~ s/job_/gosa_/;
1149         delete $out_msg_hash->{header};
1150         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1151         
1152         # add sqlite_id 
1153         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1154     
1155         my $out_msg = &create_xml_string($out_msg_hash);
1157         # encrypt msg as a GosaPackage module
1158         my $cipher = &create_ciphering($gosa_passwd);
1159         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1161         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1163 #######################
1164 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1166         if ($error == 0) {
1167             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1168             my $res = $job_db->exec_statement($sql);
1169         } else {
1170             my $update_hash = { table=>$job_queue_table_name, 
1171                                 update=> [ { status=>'error' } ],
1172                                 where=> [ { ROWID=>$jobdb_id } ],
1173                               };
1174             my $res = $job_db->update_dbentry($update_hash);
1175         }
1177     }