Code

Correct the source ip if 0.0.0.0
[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;
410 #===  FUNCTION  ================================================================
411 #         NAME:  create_passwd
412 #   PARAMETERS:  nothing
413 #      RETURNS:  new_passwd - string 
414 #  DESCRIPTION:  creates a 32 bit long random passwd out of "a".."z","A".."Z",0..9
415 #===============================================================================
416 sub create_passwd {
417     my $new_passwd = "";
418     for(my $i=0; $i<31; $i++) {
419         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
420     }
421     return $new_passwd;
425 sub create_ciphering {
426     my ($passwd) = @_;
427     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
428     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
429     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
430     $my_cipher->set_iv($iv);
431     return $my_cipher;
435 sub encrypt_msg {
436     my ($msg, $key) = @_;
437     my $my_cipher = &create_ciphering($key);
438     {
439       use bytes;
440       $msg = "\0"x(16-length($msg)%16).$msg;
441     }
442     $msg = $my_cipher->encrypt($msg);
443     chomp($msg = &encode_base64($msg));
444     # there are no newlines allowed inside msg
445     $msg=~ s/\n//g;
446     return $msg;
450 sub decrypt_msg {
451     my ($msg, $key) = @_ ;
452     $msg = &decode_base64($msg);
453     my $my_cipher = &create_ciphering($key);
454     $msg = $my_cipher->decrypt($msg); 
455     $msg =~ s/\0*//g;
456     return $msg;
460 sub send_msg_hash2address {
461     my ($msg_hash, $address, $encrypt_key) = @_ ;
462     my $msg = &create_xml_string($msg_hash);
463     my $header = @{$msg_hash->{'header'}}[0];
464     &send_msg_to_target($msg, $address, $encrypt_key, $header);
465     
466     return;
470 sub send_msg_to_target {
471     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
472     my $error = 0;
473     my $header;
474     my $new_status;
475     my $act_status;
476     my ($sql_statement, $res);
478     if( $msg_header ) {
479         $header = "'$msg_header'-";
480     }
481     else {
482         $header = "";
483     }
485     # encrypt xml msg
486     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
488     # opensocket
489     my $socket = &open_socket($address);
490     if( !$socket ) {
491         daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
492         $error++;
493     }
494     
495     if( $error == 0 ) {
496         # send xml msg
497         print $socket $crypted_msg."\n";
499         daemon_log("send ".$header."msg to $address", 1);
500         daemon_log("message:\n$msg", 8);
502     }
504     # close socket in any case
505     if( $socket ) {
506         close $socket;
507     }
509     if( $error > 0 ) { $new_status = "down"; }
510     else { $new_status = $msg_header; }
513     # known_clients
514     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$address'";
515     $res = $bus_known_clients_db->select_dbentry($sql_statement);
516     if( keys(%$res) > 0 ) {
517         $act_status = $res->{1}->{'status'};
518         if( $act_status eq "down" ) {
519             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
520             $res = $bus_known_clients_db->del_dbentry($sql_statement);
521             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from bus_known_clients", 3);
522         } 
523         else { 
524             $sql_statement = "UPDATE bus_known_clients SET status='$new_status' WHERE hostname='$address'";
525             $res = $bus_known_clients_db->update_dbentry($sql_statement);
526             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
527         }
528     }
530     # known_server
531     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$address'";
532     $res = $bus_known_server_db->select_dbentry($sql_statement);
533     if( keys(%$res) > 0) {
534         $act_status = $res->{1}->{'status'};
535         if( $act_status eq "down" ) {
536             $sql_statement = "DELETE FROM bus_known_clients WHERE hostname='$address'";
537             $res = $bus_known_clients_db->del_dbentry($sql_statement);
538             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from bus_known_server", 3);
539         } 
540         else { 
541             $sql_statement = "UPDATE bus_known_server SET status='$new_status' WHERE hostname='$address'";
542             $res = $bus_known_server_db->update_dbentry($sql_statement);
543             daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5)
544         }
545     }
547     return;
551 #===  FUNCTION  ================================================================
552 #         NAME:  open_socket
553 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
554 #                [PeerPort] string necessary if port not appended by PeerAddr
555 #      RETURNS:  socket IO::Socket::INET
556 #  DESCRIPTION:  open a socket to PeerAddr
557 #===============================================================================
558 sub open_socket {
559     my ($PeerAddr, $PeerPort) = @_ ;
560     if(defined($PeerPort)){
561         $PeerAddr = $PeerAddr.":".$PeerPort;
562     }
563     my $socket;
564     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
565             Porto => "tcp",
566             Type => SOCK_STREAM,
567             Timeout => 5,
568             );
569     if(not defined $socket) {
570         return;
571     }
572     &daemon_log("open_socket: $PeerAddr", 7);
573     return $socket;
577 sub check_key_and_xml_validity {
578     my ($crypted_msg, $module_key) = @_;
579 #print STDERR "crypted_msg:$crypted_msg\n";
580 #print STDERR "modul_key:$module_key\n";
582     my $msg;
583     my $msg_hash;
584     eval{
585         $msg = &decrypt_msg($crypted_msg, $module_key);
586         &main::daemon_log("decrypted_msg: \n$msg", 8);
588         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
590         # check header
591         my $header_l = $msg_hash->{'header'};
592         if( 1 != @{$header_l} ) {
593             die 'no or more headers specified';
594         }
595         my $header = @{$header_l}[0];
596         if( 0 == length $header) {
597             die 'header has length 0';
598         }
600         # check source
601         my $source_l = $msg_hash->{'source'};
602         if( 1 != @{$source_l} ) {
603             die 'no or more sources specified';
604         }
605         my $source = @{$source_l}[0];
606         if( 0 == length $source) {
607             die 'source has length 0';
608         }
610         # check target
611         my $target_l = $msg_hash->{'target'};
612         if( 1 != @{$target_l} ) {
613             die 'no or more targets specified ';
614         }
615         my $target = @{$target_l}[0];
616         if( 0 == length $target) {
617             die 'target has length 0 ';
618         }
620     };
621     if($@) {
622         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
623         &main::daemon_log("$@", 8);
624     }
626     return ($msg, $msg_hash);
630 sub input_from_new_server {
631     no strict "refs";
632     my ($input) = @_ ;
633     my ($msg, $msg_hash);
635     daemon_log("bus_known_server host_name: new host", 7);
636     daemon_log("bus_known_server host_key: $bus_key", 7);
638     # check if module can open msg envelope with key
639     ($msg, $msg_hash) = &check_key_and_xml_validity($input, $bus_key);
641     if( (!$msg) || (!$msg_hash) ) {
642         daemon_log("Incoming message is not from a new gosa-si-server", 5);
643     }
645     return ($msg, $msg_hash);
649 sub input_from_known_server {
650     my ($input, $remote_ip) = @_ ;  
651     my ($msg, $msg_hash);
653     my $sql_statement= "SELECT * FROM bus_known_server";
654     my $query_res = $bus_known_server_db->select_dbentry( $sql_statement ); 
656     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
657         my $host_name = $hit->{hostname};
658         if( not $host_name =~ "^$remote_ip") {
659             next;
660         }
661         my $host_key = $hit->{hostkey};
662         daemon_log("bus_known_server host_name: $host_name", 7);
663         daemon_log("bus_known_server host_key: $host_key", 7);
665         # check if module can open msg envelope with module key
666         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
667         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
668             next;
669         }
670         else {
671             $msg = $tmp_msg;
672             $msg_hash = $tmp_msg_hash;
673             last;
674         }
675     }
677     if( (!$msg) || (!$msg_hash) ) {
678         daemon_log("Incoming message is not from a known gosa-si-server", 5);
679     }
680   
681     return ($msg, $msg_hash);
685 sub _start {
686     my $kernel = $_[KERNEL];
687     $kernel->alias_set('gosa_si_bus_session');
688     return;
691 sub _default {
692     daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
693     return;
697 sub bus_input {
698     my ($kernel, $heap, $input, $wheel, $session) = @_[KERNEL, HEAP, ARG0, ARG1, SESSION];
699     my ($msg, $msg_hash);
700     my $error = 0;
701     
702     daemon_log("Incoming msg:\n$input\n", 8);
704     # msg is from a new gosa-si-server
705     ($msg, $msg_hash) = &input_from_new_server($input);
707     # msg is from a gosa-si-server or gosa-si-bus
708     if(( !$msg ) || ( !$msg_hash ) ){
709         ($msg, $msg_hash) = &input_from_known_server($input, $heap->{'remote_ip'});
710     }
712     # an error occurred
713     if(( !$msg ) || ( !$msg_hash )){
714         $error++;
715     }
717     if( $error == 0) {
718         my @target_l = @{$msg_hash->{'target'}};
719         my $source = @{$msg_hash->{'source'}}[0];
720         my $header = @{$msg_hash->{header}}[0];
722         my $target_string = join(",", @target_l);
723         daemon_log("got msg '$header' with target '$target_string' from ".$heap->{'remote_ip'}, 3);
725         if( 1 == length(@target_l) && $target_l[0] eq $bus_address ) {
726             # msg is for bus
727 #print STDERR "msg is for bus\n";
728             $kernel->post('gosa_si_bus_session', $header, $msg, $msg_hash);
729         }
730         else {
731             # msg is for someone else, deliver it
733 #print STDERR "msg is for someone else\n";
734             foreach my $target (@target_l) {
735                 if( $target =~ /(\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}:\d+)/ ) {
736                     # target is a ip address
737                     my ($sql_statement, $query_res);
739                     $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$target'";
740                     $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
741                     if( 1 == keys(%$query_res) ) {
742                         my $host_name = $query_res->{1}->{'hostname'};
743                         my $host_key = $query_res->{1}->{'hostkey'};
744                         &send_msg_to_target($msg, $host_name, $host_key, $header);
745                         next;
746                     } 
748                     $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$target'";
749                     $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
750                     if( 1 == keys(%$query_res) ) {
751                         my $host_name = $query_res->{1}->{'hostname'};
752                         my $server_name = $query_res->{1}->{'registered'};
753                         # fetch correct key for server
754                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
755                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
756                         my $server_key = $query_res->{1}->{'hostkey'};
757                         &send_msg_to_target($msg, $server_name, $server_key, $header);
758                         next;
759                     } 
761                     daemon_log("ERROR:unknown host, can not process message '$header'", 1);
762                 }
763                 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})/ ) {
764                     # target is a mac address
765                     my $sql_statement = "SELECT * FROM bus_known_clients WHERE macaddress='$target'";
766                     my $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
767                     if( 1 > keys(%{$query_res})) {
768                         daemon_log("ERROR: there are more than one hosts in bus_known_clients_db with mac address '$target'", 1);
769                     }
770                     elsif( 0 == keys(%{$query_res})) {
771                         daemon_log("WARNING: no host found in bus_known_clients_db with mac address '$target'", 3);
772                     }
773                     else {
774                         my $host_name = $query_res->{1}->{'hostname'};
775                         my $server_name = $query_res->{1}->{'registered'};
776                         my $out_msg = $msg;
777                         $out_msg =~ s/<target>$target<\/target>/<target>$host_name<\/target>/;
779                         # fetch correct key for server
780                         my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$server_name'";
781                         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
782                         my $server_key = $query_res->{1}->{'hostkey'};
784                         &send_msg_to_target($out_msg, $server_name, $server_key, $header);
785                     }
786                 }
787                 else {
788                     daemon_log("ERROR: target address '$target' does not match neiter ".
789                         "to ip address nor to mac address, can not process msg", 1);
790                 }
792             }
793         }
794     }
798 sub here_i_am {
799     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
800     my $source = @{$msg_hash->{'source'}}[0];
801     my $target = @{$msg_hash->{'target'}}[0];
803     my $new_key = &create_passwd();
805     # create bus_known_server entry
806     my $add_hash = {
807         table=>"bus_known_server",
808         primkey=>"hostname",
809         hostname=>$source,
810         status=>"registered",
811         hostkey=>$bus_key,
812     };
813     $bus_known_server_db->add_dbentry($add_hash);
815     # create outgoing msg
816     my $out_hash = &create_xml_hash("new_key", $target, $source, $new_key);
817     &send_msg_hash2address($out_hash, $source, $bus_key);
819     # change hostkey, reason
820     my $where_str= " WHERE hostname='$source'";
821     my $update_str= " SET hostkey='$new_key'";
822     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
823     $bus_known_server_db->update_dbentry($sql_statement);
827 sub confirm_new_key {
828     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
829     my $source = @{$msg_hash->{'source'}}[0];
830     daemon_log("'$source' confirms new key", 3);
834 sub new_client {
835     my ($msg, $msg_hash) = @_[ ARG0, ARG1 ];
837     my $new_client = @{$msg_hash->{'new_client'}}[0];
838     my $source = @{$msg_hash->{'source'}}[0];
839     my $mac_address = @{$msg_hash->{'macaddress'}}[0];
840     my $act_timestamp = @{$msg_hash->{'timestamp'}}[0];
841     
842     my $add_hash = {
843         table => "bus_known_clients",
844         primkey=>"hostname",
845         hostname=>$new_client,
846         status=>'activ',
847         registered=>$source,
848         macaddress=>$mac_address,
849         timestamp=>$act_timestamp,
850     };
851     $bus_known_clients_db->add_dbentry($add_hash);
852     daemon_log("add new client '$new_client' to bus_known_clients_db", 3);
857 #==== MAIN = main ==============================================================
860 #  parse commandline options
861 Getopt::Long::Configure( "bundling" );
862 GetOptions("h|help" => \&usage,
863            "c|config=s" => \$cfg_file,
864            "f|foreground" => \$foreground,
865            "v|verbose+" => \$verbose,
866            );
868 #  read and set config parameters
869 &check_cmdline_param ;
870 &read_configfile;
871 &check_pid;
873 $SIG{CHLD} = 'IGNORE';
876 # forward error messages to logfile
877 if ( ! $foreground ) {
878         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
879         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
880         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
883 # Just fork, if we are not in foreground mode
884 if( ! $foreground ) { 
885     chdir '/'                 or die "Can't chdir to /: $!";
886     $pid = fork;
887     setsid                    or die "Can't start a new session: $!";
888     umask 0;
889
890 else { 
891     $pid = $$; 
894 # Do something useful - put our PID into the pid_file
895 if( 0 != $pid ) {
896     open( LOCK_FILE, ">$pid_file" );
897     print LOCK_FILE "$pid\n";
898     close( LOCK_FILE );
899     if( !$foreground ) { 
900         exit( 0 ) 
901     };
904 # restart daemon log file
905 if(-e $log_file ) { unlink $log_file }
906 daemon_log(" ", 1);
907 daemon_log("started!", 1);
909 # delete old DBsqlite lock files
910 system('rm -f /tmp/gosa_si_lock*gosa-si-bus*');
912 #prepare other variables
913 $xml =  new XML::Simple();
914 $bus_address = "$bus_ip:$bus_port";
916 # detect ip and mac address and complete host address
917 my $network_interface= &get_interface_for_ip($bus_ip);
918 $bus_mac_address= &get_mac($network_interface);
919 daemon_log("gosa-si-bus ip address detected: $bus_ip", 1);
920 daemon_log("gosa-si-bus mac address detected: $bus_mac_address", 1);
922 # connect to bus_known_server_db
923 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
924 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
925 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
927 my @clients_col_names = ('hostname', 'status', 'registered', 'macaddress', 'timestamp');
928 $bus_known_clients_db = GOSA::DBsqlite->new($bus_known_clients_file_name);
929 $bus_known_clients_db->create_table('bus_known_clients', \@clients_col_names);
931 # create socket for incoming xml messages
932 POE::Component::Server::TCP->new(
933     Alias => 'gosa-si-bus_socket',
934         Port => $bus_port,
935         ClientInput => \&bus_input,
936 );
937 daemon_log("start socket for incoming xml messages at port '$bus_port' ", 1);
939 # start session
940 POE::Session->create(
941         inline_states => {
942                 _start => \&_start, 
943         _default => \&_default,
944         here_i_am => \&here_i_am,
945         confirm_new_key => \&confirm_new_key,
946         new_client => \&new_client,
947         }
948 );
950 POE::Kernel->run();
951 exit;