Code

8076db2883ca2145b28202ebc8c973afc542c4fa
[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 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     }
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     }
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" ;
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     }
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;
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;
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;
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;
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;
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;
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;
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;
483 sub encrypt_msg {
484     my ($msg, $key) = @_;
485     my $my_cipher = &create_ciphering($key);
486     {
487       use bytes;
488       $msg = "\0"x(16-length($msg)%16).$msg;
489     }
490     $msg = $my_cipher->encrypt($msg);
491     chomp($msg = &encode_base64($msg));
492     # there are no newlines allowed inside msg
493     $msg=~ s/\n//g;
494     return $msg;
498 sub decrypt_msg {
500     my ($msg, $key) = @_ ;
501     $msg = &decode_base64($msg);
502     my $my_cipher = &create_ciphering($key);
503     $msg = $my_cipher->decrypt($msg); 
504     $msg =~ s/\0*//g;
505     return $msg;
509 sub send_msg_hash2address {
510     my ($msg_hash, $address, $encrypt_key) = @_ ;
511     my $msg = &create_xml_string($msg_hash);
512     my $header = @{$msg_hash->{'header'}}[0];
513     &send_msg_to_target($msg, $address, $encrypt_key, $header);
514     
515     return;
519 sub send_msg_to_target {
520     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
521     my $error = 0;
522     my $header;
523     my $new_status;
524     my $act_status;
525     my ($sql_statement, $res);
527     if( $msg_header ) {
528         $header = "'$msg_header'-";
529     }
530     else {
531         $header = "";
532     }
534     # encrypt xml msg
535     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
537     # opensocket
538     my $socket = &open_socket($address);
539     if( !$socket ) {
540         daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
541         $error++;
542     }
543     
544     if( $error == 0 ) {
545         # send xml msg
546         print $socket $crypted_msg."\n";
548         daemon_log("send ".$header."msg to $address", 1);
549         daemon_log("message:\n$msg", 8);
551     }
553     # close socket in any case
554     if( $socket ) {
555         close $socket;
556     }
558     if( $error > 0 ) { $new_status = "down"; }
559     else { $new_status = $msg_header; }
562     # known_clients
563     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$address'";
564     $res = $bus_known_clients_db->select_dbentry($sql_statement);
565     if( keys(%$res) > 0 ) {
566         $act_status = $res->{1}->{'status'};
567         if( $act_status eq "down" ) {
568             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
569             $res = $bus_known_clients_db->del_dbentry($sql_statement);
570             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from bus_known_clients", 3);
571         } 
572         else { 
573             $sql_statement = "UPDATE bus_known_clients SET status='$new_status' WHERE hostname='$address'";
574             $res = $bus_known_clients_db->update_dbentry($sql_statement);
575             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
576         }
577     }
579     # known_server
580     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$address'";
581     $res = $bus_known_server_db->select_dbentry($sql_statement);
582     if( keys(%$res) > 0) {
583         $act_status = $res->{1}->{'status'};
584         if( $act_status eq "down" ) {
585             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
586             $res = $bus_known_clients_db->del_dbentry($sql_statement);
587             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from bus_known_server", 3);
588         } 
589         else { 
590             $sql_statement = "UPDATE bus_known_server SET status='$new_status' WHERE hostname='$address'";
591             $res = $bus_known_server_db->update_dbentry($sql_statement);
592             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5)
593         }
594     }
596     return;
600 #===  FUNCTION  ================================================================
601 #         NAME:  open_socket
602 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
603 #                [PeerPort] string necessary if port not appended by PeerAddr
604 #      RETURNS:  socket IO::Socket::INET
605 #  DESCRIPTION:  open a socket to PeerAddr
606 #===============================================================================
607 sub open_socket {
608     my ($PeerAddr, $PeerPort) = @_ ;
609     if(defined($PeerPort)){
610         $PeerAddr = $PeerAddr.":".$PeerPort;
611     }
612     my $socket;
613     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
614             Porto => "tcp",
615             Type => SOCK_STREAM,
616             Timeout => 5,
617             );
618     if(not defined $socket) {
619         return;
620     }
621     &daemon_log("open_socket: $PeerAddr", 7);
622     return $socket;
626 sub check_key_and_xml_validity {
627     my ($crypted_msg, $module_key) = @_;
628 #print STDERR "crypted_msg:$crypted_msg\n";
629 #print STDERR "modul_key:$module_key\n";
631     my $msg;
632     my $msg_hash;
633     eval{
634         $msg = &decrypt_msg($crypted_msg, $module_key);
635         &main::daemon_log("decrypted_msg: \n$msg", 8);
637         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
639         # check header
640         my $header_l = $msg_hash->{'header'};
641         if( 1 != @{$header_l} ) {
642             die 'no or more headers specified';
643         }
644         my $header = @{$header_l}[0];
645         if( 0 == length $header) {
646             die 'header has length 0';
647         }
649         # check source
650         my $source_l = $msg_hash->{'source'};
651         if( 1 != @{$source_l} ) {
652             die 'no or more sources specified';
653         }
654         my $source = @{$source_l}[0];
655         if( 0 == length $source) {
656             die 'source has length 0';
657         }
659         # check target
660         my $target_l = $msg_hash->{'target'};
661         if( 1 != @{$target_l} ) {
662             die 'no or more targets specified ';
663         }
664         my $target = @{$target_l}[0];
665         if( 0 == length $target) {
666             die 'target has length 0 ';
667         }
669     };
670     if($@) {
671         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
672         &main::daemon_log("$@", 8);
673     }
675     return ($msg, $msg_hash);
679 sub input_from_new_server {
680     no strict "refs";
681     my ($input) = @_ ;
682     my ($msg, $msg_hash);
684     daemon_log("bus_known_server host_name: new host", 7);
685     daemon_log("bus_known_server host_key: $bus_key", 7);
687     # check if module can open msg envelope with key
688     ($msg, $msg_hash) = &check_key_and_xml_validity($input, $bus_key);
690     if( (!$msg) || (!$msg_hash) ) {
691         daemon_log("Incoming message is not from a new gosa-si-server", 5);
692     }
694     return ($msg, $msg_hash);
698 sub input_from_known_server {
699     my ($input, $remote_ip) = @_ ;  
700     my ($msg, $msg_hash);
702     my $sql_statement= "SELECT * FROM bus_known_server";
703     my $query_res = $bus_known_server_db->select_dbentry( $sql_statement ); 
705     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
706         my $host_name = $hit->{hostname};
707         if( not $host_name =~ "^$remote_ip") {
708             next;
709         }
710         my $host_key = $hit->{hostkey};
711         daemon_log("bus_known_server host_name: $host_name", 7);
712         daemon_log("bus_known_server host_key: $host_key", 7);
714         # check if module can open msg envelope with module key
715         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
716         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
717             next;
718         }
719         else {
720             $msg = $tmp_msg;
721             $msg_hash = $tmp_msg_hash;
722             last;
723         }
724     }
726     if( (!$msg) || (!$msg_hash) ) {
727         daemon_log("Incoming message is not from a known gosa-si-server", 5);
728     }
729   
730     return ($msg, $msg_hash);
734 sub _start {
735     my $kernel = $_[KERNEL];
736     $kernel->alias_set('gosa_si_bus_session');
737     return;
740 sub _default {
741     daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
742     return;
746 sub bus_input {
747     my ($kernel, $heap, $input, $wheel, $session) = @_[KERNEL, HEAP, ARG0, ARG1, SESSION];
748     my ($msg, $msg_hash);
749     my $error = 0;
750     
751     daemon_log("Incoming msg:\n$input\n", 8);
753     # msg is from a new gosa-si-server
754     ($msg, $msg_hash) = &input_from_new_server($input);
756     # msg is from a gosa-si-server or gosa-si-bus
757     if(( !$msg ) || ( !$msg_hash ) ){
758         ($msg, $msg_hash) = &input_from_known_server($input, $heap->{'remote_ip'});
759     }
761     # an error occurred
762     if(( !$msg ) || ( !$msg_hash )){
763         $error++;
764     }
766     if( $error == 0) {
767         my @target_l = @{$msg_hash->{'target'}};
768         my $source = @{$msg_hash->{'source'}}[0];
769         my $header = @{$msg_hash->{header}}[0];
771         my $target_string = join(",", @target_l);
772         daemon_log("got msg '$header' with target '$target_string' from ".$heap->{'remote_ip'}, 3);
774         if( 1 == length(@target_l) && &bus_matches($target_l[0]) ) {
775             # msg is for bus
776 #print STDERR "msg is for bus\n";
777             $kernel->post('gosa_si_bus_session', $header, $msg, $msg_hash);
778         }
779         else {
780             # msg is for someone else, deliver it
782 #print STDERR "msg is for someone else\n";
783             foreach my $target (@target_l) {
784                 if( $target =~ /(\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}:\d+)/ ) {
785                     # target is a ip address
786                     my ($sql_statement, $query_res);
788                     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$target'";
789                     $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
790                     if( 1 == keys(%$query_res) ) {
791                         my $host_name = $query_res->{1}->{'hostname'};
792                         my $host_key = $query_res->{1}->{'hostkey'};
793                         &send_msg_to_target($msg, $host_name, $host_key, $header);
794                         next;
795                     } 
797                     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$target'";
798                     $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
799                     if( 1 == keys(%$query_res) ) {
800                         my $host_name = $query_res->{1}->{'hostname'};
801                         my $server_name = $query_res->{1}->{'registered'};
802                         # fetch correct key for server
803                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
804                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
805                         my $server_key = $query_res->{1}->{'hostkey'};
806                         &send_msg_to_target($msg, $server_name, $server_key, $header);
807                         next;
808                     } 
810                     daemon_log("ERROR:unknown host, can not send message '$header' to target '$target'", 1);
811                 }
812                 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})/ ) {
813                     # target is a mac address
814                     my $sql_statement = "SELECT * FROM bus_known_clients WHERE macaddress='$target'";
815                     my $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
816                     if( 1 > keys(%{$query_res})) {
817                         daemon_log("ERROR: there are more than one hosts in bus_known_clients_db with mac address '$target'", 1);
818                     }
819                     elsif( 0 == keys(%{$query_res})) {
820                         daemon_log("WARNING: no host found in bus_known_clients_db with mac address '$target'", 3);
821                     }
822                     else {
823                         my $host_name = $query_res->{1}->{'hostname'};
824                         my $server_name = $query_res->{1}->{'registered'};
825                         my $out_msg = $msg;
826                         $out_msg =~ s/<target>$target<\/target>/<target>$host_name<\/target>/;
828                         # fetch correct key for server
829                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
830                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
831                         my $server_key = $query_res->{1}->{'hostkey'};
833                         &send_msg_to_target($out_msg, $server_name, $server_key, $header);
834                     }
835                 }
836                 else {
837                     daemon_log("ERROR: target address '$target' does not match neiter ".
838                         "to ip address nor to mac address, can not send msg", 1);
839                 }
841             }
842         }
843     }
847 sub here_i_am {
848     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
849     my $source = @{$msg_hash->{'source'}}[0];
850     my $target = @{$msg_hash->{'target'}}[0];
852     my $new_key = &create_passwd();
854     # create bus_known_server entry
855     my $add_hash = {
856         table=>"bus_known_server",
857         primkey=>"hostname",
858         hostname=>$source,
859         status=>"registered",
860         hostkey=>$bus_key,
861     };
862     $bus_known_server_db->add_dbentry($add_hash);
864     # create outgoing msg
865     my $out_hash = &create_xml_hash("new_key", $target, $source, $new_key);
866     &send_msg_hash2address($out_hash, $source, $bus_key);
868     # change hostkey, reason
869     my $where_str= " WHERE hostname='$source'";
870     my $update_str= " SET hostkey='$new_key'";
871     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
872     $bus_known_server_db->update_dbentry($sql_statement);
876 sub confirm_new_key {
877     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
878     my $source = @{$msg_hash->{'source'}}[0];
879     daemon_log("'$source' confirms new key", 3);
883 sub new_client {
884     my ($msg, $msg_hash) = @_[ ARG0, ARG1 ];
886     my $new_client = @{$msg_hash->{'new_client'}}[0];
887     my $source = @{$msg_hash->{'source'}}[0];
888     my $mac_address = @{$msg_hash->{'macaddress'}}[0];
889     my $act_timestamp = @{$msg_hash->{'timestamp'}}[0];
890     
891     my $add_hash = {
892         table => "bus_known_clients",
893         primkey=>"hostname",
894         hostname=>$new_client,
895         status=>'activ',
896         registered=>$source,
897         macaddress=>$mac_address,
898         timestamp=>$act_timestamp,
899     };
900     $bus_known_clients_db->add_dbentry($add_hash);
901     daemon_log("add new client '$new_client' to bus_known_clients_db", 3);
906 #==== MAIN = main ==============================================================
909 #  parse commandline options
910 Getopt::Long::Configure( "bundling" );
911 GetOptions("h|help" => \&usage,
912            "c|config=s" => \$cfg_file,
913            "f|foreground" => \$foreground,
914            "v|verbose+" => \$verbose,
915            );
917 #  read and set config parameters
918 &check_cmdline_param ;
919 &read_configfile;
920 &check_pid;
922 $SIG{CHLD} = 'IGNORE';
925 # forward error messages to logfile
926 if ( ! $foreground ) {
927         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
928         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
929         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
932 # Just fork, if we are not in foreground mode
933 if( ! $foreground ) { 
934     chdir '/'                 or die "Can't chdir to /: $!";
935     $pid = fork;
936     setsid                    or die "Can't start a new session: $!";
937     umask 0;
938
939 else { 
940     $pid = $$; 
943 # Do something useful - put our PID into the pid_file
944 if( 0 != $pid ) {
945     open( LOCK_FILE, ">$pid_file" );
946     print LOCK_FILE "$pid\n";
947     close( LOCK_FILE );
948     if( !$foreground ) { 
949         exit( 0 ) 
950     };
953 # restart daemon log file
954 if(-e $log_file ) { unlink $log_file }
955 daemon_log(" ", 1);
956 daemon_log("started!", 1);
958 # delete old DBsqlite lock files
959 system('rm -f /tmp/gosa_si_lock*gosa-si-bus*');
961 #prepare other variables
962 $xml =  new XML::Simple();
963 $bus_address = "$bus_ip:$bus_port";
965 # detect ip and mac address and complete host address
966 my $network_interface= &get_interface_for_ip($bus_ip);
967 $bus_mac_address= &get_mac($network_interface);
968 daemon_log("gosa-si-bus ip address detected: $bus_ip", 1);
969 daemon_log("gosa-si-bus mac address detected: $bus_mac_address", 1);
971 # connect to bus_known_server_db
972 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
973 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
974 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
976 my @clients_col_names = ('hostname', 'status', 'registered', 'macaddress', 'timestamp');
977 $bus_known_clients_db = GOSA::DBsqlite->new($bus_known_clients_file_name);
978 $bus_known_clients_db->create_table('bus_known_clients', \@clients_col_names);
980 # create socket for incoming xml messages
981 POE::Component::Server::TCP->new(
982     Alias => 'gosa-si-bus_socket',
983         Port => $bus_port,
984         ClientInput => \&bus_input,
985 );
986 daemon_log("start socket for incoming xml messages at port '$bus_port' ", 1);
988 # start session
989 POE::Session->create(
990         inline_states => {
991                 _start => \&_start, 
992         _default => \&_default,
993         here_i_am => \&here_i_am,
994         confirm_new_key => \&confirm_new_key,
995         new_client => \&new_client,
996         }
997 );
999 POE::Kernel->run();
1000 exit;