Code

2d4b84d484fd688d59c0346a4bad91f4469077cc
[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_daemons, $shmda, $known_clients, $shmcl, $known_modules, $known_clients_file_name, $known_server_file_name, $known_clients_db, $known_server_db);
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;
97 our $known_daemons = {};
98 our $shmda = tie($known_daemons, 'IPC::Shareable', undef, {create => 1, 
99                                                             exclusive => 1, 
100                                                             mode => 0666, 
101                                                             destroy => 1,
102                                                             });
104 # holds all registrated clients
105 our $known_clients_db;
106 #our $known_clients = {};
107 #our $shmcl = tie($known_clients, 'IPC::Shareable', undef, {create => 1, 
108 #                                                            exclusive => 1, 
109 #                                                            mode => 0666, 
110 #                                                            destroy => 1,
111 #                                                            });
114 %cfg_defaults =
115 ("general" =>
116     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
117     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
118     "child_max" => [\$child_max, 10],
119     "child_min" => [\$child_min, 3],
120     "child_timeout" => [\$child_timeout, 180],
121     "job_queue_timeout" => [\$job_queue_timeout, undef],
122     "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
123     "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
124     "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/kown_server.db'],
125    },
126 "bus" =>
127     {"bus_activ" => [\$bus_activ, "on"],
128     "bus_passwd" => [\$bus_passwd, ""],
129     "bus_ip" => [\$bus_ip, ""],
130     "bus_port" => [\$bus_port, "20080"],
131     },
132 "server" =>
133     {"server_activ" => [\$server_activ, "on"],
134     "server_ip" => [\$server_ip, ""],
135     "server_port" => [\$server_port, "20081"],
136     "server_passwd" => [\$server_passwd, ""],
137     "max_clients" => [\$max_clients, 100],
138     },
139 "arp" =>
140     {"arp_activ" => [\$arp_activ, "on"],
141     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
142     },
143 "gosa" =>
144     {"gosa_activ" => [\$gosa_activ, "on"],
145     "gosa_ip" => [\$gosa_ip, ""],
146     "gosa_port" => [\$gosa_port, "20082"],
147     "gosa_passwd" => [\$gosa_passwd, "none"],
148     },
149     );
152 #===  FUNCTION  ================================================================
153 #         NAME:  usage
154 #   PARAMETERS:  nothing
155 #      RETURNS:  nothing
156 #  DESCRIPTION:  print out usage text to STDERR
157 #===============================================================================
158 sub usage {
159     print STDERR << "EOF" ;
160 usage: $0 [-hvf] [-c config]
162            -h        : this (help) message
163            -c <file> : config file
164            -f        : foreground, process will not be forked to background
165            -v        : be verbose (multiple to increase verbosity)
166            -no-bus   : starts $0 without connection to bus
167            -no-arp   : starts $0 without connection to arp module
168  
169 EOF
170     print "\n" ;
174 #===  FUNCTION  ================================================================
175 #         NAME:  read_configfile
176 #   PARAMETERS:  cfg_file - string -
177 #      RETURNS:  nothing
178 #  DESCRIPTION:  read cfg_file and set variables
179 #===============================================================================
180 sub read_configfile {
181     my $cfg;
182     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
183         if( -r $cfg_file ) {
184             $cfg = Config::IniFiles->new( -file => $cfg_file );
185         } else {
186             print STDERR "Couldn't read config file!";
187         }
188     } else {
189         $cfg = Config::IniFiles->new() ;
190     }
191     foreach my $section (keys %cfg_defaults) {
192         foreach my $param (keys %{$cfg_defaults{ $section }}) {
193             my $pinfo = $cfg_defaults{ $section }{ $param };
194             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
195         }
196     }
200 #===  FUNCTION  ================================================================
201 #         NAME:  logging
202 #   PARAMETERS:  level - string - default 'info'
203 #                msg - string -
204 #                facility - string - default 'LOG_DAEMON'
205 #      RETURNS:  nothing
206 #  DESCRIPTION:  function for logging
207 #===============================================================================
208 sub daemon_log {
209     # log into log_file
210     my( $msg, $level ) = @_;
211     if(not defined $msg) { return }
212     if(not defined $level) { $level = 1 }
213     if(defined $log_file){
214         open(LOG_HANDLE, ">>$log_file");
215         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
216             print STDERR "cannot open $log_file: $!";
217             return }
218             chomp($msg);
219             if($level <= $verbose){
220                 print LOG_HANDLE "$level $msg\n";
221                 if($foreground) { print $msg."\n" }
222             }
223     }
224 #    close( LOG_HANDLE );
225 #log into syslog
226 #    my ($msg, $level, $facility) = @_;
227 #    if(not defined $msg) {return}
228 #    if(not defined $level) {$level = "info"}
229 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
230 #    openlog($0, "pid,cons,", $facility);
231 #    syslog($level, $msg);
232 #    closelog;
233 #    return;
237 #===  FUNCTION  ================================================================
238 #         NAME:  check_cmdline_param
239 #   PARAMETERS:  nothing
240 #      RETURNS:  nothing
241 #  DESCRIPTION:  validates commandline parameter
242 #===============================================================================
243 sub check_cmdline_param () {
244     my $err_config;
245     my $err_counter = 0;
246     if( not defined( $cfg_file)) {
247         #$err_config = "please specify a config file";
248         #$err_counter += 1;
249         my $cwd = getcwd;
250         my $name = "/etc/gosa-si/server.conf";
251         $cfg_file = File::Spec->catfile( $cwd, $name );
252     }
253     if( $err_counter > 0 ) {
254         &usage( "", 1 );
255         if( defined( $err_config)) { print STDERR "$err_config\n"}
256         print STDERR "\n";
257         exit( -1 );
258     }
262 #===  FUNCTION  ================================================================
263 #         NAME:  check_pid
264 #   PARAMETERS:  nothing
265 #      RETURNS:  nothing
266 #  DESCRIPTION:  handels pid processing
267 #===============================================================================
268 sub check_pid {
269     $pid = -1;
270     # Check, if we are already running
271     if( open(LOCK_FILE, "<$pid_file") ) {
272         $pid = <LOCK_FILE>;
273         if( defined $pid ) {
274             chomp( $pid );
275             if( -f "/proc/$pid/stat" ) {
276                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
277                 if( $0 eq $stat ) {
278                     close( LOCK_FILE );
279                     exit -1;
280                 }
281             }
282         }
283         close( LOCK_FILE );
284         unlink( $pid_file );
285     }
287     # create a syslog msg if it is not to possible to open PID file
288     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
289         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
290         if (open(LOCK_FILE, '<', $pid_file)
291                 && ($pid = <LOCK_FILE>))
292         {
293             chomp($pid);
294             $msg .= "(PID $pid)\n";
295         } else {
296             $msg .= "(unable to read PID)\n";
297         }
298         if( ! ($foreground) ) {
299             openlog( $0, "cons,pid", "daemon" );
300             syslog( "warning", $msg );
301             closelog();
302         }
303         else {
304             print( STDERR " $msg " );
305         }
306         exit( -1 );
307     }
311 #===  FUNCTION  ================================================================
312 #         NAME:  get_ip_and_mac 
313 #   PARAMETERS:  nothing
314 #      RETURNS:  (ip, mac) 
315 #  DESCRIPTION:  executes /sbin/ifconfig and parses the output, the first occurence 
316 #                of a inet address is returned as well as the mac address in the line
317 #                above the inet address
318 #===============================================================================
319 sub get_ip_and_mac {
320     my $ip = "0.0.0.0.0"; # Defualt-IP
321     my $mac = "00:00:00:00:00:00";  # Default-MAC
322     my @ifconfig = qx(/sbin/ifconfig);
323     foreach(@ifconfig) {
324         if (/Hardware Adresse (\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/) {
325             $mac = "$1:$2:$3:$4:$5:$6";
326             next;
327         }
328         if (/inet Adresse:(\d+).(\d+).(\d+).(\d+)/) {
329             $ip = "$1.$2.$3.$4";
330             last;
331         }
332     }
333     return ($ip, $mac);
338 #===  FUNCTION  ================================================================
339 #         NAME:  import_modules
340 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
341 #                are stored
342 #      RETURNS:  nothing
343 #  DESCRIPTION:  each file in module_path which ends with '.pm' is imported by 
344 #                "require 'file';"
345 #===============================================================================
346 sub import_modules {
347     daemon_log(" ", 1);
349     if (not -e $modules_path) {
350         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
351     }
353     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
354     while (defined (my $file = readdir (DIR))) {
355         if (not $file =~ /(\S*?).pm$/) {
356             next;
357         }
358         eval { require $file; };
359         if ($@) {
360             daemon_log("ERROR: gosa-sd could not load module $file", 1);
361             daemon_log("$@", 5);
362             next;
363         }
364         my $mod_name = $1;
365         #my $module_tag_hash = eval( $mod_name.'::get_module_tags()' );
367         my $info = eval($mod_name.'::get_module_info()');
368         my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
369         $known_modules->{$mod_name} = $info;
371         daemon_log("module $mod_name loaded", 1);
372     }   
374     # for debugging
375     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
376     #    print "\tmodule: $module"."\n";   
377     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
378     #}
379     close (DIR);
383 #===  FUNCTION  ================================================================
384 #         NAME:  sig_int_handler
385 #   PARAMETERS:  signal - string - signal arose from system
386 #      RETURNS:  noting
387 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
388 #===============================================================================
389 sub sig_int_handler {
390     my ($signal) = @_;
391     if($server){
392         close($server);
393         daemon_log("daemon server closed", 1);
394     }
395     if( -p $arp_fifo_path ) {
396         close $arp_fifo  ;
397         unlink($arp_fifo_path) ;
398         daemon_log("ARP_FIFO closed", 1) ;
399     }
401     if($gosa_server){
402         close($gosa_server);
403         daemon_log("gosa server closed", 1);
404     }
406     print STDERR "$signal\n";
407     
408     exit(1);
410 $SIG{INT} = \&sig_int_handler;
413 #===  FUNCTION  ================================================================
414 #         NAME:  activating_child
415 #   PARAMETERS:  msg - string - incoming message
416 #                host - string - host from which the incomming message comes
417 #      RETURNS:  nothing
418 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
419 #===============================================================================
420 sub activating_child {
421     my ($msg, $host, $client) = @_;
422     my $child = &get_processing_child();
423     my $pipe_wr = $$child{'pipe_wr'};
424     my $pipe_rd = $$child{'pipe_rd'};
425     $$child{client_ref} = $client;
426     
427     daemon_log("activating: childpid:$$child{'pid'}", 5);
429     print $pipe_wr $msg.".".$host."\n";
431     return;
435 #===  FUNCTION  ================================================================
436 #         NAME:  get_processing_child
437 #   PARAMETERS:  nothing
438 #      RETURNS:  child - hash - holding the process id and the references to the pipe
439 #                               handles pipe_wr and pipe_rd
440 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
441 #===============================================================================
442 sub get_processing_child {
443     my $child;
445     while(my ($key, $val) = each(%free_child)) {
446         my $exitus_pid = waitpid($key, WNOHANG);
447         if($exitus_pid != 0) {
448             delete $free_child{$key};
449         }
450         daemon_log("free child:$key", 5);
451     }
452     # check @free_child and @busy_child
453     my $free_len = scalar(keys(%free_child));
454     my $busy_len = scalar(keys(%busy_child));
455     daemon_log("free children $free_len, busy children $busy_len", 5);
457     # if there is a free child, let the child work
458     if($free_len > 0){
459         my @keys = keys(%free_child);
460         $child = $free_child{$keys[0]};
461         if(defined $child) {
462             $busy_child{$$child{'pid'}} = $child ;
463             delete $free_child{$$child{'pid'}};
464         }
465         return $child;
466     }
468     # no free child, try to fork another one
469     if($free_len + $busy_len < $child_max) {
471         daemon_log("not enough children, create a new one", 5);
473         # New pipes for communication
474         my( $PARENT_wr, $PARENT_rd );
475         my( $CHILD_wr, $CHILD_rd );
476         pipe( $CHILD_rd,  $PARENT_wr );
477         pipe( $PARENT_rd, $CHILD_wr  );
478         $PARENT_wr->autoflush(1);
479         $CHILD_wr->autoflush(1);
481         ############
482         # fork child
483         ############
484         my $child_pid = fork();
485         
486         #CHILD
487         if($child_pid == 0) {
488             # Close unused pipes
489             close( $CHILD_rd );
490             close( $CHILD_wr );
491             while( 1 ) {
492                 my $rbits = "";
493                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
494                 my $nf = select($rbits, undef, undef, $child_timeout);
495                 if($nf < 0 ) {
496                     die "select(): $!\n";
497                 } elsif (! $nf) {
498                     # if already child_min childs are alive, then leave loop
499                     $free_len = scalar(keys(%free_child));
500                     $busy_len = scalar(keys(%busy_child));
501                     if($free_len + $busy_len >= $child_min) {
502                         last;
503                     } else {
504                         redo;
505                     }
506                 }
508                 # a job for a child arise
509                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
510                     # read everything from pipe
511                     my $msg = "";
512                     $PARENT_rd->blocking(0);
513                     while(1) {
514                         my $read = <$PARENT_rd>;
515                         if(not defined $read) { last}
516                         $msg .= $read;
517                     }
519                     ######################################
520                     # forward msg to all imported modules 
521                     no strict "refs";
522                     my $answer;
523                     my %act_modules = %$known_modules;
524                     while( my ($module, $info) = each(%act_modules)) {
525                             &daemon_log("##########", 5);
526                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
527                             if (defined $tmp) {
528                                 $answer = $tmp;
529                             }
530                             &daemon_log("##########", 5);
531                     }        
533                     #&print_known_daemons();
534                     #&print_known_clients();
536                     daemon_log("processing of msg finished", 5);
537  
538                    if (defined $answer) {
539                         print $PARENT_wr $answer."\n";
540                         daemon_log("with answer: $answer", 5);
541                         daemon_log(" ", 5);
542                     } else {
543                         print $PARENT_wr "done"."\n";
544                         daemon_log(" ", 5);
545                     }
546                     redo;
547                 }
548             }
549             # childs leaving the loop are allowed to die
550             exit(0);
553         #PARENT
554         } else {
555             # Close unused pipes
556             close( $PARENT_rd );
557             close( $PARENT_wr );
559             # add child to child alive hash
560             my %child_hash = (
561                     'pid' => $child_pid,
562                     'pipe_wr' => $CHILD_wr,
563                     'pipe_rd' => $CHILD_rd,
564                     'client_ref' => "",
565                     );
567             $child = \%child_hash;
568             $busy_child{$$child{'pid'}} = $child;
569             return $child;
570         }
571     }
575 #===  FUNCTION  ================================================================
576 #         NAME:  read_from_socket
577 #   PARAMETERS:  socket fh - 
578 #      RETURNS:  result string - readed characters from socket
579 #  DESCRIPTION:  reads data from socket in 16 byte steps
580 #===============================================================================
581 sub read_from_socket {
582     my ($socket) = @_;
583     my $result = "";
585     $socket->blocking(1);
586     $result = <$socket>;
588     $socket->blocking(0);
589     while ( my $char = <$socket> ) {
590         if (not defined $char) { last }
591         $result .= $char;
592     }
594     return $result;
598 #===  FUNCTION  ================================================================
599 #         NAME:  print_known_daemons
600 #   PARAMETERS:  nothing
601 #      RETURNS:  nothing
602 #  DESCRIPTION:  nomen est omen
603 #===============================================================================
604 #sub print_known_daemons {
605 #    my ($tmp) = @_ ;
606 #    print "####################################\n";
607 #    print "# status of known_daemons\n";
608 #    $shmda->shlock(LOCK_EX);
609 #    my @hosts = keys %$known_daemons;
610 #    foreach my $host (@hosts) {
611 #        my $status = $known_daemons->{$host}->{status} ;
612 #        my $passwd = $known_daemons->{$host}->{passwd};
613 #        my $timestamp = $known_daemons->{$host}->{timestamp};
614 #        print "$host\n";
615 #        print "\tstatus:    $status\n";
616 #        print "\tpasswd:    $passwd\n";
617 #        print "\ttimestamp: $timestamp\n";
618 #    }
619 #    $shmda->shunlock(LOCK_EX);
620 #    print "####################################\n";
621 #    return;
622 #}
625 #===  FUNCTION  ================================================================
626 #         NAME:  create_known_daemon
627 #   PARAMETERS:  hostname - string - key for the hash known_daemons
628 #      RETURNS:  nothing
629 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
630 #===============================================================================
631 sub create_known_daemon {
632     my ($hostname) = @_;
633     $shmda->shlock(LOCK_EX);
634     $known_daemons->{$hostname} = {};
635     $known_daemons->{$hostname}->{status} = "none";
636     $known_daemons->{$hostname}->{passwd} = "none";
637     $known_daemons->{$hostname}->{timestamp} = "none";
638     $shmda->shunlock(LOCK_EX); 
639     return;  
643 #===  FUNCTION  ================================================================
644 #         NAME:  add_content2known_daemons
645 #   PARAMETERS:  hostname - string - ip address and port of host (required)
646 #                status - string - (optional)
647 #                passwd - string - (optional)
648 #                mac_address - string - mac address of host (optional)
649 #      RETURNS:  nothing
650 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
651 #===============================================================================
652 sub add_content2known_daemons {
653     my $arg = {
654         hostname => undef, status => undef, passwd => undef,
655         mac_address => undef, events => undef, 
656         @_ };
657     my $hostname = $arg->{hostname};
658     my $status = $arg->{status};
659     my $passwd = $arg->{passwd};
660     my $mac_address = $arg->{mac_address};
661     my $events = $arg->{events};
663     if (not defined $hostname) {
664         daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
665         return;
666     }
668     my ($seconds, $minutes, $hours, $monthday, $month,
669     $year, $weekday, $yearday, $sommertime) = localtime(time);
670     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
671     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
672     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
673     $month+=1;
674     $month = $month < 10 ? $month = "0".$month : $month;
675     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
676     $year+=1900;
677     my $t = "$year$month$monthday$hours$minutes$seconds";
678     
679     $shmda->shlock(LOCK_EX);
680     if (defined $status) {
681         $known_daemons->{$hostname}->{status} = $status;
682     }
683     if (defined $passwd) {
684         $known_daemons->{$hostname}->{passwd} = $passwd;
685     }
686     if (defined $mac_address) {
687         $known_daemons->{$hostname}->{mac_address} = $mac_address;
688     }
689     if (defined $events) {
690         $known_daemons->{$hostname}->{events} = $events;
691     }
692     $known_daemons->{$hostname}->{timestamp} = $t;
693     $shmda->shlock(LOCK_EX);
694     return;
698 #===  FUNCTION  ================================================================
699 #         NAME:  update_known_daemons
700 #   PARAMETERS:  hostname - string - ip address and port of host (required)
701 #                status - string - (optional)
702 #                passwd - string - (optional)
703 #                client - string - ip address and port of client (optional)
704 #      RETURNS:  nothing
705 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
706 #===============================================================================
707 sub update_known_daemons {
708     my $arg = {
709         hostname => undef, status => undef, passwd => undef,
710         @_ };
711     my $hostname = $arg->{hostname};
712     my $status = $arg->{status};
713     my $passwd = $arg->{passwd};
715     if (not defined $hostname) {
716         daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
717         return;
718     }
720     my ($seconds, $minutes, $hours, $monthday, $month,
721     $year, $weekday, $yearday, $sommertime) = localtime(time);
722     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
723     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
724     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
725     $month+=1;
726     $month = $month < 10 ? $month = "0".$month : $month;
727     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
728     $year+=1900;
729     my $t = "$year$month$monthday$hours$minutes$seconds";
731     $shmda->shlock(LOCK_EX);
732     if (defined $status) {
733         $known_daemons->{$hostname}->{status} = $status;
734     }
735     if (defined $passwd) {
736         $known_daemons->{$hostname}->{passwd} = $passwd;
737     }
738     $known_daemons->{$hostname}->{timestamp} = $t;
739     $shmda->shunlock(LOCK_EX);
740     return;
744 #===  FUNCTION  ================================================================
745 #         NAME:  print_known_clients 
746 #   PARAMETERS:  nothing
747 #      RETURNS:  nothing
748 #  DESCRIPTION:  nomen est omen
749 #===============================================================================
750 #sub print_known_clients {
752 #    print "####################################\n";
753 #    print "# status of known_clients\n";
754 #    $shmcl->shlock(LOCK_EX);
755 #    my @hosts = keys %$known_clients;
756 #    if (@hosts) {
757 #        foreach my $host (@hosts) {
758 #            my $status = $known_clients->{$host}->{status} ;
759 #            my $passwd = $known_clients->{$host}->{passwd};
760 #            my $timestamp = $known_clients->{$host}->{timestamp};
761 #            my $mac_address = $known_clients->{$host}->{mac_address};
762 #            my $events = $known_clients->{$host}->{events};
763 #            print "$host\n";
764 #            print "\tstatus:      $status\n";
765 #            print "\tpasswd:      $passwd\n";
766 #            print "\ttimestamp:   $timestamp\n";
767 #            print "\tmac_address: $mac_address\n";
768 #            print "\tevents:      $events\n";
769 #        }
770 #    }
771 #    $shmcl->shunlock(LOCK_EX);
772 #    print "####################################\n";
773 #    return;
774 #}
777 #===  FUNCTION  ================================================================
778 #         NAME:  create_known_client
779 #   PARAMETERS:  hostname - string - key for the hash known_clients
780 #      RETURNS:  nothing
781 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
782 #===============================================================================
783 sub create_known_client {
784     my ($hostname) = @_;
786     my $entry = { table=>'known_clients',
787         hostname=>$hostname,
788         status=>'none',
789         hostkey=>'none',
790         timestamp=>'none',
791         macaddress=>'none',
792         events=>'none',
793     };
794     my $res = $known_clients_db->add_dbentry($entry);
795     if ($res > 0) {
796         daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
797     }
799 #    $shmcl->shlock(LOCK_EX);
800 #    $known_clients->{$hostname} = {};
801 #    $known_clients->{$hostname}->{status} = "none";
802 #    $known_clients->{$hostname}->{passwd} = "none";
803 #    $known_clients->{$hostname}->{timestamp} = "none";
804 #    $known_clients->{$hostname}->{mac_address} = "none";
805 #    $known_clients->{$hostname}->{events} = "none";
806 #    $shmcl->shunlock(LOCK_EX); 
807     return;  
811 #===  FUNCTION  ================================================================
812 #         NAME:  add_content2known_clients
813 #   PARAMETERS:  hostname - string - ip address and port of host (required)
814 #                status - string - (optional)
815 #                passwd - string - (optional)
816 #                mac_address - string - (optional)
817 #                events - string - event of client, executable skripts 
818 #                under /etc/gosac/events
819 #      RETURNS:  nothing
820 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
821 #===============================================================================
822 sub update_known_clients {
823     my $arg = {
824         hostname => undef, status => undef, hostkey => undef,
825         macaddress => undef, events => undef, timestamp=>undef,
826         @_ };
827     my $hostname = $arg->{hostname};
828     my $status = $arg->{status};
829     my $hostkey = $arg->{hostkey};
830     my $macaddress = $arg->{macaddress};
831     my $events = $arg->{events};
832     my $timestamp = $arg->{timestamp}; 
834     if (not defined $hostname) {
835         daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
836         return;
837     }
839     my ($seconds, $minutes, $hours, $monthday, $month,
840     $year, $weekday, $yearday, $sommertime) = localtime(time);
841     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
842     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
843     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
844     $month+=1;
845     $month = $month < 10 ? $month = "0".$month : $month;
846     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
847     $year+=1900;
848     my $t = "$year$month$monthday$hours$minutes$seconds";
849  
850     my $change_entry = { table=>'known_clients',
851                         where=>'hostname', 
852                         timestamp=>$t, 
853                         };
854    
855    
856     if (defined $status) {
857         $change_entry->{status} = $status;
858     }
859     if (defined $hostkey) {
860         $change_entry->{hostkey} = $hostkey;
861     }
862     if (defined $macaddress) {
863         $change_entry->{macaddress} = $macaddress;
864     }
865     if (defined $events) {
866         $change_entry->{events} = $events;
867     }
868     
869     $known_clients->change_dbentry($change_entry);
870     return;
872  
874 #===  FUNCTION  ================================================================
875 #         NAME:  
876 #   PARAMETERS:  
877 #      RETURNS:  
878 #  DESCRIPTION:  
879 #===============================================================================    
880 sub clean_up_known_clients {
881     my ($address) = @_ ;
882     
883     if (not exists $known_clients->{$address}) {
884         daemon_log("cannot prune known_clients from $address, client not known", 5);
885         return;
886     }
888     delete $known_clients->{$address};
890     # send bus a msg that address was deleted from known_clients
891     my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
892     &send_msg_hash2bus($out_hash);
894     daemon_log("client $address deleted from known_clients because of multiple down time", 3);
895     return;
899 #===  FUNCTION  ================================================================
900 #         NAME:  update_known_clients
901 #   PARAMETERS:  hostname - string - ip address and port of host (required)
902 #                status - string - (optional)
903 #                passwd - string - (optional)
904 #                client - string - ip address and port of client (optional)
905 #      RETURNS:  nothing
906 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
907 #===============================================================================
908 #sub update_known_clients {
909 #    my $arg = {
910 #        hostname => undef, status => undef, passwd => undef,
911 #        mac_address => undef, events => undef,
912 #        @_ };
913 #    my $hostname = $arg->{hostname};
914 #    my $status = $arg->{status};
915 #    my $passwd = $arg->{passwd};
916 #    my $mac_address = $arg->{mac_address};
917 #    my $events = $arg->{events};
919 #    if (not defined $hostname) {
920 #        daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
921 #        return;
922 #    }
924 #    my ($seconds, $minutes, $hours, $monthday, $month,
925 #    $year, $weekday, $yearday, $sommertime) = localtime(time);
926 #    $hours = $hours < 10 ? $hours = "0".$hours : $hours;
927 #    $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
928 #    $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
929 #    $month+=1;
930 #    $month = $month < 10 ? $month = "0".$month : $month;
931 #    $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
932 #    $year+=1900;
933 #    my $t = "$year$month$monthday$hours$minutes$seconds";
935 #    if (defined $status) {
936 #        $known_clients->{$hostname}->{status} = $status;
937 #    }
938 #    if (defined $passwd) {
939 #        $known_clients->{$hostname}->{passwd} = $passwd;
940 #    }
941 #    if (defined $mac_address) {
942 #        $known_clients->{$hostname}->{mac_address} = $mac_address; 
943 #    }
944 #    if (defined $events) {
945 #        $known_clients->{$hostname}->{events} = $events;
946 #    }
947 #    $known_clients_db->{$hostname}->{timestamp} = $t;
948 #    return;
949 #}
957 #==== MAIN = main ==============================================================
959 #  parse commandline options
960 Getopt::Long::Configure( "bundling" );
961 GetOptions("h|help" => \&usage,
962         "c|config=s" => \$cfg_file,
963         "f|foreground" => \$foreground,
964         "v|verbose+" => \$verbose,
965         "no-bus+" => \$no_bus,
966         "no-arp+" => \$no_arp,
967            );
969 #  read and set config parameters
970 &check_cmdline_param ;
971 &read_configfile;
972 &check_pid;
974 $SIG{CHLD} = 'IGNORE';
976 # restart daemon log file
977 if(-e $log_file ) { unlink $log_file }
978 daemon_log(" ", 1);
979 daemon_log("$0 started!", 1);
981 # Just fork, if we"re not in foreground mode
982 if( ! $foreground ) { 
983     $pid = fork();  
984 } else { 
985     $pid = $$; 
988 # Do something useful - put our PID into the pid_file
989 if( 0 != $pid ) {
990     open( LOCK_FILE, ">$pid_file" );
991     print LOCK_FILE "$pid\n";
992     close( LOCK_FILE );
993     if( !$foreground ) { 
994         exit( 0 ) 
995     };
998 # connect to gosa-si job queue
999 my @job_col_names = ("timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1000 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1001 $job_db->create_table('jobs', \@job_col_names);
1003 # connect to known_clients_db
1004 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1005 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1006 $known_clients_db->create_table('known_clients', \@clients_col_names);
1008 # connect to known_server_db
1009 my @server_col_names = ();
1011 # import all modules
1012 &import_modules;
1014 # check wether all modules are gosa-si valid passwd check
1016 # create reading and writing vectors
1017 my $rbits = my $wbits = my $ebits = "";
1019 # add all module inputs to listening vector
1020 while( my ($mod_name, $info) = each %$known_modules ) {
1021     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
1022     vec($rbits, fileno $input, 1) = 1;   
1027 ## start arp fifo
1028 #if ($no_arp > 0) {
1029 #    $arp_activ = "off";
1030 #}
1031 #my $my_fifo;
1032 #if($arp_activ eq "on") {
1033 #    daemon_log(" ", 1);
1034 #    $my_fifo = &open_fifo($arp_fifo_path);
1035 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
1036 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
1037 #    
1038 #    vec($rbits, fileno $arp_fifo, 1) = 1;
1039 #}
1043 ##################################
1044 #everything ready, okay, lets start
1045 ##################################
1046 while(1) {
1048     # add all handles from the childs
1049     while ( my ($pid, $child_hash) = each %busy_child ) {
1050         
1051         # check whether process still exists
1052         my $exitus_pid = waitpid($pid, WNOHANG);
1053         if($exitus_pid != 0) {
1054             delete $busy_child{$pid};
1055             next;
1056         }
1057      
1058         # add child fhd to the listener    
1059         my $fhd = $$child_hash{'pipe_rd'};
1060         vec($rbits, fileno $fhd, 1) = 1;
1061     }
1063     my ($rout, $wout);
1064     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1066     # error handling
1067     if($nf < 0 ) {
1068     }
1071 #    if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1072 #        my $in_msg = <$arp_fifo>;
1073 #        chomp($in_msg);
1074 #        print "arp_activ: msg: $in_msg\n";
1075 #        my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1076 #        print "arp_activ: arp_passwd: $act_passwd\n";
1078 #        my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1080 #        my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1082 #        if ($target eq $server_address) { 
1083 #             print "arp_activ: forward to server\n";
1084 #            my $arp_cipher = &create_ciphering($act_passwd);
1085 #            my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1086 #            &activating_child($crypted_msg, $server_ip);
1087 #        } else {
1088 #            print "arp_activ: send to bus\n";
1089 #            &send_msg_hash2address($in_msg_hash, $bus_address);
1090 #        }
1091 #        print "\n";
1092 #    }
1095     # check input fhd of all modules 
1096     while ( my ($mod_name, $info) = each %$known_modules) {
1097         my $input_fhd = @{$info}[2];    
1098         my $input_activ = @{$info}[3];
1099         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1100             daemon_log(" ", 1);
1101             my $client = $input_fhd->accept();
1102             my $other_end = getpeername($client);
1103             if(not defined $other_end) {
1104                 daemon_log("client cannot be identified: $!");
1105             } else {
1106                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1107                 my $actual_ip = inet_ntoa($iaddr);
1108                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1109                 my $in_msg = &read_from_socket($client);
1110                 if(defined $in_msg){
1111                     chomp($in_msg);
1112                     &activating_child($in_msg, $actual_ip, $client);
1113                 } else {
1114                     daemon_log("cannot read from $actual_ip", 5);
1115                 }
1116             }
1117         }
1118     }
1120     # check all processing childs whether they are finished ('done') or 
1121     while ( my ($pid, $child_hash) = each %busy_child ) {
1122         my $fhd = $$child_hash{'pipe_rd'};
1124         if (vec($rout, fileno $fhd, 1) ) {
1125             daemon_log("process child $pid is ready to read", 5);
1127             $fhd->blocking(1);
1128             my $in_msg = <$fhd>;
1129             $fhd->blocking(0);
1130             my $part_in_msg;
1131             while ($part_in_msg = <$fhd>) {
1132                 if (not defined $part_in_msg) {
1133                     last;
1134                 }
1135                 $in_msg .= $part_in_msg;
1136             }
1137             chomp($in_msg);
1139             daemon_log("process child read: $in_msg", 5);
1140             if (not defined $in_msg) { 
1141                 next; 
1142             } elsif ($in_msg =~ "done") {
1143                 delete $busy_child{$pid};
1144                 $free_child{$pid} = $child_hash;
1145  
1146             } else {
1147                 # send computed answer back to connected client
1148                 my $act_client = $busy_child{$pid}{client_ref};
1149                 print $act_client $in_msg."\n";
1151                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1152                 delete $busy_child{$pid};
1153                 $free_child{$pid} = $child_hash;
1155                 # give the client a chance to read 
1156                 sleep(2);
1157                 close ($act_client);   
1158             }
1159         }
1160     }
1162     # check gosa job queue for jobs with executable timestamp
1163     my ($seconds, $minutes, $hours, $monthday, $month,
1164     $year, $weekday, $yearday, $sommertime) = localtime(time);
1165     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1166     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1167     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1168     $month+=1;
1169     $month = $month < 10 ? $month = "0".$month : $month;
1170     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1171     $year+=1900;
1172     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1173     
1174     
1175     my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp  } );
1177     while( my ($id, $hit) = each %{$res} ) {         
1179         my $jobdb_id = $hit->{ROWID};
1180         my $macaddress = $hit->{macaddress};
1181         my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1182         my $out_msg_hash = $job_msg_hash;
1183         my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1184         # expect macaddress is unique!!!!!!
1185         my $target = $res_hash->{1}->{hostname};
1186         
1187         if (not defined $target) {
1188             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1189             &daemon_log("xml message: $hit->{xmlmessage}", 5);
1190             my $update_hash = { table=>$job_queue_table_name,
1191                 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1192                 where=> [ { ROWID=>[$jobdb_id] } ],
1193             };
1194             my $res = $job_db->update_dbentry($update_hash);
1196             next;
1197         }
1199         # add target
1200         &add_content2xml_hash($out_msg_hash, "target", $target);
1202         # add new header
1203         my $out_header = $job_msg_hash->{header}[0];
1204         $out_header =~ s/job_/gosa_/;
1205         delete $out_msg_hash->{header};
1206         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1207         
1208         # add sqlite_id 
1209         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1210     
1211         my $out_msg = &create_xml_string($out_msg_hash);
1213         # encrypt msg as a GosaPackage module
1214         my $cipher = &create_ciphering($gosa_passwd);
1215         my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1217         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1219 #######################
1220 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1222         if ($error == 0) {
1223             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1224             my $res = $job_db->exec_statement($sql);
1225         } else {
1226             my $update_hash = { table=>$job_queue_table_name, 
1227                                 update=> [ { status=>'error' } ],
1228                                 where=> [ { ROWID=>$jobdb_id } ],
1229                               };
1230             my $res = $job_db->update_dbentry($update_hash);
1231         }
1233     }