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 # BUGS: ---
14 # NOTES:
15 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
16 # COMPANY:
17 # VERSION: 1.0
18 # CREATED: 12.09.2007 08:54:41 CEST
19 # REVISION: ---
20 #===============================================================================
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::GosaSupportDaemon;
44 use GOSA::DBsqlite;
45 use POE qw(Component::Server::TCP);
47 my $modules_path = "/usr/lib/gosa-si/modules";
48 use lib "/usr/lib/gosa-si/modules";
50 my (%cfg_defaults, $foreground, $verbose, $ping_timeout);
51 my ($bus, $msg_to_bus, $bus_cipher);
52 my ($server, $server_mac_address, $server_events);
53 my ($gosa_server, $job_queue_timeout, $job_queue_table_name, $job_queue_file_name);
54 my ($known_modules, $known_clients_file_name, $known_server_file_name);
55 my ($max_clients);
56 my ($pid_file, $procid, $pid, $log_file);
57 my (%free_child, %busy_child, $child_max, $child_min, %child_alive_time, $child_timeout);
58 my ($arp_activ, $arp_fifo, $arp_fifo_path);
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, $server_passwd, $max_clients,
64 $arp_activ, $arp_fifo_path,
65 $gosa_activ, $gosa_passwd, $gosa_ip, $gosa_port, $gosa_timeout,
66 );
68 # additional variable which should be globaly accessable
69 our $xml;
70 our $server_address;
71 our $bus_address;
72 our $gosa_address;
73 our $no_bus;
74 our $no_arp;
75 our $verbose;
76 our $forground;
77 our $cfg_file;
79 # specifies the verbosity of the daemon_log
80 $verbose = 0 ;
82 # if foreground is not null, script will be not forked to background
83 $foreground = 0 ;
85 # specifies the timeout seconds while checking the online status of a registrating client
86 $ping_timeout = 5;
88 $no_bus = 0;
90 $no_arp = 0;
92 # name of table for storing gosa jobs
93 our $job_queue_table_name = 'jobs';
94 our $job_db;
96 # holds all other gosa-sd as well as the gosa-sd-bus
97 our $known_server_db;
99 # holds all registrated clients
100 our $known_clients_db;
102 %cfg_defaults =
103 ("general" =>
104 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
105 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
106 "child_max" => [\$child_max, 10],
107 "child_min" => [\$child_min, 3],
108 "child_timeout" => [\$child_timeout, 180],
109 "job_queue_timeout" => [\$job_queue_timeout, undef],
110 "job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
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 "server_passwd" => [\$server_passwd, ""],
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 "gosa_passwd" => [\$gosa_passwd, "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 #=== FUNCTION ================================================================
241 # NAME: check_cmdline_param
242 # PARAMETERS: nothing
243 # RETURNS: nothing
244 # DESCRIPTION: validates commandline parameter
245 #===============================================================================
246 sub check_cmdline_param () {
247 my $err_config;
248 my $err_counter = 0;
249 if(not defined($cfg_file)) {
250 $cfg_file = "/etc/gosa-si/server.conf";
251 if(! -r $cfg_file) {
252 $err_config = "please specify a config file";
253 $err_counter += 1;
254 }
255 }
256 if( $err_counter > 0 ) {
257 &usage( "", 1 );
258 if( defined( $err_config)) { print STDERR "$err_config\n"}
259 print STDERR "\n";
260 exit( -1 );
261 }
262 }
265 #=== FUNCTION ================================================================
266 # NAME: check_pid
267 # PARAMETERS: nothing
268 # RETURNS: nothing
269 # DESCRIPTION: handels pid processing
270 #===============================================================================
271 sub check_pid {
272 $pid = -1;
273 # Check, if we are already running
274 if( open(LOCK_FILE, "<$pid_file") ) {
275 $pid = <LOCK_FILE>;
276 if( defined $pid ) {
277 chomp( $pid );
278 if( -f "/proc/$pid/stat" ) {
279 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
280 if( $0 eq $stat ) {
281 close( LOCK_FILE );
282 exit -1;
283 }
284 }
285 }
286 close( LOCK_FILE );
287 unlink( $pid_file );
288 }
290 # create a syslog msg if it is not to possible to open PID file
291 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
292 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
293 if (open(LOCK_FILE, '<', $pid_file)
294 && ($pid = <LOCK_FILE>))
295 {
296 chomp($pid);
297 $msg .= "(PID $pid)\n";
298 } else {
299 $msg .= "(unable to read PID)\n";
300 }
301 if( ! ($foreground) ) {
302 openlog( $0, "cons,pid", "daemon" );
303 syslog( "warning", $msg );
304 closelog();
305 }
306 else {
307 print( STDERR " $msg " );
308 }
309 exit( -1 );
310 }
311 }
313 #=== FUNCTION ================================================================
314 # NAME: import_modules
315 # PARAMETERS: module_path - string - abs. path to the directory the modules
316 # are stored
317 # RETURNS: nothing
318 # DESCRIPTION: each file in module_path which ends with '.pm' is imported by
319 # "require 'file';"
320 #===============================================================================
321 sub import_modules {
322 daemon_log(" ", 1);
324 if (not -e $modules_path) {
325 daemon_log("ERROR: cannot find directory or directory is not readable: $modules_path", 1);
326 }
328 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
329 while (defined (my $file = readdir (DIR))) {
330 if (not $file =~ /(\S*?).pm$/) {
331 next;
332 }
333 eval { require $file; };
334 if ($@) {
335 daemon_log("ERROR: gosa-si-server could not load module $file", 1);
336 daemon_log("$@", 5);
337 } else {
338 my $mod_name = $1;
339 my $info = eval($mod_name.'::get_module_info()');
340 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
341 $known_modules->{$mod_name} = $info;
343 daemon_log("module $mod_name loaded", 1);
344 }
345 }
347 # for debugging
348 #while ( my ($module, $tag_hash) = each(%$known_modules)) {
349 # print "\tmodule: $module"."\n";
350 # print "\ttags: ".join(", ", keys(%$tag_hash))."\n";
351 #}
352 close (DIR);
353 }
356 #=== FUNCTION ================================================================
357 # NAME: sig_int_handler
358 # PARAMETERS: signal - string - signal arose from system
359 # RETURNS: noting
360 # DESCRIPTION: handels tasks to be done befor signal becomes active
361 #===============================================================================
362 sub sig_int_handler {
363 my ($signal) = @_;
365 daemon_log("shutting down gosa-si-server", 1);
366 exit(1);
367 }
368 $SIG{INT} = \&sig_int_handler;
371 #=== FUNCTION ================================================================
372 # NAME: activating_child
373 # PARAMETERS: msg - string - incoming message
374 # host - string - host from which the incomming message comes
375 # RETURNS: nothing
376 # DESCRIPTION: handels the distribution of incoming messages to working childs
377 #===============================================================================
378 sub activating_child {
379 my ($msg, $host, $client) = @_;
380 my $child = &get_processing_child();
381 if(!$child) {
382 daemon_log("Got no child! Trying again", 5);
383 sleep(1);
384 $child = &get_processing_child();
385 if(!$child) {
386 daemon_log("Got no child at the second try! Trying again", 5);
387 }
388 }
389 my $pipe_wr = $$child{'pipe_wr'};
390 my $pipe_rd = $$child{'pipe_rd'};
391 $$child{client_ref} = $client;
393 daemon_log("activating: childpid:$$child{'pid'}", 5);
395 print $pipe_wr $msg.".".$host."\n";
397 return;
398 }
401 #=== FUNCTION ================================================================
402 # NAME: get_processing_child
403 # PARAMETERS: nothing
404 # RETURNS: child - hash - holding the process id and the references to the pipe
405 # handles pipe_wr and pipe_rd
406 # DESCRIPTION: handels the forking, reactivating and keeping alive tasks
407 #===============================================================================
408 sub get_processing_child {
409 my $child;
411 while(my ($key, $val) = each(%free_child)) {
412 my $exitus_pid = waitpid($key, WNOHANG);
413 if($exitus_pid != 0) {
414 delete $free_child{$key};
415 }
416 daemon_log("free child:$key", 5);
417 }
418 # check @free_child and @busy_child
419 my $free_len = scalar(keys(%free_child));
420 my $busy_len = scalar(keys(%busy_child));
421 daemon_log("free children $free_len, busy children $busy_len", 5);
423 # if there is a free child, let the child work
424 if($free_len > 0){
425 my @keys = keys(%free_child);
426 $child = $free_child{$keys[0]};
427 if(defined $child) {
428 $busy_child{$$child{'pid'}} = $child ;
429 delete $free_child{$$child{'pid'}};
430 }
431 return $child;
432 }
434 # no free child, try to fork another one
435 if($free_len + $busy_len < $child_max) {
437 daemon_log("not enough children, create a new one", 5);
439 # New pipes for communication
440 my( $PARENT_wr, $PARENT_rd );
441 my( $CHILD_wr, $CHILD_rd );
442 pipe( $CHILD_rd, $PARENT_wr );
443 pipe( $PARENT_rd, $CHILD_wr );
444 $PARENT_wr->autoflush(1);
445 $CHILD_wr->autoflush(1);
447 ############
448 # fork child
449 ############
450 my $child_pid = fork();
452 #CHILD
453 if($child_pid == 0) {
454 # Close unused pipes
455 close( $CHILD_rd );
456 close( $CHILD_wr );
457 while( 1 ) {
458 my $rbits = "";
459 vec( $rbits, fileno $PARENT_rd , 1 ) = 1;
460 my $nf = select($rbits, undef, undef, $child_timeout);
461 if($nf < 0 ) {
462 die "select(): $!\n";
463 } elsif (! $nf) {
464 # if already child_min childs are alive, then leave loop
465 $free_len = scalar(keys(%free_child));
466 $busy_len = scalar(keys(%busy_child));
467 if($free_len + $busy_len >= $child_min) {
468 last;
469 } else {
470 redo;
471 }
472 }
474 # a job for a child arise
475 if ( vec $rbits, fileno $PARENT_rd, 1 ) {
476 # read everything from pipe
477 my $msg = "";
478 $PARENT_rd->blocking(0);
479 while(1) {
480 my $read = <$PARENT_rd>;
481 if(not defined $read) { last}
482 $msg .= $read;
483 }
485 ######################################
486 # forward msg to all imported modules
487 no strict "refs";
488 my $answer;
489 my %act_modules = %$known_modules;
490 while( my ($module, $info) = each(%act_modules)) {
491 my $tmp = &{ $module."::process_incoming_msg" }($msg);
492 if (defined $tmp) {
493 $answer = $tmp;
494 }
495 }
496 daemon_log("processing of msg finished", 5);
498 if (defined $answer) {
499 print $PARENT_wr $answer."\n";
500 print $PARENT_wr "ENDMESSAGE\n";
501 my $len_answer = length $answer;
502 daemon_log("with answer: length of answer: $len_answer", 7);
503 daemon_log("\n$answer", 7);
504 } else {
505 print $PARENT_wr "done"."\n";
506 print $PARENT_wr "ENDMESSAGE\n";
507 }
508 redo;
509 }
510 }
511 # childs leaving the loop are allowed to die
512 exit(0);
515 #PARENT
516 } else {
517 # Close unused pipes
518 close( $PARENT_rd );
519 close( $PARENT_wr );
521 # add child to child alive hash
522 my %child_hash = (
523 'pid' => $child_pid,
524 'pipe_wr' => $CHILD_wr,
525 'pipe_rd' => $CHILD_rd,
526 'client_ref' => "",
527 );
529 $child = \%child_hash;
530 $busy_child{$$child{'pid'}} = $child;
531 return $child;
532 }
533 }
534 }
537 #=== FUNCTION ================================================================
538 # NAME: read_from_socket
539 # PARAMETERS: socket fh -
540 # RETURNS: result string - readed characters from socket
541 # DESCRIPTION: reads data from socket in 16 byte steps
542 #===============================================================================
543 sub read_from_socket {
544 my ($socket) = @_;
545 my $result = "";
547 $socket->blocking(1);
548 $result = <$socket>;
550 $socket->blocking(0);
551 while ( my $char = <$socket> ) {
552 if (not defined $char) { last }
553 $result .= $char;
554 }
556 return $result;
557 }
560 #=== FUNCTION ================================================================
561 # NAME: print_known_daemons
562 # PARAMETERS: nothing
563 # RETURNS: nothing
564 # DESCRIPTION: nomen est omen
565 #===============================================================================
566 #sub print_known_daemons {
567 # my ($tmp) = @_ ;
568 # print "####################################\n";
569 # print "# status of known_daemons\n";
570 # $shmda->shlock(LOCK_EX);
571 # my @hosts = keys %$known_daemons;
572 # foreach my $host (@hosts) {
573 # my $status = $known_daemons->{$host}->{status} ;
574 # my $passwd = $known_daemons->{$host}->{passwd};
575 # my $timestamp = $known_daemons->{$host}->{timestamp};
576 # print "$host\n";
577 # print "\tstatus: $status\n";
578 # print "\tpasswd: $passwd\n";
579 # print "\ttimestamp: $timestamp\n";
580 # }
581 # $shmda->shunlock(LOCK_EX);
582 # print "####################################\n";
583 # return;
584 #}
587 #=== FUNCTION ================================================================
588 # NAME: create_known_daemon
589 # PARAMETERS: hostname - string - key for the hash known_daemons
590 # RETURNS: nothing
591 # DESCRIPTION: creates a dummy entry for hostname in known_daemons
592 #===============================================================================
593 #sub create_known_daemon {
594 # my ($hostname) = @_;
595 # $shmda->shlock(LOCK_EX);
596 # $known_daemons->{$hostname} = {};
597 # $known_daemons->{$hostname}->{status} = "none";
598 # $known_daemons->{$hostname}->{passwd} = "none";
599 # $known_daemons->{$hostname}->{timestamp} = "none";
600 # $shmda->shunlock(LOCK_EX);
601 # return;
602 #}
605 #=== FUNCTION ================================================================
606 # NAME: add_content2known_daemons
607 # PARAMETERS: hostname - string - ip address and port of host (required)
608 # status - string - (optional)
609 # passwd - string - (optional)
610 # mac_address - string - mac address of host (optional)
611 # RETURNS: nothing
612 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
613 #===============================================================================
614 #sub add_content2known_daemons {
615 # my $arg = {
616 # hostname => undef, status => undef, passwd => undef,
617 # mac_address => undef, events => undef,
618 # @_ };
619 # my $hostname = $arg->{hostname};
620 # my $status = $arg->{status};
621 # my $passwd = $arg->{passwd};
622 # my $mac_address = $arg->{mac_address};
623 # my $events = $arg->{events};
624 #
625 # if (not defined $hostname) {
626 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
627 # return;
628 # }
629 #
630 # my ($seconds, $minutes, $hours, $monthday, $month,
631 # $year, $weekday, $yearday, $sommertime) = localtime(time);
632 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
633 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
634 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
635 # $month+=1;
636 # $month = $month < 10 ? $month = "0".$month : $month;
637 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
638 # $year+=1900;
639 # my $t = "$year$month$monthday$hours$minutes$seconds";
640 #
641 # $shmda->shlock(LOCK_EX);
642 # if (defined $status) {
643 # $known_daemons->{$hostname}->{status} = $status;
644 # }
645 # if (defined $passwd) {
646 # $known_daemons->{$hostname}->{passwd} = $passwd;
647 # }
648 # if (defined $mac_address) {
649 # $known_daemons->{$hostname}->{mac_address} = $mac_address;
650 # }
651 # if (defined $events) {
652 # $known_daemons->{$hostname}->{events} = $events;
653 # }
654 # $known_daemons->{$hostname}->{timestamp} = $t;
655 # $shmda->shlock(LOCK_EX);
656 # return;
657 #}
660 #=== FUNCTION ================================================================
661 # NAME: update_known_daemons
662 # PARAMETERS: hostname - string - ip address and port of host (required)
663 # status - string - (optional)
664 # passwd - string - (optional)
665 # client - string - ip address and port of client (optional)
666 # RETURNS: nothing
667 # DESCRIPTION: nome est omen and updates each time the timestamp of hostname
668 #===============================================================================
669 #sub update_known_daemons {
670 # my $arg = {
671 # hostname => undef, status => undef, passwd => undef,
672 # @_ };
673 # my $hostname = $arg->{hostname};
674 # my $status = $arg->{status};
675 # my $passwd = $arg->{passwd};
676 #
677 # if (not defined $hostname) {
678 # daemon_log("ERROR: function add_content2known_daemons is not invoked with requiered parameter 'hostname'", 1);
679 # return;
680 # }
681 #
682 # my ($seconds, $minutes, $hours, $monthday, $month,
683 # $year, $weekday, $yearday, $sommertime) = localtime(time);
684 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
685 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
686 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
687 # $month+=1;
688 # $month = $month < 10 ? $month = "0".$month : $month;
689 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
690 # $year+=1900;
691 # my $t = "$year$month$monthday$hours$minutes$seconds";
692 #
693 # $shmda->shlock(LOCK_EX);
694 # if (defined $status) {
695 # $known_daemons->{$hostname}->{status} = $status;
696 # }
697 # if (defined $passwd) {
698 # $known_daemons->{$hostname}->{passwd} = $passwd;
699 # }
700 # $known_daemons->{$hostname}->{timestamp} = $t;
701 # $shmda->shunlock(LOCK_EX);
702 # return;
703 #}
706 #=== FUNCTION ================================================================
707 # NAME: print_known_clients
708 # PARAMETERS: nothing
709 # RETURNS: nothing
710 # DESCRIPTION: nomen est omen
711 #===============================================================================
712 #sub print_known_clients {
713 #
714 # print "####################################\n";
715 # print "# status of known_clients\n";
716 # $shmcl->shlock(LOCK_EX);
717 # my @hosts = keys %$known_clients;
718 # if (@hosts) {
719 # foreach my $host (@hosts) {
720 # my $status = $known_clients->{$host}->{status} ;
721 # my $passwd = $known_clients->{$host}->{passwd};
722 # my $timestamp = $known_clients->{$host}->{timestamp};
723 # my $mac_address = $known_clients->{$host}->{mac_address};
724 # my $events = $known_clients->{$host}->{events};
725 # print "$host\n";
726 # print "\tstatus: $status\n";
727 # print "\tpasswd: $passwd\n";
728 # print "\ttimestamp: $timestamp\n";
729 # print "\tmac_address: $mac_address\n";
730 # print "\tevents: $events\n";
731 # }
732 # }
733 # $shmcl->shunlock(LOCK_EX);
734 # print "####################################\n";
735 # return;
736 #}
739 #=== FUNCTION ================================================================
740 # NAME: create_known_client
741 # PARAMETERS: hostname - string - key for the hash known_clients
742 # RETURNS: nothing
743 # DESCRIPTION: creates a dummy entry for hostname in known_clients
744 #===============================================================================
745 sub create_known_client {
746 my ($hostname) = @_;
748 my $entry = { table=>'known_clients',
749 hostname=>$hostname,
750 status=>'none',
751 hostkey=>'none',
752 timestamp=>'none',
753 macaddress=>'none',
754 events=>'none',
755 };
756 my $res = $known_clients_db->add_dbentry($entry);
757 if ($res > 0) {
758 daemon_log("ERROR: cannot add entry to known_clients.db: $res", 1);
759 }
761 return;
762 }
764 #==== MAIN = main ==============================================================
766 # parse commandline options
767 Getopt::Long::Configure( "bundling" );
768 GetOptions("h|help" => \&usage,
769 "c|config=s" => \$cfg_file,
770 "f|foreground" => \$foreground,
771 "v|verbose+" => \$verbose,
772 "no-bus+" => \$no_bus,
773 "no-arp+" => \$no_arp,
774 );
776 # read and set config parameters
777 &check_cmdline_param ;
778 &read_configfile;
779 &check_pid;
782 $SIG{CHLD} = 'IGNORE';
784 # forward error messages to logfile
785 if( ! $foreground ) {
786 open(STDERR, '>>', $log_file);
787 open(STDOUT, '>>', $log_file);
788 }
790 # Just fork, if we are not in foreground mode
791 if( ! $foreground ) {
792 chdir '/' or die "Can't chdir to /: $!";
793 $pid = fork;
794 setsid or die "Can't start a new session: $!";
795 umask 0;
796 } else {
797 $pid = $$;
798 }
800 # Do something useful - put our PID into the pid_file
801 if( 0 != $pid ) {
802 open( LOCK_FILE, ">$pid_file" );
803 print LOCK_FILE "$pid\n";
804 close( LOCK_FILE );
805 if( !$foreground ) {
806 exit( 0 )
807 };
808 }
810 daemon_log(" ", 1);
811 daemon_log("$0 started!", 1);
813 # delete old DBsqlite lock files
814 system('rm -f /tmp/gosa_si_lock*');
816 # connect to gosa-si job queue
817 my @job_col_names = ("id", "timestamp", "status", "result", "headertag", "targettag", "xmlmessage", "macaddress");
818 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
819 $job_db->create_table('jobs', \@job_col_names);
821 # connect to known_clients_db
822 my @clients_col_names = ('hostname', 'status', 'hostkey', 'timestamp', 'macaddress', 'events');
823 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
824 $known_clients_db->create_table('known_clients', \@clients_col_names);
826 # connect to known_server_db
827 my @server_col_names = ('hostname', 'status', 'hostkey', 'timestamp');
828 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
829 $known_server_db->create_table('known_server', \@server_col_names);
831 # import all modules
832 &import_modules;
834 # check wether all modules are gosa-si valid passwd check
836 # create reading and writing vectors
837 my $rbits = my $wbits = my $ebits = "";
839 # add all module inputs to listening vector
840 # while( my ($mod_name, $info) = each %$known_modules ) {
841 # my ($input_address, $input_key, $input, $input_activ, $input_type) = @{$info};
842 # vec($rbits, fileno $input, 1) = 1;
843 #
844 # }
847 ## start arp fifo
848 #if ($no_arp > 0) {
849 # $arp_activ = "off";
850 #}
851 #my $my_fifo;
852 #if($arp_activ eq "on") {
853 # daemon_log(" ", 1);
854 # $my_fifo = &open_fifo($arp_fifo_path);
855 # if($my_fifo == 0) { die "fifo file disappeared\n" }
856 # sysopen($arp_fifo, $arp_fifo_path, O_RDWR) or die "can't read from $arp_fifo: $!" ;
857 #
858 # vec($rbits, fileno $arp_fifo, 1) = 1;
859 #}
860 #
862 ###################################
863 ##everything ready, okay, lets start
864 ###################################
865 #while(1) {
866 #
867 # # add all handles from the childs
868 # while ( my ($pid, $child_hash) = each %busy_child ) {
869 #
870 # # check whether process still exists
871 # my $exitus_pid = waitpid($pid, WNOHANG);
872 # if($exitus_pid != 0) {
873 # delete $busy_child{$pid};
874 # next;
875 # }
876 #
877 # # add child fhd to the listener
878 # my $fhd = $$child_hash{'pipe_rd'};
879 # vec($rbits, fileno $fhd, 1) = 1;
880 # }
881 #
882 # my ($rout, $wout);
883 # my $nf = select($rout=$rbits, $wout=$wbits, undef, $job_queue_timeout);
884 #
885 # # error handling
886 # if($nf < 0 ) {
887 # }
888 #
889 #
890 ## if($arp_activ eq "on" && vec($rout, fileno $arp_fifo, 1)) {
891 ## my $in_msg = <$arp_fifo>;
892 ## chomp($in_msg);
893 ## print "arp_activ: msg: $in_msg\n";
894 ## my $act_passwd = $known_daemons->{$bus_address}->{passwd};
895 ## print "arp_activ: arp_passwd: $act_passwd\n";
896 ##
897 ## my $in_msg_hash = $xml->XMLin($in_msg, ForceArray=>1);
898 ##
899 ## my $target = &get_content_from_xml_hash($in_msg_hash, 'target');
900 ##
901 ## if ($target eq $server_address) {
902 ## print "arp_activ: forward to server\n";
903 ## my $arp_cipher = &create_ciphering($act_passwd);
904 ## my $crypted_msg = &encrypt_msg($in_msg, $arp_cipher);
905 ## &activating_child($crypted_msg, $server_ip);
906 ## } else {
907 ## print "arp_activ: send to bus\n";
908 ## &send_msg_hash2address($in_msg_hash, $bus_address);
909 ## }
910 ## print "\n";
911 ## }
912 #
913 #
914 # # check input fhd of all modules
915 # while ( my ($mod_name, $info) = each %$known_modules) {
916 # my $input_fhd = @{$info}[2];
917 # my $input_activ = @{$info}[3];
918 # if (vec($rout, fileno $input_fhd, 1) && $input_activ eq 'on') {
919 # daemon_log(" ", 1);
920 # my $client = $input_fhd->accept();
921 # my $other_end = getpeername($client);
922 # if(not defined $other_end) {
923 # daemon_log("client cannot be identified: $!");
924 # } else {
925 # my ($port, $iaddr) = unpack_sockaddr_in($other_end);
926 # my $actual_ip = inet_ntoa($iaddr);
927 # daemon_log("accept client at daemon socket from $actual_ip", 5);
928 # my $in_msg = &read_from_socket($client);
929 # if(defined $in_msg){
930 # chomp($in_msg);
931 # &activating_child($in_msg, $actual_ip, $client);
932 # } else {
933 # daemon_log("cannot read from $actual_ip", 5);
934 # }
935 # }
936 # }
937 # }
938 #
939 # # check all processing childs whether they are finished ('done') or
940 # while ( my ($pid, $child_hash) = each %busy_child ) {
941 # my $fhd = $$child_hash{'pipe_rd'};
942 #
943 # if (vec($rout, fileno $fhd, 1) ) {
944 # daemon_log("process child $pid is ready to read", 5);
945 #
946 # my $in_msg;
947 # while (1) {
948 # my $part_in_msg = <$fhd>;
949 # if( $part_in_msg eq "ENDMESSAGE\n") {
950 # last;
951 # }
952 # $in_msg .= $part_in_msg;
953 # }
954 # chomp($in_msg);
955 #
956 # if (not defined $in_msg) {
957 # next;
958 # } elsif ($in_msg =~ "done") {
959 # daemon_log("process child read: $in_msg", 7);
960 # delete $busy_child{$pid};
961 # $free_child{$pid} = $child_hash;
962 #
963 # } else {
964 # daemon_log("process child read:", 7);
965 # daemon_log("\n$in_msg", 8);
966 # # send computed answer back to connected client
967 # my $act_client = $busy_child{$pid}{client_ref};
968 # print $act_client $in_msg."\n";
969 # delete $busy_child{$pid};
970 # $free_child{$pid} = $child_hash;
971 #
972 # }
973 # }
974 # }
975 #
976 # # check gosa job queue for jobs with executable timestamp
977 # my ($seconds, $minutes, $hours, $monthday, $month,
978 # $year, $weekday, $yearday, $sommertime) = localtime(time);
979 # $hours = $hours < 10 ? $hours = "0".$hours : $hours;
980 # $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
981 # $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
982 # $month+=1;
983 # $month = $month < 10 ? $month = "0".$month : $month;
984 # $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
985 # $year+=1900;
986 # my $timestamp = "$year$month$monthday$hours$minutes$seconds";
987 #
988 #
989 # my $res = $job_db->select_dbentry( { table=>$job_queue_table_name, status=>'waiting', timestamp=>$timestamp } );
990 #
991 # while( my ($id, $hit) = each %{$res} ) {
992 #
993 # my $jobdb_id = $hit->{id};
994 # my $macaddress = $hit->{macaddress};
995 # my $job_msg_hash = &transform_msg2hash($hit->{xmlmessage});
996 # my $out_msg_hash = $job_msg_hash;
997 # my $res_hash = $known_clients_db->select_dbentry( {table=>'known_clients', macaddress=>$macaddress} );
998 # # expect macaddress is unique!!!!!!
999 # my $target = $res_hash->{1}->{hostname};
1000 #
1001 # if (not defined $target) {
1002 # &daemon_log("ERROR: no host found for mac address: $job_msg_hash->{mac}[0]", 1);
1003 # &daemon_log("xml message: $hit->{xmlmessage}", 5);
1004 # my $update_hash = { table=>$job_queue_table_name,
1005 # update=> [ { status=>['error'], result=>["no host found for mac address"] } ],
1006 # where=> [ { id=>[$jobdb_id] } ],
1007 # };
1008 # my $res = $job_db->update_dbentry($update_hash);
1009 #
1010 # next;
1011 # }
1012 #
1013 # # add target
1014 # &add_content2xml_hash($out_msg_hash, "target", $target);
1015 #
1016 # # add new header
1017 # my $out_header = $job_msg_hash->{header}[0];
1018 # $out_header =~ s/job_/gosa_/;
1019 # delete $out_msg_hash->{header};
1020 # &add_content2xml_hash($out_msg_hash, "header", $out_header);
1021 #
1022 # # add sqlite_id
1023 # &add_content2xml_hash($out_msg_hash, "jobdb_id", $jobdb_id);
1024 #
1025 # my $out_msg = &create_xml_string($out_msg_hash);
1026 #
1027 # # encrypt msg as a GosaPackage module
1028 # my $cipher = &create_ciphering($gosa_passwd);
1029 # my $crypted_out_msg = &encrypt_msg($out_msg, $cipher);
1030 #
1031 # my $error = &send_msg_hash2address($out_msg_hash, "$gosa_ip:$gosa_port", $gosa_passwd);
1032 #
1033 # if ($error == 0) {
1034 # my $sql = "UPDATE '$job_queue_table_name' SET status='processing', targettag='$target' WHERE id='$jobdb_id'";
1035 # my $res = $job_db->exec_statement($sql);
1036 # } else {
1037 # my $update_hash = { table=>$job_queue_table_name,
1038 # update=> [ { status=>'error' } ],
1039 # where=> [ { id=>$jobdb_id } ],
1040 # };
1041 # my $res = $job_db->update_dbentry($update_hash);
1042 # }
1043 #
1044 # }
1045 #
1046 #
1047 #}
1048 print STDERR "Server Port: $server_port\n";
1049 POE::Component::Server::TCP->new
1050 (
1051 Port => $server_port,
1052 ClientInput => \&client_input,
1053 );
1055 POE::Kernel->run();
1056 exit;
1058 sub client_input {
1059 my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
1060 #print STDERR Dumper($heap);
1061 ######################################
1062 # forward msg to all imported modules
1063 no strict "refs";
1064 my $answer;
1065 my %act_modules = %$known_modules;
1066 while( my ($module, $info) = each(%act_modules)) {
1067 daemon_log("Processing module ".$module, 3);
1068 my $tmp = &{ $module."::process_incoming_msg" }($input.".".$heap->{remote_ip}."\n");
1069 if (defined $tmp) {
1070 $answer = $tmp;
1071 }
1072 daemon_log("Got answer from module ".$module.": ".$answer,3);
1073 }
1074 daemon_log("processing of msg finished", 5);
1076 if (defined $answer) {
1077 $heap->{client}->put($answer);
1078 } else {
1079 $heap->{client}->put("done\n");
1080 }
1081 #redo;
1082 }