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 }
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(defined($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:$module\n";
394 #print STDERR "modul_key:$module_key\n";
396 my $msg;
397 my $msg_hash;
398 eval{
399 $msg = &decrypt_msg($crypted_msg, $module_key);
400 &main::daemon_log("decrypted_msg: \n$msg", 8);
402 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
404 # check header
405 my $header_l = $msg_hash->{'header'};
406 if( 1 != @{$header_l} ) {
407 die'header error';
408 }
409 my $header = @{$header_l}[0];
410 if( 0 == length $header) {
411 die 'header error';
412 }
414 # check source
415 my $source_l = $msg_hash->{'source'};
416 if( 1 != @{$source_l} ) {
417 die'source error';
418 }
419 my $source = @{$source_l}[0];
420 if( 0 == length $source) {
421 die 'source error';
422 }
424 # check target
425 my $target_l = $msg_hash->{'target'};
426 if( 1 != @{$target_l} ) {
427 die'target error';
428 }
429 my $target = @{$target_l}[0];
430 if( 0 == length $target) {
431 die 'target error';
432 }
434 };
435 if($@) {
436 &main::daemon_log("WARNING: do not understand the message:", 5);
437 &main::daemon_log("$@", 8);
438 }
440 return ($msg, $msg_hash);
441 }
444 sub input_from_known_server {
445 my ($input, $remote_ip) = @_ ;
446 my ($msg, $msg_hash, $module);
449 my $sql_statement= "SELECT * FROM known_server";
450 my $query_res = $known_server_db->select_dbentry( $sql_statement );
451 while( my ($hit_num, $hit) = each %{ $query_res } ) {
452 my $host_name = $hit->{hostname};
453 if( not $host_name =~ "^$remote_ip") {
454 next;
455 }
456 my $host_key = $hit->{hostkey};
457 daemon_log("SIPackages: host_name: $host_name", 7);
458 daemon_log("SIPackages: host_key: $host_key", 7);
460 # check if module can open msg envelope with module key
461 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key);
462 if( (!$msg) || (!$msg_hash) ) {
463 daemon_log("SIPackages: deciphering raise error", 7);
464 daemon_log("$@", 8);
465 next;
466 }
467 else {
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: host_name: $host_name", 7);
494 &daemon_log("SIPackages: 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", 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 {
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";
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 my $host_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";
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 = "";
658 }
660 # encrypt xml msg
661 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
663 # opensocket
664 my $socket = &open_socket($address);
665 if(not defined $socket){
666 daemon_log("cannot send $msg_header msg to $address , host not reachable", 1);
667 $error++;
668 }
670 if( $error == 0 ) {
672 # send xml msg
673 print $socket $crypted_msg."\n";
675 close $socket;
677 daemon_log("send msg to $address", 1);
678 daemon_log("message:\n$msg", 8);
680 }
682 return;
683 }
686 sub client_input {
687 no strict "refs";
688 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
689 my ($msg, $msg_hash, $module);
690 my $error = 0;
691 my $answer_l;
692 my ($answer_header, @answer_target_l, $answer_source);
693 my $client_answer;
695 daemon_log("Incoming msg:\n$input\n", 8);
697 # msg is from a new client or gosa
698 ($msg, $msg_hash, $module) = &input_from_unknown_host($input);
700 # msg is from a gosa-si-server or gosa-si-bus
701 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
702 ($msg, $msg_hash, $module) = &input_from_known_server($input, $heap->{'remote_ip'});
703 }
705 # msg is from a gosa-si-client
706 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
707 ($msg, $msg_hash, $module) = &input_from_known_client($input, $heap->{'remote_ip'});
708 }
710 # an error occurred
711 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
712 $error++;
713 }
715 ######################
716 # process incoming msg
717 if( $error == 0) {
718 daemon_log("Processing module ".$module, 3);
719 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash);
721 if ( 0 > @{$answer_l} ) {
722 my $answer_str = join("\n", @{$answer_l});
723 daemon_log("$module: Got answer from module: \n".$answer_str,8);
724 }
725 }
726 if( !$answer_l ) { $error++ };
728 # for each answer in answer list
729 foreach my $answer ( @{$answer_l} ) {
731 # check answer if gosa-si envelope conform
732 if( $error == 0 ) {
733 my $answer_hash = $xml->XMLin($answer, ForceArray=>1);
734 $answer_header = @{$answer_hash->{'header'}}[0];
735 @answer_target_l = @{$answer_hash->{'target'}};
736 $answer_source = @{$answer_hash->{'source'}}[0];
737 if( !$answer_header ) {
738 daemon_log('ERROR: module answer is not gosa-si envelope conform: no header', 1);
739 $error++;
740 }
741 if( 0 == length @answer_target_l ) {
742 daemon_log('ERROR: module answer is not gosa-si envelope conform: no targets', 1);
743 $error++;
744 }
745 if( !$answer_source ) {
746 daemon_log('ERROR: module answer is not gosa-si envelope conform: no source', 1);
747 $error++;
748 }
749 }
751 # deliver msg to all targets
752 foreach my $answer_target ( @answer_target_l ) {
753 if( $answer_target eq "*" ) {
754 # answer is for all clients
755 my $sql_statement= "SELECT * FROM known_clients";
756 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
757 while( my ($hit_num, $hit) = each %{ $query_res } ) {
758 my $host_name = $hit->{hostname};
759 my $host_key = $hit->{hostkey};
760 &send_msg_to_target($answer, $host_name, $host_key);
761 }
762 }
763 elsif( $answer_target eq "GOSA" ) {
764 # answer is for GOSA and has to returned to connected client
765 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
766 $client_answer = $gosa_answer;
767 }
768 else {
769 # answer is for one specific host
770 # get encrypt_key
771 my $encrypt_key = &get_encrypt_key($answer_target);
772 if( !$encrypt_key ) {
773 daemon_log("ERROR: no encrypt key found for answer target '$answer_target'", 1);
774 next;
775 }
776 # send_msg
777 &send_msg_to_target($answer, $answer_target, $encrypt_key);
778 }
779 }
780 }
782 if( $client_answer ) {
783 $heap->{client}->put($client_answer);
784 }
786 return;
787 }
790 sub trigger_db_loop {
791 my ($kernel) = $_[KERNEL];
792 $kernel->delay_set('watch_for_new_jobs',3);
793 }
796 sub watch_for_new_jobs {
797 my ($kernel,$heap) = @_[KERNEL, HEAP];
799 # check gosa job queue for jobs with executable timestamp
800 my $timestamp = &get_time();
802 my $sql_statement = "SELECT * FROM ".$job_queue_table_name.
803 " WHERE status='waiting' AND timestamp<'$timestamp'";
805 my $res = $job_db->select_dbentry( $sql_statement );
807 while( my ($id, $hit) = each %{$res} ) {
809 my $jobdb_id = $hit->{id};
810 my $macaddress = $hit->{macaddress};
811 my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
812 my $out_msg_hash = $job_msg_hash;
813 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress='$macaddress'";
814 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
815 # expect macaddress is unique!!!!!!
816 my $target = $res_hash->{1}->{hostname};
818 if (not defined $target) {
819 &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
820 &daemon_log("xml message: $hit->{xmlmessage}", 5);
821 my $sql_statement = "UPDATE $job_queue_table_name ".
822 "SET status='error', result='no host found for mac address' ".
823 "WHERE id='$jobdb_id'";
824 my $res = $job_db->update_dbentry($sql_statement);
825 next;
826 }
828 # add target
829 &add_content2xml_hash($out_msg_hash, "target", $target);
831 # add new header
832 my $out_header = $job_msg_hash->{header}[0];
833 $out_header =~ s/job_/gosa_/;
834 delete $out_msg_hash->{header};
835 &add_content2xml_hash($out_msg_hash, "header", $out_header);
837 # add sqlite_id
838 &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
840 my $out_msg = &create_xml_string($out_msg_hash);
842 # encrypt msg as a GosaPackage module
843 my $cipher = &create_ciphering($GosaPackages_key);
844 my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
846 my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $GosaPackages_key);
848 if ($error == 0) {
849 my $sql_statement = "UPDATE $job_queue_table_name ".
850 "SET status='processing', targettag='$target' ".
851 "WHERE id='$jobdb_id'";
852 my $res = $job_db->update_dbentry($sql_statement);
853 } else {
854 my $sql_statement = "UPDATE $job_queue_table_name ".
855 "SET status='error' ".
856 "WHERE id='$jobdb_id'";
857 my $res = $job_db->update_dbentry($sql_statement);
858 }
859 }
861 $kernel->delay_set('watch_for_new_jobs',3);
862 }
865 #==== MAIN = main ==============================================================
866 # parse commandline options
867 Getopt::Long::Configure( "bundling" );
868 GetOptions("h|help" => \&usage,
869 "c|config=s" => \$cfg_file,
870 "f|foreground" => \$foreground,
871 "v|verbose+" => \$verbose,
872 "no-bus+" => \$no_bus,
873 "no-arp+" => \$no_arp,
874 );
876 # read and set config parameters
877 &check_cmdline_param ;
878 &read_configfile;
879 &check_pid;
881 $SIG{CHLD} = 'IGNORE';
883 # forward error messages to logfile
884 if( ! $foreground ) {
885 open(STDERR, '>>', $log_file);
886 open(STDOUT, '>>', $log_file);
887 }
889 # Just fork, if we are not in foreground mode
890 if( ! $foreground ) {
891 chdir '/' or die "Can't chdir to /: $!";
892 $pid = fork;
893 setsid or die "Can't start a new session: $!";
894 umask 0;
895 } else {
896 $pid = $$;
897 }
899 # Do something useful - put our PID into the pid_file
900 if( 0 != $pid ) {
901 open( LOCK_FILE, ">$pid_file" );
902 print LOCK_FILE "$pid\n";
903 close( LOCK_FILE );
904 if( !$foreground ) {
905 exit( 0 )
906 };
907 }
909 daemon_log(" ", 1);
910 daemon_log("$0 started!", 1);
912 # delete old DBsqlite lock files
913 system('rm -f /tmp/gosa_si_lock*');
915 # connect to gosa-si job queue
916 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
917 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
918 $job_db->create_table('jobs', \@job_col_names);
920 # connect to known_clients_db
921 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
922 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
923 $known_clients_db->create_table('known_clients', \@clients_col_names);
925 # connect to known_server_db
926 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
927 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
928 $known_server_db->create_table('known_server', \@server_col_names);
930 # import all modules
931 &import_modules;
933 # check wether all modules are gosa-si valid passwd check
935 # create xml object used for en/decrypting
936 $xml = new XML::Simple();
938 # create session for repeatedly checking the job queue for jobs
939 POE::Session->create(
940 inline_states => {
941 _start => \&trigger_db_loop,
942 watch_for_new_jobs => \&watch_for_new_jobs,
943 }
944 );
946 # create socket for incoming xml messages
947 POE::Component::Server::TCP->new(
948 Port => $server_port,
949 ClientInput => \&client_input,
950 );
951 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
953 POE::Kernel->run();
954 exit;