Code

add 'order by' xml-tag to GosaPackages
[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_passwd, $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/bus_known_server.db"]
57     },
58 "bus" =>
59     {"bus_activ" => [\$bus_activ, "on"],
60     "bus_passwd" => [\$bus_passwd, ""],
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 $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     }
511 #===  FUNCTION  ================================================================
512 #         NAME:  process_incoming_msg
513 #   PARAMETERS:  crypted_msg - string - incoming crypted message
514 #      RETURNS:  nothing
515 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
516 #===============================================================================
517 sub process_incoming_msg {
518     my ($crypted_msg) = @_;
519     if(not defined $crypted_msg) {
520         daemon_log("function 'process_incoming_msg': got no msg", 7);
521         return;
522     }
523     $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
524     $crypted_msg = $1;
525     my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
527     my $msg;
528     my $msg_hash;
529     my $host_name;
530     my $host_key;
532     # check wether incoming msg is a new msg
533     $host_name = $bus_address;
534     $host_key = $bus_passwd;
535     daemon_log("process_incoming_msg: host_name: $host_name", 7);
536     daemon_log("process_incoming_msg: host_key: $host_key", 7);
537     eval{
538         my $key_cipher = &create_ciphering($host_key);
539         $msg = &decrypt_msg($crypted_msg, $key_cipher);
540         $msg_hash = &transform_msg2hash($msg);
541     };
542     if($@) {
543         daemon_log("process_incoming_msg: deciphering raise error", 7);
544         daemon_log("$@", 8);
545         $msg = undef;
546         $msg_hash = undef;
547         $host_name = undef;
548         $host_key = undef;
549     }
551     # check wether incoming msg is from a bus_known_server
552     if( not defined $msg ) {
553         my $sql_statement= "SELECT * FROM bus_known_server";
554         my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
555         while( my ($hit_num, $hit) = each %{ $query_res } ) {
556             $host_name = $hit->{hostname};
557             if( not $host_name =~ "^$host") {
558                 next;
559             }
560             $host_key = $hit->{hostkey};
561             daemon_log("process_incoming_msg: host_name: $host_name", 7);
562             daemon_log("process_incoming_msg: host_key: $host_key", 7);
563             eval{
564                 my $key_cipher = &create_ciphering($host_key);
565                 $msg = &decrypt_msg($crypted_msg, $key_cipher);
566                 $msg_hash = &transform_msg2hash($msg);
567             };
568             if($@) {
569                 daemon_log("process_incoming_msg: deciphering raise error", 7);
570                 daemon_log("$@", 8);
571                 $msg = undef;
572                 $msg_hash = undef;
573                 $host_name = undef;
574                 $host_key = undef;
575             } else {
576                 last;
577             }
578         }
579     }
581     if( not defined $msg ) {
582         daemon_log("WARNING: bus does not understand the message:", 5);
583         return;
584     }
586     # process incoming msg
587     my $header = @{$msg_hash->{header}}[0];
588     my $source = @{$msg_hash->{source}}[0];
590     daemon_log("header from msg: $header", 1);
591     daemon_log("msg to process:", 5);
592     daemon_log($msg, 5);
594     my @targets = @{$msg_hash->{target}};
595     my $len_targets = @targets;
597     if ($len_targets == 0){
598         daemon_log("ERROR: no target specified for msg $header", 1);
600     } elsif ($len_targets == 1){
601         # we have only one target symbol
602         my $target = $targets[0];
603         daemon_log("msg is for: $target", 7);
605         if($target eq $bus_address) {
606             # msg is for bus
607             if($header eq 'here_i_am'){ &here_i_am($msg_hash)}
608             elsif($header eq 'confirm_new_passwd'){ &confirm_new_passwd($msg_hash)}
609             elsif($header eq 'got_ping') { &got_ping($msg_hash)} 
610             elsif($header eq 'ping') { &ping($msg_hash)}
611             elsif($header eq 'who_has') { &who_has($msg_hash)}
612             elsif($header eq 'new_client') { &new_client($msg_hash)}
613             elsif($header eq 'delete_client') { &delete_client($msg_hash)}
615         } elsif ($target eq "*"){
616             # msg is for all server
617             my $sql_statement= "SELECT * FROM known_server";
618             my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
619             while( my ($hit_num, $hit) = each %{ $query_res } ) {
620                 $host_name = $hit->{hostname};
621                 $host_key = $hit->{hostkey};
622                 $msg_hash->{target} = [$host_name];
623                 &send_msg_hash2address($msg_hash, $host_name, $host_key);
624             }
625             return;
626         }
628     } else {
629         # a list of targets is specified            
630         my $target_address;
631         foreach $target_address (@targets) {
633             my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target_address'";
634             my $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
635             if( 1 == keys %{$query_res} ) {
636                 $host_key = $query_res->{1}->{hostkey};
637                 &send_msg_hash2address($msg_hash, $target_address, $host_key);
638                 next;
640             } else { 
641                 my $sql_statement= "SELECT * FROM known_server";
642                 $query_res = $bus_known_server_db->select_dbentry( $sql_statement );
643                 while( my ($hit_num, $hit) = each %{$query_res} ) {
644                     my $host_name = $hit->{hostname};
645                     my $host_key = $hit->{hostkey};
646                     my $clients = $hit->{clients};
647                     my @clients = split(/,/, $clients);
648                     foreach my $client (@clients) {
649                         if( not $client eq $target_address ) {
650                             next;
651                         }
652                         $msg_hash->{target} = [ $target_address ];
653                         &send_msg_hash2address($msg_hash, $host_name, $host_key);
654                         daemon_log("bus forwards msg $header for client $target_address to server $host_name", 3);
655                         last;
656                     }
657                 }
658             }
659         }
660     }
662     return;
667 #===  FUNCTION  ================================================================
668 #         NAME:  create_passwd
669 #   PARAMETERS:  nothing
670 #      RETURNS:  new_passwd - string 
671 #  DESCRIPTION:  creates a 32 bit long random passwd out of "a".."z","A".."Z",0..9
672 #===============================================================================
673 sub create_passwd {
674     my $new_passwd = "";
675     for(my $i=0; $i<31; $i++) {
676         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
677     }
678     return $new_passwd;
682 #===  FUNCTION  ================================================================
683 #         NAME:  read_from_socket
684 #   PARAMETERS:  socket - fh - filehandel to read from  
685 #      RETURNS:  result - string - readed characters from socket
686 #  DESCRIPTION:  reads data from socket in 16 byte steps
687 #===============================================================================
688 sub read_from_socket {
689     my ($socket) = @_;
691     $socket->blocking(1);
692     my $result = <$socket>;
693     $socket->blocking(0);
694     my $part_msg;
695     while ($part_msg = <$socket>) {
696         if (not defined $part_msg) { last; }
697         $result .= $part_msg;
698     }
699     
700     #my $result = "";
701     #my $len = 16;
702     #while($len == 16){
703     #    my $char;
704     #    $len = sysread($socket, $char, 16);
705     #    if($len != 16) { last }
706     #    if($len != 16) { last }
707     #    $result .= $char;
708     #}
709     return $result;
713 #===  FUNCTION  ================================================================
714 #         NAME:  here_i_am
715 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
716 #      RETURNS:  nothing
717 #  DESCRIPTION:  process the incoming msg 'here_i_am'
718 #===============================================================================
719 sub here_i_am {
720     my ($msg_hash) = @_ ;
721     my $source = @{$msg_hash->{source}}[0];;
723     my $new_key = &create_passwd();
725     # create bus_known_server entry
726     my $add_hash = {
727         table=>"bus_known_server",
728         primkey=>"hostname",
729         hostname=>$source,
730         status=>"registered",
731         hostkey=>$bus_passwd,
732         clients=>"",
733     };
734     $bus_known_server_db->add_dbentry($add_hash);
736     # create outgoing msg
737     my $out_hash = &create_xml_hash("new_passwd", $bus_address, $source, $new_key);
738     &send_msg_hash2address($out_hash, $source, $bus_passwd);
740     # change hostkey, reason
741     my $where_str= " WHERE hostname='$source'";
742     my $update_str= " SET hostkey='$new_key'";
743     my $sql_statement= "UPDATE bus_known_server $update_str $where_str";
744     $bus_known_server_db->update_dbentry($sql_statement);
746     return;
750 #===  FUNCTION  ================================================================
751 #         NAME:  confirm_new_passwd
752 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
753 #      RETURNS:  nothing
754 #  DESCRIPTION:  process this incoming message
755 #===============================================================================
756 sub confirm_new_passwd {
757     my ($msg_hash) = @_ ;
758     my $source = @{$msg_hash->{source}}[0];
759     my $sql_statement= "UPDATE bus_known_server ".
760         "SET status='key_confirmed' ".
761         "WHERE hostname='$source' ";
763     $bus_known_server_db->update_dbentry($sql_statement);
765     return;
769 #===  FUNCTION  ================================================================
770 #         NAME:  ping
771 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
772 #      RETURNS:  nothing
773 #  DESCRIPTION:  process this incoming message
774 #===============================================================================
775 sub ping {
776     my ($msg_hash) = @_ ;
777     my $header = @{$msg_hash->{header}}[0];
778     my $source = @{$msg_hash->{source}}[0];
780     my $sql_statement= "UPDATE bus_known_server SET status='$header' WHERE hostname='$source'";
781     $bus_known_server_db->update_dbentry($sql_statement);
783     my $out_hash = &create_xml_hash("got_ping", $bus_address, $source);
784     
785     $sql_statement= "SELECT * FROM bus_known_server WHERE hostname='$source'";
786     my $res = $bus_known_server_db->select_dbentry( $sql_statement );
787     my $hostkey = $res->{1}->{hostkey};
788     &send_msg_hash2address($out_hash, $source, $hostkey);
790     return;
794 #===  FUNCTION  ================================================================
795 #         NAME:  got_ping
796 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
797 #      RETURNS:  nothing
798 #  DESCRIPTION:  process this incoming message
799 #===============================================================================
800 sub got_ping {
801     my ($msg_hash) = @_;
802     my $source = @{$msg_hash->{source}}[0];
803     
804     my $sql_statement= "UPDATE bus_known_server SET status='got_ping' WHERE hostname='$source'";
805     $bus_known_server_db->update_dbentry($sql_statement);
807     return;
811 #===  FUNCTION  ================================================================
812 #         NAME:  new_client
813 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
814 #      RETURNS:  nothing
815 #  DESCRIPTION:  process this incoming message
816 #===============================================================================
817 sub new_client {
818     my ($msg_hash) = @_ ;
819     my $source = @{$msg_hash->{source}}[0];
820     my $header = @{$msg_hash->{header}}[0];
821     my $new_client = @{$msg_hash->{$header}}[0];
822  
823     my $sql_statement= "SELECT * FROM bus_known_server WHERE hostname='$source'";
824     my $res = $bus_known_server_db->select_dbentry( $sql_statement );
825     my $clients = $res->{1}->{clients};
827     # if host has alread more clients, than just append
828     if( length($clients) != 0 ) {
829         $clients .= ",$new_client";
830     } else {
831         $clients = $new_client;
832     }
834     $sql_statement= "UPDATE bus_known_server SET clients='$clients' WHERE hostname='$source'";
835     $bus_known_server_db->update_dbentry( $sql_statement );
836     return;
840 #==== MAIN = main ==============================================================
842 #  parse commandline options
843 Getopt::Long::Configure( "bundling" );
844 GetOptions("h|help" => \&usage,
845            "c|config=s" => \$cfg_file,
846            "f|foreground" => \$foreground,
847            "v|verbose+" => \$verbose,
848            );
850 #  read and set config parameters
851 &check_cmdline_param ;
852 &read_configfile;
853 &check_pid;
855 $SIG{CHLD} = 'IGNORE';
857 # restart daemon log file
858 if(-e $log_file ) { unlink $log_file }
859 daemon_log(" ", 1);
860 daemon_log("$0 started!", 1);
862 # delete old DBsqlite lock files
863 system('rm -f /tmp/gosa_si_lock*');
865 # forward error messages to logfile
866 if( ! $foreground ) {
867         open(STDERR, '>>', $log_file);
868         open(STDOUT, '>>', $log_file);
871 # Just fork, if we"re not in foreground mode
872 if( ! $foreground ) {
873         chdir '/'                 or die "Can't chdir to /: $!";
874         $pid = fork;
875         setsid                    or die "Can't start a new session: $!";
876         umask 0;
877 } else { 
878     $pid = $$; 
881 # Do something useful - put our PID into the pid_file
882 if( 0 != $pid ) {
883     open( LOCK_FILE, ">$pid_file" );
884     print LOCK_FILE "$pid\n";
885     close( LOCK_FILE );
886     if( ! $foreground ) { exit( 0 ) };
889 # connect to bus_known_server_db
890 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'clients' );
891 $bus_known_server_db = GOSA::DBsqlite->new($bus_known_server_file_name);
892 $bus_known_server_db->create_table('bus_known_server', \@server_col_names);
895 # detect own ip and mac address
896 $network_interface= &get_interface_for_ip($bus_ip);
897 $bus_mac_address= &get_mac($network_interface);
898 daemon_log("bus ip address detected: $bus_ip", 1);
899 daemon_log("bus mac address detected: $bus_mac_address", 1);
901 # complete addresses
902 $bus_address = "$bus_ip:$bus_port";
904 # setup xml parser
905 $xml = new XML::Simple();
907 # create cipher object
908 $bus_cipher = &create_ciphering($bus_passwd);
909 $bus_address = "$bus_ip:$bus_port";
911 # create reading and writing vectors
912 my $rbits = my $wbits = my $ebits = "";
914 # open the bus socket
915 if($bus_activ eq "on") {
916     daemon_log(" ", 1);
917     $bus = IO::Socket::INET->new(LocalPort => $bus_port,
918             Type => SOCK_STREAM,
919             Reuse => 1,
920             Listen => 20,
921             ) or die "kann kein TCP-Server an Port $bus_port sein: $@\n";
922     vec($rbits, fileno $bus, 1) = 1;
923     vec($wbits, fileno $bus, 1) = 1;
924     daemon_log ("start bus at $bus_ip:$bus_port", 1);        
927 # add bus to known_daemons 
929 #&create_known_daemons_entry($bus_address);
930 #&update_known_daemons_entry(hostname=>$bus_address, status=>"bus", passwd=>$bus_passwd);
933 while(1) {
934     my $nf = select($rbits, $wbits, undef, undef);
935     # error handling
936     if($nf < 0 ) { 
937     }
939     # something is coming in 
940     if(vec $rbits, fileno $bus, 1 ) {
941         my $client = $bus->accept();
942         my $other_end = getpeername($client);
943         if(not defined $other_end) {
944             daemon_log("Gegenstelle konnte nicht identifiziert werden: $!\n");
945         } else {
946             my ($port, $iaddr) = unpack_sockaddr_in($other_end);
947             my $actual_ip = inet_ntoa($iaddr);
948             daemon_log("\naccept client from $actual_ip\n", 5);
949             my $in_msg = &read_from_socket($client);
950             if(defined $in_msg){
951                 &activating_child($in_msg, $actual_ip);
952             } else {
953                 daemon_log("cannot read from $actual_ip\n",1);
954             }
955         }
956         close($client);        
957     }