Code

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