Code

dfec2b882ef7a11752e3aeef476375b2d6858cac
[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, ""],
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, ""],
133     "gosa_port" => [\$gosa_port, "20082"],
134     "gosa_passwd" => [\$gosa_passwd, "none"],
135     },
136     );
139 #===  FUNCTION  ================================================================
140 #         NAME:  usage
141 #   PARAMETERS:  nothing
142 #      RETURNS:  nothing
143 #  DESCRIPTION:  print out usage text to STDERR
144 #===============================================================================
145 sub usage {
146     print STDERR << "EOF" ;
147 usage: $0 [-hvf] [-c config]
149            -h        : this (help) message
150            -c <file> : config file
151            -f        : foreground, process will not be forked to background
152            -v        : be verbose (multiple to increase verbosity)
153            -no-bus   : starts $0 without connection to bus
154            -no-arp   : starts $0 without connection to arp module
155  
156 EOF
157     print "\n" ;
161 #===  FUNCTION  ================================================================
162 #         NAME:  read_configfile
163 #   PARAMETERS:  cfg_file - string -
164 #      RETURNS:  nothing
165 #  DESCRIPTION:  read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168     my $cfg;
169     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
170         if( -r $cfg_file ) {
171             $cfg = Config::IniFiles->new( -file => $cfg_file );
172         } else {
173             print STDERR "Couldn't read config file!";
174         }
175     } else {
176         $cfg = Config::IniFiles->new() ;
177     }
178     foreach my $section (keys %cfg_defaults) {
179         foreach my $param (keys %{$cfg_defaults{ $section }}) {
180             my $pinfo = $cfg_defaults{ $section }{ $param };
181             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
182         }
183     }
187 #===  FUNCTION  ================================================================
188 #         NAME:  logging
189 #   PARAMETERS:  level - string - default 'info'
190 #                msg - string -
191 #                facility - string - default 'LOG_DAEMON'
192 #      RETURNS:  nothing
193 #  DESCRIPTION:  function for logging
194 #===============================================================================
195 sub daemon_log {
196     # log into log_file
197     my( $msg, $level ) = @_;
198     if(not defined $msg) { return }
199     if(not defined $level) { $level = 1 }
200     if(defined $log_file){
201         open(LOG_HANDLE, ">>$log_file");
202         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
203             print STDERR "cannot open $log_file: $!";
204             return }
205             chomp($msg);
206             if($level <= $verbose){
207                 print LOG_HANDLE "$level $msg\n";
208                 if($foreground) { print $msg."\n" }
209             }
210     }
211 #    close( LOG_HANDLE );
212 #log into syslog
213 #    my ($msg, $level, $facility) = @_;
214 #    if(not defined $msg) {return}
215 #    if(not defined $level) {$level = "info"}
216 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
217 #    openlog($0, "pid,cons,", $facility);
218 #    syslog($level, $msg);
219 #    closelog;
220 #    return;
224 #===  FUNCTION  ================================================================
225 #         NAME:  check_cmdline_param
226 #   PARAMETERS:  nothing
227 #      RETURNS:  nothing
228 #  DESCRIPTION:  validates commandline parameter
229 #===============================================================================
230 sub check_cmdline_param () {
231     my $err_config;
232     my $err_counter = 0;
233     if( not defined( $cfg_file)) {
234         #$err_config = "please specify a config file";
235         #$err_counter += 1;
236         my $cwd = getcwd;
237         my $name = "/etc/gosa-si/server.conf";
238         $cfg_file = File::Spec->catfile( $cwd, $name );
239     }
240     if( $err_counter > 0 ) {
241         &usage( "", 1 );
242         if( defined( $err_config)) { print STDERR "$err_config\n"}
243         print STDERR "\n";
244         exit( -1 );
245     }
249 #===  FUNCTION  ================================================================
250 #         NAME:  check_pid
251 #   PARAMETERS:  nothing
252 #      RETURNS:  nothing
253 #  DESCRIPTION:  handels pid processing
254 #===============================================================================
255 sub check_pid {
256     $pid = -1;
257     # Check, if we are already running
258     if( open(LOCK_FILE, "<$pid_file") ) {
259         $pid = <LOCK_FILE>;
260         if( defined $pid ) {
261             chomp( $pid );
262             if( -f "/proc/$pid/stat" ) {
263                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
264                 if( $0 eq $stat ) {
265                     close( LOCK_FILE );
266                     exit -1;
267                 }
268             }
269         }
270         close( LOCK_FILE );
271         unlink( $pid_file );
272     }
274     # create a syslog msg if it is not to possible to open PID file
275     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
276         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
277         if (open(LOCK_FILE, '<', $pid_file)
278                 && ($pid = <LOCK_FILE>))
279         {
280             chomp($pid);
281             $msg .= "(PID $pid)\n";
282         } else {
283             $msg .= "(unable to read PID)\n";
284         }
285         if( ! ($foreground) ) {
286             openlog( $0, "cons,pid", "daemon" );
287             syslog( "warning", $msg );
288             closelog();
289         }
290         else {
291             print( STDERR " $msg " );
292         }
293         exit( -1 );
294     }
297 #===  FUNCTION  ================================================================
298 #         NAME:  import_modules
299 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
300 #                are stored
301 #      RETURNS:  nothing
302 #  DESCRIPTION:  each file in module_path which ends with '.pm' is imported by 
303 #                "require 'file';"
304 #===============================================================================
305 sub import_modules {
306     daemon_log(" ", 1);
308     if (not -e $modules_path) {
309         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
310     }
312     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
313     while (defined (my $file = readdir (DIR))) {
314         if (not $file =~ /(\S*?).pm$/) {
315             next;
316         }
317         eval { require $file; };
318         if ($@) {
319             daemon_log("ERROR: gosa-sd could not load module $file", 1);
320             daemon_log("$@", 5);
321             next;
322         }
323         my $mod_name = $1;
324         #my $module_tag_hash = eval( $mod_name.'::get_module_tags()' );
326         my $info = eval($mod_name.'::get_module_info()');
327         my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
328         $known_modules->{$mod_name} = $info;
330         daemon_log("module $mod_name loaded", 1);
331     }   
333     # for debugging
334     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
335     #    print "\tmodule: $module"."\n";   
336     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
337     #}
338     close (DIR);
342 #===  FUNCTION  ================================================================
343 #         NAME:  sig_int_handler
344 #   PARAMETERS:  signal - string - signal arose from system
345 #      RETURNS:  noting
346 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
347 #===============================================================================
348 sub sig_int_handler {
349     my ($signal) = @_;
350     if($server){
351         close($server);
352         daemon_log("daemon server closed", 1);
353     }
354     if( -p $arp_fifo_path ) {
355         close $arp_fifo  ;
356         unlink($arp_fifo_path) ;
357         daemon_log("ARP_FIFO closed", 1) ;
358     }
360     if($gosa_server){
361         close($gosa_server);
362         daemon_log("gosa server closed", 1);
363     }
365     print STDERR "$signal\n";
366     
367     exit(1);
369 $SIG{INT} = \&sig_int_handler;
372 #===  FUNCTION  ================================================================
373 #         NAME:  activating_child
374 #   PARAMETERS:  msg - string - incoming message
375 #                host - string - host from which the incomming message comes
376 #      RETURNS:  nothing
377 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
378 #===============================================================================
379 sub activating_child {
380     my ($msg, $host, $client) = @_;
381     my $child = &get_processing_child();
382     my $pipe_wr = $$child{'pipe_wr'};
383     my $pipe_rd = $$child{'pipe_rd'};
384     $$child{client_ref} = $client;
385     
386     daemon_log("activating: childpid:$$child{'pid'}", 5);
388     print $pipe_wr $msg.".".$host."\n";
390     return;
394 #===  FUNCTION  ================================================================
395 #         NAME:  get_processing_child
396 #   PARAMETERS:  nothing
397 #      RETURNS:  child - hash - holding the process id and the references to the pipe
398 #                               handles pipe_wr and pipe_rd
399 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
400 #===============================================================================
401 sub get_processing_child {
402     my $child;
404     while(my ($key, $val) = each(%free_child)) {
405         my $exitus_pid = waitpid($key, WNOHANG);
406         if($exitus_pid != 0) {
407             delete $free_child{$key};
408         }
409         daemon_log("free child:$key", 5);
410     }
411     # check @free_child and @busy_child
412     my $free_len = scalar(keys(%free_child));
413     my $busy_len = scalar(keys(%busy_child));
414     daemon_log("free children $free_len, busy children $busy_len", 5);
416     # if there is a free child, let the child work
417     if($free_len > 0){
418         my @keys = keys(%free_child);
419         $child = $free_child{$keys[0]};
420         if(defined $child) {
421             $busy_child{$$child{'pid'}} = $child ;
422             delete $free_child{$$child{'pid'}};
423         }
424         return $child;
425     }
427     # no free child, try to fork another one
428     if($free_len + $busy_len < $child_max) {
430         daemon_log("not enough children, create a new one", 5);
432         # New pipes for communication
433         my( $PARENT_wr, $PARENT_rd );
434         my( $CHILD_wr, $CHILD_rd );
435         pipe( $CHILD_rd,  $PARENT_wr );
436         pipe( $PARENT_rd, $CHILD_wr  );
437         $PARENT_wr->autoflush(1);
438         $CHILD_wr->autoflush(1);
440         ############
441         # fork child
442         ############
443         my $child_pid = fork();
444         
445         #CHILD
446         if($child_pid == 0) {
447             # Close unused pipes
448             close( $CHILD_rd );
449             close( $CHILD_wr );
450             while( 1 ) {
451                 my $rbits = "";
452                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
453                 my $nf = select($rbits, undef, undef, $child_timeout);
454                 if($nf < 0 ) {
455                     die "select(): $!\n";
456                 } elsif (! $nf) {
457                     # if already child_min childs are alive, then leave loop
458                     $free_len = scalar(keys(%free_child));
459                     $busy_len = scalar(keys(%busy_child));
460                     if($free_len + $busy_len >= $child_min) {
461                         last;
462                     } else {
463                         redo;
464                     }
465                 }
467                 # a job for a child arise
468                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
469                     # read everything from pipe
470                     my $msg = "";
471                     $PARENT_rd->blocking(0);
472                     while(1) {
473                         my $read = <$PARENT_rd>;
474                         if(not defined $read) { last}
475                         $msg .= $read;
476                     }
478                     ######################################
479                     # forward msg to all imported modules 
480                     no strict "refs";
481                     my $answer;
482                     my %act_modules = %$known_modules;
483                     while( my ($module, $info) = each(%act_modules)) {
484                             &daemon_log("##########", 5);
485                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
486                             if (defined $tmp) {
487                                 $answer = $tmp;
488                             }
489                             &daemon_log("##########", 5);
490                     }        
492                     #&print_known_daemons();
493                     #&print_known_clients();
495                     daemon_log("processing of msg finished", 5);
496  
497                    if (defined $answer) {
498                         print $PARENT_wr $answer."\n";
499                         daemon_log("with answer: $answer", 5);
500                         daemon_log(" ", 5);
501                     } else {
502                         print $PARENT_wr "done"."\n";
503                         daemon_log(" ", 5);
504                     }
505                     redo;
506                 }
507             }
508             # childs leaving the loop are allowed to die
509             exit(0);
512         #PARENT
513         } else {
514             # Close unused pipes
515             close( $PARENT_rd );
516             close( $PARENT_wr );
518             # add child to child alive hash
519             my %child_hash = (
520                     'pid' => $child_pid,
521                     'pipe_wr' => $CHILD_wr,
522                     'pipe_rd' => $CHILD_rd,
523                     'client_ref' => "",
524                     );
526             $child = \%child_hash;
527             $busy_child{$$child{'pid'}} = $child;
528             return $child;
529         }
530     }
534 #===  FUNCTION  ================================================================
535 #         NAME:  read_from_socket
536 #   PARAMETERS:  socket fh - 
537 #      RETURNS:  result string - readed characters from socket
538 #  DESCRIPTION:  reads data from socket in 16 byte steps
539 #===============================================================================
540 sub read_from_socket {
541     my ($socket) = @_;
542     my $result = "";
544     $socket->blocking(1);
545     $result = <$socket>;
547     $socket->blocking(0);
548     while ( my $char = <$socket> ) {
549         if (not defined $char) { last }
550         $result .= $char;
551     }
553     return $result;
557 #===  FUNCTION  ================================================================
558 #         NAME:  print_known_daemons
559 #   PARAMETERS:  nothing
560 #      RETURNS:  nothing
561 #  DESCRIPTION:  nomen est omen
562 #===============================================================================
563 #sub print_known_daemons {
564 #    my ($tmp) = @_ ;
565 #    print "####################################\n";
566 #    print "# status of known_daemons\n";
567 #    $shmda->shlock(LOCK_EX);
568 #    my @hosts = keys %$known_daemons;
569 #    foreach my $host (@hosts) {
570 #        my $status = $known_daemons->{$host}->{status} ;
571 #        my $passwd = $known_daemons->{$host}->{passwd};
572 #        my $timestamp = $known_daemons->{$host}->{timestamp};
573 #        print "$host\n";
574 #        print "\tstatus:    $status\n";
575 #        print "\tpasswd:    $passwd\n";
576 #        print "\ttimestamp: $timestamp\n";
577 #    }
578 #    $shmda->shunlock(LOCK_EX);
579 #    print "####################################\n";
580 #    return;
581 #}
584 #===  FUNCTION  ================================================================
585 #         NAME:  create_known_daemon
586 #   PARAMETERS:  hostname - string - key for the hash known_daemons
587 #      RETURNS:  nothing
588 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
589 #===============================================================================
590 #sub create_known_daemon {
591 #    my ($hostname) = @_;
592 #    $shmda->shlock(LOCK_EX);
593 #    $known_daemons->{$hostname} = {};
594 #    $known_daemons->{$hostname}->{status} = "none";
595 #    $known_daemons->{$hostname}->{passwd} = "none";
596 #    $known_daemons->{$hostname}->{timestamp} = "none";
597 #    $shmda->shunlock(LOCK_EX); 
598 #    return;  
599 #}
602 #===  FUNCTION  ================================================================
603 #         NAME:  add_content2known_daemons
604 #   PARAMETERS:  hostname - string - ip address and port of host (required)
605 #                status - string - (optional)
606 #                passwd - string - (optional)
607 #                mac_address - string - mac address of host (optional)
608 #      RETURNS:  nothing
609 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
610 #===============================================================================
611 #sub add_content2known_daemons {
612 #    my $arg = {
613 #        hostname => undef, status => undef, passwd => undef,
614 #        mac_address => undef, events => undef, 
615 #        @_ };
616 #    my $hostname = $arg->{hostname};
617 #    my $status = $arg->{status};
618 #    my $passwd = $arg->{passwd};
619 #    my $mac_address = $arg->{mac_address};
620 #    my $events = $arg->{events};
622 #    if (not defined $hostname) {
623 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
624 #        return;
625 #    }
627 #    my ($seconds, $minutes, $hours, $monthday, $month,
628 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
629 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
630 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
631 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
632 #    $month+=1;
633 #    $month = $month < 10 ? $month = "0".$month : $month;
634 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
635 #    $year+=1900;
636 #    my $t = "$year$month$monthday$hours$minutes$seconds";
637 #    
638 #    $shmda->shlock(LOCK_EX);
639 #    if (defined $status) {
640 #        $known_daemons->{$hostname}->{status} = $status;
641 #    }
642 #    if (defined $passwd) {
643 #        $known_daemons->{$hostname}->{passwd} = $passwd;
644 #    }
645 #    if (defined $mac_address) {
646 #        $known_daemons->{$hostname}->{mac_address} = $mac_address;
647 #    }
648 #    if (defined $events) {
649 #        $known_daemons->{$hostname}->{events} = $events;
650 #    }
651 #    $known_daemons->{$hostname}->{timestamp} = $t;
652 #    $shmda->shlock(LOCK_EX);
653 #    return;
654 #}
657 #===  FUNCTION  ================================================================
658 #         NAME:  update_known_daemons
659 #   PARAMETERS:  hostname - string - ip address and port of host (required)
660 #                status - string - (optional)
661 #                passwd - string - (optional)
662 #                client - string - ip address and port of client (optional)
663 #      RETURNS:  nothing
664 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
665 #===============================================================================
666 #sub update_known_daemons {
667 #    my $arg = {
668 #        hostname => undef, status => undef, passwd => undef,
669 #        @_ };
670 #    my $hostname = $arg->{hostname};
671 #    my $status = $arg->{status};
672 #    my $passwd = $arg->{passwd};
674 #    if (not defined $hostname) {
675 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
676 #        return;
677 #    }
679 #    my ($seconds, $minutes, $hours, $monthday, $month,
680 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
681 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
682 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
683 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
684 #    $month+=1;
685 #    $month = $month < 10 ? $month = "0".$month : $month;
686 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
687 #    $year+=1900;
688 #    my $t = "$year$month$monthday$hours$minutes$seconds";
690 #    $shmda->shlock(LOCK_EX);
691 #    if (defined $status) {
692 #        $known_daemons->{$hostname}->{status} = $status;
693 #    }
694 #    if (defined $passwd) {
695 #        $known_daemons->{$hostname}->{passwd} = $passwd;
696 #    }
697 #    $known_daemons->{$hostname}->{timestamp} = $t;
698 #    $shmda->shunlock(LOCK_EX);
699 #    return;
700 #}
703 #===  FUNCTION  ================================================================
704 #         NAME:  print_known_clients 
705 #   PARAMETERS:  nothing
706 #      RETURNS:  nothing
707 #  DESCRIPTION:  nomen est omen
708 #===============================================================================
709 #sub print_known_clients {
711 #    print "####################################\n";
712 #    print "# status of known_clients\n";
713 #    $shmcl->shlock(LOCK_EX);
714 #    my @hosts = keys %$known_clients;
715 #    if (@hosts) {
716 #        foreach my $host (@hosts) {
717 #            my $status = $known_clients->{$host}->{status} ;
718 #            my $passwd = $known_clients->{$host}->{passwd};
719 #            my $timestamp = $known_clients->{$host}->{timestamp};
720 #            my $mac_address = $known_clients->{$host}->{mac_address};
721 #            my $events = $known_clients->{$host}->{events};
722 #            print "$host\n";
723 #            print "\tstatus:      $status\n";
724 #            print "\tpasswd:      $passwd\n";
725 #            print "\ttimestamp:   $timestamp\n";
726 #            print "\tmac_address: $mac_address\n";
727 #            print "\tevents:      $events\n";
728 #        }
729 #    }
730 #    $shmcl->shunlock(LOCK_EX);
731 #    print "####################################\n";
732 #    return;
733 #}
736 #===  FUNCTION  ================================================================
737 #         NAME:  create_known_client
738 #   PARAMETERS:  hostname - string - key for the hash known_clients
739 #      RETURNS:  nothing
740 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
741 #===============================================================================
742 sub create_known_client {
743     my ($hostname) = @_;
745     my $entry = { table=>'known_clients',
746         hostname=>$hostname,
747         status=>'none',
748         hostkey=>'none',
749         timestamp=>'none',
750         macaddress=>'none',
751         events=>'none',
752     };
753     my $res = $known_clients_db->add_dbentry($entry);
754     if ($res > 0) {
755         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
756     }
758     return;  
762 #===  FUNCTION  ================================================================
763 #         NAME:  add_content2known_clients
764 #   PARAMETERS:  hostname - string - ip address and port of host (required)
765 #                status - string - (optional)
766 #                passwd - string - (optional)
767 #                mac_address - string - (optional)
768 #                events - string - event of client, executable skripts 
769 #                under /etc/gosac/events
770 #      RETURNS:  nothing
771 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
772 #===============================================================================
773 #sub update_known_clients {
774 #    my $arg = {
775 #        hostname => undef, status => undef, hostkey => undef,
776 #        macaddress => undef, events => undef, timestamp=>undef,
777 #        @_ };
778 #    my $hostname = $arg->{hostname};
779 #    my $status = $arg->{status};
780 #    my $hostkey = $arg->{hostkey};
781 #    my $macaddress = $arg->{macaddress};
782 #    my $events = $arg->{events};
783 #    my $timestamp = $arg->{timestamp}; 
785 #    if (not defined $hostname) {
786 #        daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
787 #        return;
788 #    }
790 #    my $change_entry = { table=>'known_clients',
791 #                        where=>'hostname', 
792 #                        timestamp=>&get_time, 
793 #                        };
794 #   
795 #   
796 #    if (defined $status) {
797 #        $change_entry->{status} = $status;
798 #    }
799 #    if (defined $hostkey) {
800 #        $change_entry->{hostkey} = $hostkey;
801 #    }
802 #    if (defined $macaddress) {
803 #        $change_entry->{macaddress} = $macaddress;
804 #    }
805 #    if (defined $events) {
806 #        $change_entry->{events} = $events;
807 #    }
808 #    
809 #    $known_clients->change_dbentry($change_entry);
810 #    return;
811 #}
812  
814 #===  FUNCTION  ================================================================
815 #         NAME:  
816 #   PARAMETERS:  
817 #      RETURNS:  
818 #  DESCRIPTION:  
819 #===============================================================================    
820 #sub clean_up_known_clients {
821 #    my ($address) = @_ ;
822 #    
823 #    if (not exists $known_clients->{$address}) {
824 #        daemon_log("cannot prune known_clients from $address, client not known", 5);
825 #        return;
826 #    }
828 #    delete $known_clients->{$address};
830 #    # send bus a msg that address was deleted from known_clients
831 #    my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
832 #    &send_msg_hash2bus($out_hash);
834 #    daemon_log("client $address deleted from known_clients because of multiple down time", 3);
835 #    return;
836 #}
839 #===  FUNCTION  ================================================================
840 #         NAME:  update_known_clients
841 #   PARAMETERS:  hostname - string - ip address and port of host (required)
842 #                status - string - (optional)
843 #                passwd - string - (optional)
844 #                client - string - ip address and port of client (optional)
845 #      RETURNS:  nothing
846 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
847 #===============================================================================
848 #sub update_known_clients {
849 #    my $arg = {
850 #        hostname => undef, status => undef, passwd => undef,
851 #        mac_address => undef, events => undef,
852 #        @_ };
853 #    my $hostname = $arg->{hostname};
854 #    my $status = $arg->{status};
855 #    my $passwd = $arg->{passwd};
856 #    my $mac_address = $arg->{mac_address};
857 #    my $events = $arg->{events};
859 #    if (not defined $hostname) {
860 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
861 #        return;
862 #    }
864 #    my ($seconds, $minutes, $hours, $monthday, $month,
865 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
866 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
867 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
868 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
869 #    $month+=1;
870 #    $month = $month < 10 ? $month = "0".$month : $month;
871 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
872 #    $year+=1900;
873 #    my $t = "$year$month$monthday$hours$minutes$seconds";
875 #    if (defined $status) {
876 #        $known_clients->{$hostname}->{status} = $status;
877 #    }
878 #    if (defined $passwd) {
879 #        $known_clients->{$hostname}->{passwd} = $passwd;
880 #    }
881 #    if (defined $mac_address) {
882 #        $known_clients->{$hostname}->{mac_address} = $mac_address; 
883 #    }
884 #    if (defined $events) {
885 #        $known_clients->{$hostname}->{events} = $events;
886 #    }
887 #    $known_clients_db->{$hostname}->{timestamp} = $t;
888 #    return;
889 #}
897 #==== MAIN = main ==============================================================
899 #  parse commandline options
900 Getopt::Long::Configure( "bundling" );
901 GetOptions("h|help" => \&usage,
902         "c|config=s" => \$cfg_file,
903         "f|foreground" => \$foreground,
904         "v|verbose+" => \$verbose,
905         "no-bus+" => \$no_bus,
906         "no-arp+" => \$no_arp,
907            );
909 #  read and set config parameters
910 &check_cmdline_param ;
911 &read_configfile;
912 &check_pid;
914 $SIG{CHLD} = 'IGNORE';
916 # restart daemon log file
917 daemon_log(" ", 1);
918 daemon_log("$0 started!", 1);
920 # Just fork, if we"re not in foreground mode
921 if( ! $foreground ) { 
922     chdir '/'                 or die "Can't chdir to /: $!";
923     $pid = fork;
924     setsid                    or die "Can't start a new session: $!";
925     umask 0;
926 } else { 
927     $pid = $$; 
930 # Do something useful - put our PID into the pid_file
931 if( 0 != $pid ) {
932     open( LOCK_FILE, ">$pid_file" );
933     print LOCK_FILE "$pid\n";
934     close( LOCK_FILE );
935     if( !$foreground ) { 
936         exit( 0 ) 
937     };
940 # connect to gosa-si job queue
941 my @job_col_names = ("timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
942 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
943 $job_db->create_table('jobs', \@job_col_names);
945 # connect to known_clients_db
946 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
947 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
948 $known_clients_db->create_table('known_clients', \@clients_col_names);
950 # connect to known_server_db
951 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
952 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
953 $known_server_db->create_table('known_server', \@server_col_names);
955 # import all modules
956 &import_modules;
958 # check wether all modules are gosa-si valid passwd check
960 # create reading and writing vectors
961 my $rbits = my $wbits = my $ebits = "";
963 # add all module inputs to listening vector
964 while( my ($mod_name, $info) = each %$known_modules ) {
965     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
966     vec($rbits, fileno $input, 1) = 1;   
971 ## start arp fifo
972 #if ($no_arp > 0) {
973 #    $arp_activ = "off";
974 #}
975 #my $my_fifo;
976 #if($arp_activ eq "on") {
977 #    daemon_log(" ", 1);
978 #    $my_fifo = &open_fifo($arp_fifo_path);
979 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
980 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
981 #    
982 #    vec($rbits, fileno $arp_fifo, 1) = 1;
983 #}
986 ##################################
987 #everything ready, okay, lets start
988 ##################################
989 while(1) {
991     # add all handles from the childs
992     while ( my ($pid, $child_hash) = each %busy_child ) {
993         
994         # check whether process still exists
995         my $exitus_pid = waitpid($pid, WNOHANG);
996         if($exitus_pid != 0) {
997             delete $busy_child{$pid};
998             next;
999         }
1000      
1001         # add child fhd to the listener    
1002         my $fhd = $$child_hash{'pipe_rd'};
1003         vec($rbits, fileno $fhd, 1) = 1;
1004     }
1006     my ($rout, $wout);
1007     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1009     # error handling
1010     if($nf < 0 ) {
1011     }
1014 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1015 #        my $in_msg = <$arp_fifo>;
1016 #        chomp($in_msg);
1017 #        print "arp_activ: msg: $in_msg\n";
1018 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1019 #        print "arp_activ: arp_passwd: $act_passwd\n";
1021 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1023 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1025 #        if ($target eq $server_address) { 
1026 #             print "arp_activ: forward to server\n";
1027 #            my $arp_cipher = &create_ciphering($act_passwd);
1028 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1029 #            &activating_child($crypted_msg, $server_ip);
1030 #        } else {
1031 #            print "arp_activ: send to bus\n";
1032 #            &send_msg_hash2address($in_msg_hash, $bus_address);
1033 #        }
1034 #        print "\n";
1035 #    }
1038     # check input fhd of all modules 
1039     while ( my ($mod_name, $info) = each %$known_modules) {
1040         my $input_fhd = @{$info}[2];    
1041         my $input_activ = @{$info}[3];
1042         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1043             daemon_log(" ", 1);
1044             my $client = $input_fhd->accept();
1045             my $other_end = getpeername($client);
1046             if(not defined $other_end) {
1047                 daemon_log("client cannot be identified: $!");
1048             } else {
1049                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1050                 my $actual_ip = inet_ntoa($iaddr);
1051                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1052                 my $in_msg = &read_from_socket($client);
1053                 if(defined $in_msg){
1054                     chomp($in_msg);
1055                     &activating_child($in_msg, $actual_ip, $client);
1056                 } else {
1057                     daemon_log("cannot read from $actual_ip", 5);
1058                 }
1059             }
1060         }
1061     }
1063     # check all processing childs whether they are finished ('done') or 
1064     while ( my ($pid, $child_hash) = each %busy_child ) {
1065         my $fhd = $$child_hash{'pipe_rd'};
1067         if (vec($rout, fileno $fhd, 1) ) {
1068             daemon_log("process child $pid is ready to read", 5);
1070             $fhd->blocking(1);
1071             my $in_msg = <$fhd>;
1072             $fhd->blocking(0);
1073             my $part_in_msg;
1074             while ($part_in_msg = <$fhd>) {
1075                 if (not defined $part_in_msg) {
1076                     last;
1077                 }
1078                 $in_msg .= $part_in_msg;
1079             }
1080             chomp($in_msg);
1082             daemon_log("process child read: $in_msg", 5);
1083             if (not defined $in_msg) { 
1084                 next; 
1085             } elsif ($in_msg =~ "done") {
1086                 delete $busy_child{$pid};
1087                 $free_child{$pid} = $child_hash;
1088  
1089             } else {
1090                 # send computed answer back to connected client
1091                 my $act_client = $busy_child{$pid}{client_ref};
1092                 print $act_client $in_msg."\n";
1094                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1095                 delete $busy_child{$pid};
1096                 $free_child{$pid} = $child_hash;
1098                 # give the client a chance to read 
1099                 sleep(2);
1100                 close ($act_client);   
1101             }
1102         }
1103     }
1105     # check gosa job queue for jobs with executable timestamp
1106     my ($seconds, $minutes, $hours, $monthday, $month,
1107     $year, $weekday, $yearday, $sommertime) = localtime(time);
1108     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1109     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1110     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1111     $month+=1;
1112     $month = $month < 10 ? $month = "0".$month : $month;
1113     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1114     $year+=1900;
1115     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1116     
1117     
1118     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1120     while( my ($id, $hit) = each %{$res} ) {         
1122         my $jobdb_id = $hit->{ROWID};
1123         my $macaddress = $hit->{macaddress};
1124         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1125         my $out_msg_hash = $job_msg_hash;
1126         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1127         # expect macaddress is unique!!!!!!
1128         my $target = $res_hash->{1}->{hostname};
1129         
1130         if (not defined $target) {
1131             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1132             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1133             my $update_hash = { table=>$job_queue_table_name,
1134                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1135                 where=> [ { ROWID=>[$jobdb_id] } ],
1136             };
1137             my $res = $job_db->update_dbentry($update_hash);
1139             next;
1140         }
1142         # add target
1143         &add_content2xml_hash($out_msg_hash, "target", $target);
1145         # add new header
1146         my $out_header = $job_msg_hash->{header}[0];
1147         $out_header =~ s/job_/gosa_/;
1148         delete $out_msg_hash->{header};
1149         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1150         
1151         # add sqlite_id 
1152         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1153     
1154         my $out_msg = &create_xml_string($out_msg_hash);
1156         # encrypt msg as a GosaPackage module
1157         my $cipher = &create_ciphering($gosa_passwd);
1158         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1160         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1162 #######################
1163 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1165         if ($error == 0) {
1166             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1167             my $res = $job_db->exec_statement($sql);
1168         } else {
1169             my $update_hash = { table=>$job_queue_table_name, 
1170                                 update=> [ { status=>'error' } ],
1171                                 where=> [ { ROWID=>$jobdb_id } ],
1172                               };
1173             my $res = $job_db->update_dbentry($update_hash);
1174         }
1176     }