Code

Code killing
[gosa.git] / gosa-si / gosa-si-server
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 #         FILE:  gosa-sd
5 #
6 #        USAGE:  ./gosa-sd
7 #
8 #  DESCRIPTION:
9 #
10 #      OPTIONS:  ---
11 # REQUIREMENTS:  libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl 
12 #                libdata-dumper-simple-perl libdbd-sqlite3-perl libnet-ldap-perl
13 #                libpoe-perl
14 #         BUGS:  ---
15 #        NOTES:
16 #       AUTHOR:   (Andreas Rettenberger), <rettenberger@gonicus.de>
17 #      COMPANY:
18 #      VERSION:  1.0
19 #      CREATED:  12.09.2007 08:54:41 CEST
20 #     REVISION:  ---
21 #===============================================================================
23 use strict;
24 use warnings;
25 use Getopt::Long;
26 use Config::IniFiles;
27 use POSIX;
28 use utf8;
30 use Fcntl;
31 use IO::Socket::INET;
32 use IO::Handle;
33 use IO::Select;
34 use Symbol qw(qualify_to_ref);
35 use Crypt::Rijndael;
36 use MIME::Base64;
37 use Digest::MD5  qw(md5 md5_hex md5_base64);
38 use XML::Simple;
39 use Data::Dumper;
40 use Sys::Syslog qw( :DEFAULT setlogsock);
41 use Cwd;
42 use File::Spec;
43 use File::Basename;
44 use GOSA::DBsqlite;
45 use GOSA::GosaSupportDaemon;
46 use POE qw(Component::Server::TCP);
48 my $modules_path = "/usr/lib/gosa-si/modules";
49 use lib "/usr/lib/gosa-si/modules";
51 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
52 my ($bus_activ, $bus, $msg_to_bus, $bus_cipher);
53 my ($server, $server_mac_address);
54 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
55 my ($known_modules, $known_clients_file_name, $known_server_file_name);
56 my ($pid_file, $procid, $pid, $log_file);
57 my ($arp_activ, $arp_fifo);
58 my ($xml);
60 # variables declared in config file are always set to 'our'
61 our (%cfg_defaults, $log_file, $pid_file, 
62     $server_ip, $server_port, $SIPackages_key, 
63     $arp_activ, $gosa_unit_tag,
64     $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
65 );
67 # additional variable which should be globaly accessable
68 our $server_address;
69 our $bus_address;
70 our $gosa_address;
71 our $no_bus;
72 our $no_arp;
73 our $verbose;
74 our $forground;
75 our $cfg_file;
77 # specifies the verbosity of the daemon_log
78 $verbose = 0 ;
80 # if foreground is not null, script will be not forked to background
81 $foreground = 0 ;
83 # specifies the timeout seconds while checking the online status of a registrating client
84 $ping_timeout = 5;
86 $no_bus = 0;
87 $bus_activ = "true";
89 $no_arp = 0;
91 # holds all gosa jobs
92 our $job_db;
93 our $job_queue_table_name = 'jobs';
95 # holds all other gosa-sd as well as the gosa-sd-bus
96 our $known_server_db;
98 # holds all registrated clients
99 our $known_clients_db;
100 our $prg= basename($0);
102 %cfg_defaults = (
103 "general" => {
104     "log-file" => [\$log_file, "/var/run/".$prg.".log"],
105     "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
106     },
107 "bus" => {
108     "activ" => [\$bus_activ, "true"],
109     },
110 "server" => {
111 #    "ip" => [\$server_ip, "0.0.0.0"],  
112     "port" => [\$server_port, "20081"],
113     "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
114     "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
115         "gosa-unit-tag" => [\$gosa_unit_tag, ""],
116     },
117 "GOsaPackages" => {
118     "ip" => [\$gosa_ip, "0.0.0.0"],
119     "port" => [\$gosa_port, "20082"],
120     "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
121     "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
122     "key" => [\$GosaPackages_key, "none"],
123     },
124 "SIPackages" => {
125     "key" => [\$SIPackages_key, "none"],
126     },
127 );
130 #===  FUNCTION  ================================================================
131 #         NAME:  usage
132 #   PARAMETERS:  nothing
133 #      RETURNS:  nothing
134 #  DESCRIPTION:  print out usage text to STDERR
135 #===============================================================================
136 sub usage {
137     print STDERR << "EOF" ;
138 usage: $prg [-hvf] [-c config]
140            -h        : this (help) message
141            -c <file> : config file
142            -f        : foreground, process will not be forked to background
143            -v        : be verbose (multiple to increase verbosity)
144            -no-bus   : starts $prg without connection to bus
145            -no-arp   : starts $prg without connection to arp module
146  
147 EOF
148     print "\n" ;
152 #===  FUNCTION  ================================================================
153 #         NAME:  read_configfile
154 #   PARAMETERS:  cfg_file - string -
155 #      RETURNS:  nothing
156 #  DESCRIPTION:  read cfg_file and set variables
157 #===============================================================================
158 sub read_configfile {
159     my $cfg;
160     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
161         if( -r $cfg_file ) {
162             $cfg = Config::IniFiles->new( -file => $cfg_file );
163         } else {
164             print STDERR "Couldn't read config file!\n";
165         }
166     } else {
167         $cfg = Config::IniFiles->new() ;
168     }
169     foreach my $section (keys %cfg_defaults) {
170         foreach my $param (keys %{$cfg_defaults{ $section }}) {
171             my $pinfo = $cfg_defaults{ $section }{ $param };
172             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
173         }
174     }
178 #===  FUNCTION  ================================================================
179 #         NAME:  logging
180 #   PARAMETERS:  level - string - default 'info'
181 #                msg - string -
182 #                facility - string - default 'LOG_DAEMON'
183 #      RETURNS:  nothing
184 #  DESCRIPTION:  function for logging
185 #===============================================================================
186 sub daemon_log {
187     # log into log_file
188     my( $msg, $level ) = @_;
189     if(not defined $msg) { return }
190     if(not defined $level) { $level = 1 }
191     if(defined $log_file){
192         open(LOG_HANDLE, ">>$log_file");
193         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
194             print STDERR "cannot open $log_file: $!";
195             return }
196             chomp($msg);
197             if($level <= $verbose){
198                 my ($seconds, $minutes, $hours, $monthday, $month,
199                         $year, $weekday, $yearday, $sommertime) = localtime(time);
200                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
201                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
202                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
203                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
204                 $month = $monthnames[$month];
205                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
206                 $year+=1900;
207                 my $name = $prg;
209                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
210                 print LOG_HANDLE $log_msg;
211                 if( $foreground ) { 
212                     print STDERR $log_msg;
213                 }
214             }
215         close( LOG_HANDLE );
216     }
220 #===  FUNCTION  ================================================================
221 #         NAME:  check_cmdline_param
222 #   PARAMETERS:  nothing
223 #      RETURNS:  nothing
224 #  DESCRIPTION:  validates commandline parameter
225 #===============================================================================
226 sub check_cmdline_param () {
227     my $err_config;
228     my $err_counter = 0;
229         if(not defined($cfg_file)) {
230                 $cfg_file = "/etc/gosa-si/server.conf";
231                 if(! -r $cfg_file) {
232                         $err_config = "please specify a config file";
233                         $err_counter += 1;
234                 }
235     }
236     if( $err_counter > 0 ) {
237         &usage( "", 1 );
238         if( defined( $err_config)) { print STDERR "$err_config\n"}
239         print STDERR "\n";
240         exit( -1 );
241     }
245 #===  FUNCTION  ================================================================
246 #         NAME:  check_pid
247 #   PARAMETERS:  nothing
248 #      RETURNS:  nothing
249 #  DESCRIPTION:  handels pid processing
250 #===============================================================================
251 sub check_pid {
252     $pid = -1;
253     # Check, if we are already running
254     if( open(LOCK_FILE, "<$pid_file") ) {
255         $pid = <LOCK_FILE>;
256         if( defined $pid ) {
257             chomp( $pid );
258             if( -f "/proc/$pid/stat" ) {
259                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
260                 if( $0 eq $stat ) {
261                     close( LOCK_FILE );
262                     exit -1;
263                 }
264             }
265         }
266         close( LOCK_FILE );
267         unlink( $pid_file );
268     }
270     # create a syslog msg if it is not to possible to open PID file
271     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
272         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
273         if (open(LOCK_FILE, '<', $pid_file)
274                 && ($pid = <LOCK_FILE>))
275         {
276             chomp($pid);
277             $msg .= "(PID $pid)\n";
278         } else {
279             $msg .= "(unable to read PID)\n";
280         }
281         if( ! ($foreground) ) {
282             openlog( $0, "cons,pid", "daemon" );
283             syslog( "warning", $msg );
284             closelog();
285         }
286         else {
287             print( STDERR " $msg " );
288         }
289         exit( -1 );
290     }
293 #===  FUNCTION  ================================================================
294 #         NAME:  import_modules
295 #   PARAMETERS:  module_path - string - abs. path to the directory the modules 
296 #                are stored
297 #      RETURNS:  nothing
298 #  DESCRIPTION:  each file in module_path which ends with '.pm' and activation 
299 #                state is on is imported by "require 'file';"
300 #===============================================================================
301 sub import_modules {
302     daemon_log(" ", 1);
304     if (not -e $modules_path) {
305         daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);   
306     }
308     opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
309     while (defined (my $file = readdir (DIR))) {
310         if (not $file =~ /(\S*?).pm$/) {
311             next;
312         }
313                 my $mod_name = $1;
315         if( $file =~ /ArpHandler.pm/ ) {
316             if( $no_arp > 0 ) {
317                 next;
318             }
319         }
320         
321         eval { require $file; };
322         if ($@) {
323             daemon_log("ERROR: gosa-si-server could not load module $file", 1);
324             daemon_log("$@", 5);
325                 } else {
326                         my $info = eval($mod_name.'::get_module_info()');
327                         # Only load module if get_module_info() returns a non-null object
328                         if( $info ) {
329                                 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
330                                 $known_modules->{$mod_name} = $info;
331                                 daemon_log("INFO: module $mod_name loaded", 5);
332                         }
333                 }
334     }   
335     close (DIR);
339 #===  FUNCTION  ================================================================
340 #         NAME:  sig_int_handler
341 #   PARAMETERS:  signal - string - signal arose from system
342 #      RETURNS:  noting
343 #  DESCRIPTION:  handels tasks to be done befor signal becomes active
344 #===============================================================================
345 sub sig_int_handler {
346     my ($signal) = @_;
348     daemon_log("shutting down gosa-si-server", 1);
349     exit(1);
351 $SIG{INT} = \&sig_int_handler;
355 sub check_key_and_xml_validity {
356     my ($crypted_msg, $module_key) = @_;
357     my $msg;
358     my $msg_hash;
359     my $error_string;
360     eval{
361         $msg = &decrypt_msg($crypted_msg, $module_key);
363         if ($msg =~ /<xml>/i){
364             &main::daemon_log("decrypted_msg: \n$msg", 8);
365             $msg_hash = $xml->XMLin($msg, ForceArray=>1);
367             ##############
368             # check header
369             if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
370             my $header_l = $msg_hash->{'header'};
371             if( 1 > @{$header_l} ) { die 'empty header tag'; }
372             if( 1 < @{$header_l} ) { die 'more than one header specified'; }
373             my $header = @{$header_l}[0];
374             if( 0 == length $header) { die 'empty string in header tag'; }
376             ##############
377             # check source
378             if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
379             my $source_l = $msg_hash->{'source'};
380             if( 1 > @{$source_l} ) { die 'empty source tag'; }
381             if( 1 < @{$source_l} ) { die 'more than one source specified'; }
382             my $source = @{$source_l}[0];
383             if( 0 == length $source) { die 'source error'; }
385             ##############
386             # check target
387             if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
388             my $target_l = $msg_hash->{'target'};
389             if( 1 > @{$target_l} ) { die 'empty target tag'; }
390         }
391     };
392     if($@) {
393         &main::daemon_log("WARNING: do not understand the message", 5);
394         &main::daemon_log("$@", 8);
395         $msg = undef;
396         $msg_hash = undef;
397     }
399     return ($msg, $msg_hash);
403 sub check_outgoing_xml_validity {
404     my ($msg) = @_;
406     my $msg_hash;
407     eval{
408         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
410         ##############
411         # check header
412         my $header_l = $msg_hash->{'header'};
413         if( 1 != @{$header_l} ) {
414             die 'no or more than one headers specified';
415         }
416         my $header = @{$header_l}[0];
417         if( 0 == length $header) {
418             die 'header has length 0';
419         }
421         ##############
422         # check source
423         my $source_l = $msg_hash->{'source'};
424         if( 1 != @{$source_l} ) {
425             die 'no or more than 1 sources specified';
426         }
427         my $source = @{$source_l}[0];
428         if( 0 == length $source) {
429             die 'source has length 0';
430         }
431         unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
432                 $source =~ /^GOSA$/i ) {
433             die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
434         }
435         
436         ##############
437         # check target  
438         my $target_l = $msg_hash->{'target'};
439         if( 0 == @{$target_l} ) {
440             die "no targets specified";
441         }
442         foreach my $target (@$target_l) {
443             if( 0 == length $target) {
444                 die "target has length 0";
445             }
446             unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
447                     $target =~ /^GOSA$/i ||
448                     $target =~ /^\*$/ ||
449                     $target =~ /KNOWN_SERVER/i ||
450                     $target =~ /JOBDB/i ||
451                     $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})$/i ){
452                 die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
453             }
454         }
455     };
456     if($@) {
457         daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
458         daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 8);
459         $msg_hash = undef;
460     }
462     return ($msg_hash);
466 sub input_from_known_server {
467     my ($input, $remote_ip) = @_ ;  
468     my ($msg, $msg_hash, $module);
470     my $sql_statement= "SELECT * FROM known_server";
471     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
473     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
474         my $host_name = $hit->{hostname};
475         if( not $host_name =~ "^$remote_ip") {
476             next;
477         }
478         my $host_key = $hit->{hostkey};
479         daemon_log("DEBUG: input_from_known_server: host_name: $host_name", 7);
480         daemon_log("DEBUG: input_from_known_server: host_key: $host_key", 7);
482         # check if module can open msg envelope with module key
483         my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
484         if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
485             daemon_log("DEBUG: input_from_known_server: deciphering raise error", 7);
486             daemon_log("$@", 8);
487             next;
488         }
489         else {
490             $msg = $tmp_msg;
491             $msg_hash = $tmp_msg_hash;
492             $module = "SIPackages";
493             last;
494         }
495     }
497     if( (!$msg) || (!$msg_hash) || (!$module) ) {
498         daemon_log("INFO: Incoming message is not from a known server", 5);
499     }
500   
501     return ($msg, $msg_hash, $module);
505 sub input_from_known_client {
506     my ($input, $remote_ip) = @_ ;  
507     my ($msg, $msg_hash, $module);
509     my $sql_statement= "SELECT * FROM known_clients";
510     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
511     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
512         my $host_name = $hit->{hostname};
513         if( not $host_name =~ /^$remote_ip:\d*$/) {
514                 next;
515                 }
516         my $host_key = $hit->{hostkey};
517         &daemon_log("DEBUG: input_from_known_client: host_name: $host_name", 7);
518         &daemon_log("DEBUG: input_from_known_client: host_key: $host_key", 7);
520         # check if module can open msg envelope with module key
521         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
523         if( (!$msg) || (!$msg_hash) ) {
524             &daemon_log("DEGUG: input_from_known_client: deciphering raise error", 7);
525             &daemon_log("$@", 8);
526             next;
527         }
528         else {
529             $module = "SIPackages";
530             last;
531         }
532     }
534     if( (!$msg) || (!$msg_hash) || (!$module) ) {
535         &daemon_log("INFO: Incoming message is not from a known client", 5);
536     }
538     return ($msg, $msg_hash, $module);
542 sub input_from_unknown_host {
543     no strict "refs";
544     my ($input) = @_ ;
545     my ($msg, $msg_hash, $module);
546     my $error_string;
547     
548         my %act_modules = %$known_modules;
550         while( my ($mod, $info) = each(%act_modules)) {
552         # check a key exists for this module
553         my $module_key = ${$mod."_key"};
554         if( not defined $module_key ) {
555             if( $mod eq 'ArpHandler' ) {
556                 next;
557             }
558             daemon_log("ERROR: no key specified in config file for $mod", 1);
559             next;
560         }
561         daemon_log("DEBUG: $mod: $module_key", 7);
563         # check if module can open msg envelope with module key
564         ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
565         if( (not defined $msg) || (not defined $msg_hash) ) {
566             next;
567         }
568         else {
569             $module = $mod;
570             last;
571         }
572     }
574     if( (!$msg) || (!$msg_hash) || (!$module)) {
575         daemon_log("INFO: Incoming message is not from an unknown host", 5);
576     }
578     return ($msg, $msg_hash, $module);
582 sub create_ciphering {
583     my ($passwd) = @_;
584         if((!defined($passwd)) || length($passwd)==0) {
585                 $passwd = "";
586         }
587     $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
588     my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
589     my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
590     $my_cipher->set_iv($iv);
591     return $my_cipher;
595 sub encrypt_msg {
596     my ($msg, $key) = @_;
597     my $my_cipher = &create_ciphering($key);
598     my $len;
599     {
600             use bytes;
601             $len= 16-length($msg)%16;
602     }
603     $msg = "\0"x($len).$msg;
604     $msg = $my_cipher->encrypt($msg);
605     chomp($msg = &encode_base64($msg));
606     # there are no newlines allowed inside msg
607     $msg=~ s/\n//g;
608     return $msg;
612 sub decrypt_msg {
614     my ($msg, $key) = @_ ;
615     $msg = &decode_base64($msg);
616     my $my_cipher = &create_ciphering($key);
617     $msg = $my_cipher->decrypt($msg); 
618     $msg =~ s/\0*//g;
619     return $msg;
623 sub get_encrypt_key {
624     my ($target) = @_ ;
625     my $encrypt_key;
626     my $error = 0;
628     # target can be in known_server
629     if( not defined $encrypt_key ) {
630         my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
631         my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
632         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
633             my $host_name = $hit->{hostname};
634             if( $host_name ne $target ) {
635                 next;
636             }
637             $encrypt_key = $hit->{hostkey};
638             last;
639         }
640     }
642     # target can be in known_client
643     if( not defined $encrypt_key ) {
644         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
645         my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
646         while( my ($hit_num, $hit) = each %{ $query_res } ) {    
647             my $host_name = $hit->{hostname};
648             if( $host_name ne $target ) {
649                 next;
650             }
651             $encrypt_key = $hit->{hostkey};
652             last;
653         }
654     }
656     return $encrypt_key;
660 #===  FUNCTION  ================================================================
661 #         NAME:  open_socket
662 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
663 #                [PeerPort] string necessary if port not appended by PeerAddr
664 #      RETURNS:  socket IO::Socket::INET
665 #  DESCRIPTION:  open a socket to PeerAddr
666 #===============================================================================
667 sub open_socket {
668     my ($PeerAddr, $PeerPort) = @_ ;
669     if(defined($PeerPort)){
670         $PeerAddr = $PeerAddr.":".$PeerPort;
671     }
672     my $socket;
673     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
674             Porto => "tcp",
675             Type => SOCK_STREAM,
676             Timeout => 5,
677             );
678     if(not defined $socket) {
679         return;
680     }
681 #    &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
682     return $socket;
686 #===  FUNCTION  ================================================================
687 #         NAME:  get_ip 
688 #   PARAMETERS:  interface name (i.e. eth0)
689 #      RETURNS:  (ip address) 
690 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
691 #===============================================================================
692 sub get_ip {
693         my $ifreq= shift;
694         my $result= "";
695         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
696         my $proto= getprotobyname('ip');
698         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
699                 or die "socket: $!";
701         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
702                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
703                 my ($port, $addr) = sockaddr_in $sin;
704                 my $ip            = inet_ntoa $addr;
706                 if ($ip && length($ip) > 0) {
707                         $result = $ip;
708                 }
709         }
711         return $result;
714 sub get_local_ip_for_remote_ip {
715         my $remote_ip= shift;
716         my $result="0.0.0.0";
718         if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
719                 if($remote_ip eq "127.0.0.1") {
720                         $result = "127.0.0.1";
721                 } else {
722                         my $PROC_NET_ROUTE= ('/proc/net/route');
724                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
725                                 or die "Could not open $PROC_NET_ROUTE";
727                         my @ifs = <PROC_NET_ROUTE>;
729                         close(PROC_NET_ROUTE);
731                         # Eat header line
732                         shift @ifs;
733                         chomp @ifs;
734                         foreach my $line(@ifs) {
735                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
736                                 my $destination;
737                                 my $mask;
738                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
739                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
740                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
741                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
742                                 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
743                                         # destination matches route, save mac and exit
744                                         $result= &get_ip($Iface);
745                                         last;
746                                 }
747                         }
748                 }
749         } else {
750                 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
751         }
752         return $result;
755 sub send_msg_to_target {
756     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
757     my $error = 0;
758     my $header;
759     my $new_status;
760     my $act_status;
761     my ($sql_statement, $res);
762   
763     if( $msg_header ) {
764         $header = "'$msg_header'-";
765     }
766     else {
767         $header = "";
768     }
770         # Patch the source ip
771         if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
772                 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
773                 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
774         }
776     # encrypt xml msg
777     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
779     # opensocket
780     my $socket = &open_socket($address);
781     if( !$socket ) {
782         daemon_log("ERROR: cannot send ".$header."msg to $address , host not reachable", 1);
783         $error++;
784     }
785     
786     if( $error == 0 ) {
787         # send xml msg
788         print $socket $crypted_msg."\n";
790         daemon_log("INFO: send ".$header."msg to $address", 5);
791         daemon_log("message:\n$msg", 8);
792         
793     }
795     # close socket in any case
796     if( $socket ) {
797         close $socket;
798     }
800     if( $error > 0 ) { $new_status = "down"; }
801     else { $new_status = $msg_header; }
804     # known_clients
805     $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
806     $res = $known_clients_db->select_dbentry($sql_statement);
807     if( keys(%$res) > 0) {
808         $act_status = $res->{1}->{'status'};
809         if( $act_status eq "down" ) {
810             $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
811             $res = $known_clients_db->del_dbentry($sql_statement);
812             daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
813         } 
814         else { 
815             $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
816             $res = $known_clients_db->update_dbentry($sql_statement);
817             if($new_status eq "down"){
818                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
819             }
820             else {
821                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
822             }
823         }
824     }
826     # known_server
827     $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
828     $res = $known_server_db->select_dbentry($sql_statement);
829     if( keys(%$res) > 0 ) {
830         $act_status = $res->{1}->{'status'};
831         if( $act_status eq "down" ) {
832             $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
833             $res = $known_server_db->del_dbentry($sql_statement);
834             daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
835         } 
836         else { 
837             $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
838             $res = $known_server_db->update_dbentry($sql_statement);
839             if($new_status eq "down"){
840                 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
841             }
842             else {
843                 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
844             }
845         }
846     }
847     return $error; 
851 sub _start {
852     my ($kernel) = $_[KERNEL];
853     &trigger_db_loop($kernel);
857 sub client_input {
858     no strict "refs";
859     my ($kernel, $session, $heap,$input,$wheel) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
860     my $session_id = $session->ID;
861     my ($msg, $msg_hash, $module);
862     my $error = 0;
863     my $answer_l;
864     my ($answer_header, @answer_target_l, $answer_source);
865     my $client_answer;
867     daemon_log("INFO: Incoming msg from '".$heap->{'remote_ip'}."'", 5);
868     daemon_log("DEBUG: Incoming message:\n$input", 8);
870     ####################
871     # check incoming msg
872     # msg is from a new client or gosa
873     ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
874     # msg is from a gosa-si-server or gosa-si-bus
875     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
876         ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
877     }
878     # msg is from a gosa-si-client
879     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
880         ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
881     }
882     # an error occurred
883     if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
884         $error++;
885     }
887     ######################
888     # process incoming msg
889     if( $error == 0) {
890         daemon_log("DEBUG: Processing module ".$module, 7);
891         $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
893         if ( 0 > @{$answer_l} ) {
894             my $answer_str = join("\n", @{$answer_l});
895             daemon_log("DEGUB: $module: Got answer from module: \n".$answer_str,8);
896         }
897     }
898     if( !$answer_l ) { $error++ };
900     ########
901     # answer
902     if( $error == 0 ) {
904         foreach my $answer ( @{$answer_l} ) {
905             # for each answer in answer list
906             
907             # check outgoing msg to xml validity
908             my $answer_hash = &check_outgoing_xml_validity($answer);
909             if( not defined $answer_hash ) {
910                 next;
911             }
912             
913             $answer_header = @{$answer_hash->{'header'}}[0];
914             @answer_target_l = @{$answer_hash->{'target'}};
915             $answer_source = @{$answer_hash->{'source'}}[0];
917             # deliver msg to all targets 
918             foreach my $answer_target ( @answer_target_l ) {
920                 # targets of msg are all gosa-si-clients in known_clients_db
921                 if( $answer_target eq "*" ) {
922                     # answer is for all clients
923                     my $sql_statement= "SELECT * FROM known_clients";
924                     my $query_res = $known_clients_db->select_dbentry( $sql_statement ); 
925                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
926                         my $host_name = $hit->{hostname};
927                         my $host_key = $hit->{hostkey};
928                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
929                     }
930                 }
932                 # targets of msg are all gosa-si-server in known_server_db
933                 elsif( $answer_target eq "KNOWN_SERVER" ) {
934                     # answer is for all server in known_server
935                     my $sql_statement= "SELECT * FROM known_server";
936                     my $query_res = $known_server_db->select_dbentry( $sql_statement ); 
937                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
938                         my $host_name = $hit->{hostname};
939                         my $host_key = $hit->{hostkey};
940                         $answer =~ s/KNOWN_SERVER/$host_name/g;
941                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
942                     }
943                 }
945                 # target of msg is GOsa
946                 elsif( $answer_target eq "GOSA" ) {
947                     $answer =~ /<session_id>(\d+)<\/session_id>/;
948                     my $session_id = $1;
949                     my $add_on = "";
950                     if( defined $session_id ) {
951                         $add_on = ".session_id=$session_id";
952                     }
953                     # answer is for GOSA and has to returned to connected client
954                     my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
955                     $client_answer = $gosa_answer.$add_on;
956                 }
958                 # target of msg is job queue at this host
959                 elsif( $answer_target eq "JOBDB") {
960                     $answer =~ /<header>(\S+)<\/header>/;   
961                     my $header;
962                     if( defined $1 ) { $header = $1; }
963                     &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header);
964                 }
966                 # target of msg is a mac address
967                 elsif( $answer_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})$/i ) {
968                     daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
969                     my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
970                     my $query_res = $known_clients_db->select_dbentry( $sql_statement );
971                     my $found_ip_flag = 0;
972                     while( my ($hit_num, $hit) = each %{ $query_res } ) {    
973                         my $host_name = $hit->{hostname};
974                         my $host_key = $hit->{hostkey};
975                         $answer =~ s/$answer_target/$host_name/g;
976                         daemon_log("found host '$host_name', associated to '$answer_target'", 3);
977                         &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
978                         $found_ip_flag++ ;
979                     }   
980                     if( $found_ip_flag == 0) {
981                         daemon_log("WARNING: no host found in known_clients with mac address '$answer_target'", 3);
982                         if( $bus_activ eq "true" ) { 
983                             daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
984                             my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
985                             my $query_res = $known_server_db->select_dbentry( $sql_statement );
986                             while( my ($hit_num, $hit) = each %{ $query_res } ) {    
987                                 my $bus_address = $hit->{hostname};
988                                 my $bus_key = $hit->{hostkey};
989                                 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
990                                 last;
991                             }
992                         }
994                     }
996                 #  answer is for one specific host   
997                 } else {
998                     # get encrypt_key
999                     my $encrypt_key = &get_encrypt_key($answer_target);
1000                     if( not defined $encrypt_key ) {
1001                         # unknown target, forward msg to bus
1002                         daemon_log("WARNING: unknown target '$answer_target'", 3);
1003                         if( $bus_activ eq "true" ) { 
1004                             daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
1005                             my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
1006                             my $query_res = $known_server_db->select_dbentry( $sql_statement );
1007                             my $res_length = keys( %{$query_res} );
1008                             if( $res_length == 0 ){
1009                                 daemon_log("WARNING: send '$answer_header' to '$bus_address' failed, no bus found in known_server", 3);
1010                             }
1011                             else {
1012                                 while( my ($hit_num, $hit) = each %{ $query_res } ) {    
1013                                     my $bus_key = $hit->{hostkey};
1014                                     &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
1015                                 }
1016                             }
1017                         }
1018                         next;
1019                     }
1020                     # send_msg
1021                     &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
1022                 }
1023             }
1024         }
1025     }
1027     if( $client_answer ) {
1028         if( $client_answer =~ s/session_id=(\d+)$// ) {
1029             my $session_id = $1;
1030             if( defined $session_id ) {
1031                 my $session_reference = $kernel->ID_id_to_session($session_id);
1032                 $heap = $session_reference->get_heap();
1033             }     
1034         }
1035         $heap->{client}->put($client_answer);
1036     }
1038     return;
1043 sub trigger_db_loop {
1044 #       my ($kernel) = $_[KERNEL];
1045         my ($kernel) = @_ ;
1046         $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1050 sub watch_for_new_jobs {
1051         my ($kernel,$heap) = @_[KERNEL, HEAP];
1053         # check gosa job queue for jobs with executable timestamp
1054     my $timestamp = &get_time();
1055     my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
1056         " WHERE status='waiting' AND timestamp<'$timestamp'";
1057         my $res = $job_db->select_dbentry( $sql_statement );
1059         while( my ($id, $hit) = each %{$res} ) {         
1060                 my $jobdb_id = $hit->{id};
1061                 my $macaddress = $hit->{'macaddress'};
1062         my $job_msg = $hit->{'xmlmessage'};
1063         my $header = $hit->{'headertag'};
1064         my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1065                 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1066                 # expect macaddress is unique!!!!!!
1067                 my $target = $res_hash->{1}->{hostname};
1069                 if (not defined $target) {
1070                         &daemon_log("ERROR: no host found for mac address: $macaddress", 1);
1071                         &daemon_log("$hit->{xmlmessage}", 8);
1072             my $sql_statement = "UPDATE $job_queue_table_name ".
1073                 "SET status='error', result='no host found for mac address' ".
1074                 "WHERE id='$jobdb_id'";
1075                         my $res = $job_db->update_dbentry($sql_statement);
1076                         next;
1077                 }
1079                 # change header
1080         $job_msg =~ s/<header>job_/<header>gosa_/;
1082                 # add sqlite_id 
1083         $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1085                 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header);
1086     }
1088         $kernel->delay_set('watch_for_new_jobs',3);
1092 #==== MAIN = main ==============================================================
1093 #  parse commandline options
1094 Getopt::Long::Configure( "bundling" );
1095 GetOptions("h|help" => \&usage,
1096         "c|config=s" => \$cfg_file,
1097         "f|foreground" => \$foreground,
1098         "v|verbose+" => \$verbose,
1099         "no-bus+" => \$no_bus,
1100         "no-arp+" => \$no_arp,
1101            );
1103 #  read and set config parameters
1104 &check_cmdline_param ;
1105 &read_configfile;
1106 &check_pid;
1108 $SIG{CHLD} = 'IGNORE';
1110 # forward error messages to logfile
1111 if( ! $foreground ) {
1112     open(STDERR, '>>', $log_file);
1113     open(STDOUT, '>>', $log_file);
1116 # Just fork, if we are not in foreground mode
1117 if( ! $foreground ) { 
1118     chdir '/'                 or die "Can't chdir to /: $!";
1119     $pid = fork;
1120     setsid                    or die "Can't start a new session: $!";
1121     umask 0;
1122 } else { 
1123     $pid = $$; 
1126 # Do something useful - put our PID into the pid_file
1127 if( 0 != $pid ) {
1128     open( LOCK_FILE, ">$pid_file" );
1129     print LOCK_FILE "$pid\n";
1130     close( LOCK_FILE );
1131     if( !$foreground ) { 
1132         exit( 0 ) 
1133     };
1136 daemon_log(" ", 1);
1137 daemon_log("$0 started!", 1);
1139 if ($no_bus > 0) {
1140     $bus_activ = "false"
1145 # delete old DBsqlite lock files
1146 #unlink('/tmp/gosa_si_lock*');
1148 # connect to gosa-si job queue
1149 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "progress", "headertag", "targettag", "xmlmessage", "macaddress");
1150 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1151 $job_db->create_table('jobs', \@job_col_names);
1153 # connect to known_clients_db
1154 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events', 'login');
1155 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1156 $known_clients_db->create_table('known_clients', \@clients_col_names);
1158 # connect to known_server_db
1159 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1160 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1161 $known_server_db->create_table('known_server', \@server_col_names);
1163 # create xml object used for en/decrypting
1164 $xml = new XML::Simple();
1166 # create socket for incoming xml messages
1167 POE::Component::Server::TCP->new(
1168         Port => $server_port,
1169         ClientInput => \&client_input,
1170 );
1171 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1173 # create session for repeatedly checking the job queue for jobs
1174 POE::Session->create(
1175         inline_states => {
1176                 _start => \&_start,
1177                 watch_for_new_jobs => \&watch_for_new_jobs,
1178         }
1179 );
1182 # import all modules
1183 &import_modules;
1185 # check wether all modules are gosa-si valid passwd check
1187 POE::Kernel->run();
1188 exit;