Code

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