Code

a9ae07261e929c0c4fff58732c3bad79cd5e87fa
[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 File::Basename;
38 use Digest::MD5  qw(md5 md5_hex md5_base64);
41 my ($cfg_file, $default_cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file,);
42 my ($bus_address, $bus_key, $bus_ip, $bus_port, $bus_mac_address);
43 my ($bus_known_server_db, $bus_known_server_file_name, $bus_known_clients_db, $bus_known_clients_file_name);
44 my $xml;
45 our $prg= basename($0);
47 $foreground = 0 ;
48 %cfg_defaults = (
49 "general" => {
50     "log_file" => [\$log_file, "/var/run/".$prg.".log"],
51     "pid_file" => [\$pid_file, "/var/run/".$prg.".pid"],
52     },
53 "bus" => {
54     "key"  => [\$bus_key, "secret-bus-password"],
55     "ip"   => [\$bus_ip, "0.0.0.0"],
56     "port" => [\$bus_port, "20080"],
57     "known-servers" => [\$bus_known_server_file_name, "/var/lib/gosa-si/bus-servers.db"],
58     "known-clients" => [\$bus_known_clients_file_name, "/var/lib/gosa-si/bus-clients.db"],
59    }, 
60 );
62 #=== FUNCTIONS = functions =====================================================
64 #===  FUNCTION  ================================================================
65 #         NAME: check_cmdline_param
66 #   PARAMETERS: 
67 #      RETURNS:  
68 #  DESCRIPTION: 
69 #===============================================================================
70 sub check_cmdline_param () {
71     my @error_l;
72     my $error = 0;
74         if( !$cfg_file ) {
75                 $cfg_file = "/etc/gosa-si/bus.conf";
76     }
77     if( not -f $cfg_file ) {
78         push(@error_l, "can not find file '$cfg_file'");
79         $error++;
80     }
81         if( not -r $cfg_file) {
82                         push(@error_l, "can not read file '$cfg_file'");
83                         $error++;
84     }
86     if( $error > 0 ) {
87         &usage( "", 1 );
88         print STDERR join("\n", @error_l);
89         print STDERR "\n";
90         exit( -1 );
91     }
92 }
95 #===  FUNCTION  ================================================================
96 #         NAME:  read_configfile
97 #   PARAMETERS:  cfg_file - string - 
98 #      RETURNS:  nothing 
99 #  DESCRIPTION:  read cfg_file and set variables
100 #===============================================================================
101 sub read_configfile {
102     my $cfg;
103     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
104         if( -r $cfg_file ) {
105             $cfg = Config::IniFiles->new( -file => $cfg_file );
106         } else {
107             print STDERR "Couldn't read config file!";
108         }
109     } else {
110         $cfg = Config::IniFiles->new() ;
111     }
112     foreach my $section (keys %cfg_defaults) {
113         foreach my $param (keys %{$cfg_defaults{ $section }}) {
114             my $pinfo = $cfg_defaults{ $section }{ $param };
115             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
116         }
117     }
121 #===  FUNCTION  ================================================================
122 #         NAME:  check_pid
123 #   PARAMETERS:  nothing
124 #      RETURNS:  nothing
125 #  DESCRIPTION:  handels pid processing
126 #===============================================================================
127 sub check_pid {
128     $pid = -1;
129     # Check, if we are already running
130     if( open(LOCK_FILE, "<$pid_file") ) {
131         $pid = <LOCK_FILE>;
132         if( defined $pid ) {
133             chomp( $pid );
134             if( -f "/proc/$pid/stat" ) {
135                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
136                 if( $0 eq $stat ) {
137                     close( LOCK_FILE );
138                     exit -1;
139                 }
140             }
141         }
142         close( LOCK_FILE );
143         unlink( $pid_file );
144     }
146     # create a syslog msg if it is not to possible to open PID file
147     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
148         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
149         if (open(LOCK_FILE, '<', $pid_file)
150                 && ($pid = <LOCK_FILE>))
151         {
152             chomp($pid);
153             $msg .= "(PID $pid)\n";
154         } else {
155             $msg .= "(unable to read PID)\n";
156         }
157         if( ! ($foreground) ) {
158             openlog( $0, "cons,pid", "daemon" );
159             syslog( "warning", $msg );
160             closelog();
161         }
162         else {
163             print( STDERR " $msg " );
164         }
165         exit( -1 );
166     }
170 #===  FUNCTION  ================================================================
171 #         NAME:  usage
172 #   PARAMETERS:  nothing
173 #      RETURNS:  nothing
174 #  DESCRIPTION:  print out usage text to STDERR
175 #===============================================================================
176 sub usage {
177     print STDERR << "EOF" ;
178 usage: $prg [-hvf] [-c config]
180     -h        : this (help) message
181     -c <file> : config file
182     -f        : foreground, process will not be forked to background
183     -v        : be verbose (multiple to increase verbosity)
184 EOF
185     print "\n" ;
189 #===  FUNCTION  ================================================================
190 #         NAME:  logging
191 #   PARAMETERS:  level - string - default 'info' 
192 #                msg - string - 
193 #                facility - string - default 'LOG_DAEMON' 
194 #      RETURNS:  
195 #  DESCRIPTION: 
196 #===============================================================================
197 sub daemon_log {
198     # log into log_file
199     my( $msg, $level ) = @_;
200     if(not defined $msg) { return }
201     if(not defined $level) { $level = 1 }
202     if(defined $log_file){
203         open(LOG_HANDLE, ">>$log_file");
204         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
205             print STDERR "cannot open $log_file: $!";
206             return }
207             chomp($msg);
208             if($level <= $verbose){
209                 my ($seconds, $minutes, $hours, $monthday, $month,
210                         $year, $weekday, $yearday, $sommertime) = localtime(time);
211                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
212                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
213                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
214                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
215                 $month = $monthnames[$month];
216                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
217                 $year+=1900;
219                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $prg $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 send_msg_hash2address {
470     my ($msg_hash, $address, $encrypt_key) = @_ ;
471     my $msg = &create_xml_string($msg_hash);
472     my $header = @{$msg_hash->{'header'}}[0];
473     &send_msg_to_target($msg, $address, $encrypt_key, $header);
474     
475     return;
479 sub send_msg_to_target {
480     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
481     my $error = 0;
482     my $header;
483     my $new_status;
484     my $act_status;
485     my ($sql_statement, $res);
487     if( $msg_header ) {
488         $header = "'$msg_header'-";
489     }
490     else {
491         $header = "";
492     }
494     # encrypt xml msg
495     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
497     # opensocket
498     my $socket = &open_socket($address);
499     if( !$socket ) {
500         daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
501         $error++;
502     }
503     
504     if( $error == 0 ) {
505         # send xml msg
506         print $socket $crypted_msg."\n";
508         daemon_log("send ".$header."msg to $address", 1);
509         daemon_log("message:\n$msg", 8);
511     }
513     # close socket in any case
514     if( $socket ) {
515         close $socket;
516     }
518     if( $error > 0 ) { $new_status = "down"; }
519     else { $new_status = $msg_header; }
522     # known_clients
523     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$address'";
524     $res = $bus_known_clients_db->select_dbentry($sql_statement);
525     if( keys(%$res) > 0 ) {
526         $act_status = $res->{1}->{'status'};
527         if( $act_status eq "down" ) {
528             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
529             $res = $bus_known_clients_db->del_dbentry($sql_statement);
530             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from bus_known_clients", 3);
531         } 
532         else { 
533             $sql_statement = "UPDATE bus_known_clients SET status='$new_status' WHERE hostname='$address'";
534             $res = $bus_known_clients_db->update_dbentry($sql_statement);
535             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
536         }
537     }
539     # known_server
540     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$address'";
541     $res = $bus_known_server_db->select_dbentry($sql_statement);
542     if( keys(%$res) > 0) {
543         $act_status = $res->{1}->{'status'};
544         if( $act_status eq "down" ) {
545             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
546             $res = $bus_known_clients_db->del_dbentry($sql_statement);
547             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from bus_known_server", 3);
548         } 
549         else { 
550             $sql_statement = "UPDATE bus_known_server SET status='$new_status' WHERE hostname='$address'";
551             $res = $bus_known_server_db->update_dbentry($sql_statement);
552             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5)
553         }
554     }
556     return;
560 #===  FUNCTION  ================================================================
561 #         NAME:  open_socket
562 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
563 #                [PeerPort] string necessary if port not appended by PeerAddr
564 #      RETURNS:  socket IO::Socket::INET
565 #  DESCRIPTION:  open a socket to PeerAddr
566 #===============================================================================
567 sub open_socket {
568     my ($PeerAddr, $PeerPort) = @_ ;
569     if(defined($PeerPort)){
570         $PeerAddr = $PeerAddr.":".$PeerPort;
571     }
572     my $socket;
573     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
574             Porto => "tcp",
575             Type => SOCK_STREAM,
576             Timeout => 5,
577             );
578     if(not defined $socket) {
579         return;
580     }
581     &daemon_log("open_socket: $PeerAddr", 7);
582     return $socket;
586 sub check_key_and_xml_validity {
587     my ($crypted_msg, $module_key) = @_;
588 #print STDERR "crypted_msg:$crypted_msg\n";
589 #print STDERR "modul_key:$module_key\n";
591     my $msg;
592     my $msg_hash;
593     eval{
594         $msg = &decrypt_msg($crypted_msg, $module_key);
595         &main::daemon_log("decrypted_msg: \n$msg", 8);
597         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
599         # check header
600         my $header_l = $msg_hash->{'header'};
601         if( 1 != @{$header_l} ) {
602             die 'no or more headers specified';
603         }
604         my $header = @{$header_l}[0];
605         if( 0 == length $header) {
606             die 'header has length 0';
607         }
609         # check source
610         my $source_l = $msg_hash->{'source'};
611         if( 1 != @{$source_l} ) {
612             die 'no or more sources specified';
613         }
614         my $source = @{$source_l}[0];
615         if( 0 == length $source) {
616             die 'source has length 0';
617         }
619         # check target
620         my $target_l = $msg_hash->{'target'};
621         if( 1 != @{$target_l} ) {
622             die 'no or more targets specified ';
623         }
624         my $target = @{$target_l}[0];
625         if( 0 == length $target) {
626             die 'target has length 0 ';
627         }
629     };
630     if($@) {
631         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
632         &main::daemon_log("$@", 8);
633     }
635     return ($msg, $msg_hash);
639 sub input_from_new_server {
640     no strict "refs";
641     my ($input) = @_ ;
642     my ($msg, $msg_hash);
644     daemon_log("bus_known_server host_name: new host", 7);
645     daemon_log("bus_known_server host_key: $bus_key", 7);
647     # check if module can open msg envelope with key
648     ($msg, $msg_hash) = &check_key_and_xml_validity($input, $bus_key);
650     if( (!$msg) || (!$msg_hash) ) {
651         daemon_log("Incoming message is not from a new gosa-si-server", 5);
652     }
654     return ($msg, $msg_hash);
658 sub input_from_known_server {
659     my ($input, $remote_ip) = @_ ;  
660     my ($msg, $msg_hash);
662     my $sql_statement= "SELECT * FROM bus_known_server";
663     my $query_res = $bus_known_server_db->select_dbentry( $sql_statement ); 
665     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
666         my $host_name = $hit->{hostname};
667         if( not $host_name =~ "^$remote_ip") {
668             next;
669         }
670         my $host_key = $hit->{hostkey};
671         daemon_log("bus_known_server host_name: $host_name", 7);
672         daemon_log("bus_known_server host_key: $host_key", 7);
674         # check if module can open msg envelope with module key
675         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
676         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
677             next;
678         }
679         else {
680             $msg = $tmp_msg;
681             $msg_hash = $tmp_msg_hash;
682             last;
683         }
684     }
686     if( (!$msg) || (!$msg_hash) ) {
687         daemon_log("Incoming message is not from a known gosa-si-server", 5);
688     }
689   
690     return ($msg, $msg_hash);
694 sub _start {
695     my $kernel = $_[KERNEL];
696     $kernel->alias_set('gosa_si_bus_session');
697     return;
700 sub _default {
701     daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
702     return;
706 sub bus_input {
707     my ($kernel, $heap, $input, $wheel, $session) = @_[KERNEL, HEAP, ARG0, ARG1, SESSION];
708     my ($msg, $msg_hash);
709     my $error = 0;
710     
711     daemon_log("Incoming msg:\n$input\n", 8);
713     # msg is from a new gosa-si-server
714     ($msg, $msg_hash) = &input_from_new_server($input);
716     # msg is from a gosa-si-server or gosa-si-bus
717     if(( !$msg ) || ( !$msg_hash ) ){
718         ($msg, $msg_hash) = &input_from_known_server($input, $heap->{'remote_ip'});
719     }
721     # an error occurred
722     if(( !$msg ) || ( !$msg_hash )){
723         $error++;
724     }
726     if( $error == 0) {
727         my @target_l = @{$msg_hash->{'target'}};
728         my $source = @{$msg_hash->{'source'}}[0];
729         my $header = @{$msg_hash->{header}}[0];
731         my $target_string = join(",", @target_l);
732         daemon_log("got msg '$header' with target '$target_string' from ".$heap->{'remote_ip'}, 3);
734         if( 1 == length(@target_l) && &bus_matches($target_l[0]) ) {
735             # msg is for bus
736 #print STDERR "msg is for bus\n";
737             $kernel->post('gosa_si_bus_session', $header, $msg, $msg_hash);
738         }
739         else {
740             # msg is for someone else, deliver it
742 #print STDERR "msg is for someone else\n";
743             foreach my $target (@target_l) {
744                 if( $target =~ /(\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}:\d+)/ ) {
745                     # target is a ip address
746                     my ($sql_statement, $query_res);
748                     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$target'";
749                     $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
750                     if( 1 == keys(%$query_res) ) {
751                         my $host_name = $query_res->{1}->{'hostname'};
752                         my $host_key = $query_res->{1}->{'hostkey'};
753                         &send_msg_to_target($msg, $host_name, $host_key, $header);
754                         next;
755                     } 
757                     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$target'";
758                     $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
759                     if( 1 == keys(%$query_res) ) {
760                         my $host_name = $query_res->{1}->{'hostname'};
761                         my $server_name = $query_res->{1}->{'registered'};
762                         # fetch correct key for server
763                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
764                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
765                         my $server_key = $query_res->{1}->{'hostkey'};
766                         &send_msg_to_target($msg, $server_name, $server_key, $header);
767                         next;
768                     } 
770                     daemon_log("ERROR:unknown host, can not send message '$header' to target '$target'", 1);
771                 }
772                 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})/ ) {
773                     # target is a mac address
774                     my $sql_statement = "SELECT * FROM bus_known_clients WHERE macaddress='$target'";
775                     my $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
776                     if( 1 > keys(%{$query_res})) {
777                         daemon_log("ERROR: there are more than one hosts in bus_known_clients_db with mac address '$target'", 1);
778                     }
779                     elsif( 0 == keys(%{$query_res})) {
780                         daemon_log("WARNING: no host found in bus_known_clients_db with mac address '$target'", 3);
781                     }
782                     else {
783                         my $host_name = $query_res->{1}->{'hostname'};
784                         my $server_name = $query_res->{1}->{'registered'};
785                         my $out_msg = $msg;
786                         $out_msg =~ s/<target>$target<\/target>/<target>$host_name<\/target>/;
788                         # fetch correct key for server
789                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
790                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
791                         my $server_key = $query_res->{1}->{'hostkey'};
793                         &send_msg_to_target($out_msg, $server_name, $server_key, $header);
794                     }
795                 }
796                 else {
797                     daemon_log("ERROR: target address '$target' does not match neiter ".
798                         "to ip address nor to mac address, can not send msg", 1);
799                 }
801             }
802         }
803     }
807 sub here_i_am {
808     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
809     my $source = @{$msg_hash->{'source'}}[0];
810     my $target = @{$msg_hash->{'target'}}[0];
812     my $new_key = &create_passwd();
814     # create bus_known_server entry
815     my $add_hash = {
816         table=>"bus_known_server",
817         primkey=>"hostname",
818         hostname=>$source,
819         status=>"registered",
820         hostkey=>$bus_key,
821     };
822     $bus_known_server_db->add_dbentry($add_hash);
824     # create outgoing msg
825     my $out_hash = &create_xml_hash("new_key", $target, $source, $new_key);
826     &send_msg_hash2address($out_hash, $source, $bus_key);
828     # change hostkey, reason
829     my $where_str= " WHERE hostname='$source'";
830     my $update_str= " SET hostkey='$new_key'";
831     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
832     $bus_known_server_db->update_dbentry($sql_statement);
836 sub confirm_new_key {
837     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
838     my $source = @{$msg_hash->{'source'}}[0];
839     daemon_log("'$source' confirms new key", 3);
843 sub new_client {
844     my ($msg, $msg_hash) = @_[ ARG0, ARG1 ];
846     my $new_client = @{$msg_hash->{'new_client'}}[0];
847     my $source = @{$msg_hash->{'source'}}[0];
848     my $mac_address = @{$msg_hash->{'macaddress'}}[0];
849     my $act_timestamp = @{$msg_hash->{'timestamp'}}[0];
850     
851     my $add_hash = {
852         table => "bus_known_clients",
853         primkey=>"hostname",
854         hostname=>$new_client,
855         status=>'activ',
856         registered=>$source,
857         macaddress=>$mac_address,
858         timestamp=>$act_timestamp,
859     };
860     $bus_known_clients_db->add_dbentry($add_hash);
861     daemon_log("add new client '$new_client' to bus_known_clients_db", 3);
866 #==== MAIN = main ==============================================================
869 #  parse commandline options
870 Getopt::Long::Configure( "bundling" );
871 GetOptions("h|help" => \&usage,
872            "c|config=s" => \$cfg_file,
873            "f|foreground" => \$foreground,
874            "v|verbose+" => \$verbose,
875            );
877 #  read and set config parameters
878 &check_cmdline_param ;
879 &read_configfile;
880 &check_pid;
882 $SIG{CHLD} = 'IGNORE';
885 # forward error messages to logfile
886 if ( ! $foreground ) {
887         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
888         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
889         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
892 # Just fork, if we are not in foreground mode
893 if( ! $foreground ) { 
894     chdir '/'                 or die "Can't chdir to /: $!";
895     $pid = fork;
896     setsid                    or die "Can't start a new session: $!";
897     umask 0;
898
899 else { 
900     $pid = $$; 
903 # Do something useful - put our PID into the pid_file
904 if( 0 != $pid ) {
905     open( LOCK_FILE, ">$pid_file" );
906     print LOCK_FILE "$pid\n";
907     close( LOCK_FILE );
908     if( !$foreground ) { 
909         exit( 0 ) 
910     };
913 # restart daemon log file
914 if(-e $log_file ) { unlink $log_file }
915 daemon_log(" ", 1);
916 daemon_log("started!", 1);
918 # delete old DBsqlite lock files
919 system('rm -f /tmp/gosa_si_lock*gosa-si-bus*');
921 #prepare other variables
922 $xml =  new XML::Simple();
923 $bus_address = "$bus_ip:$bus_port";
925 # detect ip and mac address and complete host address
926 my $network_interface= &get_interface_for_ip($bus_ip);
927 $bus_mac_address= &get_mac($network_interface);
928 daemon_log("gosa-si-bus ip address detected: $bus_ip", 1);
929 daemon_log("gosa-si-bus mac address detected: $bus_mac_address", 1);
931 # connect to bus_known_server_db
932 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
933 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
934 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
936 my @clients_col_names = ('hostname', 'status', 'registered', 'macaddress', 'timestamp');
937 $bus_known_clients_db = GOSA::DBsqlite->new($bus_known_clients_file_name);
938 $bus_known_clients_db->create_table('bus_known_clients', \@clients_col_names);
940 # create socket for incoming xml messages
941 POE::Component::Server::TCP->new(
942     Alias => 'gosa-si-bus_socket',
943         Port => $bus_port,
944         ClientInput => \&bus_input,
945 );
946 daemon_log("start socket for incoming xml messages at port '$bus_port' ", 1);
948 # start session
949 POE::Session->create(
950         inline_states => {
951                 _start => \&_start, 
952         _default => \&_default,
953         here_i_am => \&here_i_am,
954         confirm_new_key => \&confirm_new_key,
955         new_client => \&new_client,
956         }
957 );
959 POE::Kernel->run();
960 exit;