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
147 EOF
148 print "\n" ;
149 }
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 }
175 }
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 }
217 #log into syslog
218 # my ($msg, $level, $facility) = @_;
219 # if(not defined $msg) {return}
220 # if(not defined $level) {$level = "info"}
221 # if(not defined $facility) {$facility = "LOG_DAEMON"}
222 # openlog($0, "pid,cons,", $facility);
223 # syslog($level, $msg);
224 # closelog;
225 # return;
226 }
229 #=== FUNCTION ================================================================
230 # NAME: check_cmdline_param
231 # PARAMETERS: nothing
232 # RETURNS: nothing
233 # DESCRIPTION: validates commandline parameter
234 #===============================================================================
235 sub check_cmdline_param () {
236 my $err_config;
237 my $err_counter = 0;
238 if(not defined($cfg_file)) {
239 $cfg_file = "/etc/gosa-si/server.conf";
240 if(! -r $cfg_file) {
241 $err_config = "please specify a config file";
242 $err_counter += 1;
243 }
244 }
245 if( $err_counter > 0 ) {
246 &usage( "", 1 );
247 if( defined( $err_config)) { print STDERR "$err_config\n"}
248 print STDERR "\n";
249 exit( -1 );
250 }
251 }
254 #=== FUNCTION ================================================================
255 # NAME: check_pid
256 # PARAMETERS: nothing
257 # RETURNS: nothing
258 # DESCRIPTION: handels pid processing
259 #===============================================================================
260 sub check_pid {
261 $pid = -1;
262 # Check, if we are already running
263 if( open(LOCK_FILE, "<$pid_file") ) {
264 $pid = <LOCK_FILE>;
265 if( defined $pid ) {
266 chomp( $pid );
267 if( -f "/proc/$pid/stat" ) {
268 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
269 if( $0 eq $stat ) {
270 close( LOCK_FILE );
271 exit -1;
272 }
273 }
274 }
275 close( LOCK_FILE );
276 unlink( $pid_file );
277 }
279 # create a syslog msg if it is not to possible to open PID file
280 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
281 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
282 if (open(LOCK_FILE, '<', $pid_file)
283 && ($pid = <LOCK_FILE>))
284 {
285 chomp($pid);
286 $msg .= "(PID $pid)\n";
287 } else {
288 $msg .= "(unable to read PID)\n";
289 }
290 if( ! ($foreground) ) {
291 openlog( $0, "cons,pid", "daemon" );
292 syslog( "warning", $msg );
293 closelog();
294 }
295 else {
296 print( STDERR " $msg " );
297 }
298 exit( -1 );
299 }
300 }
302 #=== FUNCTION ================================================================
303 # NAME: import_modules
304 # PARAMETERS: module_path - string - abs. path to the directory the modules
305 # are stored
306 # RETURNS: nothing
307 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
308 # state is on is imported by "require 'file';"
309 #===============================================================================
310 sub import_modules {
311 daemon_log(" ", 1);
313 if (not -e $modules_path) {
314 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
315 }
317 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
318 while (defined (my $file = readdir (DIR))) {
319 if (not $file =~ /(\S*?).pm$/) {
320 next;
321 }
322 my $mod_name = $1;
324 if( $file =~ /ArpHandler.pm/ ) {
325 if( $no_arp > 0 ) {
326 next;
327 }
328 }
330 eval { require $file; };
331 if ($@) {
332 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
333 daemon_log("$@", 5);
334 } else {
335 my $info = eval($mod_name.'::get_module_info()');
336 # Only load module if get_module_info() returns a non-null object
337 if( $info ) {
338 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
339 $known_modules->{$mod_name} = $info;
340 daemon_log("INFO: module $mod_name loaded", 5);
341 }
342 }
343 }
344 close (DIR);
345 }
348 #=== FUNCTION ================================================================
349 # NAME: sig_int_handler
350 # PARAMETERS: signal - string - signal arose from system
351 # RETURNS: noting
352 # DESCRIPTION: handels tasks to be done befor signal becomes active
353 #===============================================================================
354 sub sig_int_handler {
355 my ($signal) = @_;
357 daemon_log("shutting down gosa-si-server", 1);
358 exit(1);
359 }
360 $SIG{INT} = \&sig_int_handler;
364 sub check_key_and_xml_validity {
365 my ($crypted_msg, $module_key) = @_;
366 my $msg;
367 my $msg_hash;
368 my $error_string;
369 eval{
370 $msg = &decrypt_msg($crypted_msg, $module_key);
372 if ($msg =~ /<xml>/i){
373 &main::daemon_log("decrypted_msg: \n$msg", 8);
374 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
376 ##############
377 # check header
378 if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
379 my $header_l = $msg_hash->{'header'};
380 if( 1 > @{$header_l} ) { die 'empty header tag'; }
381 if( 1 < @{$header_l} ) { die 'more than one header specified'; }
382 my $header = @{$header_l}[0];
383 if( 0 == length $header) { die 'empty string in header tag'; }
385 ##############
386 # check source
387 if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
388 my $source_l = $msg_hash->{'source'};
389 if( 1 > @{$source_l} ) { die 'empty source tag'; }
390 if( 1 < @{$source_l} ) { die 'more than one source specified'; }
391 my $source = @{$source_l}[0];
392 if( 0 == length $source) { die 'source error'; }
394 ##############
395 # check target
396 if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
397 my $target_l = $msg_hash->{'target'};
398 if( 1 > @{$target_l} ) { die 'empty target tag'; }
399 }
400 };
401 if($@) {
402 &main::daemon_log("WARNING: do not understand the message", 5);
403 &main::daemon_log("$@", 8);
404 $msg = undef;
405 $msg_hash = undef;
406 }
408 return ($msg, $msg_hash);
409 }
412 sub check_outgoing_xml_validity {
413 my ($msg) = @_;
415 my $msg_hash;
416 eval{
417 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
419 ##############
420 # check header
421 my $header_l = $msg_hash->{'header'};
422 if( 1 != @{$header_l} ) {
423 die 'no or more than one headers specified';
424 }
425 my $header = @{$header_l}[0];
426 if( 0 == length $header) {
427 die 'header has length 0';
428 }
430 ##############
431 # check source
432 my $source_l = $msg_hash->{'source'};
433 if( 1 != @{$source_l} ) {
434 die 'no or more than 1 sources specified';
435 }
436 my $source = @{$source_l}[0];
437 if( 0 == length $source) {
438 die 'source has length 0';
439 }
440 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
441 $source =~ /^GOSA$/i ) {
442 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
443 }
445 ##############
446 # check target
447 my $target_l = $msg_hash->{'target'};
448 if( 0 == @{$target_l} ) {
449 die "no targets specified";
450 }
451 foreach my $target (@$target_l) {
452 if( 0 == length $target) {
453 die "target has length 0";
454 }
455 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
456 $target =~ /^GOSA$/i ||
457 $target =~ /^\*$/ ||
458 $target =~ /KNOWN_SERVER/i ||
459 $target =~ /JOBDB/i ||
460 $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 ){
461 die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
462 }
463 }
464 };
465 if($@) {
466 daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
467 daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 8);
468 $msg_hash = undef;
469 }
471 return ($msg_hash);
472 }
475 sub input_from_known_server {
476 my ($input, $remote_ip) = @_ ;
477 my ($msg, $msg_hash, $module);
479 my $sql_statement= "SELECT * FROM known_server";
480 my $query_res = $known_server_db->select_dbentry( $sql_statement );
482 while( my ($hit_num, $hit) = each %{ $query_res } ) {
483 my $host_name = $hit->{hostname};
484 if( not $host_name =~ "^$remote_ip") {
485 next;
486 }
487 my $host_key = $hit->{hostkey};
488 daemon_log("DEBUG: input_from_known_server: host_name: $host_name", 7);
489 daemon_log("DEBUG: input_from_known_server: host_key: $host_key", 7);
491 # check if module can open msg envelope with module key
492 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
493 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
494 daemon_log("DEBUG: input_from_known_server: deciphering raise error", 7);
495 daemon_log("$@", 8);
496 next;
497 }
498 else {
499 $msg = $tmp_msg;
500 $msg_hash = $tmp_msg_hash;
501 $module = "SIPackages";
502 last;
503 }
504 }
506 if( (!$msg) || (!$msg_hash) || (!$module) ) {
507 daemon_log("INFO: Incoming message is not from a known server", 5);
508 }
510 return ($msg, $msg_hash, $module);
511 }
514 sub input_from_known_client {
515 my ($input, $remote_ip) = @_ ;
516 my ($msg, $msg_hash, $module);
518 my $sql_statement= "SELECT * FROM known_clients";
519 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
520 while( my ($hit_num, $hit) = each %{ $query_res } ) {
521 my $host_name = $hit->{hostname};
522 if( not $host_name =~ /^$remote_ip:\d*$/) {
523 next;
524 }
525 my $host_key = $hit->{hostkey};
526 &daemon_log("DEBUG: input_from_known_client: host_name: $host_name", 7);
527 &daemon_log("DEBUG: input_from_known_client: host_key: $host_key", 7);
529 # check if module can open msg envelope with module key
530 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
532 if( (!$msg) || (!$msg_hash) ) {
533 &daemon_log("DEGUG: input_from_known_client: deciphering raise error", 7);
534 &daemon_log("$@", 8);
535 next;
536 }
537 else {
538 $module = "SIPackages";
539 last;
540 }
541 }
543 if( (!$msg) || (!$msg_hash) || (!$module) ) {
544 &daemon_log("INFO: Incoming message is not from a known client", 5);
545 }
547 return ($msg, $msg_hash, $module);
548 }
551 sub input_from_unknown_host {
552 no strict "refs";
553 my ($input) = @_ ;
554 my ($msg, $msg_hash, $module);
555 my $error_string;
557 my %act_modules = %$known_modules;
559 while( my ($mod, $info) = each(%act_modules)) {
561 # check a key exists for this module
562 my $module_key = ${$mod."_key"};
563 if( not defined $module_key ) {
564 if( $mod eq 'ArpHandler' ) {
565 next;
566 }
567 daemon_log("ERROR: no key specified in config file for $mod", 1);
568 next;
569 }
570 daemon_log("DEBUG: $mod: $module_key", 7);
572 # check if module can open msg envelope with module key
573 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
574 if( (not defined $msg) || (not defined $msg_hash) ) {
575 next;
576 }
577 else {
578 $module = $mod;
579 last;
580 }
581 }
583 if( (!$msg) || (!$msg_hash) || (!$module)) {
584 daemon_log("INFO: Incoming message is not from an unknown host", 5);
585 }
587 return ($msg, $msg_hash, $module);
588 }
591 sub create_ciphering {
592 my ($passwd) = @_;
593 if((!defined($passwd)) || length($passwd)==0) {
594 $passwd = "";
595 }
596 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
597 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
598 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
599 $my_cipher->set_iv($iv);
600 return $my_cipher;
601 }
604 sub encrypt_msg {
605 my ($msg, $key) = @_;
606 my $my_cipher = &create_ciphering($key);
607 {
608 use bytes;
609 $msg = "\0"x(16-length($msg)%16).$msg;
610 }
611 $msg = $my_cipher->encrypt($msg);
612 chomp($msg = &encode_base64($msg));
613 # there are no newlines allowed inside msg
614 $msg=~ s/\n//g;
615 return $msg;
616 }
619 sub decrypt_msg {
621 my ($msg, $key) = @_ ;
622 $msg = &decode_base64($msg);
623 my $my_cipher = &create_ciphering($key);
624 $msg = $my_cipher->decrypt($msg);
625 $msg =~ s/\0*//g;
626 return $msg;
627 }
630 sub get_encrypt_key {
631 my ($target) = @_ ;
632 my $encrypt_key;
633 my $error = 0;
635 # target can be in known_server
636 if( not defined $encrypt_key ) {
637 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
638 my $query_res = $known_server_db->select_dbentry( $sql_statement );
639 while( my ($hit_num, $hit) = each %{ $query_res } ) {
640 my $host_name = $hit->{hostname};
641 if( $host_name ne $target ) {
642 next;
643 }
644 $encrypt_key = $hit->{hostkey};
645 last;
646 }
647 }
649 # target can be in known_client
650 if( not defined $encrypt_key ) {
651 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
652 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
653 while( my ($hit_num, $hit) = each %{ $query_res } ) {
654 my $host_name = $hit->{hostname};
655 if( $host_name ne $target ) {
656 next;
657 }
658 $encrypt_key = $hit->{hostkey};
659 last;
660 }
661 }
663 return $encrypt_key;
664 }
667 #=== FUNCTION ================================================================
668 # NAME: open_socket
669 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
670 # [PeerPort] string necessary if port not appended by PeerAddr
671 # RETURNS: socket IO::Socket::INET
672 # DESCRIPTION: open a socket to PeerAddr
673 #===============================================================================
674 sub open_socket {
675 my ($PeerAddr, $PeerPort) = @_ ;
676 if(defined($PeerPort)){
677 $PeerAddr = $PeerAddr.":".$PeerPort;
678 }
679 my $socket;
680 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
681 Porto => "tcp",
682 Type => SOCK_STREAM,
683 Timeout => 5,
684 );
685 if(not defined $socket) {
686 return;
687 }
688 # &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
689 return $socket;
690 }
693 #=== FUNCTION ================================================================
694 # NAME: get_ip
695 # PARAMETERS: interface name (i.e. eth0)
696 # RETURNS: (ip address)
697 # DESCRIPTION: Uses ioctl to get ip address directly from system.
698 #===============================================================================
699 sub get_ip {
700 my $ifreq= shift;
701 my $result= "";
702 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
703 my $proto= getprotobyname('ip');
705 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
706 or die "socket: $!";
708 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
709 my ($if, $sin) = unpack 'a16 a16', $ifreq;
710 my ($port, $addr) = sockaddr_in $sin;
711 my $ip = inet_ntoa $addr;
713 if ($ip && length($ip) > 0) {
714 $result = $ip;
715 }
716 }
718 return $result;
719 }
721 sub get_local_ip_for_remote_ip {
722 my $remote_ip= shift;
723 my $result="0.0.0.0";
725 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
726 if($remote_ip eq "127.0.0.1") {
727 $result = "127.0.0.1";
728 } else {
729 my $PROC_NET_ROUTE= ('/proc/net/route');
731 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
732 or die "Could not open $PROC_NET_ROUTE";
734 my @ifs = <PROC_NET_ROUTE>;
736 close(PROC_NET_ROUTE);
738 # Eat header line
739 shift @ifs;
740 chomp @ifs;
741 foreach my $line(@ifs) {
742 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
743 my $destination;
744 my $mask;
745 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
746 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
747 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
748 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
749 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
750 # destination matches route, save mac and exit
751 $result= &get_ip($Iface);
752 last;
753 }
754 }
755 }
756 } else {
757 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
758 }
759 return $result;
760 }
762 sub send_msg_to_target {
763 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
764 my $error = 0;
765 my $header;
766 my $new_status;
767 my $act_status;
768 my ($sql_statement, $res);
770 if( $msg_header ) {
771 $header = "'$msg_header'-";
772 }
773 else {
774 $header = "";
775 }
777 # Patch the source ip
778 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
779 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
780 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
781 }
783 # encrypt xml msg
784 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
786 # opensocket
787 my $socket = &open_socket($address);
788 if( !$socket ) {
789 daemon_log("ERROR: cannot send ".$header."msg to $address , host not reachable", 1);
790 $error++;
791 }
793 if( $error == 0 ) {
794 # send xml msg
795 print $socket $crypted_msg."\n";
797 daemon_log("INFO: send ".$header."msg to $address", 5);
798 daemon_log("message:\n$msg", 8);
800 }
802 # close socket in any case
803 if( $socket ) {
804 close $socket;
805 }
807 if( $error > 0 ) { $new_status = "down"; }
808 else { $new_status = $msg_header; }
811 # known_clients
812 $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
813 $res = $known_clients_db->select_dbentry($sql_statement);
814 if( keys(%$res) > 0) {
815 $act_status = $res->{1}->{'status'};
816 if( $act_status eq "down" ) {
817 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
818 $res = $known_clients_db->del_dbentry($sql_statement);
819 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
820 }
821 else {
822 $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
823 $res = $known_clients_db->update_dbentry($sql_statement);
824 if($new_status eq "down"){
825 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
826 }
827 else {
828 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
829 }
830 }
831 }
833 # known_server
834 $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
835 $res = $known_server_db->select_dbentry($sql_statement);
836 if( keys(%$res) > 0 ) {
837 $act_status = $res->{1}->{'status'};
838 if( $act_status eq "down" ) {
839 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
840 $res = $known_server_db->del_dbentry($sql_statement);
841 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
842 }
843 else {
844 $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
845 $res = $known_server_db->update_dbentry($sql_statement);
846 if($new_status eq "down"){
847 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
848 }
849 else {
850 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
851 }
852 }
853 }
854 return $error;
855 }
858 sub _start {
859 my ($kernel) = $_[KERNEL];
860 &trigger_db_loop($kernel);
861 }
864 sub client_input {
865 no strict "refs";
866 my ($kernel, $session, $heap,$input,$wheel) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
867 my $session_id = $session->ID;
868 my ($msg, $msg_hash, $module);
869 my $error = 0;
870 my $answer_l;
871 my ($answer_header, @answer_target_l, $answer_source);
872 my $client_answer;
874 daemon_log("INFO: Incoming msg from '".$heap->{'remote_ip'}."'", 5);
875 daemon_log("DEBUG: Incoming message:\n$input", 8);
877 ####################
878 # check incoming msg
879 # msg is from a new client or gosa
880 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
881 # msg is from a gosa-si-server or gosa-si-bus
882 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
883 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
884 }
885 # msg is from a gosa-si-client
886 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
887 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
888 }
889 # an error occurred
890 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
891 $error++;
892 }
894 ######################
895 # process incoming msg
896 if( $error == 0) {
897 daemon_log("DEBUG: Processing module ".$module, 7);
898 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
900 if ( 0 > @{$answer_l} ) {
901 my $answer_str = join("\n", @{$answer_l});
902 daemon_log("DEGUB: $module: Got answer from module: \n".$answer_str,8);
903 }
904 }
905 if( !$answer_l ) { $error++ };
907 ########
908 # answer
909 if( $error == 0 ) {
911 foreach my $answer ( @{$answer_l} ) {
912 # for each answer in answer list
914 # check outgoing msg to xml validity
915 my $answer_hash = &check_outgoing_xml_validity($answer);
916 if( not defined $answer_hash ) {
917 next;
918 }
920 $answer_header = @{$answer_hash->{'header'}}[0];
921 @answer_target_l = @{$answer_hash->{'target'}};
922 $answer_source = @{$answer_hash->{'source'}}[0];
924 # deliver msg to all targets
925 foreach my $answer_target ( @answer_target_l ) {
927 # targets of msg are all gosa-si-clients in known_clients_db
928 if( $answer_target eq "*" ) {
929 # answer is for all clients
930 my $sql_statement= "SELECT * FROM known_clients";
931 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
932 while( my ($hit_num, $hit) = each %{ $query_res } ) {
933 my $host_name = $hit->{hostname};
934 my $host_key = $hit->{hostkey};
935 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
936 }
937 }
939 # targets of msg are all gosa-si-server in known_server_db
940 elsif( $answer_target eq "KNOWN_SERVER" ) {
941 # answer is for all server in known_server
942 my $sql_statement= "SELECT * FROM known_server";
943 my $query_res = $known_server_db->select_dbentry( $sql_statement );
944 while( my ($hit_num, $hit) = each %{ $query_res } ) {
945 my $host_name = $hit->{hostname};
946 my $host_key = $hit->{hostkey};
947 $answer =~ s/KNOWN_SERVER/$host_name/g;
948 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
949 }
950 }
952 # target of msg is GOsa
953 elsif( $answer_target eq "GOSA" ) {
954 $answer =~ /<session_id>(\d+)<\/session_id>/;
955 my $session_id = $1;
956 my $add_on = "";
957 if( defined $session_id ) {
958 $add_on = ".session_id=$session_id";
959 }
960 # answer is for GOSA and has to returned to connected client
961 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
962 $client_answer = $gosa_answer.$add_on;
963 }
965 # target of msg is job queue at this host
966 elsif( $answer_target eq "JOBDB") {
967 $answer =~ /<header>(\S+)<\/header>/;
968 my $header;
969 if( defined $1 ) { $header = $1; }
970 &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header);
971 }
973 # target of msg is a mac address
974 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 ) {
975 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
976 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
977 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
978 my $found_ip_flag = 0;
979 while( my ($hit_num, $hit) = each %{ $query_res } ) {
980 my $host_name = $hit->{hostname};
981 my $host_key = $hit->{hostkey};
982 $answer =~ s/$answer_target/$host_name/g;
983 daemon_log("found host '$host_name', associated to '$answer_target'", 3);
984 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
985 $found_ip_flag++ ;
986 }
987 if( $found_ip_flag == 0) {
988 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target'", 3);
989 if( $bus_activ eq "true" ) {
990 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
991 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
992 my $query_res = $known_server_db->select_dbentry( $sql_statement );
993 while( my ($hit_num, $hit) = each %{ $query_res } ) {
994 my $bus_address = $hit->{hostname};
995 my $bus_key = $hit->{hostkey};
996 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
997 last;
998 }
999 }
1001 }
1003 # answer is for one specific host
1004 } else {
1005 # get encrypt_key
1006 my $encrypt_key = &get_encrypt_key($answer_target);
1007 if( not defined $encrypt_key ) {
1008 # unknown target, forward msg to bus
1009 daemon_log("WARNING: unknown target '$answer_target'", 3);
1010 if( $bus_activ eq "true" ) {
1011 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
1012 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
1013 my $query_res = $known_server_db->select_dbentry( $sql_statement );
1014 my $res_length = keys( %{$query_res} );
1015 if( $res_length == 0 ){
1016 daemon_log("WARNING: send '$answer_header' to '$bus_address' failed, no bus found in known_server", 3);
1017 }
1018 else {
1019 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1020 my $bus_key = $hit->{hostkey};
1021 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
1022 }
1023 }
1024 }
1025 next;
1026 }
1027 # send_msg
1028 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
1029 }
1030 }
1031 }
1032 }
1034 if( $client_answer ) {
1035 if( $client_answer =~ s/session_id=(\d+)$// ) {
1036 my $session_id = $1;
1037 if( defined $session_id ) {
1038 my $session_reference = $kernel->ID_id_to_session($session_id);
1039 $heap = $session_reference->get_heap();
1040 }
1041 }
1042 $heap->{client}->put($client_answer);
1043 }
1045 return;
1046 }
1050 sub trigger_db_loop {
1051 # my ($kernel) = $_[KERNEL];
1052 my ($kernel) = @_ ;
1053 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1054 }
1057 sub watch_for_new_jobs {
1058 my ($kernel,$heap) = @_[KERNEL, HEAP];
1060 # check gosa job queue for jobs with executable timestamp
1061 my $timestamp = &get_time();
1062 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
1063 " WHERE status='waiting' AND timestamp<'$timestamp'";
1064 my $res = $job_db->select_dbentry( $sql_statement );
1066 while( my ($id, $hit) = each %{$res} ) {
1067 my $jobdb_id = $hit->{id};
1068 my $macaddress = $hit->{'macaddress'};
1069 my $job_msg = $hit->{'xmlmessage'};
1070 my $header = $hit->{'headertag'};
1071 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1072 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1073 # expect macaddress is unique!!!!!!
1074 my $target = $res_hash->{1}->{hostname};
1076 if (not defined $target) {
1077 &daemon_log("ERROR: no host found for mac address: $macaddress", 1);
1078 &daemon_log("$hit->{xmlmessage}", 8);
1079 my $sql_statement = "UPDATE $job_queue_table_name ".
1080 "SET status='error', result='no host found for mac address' ".
1081 "WHERE id='$jobdb_id'";
1082 my $res = $job_db->update_dbentry($sql_statement);
1083 next;
1084 }
1086 # change header
1087 $job_msg =~ s/<header>job_/<header>gosa_/;
1089 # add sqlite_id
1090 $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1092 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header);
1093 }
1095 $kernel->delay_set('watch_for_new_jobs',3);
1096 }
1099 #==== MAIN = main ==============================================================
1100 # parse commandline options
1101 Getopt::Long::Configure( "bundling" );
1102 GetOptions("h|help" => \&usage,
1103 "c|config=s" => \$cfg_file,
1104 "f|foreground" => \$foreground,
1105 "v|verbose+" => \$verbose,
1106 "no-bus+" => \$no_bus,
1107 "no-arp+" => \$no_arp,
1108 );
1110 # read and set config parameters
1111 &check_cmdline_param ;
1112 &read_configfile;
1113 &check_pid;
1115 $SIG{CHLD} = 'IGNORE';
1117 # forward error messages to logfile
1118 if( ! $foreground ) {
1119 open(STDERR, '>>', $log_file);
1120 open(STDOUT, '>>', $log_file);
1121 }
1123 # Just fork, if we are not in foreground mode
1124 if( ! $foreground ) {
1125 chdir '/' or die "Can't chdir to /: $!";
1126 $pid = fork;
1127 setsid or die "Can't start a new session: $!";
1128 umask 0;
1129 } else {
1130 $pid = $$;
1131 }
1133 # Do something useful - put our PID into the pid_file
1134 if( 0 != $pid ) {
1135 open( LOCK_FILE, ">$pid_file" );
1136 print LOCK_FILE "$pid\n";
1137 close( LOCK_FILE );
1138 if( !$foreground ) {
1139 exit( 0 )
1140 };
1141 }
1143 daemon_log(" ", 1);
1144 daemon_log("$0 started!", 1);
1146 if ($no_bus > 0) {
1147 $bus_activ = "false"
1148 }
1152 # delete old DBsqlite lock files
1153 #unlink('/tmp/gosa_si_lock*');
1155 # connect to gosa-si job queue
1156 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "progress", "headertag", "targettag", "xmlmessage", "macaddress");
1157 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1158 $job_db->create_table('jobs', \@job_col_names);
1160 # connect to known_clients_db
1161 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events', 'login');
1162 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1163 $known_clients_db->create_table('known_clients', \@clients_col_names);
1165 # connect to known_server_db
1166 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1167 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1168 $known_server_db->create_table('known_server', \@server_col_names);
1170 # create xml object used for en/decrypting
1171 $xml = new XML::Simple();
1173 # create socket for incoming xml messages
1174 POE::Component::Server::TCP->new(
1175 Port => $server_port,
1176 ClientInput => \&client_input,
1177 );
1178 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1180 # create session for repeatedly checking the job queue for jobs
1181 POE::Session->create(
1182 inline_states => {
1183 _start => \&_start,
1184 watch_for_new_jobs => \&watch_for_new_jobs,
1185 }
1186 );
1189 # import all modules
1190 &import_modules;
1192 # check wether all modules are gosa-si valid passwd check
1194 POE::Kernel->run();
1195 exit;