1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-si-bus
5 #
6 # USAGE: ./gosa-si-bus
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 POE qw(Component::Server::TCP);
29 use Data::Dumper;
30 use Crypt::Rijndael;
31 use IO::Socket::INET;
32 use NetAddr::IP;
33 use XML::Simple;
34 use MIME::Base64;
35 use File::Basename;
36 use Digest::MD5 qw(md5 md5_hex md5_base64);
37 use utf8;
39 use GOSA::GosaSupportDaemon;
40 use GOSA::DBsqlite;
42 my ($cfg_file, $default_cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file,);
43 my ($bus_address, $bus_key, $bus_ip, $bus_port, $bus_mac_address);
44 my ($bus_known_server_db, $bus_known_server_file_name, $bus_known_clients_db, $bus_known_clients_file_name);
45 my $xml;
46 our $prg= basename($0);
48 $foreground = 0 ;
49 %cfg_defaults = (
50 "general" => {
51 "log_file" => [\$log_file, "/var/run/".$prg.".log"],
52 "pid_file" => [\$pid_file, "/var/run/".$prg.".pid"],
53 },
54 "bus" => {
55 "key" => [\$bus_key, "secret-bus-password"],
56 "ip" => [\$bus_ip, "0.0.0.0"],
57 "port" => [\$bus_port, "20080"],
58 "known-servers" => [\$bus_known_server_file_name, "/var/lib/gosa-si/bus-servers.db"],
59 "known-clients" => [\$bus_known_clients_file_name, "/var/lib/gosa-si/bus-clients.db"],
60 },
61 );
63 #=== FUNCTIONS = functions =====================================================
65 #=== FUNCTION ================================================================
66 # NAME: check_cmdline_param
67 # PARAMETERS:
68 # RETURNS:
69 # DESCRIPTION:
70 #===============================================================================
71 sub check_cmdline_param () {
72 my @error_l;
73 my $error = 0;
75 if( !$cfg_file ) {
76 $cfg_file = "/etc/gosa-si/bus.conf";
77 }
78 if( not -f $cfg_file ) {
79 push(@error_l, "can not find file '$cfg_file'");
80 $error++;
81 }
82 if( not -r $cfg_file) {
83 push(@error_l, "can not read file '$cfg_file'");
84 $error++;
85 }
87 if( $error > 0 ) {
88 &usage( "", 1 );
89 print STDERR join("\n", @error_l);
90 print STDERR "\n";
91 exit( -1 );
92 }
93 }
96 #=== FUNCTION ================================================================
97 # NAME: read_configfile
98 # PARAMETERS: cfg_file - string -
99 # RETURNS: nothing
100 # DESCRIPTION: read cfg_file and set variables
101 #===============================================================================
102 sub read_configfile {
103 my $cfg;
104 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
105 if( -r $cfg_file ) {
106 $cfg = Config::IniFiles->new( -file => $cfg_file );
107 } else {
108 print STDERR "Couldn't read config file!";
109 }
110 } else {
111 $cfg = Config::IniFiles->new() ;
112 }
113 foreach my $section (keys %cfg_defaults) {
114 foreach my $param (keys %{$cfg_defaults{ $section }}) {
115 my $pinfo = $cfg_defaults{ $section }{ $param };
116 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
117 }
118 }
119 }
122 #=== FUNCTION ================================================================
123 # NAME: check_pid
124 # PARAMETERS: nothing
125 # RETURNS: nothing
126 # DESCRIPTION: handels pid processing
127 #===============================================================================
128 sub check_pid {
129 $pid = -1;
130 # Check, if we are already running
131 if( open(LOCK_FILE, "<$pid_file") ) {
132 $pid = <LOCK_FILE>;
133 if( defined $pid ) {
134 chomp( $pid );
135 if( -f "/proc/$pid/stat" ) {
136 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
137 if( $0 eq $stat ) {
138 close( LOCK_FILE );
139 exit -1;
140 }
141 }
142 }
143 close( LOCK_FILE );
144 unlink( $pid_file );
145 }
147 # create a syslog msg if it is not to possible to open PID file
148 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
149 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
150 if (open(LOCK_FILE, '<', $pid_file)
151 && ($pid = <LOCK_FILE>))
152 {
153 chomp($pid);
154 $msg .= "(PID $pid)\n";
155 } else {
156 $msg .= "(unable to read PID)\n";
157 }
158 if( ! ($foreground) ) {
159 openlog( $0, "cons,pid", "daemon" );
160 syslog( "warning", $msg );
161 closelog();
162 }
163 else {
164 print( STDERR " $msg " );
165 }
166 exit( -1 );
167 }
168 }
171 #=== FUNCTION ================================================================
172 # NAME: usage
173 # PARAMETERS: nothing
174 # RETURNS: nothing
175 # DESCRIPTION: print out usage text to STDERR
176 #===============================================================================
177 sub usage {
178 print STDERR << "EOF" ;
179 usage: $prg [-hvf] [-c config]
181 -h : this (help) message
182 -c <file> : config file
183 -f : foreground, process will not be forked to background
184 -v : be verbose (multiple to increase verbosity)
185 EOF
186 print "\n" ;
187 }
190 #=== FUNCTION ================================================================
191 # NAME: logging
192 # PARAMETERS: level - string - default 'info'
193 # msg - string -
194 # facility - string - default 'LOG_DAEMON'
195 # RETURNS:
196 # DESCRIPTION:
197 #===============================================================================
198 sub daemon_log {
199 # log into log_file
200 my( $msg, $level ) = @_;
201 if(not defined $msg) { return }
202 if(not defined $level) { $level = 1 }
203 if(defined $log_file){
204 open(LOG_HANDLE, ">>$log_file");
205 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
206 print STDERR "cannot open $log_file: $!";
207 return }
208 chomp($msg);
209 if($level <= $verbose){
210 my ($seconds, $minutes, $hours, $monthday, $month,
211 $year, $weekday, $yearday, $sommertime) = localtime(time);
212 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
213 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
214 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
215 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
216 $month = $monthnames[$month];
217 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
218 $year+=1900;
220 my $log_msg = "$month $monthday $hours:$minutes:$seconds $prg $msg\n";
221 print LOG_HANDLE $log_msg;
222 if( $foreground ) {
223 print STDERR $log_msg;
224 }
225 }
226 close( LOG_HANDLE );
227 }
228 }
231 #=== FUNCTION ================================================================
232 # NAME: get_ip
233 # PARAMETERS: interface name (i.e. eth0)
234 # RETURNS: (ip address)
235 # DESCRIPTION: Uses ioctl to get ip address directly from system.
236 #===============================================================================
237 sub get_ip {
238 my $ifreq= shift;
239 my $result= "";
240 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
241 my $proto= getprotobyname('ip');
243 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
244 or die "socket: $!";
246 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
247 my ($if, $sin) = unpack 'a16 a16', $ifreq;
248 my ($port, $addr) = sockaddr_in $sin;
249 my $ip = inet_ntoa $addr;
251 if ($ip && length($ip) > 0) {
252 $result = $ip;
253 }
254 }
256 return $result;
257 }
260 #=== FUNCTION ================================================================
261 # NAME: get_interface_for_ip
262 # PARAMETERS: ip address (i.e. 192.168.0.1)
263 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
264 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
265 #===============================================================================
266 sub get_interface_for_ip {
267 my $result;
268 my $ip= shift;
269 if ($ip && length($ip) > 0) {
270 my @ifs= &get_interfaces();
271 if($ip eq "0.0.0.0") {
272 $result = "all";
273 } else {
274 foreach (@ifs) {
275 my $if=$_;
276 if(get_ip($if) eq $ip) {
277 $result = $if;
278 last;
279 }
280 }
281 }
282 }
283 return $result;
284 }
287 #=== FUNCTION ================================================================
288 # NAME: get_interfaces
289 # PARAMETERS: none
290 # RETURNS: (list of interfaces)
291 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
292 #===============================================================================
293 sub get_interfaces {
294 my @result;
295 my $PROC_NET_DEV= ('/proc/net/dev');
297 open(PROC_NET_DEV, "<$PROC_NET_DEV")
298 or die "Could not open $PROC_NET_DEV";
300 my @ifs = <PROC_NET_DEV>;
302 close(PROC_NET_DEV);
304 # Eat first two line
305 shift @ifs;
306 shift @ifs;
308 chomp @ifs;
309 foreach my $line(@ifs) {
310 my $if= (split /:/, $line)[0];
311 $if =~ s/^\s+//;
312 push @result, $if;
313 }
315 return @result;
316 }
319 #=== FUNCTION ================================================================
320 # NAME: get_mac
321 # PARAMETERS: interface name (i.e. eth0)
322 # RETURNS: (mac address)
323 # DESCRIPTION: Uses ioctl to get mac address directly from system.
324 #===============================================================================
325 sub get_mac {
326 my $ifreq= shift;
327 my $result;
328 if ($ifreq && length($ifreq) > 0) {
329 if($ifreq eq "all") {
330 if(defined($bus_ip)) {
331 $result = &get_local_mac_for_remote_ip($bus_ip);
332 }
333 elsif ($bus_mac_address && length($bus_mac_address) > 0 && !($bus_mac_address eq "00:00:00:00:00:00")){
334 $result = &client_mac_address;
335 }
336 else {
337 $result = "00:00:00:00:00:00";
338 }
339 } else {
340 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
342 # A configured MAC Address should always override a guessed value
343 if ($bus_mac_address and length($bus_mac_address) > 0 and not($bus_mac_address eq "00:00:00:00:00:00")) {
344 $result= $bus_mac_address;
345 }
346 else {
347 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
348 or die "socket: $!";
350 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
351 my ($if, $mac)= unpack 'h36 H12', $ifreq;
353 if (length($mac) > 0) {
354 $mac=~ m/^([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/;
355 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
356 $result = $mac;
357 }
358 }
359 }
360 }
361 }
362 return $result;
363 }
366 #=== FUNCTION ================================================================
367 # NAME: get_local_mac_for_remote_ip
368 # PARAMETERS: none (takes server_ip from global variable)
369 # RETURNS: (ip address from interface that is used for communication)
370 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
371 # matches (defaultroute last).
372 #===============================================================================
373 sub get_local_mac_for_remote_ip {
374 my $server_ip= shift;
375 my $result= "00:00:00:00:00:00";
377 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
378 my $PROC_NET_ROUTE= ('/proc/net/route');
380 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
381 or die "Could not open $PROC_NET_ROUTE";
383 my @ifs = <PROC_NET_ROUTE>;
385 close(PROC_NET_ROUTE);
387 # Eat header line
388 shift @ifs;
389 chomp @ifs;
390 foreach my $line(@ifs) {
391 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
392 my $destination;
393 my $mask;
394 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
395 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
396 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
397 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
398 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
399 # destination matches route, save mac and exit
400 $result= &get_mac($Iface);
401 last;
402 }
403 }
404 } else {
405 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
406 }
407 return $result;
408 }
410 sub bus_matches {
411 my $target = shift;
412 my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
413 my $result = 0;
415 if($bus_ip eq $target_ip) {
416 $result= 1;
417 } elsif ($bus_ip eq "0.0.0.0") {
418 if ($target_ip eq "127.0.0.1") {
419 $result= 1;
420 } else {
421 my $PROC_NET_ROUTE= ('/proc/net/route');
423 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
424 or die "Could not open $PROC_NET_ROUTE";
426 my @ifs = <PROC_NET_ROUTE>;
428 close(PROC_NET_ROUTE);
430 # Eat header line
431 shift @ifs;
432 chomp @ifs;
433 foreach my $line(@ifs) {
434 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
435 my $destination;
436 my $mask;
437 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
438 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
439 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
440 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
441 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
442 # destination matches route, save mac and exit
443 $result= 1;
444 last;
445 }
446 }
447 }
448 } else {
449 &main::daemon_log("Target ip $target_ip does not match bus ip $bus_ip",1);
450 }
452 return $result;
453 }
455 #=== FUNCTION ================================================================
456 # NAME: create_passwd
457 # PARAMETERS: nothing
458 # RETURNS: new_passwd - string
459 # DESCRIPTION: creates a 32 bit long random passwd out of "a".."z","A".."Z",0..9
460 #===============================================================================
461 sub create_passwd {
462 my $new_passwd = "";
463 for(my $i=0; $i<31; $i++) {
464 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
465 }
466 return $new_passwd;
467 }
470 sub create_ciphering {
471 my ($passwd) = @_;
472 if((!defined($passwd)) || length($passwd)==0) {
473 $passwd = "";
474 }
475 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
476 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
477 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
478 $my_cipher->set_iv($iv);
479 return $my_cipher;
480 }
483 sub encrypt_msg {
484 my ($msg, $key) = @_;
485 my $my_cipher = &create_ciphering($key);
486 my $len;
487 {
488 use bytes;
489 $len= 16-length($msg)%16;
490 }
491 $msg = "\0"x($len).$msg;
492 $msg = $my_cipher->encrypt($msg);
493 chomp($msg = &encode_base64($msg));
494 # there are no newlines allowed inside msg
495 $msg=~ s/\n//g;
496 return $msg;
497 }
500 sub decrypt_msg {
502 my ($msg, $key) = @_ ;
503 $msg = &decode_base64($msg);
504 my $my_cipher = &create_ciphering($key);
505 $msg = $my_cipher->decrypt($msg);
506 $msg =~ s/\0*//g;
507 return $msg;
508 }
511 sub send_msg_hash2address {
512 my ($msg_hash, $address, $encrypt_key) = @_ ;
513 my $msg = &create_xml_string($msg_hash);
514 my $header = @{$msg_hash->{'header'}}[0];
515 &send_msg_to_target($msg, $address, $encrypt_key, $header);
517 return;
518 }
521 sub send_msg_to_target {
522 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
523 my $error = 0;
524 my $header;
525 my $new_status;
526 my $act_status;
527 my ($sql_statement, $res);
529 if( $msg_header ) {
530 $header = "'$msg_header'-";
531 }
532 else {
533 $header = "";
534 }
536 # encrypt xml msg
537 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
539 # opensocket
540 my $socket = &open_socket($address);
541 if( !$socket ) {
542 daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
543 $error++;
544 }
546 if( $error == 0 ) {
547 # send xml msg
548 print $socket $crypted_msg."\n";
550 daemon_log("send ".$header."msg to $address", 1);
551 daemon_log("message:\n$msg", 8);
553 }
555 # close socket in any case
556 if( $socket ) {
557 close $socket;
558 }
560 if( $error > 0 ) { $new_status = "down"; }
561 else { $new_status = $msg_header; }
564 # known_clients
565 $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$address'";
566 $res = $bus_known_clients_db->select_dbentry($sql_statement);
567 if( keys(%$res) > 0 ) {
568 $act_status = $res->{1}->{'status'};
569 if( $act_status eq "down" ) {
570 $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
571 $res = $bus_known_clients_db->del_dbentry($sql_statement);
572 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from bus_known_clients", 3);
573 }
574 else {
575 $sql_statement = "UPDATE bus_known_clients SET status='$new_status' WHERE hostname='$address'";
576 $res = $bus_known_clients_db->update_dbentry($sql_statement);
577 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
578 }
579 }
581 # known_server
582 $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$address'";
583 $res = $bus_known_server_db->select_dbentry($sql_statement);
584 if( keys(%$res) > 0) {
585 $act_status = $res->{1}->{'status'};
586 if( $act_status eq "down" ) {
587 $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
588 $res = $bus_known_clients_db->del_dbentry($sql_statement);
589 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from bus_known_server", 3);
590 }
591 else {
592 $sql_statement = "UPDATE bus_known_server SET status='$new_status' WHERE hostname='$address'";
593 $res = $bus_known_server_db->update_dbentry($sql_statement);
594 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5)
595 }
596 }
598 return;
599 }
602 #=== FUNCTION ================================================================
603 # NAME: open_socket
604 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
605 # [PeerPort] string necessary if port not appended by PeerAddr
606 # RETURNS: socket IO::Socket::INET
607 # DESCRIPTION: open a socket to PeerAddr
608 #===============================================================================
609 sub open_socket {
610 my ($PeerAddr, $PeerPort) = @_ ;
611 if(defined($PeerPort)){
612 $PeerAddr = $PeerAddr.":".$PeerPort;
613 }
614 my $socket;
615 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
616 Porto => "tcp",
617 Type => SOCK_STREAM,
618 Timeout => 5,
619 );
620 if(not defined $socket) {
621 return;
622 }
623 &daemon_log("open_socket: $PeerAddr", 7);
624 return $socket;
625 }
628 sub check_key_and_xml_validity {
629 my ($crypted_msg, $module_key) = @_;
630 #print STDERR "crypted_msg:$crypted_msg\n";
631 #print STDERR "modul_key:$module_key\n";
633 my $msg;
634 my $msg_hash;
635 eval{
636 $msg = &decrypt_msg($crypted_msg, $module_key);
637 &main::daemon_log("decrypted_msg: \n$msg", 8);
639 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
641 # check header
642 my $header_l = $msg_hash->{'header'};
643 if( 1 != @{$header_l} ) {
644 die 'no or more headers specified';
645 }
646 my $header = @{$header_l}[0];
647 if( 0 == length $header) {
648 die 'header has length 0';
649 }
651 # check source
652 my $source_l = $msg_hash->{'source'};
653 if( 1 != @{$source_l} ) {
654 die 'no or more sources specified';
655 }
656 my $source = @{$source_l}[0];
657 if( 0 == length $source) {
658 die 'source has length 0';
659 }
661 # check target
662 my $target_l = $msg_hash->{'target'};
663 if( 1 != @{$target_l} ) {
664 die 'no or more targets specified ';
665 }
666 my $target = @{$target_l}[0];
667 if( 0 == length $target) {
668 die 'target has length 0 ';
669 }
671 };
672 if($@) {
673 &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
674 &main::daemon_log("$@", 8);
675 }
677 return ($msg, $msg_hash);
678 }
681 sub input_from_new_server {
682 no strict "refs";
683 my ($input) = @_ ;
684 my ($msg, $msg_hash);
686 daemon_log("bus_known_server host_name: new host", 7);
687 daemon_log("bus_known_server host_key: $bus_key", 7);
689 # check if module can open msg envelope with key
690 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $bus_key);
692 if( (!$msg) || (!$msg_hash) ) {
693 daemon_log("Incoming message is not from a new gosa-si-server", 5);
694 }
696 return ($msg, $msg_hash);
697 }
700 sub input_from_known_server {
701 my ($input, $remote_ip) = @_ ;
702 my ($msg, $msg_hash);
704 my $sql_statement= "SELECT * FROM bus_known_server";
705 my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
707 while( my ($hit_num, $hit) = each %{ $query_res } ) {
708 my $host_name = $hit->{hostname};
709 if( not $host_name =~ "^$remote_ip") {
710 next;
711 }
712 my $host_key = $hit->{hostkey};
713 daemon_log("bus_known_server host_name: $host_name", 7);
714 daemon_log("bus_known_server host_key: $host_key", 7);
716 # check if module can open msg envelope with module key
717 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
718 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
719 next;
720 }
721 else {
722 $msg = $tmp_msg;
723 $msg_hash = $tmp_msg_hash;
724 last;
725 }
726 }
728 if( (!$msg) || (!$msg_hash) ) {
729 daemon_log("Incoming message is not from a known gosa-si-server", 5);
730 }
732 return ($msg, $msg_hash);
733 }
736 sub _start {
737 my $kernel = $_[KERNEL];
738 $kernel->alias_set('gosa_si_bus_session');
739 return;
740 }
742 sub _default {
743 daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
744 return;
745 }
748 sub bus_input {
749 my ($kernel, $heap, $input, $wheel, $session) = @_[KERNEL, HEAP, ARG0, ARG1, SESSION];
750 my ($msg, $msg_hash);
751 my $error = 0;
753 daemon_log("Incoming msg:\n$input\n", 8);
755 # msg is from a new gosa-si-server
756 ($msg, $msg_hash) = &input_from_new_server($input);
758 # msg is from a gosa-si-server or gosa-si-bus
759 if(( !$msg ) || ( !$msg_hash ) ){
760 ($msg, $msg_hash) = &input_from_known_server($input, $heap->{'remote_ip'});
761 }
763 # an error occurred
764 if(( !$msg ) || ( !$msg_hash )){
765 $error++;
766 }
768 if( $error == 0) {
769 my @target_l = @{$msg_hash->{'target'}};
770 my $source = @{$msg_hash->{'source'}}[0];
771 my $header = @{$msg_hash->{header}}[0];
773 my $target_string = join(",", @target_l);
774 daemon_log("got msg '$header' with target '$target_string' from ".$heap->{'remote_ip'}, 3);
776 if( 1 == length(@target_l) && &bus_matches($target_l[0]) ) {
777 # msg is for bus
778 #print STDERR "msg is for bus\n";
779 $kernel->post('gosa_si_bus_session', $header, $msg, $msg_hash);
780 }
781 else {
782 # msg is for someone else, deliver it
784 #print STDERR "msg is for someone else\n";
785 foreach my $target (@target_l) {
786 if( $target =~ /(\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}:\d+)/ ) {
787 # target is a ip address
788 my ($sql_statement, $query_res);
790 $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$target'";
791 $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
792 if( 1 == keys(%$query_res) ) {
793 my $host_name = $query_res->{1}->{'hostname'};
794 my $host_key = $query_res->{1}->{'hostkey'};
795 &send_msg_to_target($msg, $host_name, $host_key, $header);
796 next;
797 }
799 $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$target'";
800 $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
801 if( 1 == keys(%$query_res) ) {
802 my $host_name = $query_res->{1}->{'hostname'};
803 my $server_name = $query_res->{1}->{'registered'};
804 # fetch correct key for server
805 my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
806 my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
807 my $server_key = $query_res->{1}->{'hostkey'};
808 &send_msg_to_target($msg, $server_name, $server_key, $header);
809 next;
810 }
812 daemon_log("ERROR:unknown host, can not send message '$header' to target '$target'", 1);
813 }
814 elsif( $target =~ /([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/ ) {
815 # target is a mac address
816 my $sql_statement = "SELECT * FROM bus_known_clients WHERE macaddress='$target'";
817 my $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
818 if( 1 > keys(%{$query_res})) {
819 daemon_log("ERROR: there are more than one hosts in bus_known_clients_db with mac address '$target'", 1);
820 }
821 elsif( 0 == keys(%{$query_res})) {
822 daemon_log("WARNING: no host found in bus_known_clients_db with mac address '$target'", 3);
823 }
824 else {
825 my $host_name = $query_res->{1}->{'hostname'};
826 my $server_name = $query_res->{1}->{'registered'};
827 my $out_msg = $msg;
828 $out_msg =~ s/<target>$target<\/target>/<target>$host_name<\/target>/;
830 # fetch correct key for server
831 my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
832 my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
833 my $server_key = $query_res->{1}->{'hostkey'};
835 &send_msg_to_target($out_msg, $server_name, $server_key, $header);
836 }
837 }
838 else {
839 daemon_log("ERROR: target address '$target' does not match neiter ".
840 "to ip address nor to mac address, can not send msg", 1);
841 }
843 }
844 }
845 }
846 }
849 sub here_i_am {
850 my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
851 my $source = @{$msg_hash->{'source'}}[0];
852 my $target = @{$msg_hash->{'target'}}[0];
854 my $new_key = &create_passwd();
856 # create bus_known_server entry
857 my $add_hash = {
858 table=>"bus_known_server",
859 primkey=>"hostname",
860 hostname=>$source,
861 status=>"registered",
862 hostkey=>$bus_key,
863 };
864 $bus_known_server_db->add_dbentry($add_hash);
866 # create outgoing msg
867 my $out_hash = &create_xml_hash("new_key", $target, $source, $new_key);
868 &send_msg_hash2address($out_hash, $source, $bus_key);
870 # change hostkey, reason
871 my $where_str= " WHERE hostname='$source'";
872 my $update_str= " SET hostkey='$new_key'";
873 my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
874 $bus_known_server_db->update_dbentry($sql_statement);
875 }
878 sub confirm_new_key {
879 my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
880 my $source = @{$msg_hash->{'source'}}[0];
881 daemon_log("'$source' confirms new key", 3);
882 }
885 sub new_client {
886 my ($msg, $msg_hash) = @_[ ARG0, ARG1 ];
888 my $new_client = @{$msg_hash->{'new_client'}}[0];
889 my $source = @{$msg_hash->{'source'}}[0];
890 my $mac_address = @{$msg_hash->{'macaddress'}}[0];
891 my $act_timestamp = @{$msg_hash->{'timestamp'}}[0];
893 my $add_hash = {
894 table => "bus_known_clients",
895 primkey=>"hostname",
896 hostname=>$new_client,
897 status=>'activ',
898 registered=>$source,
899 macaddress=>$mac_address,
900 timestamp=>$act_timestamp,
901 };
902 $bus_known_clients_db->add_dbentry($add_hash);
903 daemon_log("add new client '$new_client' to bus_known_clients_db", 3);
904 }
908 #==== MAIN = main ==============================================================
911 # parse commandline options
912 Getopt::Long::Configure( "bundling" );
913 GetOptions("h|help" => \&usage,
914 "c|config=s" => \$cfg_file,
915 "f|foreground" => \$foreground,
916 "v|verbose+" => \$verbose,
917 );
919 # read and set config parameters
920 &check_cmdline_param ;
921 &read_configfile;
922 &check_pid;
924 $SIG{CHLD} = 'IGNORE';
927 # forward error messages to logfile
928 if ( ! $foreground ) {
929 open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
930 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
931 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
932 }
934 # Just fork, if we are not in foreground mode
935 if( ! $foreground ) {
936 chdir '/' or die "Can't chdir to /: $!";
937 $pid = fork;
938 setsid or die "Can't start a new session: $!";
939 umask 0;
940 }
941 else {
942 $pid = $$;
943 }
945 # Do something useful - put our PID into the pid_file
946 if( 0 != $pid ) {
947 open( LOCK_FILE, ">$pid_file" );
948 print LOCK_FILE "$pid\n";
949 close( LOCK_FILE );
950 if( !$foreground ) {
951 exit( 0 )
952 };
953 }
955 # restart daemon log file
956 if(-e $log_file ) { unlink $log_file }
957 daemon_log(" ", 1);
958 daemon_log("started!", 1);
960 # delete old DBsqlite lock files
961 system('rm -f /tmp/gosa_si_lock*gosa-si-bus*');
963 #prepare other variables
964 $xml = new XML::Simple();
965 $bus_address = "$bus_ip:$bus_port";
967 # detect ip and mac address and complete host address
968 my $network_interface= &get_interface_for_ip($bus_ip);
969 $bus_mac_address= &get_mac($network_interface);
970 daemon_log("gosa-si-bus ip address detected: $bus_ip", 1);
971 daemon_log("gosa-si-bus mac address detected: $bus_mac_address", 1);
973 # connect to bus_known_server_db
974 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
975 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
976 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
978 my @clients_col_names = ('hostname', 'status', 'registered', 'macaddress', 'timestamp');
979 $bus_known_clients_db = GOSA::DBsqlite->new($bus_known_clients_file_name);
980 $bus_known_clients_db->create_table('bus_known_clients', \@clients_col_names);
982 # create socket for incoming xml messages
983 POE::Component::Server::TCP->new(
984 Alias => 'gosa-si-bus_socket',
985 Port => $bus_port,
986 ClientInput => \&bus_input,
987 );
988 daemon_log("start socket for incoming xml messages at port '$bus_port' ", 1);
990 # start session
991 POE::Session->create(
992 inline_states => {
993 _start => \&_start,
994 _default => \&_default,
995 here_i_am => \&here_i_am,
996 confirm_new_key => \&confirm_new_key,
997 new_client => \&new_client,
998 }
999 );
1001 POE::Kernel->run();
1002 exit;