3993ca464557399385db4e0e6682a69bda32388e
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
169 EOF
170 print "\n" ;
171 }
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 }
197 }
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(defined $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;
234 }
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 }
259 }
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 }
308 }
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);
334 }
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);
380 }
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";
408 exit(1);
409 }
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;
427 daemon_log("activating: childpid:$$child{'pid'}", 5);
429 print $pipe_wr $msg.".".$host."\n";
431 return;
432 }
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();
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);
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 }
572 }
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;
595 }
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;
640 }
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";
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;
695 }
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;
741 }
744 #=== FUNCTION ================================================================
745 # NAME: print_known_clients
746 # PARAMETERS: nothing
747 # RETURNS: nothing
748 # DESCRIPTION: nomen est omen
749 #===============================================================================
750 #sub print_known_clients {
751 #
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;
808 }
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";
850 my $change_entry = { table=>'known_clients',
851 where=>'hostname',
852 timestamp=>$t,
853 };
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 }
869 $known_clients->change_dbentry($change_entry);
870 return;
871 }
874 #=== FUNCTION ================================================================
875 # NAME:
876 # PARAMETERS:
877 # RETURNS:
878 # DESCRIPTION:
879 #===============================================================================
880 sub clean_up_known_clients {
881 my ($address) = @_ ;
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;
896 }
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};
918 #
919 # if (not defined $hostname) {
920 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
921 # return;
922 # }
923 #
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";
934 #
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 ) { $pid = fork(); }
983 else { $pid = $$; }
985 # Do something useful - put our PID into the pid_file
986 if( 0 != $pid ) {
987 open( LOCK_FILE, ">$pid_file" );
988 print LOCK_FILE "$pid\n";
989 close( LOCK_FILE );
990 if( !$foreground ) { exit( 0 ) };
991 }
993 # connect to gosa-si job queue
994 my @job_col_names = ("timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
995 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
996 $job_db->create_table('jobs', \@job_col_names);
998 # connect to known_clients_db
999 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1000 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1001 $known_clients_db->create_table('known_clients', \@clients_col_names);
1003 # connect to known_server_db
1004 my @server_col_names = ();
1006 # import all modules
1007 &import_modules;
1009 # check wether all modules are gosa-si valid passwd check
1011 # create reading and writing vectors
1012 my $rbits = my $wbits = my $ebits = "";
1014 # add all module inputs to listening vector
1015 while( my ($mod_name, $info) = each %$known_modules ) {
1016 my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
1017 vec($rbits, fileno $input, 1) = 1;
1019 }
1022 ## start arp fifo
1023 #if ($no_arp > 0) {
1024 # $arp_activ = "off";
1025 #}
1026 #my $my_fifo;
1027 #if($arp_activ eq "on") {
1028 # daemon_log(" ", 1);
1029 # $my_fifo = &open_fifo($arp_fifo_path);
1030 # if($my_fifo == 0) { die "fifo file disappeared\n" }
1031 # sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
1032 #
1033 # vec($rbits, fileno $arp_fifo, 1) = 1;
1034 #}
1035 #
1038 ##################################
1039 #everything ready, okay, lets start
1040 ##################################
1041 while(1) {
1043 # add all handles from the childs
1044 while ( my ($pid, $child_hash) = each %busy_child ) {
1046 # check whether process still exists
1047 my $exitus_pid = waitpid($pid, WNOHANG);
1048 if($exitus_pid != 0) {
1049 delete $busy_child{$pid};
1050 next;
1051 }
1053 # add child fhd to the listener
1054 my $fhd = $$child_hash{'pipe_rd'};
1055 vec($rbits, fileno $fhd, 1) = 1;
1056 }
1058 my ($rout, $wout);
1059 my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1061 # error handling
1062 if($nf < 0 ) {
1063 }
1066 if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1067 my $in_msg = <$arp_fifo>;
1068 chomp($in_msg);
1069 print "arp_activ: msg: $in_msg\n";
1070 my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1071 print "arp_activ: arp_passwd: $act_passwd\n";
1073 my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1075 my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1077 if ($target eq $server_address) {
1078 print "arp_activ: forward to server\n";
1079 my $arp_cipher = &create_ciphering($act_passwd);
1080 my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1081 &activating_child($crypted_msg, $server_ip);
1082 } else {
1083 print "arp_activ: send to bus\n";
1084 &send_msg_hash2address($in_msg_hash, $bus_address);
1085 }
1086 print "\n";
1087 }
1090 # check input fhd of all modules
1091 while ( my ($mod_name, $info) = each %$known_modules) {
1092 my $input_fhd = @{$info}[2];
1093 my $input_activ = @{$info}[3];
1094 if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1095 daemon_log(" ", 1);
1096 my $client = $input_fhd->accept();
1097 my $other_end = getpeername($client);
1098 if(not defined $other_end) {
1099 daemon_log("client cannot be identified: $!");
1100 } else {
1101 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1102 my $actual_ip = inet_ntoa($iaddr);
1103 daemon_log("accept client at daemon socket from $actual_ip", 5);
1104 my $in_msg = &read_from_socket($client);
1105 if(defined $in_msg){
1106 chomp($in_msg);
1107 &activating_child($in_msg, $actual_ip, $client);
1108 } else {
1109 daemon_log("cannot read from $actual_ip", 5);
1110 }
1111 }
1112 #close($client);
1114 }
1115 }
1117 # check all processing childs whether they are finished ('done') or
1118 while ( my ($pid, $child_hash) = each %busy_child ) {
1119 my $fhd = $$child_hash{'pipe_rd'};
1121 if (vec($rout, fileno $fhd, 1) ) {
1122 daemon_log("process child $pid is ready to read", 5);
1124 $fhd->blocking(1);
1125 my $in_msg = <$fhd>;
1126 $fhd->blocking(0);
1127 my $part_in_msg;
1128 while ($part_in_msg = <$fhd>) {
1129 if (not defined $part_in_msg) {
1130 last;
1131 }
1132 $in_msg .= $part_in_msg;
1133 }
1134 chomp($in_msg);
1136 daemon_log("process child read: $in_msg", 5);
1137 if (not defined $in_msg) {
1138 next;
1139 } elsif ($in_msg =~ "done") {
1140 delete $busy_child{$pid};
1141 $free_child{$pid} = $child_hash;
1143 } else {
1144 # send computed answer back to connected client
1145 my $act_client = $busy_child{$pid}{client_ref};
1146 print $act_client $in_msg."\n";
1148 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1149 delete $busy_child{$pid};
1150 $free_child{$pid} = $child_hash;
1152 # give the client a chance to read
1153 sleep(2);
1154 close ($act_client);
1155 }
1156 }
1157 }
1159 # check gosa job queue for jobs with executable timestamp
1160 my ($seconds, $minutes, $hours, $monthday, $month,
1161 $year, $weekday, $yearday, $sommertime) = localtime(time);
1162 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1163 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1164 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1165 $month+=1;
1166 $month = $month < 10 ? $month = "0".$month : $month;
1167 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1168 $year+=1900;
1169 my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1172 my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp } );
1174 while( my ($id, $hit) = each %{$res} ) {
1176 my $jobdb_id = $hit->{ROWID};
1177 my $macaddress = $hit->{macaddress};
1178 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1179 my $out_msg_hash = $job_msg_hash;
1180 my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1181 # expect macaddress is unique!!!!!!
1182 my $target = $res_hash->{1}->{hostname};
1184 if (not defined $target) {
1185 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1186 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1187 my $update_hash = { table=>$job_queue_table_name,
1188 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1189 where=> [ { ROWID=>[$jobdb_id] } ],
1190 };
1191 my $res = $job_db->update_dbentry($update_hash);
1193 next;
1194 }
1196 # add target
1197 print "select: target: $target\n";
1198 &add_content2xml_hash($out_msg_hash, "target", $target);
1200 # add new header
1201 my $out_header = $job_msg_hash->{header}[0];
1202 $out_header =~ s/job_/gosa_/;
1203 print "select: header: $out_header\n";
1204 delete $out_msg_hash->{header};
1205 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1207 # add sqlite_id
1208 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1210 my $out_msg = &create_xml_string($out_msg_hash);
1212 # encrypt msg as a GosaPackage module
1213 my $cipher = &create_ciphering($gosa_passwd);
1214 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1216 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1218 #######################
1219 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1221 if ($error == 0) {
1222 my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1223 my $res = $job_db->exec_statement($sql);
1224 } else {
1225 my $update_hash = { table=>$job_queue_table_name,
1226 update=> [ { status=>'error' } ],
1227 where=> [ { ROWID=>$jobdb_id } ],
1228 };
1229 my $res = $job_db->update_dbentry($update_hash);
1230 }
1232 }
1235 }