4397b5c1d1560b612a03e94f9b3f190d2b025e21
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);
448 my $sql_statement= "SELECT * FROM known_server";
449 my $query_res = $known_server_db->select_dbentry( $sql_statement );
450 while( my ($hit_num, $hit) = each %{ $query_res } ) {
451 my $host_name = $hit->{hostname};
452 if( not $host_name =~ "^$remote_ip") {
453 next;
454 }
455 my $host_key = $hit->{hostkey};
456 daemon_log("SIPackages: host_name: $host_name", 7);
457 daemon_log("SIPackages: host_key: $host_key", 7);
459 # check if module can open msg envelope with module key
460 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
461 if( (!$msg) || (!$msg_hash) ) {
462 daemon_log("SIPackages: deciphering raise error", 7);
463 daemon_log("$@", 8);
464 next;
465 }
466 else {
467 $module = "SIPackages";
468 last;
469 }
470 }
472 if( (!$msg) || (!$msg_hash) || (!$module) ) {
473 daemon_log("Incoming message is not from a known server", 3);
474 }
476 return ($msg, $msg_hash, $module);
477 }
480 sub input_from_known_client {
481 my ($input, $remote_ip) = @_ ;
482 my ($msg, $msg_hash, $module);
484 my $sql_statement= "SELECT * FROM known_clients";
485 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
486 while( my ($hit_num, $hit) = each %{ $query_res } ) {
487 my $host_name = $hit->{hostname};
488 if( not $host_name =~ /^$remote_ip:\d*$/) {
489 next;
490 }
491 my $host_key = $hit->{hostkey};
492 &daemon_log("SIPackages: host_name: $host_name", 7);
493 &daemon_log("SIPackages: host_key: $host_key", 7);
495 # check if module can open msg envelope with module key
496 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
498 if( (!$msg) || (!$msg_hash) ) {
499 &daemon_log("SIPackages: deciphering raise error", 7);
500 &daemon_log("$@", 8);
501 next;
502 }
503 else {
504 $module = "SIPackages";
505 last;
506 }
507 }
509 if( (!$msg) || (!$msg_hash) || (!$module) ) {
510 &daemon_log("Incoming message is not from a known client", 3);
511 }
513 return ($msg, $msg_hash, $module);
514 }
517 sub input_from_unknown_host {
518 no strict "refs";
519 my ($input) = @_ ;
520 my ($msg, $msg_hash, $module);
522 my %act_modules = %$known_modules;
524 while( my ($mod, $info) = each(%act_modules)) {
525 # check a key exists for this module
526 my $module_key = ${$mod."_key"};
527 if( ! $module_key ) {
528 daemon_log("ERROR: no key specified in config file for $mod", 1);
529 next;
530 }
531 daemon_log("$mod: $module_key", 5);
533 # check if module can open msg envelope with module key
534 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key);
535 if( (!$msg) || (!$msg_hash) ) {
536 daemon_log("$mod: deciphering failed", 5);
537 next;
538 }
539 else {
540 $module = $mod;
541 last;
542 }
543 }
545 if( (!$msg) || (!$msg_hash) || (!$module)) {
546 daemon_log("Incoming message is not from a unknown host", 3);
547 }
549 return ($msg, $msg_hash, $module);
550 }
552 sub create_ciphering {
553 my ($passwd) = @_;
554 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
555 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
556 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
557 $my_cipher->set_iv($iv);
558 return $my_cipher;
559 }
562 sub encrypt_msg {
563 my ($msg, $key) = @_;
564 my $my_cipher = &create_ciphering($key);
565 {
566 use bytes;
567 $msg = "\0"x(16-length($msg)%16).$msg;
568 }
569 $msg = $my_cipher->encrypt($msg);
570 chomp($msg = &encode_base64($msg));
571 # there are no newlines allowed inside msg
572 $msg=~ s/\n//g;
573 return $msg;
574 }
577 sub decrypt_msg {
578 my ($msg, $key) = @_ ;
579 $msg = &decode_base64($msg);
580 my $my_cipher = &create_ciphering($key);
581 $msg = $my_cipher->decrypt($msg);
582 $msg =~ s/\0*//g;
583 return $msg;
584 }
587 sub get_encrypt_key {
588 my ($target) = @_ ;
589 my $encrypt_key;
590 my $error = 0;
592 # target can be in known_server
593 if( !$encrypt_key ) {
594 my $sql_statement= "SELECT * FROM known_server";
595 my $query_res = $known_server_db->select_dbentry( $sql_statement );
596 while( my ($hit_num, $hit) = each %{ $query_res } ) {
597 my $host_name = $hit->{hostname};
598 if( $host_name ne $target ) {
599 next;
600 }
601 my $host_key = $hit->{hostkey};
602 last;
603 }
604 }
607 # target can be in known_client
608 if( !$encrypt_key ) {
609 my $sql_statement= "SELECT * FROM known_clients";
610 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
611 while( my ($hit_num, $hit) = each %{ $query_res } ) {
612 my $host_name = $hit->{hostname};
613 if( $host_name ne $target ) {
614 next;
615 }
616 $encrypt_key = $hit->{hostkey};
617 last;
618 }
619 }
621 return $encrypt_key;
622 }
625 #=== FUNCTION ================================================================
626 # NAME: open_socket
627 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
628 # [PeerPort] string necessary if port not appended by PeerAddr
629 # RETURNS: socket IO::Socket::INET
630 # DESCRIPTION: open a socket to PeerAddr
631 #===============================================================================
632 sub open_socket {
633 my ($PeerAddr, $PeerPort) = @_ ;
634 if(defined($PeerPort)){
635 $PeerAddr = $PeerAddr.":".$PeerPort;
636 }
637 my $socket;
638 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
639 Porto => "tcp",
640 Type => SOCK_STREAM,
641 Timeout => 5,
642 );
643 if(not defined $socket) {
644 return;
645 }
646 &daemon_log("open_socket: $PeerAddr", 7);
647 return $socket;
648 }
651 sub send_msg_to_target {
652 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
653 my $error = 0;
655 if( $msg_header ) {
656 $msg_header = "'$msg_header'-";
657 }
658 else {
659 $msg_header = "";
660 }
662 # encrypt xml msg
663 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
665 # opensocket
666 my $socket = &open_socket($address);
667 if( !$socket ) {
668 daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
669 $error++;
670 }
672 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 client_input {
692 no strict "refs";
693 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
694 my ($msg, $msg_hash, $module);
695 my $error = 0;
696 my $answer_l;
697 my ($answer_header, @answer_target_l, $answer_source);
698 my $client_answer;
700 daemon_log("Incoming msg:\n$input\n", 8);
702 # msg is from a new client or gosa
703 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
705 # msg is from a gosa-si-server or gosa-si-bus
706 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
707 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
708 }
710 # msg is from a gosa-si-client
711 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
712 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
713 }
715 # an error occurred
716 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
717 $error++;
718 }
720 ######################
721 # process incoming msg
722 if( $error == 0) {
723 daemon_log("Processing module ".$module, 3);
724 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
726 if ( 0 > @{$answer_l} ) {
727 my $answer_str = join("\n", @{$answer_l});
728 daemon_log("$module: Got answer from module: \n".$answer_str,8);
729 }
730 }
731 if( !$answer_l ) { $error++ };
733 if( $error == 0 ) {
735 # for each answer in answer list
736 foreach my $answer ( @{$answer_l} ) {
738 # check answer if gosa-si envelope conform
739 if( $error == 0 ) {
740 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
741 $answer_header = @{$answer_hash->{'header'}}[0];
742 @answer_target_l = @{$answer_hash->{'target'}};
743 $answer_source = @{$answer_hash->{'source'}}[0];
744 if( !$answer_header ) {
745 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
746 $error++;
747 }
748 if( 0 == length @answer_target_l ) {
749 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
750 $error++;
751 }
752 if( !$answer_source ) {
753 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
754 $error++;
755 }
757 if( $error != 0 ) {
758 next;
759 }
761 # deliver msg to all targets
762 foreach my $answer_target ( @answer_target_l ) {
763 if( $answer_target eq "*" ) {
764 # answer is for all clients
765 my $sql_statement= "SELECT * FROM known_clients";
766 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
767 while( my ($hit_num, $hit) = each %{ $query_res } ) {
768 my $host_name = $hit->{hostname};
769 my $host_key = $hit->{hostkey};
770 &send_msg_to_target($answer, $host_name, $host_key);
771 }
772 }
773 elsif( $answer_target eq "GOSA" ) {
774 # answer is for GOSA and has to returned to connected client
775 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
776 $client_answer = $gosa_answer;
777 }
778 elsif( $answer_target eq "KNOWN_SERVER" ) {
779 # answer is for all server in known_server
780 my $sql_statement= "SELECT * FROM known_server";
781 my $query_res = $known_server_db->select_dbentry( $sql_statement );
782 while( my ($hit_num, $hit) = each %{ $query_res } ) {
783 my $host_name = $hit->{hostname};
784 my $host_key = $hit->{hostkey};
785 $answer =~ s/KNOWN_SERVER/$host_name/g;
786 &send_msg_to_target($answer, $host_name, $host_key);
787 }
789 print STDERR $answer_target."\n";
791 }
792 else {
793 # answer is for one specific host
794 # get encrypt_key
795 my $encrypt_key = &get_encrypt_key($answer_target);
796 if( !$encrypt_key ) {
797 daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
798 next;
799 }
800 # send_msg
801 &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header);
802 }
803 }
804 }
805 }
806 }
808 if( $client_answer ) {
809 $heap->{client}->put($client_answer);
810 }
812 return;
813 }
815 sub _start {
816 my ($kernel) = $_[KERNEL];
817 &trigger_db_loop($kernel);
818 #®ister_at_gosa_si_bus();
819 }
822 sub trigger_db_loop {
823 # my ($kernel) = $_[KERNEL];
824 my ($kernel) = @_ ;
825 $kernel->delay_set('watch_for_new_jobs',3);
826 }
829 sub watch_for_new_jobs {
830 my ($kernel,$heap) = @_[KERNEL, HEAP];
832 # check gosa job queue for jobs with executable timestamp
833 my $timestamp = &get_time();
835 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
836 " WHERE status='waiting' AND timestamp<'$timestamp'";
838 my $res = $job_db->select_dbentry( $sql_statement );
840 while( my ($id, $hit) = each %{$res} ) {
842 my $jobdb_id = $hit->{id};
843 my $macaddress = $hit->{macaddress};
844 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
845 my $out_msg_hash = $job_msg_hash;
846 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
847 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
848 # expect macaddress is unique!!!!!!
849 my $target = $res_hash->{1}->{hostname};
851 if (not defined $target) {
852 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
853 &daemon_log("xml message: $hit->{xmlmessage}", 5);
854 my $sql_statement = "UPDATE $job_queue_table_name ".
855 "SET status='error', result='no host found for mac address' ".
856 "WHERE id='$jobdb_id'";
857 my $res = $job_db->update_dbentry($sql_statement);
858 next;
859 }
861 # add target
862 &add_content2xml_hash($out_msg_hash, "target", $target);
864 # add new header
865 my $out_header = $job_msg_hash->{header}[0];
866 $out_header =~ s/job_/gosa_/;
867 delete $out_msg_hash->{header};
868 &add_content2xml_hash($out_msg_hash, "header", $out_header);
870 # add sqlite_id
871 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
873 my $out_msg = &create_xml_string($out_msg_hash);
875 # encrypt msg as a GosaPackage module
876 my $cipher = &create_ciphering($GosaPackages_key);
877 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
879 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
881 if ($error == 0) {
882 my $sql_statement = "UPDATE $job_queue_table_name ".
883 "SET status='processing', targettag='$target' ".
884 "WHERE id='$jobdb_id'";
885 my $res = $job_db->update_dbentry($sql_statement);
886 } else {
887 my $sql_statement = "UPDATE $job_queue_table_name ".
888 "SET status='error' ".
889 "WHERE id='$jobdb_id'";
890 my $res = $job_db->update_dbentry($sql_statement);
891 }
892 }
894 $kernel->delay_set('watch_for_new_jobs',3);
895 }
898 #==== MAIN = main ==============================================================
899 # parse commandline options
900 Getopt::Long::Configure( "bundling" );
901 GetOptions("h|help" => \&usage,
902 "c|config=s" => \$cfg_file,
903 "f|foreground" => \$foreground,
904 "v|verbose+" => \$verbose,
905 "no-bus+" => \$no_bus,
906 "no-arp+" => \$no_arp,
907 );
909 # read and set config parameters
910 &check_cmdline_param ;
911 &read_configfile;
912 &check_pid;
914 $SIG{CHLD} = 'IGNORE';
916 # forward error messages to logfile
917 if( ! $foreground ) {
918 open(STDERR, '>>', $log_file);
919 open(STDOUT, '>>', $log_file);
920 }
922 # Just fork, if we are not in foreground mode
923 if( ! $foreground ) {
924 chdir '/' or die "Can't chdir to /: $!";
925 $pid = fork;
926 setsid or die "Can't start a new session: $!";
927 umask 0;
928 } else {
929 $pid = $$;
930 }
932 # Do something useful - put our PID into the pid_file
933 if( 0 != $pid ) {
934 open( LOCK_FILE, ">$pid_file" );
935 print LOCK_FILE "$pid\n";
936 close( LOCK_FILE );
937 if( !$foreground ) {
938 exit( 0 )
939 };
940 }
942 daemon_log(" ", 1);
943 daemon_log("$0 started!", 1);
945 # delete old DBsqlite lock files
946 system('rm -f /tmp/gosa_si_lock*gosa-si-server*');
948 # connect to gosa-si job queue
949 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
950 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
951 $job_db->create_table('jobs', \@job_col_names);
953 # connect to known_clients_db
954 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
955 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
956 $known_clients_db->create_table('known_clients', \@clients_col_names);
958 # connect to known_server_db
959 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
960 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
961 $known_server_db->create_table('known_server', \@server_col_names);
963 # import all modules
964 &import_modules;
966 # check wether all modules are gosa-si valid passwd check
968 # create xml object used for en/decrypting
969 $xml = new XML::Simple();
972 # create socket for incoming xml messages
973 POE::Component::Server::TCP->new(
974 Port => $server_port,
975 ClientInput => \&client_input,
976 );
977 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
979 # create session for repeatedly checking the job queue for jobs
980 POE::Session->create(
981 inline_states => {
982 _start => \&_start,
983 watch_for_new_jobs => \&watch_for_new_jobs,
984 }
985 );
987 POE::Kernel->run();
988 exit;