bc7d4f52f3576d1f2ce6305491252ac8e8015f43
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-sd
5 #
6 # USAGE: ./gosa-sd
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl
12 # libdata-dumper-simple-perl libdbd-sqlite3-perl libnet-ldap-perl
13 # libpoe-perl
14 # BUGS: ---
15 # NOTES:
16 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
17 # COMPANY:
18 # VERSION: 1.0
19 # CREATED: 12.09.2007 08:54:41 CEST
20 # REVISION: ---
21 #===============================================================================
23 use strict;
24 use warnings;
25 use Getopt::Long;
26 use Config::IniFiles;
27 use POSIX;
29 use Fcntl;
30 use IO::Socket::INET;
31 use IO::Handle;
32 use IO::Select;
33 use Symbol qw(qualify_to_ref);
34 use Crypt::Rijndael;
35 use MIME::Base64;
36 use Digest::MD5 qw(md5 md5_hex md5_base64);
37 use XML::Simple;
38 use Data::Dumper;
39 use Sys::Syslog qw( :DEFAULT setlogsock);
40 use Cwd;
41 use File::Spec;
42 use GOSA::DBsqlite;
43 use POE qw(Component::Server::TCP);
45 my $modules_path = "/usr/lib/gosa-si/modules";
46 use lib "/usr/lib/gosa-si/modules";
48 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
49 my ($bus, $msg_to_bus, $bus_cipher);
50 my ($server, $server_mac_address, $server_events);
51 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
52 my ($known_modules, $known_clients_file_name, $known_server_file_name);
53 my ($max_clients);
54 my ($pid_file, $procid, $pid, $log_file);
55 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
56 my ($arp_activ, $arp_fifo, $arp_fifo_path);
57 my ($xml);
59 # variables declared in config file are always set to 'our'
60 our (%cfg_defaults, $log_file, $pid_file,
61 $bus_activ, $bus_key, $bus_ip, $bus_port,
62 $server_activ, $server_ip, $server_port, $SIPackages_key, $max_clients,
63 $arp_activ, $arp_fifo_path,
64 $gosa_activ, $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
65 );
67 # additional variable which should be globaly accessable
68 our $server_address;
69 our $bus_address;
70 our $gosa_address;
71 our $no_bus;
72 our $no_arp;
73 our $verbose;
74 our $forground;
75 our $cfg_file;
77 # specifies the verbosity of the daemon_log
78 $verbose = 0 ;
80 # if foreground is not null, script will be not forked to background
81 $foreground = 0 ;
83 # specifies the timeout seconds while checking the online status of a registrating client
84 $ping_timeout = 5;
86 $no_bus = 0;
88 $no_arp = 0;
90 # name of table for storing gosa jobs
91 our $job_queue_table_name = 'jobs';
92 our $job_db;
94 # holds all other gosa-sd as well as the gosa-sd-bus
95 our $known_server_db;
97 # holds all registrated clients
98 our $known_clients_db;
100 %cfg_defaults =
101 ("general" =>
102 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
103 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
104 "child_max" => [\$child_max, 10],
105 "child_min" => [\$child_min, 3],
106 "child_timeout" => [\$child_timeout, 180],
107 "job_queue_timeout" => [\$job_queue_timeout, undef],
108 "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/gosa-si-server_jobs.db'],
109 "job_queue_loop_delay" => [\$job_queue_loop_delay, 3],
110 "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/gosa-si-server_known_clients.db' ],
111 "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/gosa-si-server_known_server.db'],
112 },
113 "bus" =>
114 {"bus_activ" => [\$bus_activ, "on"],
115 "bus_passwd" => [\$bus_key, ""],
116 "bus_ip" => [\$bus_ip, "0.0.0.0"],
117 "bus_port" => [\$bus_port, "20080"],
118 },
119 "server" =>
120 {"server_activ" => [\$server_activ, "on"],
121 "server_ip" => [\$server_ip, "0.0.0.0"],
122 "server_port" => [\$server_port, "20081"],
123 "SIPackages_key" => [\$SIPackages_key, "none"],
124 "max_clients" => [\$max_clients, 100],
125 },
126 "arp" =>
127 {"arp_activ" => [\$arp_activ, "on"],
128 "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
129 },
130 "gosa" =>
131 {"gosa_activ" => [\$gosa_activ, "on"],
132 "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
133 "gosa_port" => [\$gosa_port, "20082"],
134 "GosaPackages_key" => [\$GosaPackages_key, "none"],
135 },
136 );
139 #=== FUNCTION ================================================================
140 # NAME: usage
141 # PARAMETERS: nothing
142 # RETURNS: nothing
143 # DESCRIPTION: print out usage text to STDERR
144 #===============================================================================
145 sub usage {
146 print STDERR << "EOF" ;
147 usage: $0 [-hvf] [-c config]
149 -h : this (help) message
150 -c <file> : config file
151 -f : foreground, process will not be forked to background
152 -v : be verbose (multiple to increase verbosity)
153 -no-bus : starts $0 without connection to bus
154 -no-arp : starts $0 without connection to arp module
156 EOF
157 print "\n" ;
158 }
161 #=== FUNCTION ================================================================
162 # NAME: read_configfile
163 # PARAMETERS: cfg_file - string -
164 # RETURNS: nothing
165 # DESCRIPTION: read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168 my $cfg;
169 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
170 if( -r $cfg_file ) {
171 $cfg = Config::IniFiles->new( -file => $cfg_file );
172 } else {
173 print STDERR "Couldn't read config file!\n";
174 }
175 } else {
176 $cfg = Config::IniFiles->new() ;
177 }
178 foreach my $section (keys %cfg_defaults) {
179 foreach my $param (keys %{$cfg_defaults{ $section }}) {
180 my $pinfo = $cfg_defaults{ $section }{ $param };
181 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
182 }
183 }
184 }
187 #=== FUNCTION ================================================================
188 # NAME: logging
189 # PARAMETERS: level - string - default 'info'
190 # msg - string -
191 # facility - string - default 'LOG_DAEMON'
192 # RETURNS: nothing
193 # DESCRIPTION: function for logging
194 #===============================================================================
195 sub daemon_log {
196 # log into log_file
197 my( $msg, $level ) = @_;
198 if(not defined $msg) { return }
199 if(not defined $level) { $level = 1 }
200 if(defined $log_file){
201 open(LOG_HANDLE, ">>$log_file");
202 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
203 print STDERR "cannot open $log_file: $!";
204 return }
205 chomp($msg);
206 if($level <= $verbose){
207 my ($seconds, $minutes, $hours, $monthday, $month,
208 $year, $weekday, $yearday, $sommertime) = localtime(time);
209 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
210 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
211 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
212 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
213 $month = $monthnames[$month];
214 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
215 $year+=1900;
216 my $name = $0;
217 $name =~ s/\.\///;
219 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
220 print LOG_HANDLE $log_msg;
221 if( $foreground ) {
222 print STDERR $log_msg;
223 }
224 }
225 close( LOG_HANDLE );
226 }
227 #log into syslog
228 # my ($msg, $level, $facility) = @_;
229 # if(not defined $msg) {return}
230 # if(not defined $level) {$level = "info"}
231 # if(not defined $facility) {$facility = "LOG_DAEMON"}
232 # openlog($0, "pid,cons,", $facility);
233 # syslog($level, $msg);
234 # closelog;
235 # return;
236 }
239 sub get_time {
240 my ($seconds, $minutes, $hours, $monthday, $month,
241 $year, $weekday, $yearday, $sommertime) = localtime(time);
242 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
243 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
244 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
245 $month+=1;
246 $month = $month < 10 ? $month = "0".$month : $month;
247 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
248 $year+=1900;
249 return "$year$month$monthday$hours$minutes$seconds";
251 }
254 #=== FUNCTION ================================================================
255 # NAME: check_cmdline_param
256 # PARAMETERS: nothing
257 # RETURNS: nothing
258 # DESCRIPTION: validates commandline parameter
259 #===============================================================================
260 sub check_cmdline_param () {
261 my $err_config;
262 my $err_counter = 0;
263 if(not defined($cfg_file)) {
264 $cfg_file = "/etc/gosa-si/server.conf";
265 if(! -r $cfg_file) {
266 $err_config = "please specify a config file";
267 $err_counter += 1;
268 }
269 }
270 if( $err_counter > 0 ) {
271 &usage( "", 1 );
272 if( defined( $err_config)) { print STDERR "$err_config\n"}
273 print STDERR "\n";
274 exit( -1 );
275 }
276 }
279 #=== FUNCTION ================================================================
280 # NAME: check_pid
281 # PARAMETERS: nothing
282 # RETURNS: nothing
283 # DESCRIPTION: handels pid processing
284 #===============================================================================
285 sub check_pid {
286 $pid = -1;
287 # Check, if we are already running
288 if( open(LOCK_FILE, "<$pid_file") ) {
289 $pid = <LOCK_FILE>;
290 if( defined $pid ) {
291 chomp( $pid );
292 if( -f "/proc/$pid/stat" ) {
293 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
294 if( $0 eq $stat ) {
295 close( LOCK_FILE );
296 exit -1;
297 }
298 }
299 }
300 close( LOCK_FILE );
301 unlink( $pid_file );
302 }
304 # create a syslog msg if it is not to possible to open PID file
305 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
306 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
307 if (open(LOCK_FILE, '<', $pid_file)
308 && ($pid = <LOCK_FILE>))
309 {
310 chomp($pid);
311 $msg .= "(PID $pid)\n";
312 } else {
313 $msg .= "(unable to read PID)\n";
314 }
315 if( ! ($foreground) ) {
316 openlog( $0, "cons,pid", "daemon" );
317 syslog( "warning", $msg );
318 closelog();
319 }
320 else {
321 print( STDERR " $msg " );
322 }
323 exit( -1 );
324 }
325 }
327 #=== FUNCTION ================================================================
328 # NAME: import_modules
329 # PARAMETERS: module_path - string - abs. path to the directory the modules
330 # are stored
331 # RETURNS: nothing
332 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
333 # state is on is imported by "require 'file';"
334 #===============================================================================
335 sub import_modules {
336 daemon_log(" ", 1);
338 if (not -e $modules_path) {
339 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
340 }
342 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
343 while (defined (my $file = readdir (DIR))) {
344 if (not $file =~ /(\S*?).pm$/) {
345 next;
346 }
347 my $mod_name = $1;
349 if( $file =~ /ArpHandler.pm/ ) {
350 if( $no_arp > 0 ) {
351 next;
352 }
353 }
355 eval { require $file; };
356 if ($@) {
357 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
358 daemon_log("$@", 5);
359 } else {
360 my $info = eval($mod_name.'::get_module_info()');
361 # Only load module if get_module_info() returns a non-null object
362 if( $info ) {
363 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
364 $known_modules->{$mod_name} = $info;
365 daemon_log("module $mod_name loaded", 1);
366 }
367 }
368 }
369 close (DIR);
370 }
373 #=== FUNCTION ================================================================
374 # NAME: sig_int_handler
375 # PARAMETERS: signal - string - signal arose from system
376 # RETURNS: noting
377 # DESCRIPTION: handels tasks to be done befor signal becomes active
378 #===============================================================================
379 sub sig_int_handler {
380 my ($signal) = @_;
382 daemon_log("shutting down gosa-si-server", 1);
383 exit(1);
384 }
385 $SIG{INT} = \&sig_int_handler;
389 sub check_key_and_xml_validity {
390 my ($crypted_msg, $module_key) = @_;
391 #print STDERR "crypted_msg:$crypted_msg\n";
392 #print STDERR "modul_key:$module_key\n";
394 my $msg;
395 my $msg_hash;
396 eval{
397 $msg = &decrypt_msg($crypted_msg, $module_key);
398 &main::daemon_log("decrypted_msg: \n$msg", 8);
400 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
402 # check header
403 my $header_l = $msg_hash->{'header'};
404 if( 1 != @{$header_l} ) {
405 die'header error';
406 }
407 my $header = @{$header_l}[0];
408 if( 0 == length $header) {
409 die 'header error';
410 }
412 # check source
413 my $source_l = $msg_hash->{'source'};
414 if( 1 != @{$source_l} ) {
415 die'source error';
416 }
417 my $source = @{$source_l}[0];
418 if( 0 == length $source) {
419 die 'source error';
420 }
422 # check target
423 my $target_l = $msg_hash->{'target'};
424 if( 1 != @{$target_l} ) {
425 die'target error';
426 }
427 my $target = @{$target_l}[0];
428 if( 0 == length $target) {
429 die 'target error';
430 }
432 };
433 if($@) {
434 &main::daemon_log("WARNING: do not understand the message:", 5);
435 &main::daemon_log("$@", 8);
436 }
438 return ($msg, $msg_hash);
439 }
442 sub input_from_known_server {
443 my ($input, $remote_ip) = @_ ;
444 my ($msg, $msg_hash, $module);
446 my $sql_statement= "SELECT * FROM known_server";
447 my $query_res = $known_server_db->select_dbentry( $sql_statement );
449 while( my ($hit_num, $hit) = each %{ $query_res } ) {
450 my $host_name = $hit->{hostname};
451 if( not $host_name =~ "^$remote_ip") {
452 next;
453 }
454 my $host_key = $hit->{hostkey};
455 daemon_log("SIPackages: known_server host_name: $host_name", 7);
456 daemon_log("SIPackages: known_server host_key: $host_key", 7);
458 # check if module can open msg envelope with module key
459 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key);
460 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
461 daemon_log("SIPackages: deciphering raise error", 7);
462 daemon_log("$@", 8);
463 next;
464 }
465 else {
466 $msg = $tmp_msg;
467 $msg_hash = $tmp_msg_hash;
468 $module = "SIPackages";
469 last;
470 }
471 }
473 if( (!$msg) || (!$msg_hash) || (!$module) ) {
474 daemon_log("Incoming message is not from a known server", 3);
475 }
477 return ($msg, $msg_hash, $module);
478 }
481 sub input_from_known_client {
482 my ($input, $remote_ip) = @_ ;
483 my ($msg, $msg_hash, $module);
485 my $sql_statement= "SELECT * FROM known_clients";
486 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
487 while( my ($hit_num, $hit) = each %{ $query_res } ) {
488 my $host_name = $hit->{hostname};
489 if( not $host_name =~ /^$remote_ip:\d*$/) {
490 next;
491 }
492 my $host_key = $hit->{hostkey};
493 &daemon_log("SIPackages: known_client host_name: $host_name", 7);
494 &daemon_log("SIPackages: known_client host_key: $host_key", 7);
496 # check if module can open msg envelope with module key
497 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
499 if( (!$msg) || (!$msg_hash) ) {
500 &daemon_log("SIPackages: deciphering raise error", 7);
501 &daemon_log("$@", 8);
502 next;
503 }
504 else {
505 $module = "SIPackages";
506 last;
507 }
508 }
510 if( (!$msg) || (!$msg_hash) || (!$module) ) {
511 &daemon_log("Incoming message is not from a known client", 3);
512 }
514 return ($msg, $msg_hash, $module);
515 }
518 sub input_from_unknown_host {
519 no strict "refs";
520 my ($input) = @_ ;
521 my ($msg, $msg_hash, $module);
523 my %act_modules = %$known_modules;
525 while( my ($mod, $info) = each(%act_modules)) {
526 # check a key exists for this module
527 my $module_key = ${$mod."_key"};
528 if( ! $module_key ) {
529 daemon_log("ERROR: no key specified in config file for $mod", 1);
530 next;
531 }
532 daemon_log("$mod: $module_key", 5);
534 # check if module can open msg envelope with module key
535 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
536 if( (!$msg) || (!$msg_hash) ) {
537 daemon_log("$mod: deciphering failed", 5);
538 next;
539 }
540 else {
541 $module = $mod;
542 last;
543 }
544 }
546 if( (!$msg) || (!$msg_hash) || (!$module)) {
547 daemon_log("Incoming message is not from a unknown host", 5);
548 }
550 return ($msg, $msg_hash, $module);
551 }
553 sub create_ciphering {
554 my ($passwd) = @_;
555 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
556 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
557 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
558 $my_cipher->set_iv($iv);
559 return $my_cipher;
560 }
563 sub encrypt_msg {
564 my ($msg, $key) = @_;
565 my $my_cipher = &create_ciphering($key);
566 {
567 use bytes;
568 $msg = "\0"x(16-length($msg)%16).$msg;
569 }
570 $msg = $my_cipher->encrypt($msg);
571 chomp($msg = &encode_base64($msg));
572 # there are no newlines allowed inside msg
573 $msg=~ s/\n//g;
574 return $msg;
575 }
578 sub decrypt_msg {
579 my ($msg, $key) = @_ ;
580 $msg = &decode_base64($msg);
581 my $my_cipher = &create_ciphering($key);
582 $msg = $my_cipher->decrypt($msg);
583 $msg =~ s/\0*//g;
584 return $msg;
585 }
588 sub get_encrypt_key {
589 my ($target) = @_ ;
590 my $encrypt_key;
591 my $error = 0;
593 # target can be in known_server
594 if( !$encrypt_key ) {
595 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
596 my $query_res = $known_server_db->select_dbentry( $sql_statement );
597 while( my ($hit_num, $hit) = each %{ $query_res } ) {
598 my $host_name = $hit->{hostname};
599 if( $host_name ne $target ) {
600 next;
601 }
602 $encrypt_key = $hit->{hostkey};
603 last;
604 }
605 }
608 # target can be in known_client
609 if( !$encrypt_key ) {
610 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
611 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
612 while( my ($hit_num, $hit) = each %{ $query_res } ) {
613 my $host_name = $hit->{hostname};
614 if( $host_name ne $target ) {
615 next;
616 }
617 $encrypt_key = $hit->{hostkey};
618 last;
619 }
620 }
622 return $encrypt_key;
623 }
626 #=== FUNCTION ================================================================
627 # NAME: open_socket
628 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
629 # [PeerPort] string necessary if port not appended by PeerAddr
630 # RETURNS: socket IO::Socket::INET
631 # DESCRIPTION: open a socket to PeerAddr
632 #===============================================================================
633 sub open_socket {
634 my ($PeerAddr, $PeerPort) = @_ ;
635 if(defined($PeerPort)){
636 $PeerAddr = $PeerAddr.":".$PeerPort;
637 }
638 my $socket;
639 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
640 Porto => "tcp",
641 Type => SOCK_STREAM,
642 Timeout => 5,
643 );
644 if(not defined $socket) {
645 return;
646 }
647 &daemon_log("open_socket: $PeerAddr", 7);
648 return $socket;
649 }
652 sub send_msg_to_target {
653 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
654 my $error = 0;
656 if( $msg_header ) {
657 $msg_header = "'$msg_header'-";
658 }
659 else {
660 $msg_header = "";
661 }
663 # encrypt xml msg
664 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
666 # opensocket
667 my $socket = &open_socket($address);
668 if( !$socket ) {
669 daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
670 $error++;
671 }
673 if( $error == 0 ) {
674 # send xml msg
675 print $socket $crypted_msg."\n";
677 daemon_log("send ".$msg_header."msg to $address", 1);
678 daemon_log("message:\n$msg", 8);
680 }
682 # close socket in any case
683 if( $socket ) {
684 close $socket;
685 }
687 return;
688 }
691 sub _start {
692 my ($kernel) = $_[KERNEL];
693 &trigger_db_loop($kernel);
694 }
697 sub client_input {
698 no strict "refs";
699 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
700 my ($msg, $msg_hash, $module);
701 my $error = 0;
702 my $answer_l;
703 my ($answer_header, @answer_target_l, $answer_source);
704 my $client_answer;
706 daemon_log("Incoming msg from '".$heap->{'remote_ip'}."'", 7);
707 daemon_log("\n$input", 8);
709 # msg is from a new client or gosa
710 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
712 # msg is from a gosa-si-server or gosa-si-bus
713 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
714 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
715 }
717 # msg is from a gosa-si-client
718 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
719 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
720 }
722 # an error occurred
723 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
724 $error++;
725 }
727 ######################
728 # process incoming msg
729 if( $error == 0) {
730 daemon_log("Processing module ".$module, 5);
731 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $heap->{'remote_ip'});
733 if ( 0 > @{$answer_l} ) {
734 my $answer_str = join("\n", @{$answer_l});
735 daemon_log("$module: Got answer from module: \n".$answer_str,8);
736 }
737 }
738 if( !$answer_l ) { $error++ };
740 ########
741 # answer
742 if( $error == 0 ) {
744 # for each answer in answer list
745 foreach my $answer ( @{$answer_l} ) {
747 my $error = 0;
748 # check answer if gosa-si envelope conform
749 if(defined($answer)) {
750 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
751 $answer_header = @{$answer_hash->{'header'}}[0];
752 @answer_target_l = @{$answer_hash->{'target'}};
753 $answer_source = @{$answer_hash->{'source'}}[0];
754 if( !$answer_header ) {
755 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
756 daemon_log("\n$answer", 8);
757 $error++;
758 }
759 if( 0 == length @answer_target_l ) {
760 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
761 daemon_log("\n$answer", 8);
762 $error++;
763 }
764 if( !$answer_source ) {
765 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
766 daemon_log("\n$answer", 8);
767 $error++;
768 }
770 if( $error != 0 ) {
771 next;
772 }
773 }
775 # deliver msg to all targets
776 foreach my $answer_target ( @answer_target_l ) {
777 if( $answer_target eq "*" ) {
778 # answer is for all clients
779 my $sql_statement= "SELECT * FROM known_clients";
780 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
781 while( my ($hit_num, $hit) = each %{ $query_res } ) {
782 my $host_name = $hit->{hostname};
783 my $host_key = $hit->{hostkey};
784 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
785 }
786 }
787 elsif( $answer_target eq "GOSA" ) {
788 # answer is for GOSA and has to returned to connected client
789 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
790 $client_answer = $gosa_answer;
791 }
792 elsif( $answer_target eq "KNOWN_SERVER" ) {
793 # answer is for all server in known_server
794 my $sql_statement= "SELECT * FROM known_server";
795 my $query_res = $known_server_db->select_dbentry( $sql_statement );
796 while( my ($hit_num, $hit) = each %{ $query_res } ) {
797 my $host_name = $hit->{hostname};
798 my $host_key = $hit->{hostkey};
799 $answer =~ s/KNOWN_SERVER/$host_name/g;
800 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
801 }
802 }
803 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})/ ) {
804 daemon_log("target is mac address '$answer_target', looking for host in known_clients", 3);
805 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$answer_target'";
806 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
807 my $found_ip_flag = 0;
808 while( my ($hit_num, $hit) = each %{ $query_res } ) {
809 my $host_name = $hit->{hostname};
810 my $host_key = $hit->{hostkey};
811 $answer =~ s/$answer_target/$host_name/g;
812 daemon_log("found host '$host_name', assoziated to '$answer_target'", 3);
813 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
814 $found_ip_flag++ ;
815 }
816 if( $found_ip_flag == 0) {
817 daemon_log("WARNING: no host found in known_clients with mac address '$answer_target', forward msg to bus", 1);
818 my $sql_statement = "SELECT * FROM known_server WHERE status='bus'";
819 my $query_res = $known_server_db->select_dbentry( $sql_statement );
820 while( my ($hit_num, $hit) = each %{ $query_res } ) {
821 my $bus_address = $hit->{hostname};
822 my $bus_key = $hit->{hostkey};
823 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
824 last;
825 }
827 }
828 }
829 else {
830 # answer is for one specific host
831 # get encrypt_key
832 my $encrypt_key = &get_encrypt_key($answer_target);
833 if( !$encrypt_key ) {
834 # unknown target, forward msg to bus
835 daemon_log("WARNING: unknown target '$answer_target', forward msg to bus", 3);
836 my $sql_statement = "SELECT * FROM known_server WHERE status='bus'";
837 my $query_res = $known_server_db->select_dbentry( $sql_statement );
838 my $bus_address = $query_res->{1}->{hostname};
839 my $bus_key = $query_res->{1}->{hostkey};
840 &send_msg_to_target($answer, $bus_address, $bus_key, $answer_header);
841 next;
842 }
843 # send_msg
844 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
845 }
846 }
847 }
848 }
850 if( $client_answer ) {
851 $heap->{client}->put($client_answer);
852 }
854 return;
855 }
859 sub trigger_db_loop {
860 # my ($kernel) = $_[KERNEL];
861 my ($kernel) = @_ ;
862 $kernel->delay_set('watch_for_new_jobs',3);
863 }
866 sub watch_for_new_jobs {
867 my ($kernel,$heap) = @_[KERNEL, HEAP];
869 # check gosa job queue for jobs with executable timestamp
870 my $timestamp = &get_time();
872 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
873 " WHERE status='waiting' AND timestamp<'$timestamp'";
875 my $res = $job_db->select_dbentry( $sql_statement );
877 while( my ($id, $hit) = each %{$res} ) {
879 my $jobdb_id = $hit->{id};
880 my $macaddress = $hit->{macaddress};
881 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
882 my $out_msg_hash = $job_msg_hash;
883 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
884 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
885 # expect macaddress is unique!!!!!!
886 my $target = $res_hash->{1}->{hostname};
888 if (not defined $target) {
889 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
890 &daemon_log("xml message: $hit->{xmlmessage}", 5);
891 my $sql_statement = "UPDATE $job_queue_table_name ".
892 "SET status='error', result='no host found for mac address' ".
893 "WHERE id='$jobdb_id'";
894 my $res = $job_db->update_dbentry($sql_statement);
895 next;
896 }
898 # add target
899 &add_content2xml_hash($out_msg_hash, "target", $target);
901 # add new header
902 my $out_header = $job_msg_hash->{header}[0];
903 $out_header =~ s/job_/gosa_/;
904 delete $out_msg_hash->{header};
905 &add_content2xml_hash($out_msg_hash, "header", $out_header);
907 # add sqlite_id
908 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
910 my $out_msg = &create_xml_string($out_msg_hash);
912 # encrypt msg as a GosaPackage module
913 my $cipher = &create_ciphering($GosaPackages_key);
914 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
916 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
918 if ($error == 0) {
919 my $sql_statement = "UPDATE $job_queue_table_name ".
920 "SET status='processing', targettag='$target' ".
921 "WHERE id='$jobdb_id'";
922 my $res = $job_db->update_dbentry($sql_statement);
923 } else {
924 my $sql_statement = "UPDATE $job_queue_table_name ".
925 "SET status='error' ".
926 "WHERE id='$jobdb_id'";
927 my $res = $job_db->update_dbentry($sql_statement);
928 }
929 }
931 $kernel->delay_set('watch_for_new_jobs',3);
932 }
935 #==== MAIN = main ==============================================================
936 # parse commandline options
937 Getopt::Long::Configure( "bundling" );
938 GetOptions("h|help" => \&usage,
939 "c|config=s" => \$cfg_file,
940 "f|foreground" => \$foreground,
941 "v|verbose+" => \$verbose,
942 "no-bus+" => \$no_bus,
943 "no-arp+" => \$no_arp,
944 );
946 # read and set config parameters
947 &check_cmdline_param ;
948 &read_configfile;
949 &check_pid;
951 $SIG{CHLD} = 'IGNORE';
953 # forward error messages to logfile
954 if( ! $foreground ) {
955 open(STDERR, '>>', $log_file);
956 open(STDOUT, '>>', $log_file);
957 }
959 # Just fork, if we are not in foreground mode
960 if( ! $foreground ) {
961 chdir '/' or die "Can't chdir to /: $!";
962 $pid = fork;
963 setsid or die "Can't start a new session: $!";
964 umask 0;
965 } else {
966 $pid = $$;
967 }
969 # Do something useful - put our PID into the pid_file
970 if( 0 != $pid ) {
971 open( LOCK_FILE, ">$pid_file" );
972 print LOCK_FILE "$pid\n";
973 close( LOCK_FILE );
974 if( !$foreground ) {
975 exit( 0 )
976 };
977 }
979 daemon_log(" ", 1);
980 daemon_log("$0 started!", 1);
982 # delete old DBsqlite lock files
983 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
985 # connect to gosa-si job queue
986 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
987 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
988 $job_db->create_table('jobs', \@job_col_names);
990 # connect to known_clients_db
991 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
992 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
993 $known_clients_db->create_table('known_clients', \@clients_col_names);
995 # connect to known_server_db
996 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
997 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
998 $known_server_db->create_table('known_server', \@server_col_names);
1000 # create xml object used for en/decrypting
1001 $xml = new XML::Simple();
1003 # create socket for incoming xml messages
1004 POE::Component::Server::TCP->new(
1005 Port => $server_port,
1006 ClientInput => \&client_input,
1007 );
1008 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
1010 # create session for repeatedly checking the job queue for jobs
1011 POE::Session->create(
1012 inline_states => {
1013 _start => \&_start,
1014 watch_for_new_jobs => \&watch_for_new_jobs,
1015 }
1016 );
1019 # import all modules
1020 &import_modules;
1022 # check wether all modules are gosa-si valid passwd check
1024 POE::Kernel->run();
1025 exit;