Code

Replaced ou=devices/ou=macro/ou=conferences with get_ou
[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 libipc-shareable-perl libdata-dumper-simple-perl
12 #         BUGS:  ---
13 #        NOTES:
14 #       AUTHOR:   (Andreas Rettenberger), <rettenberger@gonicus.de>
15 #      COMPANY:
16 #      VERSION:  1.0
17 #      CREATED:  12.09.2007 08:54:41 CEST
18 #     REVISION:  ---
19 #===============================================================================
22 use strict;
23 use warnings;
24 use Getopt::Long;
25 use Config::IniFiles;
26 use POSIX;
27 use Time::HiRes qw( gettimeofday );
29 use Fcntl;
30 use IO::Socket::INET;
31 use Crypt::Rijndael;
32 use MIME::Base64;
33 use Digest::MD5  qw(md5 md5_hex md5_base64);
34 use XML::Simple;
35 use Data::Dumper;
36 use Sys::Syslog qw( :DEFAULT setlogsock);
37 use Cwd;
38 use File::Spec;
39 use IPC::Shareable qw( :lock);
40 IPC::Shareable->clean_up_all;
41 use GosaSupportDaemon;
43 use lib "/etc/gosa-si/modules";
44 my $modules_path = "/etc/gosa-si/modules";
46 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
47 my ($bus, $msg_to_bus, $bus_cipher);
48 my ($server, $server_mac_address, $server_events);
49 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name);
50 my ($known_daemons, $shmda, $known_clients, $shmcl, $known_modules);
51 my ($max_clients);
52 my ($pid_file, $procid, $pid, $log_file);
53 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
54 my ($arp_activ, $arp_fifo, $arp_fifo_path);
56 # variables declared in config file are always set to 'our'
57 our (%cfg_defaults, $log_file, $pid_file, 
58     $bus_activ, $bus_passwd, $bus_ip, $bus_port,
59     $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
60     $arp_activ, $arp_fifo_path,
61     $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
62 );
64 # additional variable which should be globaly accessable
65 our $xml;
66 our $server_address;
67 our $bus_address;
68 our $gosa_address;
69 our $no_bus;
70 our $no_arp;
71 our $verbose;
72 our $forground;
73 our $cfg_file;
75 # specifies the verbosity of the daemon_log
76 $verbose = 0 ;
78 # if foreground is not null, script will be not forked to background
79 $foreground = 0 ;
81 # specifies the timeout seconds while checking the online status of a registrating client
82 $ping_timeout = 5;
84 $no_bus = 0;
86 $no_arp = 0;
88 # name of table for storing gosa jobs
89 $job_queue_table_name = 'jobs';
91 # holds all other gosa-sd as well as the gosa-sd-bus
92 our $known_daemons = {};
93 our $shmda = tie($known_daemons, 'IPC::Shareable', undef, {create => 1, 
94                                                             exclusive => 1, 
95                                                             mode => 0666, 
96                                                             destroy => 1,
97                                                             });
98 # holds all registrated clients
99 our $known_clients = {};
100 our $shmcl = tie($known_clients, 'IPC::Shareable', undef, {create => 1, 
101                                                             exclusive => 1, 
102                                                             mode => 0666, 
103                                                             destroy => 1,
104                                                             });
107 %cfg_defaults =
108 ("general" =>
109     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
110     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
111     "child_max" => [\$child_max, 10],
112     "child_min" => [\$child_min, 3],
113     "child_timeout" => [\$child_timeout, 180],
114     "job_queue_timeout" => [\$job_queue_timeout, undef],
115     "job_queue_file_name" => [\$job_queue_file_name, '/tmp/jobs.db'],
116    },
117 "bus" =>
118     {"bus_activ" => [\$bus_activ, "on"],
119     "bus_passwd" => [\$bus_passwd, ""],
120     "bus_ip" => [\$bus_ip, ""],
121     "bus_port" => [\$bus_port, "20080"],
122     },
123 "server" =>
124     {"server_activ" => [\$server_activ, "on"],
125     "server_ip" => [\$server_ip, ""],
126     "server_port" => [\$server_port, "20081"],
127     "server_passwd" => [\$server_passwd, ""],
128     "max_clients" => [\$max_clients, 100],
129     },
130 "arp" =>
131     {"arp_activ" => [\$arp_activ, "on"],
132     "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
133     },
134 "gosa" =>
135     {"gosa_activ" => [\$gosa_activ, "on"],
136     "gosa_ip" => [\$gosa_ip, ""],
137     "gosa_port" => [\$gosa_port, "20082"],
138     "gosa_passwd" => [\$gosa_passwd, "none"],
139     },
140     );
143 #===  FUNCTION  ================================================================
144 #         NAME:  usage
145 #   PARAMETERS:  nothing
146 #      RETURNS:  nothing
147 #  DESCRIPTION:  print out usage text to STDERR
148 #===============================================================================
149 sub usage {
150     print STDERR << "EOF" ;
151 usage: $0 [-hvf] [-c config]
153            -h        : this (help) message
154            -c <file> : config file
155            -f        : foreground, process will not be forked to background
156            -v        : be verbose (multiple to increase verbosity)
157            -no-bus   : starts $0 without connection to bus
158            -no-arp   : starts $0 without connection to arp module
159  
160 EOF
161     print "\n" ;
165 #===  FUNCTION  ================================================================
166 #         NAME:  read_configfile
167 #   PARAMETERS:  cfg_file - string -
168 #      RETURNS:  nothing
169 #  DESCRIPTION:  read cfg_file and set variables
170 #===============================================================================
171 sub read_configfile {
172     my $cfg;
173     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
174         if( -r $cfg_file ) {
175             $cfg = Config::IniFiles->new( -file => $cfg_file );
176         } else {
177             print STDERR "Couldn't read config file!";
178         }
179     } else {
180         $cfg = Config::IniFiles->new() ;
181     }
182     foreach my $section (keys %cfg_defaults) {
183         foreach my $param (keys %{$cfg_defaults{ $section }}) {
184             my $pinfo = $cfg_defaults{ $section }{ $param };
185             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
186         }
187     }
191 #===  FUNCTION  ================================================================
192 #         NAME:  logging
193 #   PARAMETERS:  level - string - default 'info'
194 #                msg - string -
195 #                facility - string - default 'LOG_DAEMON'
196 #      RETURNS:  nothing
197 #  DESCRIPTION:  function for logging
198 #===============================================================================
199 sub daemon_log {
200     # log into log_file
201     my( $msg, $level ) = @_;
202     if(not defined $msg) { return }
203     if(not defined $level) { $level = 1 }
204     if(defined $log_file){
205         open(LOG_HANDLE, ">>$log_file");
206         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
207             print STDERR "cannot open $log_file: $!";
208             return }
209             chomp($msg);
210             if($level <= $verbose){
211                 print LOG_HANDLE "$level $msg\n";
212                 if(defined $foreground) { print $msg."\n" }
213             }
214     }
215 #    close( LOG_HANDLE );
216 #log into syslog
217 #    my ($msg, $level, $facility) = @_;
218 #    if(not defined $msg) {return}
219 #    if(not defined $level) {$level = "info"}
220 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
221 #    openlog($0, "pid,cons,", $facility);
222 #    syslog($level, $msg);
223 #    closelog;
224 #    return;
228 #===  FUNCTION  ================================================================
229 #         NAME:  check_cmdline_param
230 #   PARAMETERS:  nothing
231 #      RETURNS:  nothing
232 #  DESCRIPTION:  validates commandline parameter
233 #===============================================================================
234 sub check_cmdline_param () {
235     my $err_config;
236     my $err_counter = 0;
237     if( not defined( $cfg_file)) {
238         #$err_config = "please specify a config file";
239         #$err_counter += 1;
240         my $cwd = getcwd;
241         my $name = "/etc/gosa-si/server.conf";
242         $cfg_file = File::Spec->catfile( $cwd, $name );
243     }
244     if( $err_counter > 0 ) {
245         &usage( "", 1 );
246         if( defined( $err_config)) { print STDERR "$err_config\n"}
247         print STDERR "\n";
248         exit( -1 );
249     }
253 #===  FUNCTION  ================================================================
254 #         NAME:  check_pid
255 #   PARAMETERS:  nothing
256 #      RETURNS:  nothing
257 #  DESCRIPTION:  handels pid processing
258 #===============================================================================
259 sub check_pid {
260     $pid = -1;
261     # Check, if we are already running
262     if( open(LOCK_FILE, "<$pid_file") ) {
263         $pid = <LOCK_FILE>;
264         if( defined $pid ) {
265             chomp( $pid );
266             if( -f "/proc/$pid/stat" ) {
267                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
268                 if( $0 eq $stat ) {
269                     close( LOCK_FILE );
270                     exit -1;
271                 }
272             }
273         }
274         close( LOCK_FILE );
275         unlink( $pid_file );
276     }
278     # create a syslog msg if it is not to possible to open PID file
279     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
280         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
281         if (open(LOCK_FILE, '<', $pid_file)
282                 && ($pid = <LOCK_FILE>))
283         {
284             chomp($pid);
285             $msg .= "(PID $pid)\n";
286         } else {
287             $msg .= "(unable to read PID)\n";
288         }
289         if( ! ($foreground) ) {
290             openlog( $0, "cons,pid", "daemon" );
291             syslog( "warning", $msg );
292             closelog();
293         }
294         else {
295             print( STDERR " $msg " );
296         }
297         exit( -1 );
298     }
302 #===  FUNCTION  ================================================================
303 #         NAME:  get_ip_and_mac 
304 #   PARAMETERS:  nothing
305 #      RETURNS:  (ip, mac) 
306 #  DESCRIPTION:  executes /sbin/ifconfig and parses the output, the first occurence 
307 #                of a inet address is returned as well as the mac address in the line
308 #                above the inet address
309 #===============================================================================
310 sub get_ip_and_mac {
311     my $ip = "0.0.0.0.0"; # Defualt-IP
312     my $mac = "00:00:00:00:00:00";  # Default-MAC
313     my @ifconfig = qx(/sbin/ifconfig);
314     foreach(@ifconfig) {
315         if (/Hardware Adresse (\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/) {
316             $mac = "$1:$2:$3:$4:$5:$6";
317             next;
318         }
319         if (/inet Adresse:(\d+).(\d+).(\d+).(\d+)/) {
320             $ip = "$1.$2.$3.$4";
321             last;
322         }
323     }
324     return ($ip, $mac);
329 #===  FUNCTION  ================================================================
330 #         NAME:  import_modules
331 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
332 #                are stored
333 #      RETURNS:  nothing
334 #  DESCRIPTION:  each file in module_path which ends with '.pm' is imported by 
335 #                "require 'file';"
336 #===============================================================================
337 sub import_modules {
338     daemon_log(" ", 1);
340     if (not -e $modules_path) {
341         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
342     }
344     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
345     while (defined (my $file = readdir (DIR))) {
346         if (not $file =~ /(\S*?).pm$/) {
347             next;
348         }
349         eval { require $file; };
350         if ($@) {
351             daemon_log("ERROR: gosa-sd could not load module $file", 1);
352             daemon_log("$@", 5);
353             next;
354         }
355         my $mod_name = $1;
356         #my $module_tag_hash = eval( $mod_name.'::get_module_tags()' );
358         my $info = eval($mod_name.'::get_module_info()');
359         my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
360         $known_modules->{$mod_name} = $info;
362         daemon_log("module $mod_name loaded", 1);
363     }   
365     # for debugging
366     #while ( my ($module, $tag_hash) = each(%$known_modules)) {
367     #    print "\tmodule: $module"."\n";   
368     #    print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
369     #}
370     close (DIR);
374 #===  FUNCTION  ================================================================
375 #         NAME:  sig_int_handler
376 #   PARAMETERS:  signal - string - signal arose from system
377 #      RETURNS:  noting
378 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
379 #===============================================================================
380 sub sig_int_handler {
381     my ($signal) = @_;
382     if($server){
383         close($server);
384         daemon_log("daemon server closed", 1);
385     }
386     if( -p $arp_fifo_path ) {
387         close $arp_fifo  ;
388         unlink($arp_fifo_path) ;
389         daemon_log("ARP_FIFO closed", 1) ;
390     }
392     if($gosa_server){
393         close($gosa_server);
394         daemon_log("gosa server closed", 1);
395     }
397     print STDERR "$signal\n";
398     
399     exit(1);
401 $SIG{INT} = \&sig_int_handler;
404 #===  FUNCTION  ================================================================
405 #         NAME:  activating_child
406 #   PARAMETERS:  msg - string - incoming message
407 #                host - string - host from which the incomming message comes
408 #      RETURNS:  nothing
409 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
410 #===============================================================================
411 sub activating_child {
412     my ($msg, $host, $client) = @_;
413     my $child = &get_processing_child();
414     my $pipe_wr = $$child{'pipe_wr'};
415     my $pipe_rd = $$child{'pipe_rd'};
416     $$child{client_ref} = $client;
417     
418     daemon_log("activating: childpid:$$child{'pid'}", 5);
420     print $pipe_wr $msg.".".$host."\n";
422     return;
426 #===  FUNCTION  ================================================================
427 #         NAME:  get_processing_child
428 #   PARAMETERS:  nothing
429 #      RETURNS:  child - hash - holding the process id and the references to the pipe
430 #                               handles pipe_wr and pipe_rd
431 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
432 #===============================================================================
433 sub get_processing_child {
434     my $child;
436     while(my ($key, $val) = each(%free_child)) {
437         my $exitus_pid = waitpid($key, WNOHANG);
438         if($exitus_pid != 0) {
439             delete $free_child{$key};
440         }
441         daemon_log("free child:$key", 5);
442     }
443     # check @free_child and @busy_child
444     my $free_len = scalar(keys(%free_child));
445     my $busy_len = scalar(keys(%busy_child));
446     daemon_log("free children $free_len, busy children $busy_len", 5);
448     # if there is a free child, let the child work
449     if($free_len > 0){
450         my @keys = keys(%free_child);
451         $child = $free_child{$keys[0]};
452         if(defined $child) {
453             $busy_child{$$child{'pid'}} = $child ;
454             delete $free_child{$$child{'pid'}};
455         }
456         return $child;
457     }
459     # no free child, try to fork another one
460     if($free_len + $busy_len < $child_max) {
462         daemon_log("not enough children, create a new one", 5);
464         # New pipes for communication
465         my( $PARENT_wr, $PARENT_rd );
466         my( $CHILD_wr, $CHILD_rd );
467         pipe( $CHILD_rd,  $PARENT_wr );
468         pipe( $PARENT_rd, $CHILD_wr  );
469         $PARENT_wr->autoflush(1);
470         $CHILD_wr->autoflush(1);
472         ############
473         # fork child
474         ############
475         my $child_pid = fork();
476         
477         #CHILD
478         if($child_pid == 0) {
479             # Close unused pipes
480             close( $CHILD_rd );
481             close( $CHILD_wr );
482             while( 1 ) {
483                 my $rbits = "";
484                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
485                 my $nf = select($rbits, undef, undef, $child_timeout);
486                 if($nf < 0 ) {
487                     die "select(): $!\n";
488                 } elsif (! $nf) {
489                     # if already child_min childs are alive, then leave loop
490                     $free_len = scalar(keys(%free_child));
491                     $busy_len = scalar(keys(%busy_child));
492                     if($free_len + $busy_len >= $child_min) {
493                         last;
494                     } else {
495                         redo;
496                     }
497                 }
499                 # a job for a child arise
500                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
501                     # read everything from pipe
502                     my $msg = "";
503                     $PARENT_rd->blocking(0);
504                     while(1) {
505                         my $read = <$PARENT_rd>;
506                         if(not defined $read) { last}
507                         $msg .= $read;
508                     }
510                     ######################################
511                     # forward msg to all imported modules 
512                     no strict "refs";
513                     my $answer;
514                     my %act_modules = %$known_modules;
515                     while( my ($module, $info) = each(%act_modules)) {
516                             my $tmp = &{ $module."::process_incoming_msg" }($msg);
517                             if (defined $tmp) {
518                                 $answer = $tmp;
519                             }
520                     }        
522                     #&print_known_daemons();
523                     #&print_known_clients();
525                     daemon_log("processing of msg finished", 5);
526  
527                    if (defined $answer) {
528                         print $PARENT_wr $answer."\n";
529                         daemon_log("with answer: $answer", 5);
530                         daemon_log(" ", 5);
531                     } else {
532                         print $PARENT_wr "done"."\n";
533                         daemon_log(" ", 5);
534                     }
535                     redo;
536                 }
537             }
538             # childs leaving the loop are allowed to die
539             exit(0);
542         #PARENT
543         } else {
544             # Close unused pipes
545             close( $PARENT_rd );
546             close( $PARENT_wr );
548             # add child to child alive hash
549             my %child_hash = (
550                     'pid' => $child_pid,
551                     'pipe_wr' => $CHILD_wr,
552                     'pipe_rd' => $CHILD_rd,
553                     'client_ref' => "",
554                     );
556             $child = \%child_hash;
557             $busy_child{$$child{'pid'}} = $child;
558             return $child;
559         }
560     }
564 #===  FUNCTION  ================================================================
565 #         NAME:  read_from_socket
566 #   PARAMETERS:  socket fh - 
567 #      RETURNS:  result string - readed characters from socket
568 #  DESCRIPTION:  reads data from socket in 16 byte steps
569 #===============================================================================
570 sub read_from_socket {
571     my ($socket) = @_;
572     my $result = "";
574     $socket->blocking(1);
575     $result = <$socket>;
577     $socket->blocking(0);
578     while ( my $char = <$socket> ) {
579         if (not defined $char) { last }
580         $result .= $char;
581     }
583     return $result;
587 #===  FUNCTION  ================================================================
588 #         NAME:  print_known_daemons
589 #   PARAMETERS:  nothing
590 #      RETURNS:  nothing
591 #  DESCRIPTION:  nomen est omen
592 #===============================================================================
593 sub print_known_daemons {
594     my ($tmp) = @_ ;
595     print "####################################\n";
596     print "# status of known_daemons\n";
597     $shmda->shlock(LOCK_EX);
598     my @hosts = keys %$known_daemons;
599     foreach my $host (@hosts) {
600         my $status = $known_daemons->{$host}->{status} ;
601         my $passwd = $known_daemons->{$host}->{passwd};
602         my $timestamp = $known_daemons->{$host}->{timestamp};
603         print "$host\n";
604         print "\tstatus:    $status\n";
605         print "\tpasswd:    $passwd\n";
606         print "\ttimestamp: $timestamp\n";
607     }
608     $shmda->shunlock(LOCK_EX);
609     print "####################################\n";
610     return;
614 #===  FUNCTION  ================================================================
615 #         NAME:  create_known_daemon
616 #   PARAMETERS:  hostname - string - key for the hash known_daemons
617 #      RETURNS:  nothing
618 #  DESCRIPTION:  creates a dummy entry for hostname in known_daemons
619 #===============================================================================
620 sub create_known_daemon {
621     my ($hostname) = @_;
622     $shmda->shlock(LOCK_EX);
623     $known_daemons->{$hostname} = {};
624     $known_daemons->{$hostname}->{status} = "none";
625     $known_daemons->{$hostname}->{passwd} = "none";
626     $known_daemons->{$hostname}->{timestamp} = "none";
627     $shmda->shunlock(LOCK_EX); 
628     return;  
632 #===  FUNCTION  ================================================================
633 #         NAME:  add_content2known_daemons
634 #   PARAMETERS:  hostname - string - ip address and port of host (required)
635 #                status - string - (optional)
636 #                passwd - string - (optional)
637 #                mac_address - string - mac address of host (optional)
638 #      RETURNS:  nothing
639 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
640 #===============================================================================
641 sub add_content2known_daemons {
642     my $arg = {
643         hostname => undef, status => undef, passwd => undef,
644         mac_address => undef, events => undef, 
645         @_ };
646     my $hostname = $arg->{hostname};
647     my $status = $arg->{status};
648     my $passwd = $arg->{passwd};
649     my $mac_address = $arg->{mac_address};
650     my $events = $arg->{events};
652     if (not defined $hostname) {
653         daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
654         return;
655     }
657     my ($seconds, $minutes, $hours, $monthday, $month,
658     $year, $weekday, $yearday, $sommertime) = localtime(time);
659     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
660     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
661     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
662     $month+=1;
663     $month = $month < 10 ? $month = "0".$month : $month;
664     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
665     $year+=1900;
666     my $t = "$year$month$monthday$hours$minutes$seconds";
667     
668     $shmda->shlock(LOCK_EX);
669     if (defined $status) {
670         $known_daemons->{$hostname}->{status} = $status;
671     }
672     if (defined $passwd) {
673         $known_daemons->{$hostname}->{passwd} = $passwd;
674     }
675     if (defined $mac_address) {
676         $known_daemons->{$hostname}->{mac_address} = $mac_address;
677     }
678     if (defined $events) {
679         $known_daemons->{$hostname}->{events} = $events;
680     }
681     $known_daemons->{$hostname}->{timestamp} = $t;
682     $shmda->shlock(LOCK_EX);
683     return;
687 #===  FUNCTION  ================================================================
688 #         NAME:  update_known_daemons
689 #   PARAMETERS:  hostname - string - ip address and port of host (required)
690 #                status - string - (optional)
691 #                passwd - string - (optional)
692 #                client - string - ip address and port of client (optional)
693 #      RETURNS:  nothing
694 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
695 #===============================================================================
696 sub update_known_daemons {
697     my $arg = {
698         hostname => undef, status => undef, passwd => undef,
699         @_ };
700     my $hostname = $arg->{hostname};
701     my $status = $arg->{status};
702     my $passwd = $arg->{passwd};
704     if (not defined $hostname) {
705         daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
706         return;
707     }
709     my ($seconds, $minutes, $hours, $monthday, $month,
710     $year, $weekday, $yearday, $sommertime) = localtime(time);
711     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
712     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
713     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
714     $month+=1;
715     $month = $month < 10 ? $month = "0".$month : $month;
716     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
717     $year+=1900;
718     my $t = "$year$month$monthday$hours$minutes$seconds";
720     $shmda->shlock(LOCK_EX);
721     if (defined $status) {
722         $known_daemons->{$hostname}->{status} = $status;
723     }
724     if (defined $passwd) {
725         $known_daemons->{$hostname}->{passwd} = $passwd;
726     }
727     $known_daemons->{$hostname}->{timestamp} = $t;
728     $shmda->shunlock(LOCK_EX);
729     return;
733 #===  FUNCTION  ================================================================
734 #         NAME:  print_known_clients 
735 #   PARAMETERS:  nothing
736 #      RETURNS:  nothing
737 #  DESCRIPTION:  nomen est omen
738 #===============================================================================
739 sub print_known_clients {
741     print "####################################\n";
742     print "# status of known_clients\n";
743     $shmcl->shlock(LOCK_EX);
744     my @hosts = keys %$known_clients;
745     if (@hosts) {
746         foreach my $host (@hosts) {
747             my $status = $known_clients->{$host}->{status} ;
748             my $passwd = $known_clients->{$host}->{passwd};
749             my $timestamp = $known_clients->{$host}->{timestamp};
750             my $mac_address = $known_clients->{$host}->{mac_address};
751             my $events = $known_clients->{$host}->{events};
752             print "$host\n";
753             print "\tstatus:      $status\n";
754             print "\tpasswd:      $passwd\n";
755             print "\ttimestamp:   $timestamp\n";
756             print "\tmac_address: $mac_address\n";
757             print "\tevents:      $events\n";
758         }
759     }
760     $shmcl->shunlock(LOCK_EX);
761     print "####################################\n";
762     return;
766 #===  FUNCTION  ================================================================
767 #         NAME:  create_known_client
768 #   PARAMETERS:  hostname - string - key for the hash known_clients
769 #      RETURNS:  nothing
770 #  DESCRIPTION:  creates a dummy entry for hostname in known_clients
771 #===============================================================================
772 sub create_known_client {
773     my ($hostname) = @_;
774     $shmcl->shlock(LOCK_EX);
775     $known_clients->{$hostname} = {};
776     $known_clients->{$hostname}->{status} = "none";
777     $known_clients->{$hostname}->{passwd} = "none";
778     $known_clients->{$hostname}->{timestamp} = "none";
779     $known_clients->{$hostname}->{mac_address} = "none";
780     $known_clients->{$hostname}->{events} = "none";
781     $shmcl->shunlock(LOCK_EX); 
782     return;  
786 #===  FUNCTION  ================================================================
787 #         NAME:  add_content2known_clients
788 #   PARAMETERS:  hostname - string - ip address and port of host (required)
789 #                status - string - (optional)
790 #                passwd - string - (optional)
791 #                mac_address - string - (optional)
792 #                events - string - event of client, executable skripts 
793 #                under /etc/gosac/events
794 #      RETURNS:  nothing
795 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
796 #===============================================================================
797 sub add_content2known_clients {
798     my $arg = {
799         hostname => undef, status => undef, passwd => undef,
800         mac_address => undef, events => undef, 
801         @_ };
802     my $hostname = $arg->{hostname};
803     my $status = $arg->{status};
804     my $passwd = $arg->{passwd};
805     my $mac_address = $arg->{mac_address};
806     my $events = $arg->{events};
808     if (not defined $hostname) {
809         daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
810         return;
811     }
813     my ($seconds, $minutes, $hours, $monthday, $month,
814     $year, $weekday, $yearday, $sommertime) = localtime(time);
815     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
816     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
817     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
818     $month+=1;
819     $month = $month < 10 ? $month = "0".$month : $month;
820     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
821     $year+=1900;
822     my $t = "$year$month$monthday$hours$minutes$seconds";
823     
824     $shmcl->shlock(LOCK_EX);
825     if (defined $status) {
826         $known_clients->{$hostname}->{status} = $status;
827     }
828     if (defined $passwd) {
829         $known_clients->{$hostname}->{passwd} = $passwd;
830     }
831     if (defined $mac_address) {
832         $known_clients->{$hostname}->{mac_address} = $mac_address;
833     }
834     if (defined $events) {
835         $known_clients->{$hostname}->{events} = $events;
836     }
837     $known_clients->{$hostname}->{timestamp} = $t;
838     $shmcl->shlock(LOCK_EX);
839     return;
841  
843 #===  FUNCTION  ================================================================
844 #         NAME:  
845 #   PARAMETERS:  
846 #      RETURNS:  
847 #  DESCRIPTION:  
848 #===============================================================================    
849 sub clean_up_known_clients {
850     my ($address) = @_ ;
851     
852     if (not exists $known_clients->{$address}) {
853         daemon_log("cannot prune known_clients from $address, client not known", 5);
854         return;
855     }
857     delete $known_clients->{$address};
859     # send bus a msg that address was deleted from known_clients
860     my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
861     &send_msg_hash2bus($out_hash);
863     daemon_log("client $address deleted from known_clients because of multiple down time", 3);
864     return;
868 #===  FUNCTION  ================================================================
869 #         NAME:  update_known_clients
870 #   PARAMETERS:  hostname - string - ip address and port of host (required)
871 #                status - string - (optional)
872 #                passwd - string - (optional)
873 #                client - string - ip address and port of client (optional)
874 #      RETURNS:  nothing
875 #  DESCRIPTION:  nome est omen and updates each time the timestamp of hostname
876 #===============================================================================
877 sub update_known_clients {
878     my $arg = {
879         hostname => undef, status => undef, passwd => undef,
880         mac_address => undef, events => undef,
881         @_ };
882     my $hostname = $arg->{hostname};
883     my $status = $arg->{status};
884     my $passwd = $arg->{passwd};
885     my $mac_address = $arg->{mac_address};
886     my $events = $arg->{events};
888     if (not defined $hostname) {
889         daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
890         return;
891     }
893     my ($seconds, $minutes, $hours, $monthday, $month,
894     $year, $weekday, $yearday, $sommertime) = localtime(time);
895     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
896     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
897     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
898     $month+=1;
899     $month = $month < 10 ? $month = "0".$month : $month;
900     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
901     $year+=1900;
902     my $t = "$year$month$monthday$hours$minutes$seconds";
904     $shmcl->shlock(LOCK_EX);
905     if (defined $status) {
906         $known_clients->{$hostname}->{status} = $status;
907     }
908     if (defined $passwd) {
909         $known_clients->{$hostname}->{passwd} = $passwd;
910     }
911     if (defined $mac_address) {
912         $known_clients->{$hostname}->{mac_address} = $mac_address; 
913     }
914     if (defined $events) {
915         $known_clients->{$hostname}->{events} = $events;
916     }
917     $known_clients->{$hostname}->{timestamp} = $t;
918     $shmcl->shunlock(LOCK_EX);
919     return;
928 #==== MAIN = main ==============================================================
930 #  parse commandline options
931 Getopt::Long::Configure( "bundling" );
932 GetOptions("h|help" => \&usage,
933         "c|config=s" => \$cfg_file,
934         "f|foreground" => \$foreground,
935         "v|verbose+" => \$verbose,
936         "no-bus+" => \$no_bus,
937         "no-arp+" => \$no_arp,
938            );
940 #  read and set config parameters
941 &check_cmdline_param ;
942 &read_configfile;
943 &check_pid;
945 $SIG{CHLD} = 'IGNORE';
947 # restart daemon log file
948 if(-e $log_file ) { unlink $log_file }
949 daemon_log(" ", 1);
950 daemon_log("$0 started!", 1);
952 # Just fork, if we"re not in foreground mode
953 if( ! $foreground ) { $pid = fork(); }
954 else { $pid = $$; }
956 # Do something useful - put our PID into the pid_file
957 if( 0 != $pid ) {
958     open( LOCK_FILE, ">$pid_file" );
959     print LOCK_FILE "$pid\n";
960 close( LOCK_FILE );
961     if( !$foreground ) { exit( 0 ) };
964 # import all modules
965 &import_modules;
967 # check wether all modules are gosa-si valid passwd check
969 # connect to gosa-si job queue
970 my $job_db = DBsqlite->new($job_queue_file_name);
972 # create reading and writing vectors
973 my $rbits = my $wbits = my $ebits = "";
975 # add all module inputs to listening vector
976 while( my ($mod_name, $info) = each %$known_modules ) {
977     my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
978     vec($rbits, fileno $input, 1) = 1;   
983 ## start arp fifo
984 #if ($no_arp > 0) {
985 #    $arp_activ = "off";
986 #}
987 #my $my_fifo;
988 #if($arp_activ eq "on") {
989 #    daemon_log(" ", 1);
990 #    $my_fifo = &open_fifo($arp_fifo_path);
991 #    if($my_fifo == 0) { die "fifo file disappeared\n" }
992 #    sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
993 #    
994 #    vec($rbits, fileno $arp_fifo, 1) = 1;
995 #}
999 ##################################
1000 #everything ready, okay, lets start
1001 ##################################
1002 while(1) {
1004     # add all handles from the childs
1005     while ( my ($pid, $child_hash) = each %busy_child ) {
1006         
1007         # check whether process still exists
1008         my $exitus_pid = waitpid($pid, WNOHANG);
1009         if($exitus_pid != 0) {
1010             delete $busy_child{$pid};
1011             next;
1012         }
1013      
1014         # add child fhd to the listener    
1015         my $fhd = $$child_hash{'pipe_rd'};
1016         vec($rbits, fileno $fhd, 1) = 1;
1017     }
1019     my ($rout, $wout);
1020     my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1022     # error handling
1023     if($nf < 0 ) {
1024     }
1027     if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1028         my $in_msg = <$arp_fifo>;
1029         chomp($in_msg);
1030         print "arp_activ: msg: $in_msg\n";
1031         my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1032         print "arp_activ: arp_passwd: $act_passwd\n";
1034         my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1036         my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1038         if ($target eq $server_address) { 
1039              print "arp_activ: forward to server\n";
1040             my $arp_cipher = &create_ciphering($act_passwd);
1041             my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1042             &activating_child($crypted_msg, $server_ip);
1043         } else {
1044             print "arp_activ: send to bus\n";
1045             &send_msg_hash2address($in_msg_hash, $bus_address);
1046         }
1047         print "\n";
1048     }
1051     # check input fhd of all modules 
1052     while ( my ($mod_name, $info) = each %$known_modules) {
1053         my $input_fhd = @{$info}[2];    
1054         my $input_activ = @{$info}[3];
1055         if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1056             daemon_log(" ", 1);
1057             my $client = $input_fhd->accept();
1058             my $other_end = getpeername($client);
1059             if(not defined $other_end) {
1060                 daemon_log("client cannot be identified: $!");
1061             } else {
1062                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1063                 my $actual_ip = inet_ntoa($iaddr);
1064                 daemon_log("accept client at daemon socket from $actual_ip", 5);
1065                 my $in_msg = &read_from_socket($client);
1066                 if(defined $in_msg){
1067                     chomp($in_msg);
1068                     &activating_child($in_msg, $actual_ip, $client);
1069                 } else {
1070                     daemon_log("cannot read from $actual_ip", 5);
1071                 }
1072             }
1073             #close($client);
1075         }
1076     }
1078     # check all processing childs whether they are finished ('done') or 
1079     while ( my ($pid, $child_hash) = each %busy_child ) {
1080         my $fhd = $$child_hash{'pipe_rd'};
1082         if (vec($rout, fileno $fhd, 1) ) {
1083             daemon_log("process child $pid is ready to read", 5);
1085             $fhd->blocking(1);
1086             my $in_msg = <$fhd>;
1087             $fhd->blocking(0);
1088             my $part_in_msg;
1089             while ($part_in_msg = <$fhd>) {
1090                 if (not defined $part_in_msg) {
1091                     last;
1092                 }
1093                 $in_msg .= $part_in_msg;
1094             }
1095             chomp($in_msg);
1097             daemon_log("process child read: $in_msg", 5);
1098             if (not defined $in_msg) { 
1099                 next; 
1100             } elsif ($in_msg =~ "done") {
1101                 delete $busy_child{$pid};
1102                 $free_child{$pid} = $child_hash;
1103  
1104             } else {
1105                 # send computed answer back to connected client
1106                 my $act_client = $busy_child{$pid}{client_ref};
1107                 print $act_client $in_msg."\n";
1109                 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1110                 sleep(10);
1111                 close ($act_client);   
1112                 delete $busy_child{$pid};
1113                 $free_child{$pid} = $child_hash;
1115             }
1116         }
1117     }
1119     # check gosa job queue for jobs with executable timestamp
1120     print ">>>>>>>>>>>check gosa job queue ";
1121     my ($seconds, $minutes, $hours, $monthday, $month,
1122     $year, $weekday, $yearday, $sommertime) = localtime(time);
1123     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1124     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1125     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1126     $month+=1;
1127     $month = $month < 10 ? $month = "0".$month : $month;
1128     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1129     $year+=1900;
1130     my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1131     print "$timestamp\n";
1132     
1133     
1134     my $sql = "SELECT * FROM '$job_queue_table_name' WHERE status='waiting' AND timestamp<'$timestamp'";
1135     my $res = $job_db->exec_statement($sql);
1136     foreach my $msg (@{$res}) {
1137         
1138         my $jobdb_id = @{$msg}[0];
1139         my $job_msg_hash = &transform_msg2hash(@{$msg}[6]);
1140         my $out_msg_hash = $job_msg_hash;
1141     
1142         # hole mac address und suche die entsprechende ip addresse
1143         my $target;
1144         my @hostnames = keys %{$known_clients};
1145         foreach my $hostname (@hostnames) {
1146             if ($known_clients->{$hostname}->{mac_address} eq $job_msg_hash->{mac}[0]) {
1147                 $target = $hostname;
1148                 last;
1149             }
1150         }
1151         
1152         if (not defined $target) {
1153             &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1154             next;
1155         }
1157         # add target
1158         print "select: target: $target\n";
1159         &add_content2xml_hash($out_msg_hash, "target", $target);
1161         # add new header
1162         my $out_header = $job_msg_hash->{header}[0];
1163         $out_header =~ s/job_/gosa_/;
1164         print "select: header: $out_header\n";
1165         delete $out_msg_hash->{header};
1166         &add_content2xml_hash($out_msg_hash, "header", $out_header);
1167         
1168         # add sqlite_id 
1169         &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id); 
1170     
1171 #        my $out_msg = &create_xml_string($out_msg_hash);
1173 #        # encrypt msg as a GosaPackage module
1174 #        my $cipher = &create_ciphering($gosa_passwd);
1175 #        my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1177         my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1179         if ($error == 0) {
1180             my $sql = "UPDATE '$job_queue_table_name' SET status='processing', target='$target' WHERE id='$jobdb_id'";
1181             my $res = $job_db->exec_statement($sql);
1182         }
1185     }