Code

Created needed structure
[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 IO::Handle;
33 use IO::Select;
34 use Symbol qw(qualify_to_ref);
35 use Crypt::Rijndael;
36 use MIME::Base64;
37 use Digest::MD5  qw(md5 md5_hex md5_base64);
38 use XML::Simple;
39 use Data::Dumper;
40 use Sys::Syslog qw( :DEFAULT setlogsock);
41 use Cwd;
42 use File::Spec;
43 use GOSA::GosaSupportDaemon;
44 use GOSA::DBsqlite;
45 use threads;
47 my $modules_path = "/usr/lib/gosa-si/modules";
48 use lib "/usr/lib/gosa-si/modules";
50 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
51 my ($bus, $msg_to_bus, $bus_cipher);
52 my ($server, $server_mac_address, $server_events);
53 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name);
54 my ($known_modules, $known_clients_file_name, $known_server_file_name);
55 my ($max_clients);
56 my ($pid_file, $procid, $pid, $log_file);
57 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
58 my ($arp_activ, $arp_fifo, $arp_fifo_path);
60 # variables declared in config file are always set to 'our'
61 our (%cfg_defaults, $log_file, $pid_file, 
62     $bus_activ, $bus_passwd, $bus_ip, $bus_port,
63     $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
64     $arp_activ, $arp_fifo_path,
65     $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
66 );
68 # additional variable which should be globaly accessable
69 our $xml;
70 our $server_address;
71 our $bus_address;
72 our $gosa_address;
73 our $no_bus;
74 our $no_arp;
75 our $verbose;
76 our $forground;
77 our $cfg_file;
79 # specifies the verbosity of the daemon_log
80 $verbose = 0 ;
82 # if foreground is not null, script will be not forked to background
83 $foreground = 0 ;
85 # specifies the timeout seconds while checking the online status of a registrating client
86 $ping_timeout = 5;
88 $no_bus = 0;
90 $no_arp = 0;
92 # name of table for storing gosa jobs
93 our $job_queue_table_name = 'jobs';
94 our $job_db;
96 # holds all other gosa-sd as well as the gosa-sd-bus
97 our $known_server_db;
99 # holds all registrated clients
100 our $known_clients_db;
102 %cfg_defaults =
103 ("general" =>
104     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
105     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
106     "child_max" => [\$child_max, 10],
107     "child_min" => [\$child_min, 3],
108     "child_timeout" => [\$child_timeout, 180],
109     "job_queue_timeout" => [\$job_queue_timeout, undef],
110     "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
111     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
112     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/known_server.db'],
113    },
114 "bus" =>
115     {"bus_activ" => [\$bus_activ, "on"],
116     "bus_passwd" => [\$bus_passwd, ""],
117     "bus_ip" => [\$bus_ip, "0.0.0.0"],
118     "bus_port" => [\$bus_port, "20080"],
119     },
120 "server" =>
121     {"server_activ" => [\$server_activ, "on"],
122     "server_ip" => [\$server_ip, "0.0.0.0"],
123     "server_port" => [\$server_port, "20081"],
124     "server_passwd" => [\$server_passwd, ""],
125     "max_clients" => [\$max_clients, 100],
126     },
127 "arp" =>
128     {"arp_activ" => [\$arp_activ, "on"],
129     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
130     },
131 "gosa" =>
132     {"gosa_activ" => [\$gosa_activ, "on"],
133     "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
134     "gosa_port" => [\$gosa_port, "20082"],
135     "gosa_passwd" => [\$gosa_passwd, "none"],
136     },
137     );
140 #===  FUNCTION  ================================================================
141 #         NAME:  usage
142 #   PARAMETERS:  nothing
143 #      RETURNS:  nothing
144 #  DESCRIPTION:  print out usage text to STDERR
145 #===============================================================================
146 sub usage {
147     print STDERR << "EOF" ;
148 usage: $0 [-hvf] [-c config]
150            -h        : this (help) message
151            -c <file> : config file
152            -f        : foreground, process will not be forked to background
153            -v        : be verbose (multiple to increase verbosity)
154            -no-bus   : starts $0 without connection to bus
155            -no-arp   : starts $0 without connection to arp module
156  
157 EOF
158     print "\n" ;
162 #===  FUNCTION  ================================================================
163 #         NAME:  read_configfile
164 #   PARAMETERS:  cfg_file - string -
165 #      RETURNS:  nothing
166 #  DESCRIPTION:  read cfg_file and set variables
167 #===============================================================================
168 sub read_configfile {
169     my $cfg;
170     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
171         if( -r $cfg_file ) {
172             $cfg = Config::IniFiles->new( -file => $cfg_file );
173         } else {
174             print STDERR "Couldn't read config file!\n";
175         }
176     } else {
177         $cfg = Config::IniFiles->new() ;
178     }
179     foreach my $section (keys %cfg_defaults) {
180         foreach my $param (keys %{$cfg_defaults{ $section }}) {
181             my $pinfo = $cfg_defaults{ $section }{ $param };
182             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
183         }
184     }
188 #===  FUNCTION  ================================================================
189 #         NAME:  logging
190 #   PARAMETERS:  level - string - default 'info'
191 #                msg - string -
192 #                facility - string - default 'LOG_DAEMON'
193 #      RETURNS:  nothing
194 #  DESCRIPTION:  function for logging
195 #===============================================================================
196 sub daemon_log : locked {
197     # log into log_file
198     my( $msg, $level ) = @_;
199     if(not defined $msg) { return }
200     if(not defined $level) { $level = 1 }
201     if(defined $log_file){
202         open(LOG_HANDLE, ">>$log_file");
203         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
204             print STDERR "cannot open $log_file: $!";
205             return }
206             chomp($msg);
207             if($level <= $verbose){
208                 my ($seconds, $minutes, $hours, $monthday, $month,
209                         $year, $weekday, $yearday, $sommertime) = localtime(time);
210                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
211                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
212                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
213                 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
214                 $month = $monthnames[$month];
215                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
216                 $year+=1900;
217                 my $name = $0;
218                 $name =~ s/\.\///;
220                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
221                 print LOG_HANDLE $log_msg;
222                 if( $foreground ) { 
223                     print STDERR $log_msg;
224                 }
225             }
226         close( LOG_HANDLE );
227     }
228 #log into syslog
229 #    my ($msg, $level, $facility) = @_;
230 #    if(not defined $msg) {return}
231 #    if(not defined $level) {$level = "info"}
232 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
233 #    openlog($0, "pid,cons,", $facility);
234 #    syslog($level, $msg);
235 #    closelog;
236 #    return;
240 #===  FUNCTION  ================================================================
241 #         NAME:  check_cmdline_param
242 #   PARAMETERS:  nothing
243 #      RETURNS:  nothing
244 #  DESCRIPTION:  validates commandline parameter
245 #===============================================================================
246 sub check_cmdline_param () {
247     my $err_config;
248     my $err_counter = 0;
249     if( not defined( $cfg_file)) {
250         #$err_config = "please specify a config file";
251         #$err_counter += 1;
252         my $cwd = getcwd;
253         my $name = "/etc/gosa-si/server.conf";
254         $cfg_file = File::Spec->catfile( $cwd, $name );
255     }
256     if( $err_counter > 0 ) {
257         &usage( "", 1 );
258         if( defined( $err_config)) { print STDERR "$err_config\n"}
259         print STDERR "\n";
260         exit( -1 );
261     }
265 #===  FUNCTION  ================================================================
266 #         NAME:  check_pid
267 #   PARAMETERS:  nothing
268 #      RETURNS:  nothing
269 #  DESCRIPTION:  handels pid processing
270 #===============================================================================
271 sub check_pid {
272     $pid = -1;
273     # Check, if we are already running
274     if( open(LOCK_FILE, "<$pid_file") ) {
275         $pid = <LOCK_FILE>;
276         if( defined $pid ) {
277             chomp( $pid );
278             if( -f "/proc/$pid/stat" ) {
279                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
280                 if( $0 eq $stat ) {
281                     close( LOCK_FILE );
282                     exit -1;
283                 }
284             }
285         }
286         close( LOCK_FILE );
287         unlink( $pid_file );
288     }
290     # create a syslog msg if it is not to possible to open PID file
291     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
292         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
293         if (open(LOCK_FILE, '<', $pid_file)
294                 && ($pid = <LOCK_FILE>))
295         {
296             chomp($pid);
297             $msg .= "(PID $pid)\n";
298         } else {
299             $msg .= "(unable to read PID)\n";
300         }
301         if( ! ($foreground) ) {
302             openlog( $0, "cons,pid", "daemon" );
303             syslog( "warning", $msg );
304             closelog();
305         }
306         else {
307             print( STDERR " $msg " );
308         }
309         exit( -1 );
310     }
313 #===  FUNCTION  ================================================================
314 #         NAME:  import_modules
315 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
316 #                are stored
317 #      RETURNS:  nothing
318 #  DESCRIPTION:  each file in module_path which ends with '.pm' is imported by 
319 #                "require 'file';"
320 #===============================================================================
321 sub import_modules {
322     daemon_log(" ", 1);
324     if (not -e $modules_path) {
325         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
326     }
328     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
329     while (defined (my $file = readdir (DIR))) {
330         if (not $file =~ /(\S*?).pm$/) {
331             next;
332         }
333         eval { require $file; };
334         if ($@) {
335             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
336             daemon_log("$@", 5);
337         } else {
338             my $mod_name = $1;
339             my $info = eval($mod_name.'::get_module_info()');
340             my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
341             $known_modules->{$mod_name} = $info;
343             daemon_log("module $mod_name loaded", 1);
344         }
345     }   
347     # for debugging
348     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
349     #    print "\tmodule: $module"."\n";   
350     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
351     #}
352     close (DIR);
356 #===  FUNCTION  ================================================================
357 #         NAME:  sig_int_handler
358 #   PARAMETERS:  signal - string - signal arose from system
359 #      RETURNS:  noting
360 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
361 #===============================================================================
362 sub sig_int_handler {
363     my ($signal) = @_;
365     daemon_log("shutting down gosa-si-server", 1);
366     exit(1);
368 $SIG{INT} = \&sig_int_handler;
371 #===  FUNCTION  ================================================================
372 #         NAME:  activating_child
373 #   PARAMETERS:  msg - string - incoming message
374 #                host - string - host from which the incomming message comes
375 #      RETURNS:  nothing
376 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
377 #===============================================================================
378 sub activating_child {
379     my ($msg, $host, $client) = @_;
380     my $child = &get_processing_child();
381     my $pipe_wr = $$child{'pipe_wr'};
382     my $pipe_rd = $$child{'pipe_rd'};
383     $$child{client_ref} = $client;
384     
385     daemon_log("activating: childpid:$$child{'pid'}", 5);
387     print $pipe_wr $msg.".".$host."\n";
389     return;
393 #===  FUNCTION  ================================================================
394 #         NAME:  get_processing_child
395 #   PARAMETERS:  nothing
396 #      RETURNS:  child - hash - holding the process id and the references to the pipe
397 #                               handles pipe_wr and pipe_rd
398 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
399 #===============================================================================
400 sub get_processing_child {
401     my $child;
403     while(my ($key, $val) = each(%free_child)) {
404         my $exitus_pid = waitpid($key, WNOHANG);
405         if($exitus_pid != 0) {
406             delete $free_child{$key};
407         }
408         daemon_log("free child:$key", 5);
409     }
410     # check @free_child and @busy_child
411     my $free_len = scalar(keys(%free_child));
412     my $busy_len = scalar(keys(%busy_child));
413     daemon_log("free children $free_len, busy children $busy_len", 5);
415     # if there is a free child, let the child work
416     if($free_len > 0){
417         my @keys = keys(%free_child);
418         $child = $free_child{$keys[0]};
419         if(defined $child) {
420             $busy_child{$$child{'pid'}} = $child ;
421             delete $free_child{$$child{'pid'}};
422         }
423         return $child;
424     }
426     # no free child, try to fork another one
427     if($free_len + $busy_len < $child_max) {
429         daemon_log("not enough children, create a new one", 5);
431         # New pipes for communication
432         my( $PARENT_wr, $PARENT_rd );
433         my( $CHILD_wr, $CHILD_rd );
434         pipe( $CHILD_rd,  $PARENT_wr );
435         pipe( $PARENT_rd, $CHILD_wr  );
436         $PARENT_wr->autoflush(1);
437         $CHILD_wr->autoflush(1);
439         ############
440         # fork child
441         ############
442         my $child_pid = fork();
443         
444         #CHILD
445         if($child_pid == 0) {
446             # Close unused pipes
447             close( $CHILD_rd );
448             close( $CHILD_wr );
449             while( 1 ) {
450                 my $rbits = "";
451                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
452                 my $nf = select($rbits, undef, undef, $child_timeout);
453                 if($nf < 0 ) {
454                     die "select(): $!\n";
455                 } elsif (! $nf) {
456                     # if already child_min childs are alive, then leave loop
457                     $free_len = scalar(keys(%free_child));
458                     $busy_len = scalar(keys(%busy_child));
459                     if($free_len + $busy_len >= $child_min) {
460                         last;
461                     } else {
462                         redo;
463                     }
464                 }
466                 # a job for a child arise
467                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
468                     # read everything from pipe
469                     my $msg = "";
470                     $PARENT_rd->blocking(0);
471                     while(1) {
472                         my $read = <$PARENT_rd>;
473                         if(not defined $read) { last}
474                         $msg .= $read;
475                     }
477                     ######################################
478                     # forward msg to all imported modules 
479                     no strict "refs";
480                     my $answer;
481                     my %act_modules = %$known_modules;
482                     while( my ($module, $info) = each(%act_modules)) {
483                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
484                             if (defined $tmp) {
485                                 $answer = $tmp;
486                             }
487                     }        
488                     daemon_log("processing of msg finished", 5);
489  
490                    if (defined $answer) {
491                         print $PARENT_wr $answer."\n";
492                         print $PARENT_wr "ENDMESSAGE\n";
493                         my $len_answer = length $answer;
494                         daemon_log("with answer: length of answer: $len_answer", 7);
495                         daemon_log("\n$answer", 7);
496                     } else {
497                         print $PARENT_wr "done"."\n";
498                         print $PARENT_wr "ENDMESSAGE\n";
499                     }
500                     redo;
501                 }
502             }
503             # childs leaving the loop are allowed to die
504             exit(0);
507         #PARENT
508         } else {
509             # Close unused pipes
510             close( $PARENT_rd );
511             close( $PARENT_wr );
513             # add child to child alive hash
514             my %child_hash = (
515                     'pid' => $child_pid,
516                     'pipe_wr' => $CHILD_wr,
517                     'pipe_rd' => $CHILD_rd,
518                     'client_ref' => "",
519                     );
521             $child = \%child_hash;
522             $busy_child{$$child{'pid'}} = $child;
523             return $child;
524         }
525     }
529 #===  FUNCTION  ================================================================
530 #         NAME:  read_from_socket
531 #   PARAMETERS:  socket fh - 
532 #      RETURNS:  result string - readed characters from socket
533 #  DESCRIPTION:  reads data from socket in 16 byte steps
534 #===============================================================================
535 sub read_from_socket {
536     my ($socket) = @_;
537     my $result = "";
539     $socket->blocking(1);
540     $result = <$socket>;
542     $socket->blocking(0);
543     while ( my $char = <$socket> ) {
544         if (not defined $char) { last }
545         $result .= $char;
546     }
548     return $result;
552 #===  FUNCTION  ================================================================
553 #         NAME:  print_known_daemons
554 #   PARAMETERS:  nothing
555 #      RETURNS:  nothing
556 #  DESCRIPTION:  nomen est omen
557 #===============================================================================
558 #sub print_known_daemons {
559 #    my ($tmp) = @_ ;
560 #    print "####################################\n";
561 #    print "# status of known_daemons\n";
562 #    $shmda->shlock(LOCK_EX);
563 #    my @hosts = keys %$known_daemons;
564 #    foreach my $host (@hosts) {
565 #        my $status = $known_daemons->{$host}->{status} ;
566 #        my $passwd = $known_daemons->{$host}->{passwd};
567 #        my $timestamp = $known_daemons->{$host}->{timestamp};
568 #        print "$host\n";
569 #        print "\tstatus:    $status\n";
570 #        print "\tpasswd:    $passwd\n";
571 #        print "\ttimestamp: $timestamp\n";
572 #    }
573 #    $shmda->shunlock(LOCK_EX);
574 #    print "####################################\n";
575 #    return;
576 #}
579 #===  FUNCTION  ================================================================
580 #         NAME:  create_known_daemon
581 #   PARAMETERS:  hostname - string - key for the hash known_daemons
582 #      RETURNS:  nothing
583 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
584 #===============================================================================
585 #sub create_known_daemon {
586 #    my ($hostname) = @_;
587 #    $shmda->shlock(LOCK_EX);
588 #    $known_daemons->{$hostname} = {};
589 #    $known_daemons->{$hostname}->{status} = "none";
590 #    $known_daemons->{$hostname}->{passwd} = "none";
591 #    $known_daemons->{$hostname}->{timestamp} = "none";
592 #    $shmda->shunlock(LOCK_EX); 
593 #    return;  
594 #}
597 #===  FUNCTION  ================================================================
598 #         NAME:  add_content2known_daemons
599 #   PARAMETERS:  hostname - string - ip address and port of host (required)
600 #                status - string - (optional)
601 #                passwd - string - (optional)
602 #                mac_address - string - mac address of host (optional)
603 #      RETURNS:  nothing
604 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
605 #===============================================================================
606 #sub add_content2known_daemons {
607 #    my $arg = {
608 #        hostname => undef, status => undef, passwd => undef,
609 #        mac_address => undef, events => undef, 
610 #        @_ };
611 #    my $hostname = $arg->{hostname};
612 #    my $status = $arg->{status};
613 #    my $passwd = $arg->{passwd};
614 #    my $mac_address = $arg->{mac_address};
615 #    my $events = $arg->{events};
617 #    if (not defined $hostname) {
618 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
619 #        return;
620 #    }
622 #    my ($seconds, $minutes, $hours, $monthday, $month,
623 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
624 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
625 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
626 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
627 #    $month+=1;
628 #    $month = $month < 10 ? $month = "0".$month : $month;
629 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
630 #    $year+=1900;
631 #    my $t = "$year$month$monthday$hours$minutes$seconds";
632 #    
633 #    $shmda->shlock(LOCK_EX);
634 #    if (defined $status) {
635 #        $known_daemons->{$hostname}->{status} = $status;
636 #    }
637 #    if (defined $passwd) {
638 #        $known_daemons->{$hostname}->{passwd} = $passwd;
639 #    }
640 #    if (defined $mac_address) {
641 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
642 #    }
643 #    if (defined $events) {
644 #        $known_daemons->{$hostname}->{events} = $events;
645 #    }
646 #    $known_daemons->{$hostname}->{timestamp} = $t;
647 #    $shmda->shlock(LOCK_EX);
648 #    return;
649 #}
652 #===  FUNCTION  ================================================================
653 #         NAME:  update_known_daemons
654 #   PARAMETERS:  hostname - string - ip address and port of host (required)
655 #                status - string - (optional)
656 #                passwd - string - (optional)
657 #                client - string - ip address and port of client (optional)
658 #      RETURNS:  nothing
659 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
660 #===============================================================================
661 #sub update_known_daemons {
662 #    my $arg = {
663 #        hostname => undef, status => undef, passwd => undef,
664 #        @_ };
665 #    my $hostname = $arg->{hostname};
666 #    my $status = $arg->{status};
667 #    my $passwd = $arg->{passwd};
669 #    if (not defined $hostname) {
670 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
671 #        return;
672 #    }
674 #    my ($seconds, $minutes, $hours, $monthday, $month,
675 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
676 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
677 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
678 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
679 #    $month+=1;
680 #    $month = $month < 10 ? $month = "0".$month : $month;
681 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
682 #    $year+=1900;
683 #    my $t = "$year$month$monthday$hours$minutes$seconds";
685 #    $shmda->shlock(LOCK_EX);
686 #    if (defined $status) {
687 #        $known_daemons->{$hostname}->{status} = $status;
688 #    }
689 #    if (defined $passwd) {
690 #        $known_daemons->{$hostname}->{passwd} = $passwd;
691 #    }
692 #    $known_daemons->{$hostname}->{timestamp} = $t;
693 #    $shmda->shunlock(LOCK_EX);
694 #    return;
695 #}
698 #===  FUNCTION  ================================================================
699 #         NAME:  print_known_clients 
700 #   PARAMETERS:  nothing
701 #      RETURNS:  nothing
702 #  DESCRIPTION:  nomen est omen
703 #===============================================================================
704 #sub print_known_clients {
706 #    print "####################################\n";
707 #    print "# status of known_clients\n";
708 #    $shmcl->shlock(LOCK_EX);
709 #    my @hosts = keys %$known_clients;
710 #    if (@hosts) {
711 #        foreach my $host (@hosts) {
712 #            my $status = $known_clients->{$host}->{status} ;
713 #            my $passwd = $known_clients->{$host}->{passwd};
714 #            my $timestamp = $known_clients->{$host}->{timestamp};
715 #            my $mac_address = $known_clients->{$host}->{mac_address};
716 #            my $events = $known_clients->{$host}->{events};
717 #            print "$host\n";
718 #            print "\tstatus:      $status\n";
719 #            print "\tpasswd:      $passwd\n";
720 #            print "\ttimestamp:   $timestamp\n";
721 #            print "\tmac_address: $mac_address\n";
722 #            print "\tevents:      $events\n";
723 #        }
724 #    }
725 #    $shmcl->shunlock(LOCK_EX);
726 #    print "####################################\n";
727 #    return;
728 #}
731 #===  FUNCTION  ================================================================
732 #         NAME:  create_known_client
733 #   PARAMETERS:  hostname - string - key for the hash known_clients
734 #      RETURNS:  nothing
735 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
736 #===============================================================================
737 sub create_known_client {
738     my ($hostname) = @_;
740     my $entry = { table=>'known_clients',
741         hostname=>$hostname,
742         status=>'none',
743         hostkey=>'none',
744         timestamp=>'none',
745         macaddress=>'none',
746         events=>'none',
747     };
748     my $res = $known_clients_db->add_dbentry($entry);
749     if ($res > 0) {
750         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
751     }
753     return;  
756 #sub sysreadline(*;$) {
757 #    my ($hd, $timeout) = @_;
759 #    $hd = qualify_to_ref($hd, caller());
760 #    my $infinitely_patient = (@_ == 1 || $timeout < 0);
761 #    my $start_time = time();
762 #    my $selector = IO::Select->new();
763 #    $selector->add($hd);
764 #    my $line = "";
766 #SLEEP: 
767 #    until( at_eol($line)) {
768 #        if (not $infinitely_patient) {
769 #            return $line if time() > ($start_time + $timeout);
770 #        }
771 #        next SLEEP unless $selector->can_read(1.0);
772 #INPUT_READY:
773 #        while( $selector->can_read(0.0)) {
774 #            my $was_blocking = $hd->blocking(0);
775 #CHAR:       while (sysread($hd, my $nextbyte, 1)) {
776 #                $line .= $nextbyte;  
777 #                last CHAR if $nextbyte eq "\n";
779 #            }
780 #            $hd->blocking($was_blocking);
781 #            next SLEEP unless at_eol($line);
782 #            last INPUT_READY;
783 #        }
784 #    }
785 #    return $line;
786 #}
788 #sub at_eol($) {
789 #    $_[0] =~ /\n\z/ ;
790 #}
792 #==== MAIN = main ==============================================================
794 #  parse commandline options
795 Getopt::Long::Configure( "bundling" );
796 GetOptions("h|help" => \&usage,
797         "c|config=s" => \$cfg_file,
798         "f|foreground" => \$foreground,
799         "v|verbose+" => \$verbose,
800         "no-bus+" => \$no_bus,
801         "no-arp+" => \$no_arp,
802            );
804 #  read and set config parameters
805 &check_cmdline_param ;
806 &read_configfile;
807 &check_pid;
809 $SIG{CHLD} = 'IGNORE';
811 # forward error messages to logfile
812 if( ! $foreground ) {
813     open(STDERR, '>>', $log_file);
814     open(STDOUT, '>>', $log_file);
817 # Just fork, if we are not in foreground mode
818 if( ! $foreground ) { 
819     chdir '/'                 or die "Can't chdir to /: $!";
820     $pid = fork;
821     setsid                    or die "Can't start a new session: $!";
822     umask 0;
823 } else { 
824     $pid = $$; 
827 # Do something useful - put our PID into the pid_file
828 if( 0 != $pid ) {
829     open( LOCK_FILE, ">$pid_file" );
830     print LOCK_FILE "$pid\n";
831     close( LOCK_FILE );
832     if( !$foreground ) { 
833         exit( 0 ) 
834     };
837 daemon_log(" ", 1);
838 daemon_log("$0 started!", 1);
840 # delete old DBsqlite lock files
841 system('rm -f /tmp/gosa_si_lock*');
843 # connect to gosa-si job queue
844 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
845 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
846 $job_db->create_table('jobs', \@job_col_names);
848 # connect to known_clients_db
849 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
850 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
851 $known_clients_db->create_table('known_clients', \@clients_col_names);
853 # connect to known_server_db
854 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
855 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
856 $known_server_db->create_table('known_server', \@server_col_names);
858 # import all modules
859 &import_modules;
861 # check wether all modules are gosa-si valid passwd check
863 # create reading and writing vectors
864 my $rbits = my $wbits = my $ebits = "";
866 # add all module inputs to listening vector
867 while( my ($mod_name, $info) = each %$known_modules ) {
868     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
869     vec($rbits, fileno $input, 1) = 1;   
874 ## start arp fifo
875 #if ($no_arp > 0) {
876 #    $arp_activ = "off";
877 #}
878 #my $my_fifo;
879 #if($arp_activ eq "on") {
880 #    daemon_log(" ", 1);
881 #    $my_fifo = &open_fifo($arp_fifo_path);
882 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
883 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
884 #    
885 #    vec($rbits, fileno $arp_fifo, 1) = 1;
886 #}
889 ##################################
890 #everything ready, okay, lets start
891 ##################################
892 while(1) {
894     # add all handles from the childs
895     while ( my ($pid, $child_hash) = each %busy_child ) {
896         
897         # check whether process still exists
898         my $exitus_pid = waitpid($pid, WNOHANG);
899         if($exitus_pid != 0) {
900             delete $busy_child{$pid};
901             next;
902         }
903      
904         # add child fhd to the listener    
905         my $fhd = $$child_hash{'pipe_rd'};
906         vec($rbits, fileno $fhd, 1) = 1;
907     }
909     my ($rout, $wout);
910     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
912     # error handling
913     if($nf < 0 ) {
914     }
917 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
918 #        my $in_msg = <$arp_fifo>;
919 #        chomp($in_msg);
920 #        print "arp_activ: msg: $in_msg\n";
921 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
922 #        print "arp_activ: arp_passwd: $act_passwd\n";
924 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
926 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
928 #        if ($target eq $server_address) { 
929 #             print "arp_activ: forward to server\n";
930 #            my $arp_cipher = &create_ciphering($act_passwd);
931 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
932 #            &activating_child($crypted_msg, $server_ip);
933 #        } else {
934 #            print "arp_activ: send to bus\n";
935 #            &send_msg_hash2address($in_msg_hash, $bus_address);
936 #        }
937 #        print "\n";
938 #    }
941     # check input fhd of all modules 
942     while ( my ($mod_name, $info) = each %$known_modules) {
943         my $input_fhd = @{$info}[2];    
944         my $input_activ = @{$info}[3];
945         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
946             daemon_log(" ", 1);
947             my $client = $input_fhd->accept();
948             my $other_end = getpeername($client);
949             if(not defined $other_end) {
950                 daemon_log("client cannot be identified: $!");
951             } else {
952                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
953                 my $actual_ip = inet_ntoa($iaddr);
954                 daemon_log("accept client at daemon socket from $actual_ip", 5);
955                 my $in_msg = &read_from_socket($client);
956                 if(defined $in_msg){
957                     chomp($in_msg);
958                     &activating_child($in_msg, $actual_ip, $client);
959                 } else {
960                     daemon_log("cannot read from $actual_ip", 5);
961                 }
962             }
963         }
964     }
966     # check all processing childs whether they are finished ('done') or 
967     while ( my ($pid, $child_hash) = each %busy_child ) {
968         my $fhd = $$child_hash{'pipe_rd'};
970         if (vec($rout, fileno $fhd, 1) ) {
971             daemon_log("process child $pid is ready to read", 5);
972  
973             my $in_msg;
974             while (1) {
975                 my $part_in_msg = <$fhd>;
976                 if( $part_in_msg eq "ENDMESSAGE\n") {
977                     last;
978                 }
979                 $in_msg .= $part_in_msg;
980             }
981             chomp($in_msg);
982             
983             if (not defined $in_msg) { 
984                 next; 
985             } elsif ($in_msg =~ "done") {
986                 daemon_log("process child read: $in_msg", 7);
987                 delete $busy_child{$pid};
988                 $free_child{$pid} = $child_hash;
990             } else {
991                 daemon_log("process child read:", 7);
992                 daemon_log("\n$in_msg", 8);
993                 # send computed answer back to connected client
994                 my $act_client = $busy_child{$pid}{client_ref};
995                 print $act_client $in_msg."\n";
996                 delete $busy_child{$pid};
997                 $free_child{$pid} = $child_hash;
999             }
1000         }
1001     }
1003     # check gosa job queue for jobs with executable timestamp
1004     my ($seconds, $minutes, $hours, $monthday, $month,
1005     $year, $weekday, $yearday, $sommertime) = localtime(time);
1006     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1007     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1008     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1009     $month+=1;
1010     $month = $month < 10 ? $month = "0".$month : $month;
1011     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1012     $year+=1900;
1013     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1014     
1015     
1016     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1018     while( my ($id, $hit) = each %{$res} ) {         
1020         my $jobdb_id = $hit->{id};
1021         my $macaddress = $hit->{macaddress};
1022         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1023         my $out_msg_hash = $job_msg_hash;
1024         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1025         # expect macaddress is unique!!!!!!
1026         my $target = $res_hash->{1}->{hostname};
1027         
1028         if (not defined $target) {
1029             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1030             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1031             my $update_hash = { table=>$job_queue_table_name,
1032                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1033                 where=> [ { id=>[$jobdb_id] } ],
1034             };
1035             my $res = $job_db->update_dbentry($update_hash);
1037             next;
1038         }
1040         # add target
1041         &add_content2xml_hash($out_msg_hash, "target", $target);
1043         # add new header
1044         my $out_header = $job_msg_hash->{header}[0];
1045         $out_header =~ s/job_/gosa_/;
1046         delete $out_msg_hash->{header};
1047         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1048         
1049         # add sqlite_id 
1050         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1051     
1052         my $out_msg = &create_xml_string($out_msg_hash);
1054         # encrypt msg as a GosaPackage module
1055         my $cipher = &create_ciphering($gosa_passwd);
1056         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1058         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1060         if ($error == 0) {
1061             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE id='$jobdb_id'";
1062             my $res = $job_db->exec_statement($sql);
1063         } else {
1064             my $update_hash = { table=>$job_queue_table_name, 
1065                                 update=> [ { status=>'error' } ],
1066                                 where=> [ { id=>$jobdb_id } ],
1067                               };
1068             my $res = $job_db->update_dbentry($update_hash);
1069         }
1071     }