96aea80fcc24204fccfef7c733c59cc99c85d042
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/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/known_clients.db' ],
112 "known_server_file_name" => [\$known_server_file_name, '/var/lib/gosa-si/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 }
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 }
360 else {
361 my $mod_name = $1;
362 my $info = eval($mod_name.'::get_module_info()');
363 # Only load module if get_module_info() returns a non-null object
364 if(defined($info)) {
365 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
366 $known_modules->{$mod_name} = $info;
367 daemon_log("module $mod_name loaded", 1);
368 }
369 }
370 }
371 close (DIR);
372 }
375 #=== FUNCTION ================================================================
376 # NAME: sig_int_handler
377 # PARAMETERS: signal - string - signal arose from system
378 # RETURNS: noting
379 # DESCRIPTION: handels tasks to be done befor signal becomes active
380 #===============================================================================
381 sub sig_int_handler {
382 my ($signal) = @_;
384 daemon_log("shutting down gosa-si-server", 1);
385 exit(1);
386 }
387 $SIG{INT} = \&sig_int_handler;
391 sub check_key_and_xml_validity {
392 my ($crypted_msg, $module_key) = @_;
393 #print STDERR "crypted_msg:$crypted_msg\n";
394 #print STDERR "modul:$module\n";
395 #print STDERR "modul_key:$module_key\n";
397 my $msg;
398 my $msg_hash;
399 eval{
400 $msg = &decrypt_msg($crypted_msg, $module_key);
401 &main::daemon_log("decrypted_msg: \n$msg", 8);
403 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
405 # check header
406 my $header_l = $msg_hash->{'header'};
407 if( 1 != @{$header_l} ) {
408 die'header error';
409 }
410 my $header = @{$header_l}[0];
411 if( 0 == length $header) {
412 die 'header error';
413 }
415 # check source
416 my $source_l = $msg_hash->{'source'};
417 if( 1 != @{$source_l} ) {
418 die'source error';
419 }
420 my $source = @{$source_l}[0];
421 if( 0 == length $source) {
422 die 'source error';
423 }
425 # check target
426 my $target_l = $msg_hash->{'target'};
427 if( 1 != @{$target_l} ) {
428 die'target error';
429 }
430 my $target = @{$target_l}[0];
431 if( 0 == length $target) {
432 die 'target error';
433 }
435 };
436 if($@) {
437 &main::daemon_log("WARNING: do not understand the message:", 5);
438 &main::daemon_log("$@", 8);
439 }
441 return ($msg, $msg_hash);
442 }
445 sub input_from_known_server {
446 my ($input, $remote_ip) = @_ ;
447 my ($msg, $msg_hash, $module);
450 my $sql_statement= "SELECT * FROM known_server";
451 my $query_res = $known_server_db->select_dbentry( $sql_statement );
452 while( my ($hit_num, $hit) = each %{ $query_res } ) {
453 my $host_name = $hit->{hostname};
454 if( not $host_name =~ "^$remote_ip") {
455 next;
456 }
457 my $host_key = $hit->{hostkey};
458 daemon_log("ServerPackages: host_name: $host_name", 7);
459 daemon_log("ServerPackages: host_key: $host_key", 7);
461 # check if module can open msg envelope with module key
462 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
463 if( (!$msg) || (!$msg_hash) ) {
464 daemon_log("ServerPackages: deciphering raise error", 7);
465 daemon_log("$@", 8);
466 next;
467 }
468 else {
469 $module = "ServerPackages";
470 last;
471 }
472 }
474 if( (!$msg) || (!$msg_hash) || (!$module) ) {
475 daemon_log("Incoming message is not from a known server", 3);
476 }
478 return ($msg, $msg_hash, $module);
479 }
482 sub input_from_known_client {
483 my ($input, $remote_ip) = @_ ;
484 my ($msg, $msg_hash, $module);
486 my $sql_statement= "SELECT * FROM known_clients";
487 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
488 while( my ($hit_num, $hit) = each %{ $query_res } ) {
489 my $host_name = $hit->{hostname};
490 if( not $host_name =~ "^$remote_ip") {
491 next;
492 }
493 my $host_key = $hit->{hostkey};
494 daemon_log("ServerPackages: host_name: $host_name", 7);
495 daemon_log("ServerPackages: host_key: $host_key", 7);
497 # check if module can open msg envelope with module key
498 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
499 if( (!$msg) || (!$msg_hash) ) {
500 daemon_log("ServerPackages: deciphering raise error", 7);
501 daemon_log("$@", 8);
502 next;
503 }
504 else {
505 $module = "ServerPackages";
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", 3);
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 $msg = "\0"x(16-length($msg)%16).$msg;
567 $msg = $my_cipher->encrypt($msg);
568 chomp($msg = &encode_base64($msg));
569 # there are no newlines allowed inside msg
570 $msg=~ s/\n//g;
571 return $msg;
572 }
575 sub decrypt_msg {
576 my ($msg, $key) = @_ ;
577 $msg = &decode_base64($msg);
578 my $my_cipher = &create_ciphering($key);
579 $msg = $my_cipher->decrypt($msg);
580 $msg =~ s/\0*//g;
581 return $msg;
582 }
585 sub get_encrypt_key {
586 my ($target) = @_ ;
587 my $encrypt_key;
588 my $error = 0;
590 # target can be in known_server
591 if( !$encrypt_key ) {
592 my $sql_statement= "SELECT * FROM known_server";
593 my $query_res = $known_server_db->select_dbentry( $sql_statement );
594 while( my ($hit_num, $hit) = each %{ $query_res } ) {
595 my $host_name = $hit->{hostname};
596 if( $host_name ne $target ) {
597 next;
598 }
599 my $host_key = $hit->{hostkey};
600 last;
601 }
602 }
605 # target can be in known_client
606 if( !$encrypt_key ) {
607 my $sql_statement= "SELECT * FROM known_clients";
608 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
609 while( my ($hit_num, $hit) = each %{ $query_res } ) {
610 my $host_name = $hit->{hostname};
611 if( $host_name ne $target ) {
612 next;
613 }
614 $encrypt_key = $hit->{hostkey};
615 last;
616 }
617 }
619 return $encrypt_key;
620 }
623 #=== FUNCTION ================================================================
624 # NAME: open_socket
625 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
626 # [PeerPort] string necessary if port not appended by PeerAddr
627 # RETURNS: socket IO::Socket::INET
628 # DESCRIPTION: open a socket to PeerAddr
629 #===============================================================================
630 sub open_socket {
631 my ($PeerAddr, $PeerPort) = @_ ;
632 if(defined($PeerPort)){
633 $PeerAddr = $PeerAddr.":".$PeerPort;
634 }
635 my $socket;
636 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
637 Porto => "tcp",
638 Type => SOCK_STREAM,
639 Timeout => 5,
640 );
641 if(not defined $socket) {
642 return;
643 }
644 &daemon_log("open_socket: $PeerAddr", 7);
645 return $socket;
646 }
649 sub send_msg_to_target {
650 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
651 my $error = 0;
653 if( !$msg_header ) {
654 $msg_header = "";
655 }
657 # encrypt xml msg
658 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
660 # opensocket
661 my $socket = &open_socket($address);
662 if(not defined $socket){
663 daemon_log("cannot send $msg_header msg to $address , host not reachable", 1);
664 $error++;
665 }
667 if( $error == 0 ) {
669 # send xml msg
670 print $socket $crypted_msg."\n";
672 close $socket;
674 daemon_log("send msg to $address", 1);
675 daemon_log("message:\n$msg", 8);
677 }
679 return;
680 }
683 sub client_input {
684 no strict "refs";
685 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
686 my ($msg, $msg_hash, $module);
687 my $error = 0;
688 my $answer_l;
689 my ($answer_header, @answer_target_l, $answer_source);
690 my $client_answer;
692 daemon_log("Incoming msg:\n$input\n", 8);
694 # msg is from a new client or gosa
695 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
697 # msg is from a gosa-si-server or gosa-si-bus
698 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
699 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
700 }
702 # msg is from a gosa-si-client
703 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
704 ($msg, $msg_hash, $module) = &input_from_known_client($input);
705 }
707 # an error occurred
708 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
709 $error++;
710 }
712 ######################
713 # process incoming msg
714 if( $error == 0) {
715 daemon_log("Processing module ".$module, 3);
716 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
718 if ( 0 > @{$answer_l} ) {
719 my $answer_str = join("\n", @{$answer_l});
720 daemon_log("$module: Got answer from module: \n".$answer_str,8);
721 }
722 }
723 if( !$answer_l ) { $error++ };
725 # for each answer in answer list
726 foreach my $answer ( @{$answer_l} ) {
728 # check answer if gosa-si envelope conform
729 if( $error == 0 ) {
730 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
731 $answer_header = @{$answer_hash->{'header'}}[0];
732 @answer_target_l = @{$answer_hash->{'target'}};
733 $answer_source = @{$answer_hash->{'source'}}[0];
734 if( !$answer_header ) {
735 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
736 $error++;
737 }
738 if( 0 == length @answer_target_l ) {
739 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
740 $error++;
741 }
742 if( !$answer_source ) {
743 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
744 $error++;
745 }
746 }
748 # deliver msg to all targets
749 foreach my $answer_target ( @answer_target_l ) {
750 if( $answer_target eq "*" ) {
751 # answer is for all clients
752 my $sql_statement= "SELECT * FROM known_clients";
753 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
754 while( my ($hit_num, $hit) = each %{ $query_res } ) {
755 my $host_name = $hit->{hostname};
756 my $host_key = $hit->{hostkey};
757 &send_msg_to_target($answer, $host_name, $host_key);
758 }
759 }
760 elsif( $answer_target eq "GOSA" ) {
761 # answer is for GOSA and has to returned to connected client
762 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
763 $client_answer = $gosa_answer;
764 }
765 else {
766 # answer is for one specific host
767 # get encrypt_key
768 my $encrypt_key = &get_encrypt_key($answer_target);
769 if( !$encrypt_key ) {
770 daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
771 next;
772 }
773 # send_msg
774 &send_msg_to_target($answer, $answer_target, $encrypt_key);
775 }
776 }
777 }
779 if( $client_answer ) {
780 $heap->{client}->put($client_answer);
781 }
783 return;
784 }
787 sub trigger_db_loop {
788 my ($kernel) = $_[KERNEL];
789 $kernel->delay_set('watch_for_new_jobs',3);
790 }
793 sub watch_for_new_jobs {
794 my ($kernel,$heap) = @_[KERNEL, HEAP];
796 # check gosa job queue for jobs with executable timestamp
797 my $timestamp = &get_time();
799 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
800 " WHERE status='waiting' AND timestamp<'$timestamp'";
802 my $res = $job_db->select_dbentry( $sql_statement );
804 while( my ($id, $hit) = each %{$res} ) {
806 my $jobdb_id = $hit->{id};
807 my $macaddress = $hit->{macaddress};
808 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
809 my $out_msg_hash = $job_msg_hash;
810 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
811 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
812 # expect macaddress is unique!!!!!!
813 my $target = $res_hash->{1}->{hostname};
815 if (not defined $target) {
816 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
817 &daemon_log("xml message: $hit->{xmlmessage}", 5);
818 my $sql_statement = "UPDATE $job_queue_table_name ".
819 "SET status='error', result='no host found for mac address' ".
820 "WHERE id='$jobdb_id'";
821 my $res = $job_db->update_dbentry($sql_statement);
822 next;
823 }
825 # add target
826 &add_content2xml_hash($out_msg_hash, "target", $target);
828 # add new header
829 my $out_header = $job_msg_hash->{header}[0];
830 $out_header =~ s/job_/gosa_/;
831 delete $out_msg_hash->{header};
832 &add_content2xml_hash($out_msg_hash, "header", $out_header);
834 # add sqlite_id
835 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
837 my $out_msg = &create_xml_string($out_msg_hash);
839 # encrypt msg as a GosaPackage module
840 my $cipher = &create_ciphering($GosaPackages_key);
841 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
843 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
845 if ($error == 0) {
846 my $sql_statement = "UPDATE $job_queue_table_name ".
847 "SET status='processing', targettag='$target' ".
848 "WHERE id='$jobdb_id'";
849 my $res = $job_db->update_dbentry($sql_statement);
850 } else {
851 my $sql_statement = "UPDATE $job_queue_table_name ".
852 "SET status='error' ".
853 "WHERE id='$jobdb_id'";
854 my $res = $job_db->update_dbentry($sql_statement);
855 }
856 }
858 $kernel->delay_set('watch_for_new_jobs',3);
859 }
862 #==== MAIN = main ==============================================================
863 # parse commandline options
864 Getopt::Long::Configure( "bundling" );
865 GetOptions("h|help" => \&usage,
866 "c|config=s" => \$cfg_file,
867 "f|foreground" => \$foreground,
868 "v|verbose+" => \$verbose,
869 "no-bus+" => \$no_bus,
870 "no-arp+" => \$no_arp,
871 );
873 # read and set config parameters
874 &check_cmdline_param ;
875 &read_configfile;
876 &check_pid;
878 $SIG{CHLD} = 'IGNORE';
880 # forward error messages to logfile
881 if( ! $foreground ) {
882 open(STDERR, '>>', $log_file);
883 open(STDOUT, '>>', $log_file);
884 }
886 # Just fork, if we are not in foreground mode
887 if( ! $foreground ) {
888 chdir '/' or die "Can't chdir to /: $!";
889 $pid = fork;
890 setsid or die "Can't start a new session: $!";
891 umask 0;
892 } else {
893 $pid = $$;
894 }
896 # Do something useful - put our PID into the pid_file
897 if( 0 != $pid ) {
898 open( LOCK_FILE, ">$pid_file" );
899 print LOCK_FILE "$pid\n";
900 close( LOCK_FILE );
901 if( !$foreground ) {
902 exit( 0 )
903 };
904 }
906 daemon_log(" ", 1);
907 daemon_log("$0 started!", 1);
909 # delete old DBsqlite lock files
910 system('rm -f /tmp/gosa_si_lock*');
912 # connect to gosa-si job queue
913 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
914 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
915 $job_db->create_table('jobs', \@job_col_names);
917 # connect to known_clients_db
918 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
919 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
920 $known_clients_db->create_table('known_clients', \@clients_col_names);
922 # connect to known_server_db
923 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
924 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
925 $known_server_db->create_table('known_server', \@server_col_names);
927 # import all modules
928 &import_modules;
930 # check wether all modules are gosa-si valid passwd check
932 # create xml object used for en/decrypting
933 $xml = new XML::Simple();
935 # create session for repeatedly checking the job queue for jobs
936 POE::Session->create(
937 inline_states => {
938 _start => \&trigger_db_loop,
939 watch_for_new_jobs => \&watch_for_new_jobs,
940 }
941 );
943 # create socket for incoming xml messages
944 POE::Component::Server::TCP->new(
945 Port => $server_port,
946 ClientInput => \&client_input,
947 );
948 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
950 POE::Kernel->run();
951 exit;