04063e6f320286aeca851f38587d2fa843824c3a
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_activ, $bus, $msg_to_bus, $bus_cipher);
50 my ($server, $server_mac_address);
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 ($pid_file, $procid, $pid, $log_file);
54 my ($arp_activ, $arp_fifo);
55 my ($xml);
57 # variables declared in config file are always set to 'our'
58 our (%cfg_defaults, $log_file, $pid_file,
59 $server_ip, $server_port, $SIPackages_key,
60 $arp_activ,
61 $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
62 );
64 # additional variable which should be globaly accessable
65 our $server_address;
66 our $bus_address;
67 our $gosa_address;
68 our $no_bus;
69 our $no_arp;
70 our $verbose;
71 our $forground;
72 our $cfg_file;
74 # specifies the verbosity of the daemon_log
75 $verbose = 0 ;
77 # if foreground is not null, script will be not forked to background
78 $foreground = 0 ;
80 # specifies the timeout seconds while checking the online status of a registrating client
81 $ping_timeout = 5;
83 $no_bus = 0;
84 $bus_activ = "true";
86 $no_arp = 0;
88 # name of table for storing gosa jobs
89 our $job_queue_table_name = 'jobs';
90 our $job_db;
92 # holds all other gosa-sd as well as the gosa-sd-bus
93 our $known_server_db;
95 # holds all registrated clients
96 our $known_clients_db;
98 %cfg_defaults = (
99 "general" => {
100 "log-file" => [\$log_file, "/var/run/".$0.".log"],
101 "pid-file" => [\$pid_file, "/var/run/".$0.".pid"],
102 },
103 "bus" => {
104 "activ" => [\$bus_activ, "true"],
105 },
106 "server" => {
107 # "ip" => [\$server_ip, "0.0.0.0"],
108 "port" => [\$server_port, "20081"],
109 "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
110 "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
111 },
112 "GOsaPackages" => {
113 "ip" => [\$gosa_ip, "0.0.0.0"],
114 "port" => [\$gosa_port, "20082"],
115 "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
116 "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
117 "key" => [\$GosaPackages_key, "none"],
118 },
119 "SIPackages" => {
120 "key" => [\$SIPackages_key, "none"],
121 },
122 );
125 #=== FUNCTION ================================================================
126 # NAME: usage
127 # PARAMETERS: nothing
128 # RETURNS: nothing
129 # DESCRIPTION: print out usage text to STDERR
130 #===============================================================================
131 sub usage {
132 print STDERR << "EOF" ;
133 usage: $0 [-hvf] [-c config]
135 -h : this (help) message
136 -c <file> : config file
137 -f : foreground, process will not be forked to background
138 -v : be verbose (multiple to increase verbosity)
139 -no-bus : starts $0 without connection to bus
140 -no-arp : starts $0 without connection to arp module
142 EOF
143 print "\n" ;
144 }
147 #=== FUNCTION ================================================================
148 # NAME: read_configfile
149 # PARAMETERS: cfg_file - string -
150 # RETURNS: nothing
151 # DESCRIPTION: read cfg_file and set variables
152 #===============================================================================
153 sub read_configfile {
154 my $cfg;
155 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
156 if( -r $cfg_file ) {
157 $cfg = Config::IniFiles->new( -file => $cfg_file );
158 } else {
159 print STDERR "Couldn't read config file!\n";
160 }
161 } else {
162 $cfg = Config::IniFiles->new() ;
163 }
164 foreach my $section (keys %cfg_defaults) {
165 foreach my $param (keys %{$cfg_defaults{ $section }}) {
166 my $pinfo = $cfg_defaults{ $section }{ $param };
167 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
168 }
169 }
170 }
173 #=== FUNCTION ================================================================
174 # NAME: logging
175 # PARAMETERS: level - string - default 'info'
176 # msg - string -
177 # facility - string - default 'LOG_DAEMON'
178 # RETURNS: nothing
179 # DESCRIPTION: function for logging
180 #===============================================================================
181 sub daemon_log {
182 # log into log_file
183 my( $msg, $level ) = @_;
184 if(not defined $msg) { return }
185 if(not defined $level) { $level = 1 }
186 if(defined $log_file){
187 open(LOG_HANDLE, ">>$log_file");
188 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
189 print STDERR "cannot open $log_file: $!";
190 return }
191 chomp($msg);
192 if($level <= $verbose){
193 my ($seconds, $minutes, $hours, $monthday, $month,
194 $year, $weekday, $yearday, $sommertime) = localtime(time);
195 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
196 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
197 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
198 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
199 $month = $monthnames[$month];
200 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
201 $year+=1900;
202 my $name = $0;
203 $name =~ s/\.\///;
205 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
206 print LOG_HANDLE $log_msg;
207 if( $foreground ) {
208 print STDERR $log_msg;
209 }
210 }
211 close( LOG_HANDLE );
212 }
213 #log into syslog
214 # my ($msg, $level, $facility) = @_;
215 # if(not defined $msg) {return}
216 # if(not defined $level) {$level = "info"}
217 # if(not defined $facility) {$facility = "LOG_DAEMON"}
218 # openlog($0, "pid,cons,", $facility);
219 # syslog($level, $msg);
220 # closelog;
221 # return;
222 }
225 sub get_time {
226 my ($seconds, $minutes, $hours, $monthday, $month,
227 $year, $weekday, $yearday, $sommertime) = localtime(time);
228 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
229 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
230 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
231 $month+=1;
232 $month = $month < 10 ? $month = "0".$month : $month;
233 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
234 $year+=1900;
235 return "$year$month$monthday$hours$minutes$seconds";
237 }
240 #=== FUNCTION ================================================================
241 # NAME: check_cmdline_param
242 # PARAMETERS: nothing
243 # RETURNS: nothing
244 # DESCRIPTION: validates commandline parameter
245 #===============================================================================
246 sub check_cmdline_param () {
247 my $err_config;
248 my $err_counter = 0;
249 if(not defined($cfg_file)) {
250 $cfg_file = "/etc/gosa-si/server.conf";
251 if(! -r $cfg_file) {
252 $err_config = "please specify a config file";
253 $err_counter += 1;
254 }
255 }
256 if( $err_counter > 0 ) {
257 &usage( "", 1 );
258 if( defined( $err_config)) { print STDERR "$err_config\n"}
259 print STDERR "\n";
260 exit( -1 );
261 }
262 }
265 #=== FUNCTION ================================================================
266 # NAME: check_pid
267 # PARAMETERS: nothing
268 # RETURNS: nothing
269 # DESCRIPTION: handels pid processing
270 #===============================================================================
271 sub check_pid {
272 $pid = -1;
273 # Check, if we are already running
274 if( open(LOCK_FILE, "<$pid_file") ) {
275 $pid = <LOCK_FILE>;
276 if( defined $pid ) {
277 chomp( $pid );
278 if( -f "/proc/$pid/stat" ) {
279 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
280 if( $0 eq $stat ) {
281 close( LOCK_FILE );
282 exit -1;
283 }
284 }
285 }
286 close( LOCK_FILE );
287 unlink( $pid_file );
288 }
290 # create a syslog msg if it is not to possible to open PID file
291 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
292 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
293 if (open(LOCK_FILE, '<', $pid_file)
294 && ($pid = <LOCK_FILE>))
295 {
296 chomp($pid);
297 $msg .= "(PID $pid)\n";
298 } else {
299 $msg .= "(unable to read PID)\n";
300 }
301 if( ! ($foreground) ) {
302 openlog( $0, "cons,pid", "daemon" );
303 syslog( "warning", $msg );
304 closelog();
305 }
306 else {
307 print( STDERR " $msg " );
308 }
309 exit( -1 );
310 }
311 }
313 #=== FUNCTION ================================================================
314 # NAME: import_modules
315 # PARAMETERS: module_path - string - abs. path to the directory the modules
316 # are stored
317 # RETURNS: nothing
318 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
319 # state is on is imported by "require 'file';"
320 #===============================================================================
321 sub import_modules {
322 daemon_log(" ", 1);
324 if (not -e $modules_path) {
325 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
326 }
328 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
329 while (defined (my $file = readdir (DIR))) {
330 if (not $file =~ /(\S*?).pm$/) {
331 next;
332 }
333 my $mod_name = $1;
335 if( $file =~ /ArpHandler.pm/ ) {
336 if( $no_arp > 0 ) {
337 next;
338 }
339 }
341 eval { require $file; };
342 if ($@) {
343 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
344 daemon_log("$@", 5);
345 } else {
346 my $info = eval($mod_name.'::get_module_info()');
347 # Only load module if get_module_info() returns a non-null object
348 if( $info ) {
349 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
350 $known_modules->{$mod_name} = $info;
351 daemon_log("module $mod_name loaded", 1);
352 }
353 }
354 }
355 close (DIR);
356 }
359 #=== FUNCTION ================================================================
360 # NAME: sig_int_handler
361 # PARAMETERS: signal - string - signal arose from system
362 # RETURNS: noting
363 # DESCRIPTION: handels tasks to be done befor signal becomes active
364 #===============================================================================
365 sub sig_int_handler {
366 my ($signal) = @_;
368 daemon_log("shutting down gosa-si-server", 1);
369 exit(1);
370 }
371 $SIG{INT} = \&sig_int_handler;
375 sub check_key_and_xml_validity {
376 my ($crypted_msg, $module_key) = @_;
377 #print STDERR "crypted_msg:$crypted_msg\n";
378 #print STDERR "modul_key:$module_key\n";
380 my $msg;
381 my $msg_hash;
382 eval{
383 $msg = &decrypt_msg($crypted_msg, $module_key);
385 if ($msg =~ /<xml>/i){
386 &main::daemon_log("decrypted_msg: \n$msg", 8);
387 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
389 # check header
390 my $header_l = $msg_hash->{'header'};
391 if( 1 != @{$header_l} ) {
392 die 'header error';
393 }
394 my $header = @{$header_l}[0];
395 if( 0 == length $header) {
396 die 'header error';
397 }
399 # check source
400 my $source_l = $msg_hash->{'source'};
401 if( not defined @{$source_l} or 1 != @{$source_l} ) {
402 die 'source error';
403 }
404 my $source = @{$source_l}[0];
405 if( 0 == length $source) {
406 die 'source error';
407 }
409 # check target
410 my $target_l = $msg_hash->{'target'};
411 if( 1 != @{$target_l} ) {
412 die'target error';
413 }
414 my $target = @{$target_l}[0];
415 if( 0 == length $target) {
416 die 'target error';
417 }
418 }
419 };
420 if($@) {
421 &main::daemon_log("WARNING: do not understand the message", 5);
422 &main::daemon_log("$@", 8);
423 }
425 return ($msg, $msg_hash);
426 }
429 sub input_from_known_server {
430 my ($input, $remote_ip) = @_ ;
431 my ($msg, $msg_hash, $module);
433 my $sql_statement= "SELECT * FROM known_server";
434 my $query_res = $known_server_db->select_dbentry( $sql_statement );
436 while( my ($hit_num, $hit) = each %{ $query_res } ) {
437 my $host_name = $hit->{hostname};
438 if( not $host_name =~ "^$remote_ip") {
439 next;
440 }
441 my $host_key = $hit->{hostkey};
442 daemon_log("SIPackages: known_server host_name: $host_name", 7);
443 daemon_log("SIPackages: known_server host_key: $host_key", 7);
445 # check if module can open msg envelope with module key
446 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
447 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
448 daemon_log("SIPackages: deciphering raise error", 7);
449 daemon_log("$@", 8);
450 next;
451 }
452 else {
453 $msg = $tmp_msg;
454 $msg_hash = $tmp_msg_hash;
455 $module = "SIPackages";
456 last;
457 }
458 }
460 if( (!$msg) || (!$msg_hash) || (!$module) ) {
461 daemon_log("Incoming message is not from a known server", 3);
462 }
464 return ($msg, $msg_hash, $module);
465 }
468 sub input_from_known_client {
469 my ($input, $remote_ip) = @_ ;
470 my ($msg, $msg_hash, $module);
472 my $sql_statement= "SELECT * FROM known_clients";
473 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
474 while( my ($hit_num, $hit) = each %{ $query_res } ) {
475 my $host_name = $hit->{hostname};
476 if( not $host_name =~ /^$remote_ip:\d*$/) {
477 next;
478 }
479 my $host_key = $hit->{hostkey};
480 &daemon_log("SIPackages: known_client host_name: $host_name", 7);
481 &daemon_log("SIPackages: known_client host_key: $host_key", 7);
483 # check if module can open msg envelope with module key
484 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
486 if( (!$msg) || (!$msg_hash) ) {
487 &daemon_log("SIPackages: deciphering raise error", 7);
488 &daemon_log("$@", 8);
489 next;
490 }
491 else {
492 $module = "SIPackages";
493 last;
494 }
495 }
497 if( (!$msg) || (!$msg_hash) || (!$module) ) {
498 &daemon_log("Incoming message is not from a known client", 3);
499 }
501 return ($msg, $msg_hash, $module);
502 }
505 sub input_from_unknown_host {
506 no strict "refs";
507 my ($input) = @_ ;
508 my ($msg, $msg_hash, $module);
510 my %act_modules = %$known_modules;
512 while( my ($mod, $info) = each(%act_modules)) {
514 # check a key exists for this module
515 my $module_key = ${$mod."_key"};
516 if( ! $module_key ) {
517 daemon_log("ERROR: no key specified in config file for $mod", 1);
518 next;
519 }
520 daemon_log("$mod: $module_key", 5);
522 # check if module can open msg envelope with module key
523 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
524 if( (!$msg) || (!$msg_hash) ) {
525 #daemon_log("$mod: deciphering failed", 5);
526 next;
527 }
528 else {
529 $module = $mod;
530 last;
531 }
532 }
534 if( (!$msg) || (!$msg_hash) || (!$module)) {
535 daemon_log("Incoming message is not from a unknown host", 5);
536 }
538 return ($msg, $msg_hash, $module);
539 }
541 sub create_ciphering {
542 my ($passwd) = @_;
543 if((!defined($passwd)) || length($passwd)==0) {
544 $passwd = "";
545 }
546 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
547 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
548 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
549 $my_cipher->set_iv($iv);
550 return $my_cipher;
551 }
554 sub encrypt_msg {
555 my ($msg, $key) = @_;
556 my $my_cipher = &create_ciphering($key);
557 {
558 use bytes;
559 $msg = "\0"x(16-length($msg)%16).$msg;
560 }
561 $msg = $my_cipher->encrypt($msg);
562 chomp($msg = &encode_base64($msg));
563 # there are no newlines allowed inside msg
564 $msg=~ s/\n//g;
565 return $msg;
566 }
569 sub decrypt_msg {
570 my ($msg, $key) = @_ ;
571 $msg = &decode_base64($msg);
572 my $my_cipher = &create_ciphering($key);
573 $msg = $my_cipher->decrypt($msg);
574 $msg =~ s/\0*//g;
575 return $msg;
576 }
579 sub get_encrypt_key {
580 my ($target) = @_ ;
581 my $encrypt_key;
582 my $error = 0;
584 # target can be in known_server
585 if( not defined $encrypt_key ) {
586 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
587 my $query_res = $known_server_db->select_dbentry( $sql_statement );
588 while( my ($hit_num, $hit) = each %{ $query_res } ) {
589 my $host_name = $hit->{hostname};
590 if( $host_name ne $target ) {
591 next;
592 }
593 $encrypt_key = $hit->{hostkey};
594 last;
595 }
596 }
598 # target can be in known_client
599 if( not defined $encrypt_key ) {
600 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
601 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
602 while( my ($hit_num, $hit) = each %{ $query_res } ) {
603 my $host_name = $hit->{hostname};
604 if( $host_name ne $target ) {
605 next;
606 }
607 $encrypt_key = $hit->{hostkey};
608 last;
609 }
610 }
612 return $encrypt_key;
613 }
616 #=== FUNCTION ================================================================
617 # NAME: open_socket
618 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
619 # [PeerPort] string necessary if port not appended by PeerAddr
620 # RETURNS: socket IO::Socket::INET
621 # DESCRIPTION: open a socket to PeerAddr
622 #===============================================================================
623 sub open_socket {
624 my ($PeerAddr, $PeerPort) = @_ ;
625 if(defined($PeerPort)){
626 $PeerAddr = $PeerAddr.":".$PeerPort;
627 }
628 my $socket;
629 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
630 Porto => "tcp",
631 Type => SOCK_STREAM,
632 Timeout => 5,
633 );
634 if(not defined $socket) {
635 return;
636 }
637 &daemon_log("open_socket: $PeerAddr", 7);
638 return $socket;
639 }
642 #=== FUNCTION ================================================================
643 # NAME: get_ip
644 # PARAMETERS: interface name (i.e. eth0)
645 # RETURNS: (ip address)
646 # DESCRIPTION: Uses ioctl to get ip address directly from system.
647 #===============================================================================
648 sub get_ip {
649 my $ifreq= shift;
650 my $result= "";
651 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
652 my $proto= getprotobyname('ip');
654 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
655 or die "socket: $!";
657 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
658 my ($if, $sin) = unpack 'a16 a16', $ifreq;
659 my ($port, $addr) = sockaddr_in $sin;
660 my $ip = inet_ntoa $addr;
662 if ($ip && length($ip) > 0) {
663 $result = $ip;
664 }
665 }
667 return $result;
668 }
670 sub get_local_ip_for_remote_ip {
671 my $remote_ip= shift;
672 my $result="0.0.0.0";
674 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
675 if($remote_ip eq "127.0.0.1") {
676 $result = "127.0.0.1";
677 } else {
678 my $PROC_NET_ROUTE= ('/proc/net/route');
680 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
681 or die "Could not open $PROC_NET_ROUTE";
683 my @ifs = <PROC_NET_ROUTE>;
685 close(PROC_NET_ROUTE);
687 # Eat header line
688 shift @ifs;
689 chomp @ifs;
690 foreach my $line(@ifs) {
691 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
692 my $destination;
693 my $mask;
694 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
695 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
696 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
697 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
698 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
699 # destination matches route, save mac and exit
700 $result= &get_ip($Iface);
701 last;
702 }
703 }
704 }
705 } else {
706 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
707 }
708 return $result;
709 }
711 sub send_msg_to_target {
712 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
713 my $error = 0;
714 my $header;
715 my $new_status;
716 my $act_status;
717 my ($sql_statement, $res);
719 if( $msg_header ) {
720 $header = "'$msg_header'-";
721 }
722 else {
723 $header = "";
724 }
726 # Patch the source ip
727 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
728 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
729 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
730 }
732 # encrypt xml msg
733 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
735 # opensocket
736 my $socket = &open_socket($address);
737 if( !$socket ) {
738 daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
739 $error++;
740 }
742 if( $error == 0 ) {
743 # send xml msg
744 print $socket $crypted_msg."\n";
746 daemon_log("send ".$header."msg to $address", 1);
747 daemon_log("message:\n$msg", 8);
749 }
751 # close socket in any case
752 if( $socket ) {
753 close $socket;
754 }
756 if( $error > 0 ) { $new_status = "down"; }
757 else { $new_status = $msg_header; }
760 # known_clients
761 $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
762 $res = $known_clients_db->select_dbentry($sql_statement);
763 if( keys(%$res) > 0) {
764 $act_status = $res->{1}->{'status'};
765 if( $act_status eq "down" ) {
766 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
767 $res = $known_clients_db->del_dbentry($sql_statement);
768 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
769 }
770 else {
771 $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
772 $res = $known_clients_db->update_dbentry($sql_statement);
773 if($new_status eq "down"){
774 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
775 }
776 else {
777 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
778 }
779 }
780 }
782 # known_server
783 $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
784 $res = $known_server_db->select_dbentry($sql_statement);
785 if( keys(%$res) > 0 ) {
786 $act_status = $res->{1}->{'status'};
787 if( $act_status eq "down" ) {
788 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
789 $res = $known_server_db->del_dbentry($sql_statement);
790 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
791 }
792 else {
793 $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
794 $res = $known_server_db->update_dbentry($sql_statement);
795 if($new_status eq "down"){
796 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
797 }
798 else {
799 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
800 }
801 }
802 }
804 return;
805 }
808 sub _start {
809 my ($kernel) = $_[KERNEL];
810 &trigger_db_loop($kernel);
811 }
814 sub client_input {
815 no strict "refs";
816 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
817 my ($msg, $msg_hash, $module);
818 my $error = 0;
819 my $answer_l;
820 my ($answer_header, @answer_target_l, $answer_source);
821 my $client_answer;
823 daemon_log("Incoming msg from '".$heap->{'remote_ip'}."'", 7);
824 daemon_log("\n$input", 8);
826 # msg is from a new client or gosa
827 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
829 # msg is from a gosa-si-server or gosa-si-bus
830 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
831 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
832 }
834 # msg is from a gosa-si-client
835 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
836 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
837 }
839 # an error occurred
840 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
841 $error++;
842 }
844 ######################
845 # process incoming msg
846 if( $error == 0) {
847 daemon_log("Processing module ".$module, 5);
848 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $heap->{'remote_ip'});
850 if ( 0 > @{$answer_l} ) {
851 my $answer_str = join("\n", @{$answer_l});
852 daemon_log("$module: Got answer from module: \n".$answer_str,8);
853 }
854 }
855 if( !$answer_l ) { $error++ };
857 ########
858 # answer
859 if( $error == 0 ) {
861 # for each answer in answer list
862 foreach my $answer ( @{$answer_l} ) {
864 my $error = 0;
865 # check answer if gosa-si envelope conform
866 if(defined($answer)) {
867 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
868 $answer_header = @{$answer_hash->{'header'}}[0];
869 @answer_target_l = @{$answer_hash->{'target'}};
870 $answer_source = @{$answer_hash->{'source'}}[0];
871 if( !$answer_header ) {
872 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
873 daemon_log("\n$answer", 8);
874 $error++;
875 }
876 if( 0 == length @answer_target_l ) {
877 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
878 daemon_log("\n$answer", 8);
879 $error++;
880 }
881 if( !$answer_source ) {
882 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
883 daemon_log("\n$answer", 8);
884 $error++;
885 }
887 if( $error != 0 ) {
888 next;
889 }
890 }
892 # deliver msg to all targets
893 foreach my $answer_target ( @answer_target_l ) {
894 if( $answer_target eq "*" ) {
895 # answer is for all clients
896 my $sql_statement= "SELECT * FROM known_clients";
897 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
898 while( my ($hit_num, $hit) = each %{ $query_res } ) {
899 my $host_name = $hit->{hostname};
900 my $host_key = $hit->{hostkey};
901 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
902 }
903 }
904 elsif( $answer_target eq "GOSA" ) {
905 # answer is for GOSA and has to returned to connected client
906 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
907 $client_answer = $gosa_answer;
908 }
909 elsif( $answer_target eq "KNOWN_SERVER" ) {
910 # answer is for all server in known_server
911 my $sql_statement= "SELECT * FROM known_server";
912 my $query_res = $known_server_db->select_dbentry( $sql_statement );
913 while( my ($hit_num, $hit) = each %{ $query_res } ) {
914 my $host_name = $hit->{hostname};
915 my $host_key = $hit->{hostkey};
916 $answer =~ s/KNOWN_SERVER/$host_name/g;
917 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
918 }
919 }
920 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 ) {
921 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
922 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
923 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
924 my $found_ip_flag = 0;
925 while( my ($hit_num, $hit) = each %{ $query_res } ) {
926 my $host_name = $hit->{hostname};
927 my $host_key = $hit->{hostkey};
928 $answer =~ s/$answer_target/$host_name/g;
929 daemon_log("found host '$host_name', assoziated to '$answer_target'", 3);
930 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
931 $found_ip_flag++ ;
932 }
933 if( $found_ip_flag == 0) {
934 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target'", 3);
935 if( $bus_activ eq "true" ) {
936 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
937 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
938 my $query_res = $known_server_db->select_dbentry( $sql_statement );
939 while( my ($hit_num, $hit) = each %{ $query_res } ) {
940 my $bus_address = $hit->{hostname};
941 my $bus_key = $hit->{hostkey};
942 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
943 last;
944 }
945 }
947 }
948 } else {
949 # ... answer is for one specific host
951 # get encrypt_key
952 my $encrypt_key = &get_encrypt_key($answer_target);
953 if( not defined $encrypt_key ) {
954 # unknown target, forward msg to bus
955 daemon_log("WARNING: unknown target '$answer_target'", 3);
956 if( $bus_activ eq "true" ) {
957 daemon_log("INFO: try to forward msg '$answer_header' to bus '$bus_address'", 5);
958 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
959 my $query_res = $known_server_db->select_dbentry( $sql_statement );
960 my $res_length = keys( %{$query_res} );
961 if( $res_length == 0 ){
962 daemon_log("WARNING: send '$answer_header' to '$bus_address' failed, no bus found in known_server", 3);
963 }
964 else {
965 while( my ($hit_num, $hit) = each %{ $query_res } ) {
966 my $bus_key = $hit->{hostkey};
967 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
968 }
969 }
970 }
971 next;
972 }
973 # send_msg
974 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
975 }
976 }
977 }
978 }
980 if( $client_answer ) {
981 $heap->{client}->put($client_answer);
982 }
984 return;
985 }
989 sub trigger_db_loop {
990 # my ($kernel) = $_[KERNEL];
991 my ($kernel) = @_ ;
992 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
993 }
996 sub watch_for_new_jobs {
997 my ($kernel,$heap) = @_[KERNEL, HEAP];
999 # check gosa job queue for jobs with executable timestamp
1000 my $timestamp = &get_time();
1002 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
1003 " WHERE status='waiting' AND timestamp<'$timestamp'";
1005 my $res = $job_db->select_dbentry( $sql_statement );
1007 while( my ($id, $hit) = each %{$res} ) {
1009 my $jobdb_id = $hit->{id};
1010 my $macaddress = $hit->{macaddress};
1011 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
1012 my $out_msg_hash = $job_msg_hash;
1013 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1014 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1015 # expect macaddress is unique!!!!!!
1016 my $target = $res_hash->{1}->{hostname};
1018 if (not defined $target) {
1019 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1020 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1021 my $sql_statement = "UPDATE $job_queue_table_name ".
1022 "SET status='error', result='no host found for mac address' ".
1023 "WHERE id='$jobdb_id'";
1024 my $res = $job_db->update_dbentry($sql_statement);
1025 next;
1026 }
1028 # add target
1029 &add_content2xml_hash($out_msg_hash, "target", $target);
1031 # add new header
1032 my $out_header = $job_msg_hash->{header}[0];
1033 $out_header =~ s/job_/gosa_/;
1034 delete $out_msg_hash->{header};
1035 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1037 # add sqlite_id
1038 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1040 my $out_msg = &create_xml_string($out_msg_hash);
1042 # encrypt msg as a GosaPackage module
1043 my $cipher = &create_ciphering($GosaPackages_key);
1044 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1046 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
1048 if ($error == 0) {
1049 my $sql_statement = "UPDATE $job_queue_table_name ".
1050 "SET status='processing', targettag='$target' ".
1051 "WHERE id='$jobdb_id'";
1052 my $res = $job_db->update_dbentry($sql_statement);
1053 } else {
1054 my $sql_statement = "UPDATE $job_queue_table_name ".
1055 "SET status='error' ".
1056 "WHERE id='$jobdb_id'";
1057 my $res = $job_db->update_dbentry($sql_statement);
1058 }
1059 }
1061 $kernel->delay_set('watch_for_new_jobs',3);
1062 }
1065 #==== MAIN = main ==============================================================
1066 # parse commandline options
1067 Getopt::Long::Configure( "bundling" );
1068 GetOptions("h|help" => \&usage,
1069 "c|config=s" => \$cfg_file,
1070 "f|foreground" => \$foreground,
1071 "v|verbose+" => \$verbose,
1072 "no-bus+" => \$no_bus,
1073 "no-arp+" => \$no_arp,
1074 );
1076 # read and set config parameters
1077 &check_cmdline_param ;
1078 &read_configfile;
1079 &check_pid;
1081 $SIG{CHLD} = 'IGNORE';
1083 # forward error messages to logfile
1084 if( ! $foreground ) {
1085 open(STDERR, '>>', $log_file);
1086 open(STDOUT, '>>', $log_file);
1087 }
1089 # Just fork, if we are not in foreground mode
1090 if( ! $foreground ) {
1091 chdir '/' or die "Can't chdir to /: $!";
1092 $pid = fork;
1093 setsid or die "Can't start a new session: $!";
1094 umask 0;
1095 } else {
1096 $pid = $$;
1097 }
1099 # Do something useful - put our PID into the pid_file
1100 if( 0 != $pid ) {
1101 open( LOCK_FILE, ">$pid_file" );
1102 print LOCK_FILE "$pid\n";
1103 close( LOCK_FILE );
1104 if( !$foreground ) {
1105 exit( 0 )
1106 };
1107 }
1109 daemon_log(" ", 1);
1110 daemon_log("$0 started!", 1);
1112 if ($no_bus > 0) {
1113 $bus_activ = "false"
1114 }
1118 # delete old DBsqlite lock files
1119 #unlink('/tmp/gosa_si_lock*');
1121 # connect to gosa-si job queue
1122 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1123 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1124 $job_db->create_table('jobs', \@job_col_names);
1126 # connect to known_clients_db
1127 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1128 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1129 $known_clients_db->create_table('known_clients', \@clients_col_names);
1131 # connect to known_server_db
1132 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1133 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1134 $known_server_db->create_table('known_server', \@server_col_names);
1136 # create xml object used for en/decrypting
1137 $xml = new XML::Simple();
1139 # create socket for incoming xml messages
1140 POE::Component::Server::TCP->new(
1141 Port => $server_port,
1142 ClientInput => \&client_input,
1143 );
1144 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1146 # create session for repeatedly checking the job queue for jobs
1147 POE::Session->create(
1148 inline_states => {
1149 _start => \&_start,
1150 watch_for_new_jobs => \&watch_for_new_jobs,
1151 }
1152 );
1155 # import all modules
1156 &import_modules;
1158 # check wether all modules are gosa-si valid passwd check
1160 POE::Kernel->run();
1161 exit;