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 my $len;
608 {
609 use bytes;
610 $len= 16-length($msg)%16;
611 }
612 $msg = "\0"x($len).$msg;
613 $msg = $my_cipher->encrypt($msg);
614 chomp($msg = &encode_base64($msg));
615 # there are no newlines allowed inside msg
616 $msg=~ s/\n//g;
617 return $msg;
618 }
621 sub decrypt_msg {
623 my ($msg, $key) = @_ ;
624 $msg = &decode_base64($msg);
625 my $my_cipher = &create_ciphering($key);
626 $msg = $my_cipher->decrypt($msg);
627 $msg =~ s/\0*//g;
628 return $msg;
629 }
632 sub get_encrypt_key {
633 my ($target) = @_ ;
634 my $encrypt_key;
635 my $error = 0;
637 # target can be in known_server
638 if( not defined $encrypt_key ) {
639 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
640 my $query_res = $known_server_db->select_dbentry( $sql_statement );
641 while( my ($hit_num, $hit) = each %{ $query_res } ) {
642 my $host_name = $hit->{hostname};
643 if( $host_name ne $target ) {
644 next;
645 }
646 $encrypt_key = $hit->{hostkey};
647 last;
648 }
649 }
651 # target can be in known_client
652 if( not defined $encrypt_key ) {
653 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
654 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
655 while( my ($hit_num, $hit) = each %{ $query_res } ) {
656 my $host_name = $hit->{hostname};
657 if( $host_name ne $target ) {
658 next;
659 }
660 $encrypt_key = $hit->{hostkey};
661 last;
662 }
663 }
665 return $encrypt_key;
666 }
669 #=== FUNCTION ================================================================
670 # NAME: open_socket
671 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
672 # [PeerPort] string necessary if port not appended by PeerAddr
673 # RETURNS: socket IO::Socket::INET
674 # DESCRIPTION: open a socket to PeerAddr
675 #===============================================================================
676 sub open_socket {
677 my ($PeerAddr, $PeerPort) = @_ ;
678 if(defined($PeerPort)){
679 $PeerAddr = $PeerAddr.":".$PeerPort;
680 }
681 my $socket;
682 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
683 Porto => "tcp",
684 Type => SOCK_STREAM,
685 Timeout => 5,
686 );
687 if(not defined $socket) {
688 return;
689 }
690 # &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
691 return $socket;
692 }
695 #=== FUNCTION ================================================================
696 # NAME: get_ip
697 # PARAMETERS: interface name (i.e. eth0)
698 # RETURNS: (ip address)
699 # DESCRIPTION: Uses ioctl to get ip address directly from system.
700 #===============================================================================
701 sub get_ip {
702 my $ifreq= shift;
703 my $result= "";
704 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
705 my $proto= getprotobyname('ip');
707 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
708 or die "socket: $!";
710 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
711 my ($if, $sin) = unpack 'a16 a16', $ifreq;
712 my ($port, $addr) = sockaddr_in $sin;
713 my $ip = inet_ntoa $addr;
715 if ($ip && length($ip) > 0) {
716 $result = $ip;
717 }
718 }
720 return $result;
721 }
723 sub get_local_ip_for_remote_ip {
724 my $remote_ip= shift;
725 my $result="0.0.0.0";
727 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
728 if($remote_ip eq "127.0.0.1") {
729 $result = "127.0.0.1";
730 } else {
731 my $PROC_NET_ROUTE= ('/proc/net/route');
733 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
734 or die "Could not open $PROC_NET_ROUTE";
736 my @ifs = <PROC_NET_ROUTE>;
738 close(PROC_NET_ROUTE);
740 # Eat header line
741 shift @ifs;
742 chomp @ifs;
743 foreach my $line(@ifs) {
744 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
745 my $destination;
746 my $mask;
747 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
748 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
749 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
750 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
751 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
752 # destination matches route, save mac and exit
753 $result= &get_ip($Iface);
754 last;
755 }
756 }
757 }
758 } else {
759 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
760 }
761 return $result;
762 }
764 sub send_msg_to_target {
765 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
766 my $error = 0;
767 my $header;
768 my $new_status;
769 my $act_status;
770 my ($sql_statement, $res);
772 if( $msg_header ) {
773 $header = "'$msg_header'-";
774 }
775 else {
776 $header = "";
777 }
779 # Patch the source ip
780 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
781 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
782 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
783 }
785 # encrypt xml msg
786 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
788 # opensocket
789 my $socket = &open_socket($address);
790 if( !$socket ) {
791 daemon_log("ERROR: cannot send ".$header."msg to $address , host not reachable", 1);
792 $error++;
793 }
795 if( $error == 0 ) {
796 # send xml msg
797 print $socket $crypted_msg."\n";
799 daemon_log("INFO: send ".$header."msg to $address", 5);
800 daemon_log("message:\n$msg", 8);
802 }
804 # close socket in any case
805 if( $socket ) {
806 close $socket;
807 }
809 if( $error > 0 ) { $new_status = "down"; }
810 else { $new_status = $msg_header; }
813 # known_clients
814 $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
815 $res = $known_clients_db->select_dbentry($sql_statement);
816 if( keys(%$res) > 0) {
817 $act_status = $res->{1}->{'status'};
818 if( $act_status eq "down" ) {
819 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
820 $res = $known_clients_db->del_dbentry($sql_statement);
821 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
822 }
823 else {
824 $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
825 $res = $known_clients_db->update_dbentry($sql_statement);
826 if($new_status eq "down"){
827 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
828 }
829 else {
830 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
831 }
832 }
833 }
835 # known_server
836 $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
837 $res = $known_server_db->select_dbentry($sql_statement);
838 if( keys(%$res) > 0 ) {
839 $act_status = $res->{1}->{'status'};
840 if( $act_status eq "down" ) {
841 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
842 $res = $known_server_db->del_dbentry($sql_statement);
843 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
844 }
845 else {
846 $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
847 $res = $known_server_db->update_dbentry($sql_statement);
848 if($new_status eq "down"){
849 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
850 }
851 else {
852 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
853 }
854 }
855 }
856 return $error;
857 }
860 sub _start {
861 my ($kernel) = $_[KERNEL];
862 &trigger_db_loop($kernel);
863 }
866 sub client_input {
867 no strict "refs";
868 my ($kernel, $session, $heap,$input,$wheel) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
869 my $session_id = $session->ID;
870 my ($msg, $msg_hash, $module);
871 my $error = 0;
872 my $answer_l;
873 my ($answer_header, @answer_target_l, $answer_source);
874 my $client_answer;
876 daemon_log("INFO: Incoming msg from '".$heap->{'remote_ip'}."'", 5);
877 daemon_log("DEBUG: Incoming message:\n$input", 8);
879 ####################
880 # check incoming msg
881 # msg is from a new client or gosa
882 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
883 # msg is from a gosa-si-server or gosa-si-bus
884 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
885 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
886 }
887 # msg is from a gosa-si-client
888 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
889 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
890 }
891 # an error occurred
892 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
893 $error++;
894 }
896 ######################
897 # process incoming msg
898 if( $error == 0) {
899 daemon_log("DEBUG: Processing module ".$module, 7);
900 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
902 if ( 0 > @{$answer_l} ) {
903 my $answer_str = join("\n", @{$answer_l});
904 daemon_log("DEGUB: $module: Got answer from module: \n".$answer_str,8);
905 }
906 }
907 if( !$answer_l ) { $error++ };
909 ########
910 # answer
911 if( $error == 0 ) {
913 foreach my $answer ( @{$answer_l} ) {
914 # for each answer in answer list
916 # check outgoing msg to xml validity
917 my $answer_hash = &check_outgoing_xml_validity($answer);
918 if( not defined $answer_hash ) {
919 next;
920 }
922 $answer_header = @{$answer_hash->{'header'}}[0];
923 @answer_target_l = @{$answer_hash->{'target'}};
924 $answer_source = @{$answer_hash->{'source'}}[0];
926 # deliver msg to all targets
927 foreach my $answer_target ( @answer_target_l ) {
929 # targets of msg are all gosa-si-clients in known_clients_db
930 if( $answer_target eq "*" ) {
931 # answer is for all clients
932 my $sql_statement= "SELECT * FROM known_clients";
933 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
934 while( my ($hit_num, $hit) = each %{ $query_res } ) {
935 my $host_name = $hit->{hostname};
936 my $host_key = $hit->{hostkey};
937 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
938 }
939 }
941 # targets of msg are all gosa-si-server in known_server_db
942 elsif( $answer_target eq "KNOWN_SERVER" ) {
943 # answer is for all server in known_server
944 my $sql_statement= "SELECT * FROM known_server";
945 my $query_res = $known_server_db->select_dbentry( $sql_statement );
946 while( my ($hit_num, $hit) = each %{ $query_res } ) {
947 my $host_name = $hit->{hostname};
948 my $host_key = $hit->{hostkey};
949 $answer =~ s/KNOWN_SERVER/$host_name/g;
950 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
951 }
952 }
954 # target of msg is GOsa
955 elsif( $answer_target eq "GOSA" ) {
956 $answer =~ /<session_id>(\d+)<\/session_id>/;
957 my $session_id = $1;
958 my $add_on = "";
959 if( defined $session_id ) {
960 $add_on = ".session_id=$session_id";
961 }
962 # answer is for GOSA and has to returned to connected client
963 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
964 $client_answer = $gosa_answer.$add_on;
965 }
967 # target of msg is job queue at this host
968 elsif( $answer_target eq "JOBDB") {
969 $answer =~ /<header>(\S+)<\/header>/;
970 my $header;
971 if( defined $1 ) { $header = $1; }
972 &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header);
973 }
975 # target of msg is a mac address
976 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 ) {
977 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
978 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
979 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
980 my $found_ip_flag = 0;
981 while( my ($hit_num, $hit) = each %{ $query_res } ) {
982 my $host_name = $hit->{hostname};
983 my $host_key = $hit->{hostkey};
984 $answer =~ s/$answer_target/$host_name/g;
985 daemon_log("found host '$host_name', associated to '$answer_target'", 3);
986 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
987 $found_ip_flag++ ;
988 }
989 if( $found_ip_flag == 0) {
990 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target'", 3);
991 if( $bus_activ eq "true" ) {
992 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
993 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
994 my $query_res = $known_server_db->select_dbentry( $sql_statement );
995 while( my ($hit_num, $hit) = each %{ $query_res } ) {
996 my $bus_address = $hit->{hostname};
997 my $bus_key = $hit->{hostkey};
998 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
999 last;
1000 }
1001 }
1003 }
1005 # answer is for one specific host
1006 } else {
1007 # get encrypt_key
1008 my $encrypt_key = &get_encrypt_key($answer_target);
1009 if( not defined $encrypt_key ) {
1010 # unknown target, forward msg to bus
1011 daemon_log("WARNING: unknown target '$answer_target'", 3);
1012 if( $bus_activ eq "true" ) {
1013 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
1014 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
1015 my $query_res = $known_server_db->select_dbentry( $sql_statement );
1016 my $res_length = keys( %{$query_res} );
1017 if( $res_length == 0 ){
1018 daemon_log("WARNING: send '$answer_header' to '$bus_address' failed, no bus found in known_server", 3);
1019 }
1020 else {
1021 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1022 my $bus_key = $hit->{hostkey};
1023 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
1024 }
1025 }
1026 }
1027 next;
1028 }
1029 # send_msg
1030 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
1031 }
1032 }
1033 }
1034 }
1036 if( $client_answer ) {
1037 if( $client_answer =~ s/session_id=(\d+)$// ) {
1038 my $session_id = $1;
1039 if( defined $session_id ) {
1040 my $session_reference = $kernel->ID_id_to_session($session_id);
1041 $heap = $session_reference->get_heap();
1042 }
1043 }
1044 $heap->{client}->put($client_answer);
1045 }
1047 return;
1048 }
1052 sub trigger_db_loop {
1053 # my ($kernel) = $_[KERNEL];
1054 my ($kernel) = @_ ;
1055 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1056 }
1059 sub watch_for_new_jobs {
1060 my ($kernel,$heap) = @_[KERNEL, HEAP];
1062 # check gosa job queue for jobs with executable timestamp
1063 my $timestamp = &get_time();
1064 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
1065 " WHERE status='waiting' AND timestamp<'$timestamp'";
1066 my $res = $job_db->select_dbentry( $sql_statement );
1068 while( my ($id, $hit) = each %{$res} ) {
1069 my $jobdb_id = $hit->{id};
1070 my $macaddress = $hit->{'macaddress'};
1071 my $job_msg = $hit->{'xmlmessage'};
1072 my $header = $hit->{'headertag'};
1073 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1074 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1075 # expect macaddress is unique!!!!!!
1076 my $target = $res_hash->{1}->{hostname};
1078 if (not defined $target) {
1079 &daemon_log("ERROR: no host found for mac address: $macaddress", 1);
1080 &daemon_log("$hit->{xmlmessage}", 8);
1081 my $sql_statement = "UPDATE $job_queue_table_name ".
1082 "SET status='error', result='no host found for mac address' ".
1083 "WHERE id='$jobdb_id'";
1084 my $res = $job_db->update_dbentry($sql_statement);
1085 next;
1086 }
1088 # change header
1089 $job_msg =~ s/<header>job_/<header>gosa_/;
1091 # add sqlite_id
1092 $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1094 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header);
1095 }
1097 $kernel->delay_set('watch_for_new_jobs',3);
1098 }
1101 #==== MAIN = main ==============================================================
1102 # parse commandline options
1103 Getopt::Long::Configure( "bundling" );
1104 GetOptions("h|help" => \&usage,
1105 "c|config=s" => \$cfg_file,
1106 "f|foreground" => \$foreground,
1107 "v|verbose+" => \$verbose,
1108 "no-bus+" => \$no_bus,
1109 "no-arp+" => \$no_arp,
1110 );
1112 # read and set config parameters
1113 &check_cmdline_param ;
1114 &read_configfile;
1115 &check_pid;
1117 $SIG{CHLD} = 'IGNORE';
1119 # forward error messages to logfile
1120 if( ! $foreground ) {
1121 open(STDERR, '>>', $log_file);
1122 open(STDOUT, '>>', $log_file);
1123 }
1125 # Just fork, if we are not in foreground mode
1126 if( ! $foreground ) {
1127 chdir '/' or die "Can't chdir to /: $!";
1128 $pid = fork;
1129 setsid or die "Can't start a new session: $!";
1130 umask 0;
1131 } else {
1132 $pid = $$;
1133 }
1135 # Do something useful - put our PID into the pid_file
1136 if( 0 != $pid ) {
1137 open( LOCK_FILE, ">$pid_file" );
1138 print LOCK_FILE "$pid\n";
1139 close( LOCK_FILE );
1140 if( !$foreground ) {
1141 exit( 0 )
1142 };
1143 }
1145 daemon_log(" ", 1);
1146 daemon_log("$0 started!", 1);
1148 if ($no_bus > 0) {
1149 $bus_activ = "false"
1150 }
1154 # delete old DBsqlite lock files
1155 #unlink('/tmp/gosa_si_lock*');
1157 # connect to gosa-si job queue
1158 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "progress", "headertag", "targettag", "xmlmessage", "macaddress");
1159 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1160 $job_db->create_table('jobs', \@job_col_names);
1162 # connect to known_clients_db
1163 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events', 'login');
1164 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1165 $known_clients_db->create_table('known_clients', \@clients_col_names);
1167 # connect to known_server_db
1168 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1169 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1170 $known_server_db->create_table('known_server', \@server_col_names);
1172 # create xml object used for en/decrypting
1173 $xml = new XML::Simple();
1175 # create socket for incoming xml messages
1176 POE::Component::Server::TCP->new(
1177 Port => $server_port,
1178 ClientInput => \&client_input,
1179 );
1180 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1182 # create session for repeatedly checking the job queue for jobs
1183 POE::Session->create(
1184 inline_states => {
1185 _start => \&_start,
1186 watch_for_new_jobs => \&watch_for_new_jobs,
1187 }
1188 );
1191 # import all modules
1192 &import_modules;
1194 # check wether all modules are gosa-si valid passwd check
1196 POE::Kernel->run();
1197 exit;