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;
28 use Time::HiRes qw( gettimeofday );
30 use Fcntl;
31 use IO::Socket::INET;
32 use IO::Handle;
33 use IO::Select;
34 use Symbol qw(qualify_to_ref);
35 use Crypt::Rijndael;
36 use MIME::Base64;
37 use Digest::MD5 qw(md5 md5_hex md5_base64);
38 use XML::Simple;
39 use Data::Dumper;
40 use Sys::Syslog qw( :DEFAULT setlogsock);
41 use Cwd;
42 use File::Spec;
43 use GOSA::DBsqlite;
44 use POE qw(Component::Server::TCP);
46 my $modules_path = "/usr/lib/gosa-si/modules";
47 use lib "/usr/lib/gosa-si/modules";
49 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
50 my ($bus, $msg_to_bus, $bus_cipher);
51 my ($server, $server_mac_address, $server_events);
52 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name,$job_queue_loop_delay);
53 my ($known_modules, $known_clients_file_name, $known_server_file_name);
54 my ($max_clients);
55 my ($pid_file, $procid, $pid, $log_file);
56 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
57 my ($arp_activ, $arp_fifo, $arp_fifo_path);
58 my ($xml);
60 # variables declared in config file are always set to 'our'
61 our (%cfg_defaults, $log_file, $pid_file,
62 $bus_activ, $bus_passwd, $bus_ip, $bus_port,
63 $server_activ, $server_ip, $server_port, $SIPackages_key, $max_clients,
64 $arp_activ, $arp_fifo_path,
65 $gosa_activ, $GosaPackages_key, $gosa_ip, $gosa_port, $gosa_timeout,
66 );
68 # additional variable which should be globaly accessable
69 our $server_address;
70 our $bus_address;
71 our $gosa_address;
72 our $no_bus;
73 our $no_arp;
74 our $verbose;
75 our $forground;
76 our $cfg_file;
78 # specifies the verbosity of the daemon_log
79 $verbose = 0 ;
81 # if foreground is not null, script will be not forked to background
82 $foreground = 0 ;
84 # specifies the timeout seconds while checking the online status of a registrating client
85 $ping_timeout = 5;
87 $no_bus = 0;
89 $no_arp = 0;
91 # name of table for storing gosa jobs
92 our $job_queue_table_name = 'jobs';
93 our $job_db;
95 # holds all other gosa-sd as well as the gosa-sd-bus
96 our $known_server_db;
98 # holds all registrated clients
99 our $known_clients_db;
101 %cfg_defaults =
102 ("general" =>
103 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
104 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
105 "child_max" => [\$child_max, 10],
106 "child_min" => [\$child_min, 3],
107 "child_timeout" => [\$child_timeout, 180],
108 "job_queue_timeout" => [\$job_queue_timeout, undef],
109 "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/gosa-si-server_jobs.db'],
110 "job_queue_loop_delay" => [\$job_queue_loop_delay, 3],
111 "known_clients_file_name" => [\$known_clients_file_name, '/var/lib/gosa-si/gosa-si-server_known_clients.db' ],
112 "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/gosa-si-server_known_server.db'],
113 },
114 "bus" =>
115 {"bus_activ" => [\$bus_activ, "on"],
116 "bus_passwd" => [\$bus_passwd, ""],
117 "bus_ip" => [\$bus_ip, "0.0.0.0"],
118 "bus_port" => [\$bus_port, "20080"],
119 },
120 "server" =>
121 {"server_activ" => [\$server_activ, "on"],
122 "server_ip" => [\$server_ip, "0.0.0.0"],
123 "server_port" => [\$server_port, "20081"],
124 "SIPackages_key" => [\$SIPackages_key, "none"],
125 "max_clients" => [\$max_clients, 100],
126 },
127 "arp" =>
128 {"arp_activ" => [\$arp_activ, "on"],
129 "arp_fifo_path" => [\$arp_fifo_path, "/var/run/gosa-si/arp-notify"],
130 },
131 "gosa" =>
132 {"gosa_activ" => [\$gosa_activ, "on"],
133 "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
134 "gosa_port" => [\$gosa_port, "20082"],
135 "GosaPackages_key" => [\$GosaPackages_key, "none"],
136 },
137 );
140 #=== FUNCTION ================================================================
141 # NAME: usage
142 # PARAMETERS: nothing
143 # RETURNS: nothing
144 # DESCRIPTION: print out usage text to STDERR
145 #===============================================================================
146 sub usage {
147 print STDERR << "EOF" ;
148 usage: $0 [-hvf] [-c config]
150 -h : this (help) message
151 -c <file> : config file
152 -f : foreground, process will not be forked to background
153 -v : be verbose (multiple to increase verbosity)
154 -no-bus : starts $0 without connection to bus
155 -no-arp : starts $0 without connection to arp module
157 EOF
158 print "\n" ;
159 }
162 #=== FUNCTION ================================================================
163 # NAME: read_configfile
164 # PARAMETERS: cfg_file - string -
165 # RETURNS: nothing
166 # DESCRIPTION: read cfg_file and set variables
167 #===============================================================================
168 sub read_configfile {
169 my $cfg;
170 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
171 if( -r $cfg_file ) {
172 $cfg = Config::IniFiles->new( -file => $cfg_file );
173 } else {
174 print STDERR "Couldn't read config file!\n";
175 }
176 } else {
177 $cfg = Config::IniFiles->new() ;
178 }
179 foreach my $section (keys %cfg_defaults) {
180 foreach my $param (keys %{$cfg_defaults{ $section }}) {
181 my $pinfo = $cfg_defaults{ $section }{ $param };
182 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
183 }
184 }
185 }
188 #=== FUNCTION ================================================================
189 # NAME: logging
190 # PARAMETERS: level - string - default 'info'
191 # msg - string -
192 # facility - string - default 'LOG_DAEMON'
193 # RETURNS: nothing
194 # DESCRIPTION: function for logging
195 #===============================================================================
196 sub daemon_log {
197 # log into log_file
198 my( $msg, $level ) = @_;
199 if(not defined $msg) { return }
200 if(not defined $level) { $level = 1 }
201 if(defined $log_file){
202 open(LOG_HANDLE, ">>$log_file");
203 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
204 print STDERR "cannot open $log_file: $!";
205 return }
206 chomp($msg);
207 if($level <= $verbose){
208 my ($seconds, $minutes, $hours, $monthday, $month,
209 $year, $weekday, $yearday, $sommertime) = localtime(time);
210 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
211 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
212 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
213 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
214 $month = $monthnames[$month];
215 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
216 $year+=1900;
217 my $name = $0;
218 $name =~ s/\.\///;
220 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
221 print LOG_HANDLE $log_msg;
222 if( $foreground ) {
223 print STDERR $log_msg;
224 }
225 }
226 close( LOG_HANDLE );
227 }
228 #log into syslog
229 # my ($msg, $level, $facility) = @_;
230 # if(not defined $msg) {return}
231 # if(not defined $level) {$level = "info"}
232 # if(not defined $facility) {$facility = "LOG_DAEMON"}
233 # openlog($0, "pid,cons,", $facility);
234 # syslog($level, $msg);
235 # closelog;
236 # return;
237 }
240 sub get_time {
241 my ($seconds, $minutes, $hours, $monthday, $month,
242 $year, $weekday, $yearday, $sommertime) = localtime(time);
243 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
244 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
245 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
246 $month+=1;
247 $month = $month < 10 ? $month = "0".$month : $month;
248 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
249 $year+=1900;
250 return "$year$month$monthday$hours$minutes$seconds";
252 }
255 #=== FUNCTION ================================================================
256 # NAME: check_cmdline_param
257 # PARAMETERS: nothing
258 # RETURNS: nothing
259 # DESCRIPTION: validates commandline parameter
260 #===============================================================================
261 sub check_cmdline_param () {
262 my $err_config;
263 my $err_counter = 0;
264 if(not defined($cfg_file)) {
265 $cfg_file = "/etc/gosa-si/server.conf";
266 if(! -r $cfg_file) {
267 $err_config = "please specify a config file";
268 $err_counter += 1;
269 }
270 }
271 if( $err_counter > 0 ) {
272 &usage( "", 1 );
273 if( defined( $err_config)) { print STDERR "$err_config\n"}
274 print STDERR "\n";
275 exit( -1 );
276 }
277 }
280 #=== FUNCTION ================================================================
281 # NAME: check_pid
282 # PARAMETERS: nothing
283 # RETURNS: nothing
284 # DESCRIPTION: handels pid processing
285 #===============================================================================
286 sub check_pid {
287 $pid = -1;
288 # Check, if we are already running
289 if( open(LOCK_FILE, "<$pid_file") ) {
290 $pid = <LOCK_FILE>;
291 if( defined $pid ) {
292 chomp( $pid );
293 if( -f "/proc/$pid/stat" ) {
294 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
295 if( $0 eq $stat ) {
296 close( LOCK_FILE );
297 exit -1;
298 }
299 }
300 }
301 close( LOCK_FILE );
302 unlink( $pid_file );
303 }
305 # create a syslog msg if it is not to possible to open PID file
306 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
307 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
308 if (open(LOCK_FILE, '<', $pid_file)
309 && ($pid = <LOCK_FILE>))
310 {
311 chomp($pid);
312 $msg .= "(PID $pid)\n";
313 } else {
314 $msg .= "(unable to read PID)\n";
315 }
316 if( ! ($foreground) ) {
317 openlog( $0, "cons,pid", "daemon" );
318 syslog( "warning", $msg );
319 closelog();
320 }
321 else {
322 print( STDERR " $msg " );
323 }
324 exit( -1 );
325 }
326 }
328 #=== FUNCTION ================================================================
329 # NAME: import_modules
330 # PARAMETERS: module_path - string - abs. path to the directory the modules
331 # are stored
332 # RETURNS: nothing
333 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
334 # state is on is imported by "require 'file';"
335 #===============================================================================
336 sub import_modules {
337 daemon_log(" ", 1);
339 if (not -e $modules_path) {
340 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
341 }
343 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
344 while (defined (my $file = readdir (DIR))) {
345 if (not $file =~ /(\S*?).pm$/) {
346 next;
347 }
348 my $mod_name = $1;
350 if( $file =~ /ArpHandler.pm/ ) {
351 if( $no_arp > 0 ) {
352 next;
353 }
354 }
356 eval { require $file; };
357 if ($@) {
358 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
359 daemon_log("$@", 5);
360 } else {
361 my $info = eval($mod_name.'::get_module_info()');
362 # Only load module if get_module_info() returns a non-null object
363 if( $info ) {
364 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
365 $known_modules->{$mod_name} = $info;
366 daemon_log("module $mod_name loaded", 1);
367 }
368 }
369 }
370 close (DIR);
371 }
374 #=== FUNCTION ================================================================
375 # NAME: sig_int_handler
376 # PARAMETERS: signal - string - signal arose from system
377 # RETURNS: noting
378 # DESCRIPTION: handels tasks to be done befor signal becomes active
379 #===============================================================================
380 sub sig_int_handler {
381 my ($signal) = @_;
383 daemon_log("shutting down gosa-si-server", 1);
384 exit(1);
385 }
386 $SIG{INT} = \&sig_int_handler;
390 sub check_key_and_xml_validity {
391 my ($crypted_msg, $module_key) = @_;
392 #print STDERR "crypted_msg:$crypted_msg\n";
393 #print STDERR "modul_key:$module_key\n";
395 my $msg;
396 my $msg_hash;
397 eval{
398 $msg = &decrypt_msg($crypted_msg, $module_key);
399 &main::daemon_log("decrypted_msg: \n$msg", 8);
401 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
403 # check header
404 my $header_l = $msg_hash->{'header'};
405 if( 1 != @{$header_l} ) {
406 die'header error';
407 }
408 my $header = @{$header_l}[0];
409 if( 0 == length $header) {
410 die 'header error';
411 }
413 # check source
414 my $source_l = $msg_hash->{'source'};
415 if( 1 != @{$source_l} ) {
416 die'source error';
417 }
418 my $source = @{$source_l}[0];
419 if( 0 == length $source) {
420 die 'source error';
421 }
423 # check target
424 my $target_l = $msg_hash->{'target'};
425 if( 1 != @{$target_l} ) {
426 die'target error';
427 }
428 my $target = @{$target_l}[0];
429 if( 0 == length $target) {
430 die 'target error';
431 }
433 };
434 if($@) {
435 &main::daemon_log("WARNING: do not understand the message:", 5);
436 &main::daemon_log("$@", 8);
437 }
439 return ($msg, $msg_hash);
440 }
443 sub input_from_known_server {
444 my ($input, $remote_ip) = @_ ;
445 my ($msg, $msg_hash, $module);
447 my $sql_statement= "SELECT * FROM known_server";
448 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: host_name: $host_name", 7);
456 daemon_log("SIPackages: host_key: $host_key", 7);
458 # check if module can open msg envelope with module key
459 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
460 if( (!$msg) || (!$msg_hash) ) {
461 daemon_log("SIPackages: deciphering raise error", 7);
462 daemon_log("$@", 8);
463 next;
464 }
465 else {
466 $module = "SIPackages";
467 last;
468 }
469 }
471 if( (!$msg) || (!$msg_hash) || (!$module) ) {
472 daemon_log("Incoming message is not from a known server", 3);
473 }
475 return ($msg, $msg_hash, $module);
476 }
479 sub input_from_known_client {
480 my ($input, $remote_ip) = @_ ;
481 my ($msg, $msg_hash, $module);
483 my $sql_statement= "SELECT * FROM known_clients";
484 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
485 while( my ($hit_num, $hit) = each %{ $query_res } ) {
486 my $host_name = $hit->{hostname};
487 if( not $host_name =~ /^$remote_ip:\d*$/) {
488 next;
489 }
490 my $host_key = $hit->{hostkey};
491 &daemon_log("SIPackages: host_name: $host_name", 7);
492 &daemon_log("SIPackages: host_key: $host_key", 7);
494 # check if module can open msg envelope with module key
495 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
497 if( (!$msg) || (!$msg_hash) ) {
498 &daemon_log("SIPackages: deciphering raise error", 7);
499 &daemon_log("$@", 8);
500 next;
501 }
502 else {
503 $module = "SIPackages";
504 last;
505 }
506 }
508 if( (!$msg) || (!$msg_hash) || (!$module) ) {
509 &daemon_log("Incoming message is not from a known client", 3);
510 }
512 return ($msg, $msg_hash, $module);
513 }
516 sub input_from_unknown_host {
517 no strict "refs";
518 my ($input) = @_ ;
519 my ($msg, $msg_hash, $module);
521 my %act_modules = %$known_modules;
523 while( my ($mod, $info) = each(%act_modules)) {
524 # check a key exists for this module
525 my $module_key = ${$mod."_key"};
526 if( ! $module_key ) {
527 daemon_log("ERROR: no key specified in config file for $mod", 1);
528 next;
529 }
530 daemon_log("$mod: $module_key", 5);
532 # check if module can open msg envelope with module key
533 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
534 if( (!$msg) || (!$msg_hash) ) {
535 daemon_log("$mod: deciphering failed", 5);
536 next;
537 }
538 else {
539 $module = $mod;
540 last;
541 }
542 }
544 if( (!$msg) || (!$msg_hash) || (!$module)) {
545 daemon_log("Incoming message is not from a unknown host", 3);
546 }
548 return ($msg, $msg_hash, $module);
549 }
551 sub create_ciphering {
552 my ($passwd) = @_;
553 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
554 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
555 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
556 $my_cipher->set_iv($iv);
557 return $my_cipher;
558 }
561 sub encrypt_msg {
562 my ($msg, $key) = @_;
563 my $my_cipher = &create_ciphering($key);
564 {
565 use bytes;
566 $msg = "\0"x(16-length($msg)%16).$msg;
567 }
568 $msg = $my_cipher->encrypt($msg);
569 chomp($msg = &encode_base64($msg));
570 # there are no newlines allowed inside msg
571 $msg=~ s/\n//g;
572 return $msg;
573 }
576 sub decrypt_msg {
577 my ($msg, $key) = @_ ;
578 $msg = &decode_base64($msg);
579 my $my_cipher = &create_ciphering($key);
580 $msg = $my_cipher->decrypt($msg);
581 $msg =~ s/\0*//g;
582 return $msg;
583 }
586 sub get_encrypt_key {
587 my ($target) = @_ ;
588 my $encrypt_key;
589 my $error = 0;
591 # target can be in known_server
592 if( !$encrypt_key ) {
593 my $sql_statement= "SELECT * FROM known_server";
594 my $query_res = $known_server_db->select_dbentry( $sql_statement );
595 while( my ($hit_num, $hit) = each %{ $query_res } ) {
596 my $host_name = $hit->{hostname};
597 if( $host_name ne $target ) {
598 next;
599 }
600 my $host_key = $hit->{hostkey};
601 last;
602 }
603 }
606 # target can be in known_client
607 if( !$encrypt_key ) {
608 my $sql_statement= "SELECT * FROM known_clients";
609 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
610 while( my ($hit_num, $hit) = each %{ $query_res } ) {
611 my $host_name = $hit->{hostname};
612 if( $host_name ne $target ) {
613 next;
614 }
615 $encrypt_key = $hit->{hostkey};
616 last;
617 }
618 }
620 return $encrypt_key;
621 }
624 #=== FUNCTION ================================================================
625 # NAME: open_socket
626 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
627 # [PeerPort] string necessary if port not appended by PeerAddr
628 # RETURNS: socket IO::Socket::INET
629 # DESCRIPTION: open a socket to PeerAddr
630 #===============================================================================
631 sub open_socket {
632 my ($PeerAddr, $PeerPort) = @_ ;
633 if(defined($PeerPort)){
634 $PeerAddr = $PeerAddr.":".$PeerPort;
635 }
636 my $socket;
637 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
638 Porto => "tcp",
639 Type => SOCK_STREAM,
640 Timeout => 5,
641 );
642 if(not defined $socket) {
643 return;
644 }
645 &daemon_log("open_socket: $PeerAddr", 7);
646 return $socket;
647 }
650 sub send_msg_to_target {
651 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
652 my $error = 0;
654 if( $msg_header ) {
655 $msg_header = "'$msg_header'-";
656 }
657 else {
658 $msg_header = "";
659 }
661 # encrypt xml msg
662 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
664 # opensocket
665 my $socket = &open_socket($address);
666 if( !$socket ) {
667 daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
668 $error++;
669 }
671 if( $error == 0 ) {
672 # send xml msg
673 print $socket $crypted_msg."\n";
675 daemon_log("send ".$msg_header."msg to $address", 1);
676 daemon_log("message:\n$msg", 8);
678 }
680 # close socket in any case
681 if( $socket ) {
682 close $socket;
683 }
685 return;
686 }
689 sub _start {
690 my ($kernel) = $_[KERNEL];
691 &trigger_db_loop($kernel);
692 }
695 sub client_input {
696 no strict "refs";
697 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
698 my ($msg, $msg_hash, $module);
699 my $error = 0;
700 my $answer_l;
701 my ($answer_header, @answer_target_l, $answer_source);
702 my $client_answer;
704 daemon_log("Incoming msg:\n$input\n", 8);
706 # msg is from a new client or gosa
707 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
709 # msg is from a gosa-si-server or gosa-si-bus
710 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
711 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
712 }
714 # msg is from a gosa-si-client
715 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
716 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
717 }
719 # an error occurred
720 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
721 $error++;
722 }
724 ######################
725 # process incoming msg
726 if( $error == 0) {
727 daemon_log("Processing module ".$module, 3);
728 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
730 if ( 0 > @{$answer_l} ) {
731 my $answer_str = join("\n", @{$answer_l});
732 daemon_log("$module: Got answer from module: \n".$answer_str,8);
733 }
734 }
735 if( !$answer_l ) { $error++ };
737 if( $error == 0 ) {
739 # for each answer in answer list
740 foreach my $answer ( @{$answer_l} ) {
742 # check answer if gosa-si envelope conform
743 if( $error == 0 ) {
744 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
745 $answer_header = @{$answer_hash->{'header'}}[0];
746 @answer_target_l = @{$answer_hash->{'target'}};
747 $answer_source = @{$answer_hash->{'source'}}[0];
748 if( !$answer_header ) {
749 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
750 $error++;
751 }
752 if( 0 == length @answer_target_l ) {
753 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
754 $error++;
755 }
756 if( !$answer_source ) {
757 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
758 $error++;
759 }
761 if( $error != 0 ) {
762 next;
763 }
765 # deliver msg to all targets
766 foreach my $answer_target ( @answer_target_l ) {
767 if( $answer_target eq "*" ) {
768 # answer is for all clients
769 my $sql_statement= "SELECT * FROM known_clients";
770 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
771 while( my ($hit_num, $hit) = each %{ $query_res } ) {
772 my $host_name = $hit->{hostname};
773 my $host_key = $hit->{hostkey};
774 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
775 }
776 }
777 elsif( $answer_target eq "GOSA" ) {
778 # answer is for GOSA and has to returned to connected client
779 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
780 $client_answer = $gosa_answer;
781 }
782 elsif( $answer_target eq "KNOWN_SERVER" ) {
783 # answer is for all server in known_server
784 my $sql_statement= "SELECT * FROM known_server";
785 my $query_res = $known_server_db->select_dbentry( $sql_statement );
786 while( my ($hit_num, $hit) = each %{ $query_res } ) {
787 my $host_name = $hit->{hostname};
788 my $host_key = $hit->{hostkey};
789 $answer =~ s/KNOWN_SERVER/$host_name/g;
790 &send_msg_to_target($answer, $host_name, $host_key, $answer_header);
791 }
792 }
793 else {
794 # answer is for one specific host
795 # get encrypt_key
796 my $encrypt_key = &get_encrypt_key($answer_target);
797 if( !$encrypt_key ) {
798 daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
799 next;
800 }
801 # send_msg
802 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
803 }
804 }
805 }
806 }
807 }
809 if( $client_answer ) {
810 $heap->{client}->put($client_answer);
811 }
813 return;
814 }
818 sub trigger_db_loop {
819 # my ($kernel) = $_[KERNEL];
820 my ($kernel) = @_ ;
821 $kernel->delay_set('watch_for_new_jobs',3);
822 }
825 sub watch_for_new_jobs {
826 my ($kernel,$heap) = @_[KERNEL, HEAP];
828 # check gosa job queue for jobs with executable timestamp
829 my $timestamp = &get_time();
831 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
832 " WHERE status='waiting' AND timestamp<'$timestamp'";
834 my $res = $job_db->select_dbentry( $sql_statement );
836 while( my ($id, $hit) = each %{$res} ) {
838 my $jobdb_id = $hit->{id};
839 my $macaddress = $hit->{macaddress};
840 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
841 my $out_msg_hash = $job_msg_hash;
842 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
843 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
844 # expect macaddress is unique!!!!!!
845 my $target = $res_hash->{1}->{hostname};
847 if (not defined $target) {
848 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
849 &daemon_log("xml message: $hit->{xmlmessage}", 5);
850 my $sql_statement = "UPDATE $job_queue_table_name ".
851 "SET status='error', result='no host found for mac address' ".
852 "WHERE id='$jobdb_id'";
853 my $res = $job_db->update_dbentry($sql_statement);
854 next;
855 }
857 # add target
858 &add_content2xml_hash($out_msg_hash, "target", $target);
860 # add new header
861 my $out_header = $job_msg_hash->{header}[0];
862 $out_header =~ s/job_/gosa_/;
863 delete $out_msg_hash->{header};
864 &add_content2xml_hash($out_msg_hash, "header", $out_header);
866 # add sqlite_id
867 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
869 my $out_msg = &create_xml_string($out_msg_hash);
871 # encrypt msg as a GosaPackage module
872 my $cipher = &create_ciphering($GosaPackages_key);
873 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
875 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
877 if ($error == 0) {
878 my $sql_statement = "UPDATE $job_queue_table_name ".
879 "SET status='processing', targettag='$target' ".
880 "WHERE id='$jobdb_id'";
881 my $res = $job_db->update_dbentry($sql_statement);
882 } else {
883 my $sql_statement = "UPDATE $job_queue_table_name ".
884 "SET status='error' ".
885 "WHERE id='$jobdb_id'";
886 my $res = $job_db->update_dbentry($sql_statement);
887 }
888 }
890 $kernel->delay_set('watch_for_new_jobs',3);
891 }
894 #==== MAIN = main ==============================================================
895 # parse commandline options
896 Getopt::Long::Configure( "bundling" );
897 GetOptions("h|help" => \&usage,
898 "c|config=s" => \$cfg_file,
899 "f|foreground" => \$foreground,
900 "v|verbose+" => \$verbose,
901 "no-bus+" => \$no_bus,
902 "no-arp+" => \$no_arp,
903 );
905 # read and set config parameters
906 &check_cmdline_param ;
907 &read_configfile;
908 &check_pid;
910 $SIG{CHLD} = 'IGNORE';
912 # forward error messages to logfile
913 if( ! $foreground ) {
914 open(STDERR, '>>', $log_file);
915 open(STDOUT, '>>', $log_file);
916 }
918 # Just fork, if we are not in foreground mode
919 if( ! $foreground ) {
920 chdir '/' or die "Can't chdir to /: $!";
921 $pid = fork;
922 setsid or die "Can't start a new session: $!";
923 umask 0;
924 } else {
925 $pid = $$;
926 }
928 # Do something useful - put our PID into the pid_file
929 if( 0 != $pid ) {
930 open( LOCK_FILE, ">$pid_file" );
931 print LOCK_FILE "$pid\n";
932 close( LOCK_FILE );
933 if( !$foreground ) {
934 exit( 0 )
935 };
936 }
938 daemon_log(" ", 1);
939 daemon_log("$0 started!", 1);
941 # delete old DBsqlite lock files
942 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
944 # connect to gosa-si job queue
945 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
946 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
947 $job_db->create_table('jobs', \@job_col_names);
949 # connect to known_clients_db
950 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
951 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
952 $known_clients_db->create_table('known_clients', \@clients_col_names);
954 # connect to known_server_db
955 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
956 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
957 $known_server_db->create_table('known_server', \@server_col_names);
959 # import all modules
960 &import_modules;
962 # check wether all modules are gosa-si valid passwd check
964 # create xml object used for en/decrypting
965 $xml = new XML::Simple();
968 # create socket for incoming xml messages
969 POE::Component::Server::TCP->new(
970 Port => $server_port,
971 ClientInput => \&client_input,
972 );
973 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
975 # create session for repeatedly checking the job queue for jobs
976 POE::Session->create(
977 inline_states => {
978 _start => \&_start,
979 watch_for_new_jobs => \&watch_for_new_jobs,
980 }
981 );
983 POE::Kernel->run();
984 exit;