Code

Added sanity check to beware of broken ldap config on client.
[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;
474     if( $msg_header ) {
475         $msg_header = "'$msg_header'-";
476     }
477     else {
478         $msg_header = "";
479     }
481     # encrypt xml msg
482     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
484     # opensocket
485     my $socket = &open_socket($address);
486     if( !$socket ) {
487         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
488         $error++;
489     }
490     
491     if( $error == 0 ) {
492         # send xml msg
493         print $socket $crypted_msg."\n";
495         daemon_log("send ".$msg_header."msg to $address", 1);
496         daemon_log("message:\n$msg", 8);
498     }
500     # close socket in any case
501     if( $socket ) {
502         close $socket;
503     }
505     return;
509 #===  FUNCTION  ================================================================
510 #         NAME:  open_socket
511 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
512 #                [PeerPort] string necessary if port not appended by PeerAddr
513 #      RETURNS:  socket IO::Socket::INET
514 #  DESCRIPTION:  open a socket to PeerAddr
515 #===============================================================================
516 sub open_socket {
517     my ($PeerAddr, $PeerPort) = @_ ;
518     if(defined($PeerPort)){
519         $PeerAddr = $PeerAddr.":".$PeerPort;
520     }
521     my $socket;
522     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
523             Porto => "tcp",
524             Type => SOCK_STREAM,
525             Timeout => 5,
526             );
527     if(not defined $socket) {
528         return;
529     }
530     &daemon_log("open_socket: $PeerAddr", 7);
531     return $socket;
535 sub check_key_and_xml_validity {
536     my ($crypted_msg, $module_key) = @_;
537 #print STDERR "crypted_msg:$crypted_msg\n";
538 #print STDERR "modul_key:$module_key\n";
540     my $msg;
541     my $msg_hash;
542     eval{
543         $msg = &decrypt_msg($crypted_msg, $module_key);
544         &main::daemon_log("decrypted_msg: \n$msg", 8);
546         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
548         # check header
549         my $header_l = $msg_hash->{'header'};
550         if( 1 != @{$header_l} ) {
551             die 'no or more headers specified';
552         }
553         my $header = @{$header_l}[0];
554         if( 0 == length $header) {
555             die 'header has length 0';
556         }
558         # check source
559         my $source_l = $msg_hash->{'source'};
560         if( 1 != @{$source_l} ) {
561             die 'no or more sources specified';
562         }
563         my $source = @{$source_l}[0];
564         if( 0 == length $source) {
565             die 'source has length 0';
566         }
568         # check target
569         my $target_l = $msg_hash->{'target'};
570         if( 1 != @{$target_l} ) {
571             die 'no or more targets specified ';
572         }
573         my $target = @{$target_l}[0];
574         if( 0 == length $target) {
575             die 'target has length 0 ';
576         }
578     };
579     if($@) {
580         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
581         &main::daemon_log("$@", 8);
582     }
584     return ($msg, $msg_hash);
588 sub input_from_new_server {
589     no strict "refs";
590     my ($input) = @_ ;
591     my ($msg, $msg_hash);
593     daemon_log("bus_known_server host_name: new host", 7);
594     daemon_log("bus_known_server host_key: $bus_key", 7);
596     # check if module can open msg envelope with key
597     ($msg, $msg_hash) = &check_key_and_xml_validity($input, $bus_key);
599     if( (!$msg) || (!$msg_hash) ) {
600         daemon_log("Incoming message is not from a new gosa-si-server", 5);
601     }
603     return ($msg, $msg_hash);
607 sub input_from_known_server {
608     my ($input, $remote_ip) = @_ ;  
609     my ($msg, $msg_hash);
611     my $sql_statement= "SELECT * FROM bus_known_server";
612     my $query_res = $bus_known_server_db->select_dbentry( $sql_statement ); 
614     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
615         my $host_name = $hit->{hostname};
616         if( not $host_name =~ "^$remote_ip") {
617             next;
618         }
619         my $host_key = $hit->{hostkey};
620         daemon_log("bus_known_server host_name: $host_name", 7);
621         daemon_log("bus_known_server host_key: $host_key", 7);
623         # check if module can open msg envelope with module key
624         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
625         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
626             next;
627         }
628         else {
629             $msg = $tmp_msg;
630             $msg_hash = $tmp_msg_hash;
631             last;
632         }
633     }
635     if( (!$msg) || (!$msg_hash) ) {
636         daemon_log("Incoming message is not from a known gosa-si-server", 5);
637     }
638   
639     return ($msg, $msg_hash);
643 sub _start {
644     my $kernel = $_[KERNEL];
645     $kernel->alias_set('gosa_si_bus_session');
646     return;
649 sub _default {
650     daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
651     return;
655 sub bus_input {
656     my ($kernel, $heap, $input, $wheel, $session) = @_[KERNEL, HEAP, ARG0, ARG1, SESSION];
657     my ($msg, $msg_hash);
658     my $error = 0;
659     
660     daemon_log("Incoming msg:\n$input\n", 8);
662     # msg is from a new gosa-si-server
663     ($msg, $msg_hash) = &input_from_new_server($input);
665     # msg is from a gosa-si-server or gosa-si-bus
666     if(( !$msg ) || ( !$msg_hash ) ){
667         ($msg, $msg_hash) = &input_from_known_server($input, $heap->{'remote_ip'});
668     }
670     # an error occurred
671     if(( !$msg ) || ( !$msg_hash )){
672         $error++;
673     }
675     if( $error == 0) {
676         my @target_l = @{$msg_hash->{'target'}};
677         my $source = @{$msg_hash->{'source'}}[0];
678         my $header = @{$msg_hash->{header}}[0];
680         if( 1 == length(@target_l) && $target_l[0] eq $bus_address ) {
681             # msg is for bus
682             $kernel->post('gosa_si_bus_session', $header, $msg, $msg_hash);
683         }
684         else {
685             # msg is for someone else, deliver it
687             print STDERR "msg is for someone else\n";
688             foreach my $target (@target_l) {
689                 print STDERR "target: $target\n";
690                 if( $target =~ /(\d{3}\.\d{3}\.\d{3}\.\d{3}:\d+)/ ) {
691                     # target is a ip address
693                     my $sql_statement = "SELECT * FROM bus_known_server WHERE hostname='$target'";
694                     my $sql_statement = "SELECT * FROM bus_known_clients WHERE hostname='$target'";
695                 }
696                 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})/ ) {
697                     # target is a mac address
699                     my $sql_statement = "SELECT registerd FROM bus_known_clients WHERE macaddress='$target'";
700                     my $query_res = $bus_known_clients_db->select_dbentry( $sql_statement );
701                     print Dumper $query_res;
703                     
704                 }
705                 else {
707                 }
709             }
710         }
711     }
715 sub here_i_am {
716     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
717     my $source = @{$msg_hash->{'source'}}[0];
718     my $target = @{$msg_hash->{'target'}}[0];
720     my $new_key = &create_passwd();
722     # create bus_known_server entry
723     my $add_hash = {
724         table=>"bus_known_server",
725         primkey=>"hostname",
726         hostname=>$source,
727         status=>"registered",
728         hostkey=>$bus_key,
729     };
730     $bus_known_server_db->add_dbentry($add_hash);
732     # create outgoing msg
733     my $out_hash = &create_xml_hash("new_key", $target, $source, $new_key);
734     &send_msg_hash2address($out_hash, $source, $bus_key);
736     # change hostkey, reason
737     my $where_str= " WHERE hostname='$source'";
738     my $update_str= " SET hostkey='$new_key'";
739     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
740     $bus_known_server_db->update_dbentry($sql_statement);
744 sub confirm_new_key {
745     my ( $msg, $msg_hash ) = @_[ ARG0, ARG1 ];
746     my $source = @{$msg_hash->{'source'}}[0];
747     daemon_log("'$source' confirms new key", 3);
751 sub new_client {
752     my ($msg, $msg_hash) = @_[ ARG0, ARG1 ];
754     my $new_client = @{$msg_hash->{'new_client'}}[0];
755     my $source = @{$msg_hash->{'source'}}[0];
756     my $mac_address = @{$msg_hash->{'macaddress'}}[0];
757     my $act_timestamp = @{$msg_hash->{'timestamp'}}[0];
758     
759     my $add_hash = {
760         table => "bus_known_clients",
761         primkey=>"hostname",
762         hostname=>$new_client,
763         status=>'activ',
764         registered=>$source,
765         macaddress=>$mac_address,
766         timestamp=>$act_timestamp,
767     };
768     $bus_known_clients_db->add_dbentry($add_hash);
773 #==== MAIN = main ==============================================================
776 #  parse commandline options
777 Getopt::Long::Configure( "bundling" );
778 GetOptions("h|help" => \&usage,
779            "c|config=s" => \$cfg_file,
780            "f|foreground" => \$foreground,
781            "v|verbose+" => \$verbose,
782            );
784 #  read and set config parameters
785 &check_cmdline_param ;
786 &read_configfile;
787 &check_pid;
789 $SIG{CHLD} = 'IGNORE';
792 # forward error messages to logfile
793 if ( ! $foreground ) {
794         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
795         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
796         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
799 # Just fork, if we are not in foreground mode
800 if( ! $foreground ) { 
801     chdir '/'                 or die "Can't chdir to /: $!";
802     $pid = fork;
803     setsid                    or die "Can't start a new session: $!";
804     umask 0;
805
806 else { 
807     $pid = $$; 
810 # Do something useful - put our PID into the pid_file
811 if( 0 != $pid ) {
812     open( LOCK_FILE, ">$pid_file" );
813     print LOCK_FILE "$pid\n";
814     close( LOCK_FILE );
815     if( !$foreground ) { 
816         exit( 0 ) 
817     };
820 # restart daemon log file
821 if(-e $log_file ) { unlink $log_file }
822 daemon_log(" ", 1);
823 daemon_log("started!", 1);
825 # delete old DBsqlite lock files
826 system('rm -f /tmp/gosa_si_lock*gosa-si-bus*');
828 #prepare other variables
829 $xml =  new XML::Simple();
830 $bus_address = "$bus_ip:$bus_port";
832 # detect ip and mac address and complete host address
833 my $network_interface= &get_interface_for_ip($bus_ip);
834 $bus_mac_address= &get_mac($network_interface);
835 daemon_log("gosa-si-bus ip address detected: $bus_ip", 1);
836 daemon_log("gosa-si-bus mac address detected: $bus_mac_address", 1);
838 # connect to bus_known_server_db
839 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
840 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
841 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
843 my @clients_col_names = ('hostname', 'status', 'registered', 'macaddress', 'timestamp');
844 $bus_known_clients_db = GOSA::DBsqlite->new($bus_known_clients_file_name);
845 $bus_known_clients_db->create_table('bus_known_clients', \@clients_col_names);
847 # create socket for incoming xml messages
848 POE::Component::Server::TCP->new(
849     Alias => 'gosa-si-bus_socket',
850         Port => $bus_port,
851         ClientInput => \&bus_input,
852 );
853 daemon_log("start socket for incoming xml messages at port '$bus_port' ", 1);
855 # start session
856 POE::Session->create(
857         inline_states => {
858                 _start => \&_start, 
859         _default => \&_default,
860         here_i_am => \&here_i_am,
861         confirm_new_passwd => \&confirm_new_key,
862         new_client => \&new_client,
863         }
864 );
866 POE::Kernel->run();
867 exit;