Code

server working atm
[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                     }        
489                     #&print_known_daemons();
490                     #&print_known_clients();
492                     daemon_log("processing of msg finished", 5);
493  
494                    if (defined $answer) {
495                         print $PARENT_wr $answer."\n";
496                         print $PARENT_wr "ENDMESSAGE\n";
497                         my $len_answer = length $answer;
498                         daemon_log("with answer: length of answer: $len_answer", 7);
499                         daemon_log("\n$answer", 7);
500                     } else {
501                         print $PARENT_wr "done"."\n";
502                         daemon_log(" ", 7);
503                     }
504                     redo;
505                 }
506             }
507             # childs leaving the loop are allowed to die
508             exit(0);
511         #PARENT
512         } else {
513             # Close unused pipes
514             close( $PARENT_rd );
515             close( $PARENT_wr );
517             # add child to child alive hash
518             my %child_hash = (
519                     'pid' => $child_pid,
520                     'pipe_wr' => $CHILD_wr,
521                     'pipe_rd' => $CHILD_rd,
522                     'client_ref' => "",
523                     );
525             $child = \%child_hash;
526             $busy_child{$$child{'pid'}} = $child;
527             return $child;
528         }
529     }
533 #===  FUNCTION  ================================================================
534 #         NAME:  read_from_socket
535 #   PARAMETERS:  socket fh - 
536 #      RETURNS:  result string - readed characters from socket
537 #  DESCRIPTION:  reads data from socket in 16 byte steps
538 #===============================================================================
539 sub read_from_socket {
540     my ($socket) = @_;
541     my $result = "";
543     $socket->blocking(1);
544     $result = <$socket>;
546     $socket->blocking(0);
547     while ( my $char = <$socket> ) {
548         if (not defined $char) { last }
549         $result .= $char;
550     }
552     return $result;
556 #===  FUNCTION  ================================================================
557 #         NAME:  print_known_daemons
558 #   PARAMETERS:  nothing
559 #      RETURNS:  nothing
560 #  DESCRIPTION:  nomen est omen
561 #===============================================================================
562 #sub print_known_daemons {
563 #    my ($tmp) = @_ ;
564 #    print "####################################\n";
565 #    print "# status of known_daemons\n";
566 #    $shmda->shlock(LOCK_EX);
567 #    my @hosts = keys %$known_daemons;
568 #    foreach my $host (@hosts) {
569 #        my $status = $known_daemons->{$host}->{status} ;
570 #        my $passwd = $known_daemons->{$host}->{passwd};
571 #        my $timestamp = $known_daemons->{$host}->{timestamp};
572 #        print "$host\n";
573 #        print "\tstatus:    $status\n";
574 #        print "\tpasswd:    $passwd\n";
575 #        print "\ttimestamp: $timestamp\n";
576 #    }
577 #    $shmda->shunlock(LOCK_EX);
578 #    print "####################################\n";
579 #    return;
580 #}
583 #===  FUNCTION  ================================================================
584 #         NAME:  create_known_daemon
585 #   PARAMETERS:  hostname - string - key for the hash known_daemons
586 #      RETURNS:  nothing
587 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
588 #===============================================================================
589 #sub create_known_daemon {
590 #    my ($hostname) = @_;
591 #    $shmda->shlock(LOCK_EX);
592 #    $known_daemons->{$hostname} = {};
593 #    $known_daemons->{$hostname}->{status} = "none";
594 #    $known_daemons->{$hostname}->{passwd} = "none";
595 #    $known_daemons->{$hostname}->{timestamp} = "none";
596 #    $shmda->shunlock(LOCK_EX); 
597 #    return;  
598 #}
601 #===  FUNCTION  ================================================================
602 #         NAME:  add_content2known_daemons
603 #   PARAMETERS:  hostname - string - ip address and port of host (required)
604 #                status - string - (optional)
605 #                passwd - string - (optional)
606 #                mac_address - string - mac address of host (optional)
607 #      RETURNS:  nothing
608 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
609 #===============================================================================
610 #sub add_content2known_daemons {
611 #    my $arg = {
612 #        hostname => undef, status => undef, passwd => undef,
613 #        mac_address => undef, events => undef, 
614 #        @_ };
615 #    my $hostname = $arg->{hostname};
616 #    my $status = $arg->{status};
617 #    my $passwd = $arg->{passwd};
618 #    my $mac_address = $arg->{mac_address};
619 #    my $events = $arg->{events};
621 #    if (not defined $hostname) {
622 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
623 #        return;
624 #    }
626 #    my ($seconds, $minutes, $hours, $monthday, $month,
627 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
628 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
629 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
630 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
631 #    $month+=1;
632 #    $month = $month < 10 ? $month = "0".$month : $month;
633 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
634 #    $year+=1900;
635 #    my $t = "$year$month$monthday$hours$minutes$seconds";
636 #    
637 #    $shmda->shlock(LOCK_EX);
638 #    if (defined $status) {
639 #        $known_daemons->{$hostname}->{status} = $status;
640 #    }
641 #    if (defined $passwd) {
642 #        $known_daemons->{$hostname}->{passwd} = $passwd;
643 #    }
644 #    if (defined $mac_address) {
645 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
646 #    }
647 #    if (defined $events) {
648 #        $known_daemons->{$hostname}->{events} = $events;
649 #    }
650 #    $known_daemons->{$hostname}->{timestamp} = $t;
651 #    $shmda->shlock(LOCK_EX);
652 #    return;
653 #}
656 #===  FUNCTION  ================================================================
657 #         NAME:  update_known_daemons
658 #   PARAMETERS:  hostname - string - ip address and port of host (required)
659 #                status - string - (optional)
660 #                passwd - string - (optional)
661 #                client - string - ip address and port of client (optional)
662 #      RETURNS:  nothing
663 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
664 #===============================================================================
665 #sub update_known_daemons {
666 #    my $arg = {
667 #        hostname => undef, status => undef, passwd => undef,
668 #        @_ };
669 #    my $hostname = $arg->{hostname};
670 #    my $status = $arg->{status};
671 #    my $passwd = $arg->{passwd};
673 #    if (not defined $hostname) {
674 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
675 #        return;
676 #    }
678 #    my ($seconds, $minutes, $hours, $monthday, $month,
679 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
680 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
681 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
682 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
683 #    $month+=1;
684 #    $month = $month < 10 ? $month = "0".$month : $month;
685 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
686 #    $year+=1900;
687 #    my $t = "$year$month$monthday$hours$minutes$seconds";
689 #    $shmda->shlock(LOCK_EX);
690 #    if (defined $status) {
691 #        $known_daemons->{$hostname}->{status} = $status;
692 #    }
693 #    if (defined $passwd) {
694 #        $known_daemons->{$hostname}->{passwd} = $passwd;
695 #    }
696 #    $known_daemons->{$hostname}->{timestamp} = $t;
697 #    $shmda->shunlock(LOCK_EX);
698 #    return;
699 #}
702 #===  FUNCTION  ================================================================
703 #         NAME:  print_known_clients 
704 #   PARAMETERS:  nothing
705 #      RETURNS:  nothing
706 #  DESCRIPTION:  nomen est omen
707 #===============================================================================
708 #sub print_known_clients {
710 #    print "####################################\n";
711 #    print "# status of known_clients\n";
712 #    $shmcl->shlock(LOCK_EX);
713 #    my @hosts = keys %$known_clients;
714 #    if (@hosts) {
715 #        foreach my $host (@hosts) {
716 #            my $status = $known_clients->{$host}->{status} ;
717 #            my $passwd = $known_clients->{$host}->{passwd};
718 #            my $timestamp = $known_clients->{$host}->{timestamp};
719 #            my $mac_address = $known_clients->{$host}->{mac_address};
720 #            my $events = $known_clients->{$host}->{events};
721 #            print "$host\n";
722 #            print "\tstatus:      $status\n";
723 #            print "\tpasswd:      $passwd\n";
724 #            print "\ttimestamp:   $timestamp\n";
725 #            print "\tmac_address: $mac_address\n";
726 #            print "\tevents:      $events\n";
727 #        }
728 #    }
729 #    $shmcl->shunlock(LOCK_EX);
730 #    print "####################################\n";
731 #    return;
732 #}
735 #===  FUNCTION  ================================================================
736 #         NAME:  create_known_client
737 #   PARAMETERS:  hostname - string - key for the hash known_clients
738 #      RETURNS:  nothing
739 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
740 #===============================================================================
741 sub create_known_client {
742     my ($hostname) = @_;
744     my $entry = { table=>'known_clients',
745         hostname=>$hostname,
746         status=>'none',
747         hostkey=>'none',
748         timestamp=>'none',
749         macaddress=>'none',
750         events=>'none',
751     };
752     my $res = $known_clients_db->add_dbentry($entry);
753     if ($res > 0) {
754         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
755     }
757     return;  
760 sub sysreadline(*;$) {
761     my ($hd, $timeout) = @_;
763     $hd = qualify_to_ref($hd, caller());
764     my $infinitely_patient = (@_ == 1 || $timeout < 0);
765     my $start_time = time();
766     my $selector = IO::Select->new();
767     $selector->add($hd);
768     my $line = "";
770 SLEEP: 
771     until( at_eol($line)) {
772         if (not $infinitely_patient) {
773             return $line if time() > ($start_time + $timeout);
774         }
775         next SLEEP unless $selector->can_read(1.0);
776 INPUT_READY:
777         while( $selector->can_read(0.0)) {
778             my $was_blocking = $hd->blocking(0);
779 CHAR:       while (sysread($hd, my $nextbyte, 1)) {
780                 $line .= $nextbyte;  
781                 last CHAR if $nextbyte eq "\n";
783             }
784             $hd->blocking($was_blocking);
785             next SLEEP unless at_eol($line);
786             last INPUT_READY;
787         }
788     }
789     return $line;
792 sub at_eol($) {
793     $_[0] =~ /\n\z/ ;
796 #==== MAIN = main ==============================================================
798 #  parse commandline options
799 Getopt::Long::Configure( "bundling" );
800 GetOptions("h|help" => \&usage,
801         "c|config=s" => \$cfg_file,
802         "f|foreground" => \$foreground,
803         "v|verbose+" => \$verbose,
804         "no-bus+" => \$no_bus,
805         "no-arp+" => \$no_arp,
806            );
808 #  read and set config parameters
809 &check_cmdline_param ;
810 &read_configfile;
811 &check_pid;
813 $SIG{CHLD} = 'IGNORE';
815 # forward error messages to logfile
816 if( ! $foreground ) {
817     open(STDERR, '>>', $log_file);
818     open(STDOUT, '>>', $log_file);
821 # Just fork, if we are not in foreground mode
822 if( ! $foreground ) { 
823     chdir '/'                 or die "Can't chdir to /: $!";
824     $pid = fork;
825     setsid                    or die "Can't start a new session: $!";
826     umask 0;
827 } else { 
828     $pid = $$; 
831 # Do something useful - put our PID into the pid_file
832 if( 0 != $pid ) {
833     open( LOCK_FILE, ">$pid_file" );
834     print LOCK_FILE "$pid\n";
835     close( LOCK_FILE );
836     if( !$foreground ) { 
837         exit( 0 ) 
838     };
841 daemon_log(" ", 1);
842 daemon_log("$0 started!", 1);
845 # connect to gosa-si job queue
846 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
847 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
848 $job_db->create_table('jobs', \@job_col_names);
850 # connect to known_clients_db
851 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
852 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
853 $known_clients_db->create_table('known_clients', \@clients_col_names);
855 # connect to known_server_db
856 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
857 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
858 $known_server_db->create_table('known_server', \@server_col_names);
860 # import all modules
861 &import_modules;
863 # check wether all modules are gosa-si valid passwd check
865 # create reading and writing vectors
866 my $rbits = my $wbits = my $ebits = "";
868 # add all module inputs to listening vector
869 while( my ($mod_name, $info) = each %$known_modules ) {
870     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
871     vec($rbits, fileno $input, 1) = 1;   
876 ## start arp fifo
877 #if ($no_arp > 0) {
878 #    $arp_activ = "off";
879 #}
880 #my $my_fifo;
881 #if($arp_activ eq "on") {
882 #    daemon_log(" ", 1);
883 #    $my_fifo = &open_fifo($arp_fifo_path);
884 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
885 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
886 #    
887 #    vec($rbits, fileno $arp_fifo, 1) = 1;
888 #}
891 ##################################
892 #everything ready, okay, lets start
893 ##################################
894 while(1) {
896     # add all handles from the childs
897     while ( my ($pid, $child_hash) = each %busy_child ) {
898         
899         # check whether process still exists
900         my $exitus_pid = waitpid($pid, WNOHANG);
901         if($exitus_pid != 0) {
902             delete $busy_child{$pid};
903             next;
904         }
905      
906         # add child fhd to the listener    
907         my $fhd = $$child_hash{'pipe_rd'};
908         vec($rbits, fileno $fhd, 1) = 1;
909     }
911     my ($rout, $wout);
912     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
914     # error handling
915     if($nf < 0 ) {
916     }
919 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
920 #        my $in_msg = <$arp_fifo>;
921 #        chomp($in_msg);
922 #        print "arp_activ: msg: $in_msg\n";
923 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
924 #        print "arp_activ: arp_passwd: $act_passwd\n";
926 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
928 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
930 #        if ($target eq $server_address) { 
931 #             print "arp_activ: forward to server\n";
932 #            my $arp_cipher = &create_ciphering($act_passwd);
933 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
934 #            &activating_child($crypted_msg, $server_ip);
935 #        } else {
936 #            print "arp_activ: send to bus\n";
937 #            &send_msg_hash2address($in_msg_hash, $bus_address);
938 #        }
939 #        print "\n";
940 #    }
943     # check input fhd of all modules 
944     while ( my ($mod_name, $info) = each %$known_modules) {
945         my $input_fhd = @{$info}[2];    
946         my $input_activ = @{$info}[3];
947         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
948             daemon_log(" ", 1);
949             my $client = $input_fhd->accept();
950             my $other_end = getpeername($client);
951             if(not defined $other_end) {
952                 daemon_log("client cannot be identified: $!");
953             } else {
954                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
955                 my $actual_ip = inet_ntoa($iaddr);
956                 daemon_log("accept client at daemon socket from $actual_ip", 5);
957                 my $in_msg = &read_from_socket($client);
958                 if(defined $in_msg){
959                     chomp($in_msg);
960                     &activating_child($in_msg, $actual_ip, $client);
961                 } else {
962                     daemon_log("cannot read from $actual_ip", 5);
963                 }
964             }
965         }
966     }
968     # check all processing childs whether they are finished ('done') or 
969     while ( my ($pid, $child_hash) = each %busy_child ) {
970         my $fhd = $$child_hash{'pipe_rd'};
972         if (vec($rout, fileno $fhd, 1) ) {
973             daemon_log("process child $pid is ready to read", 5);
974  
975             my $in_msg;
976             while (1) {
977                 my $part_in_msg = <$fhd>;
978                 if( $part_in_msg eq "ENDMESSAGE\n") {
979                     last;
980                 }
981                 $in_msg .= $part_in_msg;
982             }
983             chomp($in_msg);
984             
985             daemon_log("process child read:", 7);
986             daemon_log("\n$in_msg", 7);
987             if (not defined $in_msg) { 
988                 next; 
989             } elsif ($in_msg =~ "done") {
990                 delete $busy_child{$pid};
991                 $free_child{$pid} = $child_hash;
993             } else {
994                 # send computed answer back to connected client
995                 my $act_client = $busy_child{$pid}{client_ref};
996                 print $act_client $in_msg."\n";
998                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
999                 delete $busy_child{$pid};
1000                 $free_child{$pid} = $child_hash;
1002                 # give the client a chance to read 
1003                 #sleep(1);
1004                 #close ($act_client);   
1006             }
1007         }
1008     }
1010     # check gosa job queue for jobs with executable timestamp
1011     my ($seconds, $minutes, $hours, $monthday, $month,
1012     $year, $weekday, $yearday, $sommertime) = localtime(time);
1013     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1014     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1015     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1016     $month+=1;
1017     $month = $month < 10 ? $month = "0".$month : $month;
1018     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1019     $year+=1900;
1020     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1021     
1022     
1023     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1025     while( my ($id, $hit) = each %{$res} ) {         
1027         my $jobdb_id = $hit->{ROWID};
1028         my $macaddress = $hit->{macaddress};
1029         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1030         my $out_msg_hash = $job_msg_hash;
1031         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1032         # expect macaddress is unique!!!!!!
1033         my $target = $res_hash->{1}->{hostname};
1034         
1035         if (not defined $target) {
1036             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1037             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1038             my $update_hash = { table=>$job_queue_table_name,
1039                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1040                 where=> [ { ROWID=>[$jobdb_id] } ],
1041             };
1042             my $res = $job_db->update_dbentry($update_hash);
1044             next;
1045         }
1047         # add target
1048         &add_content2xml_hash($out_msg_hash, "target", $target);
1050         # add new header
1051         my $out_header = $job_msg_hash->{header}[0];
1052         $out_header =~ s/job_/gosa_/;
1053         delete $out_msg_hash->{header};
1054         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1055         
1056         # add sqlite_id 
1057         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1058     
1059         my $out_msg = &create_xml_string($out_msg_hash);
1061         # encrypt msg as a GosaPackage module
1062         my $cipher = &create_ciphering($gosa_passwd);
1063         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1065         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1067 #######################
1068 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1070         if ($error == 0) {
1071             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1072             my $res = $job_db->exec_statement($sql);
1073         } else {
1074             my $update_hash = { table=>$job_queue_table_name, 
1075                                 update=> [ { status=>'error' } ],
1076                                 where=> [ { ROWID=>$jobdb_id } ],
1077                               };
1078             my $res = $job_db->update_dbentry($update_hash);
1079         }
1081     }