Code

c923354ea61bf5f11012b48f7ef98129ba566f49
[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         print STDERR ">>>>>>>>>>>>>>><$cfg_file\n";
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                 print LOG_HANDLE "\n$month $monthday $hours:$minutes:$seconds $name $msg";
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                             &daemon_log("##########", 5);
480                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
481                             if (defined $tmp) {
482                                 $answer = $tmp;
483                             }
484                             &daemon_log("##########", 5);
485                     }        
487                     #&print_known_daemons();
488                     #&print_known_clients();
490                     daemon_log("processing of msg finished", 5);
491  
492                    if (defined $answer) {
493                         print $PARENT_wr $answer."\n";
494                         my $len_answer = length $answer;
495                         daemon_log("with answer: length of answer: $len_answer", 5);
496                         daemon_log("$answer", 5);
497                     } else {
498                         print $PARENT_wr "done"."\n";
499                         daemon_log(" ", 5);
500                     }
501                     redo;
502                 }
503             }
504             # childs leaving the loop are allowed to die
505             exit(0);
508         #PARENT
509         } else {
510             # Close unused pipes
511             close( $PARENT_rd );
512             close( $PARENT_wr );
514             # add child to child alive hash
515             my %child_hash = (
516                     'pid' => $child_pid,
517                     'pipe_wr' => $CHILD_wr,
518                     'pipe_rd' => $CHILD_rd,
519                     'client_ref' => "",
520                     );
522             $child = \%child_hash;
523             $busy_child{$$child{'pid'}} = $child;
524             return $child;
525         }
526     }
530 #===  FUNCTION  ================================================================
531 #         NAME:  read_from_socket
532 #   PARAMETERS:  socket fh - 
533 #      RETURNS:  result string - readed characters from socket
534 #  DESCRIPTION:  reads data from socket in 16 byte steps
535 #===============================================================================
536 sub read_from_socket {
537     my ($socket) = @_;
538     my $result = "";
540     $socket->blocking(1);
541     $result = <$socket>;
543     $socket->blocking(0);
544     while ( my $char = <$socket> ) {
545         if (not defined $char) { last }
546         $result .= $char;
547     }
549     return $result;
553 #===  FUNCTION  ================================================================
554 #         NAME:  print_known_daemons
555 #   PARAMETERS:  nothing
556 #      RETURNS:  nothing
557 #  DESCRIPTION:  nomen est omen
558 #===============================================================================
559 #sub print_known_daemons {
560 #    my ($tmp) = @_ ;
561 #    print "####################################\n";
562 #    print "# status of known_daemons\n";
563 #    $shmda->shlock(LOCK_EX);
564 #    my @hosts = keys %$known_daemons;
565 #    foreach my $host (@hosts) {
566 #        my $status = $known_daemons->{$host}->{status} ;
567 #        my $passwd = $known_daemons->{$host}->{passwd};
568 #        my $timestamp = $known_daemons->{$host}->{timestamp};
569 #        print "$host\n";
570 #        print "\tstatus:    $status\n";
571 #        print "\tpasswd:    $passwd\n";
572 #        print "\ttimestamp: $timestamp\n";
573 #    }
574 #    $shmda->shunlock(LOCK_EX);
575 #    print "####################################\n";
576 #    return;
577 #}
580 #===  FUNCTION  ================================================================
581 #         NAME:  create_known_daemon
582 #   PARAMETERS:  hostname - string - key for the hash known_daemons
583 #      RETURNS:  nothing
584 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
585 #===============================================================================
586 #sub create_known_daemon {
587 #    my ($hostname) = @_;
588 #    $shmda->shlock(LOCK_EX);
589 #    $known_daemons->{$hostname} = {};
590 #    $known_daemons->{$hostname}->{status} = "none";
591 #    $known_daemons->{$hostname}->{passwd} = "none";
592 #    $known_daemons->{$hostname}->{timestamp} = "none";
593 #    $shmda->shunlock(LOCK_EX); 
594 #    return;  
595 #}
598 #===  FUNCTION  ================================================================
599 #         NAME:  add_content2known_daemons
600 #   PARAMETERS:  hostname - string - ip address and port of host (required)
601 #                status - string - (optional)
602 #                passwd - string - (optional)
603 #                mac_address - string - mac address of host (optional)
604 #      RETURNS:  nothing
605 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
606 #===============================================================================
607 #sub add_content2known_daemons {
608 #    my $arg = {
609 #        hostname => undef, status => undef, passwd => undef,
610 #        mac_address => undef, events => undef, 
611 #        @_ };
612 #    my $hostname = $arg->{hostname};
613 #    my $status = $arg->{status};
614 #    my $passwd = $arg->{passwd};
615 #    my $mac_address = $arg->{mac_address};
616 #    my $events = $arg->{events};
618 #    if (not defined $hostname) {
619 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
620 #        return;
621 #    }
623 #    my ($seconds, $minutes, $hours, $monthday, $month,
624 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
625 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
626 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
627 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
628 #    $month+=1;
629 #    $month = $month < 10 ? $month = "0".$month : $month;
630 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
631 #    $year+=1900;
632 #    my $t = "$year$month$monthday$hours$minutes$seconds";
633 #    
634 #    $shmda->shlock(LOCK_EX);
635 #    if (defined $status) {
636 #        $known_daemons->{$hostname}->{status} = $status;
637 #    }
638 #    if (defined $passwd) {
639 #        $known_daemons->{$hostname}->{passwd} = $passwd;
640 #    }
641 #    if (defined $mac_address) {
642 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
643 #    }
644 #    if (defined $events) {
645 #        $known_daemons->{$hostname}->{events} = $events;
646 #    }
647 #    $known_daemons->{$hostname}->{timestamp} = $t;
648 #    $shmda->shlock(LOCK_EX);
649 #    return;
650 #}
653 #===  FUNCTION  ================================================================
654 #         NAME:  update_known_daemons
655 #   PARAMETERS:  hostname - string - ip address and port of host (required)
656 #                status - string - (optional)
657 #                passwd - string - (optional)
658 #                client - string - ip address and port of client (optional)
659 #      RETURNS:  nothing
660 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
661 #===============================================================================
662 #sub update_known_daemons {
663 #    my $arg = {
664 #        hostname => undef, status => undef, passwd => undef,
665 #        @_ };
666 #    my $hostname = $arg->{hostname};
667 #    my $status = $arg->{status};
668 #    my $passwd = $arg->{passwd};
670 #    if (not defined $hostname) {
671 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
672 #        return;
673 #    }
675 #    my ($seconds, $minutes, $hours, $monthday, $month,
676 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
677 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
678 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
679 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
680 #    $month+=1;
681 #    $month = $month < 10 ? $month = "0".$month : $month;
682 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
683 #    $year+=1900;
684 #    my $t = "$year$month$monthday$hours$minutes$seconds";
686 #    $shmda->shlock(LOCK_EX);
687 #    if (defined $status) {
688 #        $known_daemons->{$hostname}->{status} = $status;
689 #    }
690 #    if (defined $passwd) {
691 #        $known_daemons->{$hostname}->{passwd} = $passwd;
692 #    }
693 #    $known_daemons->{$hostname}->{timestamp} = $t;
694 #    $shmda->shunlock(LOCK_EX);
695 #    return;
696 #}
699 #===  FUNCTION  ================================================================
700 #         NAME:  print_known_clients 
701 #   PARAMETERS:  nothing
702 #      RETURNS:  nothing
703 #  DESCRIPTION:  nomen est omen
704 #===============================================================================
705 #sub print_known_clients {
707 #    print "####################################\n";
708 #    print "# status of known_clients\n";
709 #    $shmcl->shlock(LOCK_EX);
710 #    my @hosts = keys %$known_clients;
711 #    if (@hosts) {
712 #        foreach my $host (@hosts) {
713 #            my $status = $known_clients->{$host}->{status} ;
714 #            my $passwd = $known_clients->{$host}->{passwd};
715 #            my $timestamp = $known_clients->{$host}->{timestamp};
716 #            my $mac_address = $known_clients->{$host}->{mac_address};
717 #            my $events = $known_clients->{$host}->{events};
718 #            print "$host\n";
719 #            print "\tstatus:      $status\n";
720 #            print "\tpasswd:      $passwd\n";
721 #            print "\ttimestamp:   $timestamp\n";
722 #            print "\tmac_address: $mac_address\n";
723 #            print "\tevents:      $events\n";
724 #        }
725 #    }
726 #    $shmcl->shunlock(LOCK_EX);
727 #    print "####################################\n";
728 #    return;
729 #}
732 #===  FUNCTION  ================================================================
733 #         NAME:  create_known_client
734 #   PARAMETERS:  hostname - string - key for the hash known_clients
735 #      RETURNS:  nothing
736 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
737 #===============================================================================
738 sub create_known_client {
739     my ($hostname) = @_;
741     my $entry = { table=>'known_clients',
742         hostname=>$hostname,
743         status=>'none',
744         hostkey=>'none',
745         timestamp=>'none',
746         macaddress=>'none',
747         events=>'none',
748     };
749     my $res = $known_clients_db->add_dbentry($entry);
750     if ($res > 0) {
751         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
752     }
754     return;  
758 #===  FUNCTION  ================================================================
759 #         NAME:  add_content2known_clients
760 #   PARAMETERS:  hostname - string - ip address and port of host (required)
761 #                status - string - (optional)
762 #                passwd - string - (optional)
763 #                mac_address - string - (optional)
764 #                events - string - event of client, executable skripts 
765 #                under /etc/gosac/events
766 #      RETURNS:  nothing
767 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
768 #===============================================================================
769 #sub update_known_clients {
770 #    my $arg = {
771 #        hostname => undef, status => undef, hostkey => undef,
772 #        macaddress => undef, events => undef, timestamp=>undef,
773 #        @_ };
774 #    my $hostname = $arg->{hostname};
775 #    my $status = $arg->{status};
776 #    my $hostkey = $arg->{hostkey};
777 #    my $macaddress = $arg->{macaddress};
778 #    my $events = $arg->{events};
779 #    my $timestamp = $arg->{timestamp}; 
781 #    if (not defined $hostname) {
782 #        daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
783 #        return;
784 #    }
786 #    my $change_entry = { table=>'known_clients',
787 #                        where=>'hostname', 
788 #                        timestamp=>&get_time, 
789 #                        };
790 #   
791 #   
792 #    if (defined $status) {
793 #        $change_entry->{status} = $status;
794 #    }
795 #    if (defined $hostkey) {
796 #        $change_entry->{hostkey} = $hostkey;
797 #    }
798 #    if (defined $macaddress) {
799 #        $change_entry->{macaddress} = $macaddress;
800 #    }
801 #    if (defined $events) {
802 #        $change_entry->{events} = $events;
803 #    }
804 #    
805 #    $known_clients->change_dbentry($change_entry);
806 #    return;
807 #}
808  
810 #===  FUNCTION  ================================================================
811 #         NAME:  
812 #   PARAMETERS:  
813 #      RETURNS:  
814 #  DESCRIPTION:  
815 #===============================================================================    
816 #sub clean_up_known_clients {
817 #    my ($address) = @_ ;
818 #    
819 #    if (not exists $known_clients->{$address}) {
820 #        daemon_log("cannot prune known_clients from $address, client not known", 5);
821 #        return;
822 #    }
824 #    delete $known_clients->{$address};
826 #    # send bus a msg that address was deleted from known_clients
827 #    my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
828 #    &send_msg_hash2bus($out_hash);
830 #    daemon_log("client $address deleted from known_clients because of multiple down time", 3);
831 #    return;
832 #}
835 #===  FUNCTION  ================================================================
836 #         NAME:  update_known_clients
837 #   PARAMETERS:  hostname - string - ip address and port of host (required)
838 #                status - string - (optional)
839 #                passwd - string - (optional)
840 #                client - string - ip address and port of client (optional)
841 #      RETURNS:  nothing
842 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
843 #===============================================================================
844 #sub update_known_clients {
845 #    my $arg = {
846 #        hostname => undef, status => undef, passwd => undef,
847 #        mac_address => undef, events => undef,
848 #        @_ };
849 #    my $hostname = $arg->{hostname};
850 #    my $status = $arg->{status};
851 #    my $passwd = $arg->{passwd};
852 #    my $mac_address = $arg->{mac_address};
853 #    my $events = $arg->{events};
855 #    if (not defined $hostname) {
856 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
857 #        return;
858 #    }
860 #    my ($seconds, $minutes, $hours, $monthday, $month,
861 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
862 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
863 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
864 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
865 #    $month+=1;
866 #    $month = $month < 10 ? $month = "0".$month : $month;
867 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
868 #    $year+=1900;
869 #    my $t = "$year$month$monthday$hours$minutes$seconds";
871 #    if (defined $status) {
872 #        $known_clients->{$hostname}->{status} = $status;
873 #    }
874 #    if (defined $passwd) {
875 #        $known_clients->{$hostname}->{passwd} = $passwd;
876 #    }
877 #    if (defined $mac_address) {
878 #        $known_clients->{$hostname}->{mac_address} = $mac_address; 
879 #    }
880 #    if (defined $events) {
881 #        $known_clients->{$hostname}->{events} = $events;
882 #    }
883 #    $known_clients_db->{$hostname}->{timestamp} = $t;
884 #    return;
885 #}
893 #==== MAIN = main ==============================================================
895 #  parse commandline options
896 Getopt::Long::Configure( "bundling" );
897 GetOptions("h|help" => \&usage,
898         "c|config=s" => \$cfg_file,
899         "f|foreground" => \$foreground,
900         "v|verbose+" => \$verbose,
901         "no-bus+" => \$no_bus,
902         "no-arp+" => \$no_arp,
903            );
905 #  read and set config parameters
906 &check_cmdline_param ;
907 &read_configfile;
908 &check_pid;
910 $SIG{CHLD} = 'IGNORE';
912 # forward error messages to logfile
913 if( ! $foreground ) {
914     open(STDERR, '>>', $log_file);
915     open(STDOUT, '>>', $log_file);
918 # Just fork, if we are not in foreground mode
919 if( ! $foreground ) { 
920     chdir '/'                 or die "Can't chdir to /: $!";
921     $pid = fork;
922     setsid                    or die "Can't start a new session: $!";
923     umask 0;
924 } else { 
925     $pid = $$; 
928 # Do something useful - put our PID into the pid_file
929 if( 0 != $pid ) {
930     open( LOCK_FILE, ">$pid_file" );
931     print LOCK_FILE "$pid\n";
932     close( LOCK_FILE );
933     if( !$foreground ) { 
934         exit( 0 ) 
935     };
938 daemon_log(" ", 1);
939 daemon_log("$0 started!", 1);
942 # connect to gosa-si job queue
943 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
944 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
945 $job_db->create_table('jobs', \@job_col_names);
947 # connect to known_clients_db
948 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
949 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
950 $known_clients_db->create_table('known_clients', \@clients_col_names);
952 # connect to known_server_db
953 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
954 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
955 $known_server_db->create_table('known_server', \@server_col_names);
957 # import all modules
958 &import_modules;
960 # check wether all modules are gosa-si valid passwd check
962 # create reading and writing vectors
963 my $rbits = my $wbits = my $ebits = "";
965 # add all module inputs to listening vector
966 while( my ($mod_name, $info) = each %$known_modules ) {
967     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
968     vec($rbits, fileno $input, 1) = 1;   
973 ## start arp fifo
974 #if ($no_arp > 0) {
975 #    $arp_activ = "off";
976 #}
977 #my $my_fifo;
978 #if($arp_activ eq "on") {
979 #    daemon_log(" ", 1);
980 #    $my_fifo = &open_fifo($arp_fifo_path);
981 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
982 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
983 #    
984 #    vec($rbits, fileno $arp_fifo, 1) = 1;
985 #}
988 ##################################
989 #everything ready, okay, lets start
990 ##################################
991 while(1) {
993     # add all handles from the childs
994     while ( my ($pid, $child_hash) = each %busy_child ) {
995         
996         # check whether process still exists
997         my $exitus_pid = waitpid($pid, WNOHANG);
998         if($exitus_pid != 0) {
999             delete $busy_child{$pid};
1000             next;
1001         }
1002      
1003         # add child fhd to the listener    
1004         my $fhd = $$child_hash{'pipe_rd'};
1005         vec($rbits, fileno $fhd, 1) = 1;
1006     }
1008     my ($rout, $wout);
1009     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1011     # error handling
1012     if($nf < 0 ) {
1013     }
1016 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1017 #        my $in_msg = <$arp_fifo>;
1018 #        chomp($in_msg);
1019 #        print "arp_activ: msg: $in_msg\n";
1020 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1021 #        print "arp_activ: arp_passwd: $act_passwd\n";
1023 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1025 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1027 #        if ($target eq $server_address) { 
1028 #             print "arp_activ: forward to server\n";
1029 #            my $arp_cipher = &create_ciphering($act_passwd);
1030 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1031 #            &activating_child($crypted_msg, $server_ip);
1032 #        } else {
1033 #            print "arp_activ: send to bus\n";
1034 #            &send_msg_hash2address($in_msg_hash, $bus_address);
1035 #        }
1036 #        print "\n";
1037 #    }
1040     # check input fhd of all modules 
1041     while ( my ($mod_name, $info) = each %$known_modules) {
1042         my $input_fhd = @{$info}[2];    
1043         my $input_activ = @{$info}[3];
1044         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1045             daemon_log(" ", 1);
1046             my $client = $input_fhd->accept();
1047             my $other_end = getpeername($client);
1048             if(not defined $other_end) {
1049                 daemon_log("client cannot be identified: $!");
1050             } else {
1051                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1052                 my $actual_ip = inet_ntoa($iaddr);
1053                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1054                 my $in_msg = &read_from_socket($client);
1055                 if(defined $in_msg){
1056                     chomp($in_msg);
1057                     &activating_child($in_msg, $actual_ip, $client);
1058                 } else {
1059                     daemon_log("cannot read from $actual_ip", 5);
1060                 }
1061             }
1062         }
1063     }
1065     # check all processing childs whether they are finished ('done') or 
1066     while ( my ($pid, $child_hash) = each %busy_child ) {
1067         my $fhd = $$child_hash{'pipe_rd'};
1069         if (vec($rout, fileno $fhd, 1) ) {
1070             daemon_log("process child $pid is ready to read", 5);
1072             $fhd->blocking(1);
1073             my $in_msg = <$fhd>;
1074             $fhd->blocking(0);
1075             my $part_in_msg;
1076             while ($part_in_msg = <$fhd>) {
1077                 if (not defined $part_in_msg) {
1078                     last;
1079                 }
1080                 $in_msg .= $part_in_msg;
1081             }
1082             chomp($in_msg);
1084             daemon_log("process child read: $in_msg", 5);
1085             if (not defined $in_msg) { 
1086                 next; 
1087             } elsif ($in_msg =~ "done") {
1088                 delete $busy_child{$pid};
1089                 $free_child{$pid} = $child_hash;
1090  
1091             } else {
1092                 # send computed answer back to connected client
1093                 my $act_client = $busy_child{$pid}{client_ref};
1094                 print $act_client $in_msg."\n";
1096                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1097                 delete $busy_child{$pid};
1098                 $free_child{$pid} = $child_hash;
1100                 # give the client a chance to read 
1101                 sleep(2);
1102                 close ($act_client);   
1103             }
1104         }
1105     }
1107     # check gosa job queue for jobs with executable timestamp
1108     my ($seconds, $minutes, $hours, $monthday, $month,
1109     $year, $weekday, $yearday, $sommertime) = localtime(time);
1110     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1111     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1112     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1113     $month+=1;
1114     $month = $month < 10 ? $month = "0".$month : $month;
1115     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1116     $year+=1900;
1117     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1118     
1119     
1120     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1122     while( my ($id, $hit) = each %{$res} ) {         
1124         my $jobdb_id = $hit->{ROWID};
1125         my $macaddress = $hit->{macaddress};
1126         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1127         my $out_msg_hash = $job_msg_hash;
1128         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1129         # expect macaddress is unique!!!!!!
1130         my $target = $res_hash->{1}->{hostname};
1131         
1132         if (not defined $target) {
1133             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1134             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1135             my $update_hash = { table=>$job_queue_table_name,
1136                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1137                 where=> [ { ROWID=>[$jobdb_id] } ],
1138             };
1139             my $res = $job_db->update_dbentry($update_hash);
1141             next;
1142         }
1144         # add target
1145         &add_content2xml_hash($out_msg_hash, "target", $target);
1147         # add new header
1148         my $out_header = $job_msg_hash->{header}[0];
1149         $out_header =~ s/job_/gosa_/;
1150         delete $out_msg_hash->{header};
1151         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1152         
1153         # add sqlite_id 
1154         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1155     
1156         my $out_msg = &create_xml_string($out_msg_hash);
1158         # encrypt msg as a GosaPackage module
1159         my $cipher = &create_ciphering($gosa_passwd);
1160         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1162         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1164 #######################
1165 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1167         if ($error == 0) {
1168             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1169             my $res = $job_db->exec_statement($sql);
1170         } else {
1171             my $update_hash = { table=>$job_queue_table_name, 
1172                                 update=> [ { status=>'error' } ],
1173                                 where=> [ { ROWID=>$jobdb_id } ],
1174                               };
1175             my $res = $job_db->update_dbentry($update_hash);
1176         }
1178     }