b9a1cc6d662507f53cb537a5ec6ca165f66403f6
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-sd
5 #
6 # USAGE: ./gosa-sd
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl
12 # libipc-shareable-perl libdata-dumper-simple-perl
13 # libdbd-sqlite3-perl libnet-ldap-perl
14 # BUGS: ---
15 # NOTES:
16 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
17 # COMPANY:
18 # VERSION: 1.0
19 # CREATED: 12.09.2007 08:54:41 CEST
20 # REVISION: ---
21 #===============================================================================
24 use strict;
25 use warnings;
26 use Getopt::Long;
27 use Config::IniFiles;
28 use POSIX;
29 use Time::HiRes qw( gettimeofday );
31 use Fcntl;
32 use IO::Socket::INET;
33 use Crypt::Rijndael;
34 use MIME::Base64;
35 use Digest::MD5 qw(md5 md5_hex md5_base64);
36 use XML::Simple;
37 use Data::Dumper;
38 use Sys::Syslog qw( :DEFAULT setlogsock);
39 use Cwd;
40 use File::Spec;
41 use IPC::Shareable qw( :lock);
42 IPC::Shareable->clean_up_all;
43 use GOSA::GosaSupportDaemon;
44 use GOSA::DBsqlite;
46 my $modules_path = "/usr/lib/gosa-si/modules";
47 use lib "/usr/lib/gosa-si/modules";
49 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
50 my ($bus, $msg_to_bus, $bus_cipher);
51 my ($server, $server_mac_address, $server_events);
52 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name);
53 my ($known_modules, $known_clients_file_name, $known_server_file_name);
54 my ($max_clients);
55 my ($pid_file, $procid, $pid, $log_file);
56 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
57 my ($arp_activ, $arp_fifo, $arp_fifo_path);
59 # variables declared in config file are always set to 'our'
60 our (%cfg_defaults, $log_file, $pid_file,
61 $bus_activ, $bus_passwd, $bus_ip, $bus_port,
62 $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
63 $arp_activ, $arp_fifo_path,
64 $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
65 );
67 # additional variable which should be globaly accessable
68 our $xml;
69 our $server_address;
70 our $bus_address;
71 our $gosa_address;
72 our $no_bus;
73 our $no_arp;
74 our $verbose;
75 our $forground;
76 our $cfg_file;
78 # specifies the verbosity of the daemon_log
79 $verbose = 0 ;
81 # if foreground is not null, script will be not forked to background
82 $foreground = 0 ;
84 # specifies the timeout seconds while checking the online status of a registrating client
85 $ping_timeout = 5;
87 $no_bus = 0;
89 $no_arp = 0;
91 # name of table for storing gosa jobs
92 our $job_queue_table_name = 'jobs';
93 our $job_db;
95 # holds all other gosa-sd as well as the gosa-sd-bus
96 our $known_server_db;
98 # holds all registrated clients
99 our $known_clients_db;
101 %cfg_defaults =
102 ("general" =>
103 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
104 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
105 "child_max" => [\$child_max, 10],
106 "child_min" => [\$child_min, 3],
107 "child_timeout" => [\$child_timeout, 180],
108 "job_queue_timeout" => [\$job_queue_timeout, undef],
109 "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
110 "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/known_clients.db' ],
111 "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/known_server.db'],
112 },
113 "bus" =>
114 {"bus_activ" => [\$bus_activ, "on"],
115 "bus_passwd" => [\$bus_passwd, ""],
116 "bus_ip" => [\$bus_ip, ""],
117 "bus_port" => [\$bus_port, "20080"],
118 },
119 "server" =>
120 {"server_activ" => [\$server_activ, "on"],
121 "server_ip" => [\$server_ip, "0.0.0.0"],
122 "server_port" => [\$server_port, "20081"],
123 "server_passwd" => [\$server_passwd, ""],
124 "max_clients" => [\$max_clients, 100],
125 },
126 "arp" =>
127 {"arp_activ" => [\$arp_activ, "on"],
128 "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
129 },
130 "gosa" =>
131 {"gosa_activ" => [\$gosa_activ, "on"],
132 "gosa_ip" => [\$gosa_ip, ""],
133 "gosa_port" => [\$gosa_port, "20082"],
134 "gosa_passwd" => [\$gosa_passwd, "none"],
135 },
136 );
139 #=== FUNCTION ================================================================
140 # NAME: usage
141 # PARAMETERS: nothing
142 # RETURNS: nothing
143 # DESCRIPTION: print out usage text to STDERR
144 #===============================================================================
145 sub usage {
146 print STDERR << "EOF" ;
147 usage: $0 [-hvf] [-c config]
149 -h : this (help) message
150 -c <file> : config file
151 -f : foreground, process will not be forked to background
152 -v : be verbose (multiple to increase verbosity)
153 -no-bus : starts $0 without connection to bus
154 -no-arp : starts $0 without connection to arp module
156 EOF
157 print "\n" ;
158 }
161 #=== FUNCTION ================================================================
162 # NAME: read_configfile
163 # PARAMETERS: cfg_file - string -
164 # RETURNS: nothing
165 # DESCRIPTION: read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168 my $cfg;
169 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
170 if( -r $cfg_file ) {
171 $cfg = Config::IniFiles->new( -file => $cfg_file );
172 } else {
173 print STDERR "Couldn't read config file!";
174 }
175 } else {
176 $cfg = Config::IniFiles->new() ;
177 }
178 foreach my $section (keys %cfg_defaults) {
179 foreach my $param (keys %{$cfg_defaults{ $section }}) {
180 my $pinfo = $cfg_defaults{ $section }{ $param };
181 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
182 }
183 }
184 }
187 #=== FUNCTION ================================================================
188 # NAME: logging
189 # PARAMETERS: level - string - default 'info'
190 # msg - string -
191 # facility - string - default 'LOG_DAEMON'
192 # RETURNS: nothing
193 # DESCRIPTION: function for logging
194 #===============================================================================
195 sub daemon_log {
196 # log into log_file
197 my( $msg, $level ) = @_;
198 if(not defined $msg) { return }
199 if(not defined $level) { $level = 1 }
200 if(defined $log_file){
201 open(LOG_HANDLE, ">>$log_file");
202 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
203 print STDERR "cannot open $log_file: $!";
204 return }
205 chomp($msg);
206 if($level <= $verbose){
207 my ($seconds, $minutes, $hours, $monthday, $month,
208 $year, $weekday, $yearday, $sommertime) = localtime(time);
209 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
210 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
211 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
212 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
213 $month = $monthnames[$month];
214 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
215 $year+=1900;
216 my $name = $0;
217 $name =~ s/\.\///;
219 print LOG_HANDLE "$month $monthday $hours:$minutes:$seconds $name $msg\n";
220 if($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;
233 }
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 }
258 }
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 }
307 }
309 #=== FUNCTION ================================================================
310 # NAME: import_modules
311 # PARAMETERS: module_path - string - abs. path to the directory the modules
312 # are stored
313 # RETURNS: nothing
314 # DESCRIPTION: each file in module_path which ends with '.pm' is imported by
315 # "require 'file';"
316 #===============================================================================
317 sub import_modules {
318 daemon_log(" ", 1);
320 if (not -e $modules_path) {
321 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
322 }
324 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
325 while (defined (my $file = readdir (DIR))) {
326 if (not $file =~ /(\S*?).pm$/) {
327 next;
328 }
329 eval { require $file; };
330 if ($@) {
331 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
332 daemon_log("$@", 5);
333 } else {
334 my $mod_name = $1;
335 my $info = eval($mod_name.'::get_module_info()');
336 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
337 $known_modules->{$mod_name} = $info;
339 daemon_log("module $mod_name loaded", 1);
340 }
341 }
343 # for debugging
344 #while ( my ($module, $tag_hash) = each(%$known_modules)) {
345 # print "\tmodule: $module"."\n";
346 # print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
347 #}
348 close (DIR);
349 }
352 #=== FUNCTION ================================================================
353 # NAME: sig_int_handler
354 # PARAMETERS: signal - string - signal arose from system
355 # RETURNS: noting
356 # DESCRIPTION: handels tasks to be done befor signal becomes active
357 #===============================================================================
358 sub sig_int_handler {
359 my ($signal) = @_;
361 daemon_log("shutting down gosa-si-server", 1);
362 exit(1);
363 }
364 $SIG{INT} = \&sig_int_handler;
367 #=== FUNCTION ================================================================
368 # NAME: activating_child
369 # PARAMETERS: msg - string - incoming message
370 # host - string - host from which the incomming message comes
371 # RETURNS: nothing
372 # DESCRIPTION: handels the distribution of incoming messages to working childs
373 #===============================================================================
374 sub activating_child {
375 my ($msg, $host, $client) = @_;
376 my $child = &get_processing_child();
377 my $pipe_wr = $$child{'pipe_wr'};
378 my $pipe_rd = $$child{'pipe_rd'};
379 $$child{client_ref} = $client;
381 daemon_log("activating: childpid:$$child{'pid'}", 5);
383 print $pipe_wr $msg.".".$host."\n";
385 return;
386 }
389 #=== FUNCTION ================================================================
390 # NAME: get_processing_child
391 # PARAMETERS: nothing
392 # RETURNS: child - hash - holding the process id and the references to the pipe
393 # handles pipe_wr and pipe_rd
394 # DESCRIPTION: handels the forking, reactivating and keeping alive tasks
395 #===============================================================================
396 sub get_processing_child {
397 my $child;
399 while(my ($key, $val) = each(%free_child)) {
400 my $exitus_pid = waitpid($key, WNOHANG);
401 if($exitus_pid != 0) {
402 delete $free_child{$key};
403 }
404 daemon_log("free child:$key", 5);
405 }
406 # check @free_child and @busy_child
407 my $free_len = scalar(keys(%free_child));
408 my $busy_len = scalar(keys(%busy_child));
409 daemon_log("free children $free_len, busy children $busy_len", 5);
411 # if there is a free child, let the child work
412 if($free_len > 0){
413 my @keys = keys(%free_child);
414 $child = $free_child{$keys[0]};
415 if(defined $child) {
416 $busy_child{$$child{'pid'}} = $child ;
417 delete $free_child{$$child{'pid'}};
418 }
419 return $child;
420 }
422 # no free child, try to fork another one
423 if($free_len + $busy_len < $child_max) {
425 daemon_log("not enough children, create a new one", 5);
427 # New pipes for communication
428 my( $PARENT_wr, $PARENT_rd );
429 my( $CHILD_wr, $CHILD_rd );
430 pipe( $CHILD_rd, $PARENT_wr );
431 pipe( $PARENT_rd, $CHILD_wr );
432 $PARENT_wr->autoflush(1);
433 $CHILD_wr->autoflush(1);
435 ############
436 # fork child
437 ############
438 my $child_pid = fork();
440 #CHILD
441 if($child_pid == 0) {
442 # Close unused pipes
443 close( $CHILD_rd );
444 close( $CHILD_wr );
445 while( 1 ) {
446 my $rbits = "";
447 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
448 my $nf = select($rbits, undef, undef, $child_timeout);
449 if($nf < 0 ) {
450 die "select(): $!\n";
451 } elsif (! $nf) {
452 # if already child_min childs are alive, then leave loop
453 $free_len = scalar(keys(%free_child));
454 $busy_len = scalar(keys(%busy_child));
455 if($free_len + $busy_len >= $child_min) {
456 last;
457 } else {
458 redo;
459 }
460 }
462 # a job for a child arise
463 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
464 # read everything from pipe
465 my $msg = "";
466 $PARENT_rd->blocking(0);
467 while(1) {
468 my $read = <$PARENT_rd>;
469 if(not defined $read) { last}
470 $msg .= $read;
471 }
473 ######################################
474 # forward msg to all imported modules
475 no strict "refs";
476 my $answer;
477 my %act_modules = %$known_modules;
478 while( my ($module, $info) = each(%act_modules)) {
479 &daemon_log("##########", 5);
480 my $tmp = &{ $module."::process_incoming_msg" }($msg);
481 if (defined $tmp) {
482 $answer = $tmp;
483 }
484 &daemon_log("##########", 5);
485 }
487 #&print_known_daemons();
488 #&print_known_clients();
490 daemon_log("processing of msg finished", 5);
492 if (defined $answer) {
493 print $PARENT_wr $answer."\n";
494 daemon_log("with answer:", 5);
495 daemon_log("$answer", 5);
496 } else {
497 print $PARENT_wr "done"."\n";
498 daemon_log(" ", 5);
499 }
500 redo;
501 }
502 }
503 # childs leaving the loop are allowed to die
504 exit(0);
507 #PARENT
508 } else {
509 # Close unused pipes
510 close( $PARENT_rd );
511 close( $PARENT_wr );
513 # add child to child alive hash
514 my %child_hash = (
515 'pid' => $child_pid,
516 'pipe_wr' => $CHILD_wr,
517 'pipe_rd' => $CHILD_rd,
518 'client_ref' => "",
519 );
521 $child = \%child_hash;
522 $busy_child{$$child{'pid'}} = $child;
523 return $child;
524 }
525 }
526 }
529 #=== FUNCTION ================================================================
530 # NAME: read_from_socket
531 # PARAMETERS: socket fh -
532 # RETURNS: result string - readed characters from socket
533 # DESCRIPTION: reads data from socket in 16 byte steps
534 #===============================================================================
535 sub read_from_socket {
536 my ($socket) = @_;
537 my $result = "";
539 $socket->blocking(1);
540 $result = <$socket>;
542 $socket->blocking(0);
543 while ( my $char = <$socket> ) {
544 if (not defined $char) { last }
545 $result .= $char;
546 }
548 return $result;
549 }
552 #=== FUNCTION ================================================================
553 # NAME: print_known_daemons
554 # PARAMETERS: nothing
555 # RETURNS: nothing
556 # DESCRIPTION: nomen est omen
557 #===============================================================================
558 #sub print_known_daemons {
559 # my ($tmp) = @_ ;
560 # print "####################################\n";
561 # print "# status of known_daemons\n";
562 # $shmda->shlock(LOCK_EX);
563 # my @hosts = keys %$known_daemons;
564 # foreach my $host (@hosts) {
565 # my $status = $known_daemons->{$host}->{status} ;
566 # my $passwd = $known_daemons->{$host}->{passwd};
567 # my $timestamp = $known_daemons->{$host}->{timestamp};
568 # print "$host\n";
569 # print "\tstatus: $status\n";
570 # print "\tpasswd: $passwd\n";
571 # print "\ttimestamp: $timestamp\n";
572 # }
573 # $shmda->shunlock(LOCK_EX);
574 # print "####################################\n";
575 # return;
576 #}
579 #=== FUNCTION ================================================================
580 # NAME: create_known_daemon
581 # PARAMETERS: hostname - string - key for the hash known_daemons
582 # RETURNS: nothing
583 # DESCRIPTION: creates a dummy entry for hostname in known_daemons
584 #===============================================================================
585 #sub create_known_daemon {
586 # my ($hostname) = @_;
587 # $shmda->shlock(LOCK_EX);
588 # $known_daemons->{$hostname} = {};
589 # $known_daemons->{$hostname}->{status} = "none";
590 # $known_daemons->{$hostname}->{passwd} = "none";
591 # $known_daemons->{$hostname}->{timestamp} = "none";
592 # $shmda->shunlock(LOCK_EX);
593 # return;
594 #}
597 #=== FUNCTION ================================================================
598 # NAME: add_content2known_daemons
599 # PARAMETERS: hostname - string - ip address and port of host (required)
600 # status - string - (optional)
601 # passwd - string - (optional)
602 # mac_address - string - mac address of host (optional)
603 # RETURNS: nothing
604 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
605 #===============================================================================
606 #sub add_content2known_daemons {
607 # my $arg = {
608 # hostname => undef, status => undef, passwd => undef,
609 # mac_address => undef, events => undef,
610 # @_ };
611 # my $hostname = $arg->{hostname};
612 # my $status = $arg->{status};
613 # my $passwd = $arg->{passwd};
614 # my $mac_address = $arg->{mac_address};
615 # my $events = $arg->{events};
616 #
617 # if (not defined $hostname) {
618 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
619 # return;
620 # }
621 #
622 # my ($seconds, $minutes, $hours, $monthday, $month,
623 # $year, $weekday, $yearday, $sommertime) = localtime(time);
624 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
625 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
626 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
627 # $month+=1;
628 # $month = $month < 10 ? $month = "0".$month : $month;
629 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
630 # $year+=1900;
631 # my $t = "$year$month$monthday$hours$minutes$seconds";
632 #
633 # $shmda->shlock(LOCK_EX);
634 # if (defined $status) {
635 # $known_daemons->{$hostname}->{status} = $status;
636 # }
637 # if (defined $passwd) {
638 # $known_daemons->{$hostname}->{passwd} = $passwd;
639 # }
640 # if (defined $mac_address) {
641 # $known_daemons->{$hostname}->{mac_address} = $mac_address;
642 # }
643 # if (defined $events) {
644 # $known_daemons->{$hostname}->{events} = $events;
645 # }
646 # $known_daemons->{$hostname}->{timestamp} = $t;
647 # $shmda->shlock(LOCK_EX);
648 # return;
649 #}
652 #=== FUNCTION ================================================================
653 # NAME: update_known_daemons
654 # PARAMETERS: hostname - string - ip address and port of host (required)
655 # status - string - (optional)
656 # passwd - string - (optional)
657 # client - string - ip address and port of client (optional)
658 # RETURNS: nothing
659 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
660 #===============================================================================
661 #sub update_known_daemons {
662 # my $arg = {
663 # hostname => undef, status => undef, passwd => undef,
664 # @_ };
665 # my $hostname = $arg->{hostname};
666 # my $status = $arg->{status};
667 # my $passwd = $arg->{passwd};
668 #
669 # if (not defined $hostname) {
670 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
671 # return;
672 # }
673 #
674 # my ($seconds, $minutes, $hours, $monthday, $month,
675 # $year, $weekday, $yearday, $sommertime) = localtime(time);
676 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
677 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
678 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
679 # $month+=1;
680 # $month = $month < 10 ? $month = "0".$month : $month;
681 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
682 # $year+=1900;
683 # my $t = "$year$month$monthday$hours$minutes$seconds";
684 #
685 # $shmda->shlock(LOCK_EX);
686 # if (defined $status) {
687 # $known_daemons->{$hostname}->{status} = $status;
688 # }
689 # if (defined $passwd) {
690 # $known_daemons->{$hostname}->{passwd} = $passwd;
691 # }
692 # $known_daemons->{$hostname}->{timestamp} = $t;
693 # $shmda->shunlock(LOCK_EX);
694 # return;
695 #}
698 #=== FUNCTION ================================================================
699 # NAME: print_known_clients
700 # PARAMETERS: nothing
701 # RETURNS: nothing
702 # DESCRIPTION: nomen est omen
703 #===============================================================================
704 #sub print_known_clients {
705 #
706 # print "####################################\n";
707 # print "# status of known_clients\n";
708 # $shmcl->shlock(LOCK_EX);
709 # my @hosts = keys %$known_clients;
710 # if (@hosts) {
711 # foreach my $host (@hosts) {
712 # my $status = $known_clients->{$host}->{status} ;
713 # my $passwd = $known_clients->{$host}->{passwd};
714 # my $timestamp = $known_clients->{$host}->{timestamp};
715 # my $mac_address = $known_clients->{$host}->{mac_address};
716 # my $events = $known_clients->{$host}->{events};
717 # print "$host\n";
718 # print "\tstatus: $status\n";
719 # print "\tpasswd: $passwd\n";
720 # print "\ttimestamp: $timestamp\n";
721 # print "\tmac_address: $mac_address\n";
722 # print "\tevents: $events\n";
723 # }
724 # }
725 # $shmcl->shunlock(LOCK_EX);
726 # print "####################################\n";
727 # return;
728 #}
731 #=== FUNCTION ================================================================
732 # NAME: create_known_client
733 # PARAMETERS: hostname - string - key for the hash known_clients
734 # RETURNS: nothing
735 # DESCRIPTION: creates a dummy entry for hostname in known_clients
736 #===============================================================================
737 sub create_known_client {
738 my ($hostname) = @_;
740 my $entry = { table=>'known_clients',
741 hostname=>$hostname,
742 status=>'none',
743 hostkey=>'none',
744 timestamp=>'none',
745 macaddress=>'none',
746 events=>'none',
747 };
748 my $res = $known_clients_db->add_dbentry($entry);
749 if ($res > 0) {
750 daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
751 }
753 return;
754 }
757 #=== FUNCTION ================================================================
758 # NAME: add_content2known_clients
759 # PARAMETERS: hostname - string - ip address and port of host (required)
760 # status - string - (optional)
761 # passwd - string - (optional)
762 # mac_address - string - (optional)
763 # events - string - event of client, executable skripts
764 # under /etc/gosac/events
765 # RETURNS: nothing
766 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
767 #===============================================================================
768 #sub update_known_clients {
769 # my $arg = {
770 # hostname => undef, status => undef, hostkey => undef,
771 # macaddress => undef, events => undef, timestamp=>undef,
772 # @_ };
773 # my $hostname = $arg->{hostname};
774 # my $status = $arg->{status};
775 # my $hostkey = $arg->{hostkey};
776 # my $macaddress = $arg->{macaddress};
777 # my $events = $arg->{events};
778 # my $timestamp = $arg->{timestamp};
779 #
780 # if (not defined $hostname) {
781 # daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
782 # return;
783 # }
784 #
785 # my $change_entry = { table=>'known_clients',
786 # where=>'hostname',
787 # timestamp=>&get_time,
788 # };
789 #
790 #
791 # if (defined $status) {
792 # $change_entry->{status} = $status;
793 # }
794 # if (defined $hostkey) {
795 # $change_entry->{hostkey} = $hostkey;
796 # }
797 # if (defined $macaddress) {
798 # $change_entry->{macaddress} = $macaddress;
799 # }
800 # if (defined $events) {
801 # $change_entry->{events} = $events;
802 # }
803 #
804 # $known_clients->change_dbentry($change_entry);
805 # return;
806 #}
809 #=== FUNCTION ================================================================
810 # NAME:
811 # PARAMETERS:
812 # RETURNS:
813 # DESCRIPTION:
814 #===============================================================================
815 #sub clean_up_known_clients {
816 # my ($address) = @_ ;
817 #
818 # if (not exists $known_clients->{$address}) {
819 # daemon_log("cannot prune known_clients from $address, client not known", 5);
820 # return;
821 # }
822 #
823 # delete $known_clients->{$address};
824 #
825 # # send bus a msg that address was deleted from known_clients
826 # my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
827 # &send_msg_hash2bus($out_hash);
828 #
829 # daemon_log("client $address deleted from known_clients because of multiple down time", 3);
830 # return;
831 #}
834 #=== FUNCTION ================================================================
835 # NAME: update_known_clients
836 # PARAMETERS: hostname - string - ip address and port of host (required)
837 # status - string - (optional)
838 # passwd - string - (optional)
839 # client - string - ip address and port of client (optional)
840 # RETURNS: nothing
841 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
842 #===============================================================================
843 #sub update_known_clients {
844 # my $arg = {
845 # hostname => undef, status => undef, passwd => undef,
846 # mac_address => undef, events => undef,
847 # @_ };
848 # my $hostname = $arg->{hostname};
849 # my $status = $arg->{status};
850 # my $passwd = $arg->{passwd};
851 # my $mac_address = $arg->{mac_address};
852 # my $events = $arg->{events};
853 #
854 # if (not defined $hostname) {
855 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
856 # return;
857 # }
858 #
859 # my ($seconds, $minutes, $hours, $monthday, $month,
860 # $year, $weekday, $yearday, $sommertime) = localtime(time);
861 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
862 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
863 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
864 # $month+=1;
865 # $month = $month < 10 ? $month = "0".$month : $month;
866 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
867 # $year+=1900;
868 # my $t = "$year$month$monthday$hours$minutes$seconds";
869 #
870 # if (defined $status) {
871 # $known_clients->{$hostname}->{status} = $status;
872 # }
873 # if (defined $passwd) {
874 # $known_clients->{$hostname}->{passwd} = $passwd;
875 # }
876 # if (defined $mac_address) {
877 # $known_clients->{$hostname}->{mac_address} = $mac_address;
878 # }
879 # if (defined $events) {
880 # $known_clients->{$hostname}->{events} = $events;
881 # }
882 # $known_clients_db->{$hostname}->{timestamp} = $t;
883 # return;
884 #}
892 #==== MAIN = main ==============================================================
894 # parse commandline options
895 Getopt::Long::Configure( "bundling" );
896 GetOptions("h|help" => \&usage,
897 "c|config=s" => \$cfg_file,
898 "f|foreground" => \$foreground,
899 "v|verbose+" => \$verbose,
900 "no-bus+" => \$no_bus,
901 "no-arp+" => \$no_arp,
902 );
904 # read and set config parameters
905 &check_cmdline_param ;
906 &read_configfile;
907 &check_pid;
909 $SIG{CHLD} = 'IGNORE';
911 # forward error messages to logfile
912 if( ! $foreground ) {
913 open(STDERR, '>>', $log_file);
914 open(STDOUT, '>>', $log_file);
915 }
917 # Just fork, if we are not in foreground mode
918 if( ! $foreground ) {
919 chdir '/' or die "Can't chdir to /: $!";
920 $pid = fork;
921 setsid or die "Can't start a new session: $!";
922 umask 0;
923 } else {
924 $pid = $$;
925 }
927 # Do something useful - put our PID into the pid_file
928 if( 0 != $pid ) {
929 open( LOCK_FILE, ">$pid_file" );
930 print LOCK_FILE "$pid\n";
931 close( LOCK_FILE );
932 if( !$foreground ) {
933 exit( 0 )
934 };
935 }
937 daemon_log(" ", 1);
938 daemon_log("$0 started!", 1);
941 # connect to gosa-si job queue
942 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
943 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
944 $job_db->create_table('jobs', \@job_col_names);
946 # connect to known_clients_db
947 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
948 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
949 $known_clients_db->create_table('known_clients', \@clients_col_names);
951 # connect to known_server_db
952 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
953 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
954 $known_server_db->create_table('known_server', \@server_col_names);
956 # import all modules
957 &import_modules;
959 # check wether all modules are gosa-si valid passwd check
961 # create reading and writing vectors
962 my $rbits = my $wbits = my $ebits = "";
964 # add all module inputs to listening vector
965 while( my ($mod_name, $info) = each %$known_modules ) {
966 my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
967 vec($rbits, fileno $input, 1) = 1;
969 }
972 ## start arp fifo
973 #if ($no_arp > 0) {
974 # $arp_activ = "off";
975 #}
976 #my $my_fifo;
977 #if($arp_activ eq "on") {
978 # daemon_log(" ", 1);
979 # $my_fifo = &open_fifo($arp_fifo_path);
980 # if($my_fifo == 0) { die "fifo file disappeared\n" }
981 # sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
982 #
983 # vec($rbits, fileno $arp_fifo, 1) = 1;
984 #}
985 #
987 ##################################
988 #everything ready, okay, lets start
989 ##################################
990 while(1) {
992 # add all handles from the childs
993 while ( my ($pid, $child_hash) = each %busy_child ) {
995 # check whether process still exists
996 my $exitus_pid = waitpid($pid, WNOHANG);
997 if($exitus_pid != 0) {
998 delete $busy_child{$pid};
999 next;
1000 }
1002 # add child fhd to the listener
1003 my $fhd = $$child_hash{'pipe_rd'};
1004 vec($rbits, fileno $fhd, 1) = 1;
1005 }
1007 my ($rout, $wout);
1008 my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
1010 # error handling
1011 if($nf < 0 ) {
1012 }
1015 # if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1016 # my $in_msg = <$arp_fifo>;
1017 # chomp($in_msg);
1018 # print "arp_activ: msg: $in_msg\n";
1019 # my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1020 # print "arp_activ: arp_passwd: $act_passwd\n";
1021 #
1022 # my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1023 #
1024 # my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1025 #
1026 # if ($target eq $server_address) {
1027 # print "arp_activ: forward to server\n";
1028 # my $arp_cipher = &create_ciphering($act_passwd);
1029 # my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1030 # &activating_child($crypted_msg, $server_ip);
1031 # } else {
1032 # print "arp_activ: send to bus\n";
1033 # &send_msg_hash2address($in_msg_hash, $bus_address);
1034 # }
1035 # print "\n";
1036 # }
1039 # check input fhd of all modules
1040 while ( my ($mod_name, $info) = each %$known_modules) {
1041 my $input_fhd = @{$info}[2];
1042 my $input_activ = @{$info}[3];
1043 if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
1044 daemon_log(" ", 1);
1045 my $client = $input_fhd->accept();
1046 my $other_end = getpeername($client);
1047 if(not defined $other_end) {
1048 daemon_log("client cannot be identified: $!");
1049 } else {
1050 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1051 my $actual_ip = inet_ntoa($iaddr);
1052 daemon_log("accept client at daemon socket from $actual_ip", 5);
1053 my $in_msg = &read_from_socket($client);
1054 if(defined $in_msg){
1055 chomp($in_msg);
1056 &activating_child($in_msg, $actual_ip, $client);
1057 } else {
1058 daemon_log("cannot read from $actual_ip", 5);
1059 }
1060 }
1061 }
1062 }
1064 # check all processing childs whether they are finished ('done') or
1065 while ( my ($pid, $child_hash) = each %busy_child ) {
1066 my $fhd = $$child_hash{'pipe_rd'};
1068 if (vec($rout, fileno $fhd, 1) ) {
1069 daemon_log("process child $pid is ready to read", 5);
1071 $fhd->blocking(1);
1072 my $in_msg = <$fhd>;
1073 $fhd->blocking(0);
1074 my $part_in_msg;
1075 while ($part_in_msg = <$fhd>) {
1076 if (not defined $part_in_msg) {
1077 last;
1078 }
1079 $in_msg .= $part_in_msg;
1080 }
1081 chomp($in_msg);
1083 daemon_log("process child read: $in_msg", 5);
1084 if (not defined $in_msg) {
1085 next;
1086 } elsif ($in_msg =~ "done") {
1087 delete $busy_child{$pid};
1088 $free_child{$pid} = $child_hash;
1090 } else {
1091 # send computed answer back to connected client
1092 my $act_client = $busy_child{$pid}{client_ref};
1093 print $act_client $in_msg."\n";
1095 #my $act_pipe = $busy_child{$pid}{pipe_rd};
1096 delete $busy_child{$pid};
1097 $free_child{$pid} = $child_hash;
1099 # give the client a chance to read
1100 sleep(2);
1101 close ($act_client);
1102 }
1103 }
1104 }
1106 # check gosa job queue for jobs with executable timestamp
1107 my ($seconds, $minutes, $hours, $monthday, $month,
1108 $year, $weekday, $yearday, $sommertime) = localtime(time);
1109 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1110 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1111 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1112 $month+=1;
1113 $month = $month < 10 ? $month = "0".$month : $month;
1114 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1115 $year+=1900;
1116 my $timestamp = "$year$month$monthday$hours$minutes$seconds";
1119 my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp } );
1121 while( my ($id, $hit) = each %{$res} ) {
1123 my $jobdb_id = $hit->{ROWID};
1124 my $macaddress = $hit->{macaddress};
1125 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1126 my $out_msg_hash = $job_msg_hash;
1127 my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
1128 # expect macaddress is unique!!!!!!
1129 my $target = $res_hash->{1}->{hostname};
1131 if (not defined $target) {
1132 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1133 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1134 my $update_hash = { table=>$job_queue_table_name,
1135 update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1136 where=> [ { ROWID=>[$jobdb_id] } ],
1137 };
1138 my $res = $job_db->update_dbentry($update_hash);
1140 next;
1141 }
1143 # add target
1144 &add_content2xml_hash($out_msg_hash, "target", $target);
1146 # add new header
1147 my $out_header = $job_msg_hash->{header}[0];
1148 $out_header =~ s/job_/gosa_/;
1149 delete $out_msg_hash->{header};
1150 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1152 # add sqlite_id
1153 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1155 my $out_msg = &create_xml_string($out_msg_hash);
1157 # encrypt msg as a GosaPackage module
1158 my $cipher = &create_ciphering($gosa_passwd);
1159 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1161 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1163 #######################
1164 # TODO exchange ROWID with jobid, insert column jobid in table jobs befor
1166 if ($error == 0) {
1167 my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE ROWID='$jobdb_id'";
1168 my $res = $job_db->exec_statement($sql);
1169 } else {
1170 my $update_hash = { table=>$job_queue_table_name,
1171 update=> [ { status=>'error' } ],
1172 where=> [ { ROWID=>$jobdb_id } ],
1173 };
1174 my $res = $job_db->update_dbentry($update_hash);
1175 }
1177 }
1180 }