95027948969a7f1ac28b98b6d8796433d8ffa266
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-sd
5 #
6 # USAGE: ./gosa-sd
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl libipc-shareable-perl libdata-dumper-simple-perl
12 # BUGS: ---
13 # NOTES:
14 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
15 # COMPANY:
16 # VERSION: 1.0
17 # CREATED: 12.09.2007 08:54:41 CEST
18 # REVISION: ---
19 #===============================================================================
22 use strict;
23 use warnings;
24 use Getopt::Long;
25 use Config::IniFiles;
26 use POSIX;
27 use Time::HiRes qw( gettimeofday );
29 use Fcntl;
30 use IO::Socket::INET;
31 use Crypt::Rijndael;
32 use MIME::Base64;
33 use Digest::MD5 qw(md5 md5_hex md5_base64);
34 use XML::Simple;
35 use Data::Dumper;
36 use Sys::Syslog qw( :DEFAULT setlogsock);
37 use Cwd;
38 use File::Spec;
39 use IPC::Shareable qw( :lock);
40 IPC::Shareable->clean_up_all;
42 use lib "/etc/gosa-si/modules";
43 my $modules_path = "/etc/gosa-si/modules";
45 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $ping_timeout, $no_bus);
46 my ($bus, $msg_to_bus, $bus_cipher);
47 my ($server, $server_mac_address, $server_events);
48 my ($gosa_server);
49 my ($known_daemons, $shmda, $known_clients, $shmcl, $known_modules);
50 my ($max_clients);
51 my ($pid_file, $procid, $pid, $log_file);
52 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
53 my ($arp_activ, $arp_fifo, $arp_fifo_path, $no_arp);
55 # variables declared in config file are always set to 'our'
56 our (%cfg_defaults, $log_file, $pid_file,
57 $bus_activ, $bus_passwd, $bus_ip, $bus_port,
58 $server_activ, $server_ip, $server_port, $server_passwd, $max_clients,
59 $arp_activ, $arp_fifo_path,
60 $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
61 );
63 # additional variable which should be globaly accessable
64 our $xml;
65 our $server_address;
66 our $bus_address;
67 our $gosa_address;
69 # specifies the verbosity of the daemon_log
70 $verbose = 0 ;
72 # if foreground is not null, script will be not forked to background
73 $foreground = 0 ;
75 # specifies the timeout seconds while checking the online status of a registrating client
76 $ping_timeout = 5;
78 $no_bus = 0;
80 $no_arp = 0;
82 # holds all other gosa-sd as well as the gosa-sd-bus
83 our $known_daemons = {};
84 our $shmda = tie($known_daemons, 'IPC::Shareable', undef, {create => 1,
85 exclusive => 1,
86 mode => 0666,
87 destroy => 1,
88 });
89 # holds all registrated clients
90 our $known_clients = {};
91 our $shmcl = tie($known_clients, 'IPC::Shareable', undef, {create => 1,
92 exclusive => 1,
93 mode => 0666,
94 destroy => 1,
95 });
98 %cfg_defaults =
99 ("general" =>
100 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
101 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
102 "child_max" => [\$child_max, 10],
103 "child_min" => [\$child_min, 3],
104 "child_timeout" => [\$child_timeout, 180],
105 },
106 "bus" =>
107 {"bus_activ" => [\$bus_activ, "on"],
108 "bus_passwd" => [\$bus_passwd, ""],
109 "bus_ip" => [\$bus_ip, ""],
110 "bus_port" => [\$bus_port, "20080"],
111 },
112 "server" =>
113 {"server_activ" => [\$server_activ, "on"],
114 "server_ip" => [\$server_ip, ""],
115 "server_port" => [\$server_port, "20081"],
116 "server_passwd" => [\$server_passwd, ""],
117 "max_clients" => [\$max_clients, 100],
118 },
119 "arp" =>
120 {"arp_activ" => [\$arp_activ, "on"],
121 "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
122 },
123 "gosa" =>
124 {"gosa_activ" => [\$gosa_activ, "on"],
125 "gosa_ip" => [\$gosa_ip, ""],
126 "gosa_port" => [\$gosa_port, "20082"],
127 "gosa_passwd" => [\$gosa_passwd, "none"],
128 },
129 );
132 #=== FUNCTION ================================================================
133 # NAME: usage
134 # PARAMETERS: nothing
135 # RETURNS: nothing
136 # DESCRIPTION: print out usage text to STDERR
137 #===============================================================================
138 sub usage {
139 print STDERR << "EOF" ;
140 usage: $0 [-hvf] [-c config]
142 -h : this (help) message
143 -c <file> : config file
144 -f : foreground, process will not be forked to background
145 -v : be verbose (multiple to increase verbosity)
146 EOF
147 print "\n" ;
148 }
151 #=== FUNCTION ================================================================
152 # NAME: read_configfile
153 # PARAMETERS: cfg_file - string -
154 # RETURNS: nothing
155 # DESCRIPTION: read cfg_file and set variables
156 #===============================================================================
157 sub read_configfile {
158 my $cfg;
159 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
160 if( -r $cfg_file ) {
161 $cfg = Config::IniFiles->new( -file => $cfg_file );
162 } else {
163 print STDERR "Couldn't read config file!";
164 }
165 } else {
166 $cfg = Config::IniFiles->new() ;
167 }
168 foreach my $section (keys %cfg_defaults) {
169 foreach my $param (keys %{$cfg_defaults{ $section }}) {
170 my $pinfo = $cfg_defaults{ $section }{ $param };
171 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
172 }
173 }
174 }
177 #=== FUNCTION ================================================================
178 # NAME: logging
179 # PARAMETERS: level - string - default 'info'
180 # msg - string -
181 # facility - string - default 'LOG_DAEMON'
182 # RETURNS: nothing
183 # DESCRIPTION: function for logging
184 #===============================================================================
185 sub daemon_log {
186 # log into log_file
187 my( $msg, $level ) = @_;
188 if(not defined $msg) { return }
189 if(not defined $level) { $level = 1 }
190 if(defined $log_file){
191 open(LOG_HANDLE, ">>$log_file");
192 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
193 print STDERR "cannot open $log_file: $!";
194 return }
195 chomp($msg);
196 if($level <= $verbose){
197 print LOG_HANDLE "$level $msg\n";
198 if(defined $foreground) { print $msg."\n" }
199 }
200 }
201 close( LOG_HANDLE );
202 #log into syslog
203 # my ($msg, $level, $facility) = @_;
204 # if(not defined $msg) {return}
205 # if(not defined $level) {$level = "info"}
206 # if(not defined $facility) {$facility = "LOG_DAEMON"}
207 # openlog($0, "pid,cons,", $facility);
208 # syslog($level, $msg);
209 # closelog;
210 # return;
211 }
214 #=== FUNCTION ================================================================
215 # NAME: check_cmdline_param
216 # PARAMETERS: nothing
217 # RETURNS: nothing
218 # DESCRIPTION: validates commandline parameter
219 #===============================================================================
220 sub check_cmdline_param () {
221 my $err_config;
222 my $err_counter = 0;
223 if( not defined( $cfg_file)) {
224 #$err_config = "please specify a config file";
225 #$err_counter += 1;
226 my $cwd = getcwd;
227 my $name = "/etc/gosa-si/server.conf";
228 $cfg_file = File::Spec->catfile( $cwd, $name );
229 }
230 if( $err_counter > 0 ) {
231 &usage( "", 1 );
232 if( defined( $err_config)) { print STDERR "$err_config\n"}
233 print STDERR "\n";
234 exit( -1 );
235 }
236 }
239 #=== FUNCTION ================================================================
240 # NAME: check_pid
241 # PARAMETERS: nothing
242 # RETURNS: nothing
243 # DESCRIPTION: handels pid processing
244 #===============================================================================
245 sub check_pid {
246 $pid = -1;
247 # Check, if we are already running
248 if( open(LOCK_FILE, "<$pid_file") ) {
249 $pid = <LOCK_FILE>;
250 if( defined $pid ) {
251 chomp( $pid );
252 if( -f "/proc/$pid/stat" ) {
253 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
254 if( $0 eq $stat ) {
255 close( LOCK_FILE );
256 exit -1;
257 }
258 }
259 }
260 close( LOCK_FILE );
261 unlink( $pid_file );
262 }
264 # create a syslog msg if it is not to possible to open PID file
265 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
266 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
267 if (open(LOCK_FILE, '<', $pid_file)
268 && ($pid = <LOCK_FILE>))
269 {
270 chomp($pid);
271 $msg .= "(PID $pid)\n";
272 } else {
273 $msg .= "(unable to read PID)\n";
274 }
275 if( ! ($foreground) ) {
276 openlog( $0, "cons,pid", "daemon" );
277 syslog( "warning", $msg );
278 closelog();
279 }
280 else {
281 print( STDERR " $msg " );
282 }
283 exit( -1 );
284 }
285 }
288 #=== FUNCTION ================================================================
289 # NAME: get_ip_and_mac
290 # PARAMETERS: nothing
291 # RETURNS: (ip, mac)
292 # DESCRIPTION: executes /sbin/ifconfig and parses the output, the first occurence
293 # of a inet address is returned as well as the mac address in the line
294 # above the inet address
295 #===============================================================================
296 sub get_ip_and_mac {
297 my $ip = "0.0.0.0.0"; # Defualt-IP
298 my $mac = "00:00:00:00:00:00"; # Default-MAC
299 my @ifconfig = qx(/sbin/ifconfig);
300 foreach(@ifconfig) {
301 if (/Hardware Adresse (\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/) {
302 $mac = "$1:$2:$3:$4:$5:$6";
303 next;
304 }
305 if (/inet Adresse:(\d+).(\d+).(\d+).(\d+)/) {
306 $ip = "$1.$2.$3.$4";
307 last;
308 }
309 }
310 return ($ip, $mac);
311 }
315 #=== FUNCTION ================================================================
316 # NAME: import_modules
317 # PARAMETERS: module_path - string - abs. path to the directory the modules are stored
318 # RETURNS: nothing
319 # DESCRIPTION: each file in module_path which ends with '.pm' is imported by "require 'file';"
320 #===============================================================================
321 sub import_modules {
322 daemon_log(" ", 1);
324 if (not -e $modules_path) {
325 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
326 }
328 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
329 while (defined (my $file = readdir (DIR))) {
330 if (not $file =~ /(\S*?).pm$/) {
331 next;
332 }
333 eval { require $file; };
334 if ($@) {
335 daemon_log("ERROR: gosa-sd could not load module $file", 1);
336 daemon_log("$@", 5);
337 next;
338 }
339 my $mod_name = $1;
340 my $module_tag_hash = eval( $mod_name.'::get_module_tags()' );
341 $known_modules->{$mod_name} = $module_tag_hash;
343 daemon_log("load module $mod_name", 1);
344 }
346 # for debugging
347 #while ( my ($module, $tag_hash) = each(%$known_modules)) {
348 # print "\tmodule: $module"."\n";
349 # print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
350 #}
351 close (DIR);
352 }
355 #=== FUNCTION ================================================================
356 # NAME: register_at_bus
357 # PARAMETERS: nothing
358 # RETURNS: nothing
359 # DESCRIPTION: creates an entry in known_daemons and send a 'here_i_am' msg to bus
360 #===============================================================================
361 sub register_at_bus {
363 # create known_daemons entry
364 &create_known_daemon($bus_address);
365 &add_content2known_daemons(hostname=>$bus_address, status=>"register_at_bus", passwd=>$bus_passwd);
366 daemon_log("register at bus: $bus_address", 1);
368 my $msg_hash = &create_xml_hash("here_i_am", "$server_ip:$server_port", $bus_address);
369 &send_msg_hash2address($msg_hash, $bus_address);
370 return;
371 }
374 #=== FUNCTION ================================================================
375 # NAME: sig_int_handler
376 # PARAMETERS: signal - string - signal arose from system
377 # RETURNS: noting
378 # DESCRIPTION: handels tasks to be done befor signal becomes active
379 #===============================================================================
380 sub sig_int_handler {
381 my ($signal) = @_;
382 if($server){
383 close($server);
384 daemon_log("daemon server closed", 1);
385 }
386 if( -p $arp_fifo_path ) {
387 close $arp_fifo ;
388 unlink($arp_fifo_path) ;
389 daemon_log("ARP_FIFO closed", 1) ;
390 }
392 if($gosa_server){
393 close($gosa_server);
394 daemon_log("gosa server closed", 1);
395 }
397 print STDERR "$signal\n";
399 exit(1);
400 }
401 $SIG{INT} = \&sig_int_handler;
404 #=== FUNCTION ================================================================
405 # NAME: activating_child
406 # PARAMETERS: msg - string - incoming message
407 # host - string - host from which the incomming message comes
408 # RETURNS: nothing
409 # DESCRIPTION: handels the distribution of incoming messages to working childs
410 #===============================================================================
411 sub activating_child {
412 my ($msg, $host, $client) = @_;
413 my $child = &get_processing_child();
414 my $pipe_wr = $$child{'pipe_wr'};
415 my $pipe_rd = $$child{'pipe_rd'};
416 $$child{client_ref} = $client;
417 daemon_log("activating: childpid:$$child{'pid'}", 5);
419 print $pipe_wr $msg.".".$host."\n";
421 # if (defined $client) {
422 # my $rbits = "";
423 # vec($rbits, fileno $client, 1) = 1;
424 #
425 # my ($rout);
426 # my $nf = select($rout=$rbits, undef, undef, $gosa_timeout);
427 # if($gosa_activ eq "on" && vec($rout, fileno $gosa_server, 1)) {
428 #
429 # }
430 # }
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;
444 # checking %busy_child{pipe_wr} if msg is 'done', then set child from busy to free
445 # while(my ($key, $val) = each(%busy_child)) {
446 # # test ob prozess noch existiert
447 # my $exitus_pid = waitpid($key, WNOHANG);
448 # if($exitus_pid != 0) {
449 # delete $busy_child{$key};
450 # print "prozess:$key wurde aus busy_child entfernt\n";
451 # next;
452 # }
453 #
454 # # check wether process sitll works
455 # my $fh = $$val{'pipe_rd'};
456 # $fh->blocking(0);
457 # my $child_answer;
458 # if(not $child_answer = <$fh>) { next }
459 # chomp($child_answer);
460 # if($child_answer eq "done") {
461 # delete $busy_child{$key};
462 # $free_child{$key} = $val;
463 # }
464 # }
466 while(my ($key, $val) = each(%free_child)) {
467 my $exitus_pid = waitpid($key, WNOHANG);
468 if($exitus_pid != 0) {
469 delete $free_child{$key};
470 }
471 daemon_log("free child:$key", 5);
472 }
473 # check @free_child and @busy_child
474 my $free_len = scalar(keys(%free_child));
475 my $busy_len = scalar(keys(%busy_child));
476 daemon_log("free children $free_len, busy children $busy_len", 5);
478 # if there is a free child, let the child work
479 if($free_len > 0){
480 my @keys = keys(%free_child);
481 $child = $free_child{$keys[0]};
482 if(defined $child) {
483 $busy_child{$$child{'pid'}} = $child ;
484 delete $free_child{$$child{'pid'}};
485 }
486 return $child;
487 }
489 # no free child, try to fork another one
490 if($free_len + $busy_len < $child_max) {
492 daemon_log("not enough children, create a new one", 5);
494 # New pipes for communication
495 my( $PARENT_wr, $PARENT_rd );
496 my( $CHILD_wr, $CHILD_rd );
497 pipe( $CHILD_rd, $PARENT_wr );
498 pipe( $PARENT_rd, $CHILD_wr );
499 $PARENT_wr->autoflush(1);
500 $CHILD_wr->autoflush(1);
502 ############
503 # fork child
504 ############
505 my $child_pid = fork();
507 #CHILD
508 if($child_pid == 0) {
509 # Close unused pipes
510 close( $CHILD_rd );
511 close( $CHILD_wr );
512 while( 1 ) {
513 my $rbits = "";
514 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
515 my $nf = select($rbits, undef, undef, $child_timeout);
516 if($nf < 0 ) {
517 die "select(): $!\n";
518 } elsif (! $nf) {
519 # if already child_min childs are alive, then leave loop
520 $free_len = scalar(keys(%free_child));
521 $busy_len = scalar(keys(%busy_child));
522 if($free_len + $busy_len >= $child_min) {
523 last;
524 } else {
525 redo;
526 }
527 }
529 # a job for a child arise
530 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
531 # read everything from pipe
532 my $msg = "";
533 $PARENT_rd->blocking(0);
534 while(1) {
535 my $read = <$PARENT_rd>;
536 if(not defined $read) { last}
537 $msg .= $read;
538 }
540 ######################################
541 # forward msg to all imported modules
542 no strict "refs";
543 my $answer;
544 while( my ($module, $tag_hash) = each(%$known_modules)) {
545 #if(exists $known_modules->{$module}->{server_packages}) {
546 my $tmp = &{ $module."::process_incoming_msg" }($msg);
547 if (defined $tmp) {
548 $answer = $tmp;
549 }
550 #}
551 }
553 &print_known_daemons();
554 &print_known_clients();
556 daemon_log("processing of msg finished", 5);
558 if (defined $answer) {
559 print $PARENT_wr $answer."\n";
560 daemon_log("\t$answer", 5);
561 daemon_log(" ", 5);
562 } else {
563 print $PARENT_wr "done"."\n";
564 daemon_log(" ", 5);
565 }
566 redo;
567 }
568 }
569 # childs leaving the loop are allowed to die
570 exit(0);
573 #PARENT
574 } else {
575 # Close unused pipes
576 close( $PARENT_rd );
577 close( $PARENT_wr );
579 # add child to child alive hash
580 my %child_hash = (
581 'pid' => $child_pid,
582 'pipe_wr' => $CHILD_wr,
583 'pipe_rd' => $CHILD_rd,
584 'client_ref' => "",
585 );
587 $child = \%child_hash;
588 $busy_child{$$child{'pid'}} = $child;
589 return $child;
590 }
591 }
592 }
595 #=== FUNCTION ================================================================
596 # NAME: process_incoming_msg
597 # PARAMETERS: crypted_msg - string - incoming crypted message
598 # RETURNS: nothing
599 # DESCRIPTION: handels the proceeded distribution to the appropriated functions
600 #===============================================================================
601 sub process_incoming_msg {
602 my ($crypted_msg) = @_;
603 if(not defined $crypted_msg) {
604 daemon_log("function 'process_incoming_msg': got no msg", 7);
605 }
606 $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
607 $crypted_msg = $1;
608 my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
609 daemon_log("msg from host:", 1);
610 daemon_log("\t$host", 1);
611 #daemon_log("crypted msg:", 7);
612 #daemon_log("\t$crypted_msg", 7);
614 # collect addresses from possible incoming clients
615 my @valid_keys;
616 my @host_keys = keys %$known_daemons;
617 foreach my $host_key (@host_keys) {
618 if($host_key =~ "^$host") {
619 push(@valid_keys, $host_key);
620 }
621 }
622 my @client_keys = keys %$known_clients;
623 foreach my $client_key (@client_keys) {
624 if($client_key =~ "^$host"){
625 push(@valid_keys, $client_key);
626 }
627 }
628 push(@valid_keys, $server_address);
630 my $l = @valid_keys;
631 my ($msg, $msg_hash);
632 my $msg_flag = 0;
634 # determine the correct passwd for deciphering of the incoming msgs
635 foreach my $host_key (@valid_keys) {
636 eval{
637 daemon_log( "key: $host_key", 7);
638 my $key_passwd;
639 if (exists $known_daemons->{$host_key}) {
640 $key_passwd = $known_daemons->{$host_key}->{passwd};
641 } elsif (exists $known_clients->{$host_key}) {
642 $key_passwd = $known_clients->{$host_key}->{passwd};
643 } elsif ($host_key eq $server_address) {
644 $key_passwd = $server_passwd;
645 }
646 daemon_log("key_passwd: $key_passwd", 7);
647 my $key_cipher = &create_ciphering($key_passwd);
648 $msg = &decrypt_msg($crypted_msg, $key_cipher);
649 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
650 };
651 if($@) {
652 daemon_log("key raise error", 7);
653 $msg_flag += 1;
654 } else {
655 last;
656 }
657 }
659 if($msg_flag >= $l) {
660 daemon_log("ERROR: do not understand the message:", 1);
661 daemon_log("\t$msg", 1);
662 return;
663 }
665 # process incoming msg
666 my $header = &get_content_from_xml_hash($msg_hash, "header");
667 my $source = @{$msg_hash->{source}}[0];
669 daemon_log("header from msg:", 1);
670 daemon_log("\t$header", 1);
671 daemon_log("msg to process:", 5);
672 daemon_log("\t$msg", 5);
674 my @targets = @{$msg_hash->{target}};
675 my $len_targets = @targets;
676 if ($len_targets == 0){
677 daemon_log("ERROR: no target specified for msg $header", 1);
679 } elsif ($len_targets == 1){
680 # we have only one target symbol
682 my $target = $targets[0];
683 daemon_log("msg is for:", 7);
684 daemon_log("\t$target", 7);
686 if ($target eq $server_address) {
687 # msg is for server
688 if ($header eq 'new_passwd'){ &new_passwd($msg_hash)}
689 elsif ($header eq 'here_i_am') { &here_i_am($msg_hash)}
690 elsif ($header eq 'who_has') { &who_has($msg_hash) }
691 elsif ($header eq 'who_has_i_do') { &who_has_i_do($msg_hash)}
692 elsif ($header eq 'update_status') { &update_status($msg_hash) }
693 #elsif ($header eq 'got_ping') { &got_ping($msg_hash)}
694 elsif ($header eq 'get_load') { &execute_actions($msg_hash)}
695 else { daemon_log("ERROR: no function assigned to this msg", 5) }
698 } elsif ($target eq "*") {
699 # msg is for all clients
701 my @target_addresses = keys(%$known_clients);
702 foreach my $target_address (@target_addresses) {
703 if ($target_address eq $source) { next; }
704 $msg_hash->{target} = [$target_address];
705 &send_msg_hash2address($msg_hash, $target_address);
706 }
707 } else {
708 # msg is for one client
710 if (exists $known_clients->{$target}) {
711 # target is known
713 &send_msg_hash2address($msg_hash, $target);
714 } else {
715 # target is not known
717 daemon_log("ERROR: target $target is not known in known_clients", 1);
718 }
719 }
720 } else {
721 # we have multiple target symbols
723 my $target_string = join(", ", @targets);
724 daemon_log("msg is for:", 7);
725 daemon_log("\t$target_string", 7);
727 my $target_address;
728 foreach $target_address (@targets) {
729 if (exists $known_clients->{$target_address}) {
730 # target_address is known
732 &send_msg_hash2address($msg_hash, $target_address);
733 daemon_log("server forwards msg $header to client $target_address", 3);
734 } else {
735 # target is not known
737 daemon_log("ERROR: target $target_address is not known in known_clients", 1);
738 }
739 }
742 }
744 return;
745 }
748 #=== FUNCTION ================================================================
749 # NAME: open_socket
750 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
751 # [PeerPort] string necessary if port not appended by PeerAddr
752 # RETURNS: socket IO::Socket::INET
753 # DESCRIPTION: open a socket to PeerAddr
754 #===============================================================================
755 sub open_socket {
756 my ($PeerAddr, $PeerPort) = @_ ;
757 if(defined($PeerPort)){
758 $PeerAddr = $PeerAddr.":".$PeerPort;
759 }
760 my $socket;
761 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
762 Porto => "tcp" ,
763 Type => SOCK_STREAM,
764 Timeout => 5,
765 );
766 if(not defined $socket) {
767 return;
768 }
769 daemon_log("open_socket:", 7);
770 daemon_log("\t$PeerAddr", 7);
771 return $socket;
772 }
775 #=== FUNCTION ================================================================
776 # NAME: open_fifo
777 # PARAMETERS: $fifo_path
778 # RETURNS: 0: FIFO couldn"t be setup, 1: FIFO setup correctly
779 # DESCRIPTION: creates a FIFO at $fifo_path
780 #===============================================================================
781 sub open_fifo {
782 my ($fifo_path) = @_ ;
783 if( -p $fifo_path ) {
784 daemon_log("FIFO at $fifo_path already exists! Is being deleted!", 1);
785 unlink($fifo_path);
786 }
787 POSIX::mkfifo($fifo_path, 0666) or die "can't mkfifo $fifo_path: $!";
788 daemon_log( "FIFO started at $fifo_path", 1) ;
789 return 1;
790 }
793 #=== FUNCTION ================================================================
794 # NAME: read_from_socket
795 # PARAMETERS: socket fh -
796 # RETURNS: result string - readed characters from socket
797 # DESCRIPTION: reads data from socket in 16 byte steps
798 #===============================================================================
799 sub read_from_socket {
800 my ($socket) = @_;
801 my $result = "";
803 $socket->blocking(1);
804 $result = <$socket>;
806 $socket->blocking(0);
807 while ( my $char = <$socket> ) {
808 if (not defined $char) { last }
809 $result .= $char;
810 }
812 # my $len = 16;
813 # while($len == 16){
814 # my $char;
815 # $len = sysread($socket, $char, 16);
816 # if($len != 16) { last }
817 # $result .= $char;
818 # }
819 return $result;
820 }
823 #=== FUNCTION ================================================================
824 # NAME: create_xml_hash
825 # PARAMETERS: header - string - message header (required)
826 # source - string - where the message come from (required)
827 # target - string - where the message should go to (required)
828 # [header_value] - string - something usefull (optional)
829 # RETURNS: hash - hash - nomen est omen
830 # DESCRIPTION: creates a key-value hash, all values are stored in a array
831 #===============================================================================
832 sub create_xml_hash {
833 my ($header, $source, $target, $header_value) = @_;
834 my $hash = {
835 header => [$header],
836 source => [$source],
837 target => [$target],
838 $header => [$header_value],
839 };
840 #daemon_log("create_xml_hash:", 7),
841 #chomp(my $tmp = Dumper $hash);
842 #daemon_log("\t$tmp", 7);
843 return $hash
844 }
847 #=== FUNCTION ================================================================
848 # NAME: create_xml_string
849 # PARAMETERS: xml_hash - hash - hash from function create_xml_hash
850 # RETURNS: xml_string - string - xml string representation of the hash
851 # DESCRIPTION: transform the hash to a string using XML::Simple module
852 #===============================================================================
853 sub create_xml_string {
854 my ($xml_hash) = @_ ;
855 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
856 $xml_string =~ s/[\n]+//g;
857 #daemon_log("create_xml_string:",7);
858 #daemon_log("$xml_string\n", 7);
859 return $xml_string;
860 }
863 #=== FUNCTION ================================================================
864 # NAME: add_content2xml_hash
865 # PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
866 # element - string - key for the hash
867 # content - string - value for the hash
868 # RETURNS: nothing
869 # DESCRIPTION: add key-value pair to xml_ref, if key alread exists, then append value to list
870 #===============================================================================
871 sub add_content2xml_hash {
872 my ($xml_ref, $element, $content) = @_;
873 if(not exists $$xml_ref{$element} ) {
874 $$xml_ref{$element} = [];
875 }
876 my $tmp = $$xml_ref{$element};
877 push(@$tmp, $content);
878 return;
879 }
882 #=== FUNCTION ================================================================
883 # NAME: get_content_from_xml_hash
884 # PARAMETERS: xml_ref - ref - reference of the xml hash
885 # element - string - key of the value you want
886 # RETURNS: value - string - if key is either header, target or source
887 # value - list - for all other keys in xml hash
888 # DESCRIPTION:
889 #===============================================================================
890 sub get_content_from_xml_hash {
891 my ($xml_ref, $element) = @_ ;
892 my $result = $xml_ref->{$element};
893 if( $element eq "header" || $element eq "target" || $element eq "source") {
894 return @$result[0];
895 }
896 return @$result;
897 }
900 #=== FUNCTION ================================================================
901 # NAME: encrypt_msg
902 # PARAMETERS: msg - string - message to encrypt
903 # my_cipher - ref - reference to a Crypt::Rijndael object
904 # RETURNS: crypted_msg - string - crypted message
905 # DESCRIPTION: crypts the incoming message with the Crypt::Rijndael module
906 #===============================================================================
907 sub encrypt_msg {
908 my ($msg, $my_cipher) = @_;
909 if(not defined $my_cipher) { print "no cipher object\n"; }
910 $msg = "\0"x(16-length($msg)%16).$msg;
911 my $crypted_msg = $my_cipher->encrypt($msg);
912 chomp($crypted_msg = &encode_base64($crypted_msg));
913 return $crypted_msg;
914 }
917 #=== FUNCTION ================================================================
918 # NAME: decrypt_msg
919 # PARAMETERS: crypted_msg - string - message to decrypt
920 # my_cipher - ref - reference to a Crypt::Rijndael object
921 # RETURNS: msg - string - decrypted message
922 # DESCRIPTION: decrypts the incoming message with the Crypt::Rijndael module
923 #===============================================================================
924 sub decrypt_msg {
925 my ($crypted_msg, $my_cipher) = @_ ;
926 $crypted_msg = &decode_base64($crypted_msg);
927 my $msg = $my_cipher->decrypt($crypted_msg);
928 $msg =~ s/\0*//g;
929 return $msg;
930 }
933 #=== FUNCTION ================================================================
934 # NAME: create_ciphering
935 # PARAMETERS: passwd - string - used to create ciphering
936 # RETURNS: cipher - object
937 # DESCRIPTION: creates a Crypt::Rijndael::MODE_CBC object with passwd as key
938 #===============================================================================
939 sub create_ciphering {
940 my ($passwd) = @_;
941 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
942 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
944 #daemon_log("iv: $iv", 7);
945 #daemon_log("key: $passwd", 7);
946 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
947 $my_cipher->set_iv($iv);
948 return $my_cipher;
949 }
952 #=== FUNCTION ================================================================
953 # NAME: send_msg_hash2address
954 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
955 # PeerAddr string - socket address to send msg
956 # PeerPort string - socket port, if not included in socket address
957 # RETURNS: nothing
958 # DESCRIPTION: ????
959 #===============================================================================
960 sub send_msg_hash2address {
961 my ($msg_hash, $address, $passwd) = @_ ;
963 # fetch header for logging
964 my $header = &get_content_from_xml_hash($msg_hash, "header");
966 # generate xml string
967 my $msg_xml = &create_xml_string($msg_hash);
969 # fetch the appropriated passwd from hash
970 if(not defined $passwd) {
971 if(exists $known_daemons->{$address}) {
972 $passwd = $known_daemons->{$address}->{passwd};
973 } elsif(exists $known_clients->{$address}) {
974 $passwd = $known_clients->{$address}->{passwd};
976 } else {
977 daemon_log("$address not known, neither as server nor as client", 1);
978 return;
979 }
980 }
982 # create ciphering object
983 my $act_cipher = &create_ciphering($passwd);
985 # encrypt xml msg
986 my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
988 # opensocket
989 my $socket = &open_socket($address);
990 if(not defined $socket){
991 daemon_log( "cannot send '$header'-msg to $address , server not reachable", 5);
993 if (exists $known_clients->{$address}) {
994 if ($known_clients->{$address}->{status} eq "down") {
995 # if status of not reachable client is already 'down', then delete client from known_clients
996 &clean_up_known_clients($address);
998 } else {
999 # update status to 'down'
1000 &update_known_clients(hostname=>$address, status=>"down");
1002 }
1003 }
1004 return;
1005 }
1007 # send xml msg
1008 print $socket $crypted_msg."\n";
1010 close $socket;
1012 daemon_log("send '$header'-msg to $address", 1);
1014 daemon_log("$msg_xml", 5);
1016 #daemon_log("crypted message:",7);
1017 #daemon_log("\t$crypted_msg", 7);
1019 # update status of client in known_clients with last send msg
1020 if(exists $known_daemons->{$address}) {
1021 #&update_known_daemons();
1022 } elsif(exists $known_clients->{$address}) {
1023 &update_known_clients(hostname=>$address, status=>$header);
1024 }
1026 return;
1027 }
1030 #=== FUNCTION ================================================================
1031 # NAME: send_msg_hash2bus
1032 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
1033 # RETURNS: nothing
1034 # DESCRIPTION: ????
1035 #===============================================================================
1036 sub send_msg_hash2bus {
1037 my($msg_hash) = @_;
1039 # fetch header for logging
1040 my $header = &get_content_from_xml_hash($msg_hash, "header");
1042 # generate xml string
1043 my $msg_xml = &create_xml_string($msg_hash);
1045 # encrypt xml msg
1046 my $crypted_msg = &encrypt_msg($msg_xml, $bus_cipher);
1048 # open socket
1049 my $socket = &open_socket($bus_address);
1050 if(not defined $socket){
1051 daemon_log( "cannot send '$header'-msg to $bus_address , bus not reachable", 5);
1052 return;
1053 }
1055 # send xml msg
1056 print $socket $crypted_msg."\n";
1058 close $socket;
1061 daemon_log("send '$header'-msg to bus", 1);
1062 daemon_log("$msg_xml", 5);
1063 #daemon_log("crypted msg:",7);
1064 #daemon_log("\t$crypted_msg", 7);
1066 return;
1067 }
1075 ##=== FUNCTION ================================================================
1076 ## NAME: new_passwd
1077 ## PARAMETERS: msg_hash - ref - hash from function create_xml_hash
1078 ## RETURNS: nothing
1079 ## DESCRIPTION: process this incoming message
1080 ##===============================================================================
1081 #sub new_passwd {
1082 # my ($msg_hash) = @_;
1083 #
1084 # my $source = &get_content_from_xml_hash($msg_hash, "source");
1085 # my $passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
1086 #
1087 # if (exists $known_daemons->{$source}) {
1088 # &add_content2known_daemons(hostname=>$source, status=>"new_passwd", passwd=>$passwd);
1089 # $bus_cipher = &create_ciphering($passwd);
1090 # my $hash = &create_xml_hash("confirm_new_passwd", "$server_ip:$server_port", "$source");
1091 # &send_msg_hash2address($hash, $source);
1092 #
1093 # } elsif (exists $known_clients->{$source}) {
1094 # &add_content2known_clients(hostname=>$source, status=>"new_passwd", passwd=>$passwd);
1095 #
1096 # } else {
1097 # daemon_log("ERROR: $source not known, neither in known_daemons nor in known_clients", 1)
1098 # }
1099 #
1100 # return;
1101 #}
1104 ##=== FUNCTION ================================================================
1105 ## NAME: make ping
1106 ## PARAMETERS: address - string - address which should be pinged
1107 ## RETURNS: nothing
1108 ## DESCRIPTION: send ping message to address
1109 ##===============================================================================
1110 #sub make_ping {
1111 # my ($msg_hash) = @_;
1112 #
1113 # my $source = &get_content_from_xml_hash($msg_hash, "source");
1114 # my $target = &get_content_from_xml_hash($msg_hash, "target");
1115 #
1116 # print "make_ping:$source\n";
1117 # my $out_hash = &create_xml_hash("ping", $target, $source);
1118 # &send_msg_hash2address($out_hash, $source);
1119 # return;
1120 #}
1123 ##=== FUNCTION ================================================================
1124 ## NAME: got_ping
1125 ## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
1126 ## RETURNS: nothing
1127 ## DESCRIPTION: process this incoming message
1128 ##===============================================================================
1129 #sub got_ping {
1130 # my ($msg_hash) = @_;
1131 #
1132 # my $source = &get_content_from_xml_hash($msg_hash, 'source');
1133 # my $target = &get_content_from_xml_hash($msg_hash, 'target');
1134 # my $header = &get_content_from_xml_hash($msg_hash, 'header');
1135 #
1136 # if(exists $known_daemons->{$source}) {
1137 # &add_content2known_daemons(hostname=>$source, status=>$header);
1138 # } else {
1139 # &add_content2known_clients(hostname=>$source, status=>$header);
1140 # }
1141 #
1142 # return;
1143 #}
1146 ##=== FUNCTION ================================================================
1147 ## NAME: here_i_am
1148 ## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
1149 ## RETURNS: nothing
1150 ## DESCRIPTION: process this incoming message
1151 ##===============================================================================
1152 #sub here_i_am {
1153 # my ($msg_hash) = @_;
1154 #
1155 # my $source = &get_content_from_xml_hash($msg_hash, "source");
1156 # my $mac_address = (&get_content_from_xml_hash($msg_hash, "mac_address"))[0];
1157 # my $out_hash;
1158 #
1159 # # number of known clients
1160 # my $nu_clients = keys %$known_clients;
1161 #
1162 # # check wether client address or mac address is already known
1163 # if (exists $known_clients->{$source}) {
1164 # daemon_log("WARNING: $source is already known as a client", 1);
1165 # daemon_log("WARNING: values for $source are being overwritten", 1);
1166 # $nu_clients --;
1167 # }
1168 #
1169 # # number of actual activ clients
1170 # my $act_nu_clients = $nu_clients;
1171 #
1172 # daemon_log("number of actual activ clients: $act_nu_clients", 5);
1173 # daemon_log("number of maximal allowed clients: $max_clients", 5);
1174 #
1175 # if($max_clients <= $act_nu_clients) {
1176 # my $out_hash = &create_xml_hash("denied", $server_address, $source);
1177 # &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
1178 # my $passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
1179 # &send_msg_hash2address($out_hash, $source, $passwd);
1180 # return;
1181 # }
1182 #
1183 # # new client accepted
1184 # my $new_passwd = (&get_content_from_xml_hash($msg_hash, "new_passwd"))[0];
1185 #
1186 # # create known_daemons entry
1187 # my $events = (&get_content_from_xml_hash($msg_hash, "events"))[0];
1188 # &create_known_client($source);
1189 # &add_content2known_clients(hostname=>$source, events=>$events, mac_address=>$mac_address,
1190 # status=>"registered", passwd=>$new_passwd);
1191 #
1192 # # return acknowledgement to client
1193 # $out_hash = &create_xml_hash("registered", $server_address, $source);
1194 # &send_msg_hash2address($out_hash, $source);
1195 #
1196 # # notify registered client to bus
1197 # $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
1198 # &send_msg_hash2bus($out_hash);
1199 #
1200 # # give the new client his ldap config
1201 # &new_ldap_config($source);
1202 #
1203 # return;
1204 #}
1207 #=== FUNCTION ================================================================
1208 # NAME: who_has
1209 # PARAMETERS: msg_hash - hash - hash from function create_xml_hash
1210 # RETURNS: nothing
1211 # DESCRIPTION: process this incoming message
1212 #===============================================================================
1213 #sub who_has {
1214 # my ($msg_hash) = @_ ;
1215 #
1216 # # what is your search pattern
1217 # my $search_pattern = (&get_content_from_xml_hash($msg_hash, "who_has"))[0];
1218 # my $search_element = (&get_content_from_xml_hash($msg_hash, $search_pattern))[0];
1219 # daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
1220 #
1221 # # scanning known_clients for search_pattern
1222 # my @host_addresses = keys %$known_clients;
1223 # my $known_clients_entries = length @host_addresses;
1224 # my $host_address;
1225 # foreach my $host (@host_addresses) {
1226 # my $client_element = $known_clients->{$host}->{$search_pattern};
1227 # if ($search_element eq $client_element) {
1228 # $host_address = $host;
1229 # last;
1230 # }
1231 # }
1232 #
1233 # # search was successful
1234 # if (defined $host_address) {
1235 # my $source = @{$msg_hash->{source}}[0];
1236 # my $out_msg = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
1237 # &add_content2xml_hash($out_msg, "mac_address", $search_element);
1238 # &send_msg_hash2address($out_msg, $bus_address);
1239 # }
1240 # return;
1241 #}
1244 #sub who_has_i_do {
1245 # my ($msg_hash) = @_ ;
1246 # my $header = &get_content_from_xml_hash($msg_hash, "header");
1247 # my $source = &get_content_from_xml_hash($msg_hash, "source");
1248 # my $search_param = (&get_content_from_xml_hash($msg_hash, $header))[0];
1249 # my $search_value = (&get_content_from_xml_hash($msg_hash, $search_param))[0];
1250 # print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
1251 #}
1254 #=== FUNCTION ================================================================
1255 # NAME: update_status
1256 # PARAMETERS: msg_hash - hash - hash from function create_xml_hash
1257 # RETURNS: nothing
1258 # DESCRIPTION: process this incoming message
1259 #===============================================================================
1260 #sub update_status {
1261 # my ($msg_hash) = @_;
1262 # my $header = &get_content_from_xml_hash($msg_hash, "header");
1263 # my $source = &get_content_from_xml_hash($msg_hash, "source");
1264 # my $new_status = (&get_content_from_xml_hash($msg_hash, "update_status"))[0];
1265 #
1266 # # find the source
1267 # my $act_known_hash;
1268 # if (exists $known_daemons->{$source}) {
1269 #
1270 # &add_content2known_daemons(hostname=>$source, status=>$new_status);
1271 # } elsif (exists $known_clients->{$source}) {
1272 # &update_known_clients(hostname=>$source, status=>$new_status);
1273 # #&add_content2known_clients(hostname=>$source, status=>$new_status);
1274 # } else {
1275 # daemon_log("ERROR: got $header-msg, but cannot find $source in my hashes, unable to update status", 1);
1276 # return;
1277 # }
1278 #
1279 # return;
1280 #}
1283 ##=== FUNCTION ================================================================
1284 ## NAME: new_ldap_config
1285 ## PARAMETERS: address - string - ip address and port of a host
1286 ## RETURNS: nothing
1287 ## DESCRIPTION: send to address the ldap configuration found for dn gotoLdapServer
1288 ##===============================================================================
1289 #sub new_ldap_config {
1290 # my ($address) = @_ ;
1291 #
1292 # if (not exists $known_clients->{$address}) {
1293 # daemon_log("ERROR: $address does not exist in known_clients, cannot send him his ldap config", 1);
1294 # return;
1295 # }
1296 #
1297 # my $mac_address = $known_clients->{$address}->{"mac_address"};
1298 # if (not defined $mac_address) {
1299 # daemon_log("ERROR: no mac address found for client $address", 1);
1300 # return;
1301 # }
1302 #
1303 # # fetch dn
1304 # my $goHard_cmd = "ldapsearch -x '(&(objectClass=goHard)(macAddress=00:11:22:33:44:57))' dn gotoLdapServer";
1305 # my $dn;
1306 # my @gotoLdapServer;
1307 # open (PIPE, "$goHard_cmd 2>&1 |");
1308 # while(<PIPE>) {
1309 # chomp $_;
1310 # # If it's a comment, goto next
1311 # if ($_ =~ m/^[#]/) { next;}
1312 # if ($_ =~ m/^dn: ([\S]+?)$/) {
1313 # $dn = $1;
1314 # } elsif ($_ =~ m/^gotoLdapServer: ([\S]+?)$/) {
1315 # push(@gotoLdapServer, $1);
1316 # }
1317 # }
1318 # close(PIPE);
1319 #
1320 # # no dn found
1321 # if (not defined $dn) {
1322 # daemon_log("ERROR: no dn arose from command: $goHard_cmd", 1);
1323 # return;
1324 # }
1325 #
1326 # # no gotoLdapServer found
1327 # my $gosaGroupOfNames_cmd = "ldapsearch -x '(&(objectClass=gosaGroupOfNames)(member=$dn))' gotoLdapServer";
1328 # if (@gotoLdapServer == 0) {
1329 # open (PIPE, "$gosaGroupOfNames_cmd 2>&1 |");
1330 # while(<PIPE>) {
1331 # chomp $_;
1332 # if ($_ =~ m/^[#]/) { next; }
1333 # if ($_ =~ m/^gotoLdapServer: ([\S]+?)$/) {
1334 # push(@gotoLdapServer, $1);
1335 # }
1336 # }
1337 # close(PIPE);
1338 # }
1339 #
1340 # # still no gotoLdapServer found
1341 # if (@gotoLdapServer == 0) {
1342 # daemon_log("ERROR: cannot find gotoLdapServer entry in command: $gosaGroupOfNames_cmd", 1);
1343 # return;
1344 # }
1345 #
1346 # # sort @gotoLdapServer and then split of ranking
1347 # my @sorted_gotoLdapServer = sort(@gotoLdapServer);
1348 # @gotoLdapServer = reverse(@sorted_gotoLdapServer);
1349 # foreach (@gotoLdapServer) {
1350 # $_ =~ s/^\d://;
1351 # }
1352 #
1353 # my $t = join(" ", @gotoLdapServer);
1354 #
1355 # my $out_hash = &create_xml_hash("new_ldap_config", $server_address, $address);
1356 # map(&add_content2xml_hash($out_hash, "new_ldap_config", $_), @gotoLdapServer);
1357 # &send_msg_hash2address($out_hash, $address);
1358 #
1359 # return;
1360 #}
1363 ##=== FUNCTION ================================================================
1364 ## NAME: execute_actions
1365 ## PARAMETERS: msg_hash - hash - hash from function create_xml_hash
1366 ## RETURNS: nothing
1367 ## DESCRIPTION: invokes the script specified in msg_hash which is located under
1368 ## /etc/gosad/actions
1369 ##===============================================================================
1370 #sub execute_actions {
1371 # my ($msg_hash) = @_ ;
1372 # my $configdir= '/etc/gosad/actions/';
1373 # my $result;
1374 #
1375 # my $header = &get_content_from_xml_hash($msg_hash, 'header');
1376 # my $source = &get_content_from_xml_hash($msg_hash, 'source');
1377 # my $target = &get_content_from_xml_hash($msg_hash, 'target');
1378 #
1379 #
1380 # if((not defined $source)
1381 # && (not defined $target)
1382 # && (not defined $header)) {
1383 # daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1384 # } else {
1385 # my $parameters="";
1386 # my @params = &get_content_from_xml_hash($msg_hash, $header);
1387 # my $params = join(", ", @params);
1388 # daemon_log("execute_actions: got parameters: $params", 5);
1389 #
1390 # if (@params) {
1391 # foreach my $param (@params) {
1392 # my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1393 # daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1394 # $parameters.= " ".$param_value;
1395 # }
1396 # }
1397 #
1398 # my $cmd= $configdir.$header."$parameters";
1399 # daemon_log("execute_actions: executing cmd: $cmd", 7);
1400 # $result= "";
1401 # open(PIPE, "$cmd 2>&1 |");
1402 # while(<PIPE>) {
1403 # $result.=$_;
1404 # }
1405 # close(PIPE);
1406 # }
1407 #
1408 # # process the event result
1409 #
1410 #
1411 # return;
1412 #}
1415 #=== FUNCTION ================================================================
1416 # NAME: print_known_daemons
1417 # PARAMETERS: nothing
1418 # RETURNS: nothing
1419 # DESCRIPTION: nomen est omen
1420 #===============================================================================
1421 sub print_known_daemons {
1422 my ($tmp) = @_ ;
1423 print "####################################\n";
1424 print "# status of known_daemons\n";
1425 $shmda->shlock(LOCK_EX);
1426 my @hosts = keys %$known_daemons;
1427 foreach my $host (@hosts) {
1428 my $status = $known_daemons->{$host}->{status} ;
1429 my $passwd = $known_daemons->{$host}->{passwd};
1430 my $timestamp = $known_daemons->{$host}->{timestamp};
1431 print "$host\n";
1432 print "\tstatus: $status\n";
1433 print "\tpasswd: $passwd\n";
1434 print "\ttimestamp: $timestamp\n";
1435 }
1436 $shmda->shunlock(LOCK_EX);
1437 print "####################################\n";
1438 return;
1439 }
1442 #=== FUNCTION ================================================================
1443 # NAME: create_known_daemon
1444 # PARAMETERS: hostname - string - key for the hash known_daemons
1445 # RETURNS: nothing
1446 # DESCRIPTION: creates a dummy entry for hostname in known_daemons
1447 #===============================================================================
1448 sub create_known_daemon {
1449 my ($hostname) = @_;
1450 $shmda->shlock(LOCK_EX);
1451 $known_daemons->{$hostname} = {};
1452 $known_daemons->{$hostname}->{status} = "none";
1453 $known_daemons->{$hostname}->{passwd} = "none";
1454 $known_daemons->{$hostname}->{timestamp} = "none";
1455 $shmda->shunlock(LOCK_EX);
1456 return;
1457 }
1460 #=== FUNCTION ================================================================
1461 # NAME: add_content2known_daemons
1462 # PARAMETERS: hostname - string - ip address and port of host (required)
1463 # status - string - (optional)
1464 # passwd - string - (optional)
1465 # mac_address - string - mac address of host (optional)
1466 # RETURNS: nothing
1467 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
1468 #===============================================================================
1469 sub add_content2known_daemons {
1470 my $arg = {
1471 hostname => undef, status => undef, passwd => undef,
1472 mac_address => undef, events => undef,
1473 @_ };
1474 my $hostname = $arg->{hostname};
1475 my $status = $arg->{status};
1476 my $passwd = $arg->{passwd};
1477 my $mac_address = $arg->{mac_address};
1478 my $events = $arg->{events};
1480 if (not defined $hostname) {
1481 daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
1482 return;
1483 }
1485 my ($seconds, $minutes, $hours, $monthday, $month,
1486 $year, $weekday, $yearday, $sommertime) = localtime(time);
1487 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1488 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1489 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1490 $month+=1;
1491 $month = $month < 10 ? $month = "0".$month : $month;
1492 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1493 $year+=1900;
1494 my $t = "$year$month$monthday$hours$minutes$seconds";
1496 $shmda->shlock(LOCK_EX);
1497 if (defined $status) {
1498 $known_daemons->{$hostname}->{status} = $status;
1499 }
1500 if (defined $passwd) {
1501 $known_daemons->{$hostname}->{passwd} = $passwd;
1502 }
1503 if (defined $mac_address) {
1504 $known_daemons->{$hostname}->{mac_address} = $mac_address;
1505 }
1506 if (defined $events) {
1507 $known_daemons->{$hostname}->{events} = $events;
1508 }
1509 $known_daemons->{$hostname}->{timestamp} = $t;
1510 $shmda->shlock(LOCK_EX);
1511 return;
1512 }
1515 #=== FUNCTION ================================================================
1516 # NAME: update_known_daemons
1517 # PARAMETERS: hostname - string - ip address and port of host (required)
1518 # status - string - (optional)
1519 # passwd - string - (optional)
1520 # client - string - ip address and port of client (optional)
1521 # RETURNS: nothing
1522 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
1523 #===============================================================================
1524 sub update_known_daemons {
1525 my $arg = {
1526 hostname => undef, status => undef, passwd => undef,
1527 @_ };
1528 my $hostname = $arg->{hostname};
1529 my $status = $arg->{status};
1530 my $passwd = $arg->{passwd};
1532 if (not defined $hostname) {
1533 daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
1534 return;
1535 }
1537 my ($seconds, $minutes, $hours, $monthday, $month,
1538 $year, $weekday, $yearday, $sommertime) = localtime(time);
1539 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1540 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1541 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1542 $month+=1;
1543 $month = $month < 10 ? $month = "0".$month : $month;
1544 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1545 $year+=1900;
1546 my $t = "$year$month$monthday$hours$minutes$seconds";
1548 $shmda->shlock(LOCK_EX);
1549 if (defined $status) {
1550 $known_daemons->{$hostname}->{status} = $status;
1551 }
1552 if (defined $passwd) {
1553 $known_daemons->{$hostname}->{passwd} = $passwd;
1554 }
1555 $known_daemons->{$hostname}->{timestamp} = $t;
1556 $shmda->shunlock(LOCK_EX);
1557 return;
1558 }
1561 #=== FUNCTION ================================================================
1562 # NAME: print_known_clients
1563 # PARAMETERS: nothing
1564 # RETURNS: nothing
1565 # DESCRIPTION: nomen est omen
1566 #===============================================================================
1567 sub print_known_clients {
1569 print "####################################\n";
1570 print "# status of known_clients\n";
1571 $shmcl->shlock(LOCK_EX);
1572 my @hosts = keys %$known_clients;
1573 if (@hosts) {
1574 foreach my $host (@hosts) {
1575 my $status = $known_clients->{$host}->{status} ;
1576 my $passwd = $known_clients->{$host}->{passwd};
1577 my $timestamp = $known_clients->{$host}->{timestamp};
1578 my $mac_address = $known_clients->{$host}->{mac_address};
1579 my $events = $known_clients->{$host}->{events};
1580 print "$host\n";
1581 print "\tstatus: $status\n";
1582 print "\tpasswd: $passwd\n";
1583 print "\ttimestamp: $timestamp\n";
1584 print "\tmac_address: $mac_address\n";
1585 print "\tevents: $events\n";
1586 }
1587 }
1588 $shmcl->shunlock(LOCK_EX);
1589 print "####################################\n";
1590 return;
1591 }
1597 #=== FUNCTION ================================================================
1598 # NAME: create_known_client
1599 # PARAMETERS: hostname - string - key for the hash known_clients
1600 # RETURNS: nothing
1601 # DESCRIPTION: creates a dummy entry for hostname in known_clients
1602 #===============================================================================
1603 sub create_known_client {
1604 my ($hostname) = @_;
1605 $shmcl->shlock(LOCK_EX);
1606 $known_clients->{$hostname} = {};
1607 $known_clients->{$hostname}->{status} = "none";
1608 $known_clients->{$hostname}->{passwd} = "none";
1609 $known_clients->{$hostname}->{timestamp} = "none";
1610 $known_clients->{$hostname}->{mac_address} = "none";
1611 $known_clients->{$hostname}->{events} = "none";
1612 $shmcl->shunlock(LOCK_EX);
1613 return;
1614 }
1619 #=== FUNCTION ================================================================
1620 # NAME: add_content2known_clients
1621 # PARAMETERS: hostname - string - ip address and port of host (required)
1622 # status - string - (optional)
1623 # passwd - string - (optional)
1624 # mac_address - string - (optional)
1625 # events - string - event of client, executable skripts under /etc/gosac/events
1626 # RETURNS: nothing
1627 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
1628 #===============================================================================
1629 sub add_content2known_clients {
1630 my $arg = {
1631 hostname => undef, status => undef, passwd => undef,
1632 mac_address => undef, events => undef,
1633 @_ };
1634 my $hostname = $arg->{hostname};
1635 my $status = $arg->{status};
1636 my $passwd = $arg->{passwd};
1637 my $mac_address = $arg->{mac_address};
1638 my $events = $arg->{events};
1640 if (not defined $hostname) {
1641 daemon_log("ERROR: function add_content2known_clients is not invoked with requiered parameter 'hostname'", 1);
1642 return;
1643 }
1645 my ($seconds, $minutes, $hours, $monthday, $month,
1646 $year, $weekday, $yearday, $sommertime) = localtime(time);
1647 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1648 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1649 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1650 $month+=1;
1651 $month = $month < 10 ? $month = "0".$month : $month;
1652 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1653 $year+=1900;
1654 my $t = "$year$month$monthday$hours$minutes$seconds";
1656 $shmcl->shlock(LOCK_EX);
1657 if (defined $status) {
1658 $known_clients->{$hostname}->{status} = $status;
1659 }
1660 if (defined $passwd) {
1661 $known_clients->{$hostname}->{passwd} = $passwd;
1662 }
1663 if (defined $mac_address) {
1664 $known_clients->{$hostname}->{mac_address} = $mac_address;
1665 }
1666 if (defined $events) {
1667 $known_clients->{$hostname}->{events} = $events;
1668 }
1669 $known_clients->{$hostname}->{timestamp} = $t;
1670 $shmcl->shlock(LOCK_EX);
1671 return;
1672 }
1675 #=== FUNCTION ================================================================
1676 # NAME:
1677 # PARAMETERS:
1678 # RETURNS:
1679 # DESCRIPTION:
1680 #===============================================================================
1681 sub clean_up_known_clients {
1682 my ($address) = @_ ;
1684 if (not exists $known_clients->{$address}) {
1685 daemon_log("cannot prune known_clients from $address, client not known", 5);
1686 return;
1687 }
1689 delete $known_clients->{$address};
1691 # send bus a msg that address was deleted from known_clients
1692 my $out_hash = &create_xml_hash('delete_client', $server_address, $bus_address, $address);
1693 &send_msg_hash2bus($out_hash);
1695 daemon_log("client $address deleted from known_clients because of multiple down time", 3);
1696 return;
1697 }
1700 #=== FUNCTION ================================================================
1701 # NAME: update_known_clients
1702 # PARAMETERS: hostname - string - ip address and port of host (required)
1703 # status - string - (optional)
1704 # passwd - string - (optional)
1705 # client - string - ip address and port of client (optional)
1706 # RETURNS: nothing
1707 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
1708 #===============================================================================
1709 sub update_known_clients {
1710 my $arg = {
1711 hostname => undef, status => undef, passwd => undef,
1712 mac_address => undef, events => undef,
1713 @_ };
1714 my $hostname = $arg->{hostname};
1715 my $status = $arg->{status};
1716 my $passwd = $arg->{passwd};
1717 my $mac_address = $arg->{mac_address};
1718 my $events = $arg->{events};
1720 if (not defined $hostname) {
1721 daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
1722 return;
1723 }
1725 my ($seconds, $minutes, $hours, $monthday, $month,
1726 $year, $weekday, $yearday, $sommertime) = localtime(time);
1727 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
1728 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
1729 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
1730 $month+=1;
1731 $month = $month < 10 ? $month = "0".$month : $month;
1732 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
1733 $year+=1900;
1734 my $t = "$year$month$monthday$hours$minutes$seconds";
1736 $shmcl->shlock(LOCK_EX);
1737 if (defined $status) {
1738 $known_clients->{$hostname}->{status} = $status;
1739 }
1740 if (defined $passwd) {
1741 $known_clients->{$hostname}->{passwd} = $passwd;
1742 }
1743 if (defined $mac_address) {
1744 $known_clients->{$hostname}->{mac_address} = $mac_address;
1745 }
1746 if (defined $events) {
1747 $known_clients->{$hostname}->{events} = $events;
1748 }
1749 $known_clients->{$hostname}->{timestamp} = $t;
1750 $shmcl->shunlock(LOCK_EX);
1751 return;
1752 }
1760 #==== MAIN = main ==============================================================
1762 # parse commandline options
1763 Getopt::Long::Configure( "bundling" );
1764 GetOptions("h|help" => \&usage,
1765 "c|config=s" => \$cfg_file,
1766 "f|foreground" => \$foreground,
1767 "v|verbose+" => \$verbose,
1768 "no-bus+" => \$no_bus,
1769 "no-arp+" => \$no_arp,
1770 );
1772 # read and set config parameters
1773 &check_cmdline_param ;
1774 &read_configfile;
1775 &check_pid;
1776 &import_modules;
1778 $SIG{CHLD} = 'IGNORE';
1780 # restart daemon log file
1781 if(-e $log_file ) { unlink $log_file }
1782 daemon_log(" ", 1);
1783 daemon_log("gosad started!", 1);
1785 # Just fork, if we"re not in foreground mode
1786 if( ! $foreground ) { $pid = fork(); }
1787 else { $pid = $$; }
1789 # Do something useful - put our PID into the pid_file
1790 if( 0 != $pid ) {
1791 open( LOCK_FILE, ">$pid_file" );
1792 print LOCK_FILE "$pid\n";
1793 close( LOCK_FILE );
1794 if( !$foreground ) { exit( 0 ) };
1795 }
1797 # detect own ip and mac address
1798 ($server_ip, $server_mac_address) = &get_ip_and_mac();
1799 if (not defined $server_ip) {
1800 die "EXIT: ip address of $0 could not be detected";
1801 }
1802 daemon_log("server ip address detected: $server_ip", 1);
1803 daemon_log("server mac address detected: $server_mac_address", 1);
1805 # setup xml parser
1806 $xml = new XML::Simple();
1808 # create cipher object
1809 $bus_cipher = &create_ciphering($bus_passwd);
1810 $bus_address = "$bus_ip:$bus_port";
1812 # create reading and writing vectors
1813 my $rbits = my $wbits = my $ebits = "";
1815 # open server socket
1816 $server_address = "$server_ip:$server_port";
1817 if($server_activ eq "on"){
1818 daemon_log(" ", 1);
1819 $server = IO::Socket::INET->new(LocalPort => $server_port,
1820 Type => SOCK_STREAM,
1821 Reuse => 1,
1822 Listen => 20,
1823 );
1824 if(not defined $server){
1825 daemon_log("cannot be a tcp server at $server_port : $@");
1826 } else {
1827 daemon_log("start server:", 1);
1828 daemon_log("\t$server_ip:$server_port",1) ;
1829 vec($rbits, fileno $server, 1) = 1;
1830 vec($wbits, fileno $server, 1) = 1;
1831 }
1832 }
1834 # register at bus
1835 if ($no_bus > 0) {
1836 $bus_activ = "off"
1837 }
1838 if($bus_activ eq "on") {
1839 daemon_log(" ", 1);
1840 ®ister_at_bus();
1841 }
1844 daemon_log(" ", 1);
1846 # start arp fifo
1847 if ($no_arp > 0) {
1848 $arp_activ = "off";
1849 }
1850 my $my_fifo;
1851 if($arp_activ eq "on") {
1852 $my_fifo = &open_fifo($arp_fifo_path);
1853 if($my_fifo == 0) { die "fifo file disappeared\n" }
1854 sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
1856 vec($rbits, fileno $arp_fifo, 1) = 1;
1857 }
1859 $gosa_address = "$gosa_ip:$gosa_port";
1860 # start gosa inferface fifos
1861 if ($gosa_activ eq "on") {
1862 daemon_log(" ",1);
1863 $gosa_server = IO::Socket::INET->new(LocalPort => $gosa_port,
1864 Type => SOCK_STREAM,
1865 Reuse => 1,
1866 Listen => 1,
1867 );
1868 if (not defined $gosa_server) {
1869 daemon_log("cannot start tcp server at $gosa_port for communication to gosa: $@", 1);
1870 } else {
1871 daemon_log("start server at for communication to gosa", 1);
1872 daemon_log("\t$server_ip:$gosa_port");
1873 vec($rbits, fileno $gosa_server, 1) = 1;
1875 }
1878 #&open_fifo($gosa_fifo_in);
1879 #sysopen(GOSA_FIFO_IN, $gosa_fifo_in, O_RDWR) or die "can't read from GOSA_FIFO_IN: $!" ;
1880 #vec($rbits, fileno GOSA_FIFO_IN, 1) = 1;
1882 #&open_fifo($gosa_fifo_out);
1883 #sysopen(GOSA_FIFO_OUT, $gosa_fifo_out, O_RDWR) or die "can't read from GOSA_FIFO_IN: $!" ;
1885 }
1888 ###################################
1889 #everything ready, okay, lets start
1890 ###################################
1891 while(1) {
1893 # add all handles from the childs
1894 while ( my ($pid, $child_hash) = each %busy_child ) {
1896 # check whether process still exists
1897 my $exitus_pid = waitpid($pid, WNOHANG);
1898 if($exitus_pid != 0) {
1899 delete $busy_child{$pid};
1900 next;
1901 }
1903 # add child fhd to the listener
1904 my $fhd = $$child_hash{'pipe_rd'};
1905 vec($rbits, fileno $fhd, 1) = 1;
1906 }
1908 my ($rout, $wout);
1909 my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1911 # error handling
1912 if($nf < 0 ) {
1913 }
1915 # something is coming in
1916 if($server_activ eq "on" && vec($rout, fileno $server, 1)) {
1917 daemon_log(" ", 1);
1918 my $client = $server->accept();
1919 my $other_end = getpeername($client);
1920 if(not defined $other_end) {
1921 daemon_log("client cannot be identified: $!");
1922 } else {
1923 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1924 my $actual_ip = inet_ntoa($iaddr);
1925 daemon_log("accept client at daemon socket from $actual_ip", 5);
1926 my $in_msg = &read_from_socket($client);
1927 if(defined $in_msg){
1928 chomp($in_msg);
1929 &activating_child($in_msg, $actual_ip);
1930 } else {
1931 daemon_log("cannot read from $actual_ip", 5);
1932 }
1933 }
1934 close($client);
1935 }
1937 if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
1938 my $in_msg = <$arp_fifo>;
1939 chomp($in_msg);
1940 print "arp_activ: msg: $in_msg\n";
1941 my $act_passwd = $known_daemons->{$bus_address}->{passwd};
1942 print "arp_activ: arp_passwd: $act_passwd\n";
1944 my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
1946 my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
1948 if ($target eq $server_address) {
1949 print "arp_activ: forward to server\n";
1950 my $arp_cipher = &create_ciphering($act_passwd);
1951 my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
1952 &activating_child($crypted_msg, $server_ip);
1953 } else {
1954 print "arp_activ: send to bus\n";
1955 &send_msg_hash2address($in_msg_hash, $bus_address);
1956 }
1957 print "\n";
1958 }
1960 if($gosa_activ eq "on" && vec($rout, fileno $gosa_server, 1)) {
1961 daemon_log(" ", 1);
1962 my $client = $gosa_server->accept();
1963 my $other_end = getpeername($client);
1964 if(not defined $other_end) {
1965 daemon_log("client cannot be identified: $!");
1966 } else {
1967 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1968 my $actual_ip = inet_ntoa($iaddr);
1969 daemon_log("accept client at gosa socket from $actual_ip", 5);
1970 my $in_msg = <$client>;
1971 #my $in_msg = &read_from_socket($client);
1973 daemon_log(">>>>>>>>>>> frisch vom socket gelesen\n!$in_msg!\n",1);
1974 if(defined $in_msg){
1975 chomp($in_msg);
1976 &activating_child($in_msg, $actual_ip, $client);
1977 } else {
1978 daemon_log("cannot read from $actual_ip", 5);
1979 }
1980 }
1981 #close($client);
1982 }
1984 # check all processing childs whether they are finished ('done') or
1985 while ( my ($pid, $child_hash) = each %busy_child ) {
1986 my $fhd = $$child_hash{'pipe_rd'};
1988 if (vec($rout, fileno $fhd, 1) ) {
1989 daemon_log("process child $pid is ready to read", 5);
1991 $fhd->blocking(1);
1992 my $in_msg = <$fhd>;
1993 $fhd->blocking(0);
1994 my $part_in_msg;
1995 while ($part_in_msg = <$fhd>) {
1996 if (not defined $part_in_msg) {
1997 last;
1998 }
1999 $in_msg .= $part_in_msg;
2000 }
2001 chomp($in_msg);
2003 daemon_log("process child read: $in_msg", 5);
2004 if (not defined $in_msg) {
2005 next;
2006 } elsif ($in_msg =~ "done") {
2007 delete $busy_child{$pid};
2008 $free_child{$pid} = $child_hash;
2010 } else {
2011 my $act_client = $busy_child{$pid}{client_ref};
2012 print $act_client $in_msg."\n";
2013 my $act_pipe = $busy_child{$pid}{pipe_rd};
2014 sleep(10);
2015 close ($act_client);
2016 delete $busy_child{$pid};
2017 $free_child{$pid} = $child_hash;
2019 }
2020 }
2021 }
2024 }