a46f68c2e7897aa48e57e2d903f3dcad5bd07949
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);
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;
85 $no_arp = 0;
87 # name of table for storing gosa jobs
88 our $job_queue_table_name = 'jobs';
89 our $job_db;
91 # holds all other gosa-sd as well as the gosa-sd-bus
92 our $known_server_db;
94 # holds all registrated clients
95 our $known_clients_db;
97 %cfg_defaults = (
98 "general" => {
99 "log-file" => [\$log_file, "/var/run/".$0.".log"],
100 "pid-file" => [\$pid_file, "/var/run/".$0.".pid"],
101 },
102 "server" => {
103 # "ip" => [\$server_ip, "0.0.0.0"],
104 "port" => [\$server_port, "20081"],
105 "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
106 "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
107 },
108 "GOsaPackages" => {
109 "ip" => [\$gosa_ip, "0.0.0.0"],
110 "port" => [\$gosa_port, "20082"],
111 "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
112 "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
113 "key" => [\$GosaPackages_key, "none"],
114 },
115 "SIPackages" => {
116 "key" => [\$SIPackages_key, "none"],
117 },
118 );
121 #=== FUNCTION ================================================================
122 # NAME: usage
123 # PARAMETERS: nothing
124 # RETURNS: nothing
125 # DESCRIPTION: print out usage text to STDERR
126 #===============================================================================
127 sub usage {
128 print STDERR << "EOF" ;
129 usage: $0 [-hvf] [-c config]
131 -h : this (help) message
132 -c <file> : config file
133 -f : foreground, process will not be forked to background
134 -v : be verbose (multiple to increase verbosity)
135 -no-bus : starts $0 without connection to bus
136 -no-arp : starts $0 without connection to arp module
138 EOF
139 print "\n" ;
140 }
143 #=== FUNCTION ================================================================
144 # NAME: read_configfile
145 # PARAMETERS: cfg_file - string -
146 # RETURNS: nothing
147 # DESCRIPTION: read cfg_file and set variables
148 #===============================================================================
149 sub read_configfile {
150 my $cfg;
151 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
152 if( -r $cfg_file ) {
153 $cfg = Config::IniFiles->new( -file => $cfg_file );
154 } else {
155 print STDERR "Couldn't read config file!\n";
156 }
157 } else {
158 $cfg = Config::IniFiles->new() ;
159 }
160 foreach my $section (keys %cfg_defaults) {
161 foreach my $param (keys %{$cfg_defaults{ $section }}) {
162 my $pinfo = $cfg_defaults{ $section }{ $param };
163 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
164 }
165 }
166 }
169 #=== FUNCTION ================================================================
170 # NAME: logging
171 # PARAMETERS: level - string - default 'info'
172 # msg - string -
173 # facility - string - default 'LOG_DAEMON'
174 # RETURNS: nothing
175 # DESCRIPTION: function for logging
176 #===============================================================================
177 sub daemon_log {
178 # log into log_file
179 my( $msg, $level ) = @_;
180 if(not defined $msg) { return }
181 if(not defined $level) { $level = 1 }
182 if(defined $log_file){
183 open(LOG_HANDLE, ">>$log_file");
184 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
185 print STDERR "cannot open $log_file: $!";
186 return }
187 chomp($msg);
188 if($level <= $verbose){
189 my ($seconds, $minutes, $hours, $monthday, $month,
190 $year, $weekday, $yearday, $sommertime) = localtime(time);
191 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
192 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
193 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
194 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
195 $month = $monthnames[$month];
196 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
197 $year+=1900;
198 my $name = $0;
199 $name =~ s/\.\///;
201 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
202 print LOG_HANDLE $log_msg;
203 if( $foreground ) {
204 print STDERR $log_msg;
205 }
206 }
207 close( LOG_HANDLE );
208 }
209 #log into syslog
210 # my ($msg, $level, $facility) = @_;
211 # if(not defined $msg) {return}
212 # if(not defined $level) {$level = "info"}
213 # if(not defined $facility) {$facility = "LOG_DAEMON"}
214 # openlog($0, "pid,cons,", $facility);
215 # syslog($level, $msg);
216 # closelog;
217 # return;
218 }
221 sub get_time {
222 my ($seconds, $minutes, $hours, $monthday, $month,
223 $year, $weekday, $yearday, $sommertime) = localtime(time);
224 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
225 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
226 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
227 $month+=1;
228 $month = $month < 10 ? $month = "0".$month : $month;
229 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
230 $year+=1900;
231 return "$year$month$monthday$hours$minutes$seconds";
233 }
236 #=== FUNCTION ================================================================
237 # NAME: check_cmdline_param
238 # PARAMETERS: nothing
239 # RETURNS: nothing
240 # DESCRIPTION: validates commandline parameter
241 #===============================================================================
242 sub check_cmdline_param () {
243 my $err_config;
244 my $err_counter = 0;
245 if(not defined($cfg_file)) {
246 $cfg_file = "/etc/gosa-si/server.conf";
247 if(! -r $cfg_file) {
248 $err_config = "please specify a config file";
249 $err_counter += 1;
250 }
251 }
252 if( $err_counter > 0 ) {
253 &usage( "", 1 );
254 if( defined( $err_config)) { print STDERR "$err_config\n"}
255 print STDERR "\n";
256 exit( -1 );
257 }
258 }
261 #=== FUNCTION ================================================================
262 # NAME: check_pid
263 # PARAMETERS: nothing
264 # RETURNS: nothing
265 # DESCRIPTION: handels pid processing
266 #===============================================================================
267 sub check_pid {
268 $pid = -1;
269 # Check, if we are already running
270 if( open(LOCK_FILE, "<$pid_file") ) {
271 $pid = <LOCK_FILE>;
272 if( defined $pid ) {
273 chomp( $pid );
274 if( -f "/proc/$pid/stat" ) {
275 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
276 if( $0 eq $stat ) {
277 close( LOCK_FILE );
278 exit -1;
279 }
280 }
281 }
282 close( LOCK_FILE );
283 unlink( $pid_file );
284 }
286 # create a syslog msg if it is not to possible to open PID file
287 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
288 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
289 if (open(LOCK_FILE, '<', $pid_file)
290 && ($pid = <LOCK_FILE>))
291 {
292 chomp($pid);
293 $msg .= "(PID $pid)\n";
294 } else {
295 $msg .= "(unable to read PID)\n";
296 }
297 if( ! ($foreground) ) {
298 openlog( $0, "cons,pid", "daemon" );
299 syslog( "warning", $msg );
300 closelog();
301 }
302 else {
303 print( STDERR " $msg " );
304 }
305 exit( -1 );
306 }
307 }
309 #=== FUNCTION ================================================================
310 # NAME: import_modules
311 # PARAMETERS: module_path - string - abs. path to the directory the modules
312 # are stored
313 # RETURNS: nothing
314 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
315 # state is on is imported by "require 'file';"
316 #===============================================================================
317 sub import_modules {
318 daemon_log(" ", 1);
320 if (not -e $modules_path) {
321 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
322 }
324 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
325 while (defined (my $file = readdir (DIR))) {
326 if (not $file =~ /(\S*?).pm$/) {
327 next;
328 }
329 my $mod_name = $1;
331 if( $file =~ /ArpHandler.pm/ ) {
332 if( $no_arp > 0 ) {
333 next;
334 }
335 }
337 eval { require $file; };
338 if ($@) {
339 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
340 daemon_log("$@", 5);
341 } else {
342 my $info = eval($mod_name.'::get_module_info()');
343 # Only load module if get_module_info() returns a non-null object
344 if( $info ) {
345 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
346 $known_modules->{$mod_name} = $info;
347 daemon_log("module $mod_name loaded", 1);
348 }
349 }
350 }
351 close (DIR);
352 }
355 #=== FUNCTION ================================================================
356 # NAME: sig_int_handler
357 # PARAMETERS: signal - string - signal arose from system
358 # RETURNS: noting
359 # DESCRIPTION: handels tasks to be done befor signal becomes active
360 #===============================================================================
361 sub sig_int_handler {
362 my ($signal) = @_;
364 daemon_log("shutting down gosa-si-server", 1);
365 exit(1);
366 }
367 $SIG{INT} = \&sig_int_handler;
371 sub check_key_and_xml_validity {
372 my ($crypted_msg, $module_key) = @_;
373 #print STDERR "crypted_msg:$crypted_msg\n";
374 #print STDERR "modul_key:$module_key\n";
376 my $msg;
377 my $msg_hash;
378 eval{
379 $msg = &decrypt_msg($crypted_msg, $module_key);
380 &main::daemon_log("decrypted_msg: \n$msg", 8);
382 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
384 # check header
385 my $header_l = $msg_hash->{'header'};
386 if( 1 != @{$header_l} ) {
387 die'header error';
388 }
389 my $header = @{$header_l}[0];
390 if( 0 == length $header) {
391 die 'header error';
392 }
394 # check source
395 my $source_l = $msg_hash->{'source'};
396 if( 1 != @{$source_l} ) {
397 die'source error';
398 }
399 my $source = @{$source_l}[0];
400 if( 0 == length $source) {
401 die 'source error';
402 }
404 # check target
405 my $target_l = $msg_hash->{'target'};
406 if( 1 != @{$target_l} ) {
407 die'target error';
408 }
409 my $target = @{$target_l}[0];
410 if( 0 == length $target) {
411 die 'target error';
412 }
414 };
415 if($@) {
416 &main::daemon_log("WARNING: do not understand the message", 5);
417 &main::daemon_log("$@", 8);
418 }
420 return ($msg, $msg_hash);
421 }
424 sub input_from_known_server {
425 my ($input, $remote_ip) = @_ ;
426 my ($msg, $msg_hash, $module);
428 my $sql_statement= "SELECT * FROM known_server";
429 my $query_res = $known_server_db->select_dbentry( $sql_statement );
431 while( my ($hit_num, $hit) = each %{ $query_res } ) {
432 my $host_name = $hit->{hostname};
433 if( not $host_name =~ "^$remote_ip") {
434 next;
435 }
436 my $host_key = $hit->{hostkey};
437 daemon_log("SIPackages: known_server host_name: $host_name", 7);
438 daemon_log("SIPackages: known_server host_key: $host_key", 7);
440 # check if module can open msg envelope with module key
441 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
442 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
443 daemon_log("SIPackages: deciphering raise error", 7);
444 daemon_log("$@", 8);
445 next;
446 }
447 else {
448 $msg = $tmp_msg;
449 $msg_hash = $tmp_msg_hash;
450 $module = "SIPackages";
451 last;
452 }
453 }
455 if( (!$msg) || (!$msg_hash) || (!$module) ) {
456 daemon_log("Incoming message is not from a known server", 3);
457 }
459 return ($msg, $msg_hash, $module);
460 }
463 sub input_from_known_client {
464 my ($input, $remote_ip) = @_ ;
465 my ($msg, $msg_hash, $module);
467 my $sql_statement= "SELECT * FROM known_clients";
468 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
469 while( my ($hit_num, $hit) = each %{ $query_res } ) {
470 my $host_name = $hit->{hostname};
471 if( not $host_name =~ /^$remote_ip:\d*$/) {
472 next;
473 }
474 my $host_key = $hit->{hostkey};
475 &daemon_log("SIPackages: known_client host_name: $host_name", 7);
476 &daemon_log("SIPackages: known_client host_key: $host_key", 7);
478 # check if module can open msg envelope with module key
479 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
481 if( (!$msg) || (!$msg_hash) ) {
482 &daemon_log("SIPackages: deciphering raise error", 7);
483 &daemon_log("$@", 8);
484 next;
485 }
486 else {
487 $module = "SIPackages";
488 last;
489 }
490 }
492 if( (!$msg) || (!$msg_hash) || (!$module) ) {
493 &daemon_log("Incoming message is not from a known client", 3);
494 }
496 return ($msg, $msg_hash, $module);
497 }
500 sub input_from_unknown_host {
501 no strict "refs";
502 my ($input) = @_ ;
503 my ($msg, $msg_hash, $module);
505 my %act_modules = %$known_modules;
507 while( my ($mod, $info) = each(%act_modules)) {
508 # check a key exists for this module
511 print STDERR "SIPackages_key:$SIPackages_key\n";
514 my $module_key = ${$mod."_key"};
515 if( ! $module_key ) {
516 daemon_log("ERROR: no key specified in config file for $mod", 1);
517 next;
518 }
519 daemon_log("$mod: $module_key", 5);
521 # check if module can open msg envelope with module key
522 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
523 if( (!$msg) || (!$msg_hash) ) {
524 #daemon_log("$mod: deciphering failed", 5);
525 next;
526 }
527 else {
528 $module = $mod;
529 last;
530 }
531 }
533 if( (!$msg) || (!$msg_hash) || (!$module)) {
534 daemon_log("Incoming message is not from a unknown host", 5);
535 }
537 return ($msg, $msg_hash, $module);
538 }
540 sub create_ciphering {
541 my ($passwd) = @_;
542 if((!defined($passwd)) || length($passwd)==0) {
543 $passwd = "";
544 }
545 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
546 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
547 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
548 $my_cipher->set_iv($iv);
549 return $my_cipher;
550 }
553 sub encrypt_msg {
554 my ($msg, $key) = @_;
555 my $my_cipher = &create_ciphering($key);
556 {
557 use bytes;
558 $msg = "\0"x(16-length($msg)%16).$msg;
559 }
560 $msg = $my_cipher->encrypt($msg);
561 chomp($msg = &encode_base64($msg));
562 # there are no newlines allowed inside msg
563 $msg=~ s/\n//g;
564 return $msg;
565 }
568 sub decrypt_msg {
569 my ($msg, $key) = @_ ;
570 $msg = &decode_base64($msg);
571 my $my_cipher = &create_ciphering($key);
572 $msg = $my_cipher->decrypt($msg);
573 $msg =~ s/\0*//g;
574 return $msg;
575 }
578 sub get_encrypt_key {
579 my ($target) = @_ ;
580 my $encrypt_key;
581 my $error = 0;
583 # target can be in known_server
584 if( !$encrypt_key ) {
585 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
586 my $query_res = $known_server_db->select_dbentry( $sql_statement );
587 while( my ($hit_num, $hit) = each %{ $query_res } ) {
588 my $host_name = $hit->{hostname};
589 if( $host_name ne $target ) {
590 next;
591 }
592 $encrypt_key = $hit->{hostkey};
593 last;
594 }
595 }
598 # target can be in known_client
599 if( !$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_clients_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})/ ) {
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', forward msg to bus", 1);
935 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
936 my $query_res = $known_server_db->select_dbentry( $sql_statement );
937 while( my ($hit_num, $hit) = each %{ $query_res } ) {
938 my $bus_address = $hit->{hostname};
939 my $bus_key = $hit->{hostkey};
940 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
941 last;
942 }
944 }
945 }
946 else {
947 # answer is for one specific host
948 # get encrypt_key
949 my $encrypt_key = &get_encrypt_key($answer_target);
950 if( !$encrypt_key ) {
951 # unknown target, forward msg to bus
952 daemon_log("WARNING: unknown target '$answer_target', forward msg to bus", 3);
953 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
954 my $query_res = $known_server_db->select_dbentry( $sql_statement );
955 my $bus_key = $query_res->{1}->{hostkey};
956 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
957 next;
958 }
959 # send_msg
960 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
961 }
962 }
963 }
964 }
966 if( $client_answer ) {
967 $heap->{client}->put($client_answer);
968 }
970 return;
971 }
975 sub trigger_db_loop {
976 # my ($kernel) = $_[KERNEL];
977 my ($kernel) = @_ ;
978 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
979 }
982 sub watch_for_new_jobs {
983 my ($kernel,$heap) = @_[KERNEL, HEAP];
985 # check gosa job queue for jobs with executable timestamp
986 my $timestamp = &get_time();
988 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
989 " WHERE status='waiting' AND timestamp<'$timestamp'";
991 my $res = $job_db->select_dbentry( $sql_statement );
993 while( my ($id, $hit) = each %{$res} ) {
995 my $jobdb_id = $hit->{id};
996 my $macaddress = $hit->{macaddress};
997 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
998 my $out_msg_hash = $job_msg_hash;
999 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
1000 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1001 # expect macaddress is unique!!!!!!
1002 my $target = $res_hash->{1}->{hostname};
1004 if (not defined $target) {
1005 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1006 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1007 my $sql_statement = "UPDATE $job_queue_table_name ".
1008 "SET status='error', result='no host found for mac address' ".
1009 "WHERE id='$jobdb_id'";
1010 my $res = $job_db->update_dbentry($sql_statement);
1011 next;
1012 }
1014 # add target
1015 &add_content2xml_hash($out_msg_hash, "target", $target);
1017 # add new header
1018 my $out_header = $job_msg_hash->{header}[0];
1019 $out_header =~ s/job_/gosa_/;
1020 delete $out_msg_hash->{header};
1021 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1023 # add sqlite_id
1024 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1026 my $out_msg = &create_xml_string($out_msg_hash);
1028 # encrypt msg as a GosaPackage module
1029 my $cipher = &create_ciphering($GosaPackages_key);
1030 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1032 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
1034 if ($error == 0) {
1035 my $sql_statement = "UPDATE $job_queue_table_name ".
1036 "SET status='processing', targettag='$target' ".
1037 "WHERE id='$jobdb_id'";
1038 my $res = $job_db->update_dbentry($sql_statement);
1039 } else {
1040 my $sql_statement = "UPDATE $job_queue_table_name ".
1041 "SET status='error' ".
1042 "WHERE id='$jobdb_id'";
1043 my $res = $job_db->update_dbentry($sql_statement);
1044 }
1045 }
1047 $kernel->delay_set('watch_for_new_jobs',3);
1048 }
1051 #==== MAIN = main ==============================================================
1052 # parse commandline options
1053 Getopt::Long::Configure( "bundling" );
1054 GetOptions("h|help" => \&usage,
1055 "c|config=s" => \$cfg_file,
1056 "f|foreground" => \$foreground,
1057 "v|verbose+" => \$verbose,
1058 "no-bus+" => \$no_bus,
1059 "no-arp+" => \$no_arp,
1060 );
1062 # read and set config parameters
1063 &check_cmdline_param ;
1064 &read_configfile;
1065 &check_pid;
1067 $SIG{CHLD} = 'IGNORE';
1069 # forward error messages to logfile
1070 if( ! $foreground ) {
1071 open(STDERR, '>>', $log_file);
1072 open(STDOUT, '>>', $log_file);
1073 }
1075 # Just fork, if we are not in foreground mode
1076 if( ! $foreground ) {
1077 chdir '/' or die "Can't chdir to /: $!";
1078 $pid = fork;
1079 setsid or die "Can't start a new session: $!";
1080 umask 0;
1081 } else {
1082 $pid = $$;
1083 }
1085 # Do something useful - put our PID into the pid_file
1086 if( 0 != $pid ) {
1087 open( LOCK_FILE, ">$pid_file" );
1088 print LOCK_FILE "$pid\n";
1089 close( LOCK_FILE );
1090 if( !$foreground ) {
1091 exit( 0 )
1092 };
1093 }
1095 daemon_log(" ", 1);
1096 daemon_log("$0 started!", 1);
1098 # delete old DBsqlite lock files
1099 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
1101 # connect to gosa-si job queue
1102 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1103 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1104 $job_db->create_table('jobs', \@job_col_names);
1106 # connect to known_clients_db
1107 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1108 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1109 $known_clients_db->create_table('known_clients', \@clients_col_names);
1111 # connect to known_server_db
1112 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1113 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1114 $known_server_db->create_table('known_server', \@server_col_names);
1116 # create xml object used for en/decrypting
1117 $xml = new XML::Simple();
1119 # create socket for incoming xml messages
1120 POE::Component::Server::TCP->new(
1121 Port => $server_port,
1122 ClientInput => \&client_input,
1123 );
1124 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1126 # create session for repeatedly checking the job queue for jobs
1127 POE::Session->create(
1128 inline_states => {
1129 _start => \&_start,
1130 watch_for_new_jobs => \&watch_for_new_jobs,
1131 }
1132 );
1135 # import all modules
1136 &import_modules;
1138 # check wether all modules are gosa-si valid passwd check
1140 POE::Kernel->run();
1141 exit;