39fe6f815f4e581ff0eaa7c0018204a92aa4ed0f
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;
29 use Fcntl;
30 use IO::Socket::INET;
31 use IO::Handle;
32 use IO::Select;
33 use Symbol qw(qualify_to_ref);
34 use Crypt::Rijndael;
35 use MIME::Base64;
36 use Digest::MD5 qw(md5 md5_hex md5_base64);
37 use XML::Simple;
38 use Data::Dumper;
39 use Sys::Syslog qw( :DEFAULT setlogsock);
40 use Cwd;
41 use File::Spec;
42 use GOSA::DBsqlite;
43 use POE qw(Component::Server::TCP);
45 my $modules_path = "/usr/lib/gosa-si/modules";
46 use lib "/usr/lib/gosa-si/modules";
48 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
49 my ($bus, $msg_to_bus, $bus_cipher);
50 my ($server, $server_mac_address, $server_events);
51 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
52 my ($known_modules, $known_clients_file_name, $known_server_file_name);
53 my ($max_clients);
54 my ($pid_file, $procid, $pid, $log_file);
55 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
56 my ($arp_activ, $arp_fifo, $arp_fifo_path);
57 my ($xml);
59 # variables declared in config file are always set to 'our'
60 our (%cfg_defaults, $log_file, $pid_file,
61 $bus_activ, $bus_key, $bus_ip, $bus_port,
62 $server_activ, $server_ip, $server_port, $SIPackages_key, $max_clients,
63 $arp_activ, $arp_fifo_path,
64 $gosa_activ, $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;
88 $no_arp = 0;
90 # name of table for storing gosa jobs
91 our $job_queue_table_name = 'jobs';
92 our $job_db;
94 # holds all other gosa-sd as well as the gosa-sd-bus
95 our $known_server_db;
97 # holds all registrated clients
98 our $known_clients_db;
100 %cfg_defaults =
101 ("general" =>
102 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
103 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
104 "child_max" => [\$child_max, 10],
105 "child_min" => [\$child_min, 3],
106 "child_timeout" => [\$child_timeout, 180],
107 "job_queue_timeout" => [\$job_queue_timeout, undef],
108 "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/gosa-si-server_jobs.db'],
109 "job_queue_loop_delay" => [\$job_queue_loop_delay, 3],
110 "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/gosa-si-server_known_clients.db' ],
111 "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/gosa-si-server_known_server.db'],
112 },
113 "bus" =>
114 {"bus_activ" => [\$bus_activ, "on"],
115 "bus_passwd" => [\$bus_key, ""],
116 "bus_ip" => [\$bus_ip, "0.0.0.0"],
117 "bus_port" => [\$bus_port, "20080"],
118 },
119 "server" =>
120 {"server_activ" => [\$server_activ, "on"],
121 "server_ip" => [\$server_ip, "0.0.0.0"],
122 "server_port" => [\$server_port, "20081"],
123 "SIPackages_key" => [\$SIPackages_key, "none"],
124 "max_clients" => [\$max_clients, 100],
125 },
126 "arp" =>
127 {"arp_activ" => [\$arp_activ, "on"],
128 "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
129 },
130 "gosa" =>
131 {"gosa_activ" => [\$gosa_activ, "on"],
132 "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
133 "gosa_port" => [\$gosa_port, "20082"],
134 "GosaPackages_key" => [\$GosaPackages_key, "none"],
135 },
136 );
139 #=== FUNCTION ================================================================
140 # NAME: usage
141 # PARAMETERS: nothing
142 # RETURNS: nothing
143 # DESCRIPTION: print out usage text to STDERR
144 #===============================================================================
145 sub usage {
146 print STDERR << "EOF" ;
147 usage: $0 [-hvf] [-c config]
149 -h : this (help) message
150 -c <file> : config file
151 -f : foreground, process will not be forked to background
152 -v : be verbose (multiple to increase verbosity)
153 -no-bus : starts $0 without connection to bus
154 -no-arp : starts $0 without connection to arp module
156 EOF
157 print "\n" ;
158 }
161 #=== FUNCTION ================================================================
162 # NAME: read_configfile
163 # PARAMETERS: cfg_file - string -
164 # RETURNS: nothing
165 # DESCRIPTION: read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168 my $cfg;
169 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
170 if( -r $cfg_file ) {
171 $cfg = Config::IniFiles->new( -file => $cfg_file );
172 } else {
173 print STDERR "Couldn't read config file!\n";
174 }
175 } else {
176 $cfg = Config::IniFiles->new() ;
177 }
178 foreach my $section (keys %cfg_defaults) {
179 foreach my $param (keys %{$cfg_defaults{ $section }}) {
180 my $pinfo = $cfg_defaults{ $section }{ $param };
181 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
182 }
183 }
184 }
187 #=== FUNCTION ================================================================
188 # NAME: logging
189 # PARAMETERS: level - string - default 'info'
190 # msg - string -
191 # facility - string - default 'LOG_DAEMON'
192 # RETURNS: nothing
193 # DESCRIPTION: function for logging
194 #===============================================================================
195 sub daemon_log {
196 # log into log_file
197 my( $msg, $level ) = @_;
198 if(not defined $msg) { return }
199 if(not defined $level) { $level = 1 }
200 if(defined $log_file){
201 open(LOG_HANDLE, ">>$log_file");
202 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
203 print STDERR "cannot open $log_file: $!";
204 return }
205 chomp($msg);
206 if($level <= $verbose){
207 my ($seconds, $minutes, $hours, $monthday, $month,
208 $year, $weekday, $yearday, $sommertime) = localtime(time);
209 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
210 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
211 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
212 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
213 $month = $monthnames[$month];
214 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
215 $year+=1900;
216 my $name = $0;
217 $name =~ s/\.\///;
219 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
220 print LOG_HANDLE $log_msg;
221 if( $foreground ) {
222 print STDERR $log_msg;
223 }
224 }
225 close( LOG_HANDLE );
226 }
227 #log into syslog
228 # my ($msg, $level, $facility) = @_;
229 # if(not defined $msg) {return}
230 # if(not defined $level) {$level = "info"}
231 # if(not defined $facility) {$facility = "LOG_DAEMON"}
232 # openlog($0, "pid,cons,", $facility);
233 # syslog($level, $msg);
234 # closelog;
235 # return;
236 }
239 sub get_time {
240 my ($seconds, $minutes, $hours, $monthday, $month,
241 $year, $weekday, $yearday, $sommertime) = localtime(time);
242 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
243 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
244 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
245 $month+=1;
246 $month = $month < 10 ? $month = "0".$month : $month;
247 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
248 $year+=1900;
249 return "$year$month$monthday$hours$minutes$seconds";
251 }
254 #=== FUNCTION ================================================================
255 # NAME: check_cmdline_param
256 # PARAMETERS: nothing
257 # RETURNS: nothing
258 # DESCRIPTION: validates commandline parameter
259 #===============================================================================
260 sub check_cmdline_param () {
261 my $err_config;
262 my $err_counter = 0;
263 if(not defined($cfg_file)) {
264 $cfg_file = "/etc/gosa-si/server.conf";
265 if(! -r $cfg_file) {
266 $err_config = "please specify a config file";
267 $err_counter += 1;
268 }
269 }
270 if( $err_counter > 0 ) {
271 &usage( "", 1 );
272 if( defined( $err_config)) { print STDERR "$err_config\n"}
273 print STDERR "\n";
274 exit( -1 );
275 }
276 }
279 #=== FUNCTION ================================================================
280 # NAME: check_pid
281 # PARAMETERS: nothing
282 # RETURNS: nothing
283 # DESCRIPTION: handels pid processing
284 #===============================================================================
285 sub check_pid {
286 $pid = -1;
287 # Check, if we are already running
288 if( open(LOCK_FILE, "<$pid_file") ) {
289 $pid = <LOCK_FILE>;
290 if( defined $pid ) {
291 chomp( $pid );
292 if( -f "/proc/$pid/stat" ) {
293 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
294 if( $0 eq $stat ) {
295 close( LOCK_FILE );
296 exit -1;
297 }
298 }
299 }
300 close( LOCK_FILE );
301 unlink( $pid_file );
302 }
304 # create a syslog msg if it is not to possible to open PID file
305 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
306 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
307 if (open(LOCK_FILE, '<', $pid_file)
308 && ($pid = <LOCK_FILE>))
309 {
310 chomp($pid);
311 $msg .= "(PID $pid)\n";
312 } else {
313 $msg .= "(unable to read PID)\n";
314 }
315 if( ! ($foreground) ) {
316 openlog( $0, "cons,pid", "daemon" );
317 syslog( "warning", $msg );
318 closelog();
319 }
320 else {
321 print( STDERR " $msg " );
322 }
323 exit( -1 );
324 }
325 }
327 #=== FUNCTION ================================================================
328 # NAME: import_modules
329 # PARAMETERS: module_path - string - abs. path to the directory the modules
330 # are stored
331 # RETURNS: nothing
332 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
333 # state is on is imported by "require 'file';"
334 #===============================================================================
335 sub import_modules {
336 daemon_log(" ", 1);
338 if (not -e $modules_path) {
339 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
340 }
342 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
343 while (defined (my $file = readdir (DIR))) {
344 if (not $file =~ /(\S*?).pm$/) {
345 next;
346 }
347 my $mod_name = $1;
349 if( $file =~ /ArpHandler.pm/ ) {
350 if( $no_arp > 0 ) {
351 next;
352 }
353 }
355 eval { require $file; };
356 if ($@) {
357 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
358 daemon_log("$@", 5);
359 } else {
360 my $info = eval($mod_name.'::get_module_info()');
361 # Only load module if get_module_info() returns a non-null object
362 if( $info ) {
363 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
364 $known_modules->{$mod_name} = $info;
365 daemon_log("module $mod_name loaded", 1);
366 }
367 }
368 }
369 close (DIR);
370 }
373 #=== FUNCTION ================================================================
374 # NAME: sig_int_handler
375 # PARAMETERS: signal - string - signal arose from system
376 # RETURNS: noting
377 # DESCRIPTION: handels tasks to be done befor signal becomes active
378 #===============================================================================
379 sub sig_int_handler {
380 my ($signal) = @_;
382 daemon_log("shutting down gosa-si-server", 1);
383 exit(1);
384 }
385 $SIG{INT} = \&sig_int_handler;
389 sub check_key_and_xml_validity {
390 my ($crypted_msg, $module_key) = @_;
391 #print STDERR "crypted_msg:$crypted_msg\n";
392 #print STDERR "modul_key:$module_key\n";
394 my $msg;
395 my $msg_hash;
396 eval{
397 $msg = &decrypt_msg($crypted_msg, $module_key);
398 &main::daemon_log("decrypted_msg: \n$msg", 8);
400 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
402 # check header
403 my $header_l = $msg_hash->{'header'};
404 if( 1 != @{$header_l} ) {
405 die'header error';
406 }
407 my $header = @{$header_l}[0];
408 if( 0 == length $header) {
409 die 'header error';
410 }
412 # check source
413 my $source_l = $msg_hash->{'source'};
414 if( 1 != @{$source_l} ) {
415 die'source error';
416 }
417 my $source = @{$source_l}[0];
418 if( 0 == length $source) {
419 die 'source error';
420 }
422 # check target
423 my $target_l = $msg_hash->{'target'};
424 if( 1 != @{$target_l} ) {
425 die'target error';
426 }
427 my $target = @{$target_l}[0];
428 if( 0 == length $target) {
429 die 'target error';
430 }
432 };
433 if($@) {
434 &main::daemon_log("WARNING: do not understand the message", 5);
435 &main::daemon_log("$@", 8);
436 }
438 return ($msg, $msg_hash);
439 }
442 sub input_from_known_server {
443 my ($input, $remote_ip) = @_ ;
444 my ($msg, $msg_hash, $module);
446 my $sql_statement= "SELECT * FROM known_server";
447 my $query_res = $known_server_db->select_dbentry( $sql_statement );
449 while( my ($hit_num, $hit) = each %{ $query_res } ) {
450 my $host_name = $hit->{hostname};
451 if( not $host_name =~ "^$remote_ip") {
452 next;
453 }
454 my $host_key = $hit->{hostkey};
455 daemon_log("SIPackages: known_server host_name: $host_name", 7);
456 daemon_log("SIPackages: known_server host_key: $host_key", 7);
458 # check if module can open msg envelope with module key
459 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
460 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
461 daemon_log("SIPackages: deciphering raise error", 7);
462 daemon_log("$@", 8);
463 next;
464 }
465 else {
466 $msg = $tmp_msg;
467 $msg_hash = $tmp_msg_hash;
468 $module = "SIPackages";
469 last;
470 }
471 }
473 if( (!$msg) || (!$msg_hash) || (!$module) ) {
474 daemon_log("Incoming message is not from a known server", 3);
475 }
477 return ($msg, $msg_hash, $module);
478 }
481 sub input_from_known_client {
482 my ($input, $remote_ip) = @_ ;
483 my ($msg, $msg_hash, $module);
485 my $sql_statement= "SELECT * FROM known_clients";
486 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
487 while( my ($hit_num, $hit) = each %{ $query_res } ) {
488 my $host_name = $hit->{hostname};
489 if( not $host_name =~ /^$remote_ip:\d*$/) {
490 next;
491 }
492 my $host_key = $hit->{hostkey};
493 &daemon_log("SIPackages: known_client host_name: $host_name", 7);
494 &daemon_log("SIPackages: known_client host_key: $host_key", 7);
496 # check if module can open msg envelope with module key
497 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
499 if( (!$msg) || (!$msg_hash) ) {
500 &daemon_log("SIPackages: deciphering raise error", 7);
501 &daemon_log("$@", 8);
502 next;
503 }
504 else {
505 $module = "SIPackages";
506 last;
507 }
508 }
510 if( (!$msg) || (!$msg_hash) || (!$module) ) {
511 &daemon_log("Incoming message is not from a known client", 3);
512 }
514 return ($msg, $msg_hash, $module);
515 }
518 sub input_from_unknown_host {
519 no strict "refs";
520 my ($input) = @_ ;
521 my ($msg, $msg_hash, $module);
523 my %act_modules = %$known_modules;
525 while( my ($mod, $info) = each(%act_modules)) {
526 # check a key exists for this module
527 my $module_key = ${$mod."_key"};
528 if( ! $module_key ) {
529 daemon_log("ERROR: no key specified in config file for $mod", 1);
530 next;
531 }
532 daemon_log("$mod: $module_key", 5);
534 # check if module can open msg envelope with module key
535 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
536 if( (!$msg) || (!$msg_hash) ) {
537 #daemon_log("$mod: deciphering failed", 5);
538 next;
539 }
540 else {
541 $module = $mod;
542 last;
543 }
544 }
546 if( (!$msg) || (!$msg_hash) || (!$module)) {
547 daemon_log("Incoming message is not from a unknown host", 5);
548 }
550 return ($msg, $msg_hash, $module);
551 }
553 sub create_ciphering {
554 my ($passwd) = @_;
555 if((!defined($passwd)) || length($passwd)==0) {
556 $passwd = "";
557 }
558 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
559 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
560 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
561 $my_cipher->set_iv($iv);
562 return $my_cipher;
563 }
566 sub encrypt_msg {
567 my ($msg, $key) = @_;
568 my $my_cipher = &create_ciphering($key);
569 {
570 use bytes;
571 $msg = "\0"x(16-length($msg)%16).$msg;
572 }
573 $msg = $my_cipher->encrypt($msg);
574 chomp($msg = &encode_base64($msg));
575 # there are no newlines allowed inside msg
576 $msg=~ s/\n//g;
577 return $msg;
578 }
581 sub decrypt_msg {
582 my ($msg, $key) = @_ ;
583 $msg = &decode_base64($msg);
584 my $my_cipher = &create_ciphering($key);
585 $msg = $my_cipher->decrypt($msg);
586 $msg =~ s/\0*//g;
587 return $msg;
588 }
591 sub get_encrypt_key {
592 my ($target) = @_ ;
593 my $encrypt_key;
594 my $error = 0;
596 # target can be in known_server
597 if( !$encrypt_key ) {
598 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
599 my $query_res = $known_server_db->select_dbentry( $sql_statement );
600 while( my ($hit_num, $hit) = each %{ $query_res } ) {
601 my $host_name = $hit->{hostname};
602 if( $host_name ne $target ) {
603 next;
604 }
605 $encrypt_key = $hit->{hostkey};
606 last;
607 }
608 }
611 # target can be in known_client
612 if( !$encrypt_key ) {
613 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
614 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
615 while( my ($hit_num, $hit) = each %{ $query_res } ) {
616 my $host_name = $hit->{hostname};
617 if( $host_name ne $target ) {
618 next;
619 }
620 $encrypt_key = $hit->{hostkey};
621 last;
622 }
623 }
625 return $encrypt_key;
626 }
629 #=== FUNCTION ================================================================
630 # NAME: open_socket
631 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
632 # [PeerPort] string necessary if port not appended by PeerAddr
633 # RETURNS: socket IO::Socket::INET
634 # DESCRIPTION: open a socket to PeerAddr
635 #===============================================================================
636 sub open_socket {
637 my ($PeerAddr, $PeerPort) = @_ ;
638 if(defined($PeerPort)){
639 $PeerAddr = $PeerAddr.":".$PeerPort;
640 }
641 my $socket;
642 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
643 Porto => "tcp",
644 Type => SOCK_STREAM,
645 Timeout => 5,
646 );
647 if(not defined $socket) {
648 return;
649 }
650 &daemon_log("open_socket: $PeerAddr", 7);
651 return $socket;
652 }
655 #=== FUNCTION ================================================================
656 # NAME: get_ip
657 # PARAMETERS: interface name (i.e. eth0)
658 # RETURNS: (ip address)
659 # DESCRIPTION: Uses ioctl to get ip address directly from system.
660 #===============================================================================
661 sub get_ip {
662 my $ifreq= shift;
663 my $result= "";
664 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
665 my $proto= getprotobyname('ip');
667 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
668 or die "socket: $!";
670 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
671 my ($if, $sin) = unpack 'a16 a16', $ifreq;
672 my ($port, $addr) = sockaddr_in $sin;
673 my $ip = inet_ntoa $addr;
675 if ($ip && length($ip) > 0) {
676 $result = $ip;
677 }
678 }
680 return $result;
681 }
683 sub get_local_ip_for_remote_ip {
684 my $remote_ip= shift;
685 my $result="0.0.0.0";
687 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
688 if($remote_ip eq "127.0.0.1") {
689 $result = "127.0.0.1";
690 } else {
691 my $PROC_NET_ROUTE= ('/proc/net/route');
693 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
694 or die "Could not open $PROC_NET_ROUTE";
696 my @ifs = <PROC_NET_ROUTE>;
698 close(PROC_NET_ROUTE);
700 # Eat header line
701 shift @ifs;
702 chomp @ifs;
703 foreach my $line(@ifs) {
704 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
705 my $destination;
706 my $mask;
707 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
708 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
709 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
710 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
711 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
712 # destination matches route, save mac and exit
713 $result= &get_ip($Iface);
714 last;
715 }
716 }
717 }
718 } else {
719 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
720 }
721 return $result;
722 }
724 sub send_msg_to_target {
725 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
726 my $error = 0;
727 my $header;
728 my $new_status;
729 my $act_status;
730 my ($sql_statement, $res);
732 if( $msg_header ) {
733 $header = "'$msg_header'-";
734 }
735 else {
736 $header = "";
737 }
739 # Patch the source ip
740 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
741 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
742 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
743 }
745 # encrypt xml msg
746 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
748 # opensocket
749 my $socket = &open_socket($address);
750 if( !$socket ) {
751 daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
752 $error++;
753 }
755 if( $error == 0 ) {
756 # send xml msg
757 print $socket $crypted_msg."\n";
759 daemon_log("send ".$header."msg to $address", 1);
760 daemon_log("message:\n$msg", 8);
762 }
764 # close socket in any case
765 if( $socket ) {
766 close $socket;
767 }
769 if( $error > 0 ) { $new_status = "down"; }
770 else { $new_status = $msg_header; }
773 # known_clients
774 $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
775 $res = $known_clients_db->select_dbentry($sql_statement);
776 if( keys(%$res) > 0) {
777 $act_status = $res->{1}->{'status'};
778 if( $act_status eq "down" ) {
779 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
780 $res = $known_clients_db->del_dbentry($sql_statement);
781 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
782 }
783 else {
784 $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
785 $res = $known_clients_db->update_dbentry($sql_statement);
786 if($new_status eq "down"){
787 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
788 }
789 else {
790 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
791 }
792 }
793 }
795 # known_server
796 $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
797 $res = $known_server_db->select_dbentry($sql_statement);
798 if( keys(%$res) > 0 ) {
799 $act_status = $res->{1}->{'status'};
800 if( $act_status eq "down" ) {
801 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
802 $res = $known_clients_db->del_dbentry($sql_statement);
803 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
804 }
805 else {
806 $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
807 $res = $known_server_db->update_dbentry($sql_statement);
808 if($new_status eq "down"){
809 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
810 }
811 else {
812 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
813 }
814 }
815 }
817 return;
818 }
821 sub _start {
822 my ($kernel) = $_[KERNEL];
823 &trigger_db_loop($kernel);
824 }
827 sub client_input {
828 no strict "refs";
829 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
830 my ($msg, $msg_hash, $module);
831 my $error = 0;
832 my $answer_l;
833 my ($answer_header, @answer_target_l, $answer_source);
834 my $client_answer;
836 daemon_log("Incoming msg from '".$heap->{'remote_ip'}."'", 7);
837 daemon_log("\n$input", 8);
839 # msg is from a new client or gosa
840 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
842 # msg is from a gosa-si-server or gosa-si-bus
843 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
844 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
845 }
847 # msg is from a gosa-si-client
848 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
849 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
850 }
852 # an error occurred
853 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
854 $error++;
855 }
857 ######################
858 # process incoming msg
859 if( $error == 0) {
860 daemon_log("Processing module ".$module, 5);
861 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $heap->{'remote_ip'});
863 if ( 0 > @{$answer_l} ) {
864 my $answer_str = join("\n", @{$answer_l});
865 daemon_log("$module: Got answer from module: \n".$answer_str,8);
866 }
867 }
868 if( !$answer_l ) { $error++ };
870 ########
871 # answer
872 if( $error == 0 ) {
874 # for each answer in answer list
875 foreach my $answer ( @{$answer_l} ) {
877 my $error = 0;
878 # check answer if gosa-si envelope conform
879 if(defined($answer)) {
880 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
881 $answer_header = @{$answer_hash->{'header'}}[0];
882 @answer_target_l = @{$answer_hash->{'target'}};
883 $answer_source = @{$answer_hash->{'source'}}[0];
884 if( !$answer_header ) {
885 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
886 daemon_log("\n$answer", 8);
887 $error++;
888 }
889 if( 0 == length @answer_target_l ) {
890 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
891 daemon_log("\n$answer", 8);
892 $error++;
893 }
894 if( !$answer_source ) {
895 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
896 daemon_log("\n$answer", 8);
897 $error++;
898 }
900 if( $error != 0 ) {
901 next;
902 }
903 }
905 # deliver msg to all targets
906 foreach my $answer_target ( @answer_target_l ) {
907 if( $answer_target eq "*" ) {
908 # answer is for all clients
909 my $sql_statement= "SELECT * FROM known_clients";
910 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
911 while( my ($hit_num, $hit) = each %{ $query_res } ) {
912 my $host_name = $hit->{hostname};
913 my $host_key = $hit->{hostkey};
914 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
915 }
916 }
917 elsif( $answer_target eq "GOSA" ) {
918 # answer is for GOSA and has to returned to connected client
919 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
920 $client_answer = $gosa_answer;
921 }
922 elsif( $answer_target eq "KNOWN_SERVER" ) {
923 # answer is for all server in known_server
924 my $sql_statement= "SELECT * FROM known_server";
925 my $query_res = $known_server_db->select_dbentry( $sql_statement );
926 while( my ($hit_num, $hit) = each %{ $query_res } ) {
927 my $host_name = $hit->{hostname};
928 my $host_key = $hit->{hostkey};
929 $answer =~ s/KNOWN_SERVER/$host_name/g;
930 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
931 }
932 }
933 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})/ ) {
934 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
935 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
936 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
937 my $found_ip_flag = 0;
938 while( my ($hit_num, $hit) = each %{ $query_res } ) {
939 my $host_name = $hit->{hostname};
940 my $host_key = $hit->{hostkey};
941 $answer =~ s/$answer_target/$host_name/g;
942 daemon_log("found host '$host_name', assoziated to '$answer_target'", 3);
943 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
944 $found_ip_flag++ ;
945 }
946 if( $found_ip_flag == 0) {
947 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target', forward msg to bus", 1);
948 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
949 my $query_res = $known_server_db->select_dbentry( $sql_statement );
950 while( my ($hit_num, $hit) = each %{ $query_res } ) {
951 my $bus_address = $hit->{hostname};
952 my $bus_key = $hit->{hostkey};
953 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
954 last;
955 }
957 }
958 }
959 else {
960 # answer is for one specific host
961 # get encrypt_key
962 my $encrypt_key = &get_encrypt_key($answer_target);
963 if( !$encrypt_key ) {
964 # unknown target, forward msg to bus
965 daemon_log("WARNING: unknown target '$answer_target', forward msg to bus", 3);
966 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
967 my $query_res = $known_server_db->select_dbentry( $sql_statement );
968 my $bus_key = $query_res->{1}->{hostkey};
969 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
970 next;
971 }
972 # send_msg
973 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
974 }
975 }
976 }
977 }
979 if( $client_answer ) {
980 $heap->{client}->put($client_answer);
981 }
983 return;
984 }
988 sub trigger_db_loop {
989 # my ($kernel) = $_[KERNEL];
990 my ($kernel) = @_ ;
991 $kernel->delay_set('watch_for_new_jobs',3);
992 }
995 sub watch_for_new_jobs {
996 my ($kernel,$heap) = @_[KERNEL, HEAP];
998 # check gosa job queue for jobs with executable timestamp
999 my $timestamp = &get_time();
1001 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
1002 " WHERE status='waiting' AND timestamp<'$timestamp'";
1004 my $res = $job_db->select_dbentry( $sql_statement );
1006 while( my ($id, $hit) = each %{$res} ) {
1008 my $jobdb_id = $hit->{id};
1009 my $macaddress = $hit->{macaddress};
1010 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1011 my $out_msg_hash = $job_msg_hash;
1012 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1013 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1014 # expect macaddress is unique!!!!!!
1015 my $target = $res_hash->{1}->{hostname};
1017 if (not defined $target) {
1018 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1019 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1020 my $sql_statement = "UPDATE $job_queue_table_name ".
1021 "SET status='error', result='no host found for mac address' ".
1022 "WHERE id='$jobdb_id'";
1023 my $res = $job_db->update_dbentry($sql_statement);
1024 next;
1025 }
1027 # add target
1028 &add_content2xml_hash($out_msg_hash, "target", $target);
1030 # add new header
1031 my $out_header = $job_msg_hash->{header}[0];
1032 $out_header =~ s/job_/gosa_/;
1033 delete $out_msg_hash->{header};
1034 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1036 # add sqlite_id
1037 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1039 my $out_msg = &create_xml_string($out_msg_hash);
1041 # encrypt msg as a GosaPackage module
1042 my $cipher = &create_ciphering($GosaPackages_key);
1043 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1045 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
1047 if ($error == 0) {
1048 my $sql_statement = "UPDATE $job_queue_table_name ".
1049 "SET status='processing', targettag='$target' ".
1050 "WHERE id='$jobdb_id'";
1051 my $res = $job_db->update_dbentry($sql_statement);
1052 } else {
1053 my $sql_statement = "UPDATE $job_queue_table_name ".
1054 "SET status='error' ".
1055 "WHERE id='$jobdb_id'";
1056 my $res = $job_db->update_dbentry($sql_statement);
1057 }
1058 }
1060 $kernel->delay_set('watch_for_new_jobs',3);
1061 }
1064 #==== MAIN = main ==============================================================
1065 # parse commandline options
1066 Getopt::Long::Configure( "bundling" );
1067 GetOptions("h|help" => \&usage,
1068 "c|config=s" => \$cfg_file,
1069 "f|foreground" => \$foreground,
1070 "v|verbose+" => \$verbose,
1071 "no-bus+" => \$no_bus,
1072 "no-arp+" => \$no_arp,
1073 );
1075 # read and set config parameters
1076 &check_cmdline_param ;
1077 &read_configfile;
1078 &check_pid;
1080 $SIG{CHLD} = 'IGNORE';
1082 # forward error messages to logfile
1083 if( ! $foreground ) {
1084 open(STDERR, '>>', $log_file);
1085 open(STDOUT, '>>', $log_file);
1086 }
1088 # Just fork, if we are not in foreground mode
1089 if( ! $foreground ) {
1090 chdir '/' or die "Can't chdir to /: $!";
1091 $pid = fork;
1092 setsid or die "Can't start a new session: $!";
1093 umask 0;
1094 } else {
1095 $pid = $$;
1096 }
1098 # Do something useful - put our PID into the pid_file
1099 if( 0 != $pid ) {
1100 open( LOCK_FILE, ">$pid_file" );
1101 print LOCK_FILE "$pid\n";
1102 close( LOCK_FILE );
1103 if( !$foreground ) {
1104 exit( 0 )
1105 };
1106 }
1108 daemon_log(" ", 1);
1109 daemon_log("$0 started!", 1);
1111 # delete old DBsqlite lock files
1112 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
1114 # connect to gosa-si job queue
1115 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1116 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1117 $job_db->create_table('jobs', \@job_col_names);
1119 # connect to known_clients_db
1120 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1121 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1122 $known_clients_db->create_table('known_clients', \@clients_col_names);
1124 # connect to known_server_db
1125 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1126 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1127 $known_server_db->create_table('known_server', \@server_col_names);
1129 # create xml object used for en/decrypting
1130 $xml = new XML::Simple();
1132 # create socket for incoming xml messages
1133 POE::Component::Server::TCP->new(
1134 Port => $server_port,
1135 ClientInput => \&client_input,
1136 );
1137 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1139 # create session for repeatedly checking the job queue for jobs
1140 POE::Session->create(
1141 inline_states => {
1142 _start => \&_start,
1143 watch_for_new_jobs => \&watch_for_new_jobs,
1144 }
1145 );
1148 # import all modules
1149 &import_modules;
1151 # check wether all modules are gosa-si valid passwd check
1153 POE::Kernel->run();
1154 exit;