52729a954de58cba958b6f18cdc5230d6cb2a40d
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);
381 if ($msg =~ /<xml>/i){
382 &main::daemon_log("decrypted_msg: \n$msg", 8);
383 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
385 # check header
386 my $header_l = $msg_hash->{'header'};
387 if( 1 != @{$header_l} ) {
388 die 'header error';
389 }
390 my $header = @{$header_l}[0];
391 if( 0 == length $header) {
392 die 'header error';
393 }
395 # check source
396 my $source_l = $msg_hash->{'source'};
397 if( not defined @{$source_l} or 1 != @{$source_l} ) {
398 die 'source error';
399 }
400 my $source = @{$source_l}[0];
401 if( 0 == length $source) {
402 die 'source error';
403 }
405 # check target
406 my $target_l = $msg_hash->{'target'};
407 if( 1 != @{$target_l} ) {
408 die'target error';
409 }
410 my $target = @{$target_l}[0];
411 if( 0 == length $target) {
412 die 'target error';
413 }
414 }
415 };
416 if($@) {
417 &main::daemon_log("WARNING: do not understand the message", 5);
418 &main::daemon_log("$@", 8);
419 }
421 return ($msg, $msg_hash);
422 }
425 sub input_from_known_server {
426 my ($input, $remote_ip) = @_ ;
427 my ($msg, $msg_hash, $module);
429 my $sql_statement= "SELECT * FROM known_server";
430 my $query_res = $known_server_db->select_dbentry( $sql_statement );
432 while( my ($hit_num, $hit) = each %{ $query_res } ) {
433 my $host_name = $hit->{hostname};
434 if( not $host_name =~ "^$remote_ip") {
435 next;
436 }
437 my $host_key = $hit->{hostkey};
438 daemon_log("SIPackages: known_server host_name: $host_name", 7);
439 daemon_log("SIPackages: known_server host_key: $host_key", 7);
441 # check if module can open msg envelope with module key
442 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
443 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
444 daemon_log("SIPackages: deciphering raise error", 7);
445 daemon_log("$@", 8);
446 next;
447 }
448 else {
449 $msg = $tmp_msg;
450 $msg_hash = $tmp_msg_hash;
451 $module = "SIPackages";
452 last;
453 }
454 }
456 if( (!$msg) || (!$msg_hash) || (!$module) ) {
457 daemon_log("Incoming message is not from a known server", 3);
458 }
460 return ($msg, $msg_hash, $module);
461 }
464 sub input_from_known_client {
465 my ($input, $remote_ip) = @_ ;
466 my ($msg, $msg_hash, $module);
468 my $sql_statement= "SELECT * FROM known_clients";
469 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
470 while( my ($hit_num, $hit) = each %{ $query_res } ) {
471 my $host_name = $hit->{hostname};
472 if( not $host_name =~ /^$remote_ip:\d*$/) {
473 next;
474 }
475 my $host_key = $hit->{hostkey};
476 &daemon_log("SIPackages: known_client host_name: $host_name", 7);
477 &daemon_log("SIPackages: known_client host_key: $host_key", 7);
479 # check if module can open msg envelope with module key
480 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
482 if( (!$msg) || (!$msg_hash) ) {
483 &daemon_log("SIPackages: deciphering raise error", 7);
484 &daemon_log("$@", 8);
485 next;
486 }
487 else {
488 $module = "SIPackages";
489 last;
490 }
491 }
493 if( (!$msg) || (!$msg_hash) || (!$module) ) {
494 &daemon_log("Incoming message is not from a known client", 3);
495 }
497 return ($msg, $msg_hash, $module);
498 }
501 sub input_from_unknown_host {
502 no strict "refs";
503 my ($input) = @_ ;
504 my ($msg, $msg_hash, $module);
506 my %act_modules = %$known_modules;
508 while( my ($mod, $info) = each(%act_modules)) {
510 # check a key exists for this module
511 my $module_key = ${$mod."_key"};
512 if( ! $module_key ) {
513 daemon_log("ERROR: no key specified in config file for $mod", 1);
514 next;
515 }
516 daemon_log("$mod: $module_key", 5);
518 # check if module can open msg envelope with module key
519 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
520 if( (!$msg) || (!$msg_hash) ) {
521 #daemon_log("$mod: deciphering failed", 5);
522 next;
523 }
524 else {
525 $module = $mod;
526 last;
527 }
528 }
530 if( (!$msg) || (!$msg_hash) || (!$module)) {
531 daemon_log("Incoming message is not from a unknown host", 5);
532 }
534 return ($msg, $msg_hash, $module);
535 }
537 sub create_ciphering {
538 my ($passwd) = @_;
539 if((!defined($passwd)) || length($passwd)==0) {
540 $passwd = "";
541 }
542 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
543 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
544 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
545 $my_cipher->set_iv($iv);
546 return $my_cipher;
547 }
550 sub encrypt_msg {
551 my ($msg, $key) = @_;
552 my $my_cipher = &create_ciphering($key);
553 {
554 use bytes;
555 $msg = "\0"x(16-length($msg)%16).$msg;
556 }
557 $msg = $my_cipher->encrypt($msg);
558 chomp($msg = &encode_base64($msg));
559 # there are no newlines allowed inside msg
560 $msg=~ s/\n//g;
561 return $msg;
562 }
565 sub decrypt_msg {
566 my ($msg, $key) = @_ ;
567 $msg = &decode_base64($msg);
568 my $my_cipher = &create_ciphering($key);
569 $msg = $my_cipher->decrypt($msg);
570 $msg =~ s/\0*//g;
571 return $msg;
572 }
575 sub get_encrypt_key {
576 my ($target) = @_ ;
577 my $encrypt_key;
578 my $error = 0;
580 # target can be in known_server
581 if( not defined $encrypt_key ) {
582 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
583 my $query_res = $known_server_db->select_dbentry( $sql_statement );
584 while( my ($hit_num, $hit) = each %{ $query_res } ) {
585 my $host_name = $hit->{hostname};
586 if( $host_name ne $target ) {
587 next;
588 }
589 $encrypt_key = $hit->{hostkey};
590 last;
591 }
592 }
595 # target can be in known_client
596 if( not defined $encrypt_key ) {
597 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
598 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
599 while( my ($hit_num, $hit) = each %{ $query_res } ) {
600 my $host_name = $hit->{hostname};
601 if( $host_name ne $target ) {
602 next;
603 }
604 $encrypt_key = $hit->{hostkey};
605 last;
606 }
607 }
609 return $encrypt_key;
610 }
613 #=== FUNCTION ================================================================
614 # NAME: open_socket
615 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
616 # [PeerPort] string necessary if port not appended by PeerAddr
617 # RETURNS: socket IO::Socket::INET
618 # DESCRIPTION: open a socket to PeerAddr
619 #===============================================================================
620 sub open_socket {
621 my ($PeerAddr, $PeerPort) = @_ ;
622 if(defined($PeerPort)){
623 $PeerAddr = $PeerAddr.":".$PeerPort;
624 }
625 my $socket;
626 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
627 Porto => "tcp",
628 Type => SOCK_STREAM,
629 Timeout => 5,
630 );
631 if(not defined $socket) {
632 return;
633 }
634 &daemon_log("open_socket: $PeerAddr", 7);
635 return $socket;
636 }
639 #=== FUNCTION ================================================================
640 # NAME: get_ip
641 # PARAMETERS: interface name (i.e. eth0)
642 # RETURNS: (ip address)
643 # DESCRIPTION: Uses ioctl to get ip address directly from system.
644 #===============================================================================
645 sub get_ip {
646 my $ifreq= shift;
647 my $result= "";
648 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
649 my $proto= getprotobyname('ip');
651 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
652 or die "socket: $!";
654 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
655 my ($if, $sin) = unpack 'a16 a16', $ifreq;
656 my ($port, $addr) = sockaddr_in $sin;
657 my $ip = inet_ntoa $addr;
659 if ($ip && length($ip) > 0) {
660 $result = $ip;
661 }
662 }
664 return $result;
665 }
667 sub get_local_ip_for_remote_ip {
668 my $remote_ip= shift;
669 my $result="0.0.0.0";
671 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
672 if($remote_ip eq "127.0.0.1") {
673 $result = "127.0.0.1";
674 } else {
675 my $PROC_NET_ROUTE= ('/proc/net/route');
677 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
678 or die "Could not open $PROC_NET_ROUTE";
680 my @ifs = <PROC_NET_ROUTE>;
682 close(PROC_NET_ROUTE);
684 # Eat header line
685 shift @ifs;
686 chomp @ifs;
687 foreach my $line(@ifs) {
688 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
689 my $destination;
690 my $mask;
691 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
692 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
693 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
694 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
695 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
696 # destination matches route, save mac and exit
697 $result= &get_ip($Iface);
698 last;
699 }
700 }
701 }
702 } else {
703 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $remote_ip", 1);
704 }
705 return $result;
706 }
708 sub send_msg_to_target {
709 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
710 my $error = 0;
711 my $header;
712 my $new_status;
713 my $act_status;
714 my ($sql_statement, $res);
716 if( $msg_header ) {
717 $header = "'$msg_header'-";
718 }
719 else {
720 $header = "";
721 }
723 # Patch the source ip
724 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
725 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
726 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
727 }
729 # encrypt xml msg
730 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
732 # opensocket
733 my $socket = &open_socket($address);
734 if( !$socket ) {
735 daemon_log("cannot send ".$header."msg to $address , host not reachable", 1);
736 $error++;
737 }
739 if( $error == 0 ) {
740 # send xml msg
741 print $socket $crypted_msg."\n";
743 daemon_log("send ".$header."msg to $address", 1);
744 daemon_log("message:\n$msg", 8);
746 }
748 # close socket in any case
749 if( $socket ) {
750 close $socket;
751 }
753 if( $error > 0 ) { $new_status = "down"; }
754 else { $new_status = $msg_header; }
757 # known_clients
758 $sql_statement = "SELECT * FROM known_clients WHERE hostname='$address'";
759 $res = $known_clients_db->select_dbentry($sql_statement);
760 if( keys(%$res) > 0) {
761 $act_status = $res->{1}->{'status'};
762 if( $act_status eq "down" ) {
763 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
764 $res = $known_clients_db->del_dbentry($sql_statement);
765 daemon_log("WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
766 }
767 else {
768 $sql_statement = "UPDATE known_clients SET status='$new_status' WHERE hostname='$address'";
769 $res = $known_clients_db->update_dbentry($sql_statement);
770 if($new_status eq "down"){
771 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
772 }
773 else {
774 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
775 }
776 }
777 }
779 # known_server
780 $sql_statement = "SELECT * FROM known_server WHERE hostname='$address'";
781 $res = $known_server_db->select_dbentry($sql_statement);
782 if( keys(%$res) > 0 ) {
783 $act_status = $res->{1}->{'status'};
784 if( $act_status eq "down" ) {
785 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
786 $res = $known_clients_db->del_dbentry($sql_statement);
787 daemon_log("WARNING: failed 2x to a send msg to host '$address', delete host from known_server", 3);
788 }
789 else {
790 $sql_statement = "UPDATE known_server SET status='$new_status' WHERE hostname='$address'";
791 $res = $known_server_db->update_dbentry($sql_statement);
792 if($new_status eq "down"){
793 daemon_log("WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
794 }
795 else {
796 daemon_log("INFO: set '$address' from status '$act_status' to '$new_status'", 5);
797 }
798 }
799 }
801 return;
802 }
805 sub _start {
806 my ($kernel) = $_[KERNEL];
807 &trigger_db_loop($kernel);
808 }
811 sub client_input {
812 no strict "refs";
813 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
814 my ($msg, $msg_hash, $module);
815 my $error = 0;
816 my $answer_l;
817 my ($answer_header, @answer_target_l, $answer_source);
818 my $client_answer;
820 daemon_log("Incoming msg from '".$heap->{'remote_ip'}."'", 7);
821 daemon_log("\n$input", 8);
823 # msg is from a new client or gosa
824 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
826 # msg is from a gosa-si-server or gosa-si-bus
827 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
828 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
829 }
831 # msg is from a gosa-si-client
832 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
833 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
834 }
836 # an error occurred
837 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
838 $error++;
839 }
841 ######################
842 # process incoming msg
843 if( $error == 0) {
844 daemon_log("Processing module ".$module, 5);
845 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $heap->{'remote_ip'});
847 if ( 0 > @{$answer_l} ) {
848 my $answer_str = join("\n", @{$answer_l});
849 daemon_log("$module: Got answer from module: \n".$answer_str,8);
850 }
851 }
852 if( !$answer_l ) { $error++ };
854 ########
855 # answer
856 if( $error == 0 ) {
858 # for each answer in answer list
859 foreach my $answer ( @{$answer_l} ) {
861 my $error = 0;
862 # check answer if gosa-si envelope conform
863 if(defined($answer)) {
864 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
865 $answer_header = @{$answer_hash->{'header'}}[0];
866 @answer_target_l = @{$answer_hash->{'target'}};
867 $answer_source = @{$answer_hash->{'source'}}[0];
868 if( !$answer_header ) {
869 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
870 daemon_log("\n$answer", 8);
871 $error++;
872 }
873 if( 0 == length @answer_target_l ) {
874 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
875 daemon_log("\n$answer", 8);
876 $error++;
877 }
878 if( !$answer_source ) {
879 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
880 daemon_log("\n$answer", 8);
881 $error++;
882 }
884 if( $error != 0 ) {
885 next;
886 }
887 }
889 # deliver msg to all targets
890 foreach my $answer_target ( @answer_target_l ) {
891 if( $answer_target eq "*" ) {
892 # answer is for all clients
893 my $sql_statement= "SELECT * FROM known_clients";
894 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
895 while( my ($hit_num, $hit) = each %{ $query_res } ) {
896 my $host_name = $hit->{hostname};
897 my $host_key = $hit->{hostkey};
898 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
899 }
900 }
901 elsif( $answer_target eq "GOSA" ) {
902 # answer is for GOSA and has to returned to connected client
903 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
904 $client_answer = $gosa_answer;
905 }
906 elsif( $answer_target eq "KNOWN_SERVER" ) {
907 # answer is for all server in known_server
908 my $sql_statement= "SELECT * FROM known_server";
909 my $query_res = $known_server_db->select_dbentry( $sql_statement );
910 while( my ($hit_num, $hit) = each %{ $query_res } ) {
911 my $host_name = $hit->{hostname};
912 my $host_key = $hit->{hostkey};
913 $answer =~ s/KNOWN_SERVER/$host_name/g;
914 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
915 }
916 }
917 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 ) {
918 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
919 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
920 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
921 my $found_ip_flag = 0;
922 while( my ($hit_num, $hit) = each %{ $query_res } ) {
923 my $host_name = $hit->{hostname};
924 my $host_key = $hit->{hostkey};
925 $answer =~ s/$answer_target/$host_name/g;
926 daemon_log("found host '$host_name', assoziated to '$answer_target'", 3);
927 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
928 $found_ip_flag++ ;
929 }
930 if( $found_ip_flag == 0) {
931 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target', forward msg to bus", 1);
932 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
933 my $query_res = $known_server_db->select_dbentry( $sql_statement );
934 while( my ($hit_num, $hit) = each %{ $query_res } ) {
935 my $bus_address = $hit->{hostname};
936 my $bus_key = $hit->{hostkey};
937 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
938 last;
939 }
941 }
942 }
943 else {
944 # answer is for one specific host
945 # get encrypt_key
946 my $encrypt_key = &get_encrypt_key($answer_target);
947 if( !$encrypt_key ) {
948 # unknown target, forward msg to bus
949 daemon_log("WARNING: unknown target '$answer_target', forward msg to bus", 3);
950 my $sql_statement = "SELECT * FROM known_server WHERE hostname='$bus_address'";
951 my $query_res = $known_server_db->select_dbentry( $sql_statement );
952 my $bus_key = $query_res->{1}->{hostkey};
953 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
954 next;
955 }
956 # send_msg
957 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
958 }
959 }
960 }
961 }
963 if( $client_answer ) {
964 $heap->{client}->put($client_answer);
965 }
967 return;
968 }
972 sub trigger_db_loop {
973 # my ($kernel) = $_[KERNEL];
974 my ($kernel) = @_ ;
975 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
976 }
979 sub watch_for_new_jobs {
980 my ($kernel,$heap) = @_[KERNEL, HEAP];
982 # check gosa job queue for jobs with executable timestamp
983 my $timestamp = &get_time();
985 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
986 " WHERE status='waiting' AND timestamp<'$timestamp'";
988 my $res = $job_db->select_dbentry( $sql_statement );
990 while( my ($id, $hit) = each %{$res} ) {
992 my $jobdb_id = $hit->{id};
993 my $macaddress = $hit->{macaddress};
994 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
995 my $out_msg_hash = $job_msg_hash;
996 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
997 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
998 # expect macaddress is unique!!!!!!
999 my $target = $res_hash->{1}->{hostname};
1001 if (not defined $target) {
1002 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1003 &daemon_log("xml message: $hit->{xmlmessage}", 5);
1004 my $sql_statement = "UPDATE $job_queue_table_name ".
1005 "SET status='error', result='no host found for mac address' ".
1006 "WHERE id='$jobdb_id'";
1007 my $res = $job_db->update_dbentry($sql_statement);
1008 next;
1009 }
1011 # add target
1012 &add_content2xml_hash($out_msg_hash, "target", $target);
1014 # add new header
1015 my $out_header = $job_msg_hash->{header}[0];
1016 $out_header =~ s/job_/gosa_/;
1017 delete $out_msg_hash->{header};
1018 &add_content2xml_hash($out_msg_hash, "header", $out_header);
1020 # add sqlite_id
1021 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1023 my $out_msg = &create_xml_string($out_msg_hash);
1025 # encrypt msg as a GosaPackage module
1026 my $cipher = &create_ciphering($GosaPackages_key);
1027 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1029 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
1031 if ($error == 0) {
1032 my $sql_statement = "UPDATE $job_queue_table_name ".
1033 "SET status='processing', targettag='$target' ".
1034 "WHERE id='$jobdb_id'";
1035 my $res = $job_db->update_dbentry($sql_statement);
1036 } else {
1037 my $sql_statement = "UPDATE $job_queue_table_name ".
1038 "SET status='error' ".
1039 "WHERE id='$jobdb_id'";
1040 my $res = $job_db->update_dbentry($sql_statement);
1041 }
1042 }
1044 $kernel->delay_set('watch_for_new_jobs',3);
1045 }
1048 #==== MAIN = main ==============================================================
1049 # parse commandline options
1050 Getopt::Long::Configure( "bundling" );
1051 GetOptions("h|help" => \&usage,
1052 "c|config=s" => \$cfg_file,
1053 "f|foreground" => \$foreground,
1054 "v|verbose+" => \$verbose,
1055 "no-bus+" => \$no_bus,
1056 "no-arp+" => \$no_arp,
1057 );
1059 # read and set config parameters
1060 &check_cmdline_param ;
1061 &read_configfile;
1062 &check_pid;
1064 $SIG{CHLD} = 'IGNORE';
1066 # forward error messages to logfile
1067 if( ! $foreground ) {
1068 open(STDERR, '>>', $log_file);
1069 open(STDOUT, '>>', $log_file);
1070 }
1072 # Just fork, if we are not in foreground mode
1073 if( ! $foreground ) {
1074 chdir '/' or die "Can't chdir to /: $!";
1075 $pid = fork;
1076 setsid or die "Can't start a new session: $!";
1077 umask 0;
1078 } else {
1079 $pid = $$;
1080 }
1082 # Do something useful - put our PID into the pid_file
1083 if( 0 != $pid ) {
1084 open( LOCK_FILE, ">$pid_file" );
1085 print LOCK_FILE "$pid\n";
1086 close( LOCK_FILE );
1087 if( !$foreground ) {
1088 exit( 0 )
1089 };
1090 }
1092 daemon_log(" ", 1);
1093 daemon_log("$0 started!", 1);
1095 # delete old DBsqlite lock files
1096 unlink('/tmp/gosa_si_lock*');
1098 # connect to gosa-si job queue
1099 my @job_col_names = ("id INTEGER", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
1100 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
1101 $job_db->create_table('jobs', \@job_col_names);
1103 # connect to known_clients_db
1104 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
1105 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
1106 $known_clients_db->create_table('known_clients', \@clients_col_names);
1108 # connect to known_server_db
1109 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
1110 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
1111 $known_server_db->create_table('known_server', \@server_col_names);
1113 # create xml object used for en/decrypting
1114 $xml = new XML::Simple();
1116 # create socket for incoming xml messages
1117 POE::Component::Server::TCP->new(
1118 Port => $server_port,
1119 ClientInput => \&client_input,
1120 );
1121 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1123 # create session for repeatedly checking the job queue for jobs
1124 POE::Session->create(
1125 inline_states => {
1126 _start => \&_start,
1127 watch_for_new_jobs => \&watch_for_new_jobs,
1128 }
1129 );
1132 # import all modules
1133 &import_modules;
1135 # check wether all modules are gosa-si valid passwd check
1137 POE::Kernel->run();
1138 exit;