Code

small changes
[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 #                libipc-shareable-perl libdata-dumper-simple-perl 
13 #                libdbd-sqlite3-perl libnet-ldap-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 #===============================================================================
24 use strict;
25 use warnings;
26 use Getopt::Long;
27 use Config::IniFiles;
28 use POSIX;
29 use Time::HiRes qw( gettimeofday );
31 use Fcntl;
32 use IO::Socket::INET;
33 use Crypt::Rijndael;
34 use MIME::Base64;
35 use Digest::MD5  qw(md5 md5_hex md5_base64);
36 use XML::Simple;
37 use Data::Dumper;
38 use Sys::Syslog qw( :DEFAULT setlogsock);
39 use Cwd;
40 use File::Spec;
41 use IPC::Shareable qw( :lock);
42 IPC::Shareable->clean_up_all;
43 use GOSA::GosaSupportDaemon;
44 use GOSA::DBsqlite;
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);
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);
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, $server_passwd, $max_clients,
63     $arp_activ, $arp_fifo_path,
64     $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
65 );
67 # additional variable which should be globaly accessable
68 our $xml;
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     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
111     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/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     "server_passwd" => [\$server_passwd, ""],
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     "gosa_passwd" => [\$gosa_passwd, "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", "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                 print LOG_HANDLE "\n$month $monthday $hours:$minutes:$seconds $name $msg";
220             }
221         close( LOG_HANDLE );
222     }
223 #log into syslog
224 #    my ($msg, $level, $facility) = @_;
225 #    if(not defined $msg) {return}
226 #    if(not defined $level) {$level = "info"}
227 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
228 #    openlog($0, "pid,cons,", $facility);
229 #    syslog($level, $msg);
230 #    closelog;
231 #    return;
235 #===  FUNCTION  ================================================================
236 #         NAME:  check_cmdline_param
237 #   PARAMETERS:  nothing
238 #      RETURNS:  nothing
239 #  DESCRIPTION:  validates commandline parameter
240 #===============================================================================
241 sub check_cmdline_param () {
242     my $err_config;
243     my $err_counter = 0;
244     if( not defined( $cfg_file)) {
245         #$err_config = "please specify a config file";
246         #$err_counter += 1;
247         my $cwd = getcwd;
248         my $name = "/etc/gosa-si/server.conf";
249         $cfg_file = File::Spec->catfile( $cwd, $name );
250     }
251     if( $err_counter > 0 ) {
252         &usage( "", 1 );
253         if( defined( $err_config)) { print STDERR "$err_config\n"}
254         print STDERR "\n";
255         exit( -1 );
256     }
260 #===  FUNCTION  ================================================================
261 #         NAME:  check_pid
262 #   PARAMETERS:  nothing
263 #      RETURNS:  nothing
264 #  DESCRIPTION:  handels pid processing
265 #===============================================================================
266 sub check_pid {
267     $pid = -1;
268     # Check, if we are already running
269     if( open(LOCK_FILE, "<$pid_file") ) {
270         $pid = <LOCK_FILE>;
271         if( defined $pid ) {
272             chomp( $pid );
273             if( -f "/proc/$pid/stat" ) {
274                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
275                 if( $0 eq $stat ) {
276                     close( LOCK_FILE );
277                     exit -1;
278                 }
279             }
280         }
281         close( LOCK_FILE );
282         unlink( $pid_file );
283     }
285     # create a syslog msg if it is not to possible to open PID file
286     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
287         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
288         if (open(LOCK_FILE, '<', $pid_file)
289                 && ($pid = <LOCK_FILE>))
290         {
291             chomp($pid);
292             $msg .= "(PID $pid)\n";
293         } else {
294             $msg .= "(unable to read PID)\n";
295         }
296         if( ! ($foreground) ) {
297             openlog( $0, "cons,pid", "daemon" );
298             syslog( "warning", $msg );
299             closelog();
300         }
301         else {
302             print( STDERR " $msg " );
303         }
304         exit( -1 );
305     }
308 #===  FUNCTION  ================================================================
309 #         NAME:  import_modules
310 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
311 #                are stored
312 #      RETURNS:  nothing
313 #  DESCRIPTION:  each file in module_path which ends with '.pm' is imported by 
314 #                "require 'file';"
315 #===============================================================================
316 sub import_modules {
317     daemon_log(" ", 1);
319     if (not -e $modules_path) {
320         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
321     }
323     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
324     while (defined (my $file = readdir (DIR))) {
325         if (not $file =~ /(\S*?).pm$/) {
326             next;
327         }
328         eval { require $file; };
329         if ($@) {
330             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
331             daemon_log("$@", 5);
332         } else {
333             my $mod_name = $1;
334             my $info = eval($mod_name.'::get_module_info()');
335             my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
336             $known_modules->{$mod_name} = $info;
338             daemon_log("module $mod_name loaded", 1);
339         }
340     }   
342     # for debugging
343     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
344     #    print "\tmodule: $module"."\n";   
345     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
346     #}
347     close (DIR);
351 #===  FUNCTION  ================================================================
352 #         NAME:  sig_int_handler
353 #   PARAMETERS:  signal - string - signal arose from system
354 #      RETURNS:  noting
355 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
356 #===============================================================================
357 sub sig_int_handler {
358     my ($signal) = @_;
360     daemon_log("shutting down gosa-si-server", 1);
361     exit(1);
363 $SIG{INT} = \&sig_int_handler;
366 #===  FUNCTION  ================================================================
367 #         NAME:  activating_child
368 #   PARAMETERS:  msg - string - incoming message
369 #                host - string - host from which the incomming message comes
370 #      RETURNS:  nothing
371 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
372 #===============================================================================
373 sub activating_child {
374     my ($msg, $host, $client) = @_;
375     my $child = &get_processing_child();
376     my $pipe_wr = $$child{'pipe_wr'};
377     my $pipe_rd = $$child{'pipe_rd'};
378     $$child{client_ref} = $client;
379     
380     daemon_log("activating: childpid:$$child{'pid'}", 5);
382     print $pipe_wr $msg.".".$host."\n";
384     return;
388 #===  FUNCTION  ================================================================
389 #         NAME:  get_processing_child
390 #   PARAMETERS:  nothing
391 #      RETURNS:  child - hash - holding the process id and the references to the pipe
392 #                               handles pipe_wr and pipe_rd
393 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
394 #===============================================================================
395 sub get_processing_child {
396     my $child;
398     while(my ($key, $val) = each(%free_child)) {
399         my $exitus_pid = waitpid($key, WNOHANG);
400         if($exitus_pid != 0) {
401             delete $free_child{$key};
402         }
403         daemon_log("free child:$key", 5);
404     }
405     # check @free_child and @busy_child
406     my $free_len = scalar(keys(%free_child));
407     my $busy_len = scalar(keys(%busy_child));
408     daemon_log("free children $free_len, busy children $busy_len", 5);
410     # if there is a free child, let the child work
411     if($free_len > 0){
412         my @keys = keys(%free_child);
413         $child = $free_child{$keys[0]};
414         if(defined $child) {
415             $busy_child{$$child{'pid'}} = $child ;
416             delete $free_child{$$child{'pid'}};
417         }
418         return $child;
419     }
421     # no free child, try to fork another one
422     if($free_len + $busy_len < $child_max) {
424         daemon_log("not enough children, create a new one", 5);
426         # New pipes for communication
427         my( $PARENT_wr, $PARENT_rd );
428         my( $CHILD_wr, $CHILD_rd );
429         pipe( $CHILD_rd,  $PARENT_wr );
430         pipe( $PARENT_rd, $CHILD_wr  );
431         $PARENT_wr->autoflush(1);
432         $CHILD_wr->autoflush(1);
434         ############
435         # fork child
436         ############
437         my $child_pid = fork();
438         
439         #CHILD
440         if($child_pid == 0) {
441             # Close unused pipes
442             close( $CHILD_rd );
443             close( $CHILD_wr );
444             while( 1 ) {
445                 my $rbits = "";
446                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
447                 my $nf = select($rbits, undef, undef, $child_timeout);
448                 if($nf < 0 ) {
449                     die "select(): $!\n";
450                 } elsif (! $nf) {
451                     # if already child_min childs are alive, then leave loop
452                     $free_len = scalar(keys(%free_child));
453                     $busy_len = scalar(keys(%busy_child));
454                     if($free_len + $busy_len >= $child_min) {
455                         last;
456                     } else {
457                         redo;
458                     }
459                 }
461                 # a job for a child arise
462                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
463                     # read everything from pipe
464                     my $msg = "";
465                     $PARENT_rd->blocking(0);
466                     while(1) {
467                         my $read = <$PARENT_rd>;
468                         if(not defined $read) { last}
469                         $msg .= $read;
470                     }
472                     ######################################
473                     # forward msg to all imported modules 
474                     no strict "refs";
475                     my $answer;
476                     my %act_modules = %$known_modules;
477                     while( my ($module, $info) = each(%act_modules)) {
478                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
479                             if (defined $tmp) {
480                                 $answer = $tmp;
481                             }
482                     }        
484                     #&print_known_daemons();
485                     #&print_known_clients();
487                     daemon_log("processing of msg finished", 5);
488  
489                    if (defined $answer) {
490                         print $PARENT_wr $answer."\n";
491                         my $len_answer = length $answer;
492                         daemon_log("with answer: length of answer: $len_answer", 7);
493                         daemon_log("\n$answer", 7);
494                     } else {
495                         print $PARENT_wr "done"."\n";
496                         daemon_log(" ", 7);
497                     }
498                     redo;
499                 }
500             }
501             # childs leaving the loop are allowed to die
502             exit(0);
505         #PARENT
506         } else {
507             # Close unused pipes
508             close( $PARENT_rd );
509             close( $PARENT_wr );
511             # add child to child alive hash
512             my %child_hash = (
513                     'pid' => $child_pid,
514                     'pipe_wr' => $CHILD_wr,
515                     'pipe_rd' => $CHILD_rd,
516                     'client_ref' => "",
517                     );
519             $child = \%child_hash;
520             $busy_child{$$child{'pid'}} = $child;
521             return $child;
522         }
523     }
527 #===  FUNCTION  ================================================================
528 #         NAME:  read_from_socket
529 #   PARAMETERS:  socket fh - 
530 #      RETURNS:  result string - readed characters from socket
531 #  DESCRIPTION:  reads data from socket in 16 byte steps
532 #===============================================================================
533 sub read_from_socket {
534     my ($socket) = @_;
535     my $result = "";
537     $socket->blocking(1);
538     $result = <$socket>;
540     $socket->blocking(0);
541     while ( my $char = <$socket> ) {
542         if (not defined $char) { last }
543         $result .= $char;
544     }
546     return $result;
550 #===  FUNCTION  ================================================================
551 #         NAME:  print_known_daemons
552 #   PARAMETERS:  nothing
553 #      RETURNS:  nothing
554 #  DESCRIPTION:  nomen est omen
555 #===============================================================================
556 #sub print_known_daemons {
557 #    my ($tmp) = @_ ;
558 #    print "####################################\n";
559 #    print "# status of known_daemons\n";
560 #    $shmda->shlock(LOCK_EX);
561 #    my @hosts = keys %$known_daemons;
562 #    foreach my $host (@hosts) {
563 #        my $status = $known_daemons->{$host}->{status} ;
564 #        my $passwd = $known_daemons->{$host}->{passwd};
565 #        my $timestamp = $known_daemons->{$host}->{timestamp};
566 #        print "$host\n";
567 #        print "\tstatus:    $status\n";
568 #        print "\tpasswd:    $passwd\n";
569 #        print "\ttimestamp: $timestamp\n";
570 #    }
571 #    $shmda->shunlock(LOCK_EX);
572 #    print "####################################\n";
573 #    return;
574 #}
577 #===  FUNCTION  ================================================================
578 #         NAME:  create_known_daemon
579 #   PARAMETERS:  hostname - string - key for the hash known_daemons
580 #      RETURNS:  nothing
581 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
582 #===============================================================================
583 #sub create_known_daemon {
584 #    my ($hostname) = @_;
585 #    $shmda->shlock(LOCK_EX);
586 #    $known_daemons->{$hostname} = {};
587 #    $known_daemons->{$hostname}->{status} = "none";
588 #    $known_daemons->{$hostname}->{passwd} = "none";
589 #    $known_daemons->{$hostname}->{timestamp} = "none";
590 #    $shmda->shunlock(LOCK_EX); 
591 #    return;  
592 #}
595 #===  FUNCTION  ================================================================
596 #         NAME:  add_content2known_daemons
597 #   PARAMETERS:  hostname - string - ip address and port of host (required)
598 #                status - string - (optional)
599 #                passwd - string - (optional)
600 #                mac_address - string - mac address of host (optional)
601 #      RETURNS:  nothing
602 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
603 #===============================================================================
604 #sub add_content2known_daemons {
605 #    my $arg = {
606 #        hostname => undef, status => undef, passwd => undef,
607 #        mac_address => undef, events => undef, 
608 #        @_ };
609 #    my $hostname = $arg->{hostname};
610 #    my $status = $arg->{status};
611 #    my $passwd = $arg->{passwd};
612 #    my $mac_address = $arg->{mac_address};
613 #    my $events = $arg->{events};
615 #    if (not defined $hostname) {
616 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
617 #        return;
618 #    }
620 #    my ($seconds, $minutes, $hours, $monthday, $month,
621 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
622 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
623 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
624 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
625 #    $month+=1;
626 #    $month = $month < 10 ? $month = "0".$month : $month;
627 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
628 #    $year+=1900;
629 #    my $t = "$year$month$monthday$hours$minutes$seconds";
630 #    
631 #    $shmda->shlock(LOCK_EX);
632 #    if (defined $status) {
633 #        $known_daemons->{$hostname}->{status} = $status;
634 #    }
635 #    if (defined $passwd) {
636 #        $known_daemons->{$hostname}->{passwd} = $passwd;
637 #    }
638 #    if (defined $mac_address) {
639 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
640 #    }
641 #    if (defined $events) {
642 #        $known_daemons->{$hostname}->{events} = $events;
643 #    }
644 #    $known_daemons->{$hostname}->{timestamp} = $t;
645 #    $shmda->shlock(LOCK_EX);
646 #    return;
647 #}
650 #===  FUNCTION  ================================================================
651 #         NAME:  update_known_daemons
652 #   PARAMETERS:  hostname - string - ip address and port of host (required)
653 #                status - string - (optional)
654 #                passwd - string - (optional)
655 #                client - string - ip address and port of client (optional)
656 #      RETURNS:  nothing
657 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
658 #===============================================================================
659 #sub update_known_daemons {
660 #    my $arg = {
661 #        hostname => undef, status => undef, passwd => undef,
662 #        @_ };
663 #    my $hostname = $arg->{hostname};
664 #    my $status = $arg->{status};
665 #    my $passwd = $arg->{passwd};
667 #    if (not defined $hostname) {
668 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
669 #        return;
670 #    }
672 #    my ($seconds, $minutes, $hours, $monthday, $month,
673 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
674 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
675 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
676 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
677 #    $month+=1;
678 #    $month = $month < 10 ? $month = "0".$month : $month;
679 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
680 #    $year+=1900;
681 #    my $t = "$year$month$monthday$hours$minutes$seconds";
683 #    $shmda->shlock(LOCK_EX);
684 #    if (defined $status) {
685 #        $known_daemons->{$hostname}->{status} = $status;
686 #    }
687 #    if (defined $passwd) {
688 #        $known_daemons->{$hostname}->{passwd} = $passwd;
689 #    }
690 #    $known_daemons->{$hostname}->{timestamp} = $t;
691 #    $shmda->shunlock(LOCK_EX);
692 #    return;
693 #}
696 #===  FUNCTION  ================================================================
697 #         NAME:  print_known_clients 
698 #   PARAMETERS:  nothing
699 #      RETURNS:  nothing
700 #  DESCRIPTION:  nomen est omen
701 #===============================================================================
702 #sub print_known_clients {
704 #    print "####################################\n";
705 #    print "# status of known_clients\n";
706 #    $shmcl->shlock(LOCK_EX);
707 #    my @hosts = keys %$known_clients;
708 #    if (@hosts) {
709 #        foreach my $host (@hosts) {
710 #            my $status = $known_clients->{$host}->{status} ;
711 #            my $passwd = $known_clients->{$host}->{passwd};
712 #            my $timestamp = $known_clients->{$host}->{timestamp};
713 #            my $mac_address = $known_clients->{$host}->{mac_address};
714 #            my $events = $known_clients->{$host}->{events};
715 #            print "$host\n";
716 #            print "\tstatus:      $status\n";
717 #            print "\tpasswd:      $passwd\n";
718 #            print "\ttimestamp:   $timestamp\n";
719 #            print "\tmac_address: $mac_address\n";
720 #            print "\tevents:      $events\n";
721 #        }
722 #    }
723 #    $shmcl->shunlock(LOCK_EX);
724 #    print "####################################\n";
725 #    return;
726 #}
729 #===  FUNCTION  ================================================================
730 #         NAME:  create_known_client
731 #   PARAMETERS:  hostname - string - key for the hash known_clients
732 #      RETURNS:  nothing
733 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
734 #===============================================================================
735 sub create_known_client {
736     my ($hostname) = @_;
738     my $entry = { table=>'known_clients',
739         hostname=>$hostname,
740         status=>'none',
741         hostkey=>'none',
742         timestamp=>'none',
743         macaddress=>'none',
744         events=>'none',
745     };
746     my $res = $known_clients_db->add_dbentry($entry);
747     if ($res > 0) {
748         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
749     }
751     return;  
755 #===  FUNCTION  ================================================================
756 #         NAME:  add_content2known_clients
757 #   PARAMETERS:  hostname - string - ip address and port of host (required)
758 #                status - string - (optional)
759 #                passwd - string - (optional)
760 #                mac_address - string - (optional)
761 #                events - string - event of client, executable skripts 
762 #                under /etc/gosac/events
763 #      RETURNS:  nothing
764 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
765 #===============================================================================
766 #sub update_known_clients {
767 #    my $arg = {
768 #        hostname => undef, status => undef, hostkey => undef,
769 #        macaddress => undef, events => undef, timestamp=>undef,
770 #        @_ };
771 #    my $hostname = $arg->{hostname};
772 #    my $status = $arg->{status};
773 #    my $hostkey = $arg->{hostkey};
774 #    my $macaddress = $arg->{macaddress};
775 #    my $events = $arg->{events};
776 #    my $timestamp = $arg->{timestamp}; 
778 #    if (not defined $hostname) {
779 #        daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
780 #        return;
781 #    }
783 #    my $change_entry = { table=>'known_clients',
784 #                        where=>'hostname', 
785 #                        timestamp=>&get_time, 
786 #                        };
787 #   
788 #   
789 #    if (defined $status) {
790 #        $change_entry->{status} = $status;
791 #    }
792 #    if (defined $hostkey) {
793 #        $change_entry->{hostkey} = $hostkey;
794 #    }
795 #    if (defined $macaddress) {
796 #        $change_entry->{macaddress} = $macaddress;
797 #    }
798 #    if (defined $events) {
799 #        $change_entry->{events} = $events;
800 #    }
801 #    
802 #    $known_clients->change_dbentry($change_entry);
803 #    return;
804 #}
805  
807 #===  FUNCTION  ================================================================
808 #         NAME:  
809 #   PARAMETERS:  
810 #      RETURNS:  
811 #  DESCRIPTION:  
812 #===============================================================================    
813 #sub clean_up_known_clients {
814 #    my ($address) = @_ ;
815 #    
816 #    if (not exists $known_clients->{$address}) {
817 #        daemon_log("cannot prune known_clients from $address, client not known", 5);
818 #        return;
819 #    }
821 #    delete $known_clients->{$address};
823 #    # send bus a msg that address was deleted from known_clients
824 #    my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
825 #    &send_msg_hash2bus($out_hash);
827 #    daemon_log("client $address deleted from known_clients because of multiple down time", 3);
828 #    return;
829 #}
832 #===  FUNCTION  ================================================================
833 #         NAME:  update_known_clients
834 #   PARAMETERS:  hostname - string - ip address and port of host (required)
835 #                status - string - (optional)
836 #                passwd - string - (optional)
837 #                client - string - ip address and port of client (optional)
838 #      RETURNS:  nothing
839 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
840 #===============================================================================
841 #sub update_known_clients {
842 #    my $arg = {
843 #        hostname => undef, status => undef, passwd => undef,
844 #        mac_address => undef, events => undef,
845 #        @_ };
846 #    my $hostname = $arg->{hostname};
847 #    my $status = $arg->{status};
848 #    my $passwd = $arg->{passwd};
849 #    my $mac_address = $arg->{mac_address};
850 #    my $events = $arg->{events};
852 #    if (not defined $hostname) {
853 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
854 #        return;
855 #    }
857 #    my ($seconds, $minutes, $hours, $monthday, $month,
858 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
859 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
860 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
861 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
862 #    $month+=1;
863 #    $month = $month < 10 ? $month = "0".$month : $month;
864 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
865 #    $year+=1900;
866 #    my $t = "$year$month$monthday$hours$minutes$seconds";
868 #    if (defined $status) {
869 #        $known_clients->{$hostname}->{status} = $status;
870 #    }
871 #    if (defined $passwd) {
872 #        $known_clients->{$hostname}->{passwd} = $passwd;
873 #    }
874 #    if (defined $mac_address) {
875 #        $known_clients->{$hostname}->{mac_address} = $mac_address; 
876 #    }
877 #    if (defined $events) {
878 #        $known_clients->{$hostname}->{events} = $events;
879 #    }
880 #    $known_clients_db->{$hostname}->{timestamp} = $t;
881 #    return;
882 #}
890 #==== MAIN = main ==============================================================
892 #  parse commandline options
893 Getopt::Long::Configure( "bundling" );
894 GetOptions("h|help" => \&usage,
895         "c|config=s" => \$cfg_file,
896         "f|foreground" => \$foreground,
897         "v|verbose+" => \$verbose,
898         "no-bus+" => \$no_bus,
899         "no-arp+" => \$no_arp,
900            );
902 #  read and set config parameters
903 &check_cmdline_param ;
904 &read_configfile;
905 &check_pid;
907 $SIG{CHLD} = 'IGNORE';
909 # forward error messages to logfile
910 if( ! $foreground ) {
911     open(STDERR, '>>', $log_file);
912     open(STDOUT, '>>', $log_file);
915 # Just fork, if we are not in foreground mode
916 if( ! $foreground ) { 
917     chdir '/'                 or die "Can't chdir to /: $!";
918     $pid = fork;
919     setsid                    or die "Can't start a new session: $!";
920     umask 0;
921 } else { 
922     $pid = $$; 
925 # Do something useful - put our PID into the pid_file
926 if( 0 != $pid ) {
927     open( LOCK_FILE, ">$pid_file" );
928     print LOCK_FILE "$pid\n";
929     close( LOCK_FILE );
930     if( !$foreground ) { 
931         exit( 0 ) 
932     };
935 daemon_log(" ", 1);
936 daemon_log("$0 started!", 1);
939 # connect to gosa-si job queue
940 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
941 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
942 $job_db->create_table('jobs', \@job_col_names);
944 # connect to known_clients_db
945 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
946 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
947 $known_clients_db->create_table('known_clients', \@clients_col_names);
949 # connect to known_server_db
950 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
951 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
952 $known_server_db->create_table('known_server', \@server_col_names);
954 # import all modules
955 &import_modules;
957 # check wether all modules are gosa-si valid passwd check
959 # create reading and writing vectors
960 my $rbits = my $wbits = my $ebits = "";
962 # add all module inputs to listening vector
963 while( my ($mod_name, $info) = each %$known_modules ) {
964     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
965     vec($rbits, fileno $input, 1) = 1;   
970 ## start arp fifo
971 #if ($no_arp > 0) {
972 #    $arp_activ = "off";
973 #}
974 #my $my_fifo;
975 #if($arp_activ eq "on") {
976 #    daemon_log(" ", 1);
977 #    $my_fifo = &open_fifo($arp_fifo_path);
978 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
979 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
980 #    
981 #    vec($rbits, fileno $arp_fifo, 1) = 1;
982 #}
985 ##################################
986 #everything ready, okay, lets start
987 ##################################
988 while(1) {
990     # add all handles from the childs
991     while ( my ($pid, $child_hash) = each %busy_child ) {
992         
993         # check whether process still exists
994         my $exitus_pid = waitpid($pid, WNOHANG);
995         if($exitus_pid != 0) {
996             delete $busy_child{$pid};
997             next;
998         }
999      
1000         # add child fhd to the listener    
1001         my $fhd = $$child_hash{'pipe_rd'};
1002         vec($rbits, fileno $fhd, 1) = 1;
1003     }
1005     my ($rout, $wout);
1006     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1008     # error handling
1009     if($nf < 0 ) {
1010     }
1013 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1014 #        my $in_msg = <$arp_fifo>;
1015 #        chomp($in_msg);
1016 #        print "arp_activ: msg: $in_msg\n";
1017 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1018 #        print "arp_activ: arp_passwd: $act_passwd\n";
1020 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1022 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1024 #        if ($target eq $server_address) { 
1025 #             print "arp_activ: forward to server\n";
1026 #            my $arp_cipher = &create_ciphering($act_passwd);
1027 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1028 #            &activating_child($crypted_msg, $server_ip);
1029 #        } else {
1030 #            print "arp_activ: send to bus\n";
1031 #            &send_msg_hash2address($in_msg_hash, $bus_address);
1032 #        }
1033 #        print "\n";
1034 #    }
1037     # check input fhd of all modules 
1038     while ( my ($mod_name, $info) = each %$known_modules) {
1039         my $input_fhd = @{$info}[2];    
1040         my $input_activ = @{$info}[3];
1041         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1042             daemon_log(" ", 1);
1043             my $client = $input_fhd->accept();
1044             my $other_end = getpeername($client);
1045             if(not defined $other_end) {
1046                 daemon_log("client cannot be identified: $!");
1047             } else {
1048                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1049                 my $actual_ip = inet_ntoa($iaddr);
1050                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1051                 my $in_msg = &read_from_socket($client);
1052                 if(defined $in_msg){
1053                     chomp($in_msg);
1054                     &activating_child($in_msg, $actual_ip, $client);
1055                 } else {
1056                     daemon_log("cannot read from $actual_ip", 5);
1057                 }
1058             }
1059         }
1060     }
1062     # check all processing childs whether they are finished ('done') or 
1063     while ( my ($pid, $child_hash) = each %busy_child ) {
1064         my $fhd = $$child_hash{'pipe_rd'};
1066         if (vec($rout, fileno $fhd, 1) ) {
1067             daemon_log("process child $pid is ready to read", 5);
1069             $fhd->blocking(1);
1070             my $in_msg = <$fhd>;
1071             $fhd->blocking(0);
1072             my $part_in_msg;
1073             while ($part_in_msg = <$fhd>) {
1074                 if (not defined $part_in_msg) {
1075                     last;
1076                 }
1077                 $in_msg .= $part_in_msg;
1078             }
1079             chomp($in_msg);
1081             daemon_log("process child read: $in_msg", 7);
1082             daemon_log("\n$in_msg", 7);
1083             if (not defined $in_msg) { 
1084                 next; 
1085             } elsif ($in_msg =~ "done") {
1086                 delete $busy_child{$pid};
1087                 $free_child{$pid} = $child_hash;
1088  
1089             } else {
1090                 # send computed answer back to connected client
1091                 my $act_client = $busy_child{$pid}{client_ref};
1092                 print $act_client $in_msg."\n";
1094                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1095                 delete $busy_child{$pid};
1096                 $free_child{$pid} = $child_hash;
1098                 # give the client a chance to read 
1099                 sleep(2);
1100                 close ($act_client);   
1101             }
1102         }
1103     }
1105     # check gosa job queue for jobs with executable timestamp
1106     my ($seconds, $minutes, $hours, $monthday, $month,
1107     $year, $weekday, $yearday, $sommertime) = localtime(time);
1108     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1109     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1110     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1111     $month+=1;
1112     $month = $month < 10 ? $month = "0".$month : $month;
1113     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1114     $year+=1900;
1115     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1116     
1117     
1118     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1120     while( my ($id, $hit) = each %{$res} ) {         
1122         my $jobdb_id = $hit->{ROWID};
1123         my $macaddress = $hit->{macaddress};
1124         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1125         my $out_msg_hash = $job_msg_hash;
1126         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1127         # expect macaddress is unique!!!!!!
1128         my $target = $res_hash->{1}->{hostname};
1129         
1130         if (not defined $target) {
1131             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1132             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1133             my $update_hash = { table=>$job_queue_table_name,
1134                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1135                 where=> [ { ROWID=>[$jobdb_id] } ],
1136             };
1137             my $res = $job_db->update_dbentry($update_hash);
1139             next;
1140         }
1142         # add target
1143         &add_content2xml_hash($out_msg_hash, "target", $target);
1145         # add new header
1146         my $out_header = $job_msg_hash->{header}[0];
1147         $out_header =~ s/job_/gosa_/;
1148         delete $out_msg_hash->{header};
1149         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1150         
1151         # add sqlite_id 
1152         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1153     
1154         my $out_msg = &create_xml_string($out_msg_hash);
1156         # encrypt msg as a GosaPackage module
1157         my $cipher = &create_ciphering($gosa_passwd);
1158         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1160         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1162 #######################
1163 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1165         if ($error == 0) {
1166             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1167             my $res = $job_db->exec_statement($sql);
1168         } else {
1169             my $update_hash = { table=>$job_queue_table_name, 
1170                                 update=> [ { status=>'error' } ],
1171                                 where=> [ { ROWID=>$jobdb_id } ],
1172                               };
1173             my $res = $job_db->update_dbentry($update_hash);
1174         }
1176     }