Code

Create Entry in ou=incoming if client does not exist in LDAP (if ArpHandler is not...
[gosa.git] / gosa-si / gosa-si-bus
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 #         FILE:  gosa-server
5 #
6 #        USAGE:  ./gosa-server
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 IO::Socket::INET;
29 use Crypt::Rijndael;
30 use MIME::Base64;
31 use Digest::MD5  qw(md5 md5_hex md5_base64);
32 use XML::Simple;
33 use Data::Dumper;
34 use Sys::Syslog qw( :DEFAULT setlogsock);
35 use Cwd;
36 use File::Spec;
37 use GOSA::GosaSupportDaemon;
38 use GOSA::DBsqlite;
40 my ($cfg_file, $default_cfg_file, %cfg_defaults, $foreground, $verbose);
41 my ($bus_activ, $bus_key, $bus_ip, $bus_port, $bus_address, $bus, $bus_mac_address, $network_interface);
42 my ($pid_file, $procid, $pid, $log_file, $my_own_address);
43 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
44 my ($bus_known_server_db, $bus_known_server_file_name);
45 my ($xml, $bus_cipher);
47 $foreground = 0 ;
49 %cfg_defaults =
50 ("general" =>
51     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
52     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
53     "child_max" => [\$child_max, 10],
54     "child_min" => [\$child_min, 3],
55     "child_timeout" => [\$child_timeout, 180],
56     "bus_known_server_file_name" => [\$bus_known_server_file_name, "/var/lib/gosa-si/gosa-si-bus_known_server.db"]
57     },
58 "bus" =>
59     {"bus_activ" => [\$bus_activ, "on"],
60     "bus_passwd" => [\$bus_key, ""],
61     "bus_ip" => [\$bus_ip, "0.0.0.0"],
62     "bus_port" => [\$bus_port, "20080"],
63     }
64     );
66 #===  FUNCTION  ================================================================
67 #         NAME:  read_configfile
68 #   PARAMETERS:  cfg_file - string - 
69 #      RETURNS:  nothing 
70 #  DESCRIPTION:  read cfg_file and set variables
71 #===============================================================================
72 sub read_configfile {
73     my $cfg;
74     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
75         if( -r $cfg_file ) {
76             $cfg = Config::IniFiles->new( -file => $cfg_file );
77         } else {
78             print STDERR "Couldn't read config file!";
79         }
80     } else {
81         $cfg = Config::IniFiles->new() ;
82     }
83     foreach my $section (keys %cfg_defaults) {
84         foreach my $param (keys %{$cfg_defaults{ $section }}) {
85             my $pinfo = $cfg_defaults{ $section }{ $param };
86             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
87         }
88     }
89 }
91 #===  FUNCTION  ================================================================
92 #         NAME:  logging
93 #   PARAMETERS:  level - string - default 'info' 
94 #                msg - string - 
95 #                facility - string - default 'LOG_DAEMON' 
96 #      RETURNS:  nothing
97 #  DESCRIPTION:  function for logging
98 #===============================================================================
99 sub daemon_log {
100     my( $msg, $level ) = @_;
101     if(not defined $msg) { return }
102     if(not defined $level) { $level = 1 }
103     if(defined $log_file){
104         open(LOG_HANDLE, ">>$log_file");
105         if(not defined open( LOG_HANDLE, ">>$log_file" )) { 
106             print STDERR "cannot open $log_file: $!";
107             return }
108         chomp($msg);
109         if($level && $verbose && $level <= $verbose){
110             print LOG_HANDLE $msg."\n";
111             if(defined $foreground) { print STDERR $msg."\n" }
112         }
113     }
114     close( LOG_HANDLE );
115 #    my ($msg, $level, $facility) = @_;
116 #    if(not defined $msg) {return}
117 #    if(not defined $level) {$level = "info"}
118 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
119 #    openlog($0, "pid,cons,", $facility);
120 #    syslog($level, $msg);
121 #    closelog;
122 #    return;
125 #===  FUNCTION  ================================================================
126 #         NAME:  check_cmdline_param
127 #   PARAMETERS:  nothing
128 #      RETURNS:  nothing
129 #  DESCRIPTION:  validates commandline parameter 
130 #===============================================================================
131 sub check_cmdline_param () {
132     my $err_config;
133     my $err_counter = 0;
134     if( not defined( $cfg_file)) {
135         my $cwd = getcwd;
136         my $name = "/etc/gosa-si/bus.conf";
137         $cfg_file = File::Spec->catfile( $cwd, $name );
138     }
139     if( $err_counter > 0 ) {
140         &usage( "", 1 );
141         if( defined( $err_config)) { print STDERR "$err_config\n"}
142         print STDERR "\n";
143         exit( -1 );
144     }
147 #===  FUNCTION  ================================================================
148 #         NAME:  check_pid
149 #   PARAMETERS:  nothing
150 #      RETURNS:  nothing
151 #  DESCRIPTION:  handels pid processing
152 #===============================================================================
153 sub check_pid {
154     $pid = -1;
155     # Check, if we are already running
156     if( open(LOCK_FILE, "<$pid_file") ) {
157         $pid = <LOCK_FILE>;
158         if( defined $pid ) {
159             chomp( $pid );
160             if( -f "/proc/$pid/stat" ) {
161                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
162                 if( $0 eq $stat ) {
163                     close( LOCK_FILE );
164                     exit -1;
165                 }
166             }
167         }
168         close( LOCK_FILE );
169         unlink( $pid_file );
170     }
172     # create a syslog msg if it is not to possible to open PID file
173     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
174         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
175         if (open(LOCK_FILE, '<', $pid_file)
176                 && ($pid = <LOCK_FILE>))
177         {
178             chomp($pid);
179             $msg .= "(PID $pid)\n";
180         } else {
181             $msg .= "(unable to read PID)\n";
182         }
183         if( ! ($foreground) ) {
184             openlog( $0, "cons,pid", "daemon" );
185             syslog( "warning", $msg );
186             closelog();
187         }
188         else {
189             print( STDERR " $msg " );
190         }
191         exit( -1 );
192     }
196 #===  FUNCTION  ================================================================
197 #         NAME:  usage
198 #   PARAMETERS:  nothing
199 #      RETURNS:  nothing
200 #  DESCRIPTION:  print out usage text to STDERR
201 #===============================================================================
202 sub usage {
203     print STDERR << "EOF" ;
204 usage: $0 [-hvf] [-c config]
206     -h        : this (help) message
207     -c <file> : config file
208     -f        : foreground, process will not be forked to background
209     -v        : be verbose (multiple to increase verbosity)
210 EOF
211     print "\n" ;
215 #===  FUNCTION  ================================================================
216 #         NAME:  sig_int_handler
217 #   PARAMETERS:  signal - string - signal arose from system
218 #      RETURNS:  noting
219 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
220 #===============================================================================
221 sub sig_int_handler {
222     my ($signal) = @_;
223     if($bus){
224         close($bus);
225         print "$bus closed\n";
226     }
227     print "$signal\n";
228     exit(1);
230 $SIG{INT} = \&sig_int_handler;
232 #===  FUNCTION  ================================================================
233 #         NAME:  get_interface_for_ip
234 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
235 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
236 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
237 #===============================================================================
238 sub get_interface_for_ip {
239         my $result;
240         my $ip= shift;
241         if ($ip && length($ip) > 0) {
242                 my @ifs= &get_interfaces();
243                 if($ip eq "0.0.0.0") {
244                         $result = "all";
245                 } else {
246                         foreach (@ifs) {
247                                 my $if=$_;
248                                 if(get_ip($if) eq $ip) {
249                                         $result = $if;
250                                 }
251                         }
252                 }
253         }
254         return $result;
257 #===  FUNCTION  ================================================================
258 #         NAME:  get_interfaces 
259 #   PARAMETERS:  none
260 #      RETURNS:  (list of interfaces) 
261 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
262 #===============================================================================
263 sub get_interfaces {
264         my @result;
265         my $PROC_NET_DEV= ('/proc/net/dev');
267         open(PROC_NET_DEV, "<$PROC_NET_DEV")
268                 or die "Could not open $PROC_NET_DEV";
270         my @ifs = <PROC_NET_DEV>;
272         close(PROC_NET_DEV);
274         # Eat first two line
275         shift @ifs;
276         shift @ifs;
278         chomp @ifs;
279         foreach my $line(@ifs) {
280                 my $if= (split /:/, $line)[0];
281                 $if =~ s/^\s+//;
282                 push @result, $if;
283         }
285         return @result;
288 #===  FUNCTION  ================================================================
289 #         NAME:  get_mac 
290 #   PARAMETERS:  interface name (i.e. eth0)
291 #      RETURNS:  (mac address) 
292 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
293 #===============================================================================
294 sub get_mac {
295     my $ifreq= shift;
296     my $result;
297     if ($ifreq && length($ifreq) > 0) {
298         if($ifreq eq "all") {
299             $result = "00:00:00:00:00:00";
300         } else {
301             my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
303                 # A configured MAC Address should always override a guessed value
304                 if ($bus_mac_address and length($bus_mac_address) > 0) {
305                     return $bus_mac_address;
306                 }
308             socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
309                 or die "socket: $!";
311             if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
312                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
314                 if (length($mac) > 0) {
315                     $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])$/;
316                     $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
317                     $result = $mac;
318                 }
319             }
320         }
321     }
322     return $result;
325 #===  FUNCTION  ================================================================
326 #         NAME:  get_ip 
327 #   PARAMETERS:  interface name (i.e. eth0)
328 #      RETURNS:  (ip address) 
329 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
330 #===============================================================================
331 sub get_ip {
332         my $ifreq= shift;
333         my $result= "";
334         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
335         my $proto= getprotobyname('ip');
337         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
338                 or die "socket: $!";
340         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
341                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
342                 my ($port, $addr) = sockaddr_in $sin;
343                 my $ip            = inet_ntoa $addr;
345                 if ($ip && length($ip) > 0) {
346                         $result = $ip;
347                 }
348         }
350         return $result;
353 #===  FUNCTION  ================================================================
354 #         NAME:  activating_child
355 #   PARAMETERS:  msg - string - incoming message
356 #                host - string - host from which the incomming message comes
357 #      RETURNS:  nothing
358 #  DESCRIPTION:  handels the distribution of incoming messages to working childs
359 #===============================================================================
360 sub activating_child {
361     my ($msg, $host) = @_;
362     my $child = &get_processing_child();
363     my $pipe_wr = $$child{'pipe_wr'};
364     daemon_log("activating: childpid: $$child{'pid'}", 5);
365     print $pipe_wr $msg.".".$host."\n";
366     return;
370 #===  FUNCTION  ================================================================
371 #         NAME:  get_processing_child
372 #   PARAMETERS:  nothing
373 #      RETURNS:  child - hash - holding the process id and the references to the pipe
374 #                               handles pipe_wr and pipe_rd
375 #  DESCRIPTION:  handels the forking, reactivating and keeping alive tasks
376 #===============================================================================
377 sub get_processing_child {
378     my $child;
379     # checking %busy_child{pipe_wr} if msg is 'done', then set child from busy to free
380     while(my ($key, $val) = each(%busy_child)) {
381         # check wether process still exists
382         my $exitus_pid = waitpid($key, WNOHANG);
383         if($exitus_pid != 0) {
384             delete $busy_child{$key};
385             daemon_log( "prozess:$key wurde aus busy_child entfernt\n", 5);
386             next;
387         }
389         # check wether process sitll works
390         my $fh = $$val{'pipe_rd'};
391         $fh->blocking(0); 
392         my $child_answer;
393         if(not $child_answer = <$fh>) { next }
394         chomp($child_answer);
395         if($child_answer eq "done") {
396             delete $busy_child{$key};
397             $free_child{$key} = $val;
398         }
399     }
401     while(my ($key, $val) = each(%free_child)) {
402         my $exitus_pid = waitpid($key, WNOHANG);
403         if($exitus_pid != 0) {
404             delete $free_child{$key};
405             daemon_log( "prozess:$key wurde aus free_child entfernt\n", 5);
406         }
407         daemon_log("free child:$key\n", 5);
408     }
409     # check @free_child and @busy_child
410     my $free_len = scalar(keys(%free_child));
411     my $busy_len = scalar(keys(%busy_child));
412     daemon_log("free children $free_len, busy children $busy_len\n",5);
413     
414     # if there is a free child, let the child work 
415     if($free_len > 0){
416         my @keys = keys(%free_child);
417         $child = $free_child{$keys[0]};
418         if(defined $child) {
419             $busy_child{$$child{'pid'}} = $child ; 
420             delete $free_child{$$child{'pid'}};          
421         }
422         return $child;
423     }
424     
425     # no free child, try to fork another one 
426     if($free_len + $busy_len < $child_max) {
427                 
428         daemon_log("not enough children, create a new one\n",5);
430         # New pipes for communication
431         my( $PARENT_wr, $PARENT_rd );
432         my( $CHILD_wr, $CHILD_rd );
433         pipe( $CHILD_rd,  $PARENT_wr );
434         pipe( $PARENT_rd, $CHILD_wr  );
435         $PARENT_wr->autoflush(1);
436         $CHILD_wr->autoflush(1);
438         ############
439         # fork child
440         ############
441         my $child_pid = fork();
442         
443         #CHILD
444         if($child_pid == 0) {
445             # Close unused pipes
446             close( $CHILD_rd );
447             close( $CHILD_wr );
448             while( 1 ) {
449                 my $rbits = "";
450                 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
452                 # waiting child_timeout for jobs to do
453                 my $nf = select($rbits, undef, undef, $child_timeout);
454                 if($nf < 0 ) {
455                     # if $nf < 1, error handling
456                     die "select(): $!\n";
457                 } elsif (! $nf) {
458                     # if already child_min childs are alive, then leave loop
459                     $free_len = scalar(keys(%free_child));
460                     $busy_len = scalar(keys(%busy_child));
461                     if($free_len + $busy_len >= $child_min) {
462                         last;
463                     } else {
464                         redo;
465                     }
466                 } 
468                 # a job for a child arise
469                 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
470                     # read everything from pipe
471                     my $msg = "";
472                     $PARENT_rd->blocking(0);
473                     while(1) {
474                         my $read = <$PARENT_rd>;
475                         if(not defined $read) { last}
476                         $msg .= $read;
477                     }
479                     # forward the job msg to another function
480                     &process_incoming_msg($msg);
481                     daemon_log("processing of msg finished", 5);
483                     # important!!! wait until child says 'done', until then child is set from busy to free
484                     print $PARENT_wr "done";
485                     redo;
486                 }
487             }
488             # childs leaving the loop are allowed to die
489             exit(0);
491         #PARENT
492         } else {
493             # Close unused pipes
494             close( $PARENT_rd );
495             close( $PARENT_wr );
496             # add child to child alive hash
497             my %child_hash = (
498                     'pid' => $child_pid,
499                     'pipe_wr' => $CHILD_wr,
500                     'pipe_rd' => $CHILD_rd,
501                     );
503             $child = \%child_hash;
504             $busy_child{$$child{'pid'}} = $child;
505             return $child;
506         }
507     }
510 #===  FUNCTION  ================================================================
511 #         NAME:  open_socket
512 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
513 #                [PeerPort] string necessary if port not appended by PeerAddr
514 #      RETURNS:  socket IO::Socket::INET
515 #  DESCRIPTION:  open a socket to PeerAddr
516 #===============================================================================
517 sub open_socket {
518     my ($PeerAddr, $PeerPort) = @_ ;
519     if(defined($PeerPort)){
520         $PeerAddr = $PeerAddr.":".$PeerPort;
521     }
522     my $socket;
523     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
524             Porto => "tcp",
525             Type => SOCK_STREAM,
526             Timeout => 5,
527             );
528     if(not defined $socket) {
529         return;
530     }
531     &daemon_log("open_socket: $PeerAddr", 7);
532     return $socket;
536 sub send_msg_hash2address {
537     my ($msg_hash, $address, $encrypt_key) = @_ ;
538     my $msg = &create_xml_string($msg_hash);
539     my $header = @{$msg_hash->{'header'}}[0];
540     &send_msg_to_target($msg, $address, $encrypt_key, $header);
541     
542     return;
546 sub send_msg_to_target {
547     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
548     my $error = 0;
550     if( $msg_header ) {
551         $msg_header = "'$msg_header'-";
552     }
553     else {
554         $msg_header = "";
555     }
557     # encrypt xml msg
558     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
560     # opensocket
561     my $socket = &open_socket($address);
562     if( !$socket ) {
563         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
564         $error++;
565     }
566     
567     if( $error == 0 ) {
568         # send xml msg
569         print $socket $crypted_msg."\n";
571         daemon_log("send ".$msg_header."msg to $address", 1);
572         daemon_log("message:\n$msg", 8);
574     }
576     # close socket in any case
577     if( $socket ) {
578         close $socket;
579     }
581     return;
585 #===  FUNCTION  ================================================================
586 #         NAME:  process_incoming_msg
587 #   PARAMETERS:  crypted_msg - string - incoming crypted message
588 #      RETURNS:  nothing
589 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
590 #===============================================================================
591 sub process_incoming_msg {
592     my ($crypted_msg) = @_;
593     if(not defined $crypted_msg) {
594         daemon_log("function 'process_incoming_msg': got no msg", 7);
595         return;
596     }
597     $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
598     $crypted_msg = $1;
599     my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
601     my $msg;
602     my $msg_hash;
603     my $host_name;
604     my $host_key;
606     # check wether incoming msg is a new msg
607     $host_name = $bus_address;
608     $host_key = $bus_key;
609     daemon_log("process_incoming_msg: host_name: $host_name", 7);
610     daemon_log("process_incoming_msg: host_key: $host_key", 7);
611     eval{
612         $msg = &decrypt_msg($crypted_msg, $host_key);
613         $msg_hash = &transform_msg2hash($msg);
614     };
615     if($@) {
616         daemon_log("process_incoming_msg: deciphering raise error", 7);
617         daemon_log("$@", 8);
618         $msg = undef;
619         $msg_hash = undef;
620         $host_name = undef;
621         $host_key = undef;
622     }
624     # check wether incoming msg is from a bus_known_server
625     if( not defined $msg ) {
626         my $sql_statement= "SELECT * FROM bus_known_server";
627         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
628         while( my ($hit_num, $hit) = each %{ $query_res } ) {
629             $host_name = $hit->{hostname};
630             if( not $host_name =~ "^$host") {
631                 next;
632             }
633             $host_key = $hit->{hostkey};
634             daemon_log("process_incoming_msg: host_name: $host_name", 7);
635             daemon_log("process_incoming_msg: host_key: $host_key", 7);
636             eval{
637                 $msg = &decrypt_msg($crypted_msg, $host_key);
638                 $msg_hash = &transform_msg2hash($msg);
639             };
640             if($@) {
641                 daemon_log("process_incoming_msg: deciphering raise error", 7);
642                 daemon_log("$@", 8);
643                 $msg = undef;
644                 $msg_hash = undef;
645                 $host_name = undef;
646                 $host_key = undef;
647             } else {
648                 last;
649             }
650         }
651     }
653     if( not defined $msg ) {
654         daemon_log("WARNING: bus does not understand the message:", 5);
655         return;
656     }
658     # process incoming msg
659     my $header = @{$msg_hash->{header}}[0];
660     my $source = @{$msg_hash->{source}}[0];
662     daemon_log("header from msg: $header", 1);
663     daemon_log("msg to process:", 5);
664     daemon_log($msg, 5);
666     my @targets = @{$msg_hash->{target}};
667     my $len_targets = @targets;
669     if ($len_targets == 0){
670         daemon_log("ERROR: no target specified for msg $header", 1);
672     } elsif ($len_targets == 1){
673         # we have only one target symbol
674         my $target = $targets[0];
675         daemon_log("msg is for: $target", 7);
677         if($target eq $bus_address) {
678             # msg is for bus
679             if($header eq 'here_i_am'){ &here_i_am($msg_hash)}
680             elsif($header eq 'confirm_new_passwd'){ &confirm_new_passwd($msg_hash)}
681             elsif($header eq 'got_ping') { &got_ping($msg_hash)} 
682             elsif($header eq 'ping') { &ping($msg_hash)}
683             elsif($header eq 'who_has') { &who_has($msg_hash)}
684             elsif($header eq 'new_client') { &new_client($msg_hash)}
685             elsif($header eq 'delete_client') { &delete_client($msg_hash)}
687         } elsif ($target eq "*"){
688             # msg is for all server
689             my $sql_statement= "SELECT * FROM known_server";
690             my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
691             while( my ($hit_num, $hit) = each %{ $query_res } ) {
692                 $host_name = $hit->{hostname};
693                 $host_key = $hit->{hostkey};
694                 $msg_hash->{target} = [$host_name];
695                 &send_msg_hash2address($msg_hash, $host_name, $host_key);
696             }
697             return;
698         }
700     } else {
701         # a list of targets is specified            
702         my $target_address;
703         foreach $target_address (@targets) {
705             my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target_address'";
706             my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
707             if( 1 == keys %{$query_res} ) {
708                 $host_key = $query_res->{1}->{hostkey};
709                 &send_msg_hash2address($msg_hash, $target_address, $host_key);
710                 next;
712             } else { 
713                 my $sql_statement= "SELECT * FROM known_server";
714                 $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
715                 while( my ($hit_num, $hit) = each %{$query_res} ) {
716                     my $host_name = $hit->{hostname};
717                     my $host_key = $hit->{hostkey};
718                     my $clients = $hit->{clients};
719                     my @clients = split(/,/, $clients);
720                     foreach my $client (@clients) {
721                         if( not $client eq $target_address ) {
722                             next;
723                         }
724                         $msg_hash->{target} = [ $target_address ];
725                         &send_msg_hash2address($msg_hash, $host_name, $host_key);
726                         daemon_log("bus forwards msg $header for client $target_address to server $host_name", 3);
727                         last;
728                     }
729                 }
730             }
731         }
732     }
734     return;
739 #===  FUNCTION  ================================================================
740 #         NAME:  create_passwd
741 #   PARAMETERS:  nothing
742 #      RETURNS:  new_passwd - string 
743 #  DESCRIPTION:  creates a 32 bit long random passwd out of "a".."z","A".."Z",0..9
744 #===============================================================================
745 sub create_passwd {
746     my $new_passwd = "";
747     for(my $i=0; $i<31; $i++) {
748         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
749     }
750     return $new_passwd;
760 #===  FUNCTION  ================================================================
761 #         NAME:  read_from_socket
762 #   PARAMETERS:  socket - fh - filehandel to read from  
763 #      RETURNS:  result - string - readed characters from socket
764 #  DESCRIPTION:  reads data from socket in 16 byte steps
765 #===============================================================================
766 sub read_from_socket {
767     my ($socket) = @_;
769     $socket->blocking(1);
770     my $result = <$socket>;
771     $socket->blocking(0);
772     my $part_msg;
773     while ($part_msg = <$socket>) {
774         if (not defined $part_msg) { last; }
775         $result .= $part_msg;
776     }
777     
778     #my $result = "";
779     #my $len = 16;
780     #while($len == 16){
781     #    my $char;
782     #    $len = sysread($socket, $char, 16);
783     #    if($len != 16) { last }
784     #    if($len != 16) { last }
785     #    $result .= $char;
786     #}
787     return $result;
791 #===  FUNCTION  ================================================================
792 #         NAME:  here_i_am
793 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
794 #      RETURNS:  nothing
795 #  DESCRIPTION:  process the incoming msg 'here_i_am'
796 #===============================================================================
797 sub here_i_am {
798     my ($msg_hash) = @_ ;
799     my $source = @{$msg_hash->{source}}[0];;
801     my $new_key = &create_passwd();
803     # create bus_known_server entry
804     my $add_hash = {
805         table=>"bus_known_server",
806         primkey=>"hostname",
807         hostname=>$source,
808         status=>"registered",
809         hostkey=>$bus_key,
810         clients=>"",
811     };
812     $bus_known_server_db->add_dbentry($add_hash);
814     # create outgoing msg
815     my $out_hash = &create_xml_hash("new_key", $bus_address, $source, $new_key);
816     &send_msg_hash2address($out_hash, $source, $bus_key);
818     # change hostkey, reason
819     my $where_str= " WHERE hostname='$source'";
820     my $update_str= " SET hostkey='$new_key'";
821     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
822     $bus_known_server_db->update_dbentry($sql_statement);
824     return;
828 #===  FUNCTION  ================================================================
829 #         NAME:  confirm_new_passwd
830 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
831 #      RETURNS:  nothing
832 #  DESCRIPTION:  process this incoming message
833 #===============================================================================
834 sub confirm_new_passwd {
835     my ($msg_hash) = @_ ;
836     my $source = @{$msg_hash->{source}}[0];
837     my $sql_statement= "UPDATE bus_known_server ".
838         "SET status='key_confirmed' ".
839         "WHERE hostname='$source' ";
841     $bus_known_server_db->update_dbentry($sql_statement);
843     return;
847 #===  FUNCTION  ================================================================
848 #         NAME:  ping
849 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
850 #      RETURNS:  nothing
851 #  DESCRIPTION:  process this incoming message
852 #===============================================================================
853 sub ping {
854     my ($msg_hash) = @_ ;
855     my $header = @{$msg_hash->{header}}[0];
856     my $source = @{$msg_hash->{source}}[0];
858     my $sql_statement= "UPDATE bus_known_server SET status='$header' WHERE hostname='$source'";
859     $bus_known_server_db->update_dbentry($sql_statement);
861     my $out_hash = &create_xml_hash("got_ping", $bus_address, $source);
862     
863     $sql_statement= "SELECT * FROM bus_known_server WHERE hostname='$source'";
864     my $res = $bus_known_server_db->select_dbentry( $sql_statement );
865     my $hostkey = $res->{1}->{hostkey};
866     &send_msg_hash2address($out_hash, $source, $hostkey);
868     return;
872 #===  FUNCTION  ================================================================
873 #         NAME:  got_ping
874 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
875 #      RETURNS:  nothing
876 #  DESCRIPTION:  process this incoming message
877 #===============================================================================
878 sub got_ping {
879     my ($msg_hash) = @_;
880     my $source = @{$msg_hash->{source}}[0];
881     
882     my $sql_statement= "UPDATE bus_known_server SET status='got_ping' WHERE hostname='$source'";
883     $bus_known_server_db->update_dbentry($sql_statement);
885     return;
889 #===  FUNCTION  ================================================================
890 #         NAME:  new_client
891 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
892 #      RETURNS:  nothing
893 #  DESCRIPTION:  process this incoming message
894 #===============================================================================
895 sub new_client {
896     my ($msg_hash) = @_ ;
897     my $source = @{$msg_hash->{source}}[0];
898     my $header = @{$msg_hash->{header}}[0];
899     my $new_client = @{$msg_hash->{$header}}[0];
900  
901     my $sql_statement= "SELECT * FROM bus_known_server WHERE hostname='$source'";
902     my $res = $bus_known_server_db->select_dbentry( $sql_statement );
903     my $clients = $res->{1}->{clients};
905     # if host has alread more clients, than just append
906     my @clients_l = split(',', $clients);
907     my @new_clients_l;
908     foreach my $act_client (@clients_l) {
909         if( $new_client eq $act_client ) {
910             # do nothing
911             next;
912         }
913         push(@new_clients_l, $act_client);
914     }
915     push(@new_clients_l, $new_client);
916     $clients = join(",", @new_clients_l);
917     
918     $sql_statement= "UPDATE bus_known_server SET clients='$clients' WHERE hostname='$source'";
919     $bus_known_server_db->update_dbentry( $sql_statement );
920     return;
924 #==== MAIN = main ==============================================================
926 #  parse commandline options
927 Getopt::Long::Configure( "bundling" );
928 GetOptions("h|help" => \&usage,
929            "c|config=s" => \$cfg_file,
930            "f|foreground" => \$foreground,
931            "v|verbose+" => \$verbose,
932            );
934 #  read and set config parameters
935 &check_cmdline_param ;
936 &read_configfile;
937 &check_pid;
939 $SIG{CHLD} = 'IGNORE';
941 # restart daemon log file
942 if(-e $log_file ) { unlink $log_file }
943 daemon_log(" ", 1);
944 daemon_log("$0 started!", 1);
946 # delete old DBsqlite lock files
947 system('rm -f /tmp/gosa_si_lock*');
949 # forward error messages to logfile
950 if( ! $foreground ) {
951         open(STDERR, '>>', $log_file);
952         open(STDOUT, '>>', $log_file);
955 # Just fork, if we"re not in foreground mode
956 if( ! $foreground ) {
957         chdir '/'                 or die "Can't chdir to /: $!";
958         $pid = fork;
959         setsid                    or die "Can't start a new session: $!";
960         umask 0;
961 } else { 
962     $pid = $$; 
965 # Do something useful - put our PID into the pid_file
966 if( 0 != $pid ) {
967     open( LOCK_FILE, ">$pid_file" );
968     print LOCK_FILE "$pid\n";
969     close( LOCK_FILE );
970     if( ! $foreground ) { exit( 0 ) };
973 # connect to bus_known_server_db
974 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'clients' );
975 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
976 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
979 # detect own ip and mac address
980 $network_interface= &get_interface_for_ip($bus_ip);
981 $bus_mac_address= &get_mac($network_interface);
982 daemon_log("bus ip address detected: $bus_ip", 1);
983 daemon_log("bus mac address detected: $bus_mac_address", 1);
985 # complete addresses
986 $bus_address = "$bus_ip:$bus_port";
988 # setup xml parser
989 $xml = new XML::Simple();
991 # create cipher object
992 $bus_cipher = &create_ciphering($bus_key);
993 $bus_address = "$bus_ip:$bus_port";
995 # create reading and writing vectors
996 my $rbits = my $wbits = my $ebits = "";
998 # open the bus socket
999 if($bus_activ eq "on") {
1000     daemon_log(" ", 1);
1001     $bus = IO::Socket::INET->new(LocalPort => $bus_port,
1002             Type => SOCK_STREAM,
1003             Reuse => 1,
1004             Listen => 20,
1005             ) or die "kann kein TCP-Server an Port $bus_port sein: $@\n";
1006     vec($rbits, fileno $bus, 1) = 1;
1007     vec($wbits, fileno $bus, 1) = 1;
1008     daemon_log ("start bus at $bus_ip:$bus_port", 1);        
1011 # add bus to known_daemons 
1013 #&create_known_daemons_entry($bus_address);
1014 #&update_known_daemons_entry(hostname=>$bus_address, status=>"bus", passwd=>$bus_key);
1017 while(1) {
1018     my $nf = select($rbits, $wbits, undef, undef);
1019     # error handling
1020     if($nf < 0 ) { 
1021     }
1023     # something is coming in 
1024     if(vec $rbits, fileno $bus, 1 ) {
1025         my $client = $bus->accept();
1026         my $other_end = getpeername($client);
1027         if(not defined $other_end) {
1028             daemon_log("Gegenstelle konnte nicht identifiziert werden: $!\n");
1029         } else {
1030             my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1031             my $actual_ip = inet_ntoa($iaddr);
1032             daemon_log("\naccept client from $actual_ip\n", 5);
1033             my $in_msg = &read_from_socket($client);
1034             if(defined $in_msg){
1035                 &activating_child($in_msg, $actual_ip);
1036             } else {
1037                 daemon_log("cannot read from $actual_ip\n",1);
1038             }
1039         }
1040         close($client);        
1041     }