1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-server
5 #
6 # USAGE: gosa-si-client
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libnetaddr-ip-perl
12 # BUGS: ---
13 # NOTES:
14 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
15 # COMPANY:
16 # VERSION: 1.0
17 # CREATED: 12.09.2007 08:54:41 CEST
18 # REVISION: ---
19 #===============================================================================
21 use strict;
22 use warnings;
23 use Getopt::Long;
24 use Config::IniFiles;
25 use POSIX;
26 use Time::HiRes qw( gettimeofday );
28 use POE qw(Component::Server::TCP Wheel::FollowTail Wheel::Run);
29 use IO::Socket::INET;
30 use NetAddr::IP;
31 use Data::Dumper;
32 use Crypt::Rijndael;
33 use GOSA::GosaSupportDaemon;
34 use Digest::MD5 qw(md5_hex md5 md5_base64);
35 use MIME::Base64;
36 use XML::Simple;
37 use File::Basename;
38 use File::Spec;
40 # Workaround: need pure perl to make it work with UTF-8 :-(
41 $XML::Simple::PREFERRED_PARSER= "XML::SAX::PurePerl";
43 my $client_version = '$HeadURL$:$Rev$';
44 my $client_headURL;
45 my $client_revision;
46 my $client_status;
47 my $event_dir = "/usr/lib/gosa-si/client/events";
48 use lib "/usr/lib/gosa-si/client/events";
50 my (%cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file, $fai_logpath);
51 my ($server_ip, $server_port, $server_timeout, $server_domain, $server_key_lifetime);
52 my ($client_port, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
53 my $xml;
54 my $event_hash;
55 my $default_server_key;
56 my @servers;
57 my $gotoHardwareChecksum;
58 my $gosa_si_client_fifo;
59 my %files_to_watch;
60 $verbose= 1;
62 # globalise variables which are used in imported events
63 our $global_kernel;
64 our $cfg_file;
65 our $opts_file;
66 our $server_address;
67 our $client_address;
68 our $client_ip;
69 our $client_mac_address;
70 our $client_dnsname;
71 our $client_force_hostname;
72 our $server_key;
74 # default variables
75 our $REGISTERED = 0;
77 # path to fifo for non-gosa-si-client messages to gosa-si-server
78 $gosa_si_client_fifo = "/var/run/gosa-si-client.socket";
79 %files_to_watch = (fifo => $gosa_si_client_fifo);
81 # in function register_at_gosa_si_server, after which period of seconds a new registration should be tried if a registration was
82 # not successful until now
83 my $delay_set_time = 10;
84 our $prg= basename($0);
86 # all x seconds the client reports logged_in users to gosa-si-server
87 my $trigger_logged_in_users_report_delay = 600;
89 # directory where all log files from installation are stored
90 my $fai_log_dir = "/var/log/fai";
92 %cfg_defaults = (
93 "general" =>
94 {"log-file" => [\$log_file, "/var/run/".$prg.".log"],
95 "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
96 "opts-file" => [\$opts_file, "/var/run/".$prg.".opts"],
97 },
98 "client" =>
99 {"port" => [\$client_port, "20083"],
100 "ip" => [\$client_ip, "0.0.0.0"],
101 "mac-address" => [\$client_mac_address, "00:00:00:00:00:00"],
102 "server-domain" => [\$server_domain, ""],
103 "ldap" => [\$ldap_enabled, 1],
104 "ldap-config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
105 "pam-config" => [\$pam_config, "/etc/pam_ldap.conf"],
106 "nss-config" => [\$nss_config, "/etc/libnss-ldap.conf"],
107 "fai-logpath" => [\$fai_logpath, "/var/log/fai/fai.log"],
108 "force-hostname" => [\$client_force_hostname, "false"],
109 },
110 "server" => {
111 "ip" => [\$server_ip, "127.0.0.1"],
112 "port" => [\$server_port, "20081"],
113 "key" => [\$server_key, ""],
114 "timeout" => [\$server_timeout, 10],
115 "key-lifetime" => [\$server_key_lifetime, 600],
116 },
118 );
121 #=== FUNCTIONS = functions =====================================================
123 sub usage {
124 print STDERR << "EOF" ;
125 usage: $prg [-hvf] [-c config]
127 -h : this (help) message
128 -c <file> : config file
129 -f : foreground, process will not be forked to background
130 -v : be verbose (multiple to increase verbosity)
132 EOF
133 print "\n" ;
134 }
136 #=== FUNCTION ================================================================
137 # NAME: check_cmdline_param
138 # PARAMETERS:
139 # RETURNS:
140 # DESCRIPTION:
141 #===============================================================================
142 sub check_cmdline_param () {
143 my $err_config;
144 my $err_counter = 0;
145 if(not defined($cfg_file)) {
146 $cfg_file = "/etc/gosa-si/client.conf";
147 if(! -r $cfg_file) {
148 $err_config = "please specify a config file";
149 $err_counter += 1;
150 }
151 }
152 if( $err_counter > 0 ) {
153 &usage( "", 1 );
154 if( defined( $err_config)) { print STDERR "$err_config\n"}
155 print STDERR "\n";
156 exit( -1 );
157 }
158 }
161 #=== FUNCTION ================================================================
162 # NAME: check_pid
163 # PARAMETERS:
164 # RETURNS:
165 # DESCRIPTION:
166 #===============================================================================
167 sub check_pid {
168 $pid = -1;
169 # Check, if we are already running
170 if( open(LOCK_FILE, "<$pid_file") ) {
171 $pid = <LOCK_FILE>;
172 if( defined $pid ) {
173 chomp( $pid );
174 if( -f "/proc/$pid/stat" ) {
175 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
176 if( $0 eq $stat ) {
177 close( LOCK_FILE );
178 exit -1;
179 }
180 }
181 }
182 close( LOCK_FILE );
183 unlink( $pid_file );
184 }
186 # create a syslog msg if it is not to possible to open PID file
187 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
188 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
189 if (open(LOCK_FILE, '<', $pid_file)
190 && ($pid = <LOCK_FILE>))
191 {
192 chomp($pid);
193 $msg .= "(PID $pid)\n";
194 } else {
195 $msg .= "(unable to read PID)\n";
196 }
197 if( ! ($foreground) ) {
198 openlog( $0, "cons,pid", "daemon" );
199 syslog( "warning", $msg );
200 closelog();
201 }
202 else {
203 print( STDERR " $msg " );
204 }
205 exit( -1 );
206 }
207 }
210 sub sig_int_handler {
211 my ($signal) = @_;
213 daemon_log("shutting down gosa-si-client", 1);
214 system("kill `ps -C gosa-si-client -o pid=`");
215 }
216 $SIG{INT} = \&sig_int_handler;
219 #=== FUNCTION ================================================================
220 # NAME: logging
221 # PARAMETERS: level - string - default 'info'
222 # msg - string -
223 # facility - string - default 'LOG_DAEMON'
224 # RETURNS:
225 # DESCRIPTION:
226 #===============================================================================
227 sub daemon_log {
228 # log into log_file
229 my( $msg, $level ) = @_;
230 if(not defined $msg) { return }
231 if(not defined $level) { $level = 1 }
232 if(defined $log_file){
233 open(LOG_HANDLE, ">>$log_file");
234 chmod 0600, $log_file;
235 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
236 print STDERR "cannot open $log_file: $!";
237 return
238 }
239 chomp($msg);
240 if($level <= $verbose){
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 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
247 $month = $monthnames[$month];
248 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
249 $year+=1900;
251 my $log_msg = "$month $monthday $hours:$minutes:$seconds $prg $msg\n";
252 print LOG_HANDLE $log_msg;
253 if( $foreground ) {
254 print STDERR $log_msg;
255 }
256 }
257 close( LOG_HANDLE );
258 }
259 }
262 #=== FUNCTION ================================================================
263 # NAME: get_mac
264 # PARAMETERS: interface name (i.e. eth0)
265 # RETURNS: (mac address)
266 # DESCRIPTION: Uses ioctl to get mac address directly from system.
267 #===============================================================================
268 sub get_mac {
269 my $ifreq= shift;
270 my $result;
271 if ($ifreq && length($ifreq) > 0) {
272 if($ifreq eq "all") {
273 if(defined($server_ip)) {
274 $result = &get_local_mac_for_remote_ip($server_ip);
275 }
276 elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
277 $result = &client_mac_address;
278 }
279 else {
280 $result = "00:00:00:00:00:00";
281 }
282 } else {
283 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
285 # A configured MAC Address should always override a guessed value
286 if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
287 $result= $client_mac_address;
288 }
289 else {
290 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
291 or die "socket: $!";
293 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
294 my ($if, $mac)= unpack 'h36 H12', $ifreq;
296 if (length($mac) > 0) {
297 $mac=~ m/^([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/;
298 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
299 $result = $mac;
300 }
301 }
302 }
303 }
304 }
305 return $result;
306 }
310 #=== FUNCTION ================================================================
311 # NAME: get_local_mac_for_remote_ip
312 # PARAMETERS: none (takes server_ip from global variable)
313 # RETURNS: (ip address from interface that is used for communication)
314 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
315 # matches (defaultroute last).
316 #===============================================================================
317 sub get_local_mac_for_remote_ip {
318 my $server_ip= shift;
319 my $result= "00:00:00:00:00:00";
321 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
322 my $PROC_NET_ROUTE= ('/proc/net/route');
324 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
325 or die "Could not open $PROC_NET_ROUTE";
327 my @ifs = <PROC_NET_ROUTE>;
329 close(PROC_NET_ROUTE);
331 # Eat header line
332 shift @ifs;
333 chomp @ifs;
334 foreach my $line(@ifs) {
335 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
336 my $destination;
337 my $mask;
338 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
339 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
340 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
341 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
342 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
343 # destination matches route, save mac and exit
344 $result= &get_mac($Iface);
345 last;
346 }
347 }
348 } else {
349 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
350 }
351 return $result;
352 }
355 sub generate_hw_digest {
356 my $hw_data;
357 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
358 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
359 }
360 return(md5_base64($hw_data));
361 }
364 sub create_ciphering {
365 my ($passwd) = @_;
366 if((!defined($passwd)) || length($passwd)==0) {
367 $passwd = "";
368 }
369 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
370 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
371 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
372 $my_cipher->set_iv($iv);
373 return $my_cipher;
374 }
377 sub encrypt_msg {
378 my ($msg, $key) = @_;
379 my $my_cipher = &create_ciphering($key);
380 my $len;
381 {
382 use bytes;
383 $len= 16-length($msg)%16;
384 }
385 $msg = "\0"x($len).$msg;
386 $msg = $my_cipher->encrypt($msg);
387 chomp($msg = &encode_base64($msg));
388 # there are no newlines allowed inside msg
389 $msg=~ s/\n//g;
390 return $msg;
391 }
394 sub decrypt_msg {
396 my ($msg, $key) = @_ ;
397 $msg = &decode_base64($msg);
398 my $my_cipher = &create_ciphering($key);
399 $msg = $my_cipher->decrypt($msg);
400 $msg =~ s/\0*//g;
401 return $msg;
402 }
405 #=== FUNCTION ================================================================
406 # NAME: send_msg_hash_to_target
407 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
408 # PeerAddr string - socket address to send msg
409 # PeerPort string - socket port, if not included in socket address
410 # RETURNS: nothing
411 # DESCRIPTION: ????
412 #===============================================================================
413 sub send_msg_hash_to_target {
414 my ($msg_hash, $address, $encrypt_key) = @_ ;
415 my $msg = &create_xml_string($msg_hash);
416 my $header = @{$msg_hash->{'header'}}[0];
417 my $error = &send_msg_to_target($msg, $address, $encrypt_key, $header);
419 return $error;
420 }
423 sub send_msg_to_target {
424 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
425 my $error = 0;
427 if( $msg_header ) { $msg_header = "'$msg_header'-"; }
428 else { $msg_header = ""; }
430 # encrypt xml msg
431 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
433 # opensocket
434 my $socket = &open_socket($address);
435 if( !$socket ) {
436 daemon_log("WARNING: cannot send ".$msg_header."msg to $address , host not reachable", 3);
437 if ($REGISTERED == 1) {
438 $REGISTERED = 0; # if server is not available, cause reregistering
439 daemon_log("INFO: cause reregistering at gosa-si-server", 5);
440 $global_kernel->yield('register_at_gosa_si_server');
442 }
443 $error++;
444 }
446 # send xml msg
447 if( $error == 0 ) {
448 print $socket $crypted_msg."\n";
449 daemon_log("INFO: send ".$msg_header."msg to $address", 5);
450 daemon_log("DEBUG: message:\n$msg", 9);
451 }
453 # close socket in any case
454 if( $socket ) {
455 close $socket;
456 }
458 return $error;
459 }
462 sub write_to_file {
463 my ($string, $file) = @_;
464 my $error = 0;
466 if( not defined $file || not -f $file ) {
467 &main::daemon_log("ERROR: $prg: check '-f file' failed: $file", 1);
468 $error++;
469 }
470 if( not defined $string || 0 == length($string)) {
471 &main::daemon_log("ERROR: $prg: empty string to write to file '$file'", 1);
472 $error++;
473 }
475 if( $error == 0 ) {
477 chomp($string);
479 if (open(FILE, ">> $file")){
480 print FILE $string."\n";
481 close(FILE);
482 }
483 }
485 return;
486 }
489 sub open_socket {
490 my ($PeerAddr, $PeerPort) = @_ ;
491 if(defined($PeerPort)){
492 $PeerAddr = $PeerAddr.":".$PeerPort;
493 }
494 my $socket;
495 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
496 Porto => "tcp",
497 Type => SOCK_STREAM,
498 Timeout => 5,
499 );
500 if(not defined $socket) {
501 return;
502 }
503 &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
504 return $socket;
505 }
508 #=== FUNCTION ================================================================
509 # NAME: register_at_server
510 # PARAMETERS:
511 # RETURNS:
512 # DESCRIPTION:
513 #===============================================================================
514 sub register_at_gosa_si_server {
515 my ($kernel) = $_[KERNEL];
516 my $try_to_register = 0;
518 # if client is already registered, stop registration process
519 if ($REGISTERED) {
520 $kernel->delay('register_at_gosa_si_server');
522 # client is not registered, start registration process
523 } else {
524 # clear all other triggered events and wait till registration was successful
525 $kernel->delay('trigger_new_key');
527 # create new passwd and ciphering object for client-server communication
528 $server_key = &create_passwd();
530 my $events = join( ",", keys %{$event_hash} );
531 while(1) {
532 $try_to_register++;
534 # after one complete round through all server, stop trying to register
535 if( $try_to_register > @servers ) { last; }
537 # fetch first gosa-si-server from @servers
538 # append shifted gosa-si-server at the end of @servers, so looking for servers never stop if
539 # a registration never occured
540 my $server = shift(@servers);
541 push( @servers, $server );
543 # Check if our ip is resolvable - if not: don't try to register
544 if(!(defined($server) && $server =~ m/^[0-9\.]*?:.*$/)) {
545 &main::daemon_log("ERROR: Server with address '".defined($server)?$server:""."' is invalid!", 1);
546 if (length(@servers) == 1) {
547 &main::daemon_log("ERROR: No valid servers found!", 1);
548 exit(1);
549 }
550 }
552 # Check if our ip is resolvable - if not: don't try to register
553 my $ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
554 my $dnsname= gethostbyaddr(inet_aton($ip), AF_INET);
555 if(!defined($dnsname)) {
556 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
557 $dnsname = `hostname`;
558 } else {
559 &write_to_file("goto-error-dns:$ip", $fai_logpath);
560 exit(1);
561 }
562 }
564 # create registration msg
565 my $local_ip = &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
566 my $local_mac = &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
567 my $register_hash = &create_xml_hash("here_i_am", $local_ip.":".$client_port, $server);
568 &add_content2xml_hash($register_hash, "new_passwd", $server_key);
569 &add_content2xml_hash($register_hash, "mac_address", $local_mac);
570 &add_content2xml_hash($register_hash, "events", $events);
571 &add_content2xml_hash($register_hash, "client_status", $client_status);
572 &add_content2xml_hash($register_hash, "client_revision", $client_revision);
573 &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
574 &add_content2xml_hash($register_hash, "key_lifetime", $server_key_lifetime);
576 # Add $HOSTNAME from ENV if force-hostname is set
577 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
578 if(defined($ENV{HOSTNAME}) && length($ENV{HOSTNAME}) >0 ) {
579 &add_content2xml_hash($register_hash, "force-hostname", $ENV{HOSTNAME});
580 } else {
581 &main::daemon_log("force-hostname was set to true, but no \$HOSTNAME was found in Environment!",0);
582 }
583 }
585 # send xml hash to server with general server passwd
586 my $res = &send_msg_hash_to_target($register_hash, $server, $default_server_key);
588 # if delivery of registration msg succeed
589 if($res eq "0") {
590 # reset try_to_register
591 $try_to_register = 0;
593 # Set fixed client address and mac address
594 $client_ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
595 $client_address= "$client_ip:$client_port";
596 $client_mac_address = $local_mac;
597 $client_dnsname = $dnsname;
598 last;
600 # delivery of registration msg failed
601 } else {
602 # wait 1 sec until trying to register again
603 sleep(1);
604 next;
605 }
607 } # end of while
608 # one circle through all servers finished and no registration succeed
609 if ( $try_to_register >= @servers ) {
610 &write_to_file("gosa-si-no-server-available", $fai_logpath);
611 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
613 # delivery of registraion msg succeed, waiting for server response
614 } else {
615 daemon_log("INFO: waiting for msg 'register_at_gosa_si_server'",5);
616 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
617 # clear old settings and set it again
618 $kernel->delay('trigger_new_key');
619 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
620 }
622 }
623 return;
624 }
627 sub check_key_and_xml_validity {
628 my ($crypted_msg, $module_key) = @_;
630 my $msg;
631 my $msg_hash;
632 eval{
633 $msg = &decrypt_msg($crypted_msg, $module_key);
634 &main::daemon_log("decrypted_msg: \n$msg", 9);
636 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
638 ##############
639 # check header
640 my $header_l = $msg_hash->{'header'};
641 if( 1 != @{$header_l} ) {
642 die 'no or more headers specified';
643 }
644 my $header = @{$header_l}[0];
645 if( 0 == length $header) {
646 die 'header has length 0';
647 }
649 ##############
650 # check source
651 my $source_l = $msg_hash->{'source'};
652 if( 1 != @{$source_l} ) {
653 die 'no or more than 1 sources specified';
654 }
655 my $source = @{$source_l}[0];
656 if( 0 == length $source) {
657 die 'source has length 0';
658 }
659 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
660 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
661 }
663 ##############
664 # check target
665 my $target_l = $msg_hash->{'target'};
666 if( 1 != @{$target_l} ) {
667 die 'no or more than 1 targets specified ';
668 }
669 my $target = @{$target_l}[0];
670 if( 0 == length $target) {
671 die 'target has length 0 ';
672 }
673 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ){
674 die "source is neither a complete ip-address with port nor 'GOSA'";
675 }
676 };
677 if($@) {
678 &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
679 &main::daemon_log("$@", 8);
680 $msg = undef;
681 $msg_hash = undef;
682 }
684 return ($msg, $msg_hash);
685 }
688 sub check_outgoing_xml_validity {
689 my ($msg) = @_;
691 my $msg_hash;
692 eval{
693 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
695 ##############
696 # check header
697 my $header_l = $msg_hash->{'header'};
698 if( 1 != @{$header_l} ) {
699 die 'no or more than one headers specified';
700 }
701 my $header = @{$header_l}[0];
702 if( 0 == length $header) {
703 die 'header has length 0';
704 }
706 ##############
707 # check source
708 my $source_l = $msg_hash->{'source'};
709 if( 1 != @{$source_l} ) {
710 die 'no or more than 1 sources specified';
711 }
712 my $source = @{$source_l}[0];
713 if( 0 == length $source) {
714 die 'source has length 0';
715 }
716 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
717 $source =~ /^GOSA$/i ) {
718 die "source '$source' is neither a complete ip-address with port";
719 }
721 ##############
722 # check target
723 my $target_l = $msg_hash->{'target'};
724 if( 1 != @{$target_l} ) {
725 die "no or more than one targets specified";
726 }
727 foreach my $target (@$target_l) {
728 if( 0 == length $target) {
729 die "target has length 0";
730 }
731 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
732 die "target '$target' is not a complete ip-address with port or a valid target name";
733 }
734 }
735 };
736 if($@) {
737 daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
738 daemon_log("$@ $msg", 8);
739 $msg_hash = undef;
740 }
741 return ($msg_hash);
742 }
745 sub trigger_new_key {
746 my ($kernel) = $_[KERNEL] ;
748 my $msg = "<xml><header>new_key</header><source>$client_address</source><target>$client_address</target></xml>";
749 &send_msg_to_target($msg, $client_address, $server_key, 'new_key');
751 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
752 }
755 sub trigger_logged_in_users_report {
756 my ($kernel) = $_[KERNEL] ;
758 # just do if client is registered already
759 if( $REGISTERED ) {
760 my $result = qx(/usr/bin/users);
761 my @logged_in_user_list;
762 if( defined $result ) {
763 chomp($result);
764 @logged_in_user_list = split(/\s/, $result);
765 }
767 system("echo 'CURRENTLY_LOGGED_IN ".join(" ", @logged_in_user_list)."' > /var/run/gosa-si-client.socket");
768 $kernel->delay_set('trigger_logged_in_users_report', $trigger_logged_in_users_report_delay);
769 } else {
770 # try it in 10 sec again
771 $kernel->delay_set('trigger_logged_in_users_report', 10);
772 }
773 }
776 sub generic_file_error {
777 my ( $heap, $operation, $errno, $error_string, $wheel_id ) =
778 @_[ HEAP, ARG0, ARG1, ARG2, ARG3 ];
780 my $service = $heap->{services}->{$wheel_id};
781 daemon_log("ERROR: '$service' watcher $operation error $errno: $error_string", 1);
782 daemon_log("ERROR: shutting down '$service' file watcher", 1);
784 delete $heap->{services}->{$wheel_id};
785 delete $heap->{watchers}->{$wheel_id};
786 return;
787 }
790 sub fifo_got_record {
791 my $file_record = $_[ARG0];
792 my $header;
793 my $content = "";
794 daemon_log("DEBUG: fifo got record: $file_record", 7);
796 $file_record =~ /^(\S+)[ ]?([\s\S]+)?$/;
797 if( defined $1 ) {
798 $header = $1;
799 } else {
800 return;
801 }
803 if( defined $2 ) {
804 $content = $2;
805 }
807 my $clmsg_hash = &create_xml_hash("CLMSG_$header", $client_address, $server_address, $content);
808 &add_content2xml_hash($clmsg_hash, "macaddress", $client_mac_address);
809 my $clmsg = &create_xml_string($clmsg_hash);
810 &send_msg_to_target($clmsg, $server_address, $server_key, "CLMSG_$header");
812 # if installation finished, save all log files
813 if ($file_record eq "TASKBEGIN finish") {
814 &save_fai_log($fai_log_dir);
815 }
817 return;
818 }
821 sub save_fai_log {
822 my ($fai_log_dir) = @_ ;
823 my $FAI_DIR;
825 opendir($FAI_DIR, $fai_log_dir);
826 if (not defined $FAI_DIR) {
827 daemon_log("ERROR: can not open directory $fai_log_dir: $!", 1);
828 return;
829 }
831 my @log_files = readdir($FAI_DIR);
832 closedir($FAI_DIR);
833 my @log_list;
835 foreach my $log_file (@log_files) {
836 if( $log_file eq "." || $log_file eq ".." ) { next; }
837 my $log = "log_file:$log_file:";
838 $log_file = File::Spec->catfile( $fai_log_dir, $log_file );
839 open(my $FILE, "<$log_file");
840 if (not defined $FILE ) {
841 daemon_log("ERROR: can not open '$log_file': $!", 1);
842 next;
843 }
844 my @lines = <$FILE>;
845 my $log_string = join("", @lines);
846 $log .= &encode_base64($log_string);
847 push(@log_list, $log);
848 close ($FILE);
849 }
851 my $all_log_string = join("\n", @log_list);
852 my $msg_hash = &create_xml_hash("CLMSG_save_fai_log", $client_address, $server_address, $all_log_string);
853 &add_content2xml_hash($msg_hash, "macaddress", $client_mac_address);
854 my $msg = &create_xml_string($msg_hash);
855 &send_msg_to_target($msg, $server_address, $server_key, "CLMSG_save_fai_log");
857 }
860 sub sig_handler {
861 my ($kernel, $signal) = @_[KERNEL, ARG0] ;
862 daemon_log("0 INFO got signal '$signal'", 1);
863 $kernel->sig_handled();
864 return;
865 }
868 sub _start {
869 my ($kernel, $heap) = @_[KERNEL, HEAP];
870 $kernel->alias_set('client_session');
871 $global_kernel = $kernel; # this is used to throw events at each point of the skript
873 $kernel->sig(USR1 => "sig_handler");
875 # force a registration at a gosa-si-server
876 $kernel->yield('register_at_gosa_si_server');
878 # install all file watcher defined
879 while( my($name, $file) = each %files_to_watch ) {
880 my $watcher = POE::Wheel::FollowTail->new(
881 Filename => $file,
882 InputEvent => $name."_record",
883 # ResetEvent => "file_reset",
884 ErrorEvent => "file_error",
885 );
886 # $heap->{tail} = POE::Wheel::Run->new(
887 # Program => [ "/usr/bin/tail", "-f", $file ],
888 # StdoutEvent => $file_name."_record",
889 # );
890 $heap->{services}->{ $watcher->ID } = $name;
891 $heap->{watchers}->{ $watcher->ID } = $watcher;
892 }
893 $kernel->yield('trigger_logged_in_users_report');
894 }
897 sub _default {
898 daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
899 return;
900 }
903 sub server_input {
904 my ($kernel, $heap, $input, $wheel) = @_[KERNEL, HEAP, ARG0, ARG1];
905 my $remote_ip = $heap->{'remote_ip'},
906 my $error = 0;
907 my $answer;
910 daemon_log("INFO: Incoming msg from '$remote_ip'", 5);
911 daemon_log("DEBUG: Incoming msg:\n$input\n", 9);
913 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
914 if( (!$msg) || (!$msg_hash) ) {
915 daemon_log("WARNING: Deciphering of incoming msg failed", 3);
916 if($server_address =~ /$remote_ip/) {
917 # got a msg from gosa-si-server which can not be decrypted, may the secrete not up-to-date
918 # cause a reregistering with a new secrete handshake
919 daemon_log("WARNING: Message from gosa-si-server could not be understood, cause reregistering at server", 3);
921 # if client is alread in a registration process, that means not registered, do nothing
922 # if not, cause re-registration
923 if (not $REGISTERED) {
924 &daemon_log("WARNING: gosa-si-client is already in a registration process so ignore this message", 3);
925 } else {
926 $REGISTERED = 0;
927 $kernel->post('client_session', 'register_at_gosa_si_server');
928 }
929 }
930 $error++;
931 }
934 ######################
935 # process incoming msg
936 if( $error == 0 ) {
937 my $header = @{$msg_hash->{header}}[0];
938 my $source = @{$msg_hash->{source}}[0];
940 if( exists $event_hash->{$header} ) {
942 # a event exists with the header as name
943 daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
944 no strict 'refs';
945 $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
946 }
947 else {
948 daemon_log("WARNING: no event '$header' found in event modules under $event_dir", 3);
949 }
950 }
952 ########
953 # answer
954 if( $answer ) {
956 #check gosa-si envelope validity
957 my $answer_hash = &check_outgoing_xml_validity($answer);
959 if( $answer_hash ) {
960 # answer is valid
962 # preprocessing
963 if( $answer =~ "<header>registered</header>") {
964 # set registered flag to true to stop sending further registered msgs
965 $REGISTERED = 1;
966 }
967 else {
968 $answer =~ /<header>(\S+)<\/header>/;
969 &send_msg_to_target($answer, $server_address, $server_key, $1);
970 }
972 # postprocessing
973 if( $answer =~ "<header>new_key</header>") {
974 # set new key to global variable
975 $answer =~ /<new_key>(\S*?)<\/new_key>/;
976 my $new_key = $1;
977 $server_key = $new_key;
978 }
979 }
981 }
983 return;
984 }
987 #==== MAIN = main ==============================================================
988 # parse commandline options
989 Getopt::Long::Configure( "bundling" );
990 GetOptions("h|help" => \&usage,
991 "c|config=s" => \$cfg_file,
992 "f|foreground" => \$foreground,
993 "v|verbose+" => \$verbose,
994 );
996 # read and set config parameters
997 &check_cmdline_param ;
998 &read_configfile($cfg_file, %cfg_defaults);
999 &check_pid;
1002 # forward error messages to logfile
1003 if ( ! $foreground ) {
1004 open( STDIN, '+>/dev/null' );
1005 open( STDOUT, '+>&STDIN' );
1006 open( STDERR, '+>&STDIN' );
1007 }
1009 # Just fork, if we are not in foreground mode
1010 if( ! $foreground ) {
1011 chdir '/' or die "Can't chdir to /: $!";
1012 $pid = fork;
1013 setsid or die "Can't start a new session: $!";
1014 umask 0;
1015 } else {
1016 $pid = $$;
1017 }
1019 # Do something useful - put our PID into the pid_file
1020 if( 0 != $pid ) {
1021 open( LOCK_FILE, ">$pid_file" );
1022 print LOCK_FILE "$pid\n";
1023 close( LOCK_FILE );
1024 if( !$foreground ) {
1025 exit( 0 )
1026 };
1027 }
1029 # parse head url and revision from svn
1030 my $client_status_hash = { 'developmental'=>'revision', 'stable'=>'release'};
1031 $client_version =~ /^\$HeadURL: (\S+) \$:\$Rev: (\d+) \$$/;
1032 $client_headURL = defined $1 ? $1 : 'unknown' ;
1033 $client_revision = defined $2 ? $2 : 'unknown' ;
1034 if ($client_headURL =~ /\/tag\// ||
1035 $client_headURL =~ /\/branches\// ) {
1036 $client_status = "stable";
1037 } else {
1038 $client_status = "developmental" ;
1039 }
1041 daemon_log(" ", 1);
1042 daemon_log("$prg started!", 1);
1043 daemon_log("INFO: status: $client_status", 1);
1044 daemon_log("INFO: ".$client_status_hash->{$client_status}.": $client_revision", 1);
1046 # delete old DBsqlite lock files
1047 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1049 # detect ip and mac address and complete host address
1050 $client_address = $client_ip.":".$client_port;
1051 my $network_interface= &get_interface_for_ip($client_ip);
1052 $client_mac_address= &get_mac($network_interface);
1053 daemon_log("INFO: ip address detected: $client_ip", 1);
1054 daemon_log("INFO: gosa-si-client mac address detected: $client_mac_address", 1);
1057 # import events
1058 my ($error, $result, $tmp_hash) = &import_events($event_dir);
1059 while (my ($module, $mod_event_hash) = each %$tmp_hash) {
1060 while (my ($event_name, $nothing) = each %$mod_event_hash) {
1061 $event_hash->{$event_name} = $module;
1062 }
1063 }
1065 foreach my $log_line (@$result) {
1066 if ($log_line =~ / succeed: /) {
1067 &main::daemon_log("0 DEBUG: $log_line", 7);
1068 } else {
1069 &main::daemon_log("0 ERROR: $log_line", 1);
1070 }
1071 }
1074 # compute hardware checksum
1075 $gotoHardwareChecksum= &generate_hw_digest();
1076 daemon_log("INFO: gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1079 # create socket for incoming xml messages
1080 POE::Component::Server::TCP->new(
1081 Alias => 'gosa-si-client',
1082 Port => $client_port,
1083 ClientInput => \&server_input,
1084 );
1085 daemon_log("INFO: start socket for incoming xml messages at port '$client_port' ", 1);
1088 # prepare variables
1089 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); }
1090 if (defined $server_ip && defined $server_port) {
1091 $server_address = $server_ip.":".$server_port;
1092 }
1093 $xml = new XML::Simple();
1094 $default_server_key = $server_key;
1097 # add gosa-si-server address from config file at first position of server list
1098 my $server_check_cfg = Config::IniFiles->new( -file => $cfg_file );
1099 my $server_check = (defined($server_check_cfg))?$server_check_cfg->val( "server", "ip"):undef;
1100 if( defined $server_check ) {
1101 unshift(@servers, $server_address);
1102 my $servers_string = join(", ", @servers);
1103 daemon_log("INFO: found servers in configuration file: $servers_string", 1);
1104 } else {
1105 my @tmp_servers;
1106 if ( !$server_domain) {
1107 # Try our DNS Searchlist
1108 my @domain_list = &get_dns_domains();
1109 my $tmp_domains;
1110 my $error_string;
1111 for my $domain (@domain_list) {
1112 chomp($domain);
1113 ($tmp_domains, $error_string) = &get_server_addresses($domain);
1114 if(@$tmp_domains) {
1115 for my $tmp_server(@$tmp_domains) {
1116 push @tmp_servers, $tmp_server;
1117 }
1118 }
1119 }
1120 if (0 == @tmp_servers) {
1121 my $log_string = "no gosa-si-server found!";
1122 $log_string .= "\n\tdetermined domains out of /etc/resolv.conf: ".join(", ", @domain_list);
1123 $log_string .= "\n\tdetermined server addresses in domains: ".join(", ",@$tmp_domains);
1124 daemon_log("ERROR: $log_string", 1);
1125 daemon_log("ERROR: $error_string", 1);
1126 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1127 kill 2, $$;
1128 }
1129 } else {
1130 @tmp_servers = &get_server_addresses($server_domain);
1131 if( 0 == @tmp_servers ) {
1132 daemon_log("ERROR: no gosa-si-server found in DNS for domain '$server_domain'",1);
1133 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1134 kill 2, $$;
1135 }
1136 }
1138 foreach my $server (@tmp_servers) {
1139 unshift(@servers, $server);
1140 }
1141 my $servers_string = join(", ", @servers);
1142 daemon_log("INFO: found servers in DNS: $servers_string", 1);
1143 }
1146 # open fifo for non-gosa-si-client-msgs to gosa-si-server
1147 POSIX::mkfifo("$gosa_si_client_fifo", "0600");
1150 POE::Session->create(
1151 inline_states => {
1152 _start => \&_start,
1153 _default => \&_default,
1154 sig_handler => \&sig_handler,
1155 register_at_gosa_si_server => \®ister_at_gosa_si_server,
1157 # trigger periodical tasks
1158 trigger_new_key => \&trigger_new_key,
1159 trigger_logged_in_users_report => \&trigger_logged_in_users_report,
1161 # handle records from each defined file differently
1162 fifo_record => \&fifo_got_record,
1164 # handle file resets and errors the same way for each file
1165 file_reset => \&generic_file_reset,
1166 file_error => \&generic_file_error,
1167 }
1168 );
1170 POE::Kernel->run();
1171 exit;