1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-server
5 #
6 # USAGE: ./gosasc
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: ---
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 #===============================================================================
21 use strict;
22 use warnings;
23 use Getopt::Long;
24 use Config::IniFiles;
25 use POSIX;
26 use Time::HiRes qw( gettimeofday );
28 use Fcntl;
29 use IO::Socket::INET;
30 use Crypt::Rijndael;
31 use MIME::Base64;
32 use Digest::MD5 qw(md5 md5_hex md5_base64);
33 use XML::Simple;
34 use Data::Dumper;
35 use Sys::Syslog qw( :DEFAULT setlogsock);
36 use File::Spec;
37 use Cwd;
38 use GosaSupportDaemon;
41 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
42 my ($server_address, $server_ip, $server_port, $server_domain, $server_passwd, $server_cipher, $server_timeout);
43 my ($client_address, $client_ip, $client_port, $client_mac_address);
44 my ($input_socket, $rbits, $wbits, $ebits, $xml, $known_hosts);
45 my (@events);
47 # default variables
48 my $event_dir = "/etc/gosac/events";
49 $known_hosts = {};
50 $foreground = 0 ;
51 %cfg_defaults =
52 ("general" =>
53 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
54 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
55 },
56 "client" =>
57 {"client_port" => [\$client_port, "20083"],
58 },
59 "server" =>
60 {"server_ip" => [\$server_ip, ""],
61 "server_port" => [\$server_port, "20081"],
62 "server_passwd" => [\$server_passwd, ""],
63 "server_timeout" => [\$server_timeout, 10],
64 "server_domain" => [\$server_domain, ""],
65 },
66 );
69 #=== FUNCTION ================================================================
70 # NAME: read_configfile
71 # PARAMETERS: cfg_file - string -
72 # RETURNS:
73 # DESCRIPTION:
74 #===============================================================================
75 sub read_configfile {
76 my $cfg;
77 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
78 if( -r $cfg_file ) {
79 $cfg = Config::IniFiles->new( -file => $cfg_file );
80 } else {
81 print STDERR "Couldn't read config file!";
82 }
83 } else {
84 $cfg = Config::IniFiles->new() ;
85 }
86 foreach my $section (keys %cfg_defaults) {
87 foreach my $param (keys %{$cfg_defaults{ $section }}) {
88 my $pinfo = $cfg_defaults{ $section }{ $param };
89 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
90 }
91 }
92 }
95 #=== FUNCTION ================================================================
96 # NAME: logging
97 # PARAMETERS: level - string - default 'info'
98 # msg - string -
99 # facility - string - default 'LOG_DAEMON'
100 # RETURNS:
101 # DESCRIPTION:
102 #===============================================================================
103 sub daemon_log {
104 my( $msg, $level ) = @_;
105 if(not defined $msg) { return }
106 if(not defined $level) { $level = 1 }
107 if(defined $log_file){
108 open(LOG_HANDLE, ">>$log_file");
109 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
110 print STDERR "cannot open $log_file: $!";
111 return }
112 chomp($msg);
113 if($level <= $verbose){
114 print LOG_HANDLE $msg."\n";
115 if(defined $foreground) { print $msg."\n" }
116 }
117 }
118 close( LOG_HANDLE );
119 # my ($msg, $level, $facility) = @_;
120 # if(not defined $msg) {return}
121 # if(not defined $level) {$level = "info"}
122 # if(not defined $facility) {$facility = "LOG_DAEMON"}
123 # openlog($0, "pid,cons,", $facility);
124 # syslog($level, $msg);
125 # closelog;
126 # return;
127 }
130 #=== FUNCTION ================================================================
131 # NAME: check_cmdline_param
132 # PARAMETERS:
133 # RETURNS:
134 # DESCRIPTION:
135 #===============================================================================
136 sub check_cmdline_param () {
137 my $err_config;
138 my $err_counter = 0;
139 if( not defined( $cfg_file)) {
140 #$err_config = "please specify a config file";
141 #$err_counter += 1;
142 my $cwd = getcwd;
143 my $name = "/etc/gosa-si/client.conf";
144 $cfg_file = File::Spec->catfile( $cwd, $name );
145 print STDERR "no conf file specified\n try to use default: $cfg_file\n";
146 }
147 if( $err_counter > 0 ) {
148 &usage( "", 1 );
149 if( defined( $err_config)) { print STDERR "$err_config\n"}
150 print STDERR "\n";
151 exit( -1 );
152 }
153 }
156 #=== FUNCTION ================================================================
157 # NAME: check_pid
158 # PARAMETERS:
159 # RETURNS:
160 # DESCRIPTION:
161 #===============================================================================
162 sub check_pid {
163 $pid = -1;
164 # Check, if we are already running
165 if( open(LOCK_FILE, "<$pid_file") ) {
166 $pid = <LOCK_FILE>;
167 if( defined $pid ) {
168 chomp( $pid );
169 if( -f "/proc/$pid/stat" ) {
170 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
171 if( $0 eq $stat ) {
172 close( LOCK_FILE );
173 exit -1;
174 }
175 }
176 }
177 close( LOCK_FILE );
178 unlink( $pid_file );
179 }
181 # create a syslog msg if it is not to possible to open PID file
182 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
183 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
184 if (open(LOCK_FILE, '<', $pid_file)
185 && ($pid = <LOCK_FILE>))
186 {
187 chomp($pid);
188 $msg .= "(PID $pid)\n";
189 } else {
190 $msg .= "(unable to read PID)\n";
191 }
192 if( ! ($foreground) ) {
193 openlog( $0, "cons,pid", "daemon" );
194 syslog( "warning", $msg );
195 closelog();
196 }
197 else {
198 print( STDERR " $msg " );
199 }
200 exit( -1 );
201 }
202 }
205 #=== FUNCTION ================================================================
206 # NAME: get_ip_and_mac
207 # PARAMETERS: nothing
208 # RETURNS: (ip, mac)
209 # DESCRIPTION: executes /sbin/ifconfig and parses the output, the first occurence
210 # of a inet address is returned as well as the mac address in the line
211 # above the inet address
212 #===============================================================================
213 sub get_ip_and_mac {
214 my $ip = "0.0.0.0.0"; # Defualt-IP
215 my $mac = "00:00:00:00:00:00"; # Default-MAC
216 my @ifconfig = qx(/sbin/ifconfig);
217 foreach(@ifconfig) {
218 if (/Hardware Adresse (\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/) {
219 $mac = "$1:$2:$3:$4:$5:$6";
220 next;
221 }
222 if (/inet Adresse:(\d+).(\d+).(\d+).(\d+)/) {
223 $ip = "$1.$2.$3.$4";
224 last;
225 }
226 }
227 return ($ip, $mac);
228 }
231 #=== FUNCTION ================================================================
232 # NAME: usage
233 # PARAMETERS:
234 # RETURNS:
235 # DESCRIPTION:
236 #===============================================================================
237 sub usage {
238 my( $text, $help ) = @_;
239 $text = undef if( "h" eq $text );
240 (defined $text) && print STDERR "\n$text\n";
241 if( (defined $help && $help) || (!defined $help && !defined $text) ) {
242 print STDERR << "EOF" ;
243 usage: $0 [-hvf] [-c config]
245 -h : this (help) message
246 -c <file> : config file
247 -f : foreground, process will not be forked to background
248 -v : be verbose (multiple to increase verbosity)
249 EOF
250 }
251 print "\n" ;
252 }
254 #=== FUNCTION ================================================================
255 # NAME: get_server_addresses
256 # PARAMETERS:
257 # RETURNS:
258 # DESCRIPTION:
259 #===============================================================================
260 sub get_server_addresses {
261 my $domain= shift;
262 my @result;
263 my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
265 my $output= `$dig_cmd 2>&1`;
266 open (PIPE, "$dig_cmd 2>&1 |");
267 while(<PIPE>) {
268 chomp $_;
269 # If it's not a comment
270 if($_ =~ m/^[^;]/) {
271 my @matches= split /\s+/;
273 # Push hostname with port
274 if($matches[3] eq 'SRV') {
275 push @result, $matches[7].':'.$matches[6];
276 } elsif ($matches[3] eq 'A') {
277 my $i=0;
279 # Substitute the hostname with the ip address of the matching A record
280 foreach my $host (@result) {
281 if ((split /\:/, $host)[0] eq $matches[0]) {
282 $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
283 }
284 $i++;
285 }
286 }
287 }
288 }
289 close(PIPE);
290 return @result;
291 }
294 #=== FUNCTION ================================================================
295 # NAME: register_at_server
296 # PARAMETERS:
297 # RETURNS:
298 # DESCRIPTION:
299 #===============================================================================
300 sub register_at_server {
301 my ($tmp) = @_;
303 # create new passwd and ciphering object for client-server communication
304 my $new_server_passwd = &create_passwd();
305 my $new_server_cipher;
307 # detect all client accepted events
308 opendir(DIR, $event_dir)
309 or daemon_log("cannot find directory $event_dir!\ngosac starts without any accepting events!", 1);
310 my $file_name;
311 @events = ();
312 while(defined($file_name = readdir(DIR))){
313 if ($file_name eq "." || $file_name eq "..") {
314 next;
315 }
316 push(@events, $file_name);
317 }
318 my $events = join(",", @events);
319 daemon_log("found events: $events", 1);
321 # fill in all possible servers
322 my @servers;
323 if (defined $server_domain) {
324 my @tmp_servers = &get_server_addresses($server_domain);
325 foreach my $server (@tmp_servers) { unshift(@servers, $server); }
326 }
327 # add server address from config file at first position of server list
328 if (defined $server_address) {
329 unshift(@servers, $server_address);
330 }
331 daemon_log("found servers in configuration file and via DNS:", 5);
332 foreach my $server (@servers) {
333 daemon_log("\t$server", 5);
334 }
336 my ($rout, $wout, $reg_server);
337 foreach my $server (@servers) {
338 # create msg hash
339 my $register_hash = &create_xml_hash("here_i_am", $client_address, $server);
340 &add_content2xml_hash($register_hash, "new_passwd", $new_server_passwd);
341 &add_content2xml_hash($register_hash, "client_mac_address", $client_mac_address);
342 &add_content2xml_hash($register_hash, "events", $events);
344 # send xml hash to server with general server passwd
345 my $answer = &send_msg_hash2address($register_hash, $server, $server_passwd);
347 # sending fails, no sens to wait for response
348 if ($answer ne "done") { next; }
350 # waiting for response
351 daemon_log("waiting for response...\n", 5);
352 my $nf = select($rout=$rbits, $wout=$wbits, undef, $server_timeout);
354 # something is coming in
355 if(vec $rout, fileno $input_socket, 1) {
356 my $crypted_msg;
357 my $client = $input_socket->accept();
358 my $other_end = getpeername($client);
359 if(not defined $other_end) {
360 daemon_log("client cannot be identified: $!\n");
361 } else {
362 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
363 my $actual_ip = inet_ntoa($iaddr);
364 daemon_log("\naccept client from $actual_ip\n", 5);
365 my $in_msg = &read_from_socket($client);
366 if(defined $in_msg){
367 chomp($in_msg);
368 $crypted_msg = $in_msg;
369 } else {
370 daemon_log("cannot read from $actual_ip\n", 5);
371 }
372 }
373 close($client);
375 # validate acknowledge msg from server
376 $new_server_cipher = &create_ciphering($new_server_passwd);
377 my $msg_hash;
378 eval {
379 my $decrypted_msg = &decrypt_msg($crypted_msg, $new_server_cipher);
380 daemon_log("decrypted register msg: $decrypted_msg", 5);
381 $msg_hash = $xml->XMLin($decrypted_msg, ForceArray=>1);
382 };
383 if($@) {
384 daemon_log("ERROR: do not understand the incoming message:" , 5);
385 daemon_log("$@", 7);
386 } else {
387 my $header = &get_content_from_xml_hash($msg_hash, "header");
388 if($header eq "registered") {
389 $reg_server = $server;
390 last;
391 } elsif($header eq "denied") {
392 my $reason = (&get_content_from_xml_hash($msg_hash, "denied"))[0];
393 daemon_log("registration at $server denied: $reason", 1);
394 } else {
395 daemon_log("cannot register at $server", 1);
396 }
397 }
398 }
399 # kommt antwort nicht, dann probiere es mit dem nächsten in der liste
401 }
403 if(defined $reg_server) {
404 daemon_log("registered at $reg_server", 1);
405 } else {
406 daemon_log("cannot register at any server", 1);
407 daemon_log("exiting!!!", 1);
408 exit(1);
409 }
411 # update the global available variables
412 $server_address = $reg_server;
413 $server_passwd = $new_server_passwd;
414 $server_cipher = $new_server_cipher;
415 return;
416 }
419 #=== FUNCTION ================================================================
420 # NAME: create_xml_hash
421 # PARAMETERS:
422 # RETURNS:
423 # DESCRIPTION:
424 #===============================================================================
425 sub create_xml_hash {
426 my ($header, $source, $target, $header_value) = @_;
427 my $hash = {
428 header => [$header],
429 source => [$source],
430 target => [$target],
431 $header => [$header_value],
432 };
433 daemon_log("create_xml_hash:", 7),
434 chomp(my $tmp = Dumper $hash);
435 daemon_log("\t$tmp\n", 7);
436 return $hash
437 }
440 #=== FUNCTION ================================================================
441 # NAME: create_xml_string
442 # PARAMETERS:
443 # RETURNS:
444 # DESCRIPTION:
445 #===============================================================================
446 sub create_xml_string {
447 my ($xml_hash) = @_ ;
448 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
449 $xml_string =~ s/[\n]+//g;
450 daemon_log("create_xml_string:\n\t$xml_string\n", 7);
451 return $xml_string;
452 }
455 #=== FUNCTION ================================================================
456 # NAME: add_content2xml_hash
457 # PARAMETERS:
458 # RETURNS:
459 # DESCRIPTION:
460 #===============================================================================
461 sub add_content2xml_hash {
462 my ($xml_ref, $element, $content) = @_;
463 if(not exists $$xml_ref{$element} ) {
464 $$xml_ref{$element} = [];
465 }
466 my $tmp = $$xml_ref{$element};
467 push(@$tmp, $content);
468 return;
469 }
472 #=== FUNCTION ================================================================
473 # NAME: get_content_from_xml_hash
474 # PARAMETERS: ref : reference to the xml hash
475 # string: key of the value you want
476 # RETURNS: STRING AND ARRAY
477 # DESCRIPTION: if key of the hash is either 'header', 'target' or 'source' the
478 # function returns a string cause it is expected that these keys
479 # do just have one value, all other keys returns an array!!!
480 #===============================================================================
481 sub get_content_from_xml_hash {
482 my ($xml_ref, $element) = @_;
483 my $result = $xml_ref->{$element};
484 if( $element eq "header" || $element eq "target" || $element eq "source") {
485 return @$result[0];
486 }
487 return @$result;
488 }
490 # my ($xml_ref, $element) = @_;
491 # if (exists $xml_ref->{$element}) {
492 # my $result = $xml_ref->{$element};
493 # if( $element eq "header" || $element eq "target" || $element eq "source") {
494 # return @$result[0];
495 # } else {
496 # return @$result;
497 # }
498 #
499 # } else {
500 # my $result = ();
501 # return @$result;
502 # }
503 #}
506 #=== FUNCTION ================================================================
507 # NAME: encrypt_msg
508 # PARAMETERS:
509 # RETURNS:
510 # DESCRIPTION:
511 #===============================================================================
512 sub encrypt_msg {
513 my ($msg, $my_cipher) = @_;
514 if(not defined $my_cipher) { print "no cipher object\n"; }
515 $msg = "\0"x(16-length($msg)%16).$msg;
516 my $crypted_msg = $my_cipher->encrypt($msg);
517 chomp($crypted_msg = &encode_base64($crypted_msg));
518 return $crypted_msg;
519 }
522 #=== FUNCTION ================================================================
523 # NAME: decrypt_msg
524 # PARAMETERS:
525 # RETURNS:
526 # DESCRIPTION:
527 #===============================================================================
528 sub decrypt_msg {
529 my ($crypted_msg, $my_cipher) = @_ ;
530 $crypted_msg = &decode_base64($crypted_msg);
531 my $msg = $my_cipher->decrypt($crypted_msg);
532 $msg =~ s/\0*//g;
533 return $msg;
534 }
537 #=== FUNCTION ================================================================
538 # NAME: create_ciphering
539 # PARAMETERS:
540 # RETURNS: cipher object
541 # DESCRIPTION:
542 #===============================================================================
543 sub create_ciphering {
544 my ($passwd) = @_;
545 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
546 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
548 #daemon_log("iv: $iv", 7);
549 #daemon_log("key: $passwd", 7);
550 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
551 $my_cipher->set_iv($iv);
552 return $my_cipher;
553 }
556 #=== FUNCTION ================================================================
557 # NAME: create_passwd
558 # PARAMETERS:
559 # RETURNS: cipher object
560 # DESCRIPTION:
561 #===============================================================================
562 sub create_passwd {
563 my $new_passwd = "";
564 for(my $i=0; $i<31; $i++) {
565 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
566 }
568 return $new_passwd;
569 }
572 #=== FUNCTION ================================================================
573 # NAME: send_msg_hash2address
574 # PARAMETERS: msg string - xml message
575 # PeerAddr string - socket address to send msg
576 # PeerPort string - socket port, if not included in socket address
577 # RETURNS: nothing
578 # DESCRIPTION: ????
579 #===============================================================================
580 sub send_msg_hash2address {
581 my ($msg_hash, $address, $passwd) = @_ ;
583 # fetch header for logging
584 my $header = @{$msg_hash->{header}}[0];
586 # generiere xml string
587 my $msg_xml = &create_xml_string($msg_hash);
589 # hole das entsprechende passwd aus dem hash
590 if(not defined $passwd) {
591 if(exists $known_hosts->{$address}) {
592 $passwd = $known_hosts->{$address}->{passwd};
593 } elsif ($address eq $server_address) {
594 $passwd = $server_passwd;
595 } else {
596 daemon_log("$address not known, neither as server nor as client", 1);
597 return "failed";
598 }
599 }
601 # erzeuge ein ciphering object
602 my $act_cipher = &create_ciphering($passwd);
604 # encrypt xml msg
605 my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
607 # öffne socket
608 my $socket = &open_socket($address);
609 if(not defined $socket){
610 daemon_log("cannot open socket to $address, server not reachable", 1);
611 daemon_log("cannot send '$header'-msg", 1);
612 return "failed";
613 }
615 # versende xml msg
616 print $socket $crypted_msg."\n";
618 # schließe socket
619 close $socket;
621 daemon_log("send '$header'-msg to $address", 5);
622 daemon_log("crypted_msg:\n\t$crypted_msg", 7);
624 return "done";
625 }
628 #=== FUNCTION ================================================================
629 # NAME: open_socket
630 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
631 # [PeerPort] string necessary if port not appended by PeerAddr
632 # RETURNS: socket IO::Socket::INET
633 # DESCRIPTION:
634 #===============================================================================
635 sub open_socket {
636 my ($PeerAddr, $PeerPort) = @_ ;
637 if(defined($PeerPort)){
638 $PeerAddr = $PeerAddr.":".$PeerPort;
639 }
640 my $socket;
641 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
642 Porto => "tcp" ,
643 Type => SOCK_STREAM,
644 Timeout => 5,
645 );
646 if(not defined $socket) {
647 #daemon_log("cannot connect to socket at $PeerAddr, $@\n");
648 return;
649 }
650 daemon_log("open_socket:\n\t$PeerAddr", 7);
651 return $socket;
652 }
655 #=== FUNCTION ================================================================
656 # NAME: read_from_socket
657 # PARAMETERS: socket fh -
658 # RETURNS: result string - readed characters from socket
659 # DESCRIPTION: reads data from socket in 16 byte steps
660 #===============================================================================
661 sub read_from_socket {
662 my ($socket) = @_;
663 my $result = "";
665 $socket->blocking(1);
666 $result = <$socket>;
668 $socket->blocking(0);
669 while ( my $char = <$socket> ) {
670 if (not defined $char) { last }
671 $result .= $char;
672 }
673 return $result;
677 # my ($socket) = @_;
678 # my $result = "";
679 # my $len = 16;
680 # while($len == 16){
681 # my $char;
682 # $len = sysread($socket, $char, 16);
683 # if($len != 16) { last }
684 # if($len != 16) { last }
685 # $result .= $char;
686 # }
687 # return $result;
688 }
691 #=== FUNCTION ================================================================
692 # NAME: print_known_hosts_hash
693 # PARAMETERS:
694 # RETURNS:
695 # DESCRIPTION:
696 #===============================================================================
697 sub print_known_hosts_hash {
698 my ($tmp) = @_;
699 print "####################################\n";
700 print "# status of known_hosts\n";
701 my $hosts;
702 my $host_hash;
703 my @hosts = keys %$known_hosts;
704 foreach my $host (@hosts) {
705 #my @elements = keys %$known_hosts->{$host};
706 my $status = $known_hosts->{$host}->{status} ;
707 my $passwd = $known_hosts->{$host}->{passwd};
708 my $timestamp = $known_hosts->{$host}->{timestamp};
709 print "$host\n";
710 print "\t$status\n";
711 print "\t$passwd\n";
712 print "\t$timestamp\n";
713 }
714 print "####################################\n";
715 return;
716 }
718 #=== FUNCTION ================================================================
719 # NAME:
720 # PARAMETERS:
721 # RETURNS:
722 # DESCRIPTION:
723 #===============================================================================
724 sub create_known_hosts_entry {
725 my ($hostname) = @_;
726 $known_hosts->{$hostname} = {};
727 $known_hosts->{$hostname}->{status} = "none";
728 $known_hosts->{$hostname}->{passwd} = "none";
729 $known_hosts->{$hostname}->{timestamp} = "none";
730 return;
731 }
734 #=== FUNCTION ================================================================
735 # NAME:
736 # PARAMETERS:
737 # RETURNS:
738 # DESCRIPTION:
739 #===============================================================================
740 sub update_known_hosts_entry {
741 my ($hostname, $status, $passwd, $timestamp) = @_;
742 my ($seconds, $minutes, $hours, $monthday, $month,
743 $year, $weekday, $yearday, $sommertime) = localtime(time);
744 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
745 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
746 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
747 $month+=1;
748 $month = $month < 10 ? $month = "0".$month : $month;
749 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
750 $year+=1900;
751 my $t = "$year$month$monthday$hours$minutes$seconds";
753 if($status) {
754 $known_hosts->{$hostname}->{status} = $status;
755 }
756 if($passwd) {
757 $known_hosts->{$hostname}->{passwd} = $passwd;
758 }
759 if($timestamp) {
760 $t = $timestamp;
761 }
762 $known_hosts->{$hostname}->{timestamp} = $t;
763 return;
764 }
767 #=== FUNCTION ================================================================
768 # NAME:
769 # PARAMETERS:
770 # RETURNS:
771 # DESCRIPTION:
772 #===============================================================================
773 sub add_content2known_hosts {
774 my ($hostname, $element, $content) = @_;
775 my ($seconds, $minutes, $hours, $monthday, $month,
776 $year, $weekday, $yearday, $sommertime) = localtime(time);
777 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
778 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
779 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
780 $month+=1;
781 $month = $month < 10 ? $month = "0".$month : $month;
782 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
783 $year+=1900;
784 my $t = "$year$month$monthday$hours$minutes$seconds";
786 $known_hosts->{$hostname}->{$element} = $content;
787 $known_hosts->{$hostname}->{timestamp} = $t;
788 return;
789 }
792 #=== FUNCTION ================================================================
793 # NAME:
794 # PARAMETERS:
795 # RETURNS:
796 # DESCRIPTION:
797 #===============================================================================
798 sub process_incoming_msg {
799 my ($crypted_msg) = @_;
800 if(not defined $crypted_msg) {
801 daemon_log("function 'process_incoming_msg': got no msg", 7);
802 }
803 $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
804 $crypted_msg = $1;
805 my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
806 daemon_log("msg from host:", 1);
807 daemon_log("\t$host", 1);
808 daemon_log("crypted msg:", 7);
809 daemon_log("\t$crypted_msg", 7);
811 my $act_cipher = &create_ciphering($server_passwd);
813 # try to decrypt incoming msg
814 my ($msg, $msg_hash);
815 eval{
816 $msg = &decrypt_msg($crypted_msg, $act_cipher);
817 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
818 };
819 if($@) {
820 daemon_log("ERROR: incoming msg cannot be decrypted with server passwd", 1);
821 return;
822 }
824 my $header = &get_content_from_xml_hash($msg_hash, "header");
826 daemon_log("header from msg:", 1);
827 daemon_log("\t$header", 1);
828 daemon_log("msg to process:", 7);
829 daemon_log("\t$msg", 7);
831 #check whether msg to process is a event
832 opendir(DIR, $event_dir)
833 or daemon_log("cannot find directory $event_dir, no events specified", 5);
834 my $file_name;
835 while(defined($file_name = readdir(DIR))){
836 if ($file_name eq "." || $file_name eq "..") {
837 next;
838 }
839 if ($file_name eq $header) {
840 my $cmd = "$event_dir/$file_name '$msg'";
841 my $result_xml = "";
842 open(PIPE, "$cmd 2>&1 |");
843 while(<PIPE>) {
844 $result_xml.=$_;
845 last;
846 }
847 close(PIPE);
848 my $res_hash = &transform_msg2hash($result_xml);
849 my $res_target = @{$res_hash->{target}}[0];
850 &send_msg_hash2address($res_hash, $server_address);
852 return;
853 }
854 }
855 close(DIR);
856 daemon_log("could not assign the msg $header to an event", 5);
860 if ($header eq 'new_ldap_config') { &new_ldap_config($msg_hash)}
861 elsif ($header eq 'ping') { &got_ping($msg_hash) }
862 elsif ($header eq 'wake_up') { &execute_event($msg_hash)}
863 elsif ($header eq 'new_passwd') { &new_passwd()}
864 else { daemon_log("ERROR: no function assigned to msg $header", 5) }
866 return;
867 }
870 #=== FUNCTION ================================================================
871 # NAME:
872 # PARAMETERS:
873 # RETURNS:
874 # DESCRIPTION:
875 #===============================================================================
876 sub update_status {
877 my ($new_status) = @_ ;
878 my $out_hash = &create_xml_hash("update_status", $client_address, $server_address);
879 &add_content2xml_hash($out_hash, "update_status", $new_status);
880 &send_msg_hash2address($out_hash, $server_address);
881 return;
882 }
885 #=== FUNCTION ================================================================
886 # NAME:
887 # PARAMETERS:
888 # RETURNS:
889 # DESCRIPTION:
890 #===============================================================================
891 sub server_leaving {
892 my ($msg_hash) = @_ ;
893 my $source = &get_content_from_xml_hash("source");
894 my $header = &get_content_from_xml_hash("header");
896 daemon_log("gosa daemon $source is going down, cause registration procedure", 1);
897 my $server_address = "none";
898 my $server_passwd = "none";
899 my $server_cipher = "none";
901 # reinitialization of default values in config file
902 &read_configfile;
904 # registrated at new daemon
905 ®ister_at_server();
907 return;
908 }
911 sub got_ping {
912 my ($msg_hash) = @_ ;
914 my $source = &get_content_from_xml_hash($msg_hash, 'source');
915 my $target = &get_content_from_xml_hash($msg_hash, 'target');
916 my $header = &get_content_from_xml_hash($msg_hash, 'header');
918 &add_content2known_hosts(hostname=>$target, status=>$header);
920 my $out_hash = &create_xml_hash("got_ping", $target, $source);
921 &send_msg_hash2address($out_hash, $source, $server_passwd);
923 return;
924 }
927 sub new_ldap_config {
928 my ($msg_hash) = @_ ;
930 my @gotoLdapServer = &get_content_from_xml_hash($msg_hash, "new_ldap_config");
931 print Dumper @gotoLdapServer;
934 return;
936 }
939 sub execute_event {
940 my ($msg_hash)= @_;
941 my $configdir= '/etc/gosac/events/';
942 my $result;
944 my $header = &get_content_from_xml_hash($msg_hash, 'header');
945 my $source = &get_content_from_xml_hash($msg_hash, 'source');
946 my $target = &get_content_from_xml_hash($msg_hash, 'target');
949 if((not defined $source)
950 && (not defined $target)
951 && (not defined $header)) {
952 daemon_log("ERROR: Entries missing in XML msg for gosa events under /etc/gosac/events");
953 } else {
954 my $parameters="";
955 my @params = &get_content_from_xml_hash($msg_hash, $header);
956 my $params = join(", ", @params);
957 daemon_log("execute_event: got parameters: $params", 5);
959 if (@params) {
960 foreach my $param (@params) {
961 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
962 daemon_log("execute_event: parameter -> value: $param -> $param_value", 7);
963 $parameters.= " ".$param_value;
964 }
965 }
967 my $cmd= $configdir.$header."$parameters";
968 daemon_log("execute_event: executing cmd: $cmd", 7);
969 $result= "";
970 open(PIPE, "$cmd 2>&1 |");
971 while(<PIPE>) {
972 $result.=$_;
973 }
974 close(PIPE);
975 }
977 # process the event result
980 return;
981 }
984 sub new_passwd {
985 # my ($msg_hash) = @_ ;
986 my $new_server_passwd = &create_passwd();
987 my $new_server_cipher = &create_ciphering($new_server_passwd);
989 my $out_hash = &create_xml_hash("new_passwd", $client_address, $server_address, $new_server_passwd);
991 &send_msg_hash2address($out_hash, $server_address, $server_passwd);
993 $server_passwd = $new_server_passwd;
994 $server_cipher = $new_server_cipher;
995 return;
996 }
1001 #==== MAIN = main ==============================================================
1003 # parse commandline options
1004 Getopt::Long::Configure( "bundling" );
1005 GetOptions("h|help" => \&usage,
1006 "c|config=s" => \$cfg_file,
1007 "f|foreground" => \$foreground,
1008 "v|verbose+" => \$verbose,
1009 );
1011 # read and set config parameters
1012 &check_cmdline_param ;
1013 &read_configfile;
1014 &check_pid;
1016 # restart daemon log file
1017 if(-e $log_file ) { unlink $log_file }
1018 daemon_log("started!");
1020 # Just fork, if we"re not in foreground mode
1021 if( ! $foreground ) { $pid = fork(); }
1022 else { $pid = $$; }
1024 # Do something useful - put our PID into the pid_file
1025 if( 0 != $pid ) {
1026 open( LOCK_FILE, ">$pid_file" );
1027 print LOCK_FILE "$pid\n";
1028 close( LOCK_FILE );
1029 if( !$foreground ) { exit( 0 ) };
1030 }
1032 # detect own ip and mac address
1033 ($client_ip, $client_mac_address) = &get_ip_and_mac();
1034 if (not defined $client_ip) {
1035 die "EXIT: ip address of $0 could not be detected";
1036 }
1037 daemon_log("client ip address detected: $client_ip", 1);
1038 daemon_log("client mac address detected: $client_mac_address", 1);
1040 # prepare variables
1041 if (defined $server_ip && defined $server_port) {
1042 $server_address = $server_ip.":".$server_port;
1043 }
1044 $client_address = $client_ip.":".$client_port;
1046 # setup xml parser
1047 $xml = new XML::Simple();
1049 # create input socket
1050 $rbits = $wbits = $ebits = "";
1051 $input_socket = IO::Socket::INET->new(LocalPort => $client_port,
1052 Type => SOCK_STREAM,
1053 Reuse => 1,
1054 Listen => 20,
1055 );
1056 if(not defined $input_socket){
1057 daemon_log("cannot be a tcp server at $client_port : $@\n");
1058 } else {
1059 daemon_log("start server:\n\t$server_ip:$client_port",1) ;
1060 vec($rbits, fileno $input_socket, 1) = 1;
1061 vec($wbits, fileno $input_socket, 1) = 1;
1062 }
1064 # register at server
1065 ®ister_at_server();
1068 ##############
1069 # Debugging
1070 #############
1071 #sleep(2);
1072 #&update_status("ich_bin_ein_neuer_status");
1074 ###################################
1075 #everything ready, okay, lets start
1076 ###################################
1077 while(1) {
1078 my ($rout, $wout);
1079 my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1081 # error handling
1082 if($nf < 0 ) {
1083 }
1085 # something is coming in
1086 if(vec $rout, fileno $input_socket, 1) {
1087 my $client = $input_socket->accept();
1088 my $other_end = getpeername($client);
1090 if(not defined $other_end) {
1091 daemon_log("client cannot be identified: $!");
1092 } else {
1093 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1094 my $actual_ip = inet_ntoa($iaddr);
1095 daemon_log("accept client from $actual_ip", 5);
1096 my $in_msg = &read_from_socket($client);
1097 if(defined $in_msg){
1098 chomp($in_msg);
1099 $in_msg = $in_msg.".".$actual_ip;
1100 &process_incoming_msg($in_msg);
1102 }
1103 }
1104 }
1105 }